示例#1
0
void surfaceVectorField::WriteShapePoint(double xpt, double ypt, double spd, long dir, long view_dir, long map_dir)
{
     long NumRecord;
	double zpt=0;
     SHPObject *pSHP;

     pSHP=SHPCreateObject(SHPT_POINT, -1, 0, NULL, NULL, 1, &xpt, &ypt, &zpt, NULL);
     SHPWriteObject(hSHP, -1, pSHP);
     SHPDestroyObject(pSHP);

	NumRecord = DBFGetRecordCount(hDBF);
//	DBFWriteDoubleAttribute(hDBF, NumRecord, 0, xpt);
//   DBFWriteDoubleAttribute(hDBF, NumRecord, 1, ypt);
//	DBFWriteIntegerAttribute(hDBF, NumRecord, 2, spd);
//   DBFWriteIntegerAttribute(hDBF, NumRecord, 3, dir);
	DBFWriteDoubleAttribute(hDBF, NumRecord, 0, spd);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 1, dir);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 2, view_dir);
     DBFWriteIntegerAttribute(hDBF, NumRecord, 3, map_dir);
}
示例#2
0
bool ShpFilter::IntegerField::save(DBFHandle handle, int fieldIndex) const
{
	if (!handle || fieldIndex < 0)
	{
		assert(false);
		return false;
	}
	
	for (size_t i=0; i<values.size(); ++i)
		DBFWriteIntegerAttribute(handle,static_cast<int>(i),fieldIndex,values[i]);

	return true;
}
int writePoint(JNIEnv * env, SHPHandle hSHP, DBFHandle hDBF, int index, double latitude, double longitude, jstring name, jdouble height, int apples)
{
    SHPObject *oSHP = SHPCreateSimpleObject(SHPT_POINT, 1, &longitude, &latitude, NULL);
    SHPWriteObject(hSHP, -1, oSHP);
    const char *nativeName = (*env)->GetStringUTFChars(env, name, 0);
    DBFWriteStringAttribute(hDBF, index, 0, nativeName);
    (*env)->ReleaseStringUTFChars(env, name, nativeName);
    DBFWriteDoubleAttribute(hDBF, index, 1, height);
    DBFWriteIntegerAttribute(hDBF, index, 2, apples);

    SHPDestroyObject(oSHP);

    return 0;
}
示例#4
0
            /**
            * Add a geometry to the shapefile.
            */
            bool add(Osmium::Geometry::Geometry* geometry, ///< the geometry
                     v8::Local<v8::Object> attributes) {   ///< a %Javascript object (hash) with the attributes

                try {
                    add_geometry(geometry->create_shp_object());
                } catch (Osmium::Exception::IllegalGeometry) {
                    return false;
                }

                int ok = 0;
                for (size_t n=0; n < m_fields.size(); n++) {
                    v8::Local<v8::String> key = v8::String::New(m_fields[n].name().c_str());
                    if (attributes->HasRealNamedProperty(key)) {
                        v8::Local<v8::Value> value = attributes->GetRealNamedProperty(key);
                        if (value->IsUndefined() || value->IsNull()) {
                            DBFWriteNULLAttribute(m_dbf_handle, m_current_shape, n);
                        } else {
                            switch (m_fields[n].type()) {
                                case FTString:
                                    ok = add_string_attribute(n, value);
                                    break;
                                case FTInteger:
                                    ok = DBFWriteIntegerAttribute(m_dbf_handle, m_current_shape, n, value->Int32Value());
                                    break;
                                case FTDouble:
                                    throw std::runtime_error("fields of type double not implemented");
                                    break;
                                case FTLogical:
                                    ok = add_logical_attribute(n, value);
                                    break;
                                default:
                                    ok = 0; // should never be here
                                    break;
                            }
                            if (!ok) {
                                std::string errmsg("failed to add attribute '");
                                errmsg += m_fields[n].name();
                                errmsg += "'\n";
                                throw std::runtime_error(errmsg);
                            }
                        }
                    } else {
                        DBFWriteNULLAttribute(m_dbf_handle, m_current_shape, n);
                    }
                }
                return true;
            }
// ---------------------------------------------------------------------------
// 
// -----------
int	bDBFTable::WriteVal(int o, int f, void* val){
_bTrace_("bDBFTable::WriteVal",false);
	if(o==CountRecords()+1){
		o=CountRecords();
	}
	else{
		o--;
	}
int	sgn;
	(void)FieldSign(f,&sgn);
	f--;
	switch(sgn){
		case _int:
			if(!DBFWriteIntegerAttribute(_dbf,o,f,(*(int*)val))){
//_te_("DBFWriteIntegerAttribute "+f);
				return(-2);
			}
			break;
		case _double:
			if(!DBFWriteDoubleAttribute(_dbf,o,f,(*(double*)val))){
//_te_("DBFWriteDoubleAttribute "+f);
				return(-2);
			}
			break;
		case _char:
			if(!DBFWriteStringAttribute(_dbf,o,f,(char*)val)){
//_te_("DBFWriteStringAttribute "+f);
				return(-2);
			}
			break;
		default:
_te_("bad kind");
			return(-1);
	}
	return(0);
}
示例#6
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);
  }
}
示例#7
0
int save_table(int t)
{
    int i, j, ncols, nrows, ret, field, rec;
    char name[2000], fname[20], element[100];
    DBFHandle dbf;
    ROW *rows;
    VALUE *val;
    int dbftype, width, decimals;

    G_debug(2, "save_table %d", t);

    /* Note: because if driver is killed during the time the table is written, the process
     *        is not completed and DATA ARE LOST. To minimize this, data are first written
     *        to temporary file and then this file is renamed to 'database/table.dbf'.
     *        Hopefully both file are on the same disk/partition */

    if (!(db.tables[t].alive) || !(db.tables[t].updated))
        return DB_OK;

    /* Construct our temp name because shapelib doesn't like '.' in name */
    G__temp_element(element);
    sprintf(fname, "%d.dbf", getpid());
    G_file_name(name, element, fname, G_mapset());
    G_debug(2, "Write table to tempfile: '%s'", name);

    dbf = DBFCreate(name);
    if (dbf == NULL)
        return DB_FAILED;

    ncols = db.tables[t].ncols;
    rows = db.tables[t].rows;
    nrows = db.tables[t].nrows;

    for (i = 0; i < ncols; i++) {
        switch (db.tables[t].cols[i].type) {
        case DBF_INT:
            dbftype = FTInteger;
            break;
        case DBF_CHAR:
            dbftype = FTString;
            break;
        case DBF_DOUBLE:
            dbftype = FTDouble;
            break;
        }

        width = db.tables[t].cols[i].width;
        decimals = db.tables[t].cols[i].decimals;
        DBFAddField(dbf, db.tables[t].cols[i].name, dbftype, width, decimals);

    }

    G_debug(2, "Write %d rows", nrows);
    rec = 0;
    for (i = 0; i < nrows; i++) {
        if (rows[i].alive == FALSE)
            continue;

        for (j = 0; j < ncols; j++) {
            field = j;

            val = &(rows[i].values[j]);
            if (val->is_null) {
                DBFWriteNULLAttribute(dbf, rec, field);
            }
            else {
                switch (db.tables[t].cols[j].type) {
                case DBF_INT:
                    ret = DBFWriteIntegerAttribute(dbf, rec, field, val->i);
                    break;
                case DBF_CHAR:
                    if (val->c != NULL)
                        ret =
                            DBFWriteStringAttribute(dbf, rec, field, val->c);
                    else
                        ret = DBFWriteStringAttribute(dbf, rec, field, "");
                    break;
                case DBF_DOUBLE:
                    ret = DBFWriteDoubleAttribute(dbf, rec, field, val->d);
                    break;
                }
            }
        }
        rec++;
    }
    G_debug(2, "Written %d records", rec);

    DBFClose(dbf);

    /* Copy */
    if (G_rename_file(name, db.tables[t].file)) {
        append_error("Cannot move %s\nto %s\n", name, db.tables[t].file);
        return DB_FAILED;
    };

    return DB_OK;
}
示例#8
0
bool Countries::WriteSingleSHP(const char *fname)
{
	SHPHandle hSHP = SHPCreate(fname, SHPT_POINT);
	if (!hSHP)
		return false;

	SHPObject *obj;

	int i, j, num_places;
	int longest_place_name = 0;
	int num_countries = m_countries.GetSize();

	for (i = 0; i < num_countries; i++)
	{
		Country *country = m_countries[i];
		num_places = country->m_places.GetSize();

		for (j = 0; j < num_places; j++)
		{
			Place *place = country->m_places[j];

			obj = SHPCreateSimpleObject(SHPT_POINT, 1,
				&place->m_pos.x, &place->m_pos.y, NULL);

			SHPWriteObject(hSHP, -1, obj);
			SHPDestroyObject(obj);

			const char *utf8 = place->m_fullname.to_utf8();
			int len = strlen(utf8);
			if (len > longest_place_name)
				longest_place_name = len;
		}
	}
	SHPClose(hSHP);

	// Save DBF File also
	vtString dbfname = fname;
	dbfname = dbfname.Left(dbfname.GetLength() - 4);
	dbfname += ".dbf";
	DBFHandle db = DBFCreate(dbfname);
	if (db == NULL)
		return false;

	DBFAddField(db, "Country", FTString, 2, 0);
	DBFAddField(db, "PPC", FTInteger, 2, 0);
	DBFAddField(db, "Name", FTString, longest_place_name, 0);

	int entity = 0;
	for (i = 0; i < num_countries; i++)
	{
		Country *country = m_countries[i];
		num_places = country->m_places.GetSize();
		for (j = 0; j < num_places; j++)
		{
			Place *place = country->m_places[j];

			DBFWriteStringAttribute(db, entity, 0, (const char *) country->m_abb);

			DBFWriteIntegerAttribute(db, entity, 1, place->m_ppc);

			const char *utf8 = place->m_fullname.to_utf8();
			DBFWriteStringAttribute(db, entity, 2, utf8);

			entity++;
		}
	}
	DBFClose(db);

	return true;
}
static
void write_shapefile (local_data_t *local_data)
{
  guint npolys;

  char *shape_filename;
  SHPHandle shape_file = NULL;
  SHPObject *shape;
  double *vertex_x, *vertex_y;
  guint i, j;
  projUV p;

  char *dbf_filename;
  DBFHandle dbf_file = NULL;
  int nunits_field_index;
  int avg_ninfected_field_index;
  int avg_ndestroyed_field_index;
  int avg_nvaccinated_field_index;
  int avg_frinfected_field_index;
  int avg_frdestroyed_field_index;
  int avg_frvaccinated_field_index;

  #if DEBUG
    g_debug ("----- ENTER write_shapefile (%s)", MODEL_NAME);
  #endif

  vertex_x = g_new (double, local_data->max_nvertices);
  vertex_y = g_new (double, local_data->max_nvertices);

  /* We are going to write 2 files: the .shp file, containing the geometry of
   * the polygons, and the .dbf file, containing the numeric attributes
   * attached to the polygons. */

  shape_filename = g_strdup_printf ("%s.shp", local_data->base_filename);
  #if DEBUG
    g_debug ("creating new shapefile \"%s\"", shape_filename);
  #endif
  shape_file = SHPCreate (shape_filename, SHPT_POLYGON);
  g_assert (shape_file != NULL);

  npolys = local_data->polys->len;
  for (i = 0; i < npolys; i++)
    {
      gpc_polygon *poly;
      gpc_vertex_list *contour;

      poly = (gpc_polygon *) g_ptr_array_index (local_data->polys, i);
      g_assert (poly->num_contours == 1);
      contour = &(poly->contour[0]);
      for (j = 0; j < contour->num_vertices; j++)
        {
          /* The polygon vertices are in x-y coordinates.  We need to
           * "unproject" them back to lat-long. */
          p.u = contour->vertex[j].x;
          p.v = contour->vertex[j].y;
          p = pj_inv (p, local_data->projection);
          vertex_x[j] = p.u * RAD_TO_DEG;
          vertex_y[j] = p.v * RAD_TO_DEG;
        }
      shape = SHPCreateSimpleObject (SHPT_POLYGON, j, vertex_x, vertex_y, NULL);
      SHPWriteObject (shape_file, -1, shape);
      SHPDestroyObject (shape);
    }
  if (shape_file != NULL)
    SHPClose (shape_file);
  g_free (shape_filename);

  /* Now the attribute file */

  dbf_filename = g_strdup_printf ("%s.dbf", local_data->base_filename);
  #if DEBUG
    g_debug ("creating new attributes file \"%s\"", dbf_filename);
  #endif
  dbf_file = DBFCreate (dbf_filename);
  g_assert (dbf_file != NULL);

  /* Add attribute definitions. */
  #if DEBUG
    g_debug ("adding field definitions to DBF file \"%s\": nunits, avgninf, avgndest, avgnvacc, avgfrinf, avgfrdest, avgfrvacc",
             dbf_filename);
  #endif
  /* 9-digit integers should be enough to count # of units in a polygon. */
  nunits_field_index = DBFAddField (dbf_file, "nunits", FTInteger, 9, 0);
  /* 1 decimal place for average # of units infected or destroyed, 3 for
   * average fraction of units. */
  avg_ninfected_field_index = DBFAddField (dbf_file, "avgninf", FTDouble, 9, 1);
  avg_ndestroyed_field_index = DBFAddField (dbf_file, "avgndest", FTDouble, 9, 1);
  avg_nvaccinated_field_index = DBFAddField (dbf_file, "avgnvacc", FTDouble, 9, 1);
  avg_frinfected_field_index = DBFAddField (dbf_file, "avgfrinf", FTDouble, 9, 3);
  avg_frdestroyed_field_index = DBFAddField (dbf_file, "avgfrdest", FTDouble, 9, 3);
  avg_frvaccinated_field_index = DBFAddField (dbf_file, "avgfrvacc", FTDouble, 9, 3);

  /* Write the attributes to the file. */
  #if DEBUG
    g_debug ("writing attributes to \"%s\"", dbf_filename);
  #endif
  for (i = 0; i < npolys; i++)
    {
      guint nunits;

      /* Divide the counts by the number of runs to get the mean */
      local_data->ninfected[i] /= local_data->nruns;
      local_data->ndestroyed[i] /= local_data->nruns;
      local_data->nvaccinated[i] /= local_data->nruns;

      nunits = local_data->unit_count[i];
      DBFWriteIntegerAttribute (dbf_file, i, nunits_field_index, nunits);
      DBFWriteDoubleAttribute (dbf_file, i, avg_ninfected_field_index, local_data->ninfected[i]);
      DBFWriteDoubleAttribute (dbf_file, i, avg_ndestroyed_field_index, local_data->ndestroyed[i]);
      DBFWriteDoubleAttribute (dbf_file, i, avg_nvaccinated_field_index, local_data->nvaccinated[i]);
      DBFWriteDoubleAttribute (dbf_file, i, avg_frinfected_field_index, local_data->ninfected[i] / nunits);
      DBFWriteDoubleAttribute (dbf_file, i, avg_frdestroyed_field_index, local_data->ndestroyed[i] / nunits);
      DBFWriteDoubleAttribute (dbf_file, i, avg_frvaccinated_field_index, local_data->nvaccinated[i] / nunits);
    }
  if (dbf_file != NULL)
    DBFClose (dbf_file);
  g_free (dbf_filename);

  /* Clean up. */
  g_free (vertex_y);
  g_free (vertex_x);

  #if DEBUG
    g_debug ("----- EXIT write_shapefile (%s)", MODEL_NAME);
  #endif
  
  return;
}
示例#10
0
static void add_to_shape(DBFHandle dbase, SHPHandle shape, datapool_type_t *datapool,
			 dbf_header_t *dbf, int nCols, int n, 
			 double *lat, double *lon)
{
  int ii, field = 0;

  // Write fields into the database
  for (ii=0; ii<nCols; ii++) {
    if (strcmp(dbf[ii].header, "Granule_Name") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->granule_name);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Platform") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->platform);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Sensor") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->sensor);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Beam_Mode_Description") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->beam_mode_description);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Orbit") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->orbit);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Path_Number") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->path_number);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Frame_Number") == 0 && dbf[ii].visible) {
      DBFWriteIntegerAttribute(dbase, n, field, datapool->frame_number);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Acquisition_Date") == 0 &&
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->acquisition_date);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Processing_Date") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->processing_date);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Processing_Level") == 0 &&
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->processing_level);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Start_Time") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->start_time);
      field++;
    }
    else if (strcmp(dbf[ii].header, "End_Time") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->end_time);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Center_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Center_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->center_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lat") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_Start_Lon") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_start_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_Start_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_start_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Near_End_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->near_end_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lat") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lat);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Far_End_Lon") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->far_end_lon);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Faraday_Rotation") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->faraday_rotation);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Orbit_Direction") == 0 && 
	     dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->orbit_direction);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Url") == 0 && dbf[ii].visible) {
      DBFWriteStringAttribute(dbase, n, field, datapool->url);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Size") == 0 && dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->size);
      field++;
    }
    else if (strcmp(dbf[ii].header, "Off_Nadir_Angle") == 0 &&
	     dbf[ii].visible) {
      DBFWriteDoubleAttribute(dbase, n, field, datapool->off_nadir_angle);
      field++;
    }
  }

  SHPObject *shapeObject=NULL;
  shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, 5, lon, lat, NULL);
  SHPWriteObject(shape, -1, shapeObject);
  SHPDestroyObject(shapeObject);
}
示例#11
0
///////////////////////////////////////////////////////////////////////////////
// Export eines Objektes
HRESULT CArcViewLayer::ExportData (
	GSTRUCT *pGS, MFELD *pMF, LPCSTR pcUIdent, CArcViewLayerAttributes *pMap)
{
OBJECTTYPE rgType = GetType();
int iShapeId = -1;
int iObjTyp = pGS -> Typ;

	_ASSERTE(rgType == ObjType2OBJECTTYPE(pGS -> Typ, true));	// Objekttyp muß stimmen

// Geometrie erzeugen
	if (OBJECTTYPE_Area == rgType) {
	// Anzahl der Konturen feststellen und Konturfeld zusammenbauen
	int iKCnt = 1;
	vector<int> Cnts(1);
	int iCurr = 0;

		Cnts[0] = 0;
		for (int i = 0; 0 != pGS -> cnt[i]; ++i) {
			if (i > 0) 
				Cnts.push_back(iCurr);
			iCurr += pGS -> cnt[i];
		}
		iKCnt = i;

		_ASSERTE(iKCnt > 0 && iKCnt == Cnts.size());

	// Objekt erzeugen
	CArcViewObject Obj(SHPCreateObject(m_nShapeType, -1, iKCnt, Cnts.begin(), NULL,
						pGS -> GSize, pGS -> x, pGS -> y, NULL, NULL));

		iShapeId = SHPWriteObject(m_hSHP, -1, Obj);

	} else {
	// Objekt erzeugen
	CArcViewObject Obj(SHPCreateSimpleObject(m_nShapeType, pGS -> GSize, pGS -> x, pGS -> y, NULL));

		iShapeId = SHPWriteObject(m_hSHP, -1, Obj);
	}
	if (iShapeId == -1)
		return E_FAIL;

// Attribute sicherstellen (bei TRiAS-Datenquellen jedesmal)
	if (!HasFields() || DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id))) {
	// sämtliche Attribute dieses Layers durchgehen und ggf. erzeugen
		for (CArcViewLayerAttributes::iterator it = pMap -> begin(); it != pMap -> end(); ++it) {
		// Feld in Datei erzeugen
		int iField = -1;
		CArcViewAttribute &rAttr = (*it).second;
		LPCSTR pcName = rAttr.GetName();

			if (OBJECTTYPE_Text != m_rgType && !strcmp (pcName, g_cbLabelText))
				continue;		// Labeltext nur für Textobjekte
				
			if (FAILED(FieldExists (pcName, rAttr.GetTyp(), &iField))) 
			{
				RETURN_FAILED_HRESULT(AddField(pcName, rAttr.GetTyp(), rAttr.GetLen(), rAttr.GetDecimals(), &iField));
			}
			_ASSERTE(-1 != iField);

		// mehrerer Objekttypen eines Idents haben identischen Satz von Attributen
			_ASSERTE(-1 == (*it).second.GetField(iObjTyp) || 
					 (*it).second.GetField(iObjTyp) == iField ||
					 DEX_GetTRiASDataSourceEx(DEX_GetObjectsProject(pGS -> Id)));

		// Feldnummer beim Attribut speichern
			(*it).second.SetField(iField, iObjTyp);
		}

	// Textlabel für Textobjekte
		if (OBJECTTYPE_Text == m_rgType) {
		pair<CArcViewLayerAttributes::iterator, bool> p = 
			pMap -> insert (CArcViewLayerAttributes::value_type (-1, CArcViewAttribute(g_cbLabelText, 'a', _MAX_PATH)));

			if (p.second) {
			int iField = -1;

				it = p.first;
				if (FAILED(FieldExists (g_cbLabelText, FTString, &iField))) 
				{
					RETURN_FAILED_HRESULT(AddField(g_cbLabelText, FTString, _MAX_PATH, 0, &iField));
				}
				
				_ASSERTE(-1 != iField);
				(*it).second.SetField(iField, iObjTyp);						
			}
		}
		SetHasFields();
	}
	
// Attributwerte schreiben
	if (NULL != pMF) {
	// nur, wenn mindestens ein Attribut ausgegeben werden soll
		for (MFELD *pMFT = pMF; 0 != pMFT -> MCode; ++pMFT) {
			if (NULL != pMap) {
			CArcViewLayerAttributes::iterator it = pMap -> find (pMFT -> MCode);

				_ASSERTE(it != pMap -> end());	// Attribut sollte (jetzt) existieren
				if (it != pMap -> end()) {
				// Feld muß bereits erzeugt worden sein und Typ muß mit DBF übereinstimmen
				int iField = (*it).second.GetField(iObjTyp);

					_ASSERTE(-1 != iField);
					_ASSERTE((*it).second.GetTyp() == DBFGetFieldInfo (m_hDBF, iField, NULL, NULL, NULL));

				// Wert je nach Typ in die Datenbank schreiben
					switch ((*it).second.GetTyp()) {
					case FTString:
						{
						char cbBuffer[_MAX_PATH] = { '\0' };

							if (NULL != pMFT -> MText)
								OemToCharBuff(pMFT -> MText, cbBuffer, min(MAX_DBASEFIELD_LEN, strlen(pMFT -> MText))+1);	// '\0' mit konvertieren
							DBFWriteStringAttribute(m_hDBF, iShapeId, iField, cbBuffer);
						}
						break;

					case FTInteger:
						DBFWriteIntegerAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atol(pMFT -> MText) : 0);
						break;

					case FTDouble:
						DBFWriteDoubleAttribute(m_hDBF, iShapeId, iField, (NULL != pMFT -> MText) ? atof(pMFT -> MText) : 0.0);
						break;
					}
				}
			} else {
				_ASSERTE(NULL != pMap);		// eigentlich sollte eine Map da sein

			// keine Map, also erstmal leeren Datensatz schreiben
			int iCnt = DBFGetFieldCount(m_hDBF);

				for (int i = 0; i < iCnt; ++i) {
					switch (DBFGetFieldInfo(m_hDBF, i, NULL, NULL, NULL)) {
					case FTString:
						DBFWriteStringAttribute(m_hDBF, iShapeId, i, g_cbNil);
						break;

					case FTInteger:
						DBFWriteIntegerAttribute(m_hDBF, iShapeId, i, 0);
						break;

					case FTDouble:
						DBFWriteDoubleAttribute(m_hDBF, iShapeId, i, 0.0);
						break;
					}
				}
			}
		}
	}
	return S_OK;
}
示例#12
0
static void
WriteAttrRecordToDBF( DBFHandle hDBF, int iRecord, 
                      SDTSTransfer * poTransfer, DDFField * poSR )

{
/* -------------------------------------------------------------------- */
/*      Process each subfield in the record.                            */
/* -------------------------------------------------------------------- */
    DDFFieldDefn        *poFDefn = poSR->GetFieldDefn();
        
    for( int iSF=0; iSF < poFDefn->GetSubfieldCount(); iSF++ )
    {
        DDFSubfieldDefn *poSFDefn = poFDefn->GetSubfield( iSF );
        int                     iField;
        int                     nMaxBytes;
        const char *    pachData = poSR->GetSubfieldData(poSFDefn,
                                                         &nMaxBytes);

/* -------------------------------------------------------------------- */
/*      Identify the related DBF field, if any.                         */
/* -------------------------------------------------------------------- */
        for( iField = 0; iField < hDBF->nFields; iField++ )
        {
            if( EQUALN(poSFDefn->GetName(),
                       hDBF->pszHeader+iField*32,10) )
                break;
        }

        if( iField == hDBF->nFields )
            iField = -1;
            
/* -------------------------------------------------------------------- */
/*      Handle each of the types.                                       */
/* -------------------------------------------------------------------- */
        switch( poSFDefn->GetType() )
        {
          case DDFString:
            const char  *pszValue;

            pszValue = poSFDefn->ExtractStringData(pachData, nMaxBytes,
                                                   NULL);

            if( iField != -1 )
                DBFWriteStringAttribute(hDBF, iRecord, iField, pszValue );
            break;

          case DDFFloat:
            double      dfValue;

            dfValue = poSFDefn->ExtractFloatData(pachData, nMaxBytes,
                                                 NULL);

            if( iField != -1 )
                DBFWriteDoubleAttribute( hDBF, iRecord, iField, dfValue );
            break;

          case DDFInt:
            int         nValue;

            nValue = poSFDefn->ExtractIntData(pachData, nMaxBytes, NULL);

            if( iField != -1 )
                DBFWriteIntegerAttribute( hDBF, iRecord, iField, nValue );
            break;

          default:
            break;
        }
    } /* next subfield */
}
示例#13
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 );
}
示例#14
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 );
}
示例#15
0
static void WriteAttributeDBF( const char * pszShapefile,
                               SDTSTransfer * poTransfer,
                               const char * pszMODN )

{
    SDTSAttrReader      *poAttrReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poAttrReader = (SDTSAttrReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poAttrReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poAttrReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

/* -------------------------------------------------------------------- */
/*      Prepare the schema.                                             */
/* -------------------------------------------------------------------- */
    char        **papszMODNList = CSLAddString( NULL, pszMODN );

    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszMODNList );

    CSLDestroy( papszMODNList );
    
/* ==================================================================== */
/*      Process all the records in the module.                          */
/* ==================================================================== */
    SDTSAttrRecord *poRecord;
    int         iRecord = 0;

    while((poRecord = (SDTSAttrRecord*)poAttrReader->GetNextFeature()) != NULL)
    {
        DBFWriteIntegerAttribute( hDBF, iRecord, 0,
                                  poRecord->oModId.nRecord );

        WriteAttrRecordToDBF( hDBF, iRecord, poTransfer, poRecord->poATTR );

        if( !poAttrReader->IsIndexed() )
            delete poRecord;
        
        iRecord++;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
}    
bool
TeExportQuerierToShapefile(TeQuerier* querier, const std::string& base)
{
	// check initial conditions
	if (!querier)
		return false;

	if (!querier->loadInstances())
		return false;

	// Get the list of attributes defined by the input querier
	bool onlyObjId = false;
	TeAttributeList qAttList = querier->getAttrList();
	if (qAttList.empty())
	{
		TeAttributeList qAttList;
		TeAttribute at;
		at.rep_.type_ = TeSTRING;               
		at.rep_.numChar_ = 100;
		at.rep_.name_ = "ID";
		at.rep_.isPrimaryKey_ = true;
		qAttList.push_back(at);
		onlyObjId = true;
	}

	// Handles to each type of geometries that will be created if necessary
	DBFHandle hDBFPol = 0;
	SHPHandle hSHPPol = 0;
	DBFHandle hDBFLin = 0;
	SHPHandle hSHPLin = 0;
	DBFHandle hDBFPt = 0;
	SHPHandle hSHPPt = 0;

	// Some auxiliary variables
    int totpoints;
    double*	padfX;
	double*	padfY;
    unsigned int nVertices;
    int* panPart;
    SHPObject *psObject;
    unsigned int posXY, npoints, nelem;
	int shpRes;

	// progress information
	if (TeProgress::instance())
		TeProgress::instance()->setTotalSteps(querier->numElemInstances());
	clock_t	t0, t1, t2;
	t2 = clock();
	t0 = t1 = t2;
	int dt = CLOCKS_PER_SEC/2;
	int dt2 = CLOCKS_PER_SEC; //* .000001;

	// Loop through the instances writting their geometries and attributes
	unsigned int iRecPol=0, iRecLin=0, iRecPt=0;
	unsigned int n, l, m;
	unsigned int nIProcessed = 0;
	TeSTInstance st;
	while(querier->fetchInstance(st))
	{
		totpoints = 0;
		nVertices = 0;
		if (st.hasPolygons())
		{
			TePolygonSet& polSet = st.getPolygons();
			TePolygonSet::iterator itps;
			int nVerticesCount = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				nVertices = (*itps).size();
				nVerticesCount += nVertices;
				for (n=0; n<nVertices;++n) 
					totpoints += (*itps)[n].size();
			}

			panPart = (int *) malloc(sizeof(int) * nVerticesCount);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);

			posXY = 0;
			nelem = 0;
			for (itps = polSet.begin(); itps != polSet.end(); ++itps) 
			{
				TePolygon poly = *itps;
				for (l=0; l<poly.size(); ++l) 
				{
					if (l==0) 
					{
						if (TeOrientation(poly[l]) == TeCOUNTERCLOCKWISE) 
							TeReverseLine(poly[l]);
					}
					else 
					{
						if (TeOrientation(poly[l]) == TeCLOCKWISE)
							TeReverseLine(poly[l]);
					}
					npoints = poly[l].size();
					panPart[nelem]=posXY;
        
					for (m=0; m<npoints; ++m) 
					{
						padfX[posXY] = poly[l][m].x_;
						padfY[posXY] = poly[l][m].y_;
						posXY++;
					}
					nelem++;
				}
			}
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL, posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);   
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasCells())
		{
			TeCellSet& cellSet = st.getCells();
			nVertices = cellSet.size();
			totpoints = nVertices*5;
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			TeCellSet::iterator itcs;
			for (itcs=cellSet.begin(); itcs!=cellSet.end(); ++itcs)
			{
				panPart[nelem]=posXY;
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().upperRight().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().upperRight().y();
				posXY++;		
				padfX[posXY] = (*itcs).box().lowerLeft().x();
				padfY[posXY] = (*itcs).box().lowerLeft().y();
				++posXY;	
				++nelem;
			} 
			psObject = SHPCreateObject(SHPT_POLYGON, -1, nelem, panPart, NULL,posXY, padfX, padfY, NULL, NULL);
			if (hSHPPol == 0)
			{
				string fname = base + "_pol.shp";
				hSHPPol = SHPCreate(fname.c_str(), SHPT_POLYGON);
   				assert (hSHPPol != 0);
			}	
			shpRes = SHPWriteObject(hSHPPol, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPol == 0)
			{
				hDBFPol = TeCreateDBFFile(base + "_pol.dbf", qAttList);
				assert (hDBFPol != 0);
			}

			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPol, iRecPol, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPol, iRecPol, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPol, iRecPol, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPol, iRecPol, n, atof(val.c_str()));
					}
				}
			}
			++iRecPol;
		}
		if (st.hasLines())
		{
			TeLineSet& lineSet = st.getLines();
			nVertices = lineSet.size();
			TeLineSet::iterator itls;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
				totpoints += (*itls).size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * totpoints);
			padfY = (double *) malloc(sizeof(double) * totpoints);
			posXY = 0;
			nelem = 0;
			for (itls=lineSet.begin(); itls!=lineSet.end(); ++itls)
			{
				panPart[nelem]=posXY;
				for (l=0; l<(*itls).size(); ++l)
				{
					padfX[posXY] = (*itls)[l].x();
					padfY[posXY] = (*itls)[l].y();
					++posXY;
				}
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_ARC, -1, nVertices, panPart, NULL,	posXY, padfX, padfY, NULL, NULL);
			if (hSHPLin == 0)
			{
				string fname = base + "_lin.shp"; 
				hSHPLin = SHPCreate(fname.c_str(), SHPT_ARC);
   				assert (hSHPLin != 0);
			}		
			shpRes = SHPWriteObject(hSHPLin, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFLin == 0)
			{
				hDBFLin = TeCreateDBFFile(base + "_lin.dbf", qAttList);
				assert (hDBFLin != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFLin, iRecLin, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
					if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFLin, iRecLin, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFLin, iRecLin, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFLin, iRecLin, n, atof(val.c_str()));
					}
				}
			}
			++iRecLin;
		}
		if (st.hasPoints())
		{
			TePointSet& pointSet = st.getPoints();
			nVertices = pointSet.size();
			panPart = (int *) malloc(sizeof(int) * nVertices);
			padfX = (double *) malloc(sizeof(double) * nVertices);
			padfY = (double *) malloc(sizeof(double) * nVertices);
			nelem = 0;
			TePointSet::iterator itpts;
			for (itpts=pointSet.begin(); itpts!=pointSet.end(); ++itpts)
			{
				panPart[nelem] = nelem;
				padfX[nelem] = (*itpts).location().x();
				padfY[nelem] = (*itpts).location().y();
				++nelem;
			}
			psObject = SHPCreateObject(SHPT_POINT, -1, nVertices, panPart, NULL, nVertices, padfX, padfY, NULL, NULL );
			if (hSHPPt == 0)
			{
				string fname = base + "_pt.shp";
				hSHPPt = SHPCreate(fname.c_str(), SHPT_POINT);
   				assert (hSHPPt != 0);
			}		
			shpRes = SHPWriteObject(hSHPPt, -1, psObject);
			SHPDestroyObject(psObject);
			free(panPart);
			free(padfX);
			free(padfY);
			assert(shpRes != -1);
			if (hDBFPt == 0)
			{
				hDBFPt = TeCreateDBFFile(base + "_pt.dbf", qAttList);
				assert (hDBFPt != 0);
			}
			if (onlyObjId)
			{
				DBFWriteStringAttribute(hDBFPt, iRecPt, 0, st.objectId().c_str());
			}
			else
			{
				string val;
				for (n=0; n<qAttList.size();++n) 
				{
					st.getPropertyValue(val,n);
						if (qAttList[n].rep_.type_ == TeSTRING || qAttList[n].rep_.type_ == TeDATETIME)
					{
						DBFWriteStringAttribute(hDBFPt, iRecPt, n, val.c_str());
					}
					else if (qAttList[n].rep_.type_ == TeINT)
					{
						DBFWriteIntegerAttribute(hDBFPt, iRecPt, n, atoi(val.c_str()));
					}
					else if (qAttList[n].rep_.type_ == TeREAL)
					{
						DBFWriteDoubleAttribute(hDBFPt, iRecPt, n, atof(val.c_str()));
					}
				}
			}
			++iRecPt;
		}
		++nIProcessed;
		if (TeProgress::instance() && int(t2-t1) > dt)
		{
			t1 = t2;
			if(((int)(t2-t0) > dt2))
			{
				if (TeProgress::instance()->wasCancelled())
					break;
				else
					TeProgress::instance()->setProgress(nIProcessed);
			}
		}

	}
	if (hDBFPol != 0)
		DBFClose(hDBFPol);
	if (hSHPPol != 0)
        SHPClose(hSHPPol);
	if (hDBFLin != 0)
		DBFClose(hDBFLin);
	if (hSHPLin != 0)
        SHPClose(hSHPLin);
	if (hDBFPt != 0)
		DBFClose(hDBFPt);
	if (hSHPPt != 0)
        SHPClose(hSHPPt);

	if (TeProgress::instance())
		TeProgress::instance()->reset();
	return true;
}
示例#17
0
// Convert baseline to shape file
void baseline2shape(int ii, struct base_pair *pairs,
                    DBFHandle dbase, SHPHandle shape)
{
    int vertices=4, off;
    char date[15];
    double *lat, *lon;
    julian_date jd;
    ymd_date ymd;
    char *mon[13]= {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                   };

    // Read coordinates of the vertices
    lat = (double *) MALLOC(sizeof(double)*(vertices+1));
    lon = (double *) MALLOC(sizeof(double)*(vertices+1));
    lat[0] = pairs->ns_lat;
    lon[0] = pairs->ns_lon;
    lat[1] = pairs->fs_lat;
    lon[1] = pairs->fs_lon;
    lat[2] = pairs->fe_lat;
    lon[2] = pairs->fe_lon;
    lat[3] = pairs->ne_lat;
    lon[3] = pairs->ne_lon;
    lat[vertices] = lat[0];
    lon[vertices] = lon[0];

    // Write information into database file
    if (strcmp_case(pairs->m_sensor, pairs->s_sensor) == 0) {
        DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor);
        off = 0;
    }
    else {
        DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor);
        DBFWriteStringAttribute(dbase, ii, 1, pairs->s_sensor);
        off = 1;
    }
    DBFWriteStringAttribute(dbase, ii, off+1, pairs->mode);
    DBFWriteIntegerAttribute(dbase, ii, off+2, pairs->frame);
    DBFWriteStringAttribute(dbase, ii, off+3, pairs->orbit_dir);
    DBFWriteIntegerAttribute(dbase, ii, off+4, pairs->master);
    sscanf(pairs->m_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year);
    DBFWriteStringAttribute(dbase, ii, off+5, date);
    DBFWriteIntegerAttribute(dbase, ii, off+6, pairs->slave);
    sscanf(pairs->s_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year);
    DBFWriteStringAttribute(dbase, ii, off+7, date);
    DBFWriteIntegerAttribute(dbase, ii, off+8, pairs->b_par);
    DBFWriteIntegerAttribute(dbase, ii, off+9, pairs->b_perp);
    DBFWriteIntegerAttribute(dbase, ii, off+10, pairs->b_temp);
    DBFWriteDoubleAttribute(dbase, ii, off+11, pairs->c_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+12, pairs->c_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+13, pairs->ns_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+14, pairs->ns_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+15, pairs->fs_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+16, pairs->fs_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+17, pairs->ne_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+18, pairs->ne_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+19, pairs->fe_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+20, pairs->fe_lon);

    // Write shape object
    SHPObject *shapeObject=NULL;
    shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, vertices+1,
                                        lon, lat, NULL);
    if (shapeObject == NULL)
        asfPrintError("Could not create shape object (%d)\n", ii);
    SHPWriteObject(shape, -1, shapeObject);
    SHPDestroyObject(shapeObject);

    FREE(lat);
    FREE(lon);
}
示例#18
0
void Builder::print_shpObjects()
{
  int dim = shpObjects.size();
  int dimTexts = textObjects.size();

  QgsDebugMsg( QString( "Number of primitives: %1" ).arg( dim ) );
  QgsDebugMsg( QString( "Number of text fields: %1" ).arg( dimTexts ) );

  SHPHandle hSHP;

  if ( fname.substr( fname.length() - 4 ).compare( ".shp" ) == 0 )
  {
    outputdbf = fname;
    outputdbf = outputdbf.replace(( outputdbf.length() - 3 ), outputdbf.length(), "dbf" );
    outputshp = fname;
    outputshp = outputshp.replace(( outputshp.length() - 3 ), outputshp.length(), "shp" );
    outputtdbf = fname;
    outputtdbf = outputtdbf.replace(( outputtdbf.length() - 4 ), outputtdbf.length(), "_texts.dbf" );
    outputtshp = fname;
    outputtshp = outputtshp.replace(( outputtshp.length() - 4 ), outputtshp.length(), "_texts.shp" );
  }
  else
  {
    outputdbf = outputtdbf = fname + ".dbf";
    outputshp = outputtshp = fname + ".shp";
  }

  DBFHandle dbffile = DBFCreate( outputdbf.c_str() );
  DBFAddField( dbffile, "myid", FTInteger, 10, 0 );

  hSHP = SHPCreate( outputshp.c_str(), shapefileType );

  QgsDebugMsg( "Writing to main shp file..." );

  for ( int i = 0; i < dim; i++ )
  {
    SHPWriteObject( hSHP, -1, shpObjects[i] );
    SHPDestroyObject( shpObjects[i] );
    DBFWriteIntegerAttribute( dbffile, i, 0, i );
  }

  SHPClose( hSHP );
  DBFClose( dbffile );

  QgsDebugMsg( "Done!" );

  if ( convertText && dimTexts > 0 )
  {
    SHPHandle thSHP;

    DBFHandle Tdbffile = DBFCreate( outputtdbf.c_str() );
    thSHP = SHPCreate( outputtshp.c_str(), SHPT_POINT );

    DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "height", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "text", FTString, 50, 0 );
    DBFAddField( Tdbffile, "style", FTString, 50, 0 );
    DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 );

    QgsDebugMsg( "Writing Texts' shp File..." );

    for ( int i = 0; i < dimTexts; i++ )
    {
      SHPObject *psObject;
      double x = textObjects[i].ipx;
      double y = textObjects[i].ipy;
      double z = textObjects[i].ipz;
      psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL );

      SHPWriteObject( thSHP, -1, psObject );

      DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx );
      DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy );
      DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz );

      DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx );
      DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy );
      DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz );

      DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height );
      DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor );
      DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags );

      DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification );
      DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification );

      DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() );
      DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() );

      DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle );

      SHPDestroyObject( psObject );
    }
    SHPClose( thSHP );
    DBFClose( Tdbffile );

    QgsDebugMsg( "Done!" );
  }
}
示例#19
0
 inline static void apply(DBFHandle dbf, int row_index, int field_index,
                 T const& value)
 {
     DBFWriteIntegerAttribute(dbf, row_index, field_index, value);
 }
示例#20
0
int main( int argc, char ** argv )

{
    SHPHandle	hSHP;
    DBFHandle   hDBF;
    SHPTreeHandle	qix;

    int		i;
    char	*myfile = NULL;

    treeNodeObj *node;

#ifdef MAPSERVER
    shapeObj	shape;
    lineObj	line[3];
    pointObj	pts[6];
#else
    SHPObject	*shape;
    double	X[6], Y[6];
#endif
    int		result;
    char	mBigEndian;

    int		this_rec, factor;

    /* -------------------------------------------------------------------- */
    /*      Display a usage message.                                        */
    /* -------------------------------------------------------------------- */
    if( argc <= 2 )
    {
        printf( "shptreevis shapefile new_shapefile \n" );
        exit( 1 );
    }

    i = 1;
    if( *((unsigned char *) &i) == 1 )
        mBigEndian = 0;
    else
        mBigEndian = 1;


    qix = msSHPDiskTreeOpen (AddFileSuffix(argv[1],".qix"), 0 /* no debug*/);
    if( qix == NULL )
    {
        printf("unable to open index file %s \n", argv[1]);
        exit(-1);
    }

    /* -------------------------------------------------------------------- */
    /*      Open the passed shapefile.                                      */
    /* -------------------------------------------------------------------- */
    myfile = AddFileSuffix(argv[2],".shp");

#ifdef MAPSERVER
    hSHP = msSHPCreate ( myfile, SHPT_POLYGON );
    hDBF = msDBFCreate (  AddFileSuffix(argv[2],".dbf") );
#else
    hSHP = SHPCreate ( myfile, SHPT_POLYGON );
    hDBF = DBFCreate (  AddFileSuffix(argv[2],".dbf") );
#endif

    if ( (!hSHP) || (!hDBF) )
    {
        printf ("create error for %s    ... exiting \n", myfile);
        exit (-1);
    }

    /* add fields to dbf */
#ifdef MAPSERVER
    msDBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
    msDBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
    msDBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
#else
    DBFAddField ( hDBF, "ITEMS", FTInteger, 15,0 );
    DBFAddField ( hDBF, "SUBNODES", FTInteger, 15,0 );
    DBFAddField ( hDBF, "FACTOR", FTInteger, 15,0 );
#endif

#ifndef MAPSERVER
    SHPClose ( hSHP );
    hSHP = SHPOpen ( myfile, "r+b" );

    DBFClose (hDBF);
    hDBF = DBFOpen ( myfile, "r+b");
#endif

    printf ("This %s %s index supports a shapefile with %d shapes, %d depth \n",
            (qix->version ? "new": "old"), (qix->LSB_order? "LSB": "MSB"), (int) qix->nShapes, (int) qix->nDepth);


    /* -------------------------------------------------------------------- */
    /*	Skim over the list of shapes, printing all the vertices.	*/
    /* -------------------------------------------------------------------- */

    while( 1 )
    {
        node = readTreeNode (qix);
        if (node )
        {

            this_rec = hDBF->nRecords;

#ifdef  MAPSERVER
            msDBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
            msDBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
#else
            DBFWriteIntegerAttribute( hDBF, this_rec, 0, node->numshapes);
            DBFWriteIntegerAttribute( hDBF, this_rec, 1, node->numsubnodes);
#endif
            factor = node->numshapes + node->numsubnodes;

#ifdef  MAPSERVER
            shape.numlines = 1;
            shape.type = SHPT_POLYGON;

            pts[0].x = node->rect.minx;
            pts[0].y = node->rect.miny;
            pts[1].x = node->rect.maxx;
            pts[1].y = node->rect.miny;
            pts[2].x = node->rect.maxx;
            pts[2].y = node->rect.maxy;
            pts[3].x = node->rect.minx;
            pts[3].y = node->rect.maxy;
            pts[4].x = node->rect.minx;
            pts[4].y = node->rect.miny;

            line[0].numpoints = 5;
            line[0].point = &pts[0];
            shape.line = &line[0];
            shape.bounds = node->rect;

            result = msSHPWriteShape ( hSHP, &shape );
            if ( result < 0 )
            {
                printf ("unable to write shape \n");
                exit (0);
            }

#else
            X[0] = node->rect.minx;
            X[1] = node->rect.maxx;
            X[2] = node->rect.maxx;
            X[3] = node->rect.minx;
            X[4] = node->rect.minx;

            Y[0] = node->rect.miny;
            Y[1] = node->rect.miny;
            Y[2] = node->rect.maxy;
            Y[3] = node->rect.maxy;
            Y[4] = node->rect.miny;

            shape = SHPCreateSimpleObject( SHPT_POLYGON, 5, X, Y, NULL);
            SHPWriteObject(hSHP, -1, shape);
            SHPDestroyObject ( shape );
#endif
        }
        else
            break;
    }

#ifdef MAPSERVER
    msSHPClose( hSHP );
    msDBFClose( hDBF );
#else
    SHPClose( hSHP );
    DBFClose( hDBF );
#endif

    msSHPDiskTreeClose (qix);

    return(0);
}
示例#21
0
static void WritePointShapefile( const char * pszShapefile,
                                 SDTSTransfer * poTransfer,
                                 const char * pszMODN )

{
    SDTSPointReader     *poPointReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    poPointReader = (SDTSPointReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPointReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poPointReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POINT );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nAreaField, nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );
    nAreaField = DBFAddField( hDBF, "AreaId", FTString, 12, 0 );
    
    char  **papszModRefs = poPointReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the line features in the module.                    */
/* ==================================================================== */
    SDTSRawPoint        *poRawPoint;
        
    while( (poRawPoint = poPointReader->GetNextPoint()) != NULL )
    {
        int             iShape;
        
/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateSimpleObject( SHPT_POINT, 1,
                                         &(poRawPoint->dfX),
                                         &(poRawPoint->dfY),
                                         &(poRawPoint->dfZ) );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        char    szID[13];

        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoint->oModId.nRecord );
        
        sprintf( szID, "%s:%ld",
                 poRawPoint->oAreaId.szModule,
                 poRawPoint->oAreaId.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nAreaField, szID );

        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoint );

        if( !poPointReader->IsIndexed() )
            delete poRawPoint;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}    
示例#22
0
static void WriteLineShapefile( const char * pszShapefile,
                                SDTSTransfer * poTransfer,
                                const char * pszMODN )

{
/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed Pointgon reader.                */
/* -------------------------------------------------------------------- */
    SDTSLineReader *poLineReader = (SDTSLineReader *)
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );

    if( poLineReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

    poLineReader->Rewind();

/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_ARC );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nLeftPolyField, nRightPolyField;
    int         nStartNodeField, nEndNodeField, nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );
    nLeftPolyField = DBFAddField( hDBF, "LeftPoly", FTString, 12, 0 );
    nRightPolyField = DBFAddField( hDBF, "RightPoly", FTString, 12, 0 );
    nStartNodeField = DBFAddField( hDBF, "StartNode", FTString, 12, 0 );
    nEndNodeField = DBFAddField( hDBF, "EndNode", FTString, 12, 0 );

    char  **papszModRefs = poLineReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the line features in the module.                    */
/* ==================================================================== */
    SDTSRawLine *poRawLine = NULL;

    while( (poRawLine = poLineReader->GetNextLine()) != NULL )
    {
/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject *psShape =
            SHPCreateSimpleObject( SHPT_ARC, poRawLine->nVertices,
                                   poRawLine->padfX, poRawLine->padfY,
                                   poRawLine->padfZ );

        int iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        char    szID[13];

        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawLine->oModId.nRecord );

        sprintf( szID, "%s:%d",
                 poRawLine->oLeftPoly.szModule,
                 poRawLine->oLeftPoly.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nLeftPolyField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oRightPoly.szModule,
                 poRawLine->oRightPoly.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nRightPolyField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oStartNode.szModule,
                 poRawLine->oStartNode.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nStartNodeField, szID );

        sprintf( szID, "%s:%d",
                 poRawLine->oEndNode.szModule,
                 poRawLine->oEndNode.nRecord );
        DBFWriteStringAttribute( hDBF, iShape, nEndNodeField, szID );

        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawLine );

        if( !poLineReader->IsIndexed() )
            delete poRawLine;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}
示例#23
0
static void WritePolygonShapefile( const char * pszShapefile,
                                   SDTSTransfer * poTransfer, 
                                   const char * pszMODN )

{
    SDTSPolygonReader *poPolyReader;

/* -------------------------------------------------------------------- */
/*      Fetch a reference to the indexed polygon reader.                */
/* -------------------------------------------------------------------- */
    poPolyReader = (SDTSPolygonReader *) 
        poTransfer->GetLayerIndexedReader( poTransfer->FindLayer( pszMODN ) );
    
    if( poPolyReader == NULL )
    {
        fprintf( stderr, "Failed to open %s.\n",
                 poTransfer->GetCATD()->GetModuleFilePath( pszMODN ) );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Assemble polygon geometries from all the line layers.           */
/* -------------------------------------------------------------------- */
    poPolyReader->AssembleRings( poTransfer, poTransfer->FindLayer(pszMODN) );
    
/* -------------------------------------------------------------------- */
/*      Create the Shapefile.                                           */
/* -------------------------------------------------------------------- */
    SHPHandle   hSHP;

    hSHP = SHPCreate( pszShapefile, SHPT_POLYGON );
    if( hSHP == NULL )
    {
        fprintf( stderr, "Unable to create shapefile `%s'\n",
                 pszShapefile );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Create the database file, and our basic set of attributes.      */
/* -------------------------------------------------------------------- */
    DBFHandle   hDBF;
    int         nSDTSRecordField;
    char        szDBFFilename[1024];

    sprintf( szDBFFilename, "%s.dbf", pszShapefile );

    hDBF = DBFCreate( szDBFFilename );
    if( hDBF == NULL )
    {
        fprintf( stderr, "Unable to create shapefile .dbf for `%s'\n",
                 pszShapefile );
        return;
    }

    nSDTSRecordField = DBFAddField( hDBF, "SDTSRecId", FTInteger, 8, 0 );

    char  **papszModRefs = poPolyReader->ScanModuleReferences();
    AddPrimaryAttrToDBFSchema( hDBF, poTransfer, papszModRefs );
    CSLDestroy( papszModRefs );

/* ==================================================================== */
/*      Process all the polygon features in the module.                 */
/* ==================================================================== */
    SDTSRawPolygon      *poRawPoly;

    poPolyReader->Rewind();
    while( (poRawPoly = (SDTSRawPolygon *) poPolyReader->GetNextFeature())
           != NULL )
    {
        int             iShape;

/* -------------------------------------------------------------------- */
/*      Write out a shape with the vertices.                            */
/* -------------------------------------------------------------------- */
        SHPObject       *psShape;

        psShape = SHPCreateObject( SHPT_POLYGON, -1, poRawPoly->nRings,
                                   poRawPoly->panRingStart, NULL,
                                   poRawPoly->nVertices,
                                   poRawPoly->padfX, 
                                   poRawPoly->padfY, 
                                   poRawPoly->padfZ,
                                   NULL );

        iShape = SHPWriteObject( hSHP, -1, psShape );

        SHPDestroyObject( psShape );

/* -------------------------------------------------------------------- */
/*      Write out the attributes.                                       */
/* -------------------------------------------------------------------- */
        DBFWriteIntegerAttribute( hDBF, iShape, nSDTSRecordField,
                                  poRawPoly->oModId.nRecord );
        WritePrimaryAttrToDBF( hDBF, iShape, poTransfer, poRawPoly );

        if( !poPolyReader->IsIndexed() )
            delete poRawPoly;
    }

/* -------------------------------------------------------------------- */
/*      Close, and cleanup.                                             */
/* -------------------------------------------------------------------- */
    DBFClose( hDBF );
    SHPClose( hSHP );
}    
示例#24
0
CC_FILE_ERROR ShpFilter::saveToFile(ccHObject* entity, const std::vector<GenericField*>& fields, QString filename)
{
	if (!entity)
		return CC_FERR_BAD_ENTITY_TYPE;
	
	//this filter only supports point clouds, meshes and polylines!
	ESRI_SHAPE_TYPE inputShapeType = SHP_NULL_SHAPE;
	ccHObject::Container toSave;
	GetSupportedShapes(entity,toSave,inputShapeType/*,m_closedPolylinesAsPolygons*/);

	if (inputShapeType == SHP_NULL_SHAPE || toSave.empty())
		return CC_FERR_BAD_ENTITY_TYPE;

	ESRI_SHAPE_TYPE outputShapeType = inputShapeType;
	if (m_closedPolylinesAsPolygons && (inputShapeType == SHP_POLYLINE || inputShapeType == SHP_POLYLINE_Z))
	{
		//check if all the polylines are closed!
		bool allAreClosed = true;
		for (size_t i=0; i<toSave.size() && allAreClosed; ++i)
		{
			if (!static_cast<ccPolyline*>(toSave[i])->isClosed())
				allAreClosed = false;
		}

		if (allAreClosed)
		{
			//promote 'polylines' to 'polygon'
			outputShapeType = SHP_POLYLINE ? SHP_POLYGON : SHP_POLYGON_Z;
		}
	}

	ccLog::Print("[SHP] Output type: " + ToString(outputShapeType));

	QFileInfo fi(filename);
	QString baseFileName = fi.path() + QString("/") + fi.completeBaseName();

	//the main file (suffix should be ".shp")
	QString shpFilename = baseFileName+QString(".shp");
	QFile file(shpFilename);
	if (!file.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	//index file (same base name + ".shx")
	QString indexFilename = baseFileName+QString(".shx");
	QFile indexFile(indexFilename);
	if (!indexFile.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	//build header (refer to ESRI Shapefile Technical Description)
	char header[100];
	memset(header,0,100);
	{
		/*** WARNING: the beginning of the header is written with big endianness! ***/
		char* _header = header;
		
		//Byte 0: SHP code
		const int32_t code = qToBigEndian<int32_t>(9994);
		memcpy(_header,(const char*)&code,4);
		_header += 4;

		//Byte 4: unused (20 bytes)
		_header += 20;

		//Byte 24: file length (will be written... later ;)
		_header += 4;

		/*** WARNING: from now on, we only write data with little endianness! ***/

		//Byte 28: file verion
		const int32_t version = qToLittleEndian<int32_t>(1000);
		memcpy(_header,(const char*)&version,4);
		_header += 4;

		//Byte 32: shape type
		int32_t shapeTypeInt = qToLittleEndian<int32_t>(outputShapeType);
		memcpy(_header,(const char*)&shapeTypeInt,4);
		_header += 4;

		ccBBox box = entity->getBB();
		assert(box.isValid());

		//X and Y bounaries
		double xMin = qToLittleEndian<double>(box.minCorner().x);
		double xMax = qToLittleEndian<double>(box.maxCorner().x);
		double yMin = qToLittleEndian<double>(box.minCorner().y);
		double yMax = qToLittleEndian<double>(box.maxCorner().y);
		//Byte 36: box X min
		memcpy(_header,(const char*)&xMin,8);
		_header += 8;
		//Byte 44: box Y min
		memcpy(_header,(const char*)&yMin,8);
		_header += 8;
		//Byte 52: box X max
		memcpy(_header,(const char*)&xMax,8);
		_header += 8;
		//Byte 60: box Y max
		memcpy(_header,(const char*)&yMax,8);
		_header += 8;

		//Z bounaries
		//Unused, with value 0.0, if not Measured or Z type
		double zMin = outputShapeType < SHP_POINT_Z ? 0.0 : qToLittleEndian<double>(box.minCorner().z);
		double zMax = outputShapeType < SHP_POINT_Z ? 0.0 : qToLittleEndian<double>(box.maxCorner().z);
		//Byte 68: box Z min
		memcpy(_header,(const char*)&zMin,8);
		_header += 8;
		//Byte 76: box Z max
		memcpy(_header,(const char*)&zMax,8);
		_header += 8;

		//M bounaries (M = measures)
		double mMin = ESRI_NO_DATA;
		double mMax = ESRI_NO_DATA;
		//Byte 84: M min
		memcpy(_header,(const char*)&mMin,8);
		_header += 8;
		//Byte 92: M max
		memcpy(_header,(const char*)&mMax,8);
		_header += 8;
	}

	//actually write the header
	if (!file.write(header,100))
		return CC_FERR_WRITING;
	if (!indexFile.write(header,100)) //exact same header for index file!
		return CC_FERR_WRITING;
	int32_t fileLength = 100;

	//save shapes
	unsigned shapeIndex = 0;
	for (unsigned i=0; i<toSave.size(); ++i)
	{
		ccHObject* child = toSave[i];
		
		//check entity elligibility
		if (child->isA(CC_TYPES::POLY_LINE))
		{
			if (static_cast<ccPolyline*>(child)->size() < 3)
			{
				ccLog::Warning(QString("Polyline '%1' is too small! It won't be saved...").arg(child->getName()));
				continue;
			}
		}

		int32_t recordSize = 0;
		qint64 recordStart = file.pos();
		//write shape record in main SHP file
		{
			//Byte 0: Record Number
			const int32_t recordNumber = qToBigEndian<int32_t>(++shapeIndex); //Record numbers begin at 1
			file.write((const char*)&recordNumber,4);
			//Byte 4: Content Length
			file.write((const char*)&recordSize,4); //will be updated later
		}
		fileLength += 8;

		CC_FILE_ERROR error = CC_FERR_NO_ERROR;
		switch (inputShapeType)
		{
		case SHP_POLYLINE:
		case SHP_POLYLINE_Z:
			assert(child->isKindOf(CC_TYPES::POLY_LINE));
			error = SavePolyline(static_cast<ccPolyline*>(child),file,recordSize,outputShapeType);
			break;
		case SHP_MULTI_POINT_Z:
			assert(child->isKindOf(CC_TYPES::POINT_CLOUD));
			error = SaveAsCloud(ccHObjectCaster::ToGenericPointCloud(child),file,recordSize);
			break;
		//case SHP_MULTI_PATCH:
		//	assert(child->isKindOf(CC_TYPES::MESH));
		//	error = SaveAsMesh(ccHObjectCaster::ToMesh(child),file,recordSize);
		//	break;
		default:
			assert(false);
			break;
		}

		if (error != CC_FERR_NO_ERROR)
			return error;

		fileLength += recordSize;

		//update record size
		{
			//backup current pos
			qint64 currentPos = file.pos();
			assert((qint64)fileLength == currentPos);
			//go backward
			file.seek(recordStart+4);
			int32_t recordSize16bits = qToBigEndian<int32_t>(recordSize/2); //recordSize is measured in 16-bit words
			file.write((const char*)&recordSize16bits,4);
			//restore last pos
			file.seek(currentPos);
		}

		//write corresponding entry in index SHX file
		{
			//Byte 0: Offset
			int32_t recordStart16bits = qToBigEndian<int32_t>(recordStart/2); //recordStart is measured in 16-bit words
			indexFile.write((const char*)&recordStart16bits,4);
			
			//Byte 4: Content Length
			int32_t recordSize16bits= qToBigEndian<int32_t>(recordSize/2); //recordSize is measured in 16-bit words
			indexFile.write((const char*)&recordSize16bits,4);
		}
	}

	//update main file length
	{
		file.seek(24);
		//Byte 24: file length (in 16-bit words)
		int32_t fileLength16bits = qToBigEndian<int32_t>(fileLength/2);
		file.write((const char*)&fileLength16bits,4);
	}
	file.close();

	//update idx file length
	{
		indexFile.seek(24);
		//Byte 24: file length (in 16-bit words)
		int32_t idxFileLength = (int32_t)indexFile.size();
		int32_t idxFileLength16bits = qToBigEndian<int32_t>(idxFileLength/2);
		indexFile.write((const char*)&idxFileLength16bits,4);
	}
	indexFile.close();

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//eventually, we create the DB file (suffix should be ".dbf")
	QString dbfFilename = baseFileName+QString(".dbf");
	DBFHandle dbfHandle = DBFCreate(qPrintable(dbfFilename));
	if (dbfHandle)
	{
		while (true) //trick: we use 'while' to be able to break anytime
		{
			//always write an 'index' table
			{
				int fieldIdx = DBFAddField(dbfHandle,"local_idx",FTInteger,6,0);
				if (fieldIdx >= 0)
				{
					for (unsigned i=0; i<toSave.size(); ++i)
						DBFWriteIntegerAttribute(dbfHandle,static_cast<int>(i),fieldIdx,static_cast<int>(i)+1);
				}
				else
				{
					ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field 'index' (default)"));
					result = CC_FERR_WRITING;
					break;
				}
			}

			//and write the other tables (specified by the user)
			for (std::vector<GenericField*>::const_iterator it = fields.begin(); it != fields.end(); ++it)
			{
				const GenericField* field = *it;
				if (field->is3D()) //3D case
				{
					int xFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_x")),field->type(),field->width(),field->decimal());
					int yFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_y")),field->type(),field->width(),field->decimal());
					int zFieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()+QString("_z")),field->type(),field->width(),field->decimal());
					if (xFieldIdx >= 0 && yFieldIdx >= 0 && zFieldIdx >= 0)
					{
						if (!(*it)->save(dbfHandle,xFieldIdx,yFieldIdx,zFieldIdx))
							xFieldIdx = -1;
					}

					if (xFieldIdx < 0)
					{
						ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field '%1'").arg(field->name()));
						result = CC_FERR_WRITING;
						break;
					}
				}
				else //1D case
				{
					int fieldIdx = DBFAddField(dbfHandle,qPrintable(field->name()),field->type(),field->width(),field->decimal());
					if (fieldIdx >= 0)
					{
						if (!(*it)->save(dbfHandle,fieldIdx))
							fieldIdx = -1;
					}

					if (fieldIdx < 0)
					{
						ccLog::Warning(QString("[ShpFilter::saveToFile] Failed to save field '%1'").arg(field->name()));
						result = CC_FERR_WRITING;
						break;
					}
				}
			}

			break;
		}

		DBFClose(dbfHandle);
	}
	else
	{
		result = CC_FERR_WRITING;
	}

	return result;
}
示例#25
0
void Builder::print_shpObjects()
{
  QgsDebugMsg( QString( "Number of primitives: %1" ).arg( shpObjects.size() ) );
  QgsDebugMsg( QString( "Number of text fields: %1" ).arg( textObjects.size() ) );
  QgsDebugMsg( QString( "Number of inserts fields: %1" ).arg( insertObjects.size() ) );

  SHPHandle hSHP;

  if ( fname.endsWith( ".shp", Qt::CaseInsensitive ) )
  {
    QString fn( fname.mid( fname.length() - 4 ) );

    outputdbf = fn + ".dbf";
    outputshp = fn + ".shp";
    outputtdbf = fn + "_texts.dbf";
    outputtshp = fn + "_texts.shp";
    outputidbf = fn + "_inserts.dbf";
    outputishp = fn + "_inserts.shp";
  }
  else
  {
    outputdbf = outputtdbf = outputidbf = fname + ".dbf";
    outputshp = outputtshp = outputishp = fname + ".shp";
  }

  DBFHandle dbffile = DBFCreate( outputdbf.toUtf8() );
  DBFAddField( dbffile, "myid", FTInteger, 10, 0 );

  hSHP = SHPCreate( outputshp.toUtf8(), shapefileType );

  QgsDebugMsg( "Writing to main shp file..." );

  for ( int i = 0; i < shpObjects.size(); i++ )
  {
    SHPWriteObject( hSHP, -1, shpObjects[i] );
    SHPDestroyObject( shpObjects[i] );
    DBFWriteIntegerAttribute( dbffile, i, 0, i );
  }

  SHPClose( hSHP );
  DBFClose( dbffile );

  QgsDebugMsg( "Done!" );

  if ( !textObjects.isEmpty() )
  {
    SHPHandle thSHP;

    DBFHandle Tdbffile = DBFCreate( outputtdbf.toUtf8() );
    thSHP = SHPCreate( outputtshp.toUtf8(), SHPT_POINT );

    DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "height", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 );
    DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 );
    DBFAddField( Tdbffile, "text", FTString, 50, 0 );
    DBFAddField( Tdbffile, "style", FTString, 50, 0 );
    DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 );

    QgsDebugMsg( "Writing Texts' shp File..." );

    for ( int i = 0; i < textObjects.size(); i++ )
    {
      SHPObject *psObject;
      double x = textObjects[i].ipx;
      double y = textObjects[i].ipy;
      double z = textObjects[i].ipz;
      psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL );

      SHPWriteObject( thSHP, -1, psObject );

      DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects[i].ipx );
      DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects[i].ipy );
      DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects[i].ipz );

      DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects[i].apx );
      DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects[i].apy );
      DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects[i].apz );

      DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects[i].height );
      DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects[i].xScaleFactor );
      DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects[i].textGenerationFlags );

      DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects[i].hJustification );
      DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects[i].vJustification );

      DBFWriteStringAttribute( Tdbffile, i, 11, textObjects[i].text.c_str() );
      DBFWriteStringAttribute( Tdbffile, i, 12, textObjects[i].style.c_str() );

      DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects[i].angle );

      SHPDestroyObject( psObject );
    }
    SHPClose( thSHP );
    DBFClose( Tdbffile );

    QgsDebugMsg( "Done!" );
  }

  if ( !insertObjects.isEmpty() )
  {
    SHPHandle ihSHP;

    DBFHandle Idbffile = DBFCreate( outputidbf.toUtf8() );
    ihSHP = SHPCreate( outputishp.toUtf8(), SHPT_POINT );

    DBFAddField( Idbffile, "name", FTString, 200, 0 );
    DBFAddField( Idbffile, "ipx", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "ipy", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "ipz", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sx", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sy", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "sz", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "angle", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "cols", FTInteger, 20, 0 );
    DBFAddField( Idbffile, "rows", FTInteger, 20, 0 );
    DBFAddField( Idbffile, "colsp", FTDouble, 20, 10 );
    DBFAddField( Idbffile, "rowsp", FTDouble, 20, 10 );

    QgsDebugMsg( "Writing Insert' shp File..." );

    for ( int i = 0; i < insertObjects.size(); i++ )
    {
      SHPObject *psObject;
      double &x = insertObjects[i].ipx;
      double &y = insertObjects[i].ipy;
      double &z = insertObjects[i].ipz;
      psObject = SHPCreateObject( SHPT_POINT, i, 0, NULL, NULL, 1, &x, &y, &z, NULL );

      SHPWriteObject( ihSHP, -1, psObject );

      int c = 0;
      DBFWriteStringAttribute( Idbffile, i, c++, insertObjects[i].name.c_str() );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipx );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipy );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].ipz );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sx );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sy );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].sz );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].angle );
      DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].cols );
      DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects[i].rows );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].colSp );
      DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects[i].rowSp );

      SHPDestroyObject( psObject );
    }
    SHPClose( ihSHP );
    DBFClose( Idbffile );

    QgsDebugMsg( "Done!" );
  }
}
示例#26
0
 void add_attribute(const int field, const int value) const {
     int ok = DBFWriteIntegerAttribute(m_dbf_handle, m_current_shape, field, value);
     if (!ok) {
         throw std::runtime_error(std::string("Can't add integer to field"));
     }
 }