Example #1
0
bool vtStructureArray::WriteXML(const char* filename, bool bGZip) const
{
	VTLOG("WriteXML(%s)\n", filename);

	// Avoid trouble with '.' and ',' in Europe
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	GZOutput out(bGZip);
	if (!gfopen(out, filename))
	{
		throw xh_io_exception("Could not open output file", xh_location(filename),
				"XML Writer");
	}

	gfprintf(out, "<?xml version=\"1.0\"?>\n");
	gfprintf(out, "\n");

	gfprintf(out, "<StructureCollection xmlns=\"http://www.openplans.net\"\n"
		"\t\t\t\t\t xmlns:gml=\"http://www.opengis.net/gml\"\n"
		"\t\t\t\t\t xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
		"\t\t\t\t\t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
		"\t\t\t\t\t xsi:schemaLocation=\"http://www.openplans.net/buildings.xsd\">\n");
	gfprintf(out, "\n");

	// Write the extents (required by gml:StructureCollection)
	DRECT ext;
	GetExtents(ext);
	gfprintf(out, "\t<gml:boundedBy>\n");
	gfprintf(out, "\t\t<gml:Box>\n");
	gfprintf(out, "\t\t\t<gml:coordinates>");
	gfprintf(out, "%.9lf,%.9lf %.9lf,%.9lf", ext.left, ext.bottom, ext.right, ext.top);
	gfprintf(out, "</gml:coordinates>\n");
	gfprintf(out, "\t\t</gml:Box>\n");
	gfprintf(out, "\t</gml:boundedBy>\n");
	gfprintf(out, "\n");

	// Write projection
	char *wkt;
	OGRErr err = m_proj.exportToWkt(&wkt);
	if (err != OGRERR_NONE)
	{
		throw xh_io_exception("Couldn't write CRS to file", xh_location(filename),
				"XML Writer");
	}
	gfprintf(out, "\t<SRS>%s</SRS>\n", wkt);
	gfprintf(out, "\n");
	OGRFree(wkt);

	bool bDegrees = (m_proj.IsGeographic() == 1);

	for (uint i = 0; i < GetSize(); i++)
	{
		vtStructure *str = GetAt(i);
		str->WriteXML(out, bDegrees);
	}
	gfprintf(out, "</StructureCollection>\n");
	gfclose(out);
	return true;
}
Example #2
0
bool ColorMap::Load(const char *fname)
{
	// watch out for %f
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	FILE *fp = vtFileOpen(fname, "rb");
	if (!fp)
		return false;

	char buf[80];
	fgets(buf, 80, fp);
	if (strncmp(buf, "colormap1", 9))
		return false;

	while (fgets(buf, 80, fp) != NULL)
	{
		int ival;
		if (!strncmp(buf, "blend", 5))
		{
			sscanf(buf, "blend: %d\n", &ival);
			m_bBlend = (ival != 0);
		}

		else if (!strncmp(buf, "relative", 8))
		{
			sscanf(buf, "relative: %d\n", &ival);
			m_bRelative = (ival != 0);
		}

		else if (!strncmp(buf, "size", 4))
		{
			int size;
			sscanf(buf, "size %d\n", &size);

			m_elev.resize(size);
			m_color.resize(size);
			for (int i = 0; i < size; i++)
			{
				float f;
				short r, g, b;
				fscanf(fp, "\telev %f color %hd %hd %hd\n", &f, &r, &g, &b);
				m_elev[i] = f;
				m_color[i].Set(r, g, b);
			}
		}
	}
	fclose(fp);
	return true;
}
Example #3
0
bool vtUtilityMap::ReadOSM(const char *pathname, bool progress_callback(int))
{
	// Avoid trouble with '.' and ',' in Europe
	//  OSM always has English punctuation
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	UtilOSMVisitor visitor(this);
	try
	{
		readXML(pathname, visitor, progress_callback);
	}
	catch (xh_exception &ex)
	{
		VTLOG1(ex.getFormattedMessage().c_str());
		return false;
	}
	return true;
}
Example #4
0
bool ColorMap::Save(const char *fname) const
{
	// watch out for %f
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	FILE *fp = vtFileOpen(fname, "wb");
	if (!fp)
		return false;
	fprintf(fp, "colormap1\n");
	fprintf(fp, "blend: %d\n", m_bBlend);
	fprintf(fp, "relative: %d\n", m_bRelative);
	int size = m_elev.size();
	fprintf(fp, "size %d\n", size);
	for (int i = 0; i < size; i++)
	{
		fprintf(fp, "\telev %f color %d %d %d\n", m_elev[i],
			m_color[i].r, m_color[i].g, m_color[i].b);
	}
	fclose(fp);
	return true;
}
Example #5
0
bool vtUtilityMap::ReadXML(const char *pathname, bool progress_callback(int))
{
	// The locale might be set to something European that interprets '.' as ','
	//  and vice versa, which would break our usage of sscanf/atof terribly.
	//  So, push the 'standard' locale, it is restored when it goes out of scope.
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	bool success = false;
	UtilityVisitor visitor(this);
	try
	{
		readXML(pathname, visitor, progress_callback);
		success = true;
	}
	catch (xh_exception &ex)
	{
		// TODO: would be good to pass back the error message.
		VTLOG("XML Error: ");
		VTLOG(ex.getFormattedMessage().c_str());
		return false;
	}

	return success;
}
Example #6
0
bool vtElevLayer::ImportFromFile(const wxString &strFileName,
	bool progress_callback(int), vtElevError *err)
{
	// Avoid trouble with '.' and ',' in Europe - all the file readers assume
	//  the default "C" locale.
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	wxString strExt = strFileName.AfterLast('.');
	vtString fname = (const char *) strFileName.mb_str(wxConvUTF8);

	VTLOG("ImportFromFile '%s'\n", (const char *) fname);

	if (!strExt.CmpNoCase(_T("gz")))
	{
		// ignore .gz, look at extension under it
		wxString dropped = strFileName.Left(strFileName.Len()-3);
		strExt = dropped.AfterLast('.');
	}

	if (!strExt.CmpNoCase(_T("bz2")))
	{
		// ignore .bz2, look at extension under it
		wxString dropped = strFileName.Left(strFileName.Len()-4);
		strExt = dropped.AfterLast('.');
	}

	// The first character in the file is useful for telling which format
	// the file really is.
	FILE *fp = vtFileOpen(fname, "rb");
	char first = fgetc(fp);
	fclose(fp);

	bool success = false;

	if (!strExt.CmpNoCase(_T("dxf")))
	{
		m_pTin = new vtTin2d;
		success = m_pTin->ReadDXF(fname, progress_callback);
	}
	else
	if (!strFileName.Right(6).CmpNoCase(_T("xy.adf")))
	{
		m_pTin = new vtTin2d;
		success = m_pTin->ReadADF(fname, progress_callback);
	}
	else
	if (!strFileName.Right(4).CmpNoCase(_T(".tin")))
	{
		m_pTin = new vtTin2d;
		success = m_pTin->ReadGMS(fname, progress_callback);
	}
	else
	if (!strFileName.Right(4).CmpNoCase(_T(".ply")))
	{
		m_pTin = new vtTin2d;
		success = m_pTin->ReadPLY(fname, progress_callback);
	}
	else
	{
		if (m_pGrid == NULL)
			m_pGrid = new vtElevationGrid;
	}

	if (!strExt.CmpNoCase(_T("3tx")))
	{
		success = m_pGrid->LoadFrom3TX(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("dem")))
	{
		// If there is a .hdr file in the same place, it is most likely
		//  a GTOPO30/SRTM30 file
		vtString hdr_fname = ChangeFileExtension(fname, ".hdr");
		if (vtFileExists(hdr_fname))
			success = m_pGrid->LoadFromGTOPO30(hdr_fname, progress_callback);
		else
		{
			if (first == '*')
				success = m_pGrid->LoadFromMicroDEM(fname, progress_callback);
			else
				success = m_pGrid->LoadFromDEM(fname, progress_callback, err);
		}
	}
	else if (!strExt.CmpNoCase(_T("asc")))
	{
		success = m_pGrid->LoadFromASC(fname, progress_callback);
		// vtElevationGrid does have its own ASC reader, but use GDAL instead
//		success = m_pGrid->LoadWithGDAL(strFileName.mb_str(wxConvUTF8), progress_callback, err);
	}
	else if (!strExt.CmpNoCase(_T("bil")))
	{
		success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
	}
	else if (!strExt.CmpNoCase(_T("mem")))
	{
		success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
	}
	else if (!strExt.CmpNoCase(_T("ter")))
	{
		success = m_pGrid->LoadFromTerragen(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("cdf")))
	{
		success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
	}
	else if (!strExt.CmpNoCase(_T("hdr")))
	{
		success = m_pGrid->LoadFromGTOPO30(fname, progress_callback);
		if (!success)
			success = m_pGrid->LoadFromGLOBE(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("dte")) ||
			!strExt.CmpNoCase(_T("dt0")) ||
			!strExt.CmpNoCase(_T("dt1")) ||
			!strExt.CmpNoCase(_T("dt2")))
	{
		success = m_pGrid->LoadFromDTED(fname, progress_callback);
	}
	else if (!strExt.Left(3).CmpNoCase(_T("pgm")))
	{
		success = m_pGrid->LoadFromPGM(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("grd")))
	{
		// might by CDF, might be Surfer GRD
		if (first == 'D')
		{
			VTLOG("First character is 'D', attempting load as a Surfer Grid file.\n");
			success = m_pGrid->LoadFromGRD(fname, progress_callback);
		}
		else
		{
			VTLOG("First character is not 'D', attempting load as a netCDF file.\n");
			success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
		}
		if (!success)
		{
			VTLOG("Didn't load successfully, attempting load with GDAL.\n");
			// Might be 'Arc Binary Grid', try GDAL
			success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
		}
	}
	else if (!strFileName.Right(8).CmpNoCase(_T("catd.ddf")) ||
			!strExt.Left(3).CmpNoCase(_T("tif")) ||
			!strExt.Left(3).CmpNoCase(_T("png")) ||
			!strExt.Left(3).CmpNoCase(_T("img")) ||
			!strExt.CmpNoCase(_T("adf")))
	{
		if (m_pGrid)
			success = m_pGrid->LoadWithGDAL(fname, progress_callback, err);
	}
	else if (!strExt.CmpNoCase(_T("raw")))
	{
		RawDlg dlg(NULL, -1, _("Raw Elevation File"));

		dlg.m_iBytes = 2;
		dlg.m_iWidth = 100;
		dlg.m_iHeight = 100;
		dlg.m_fVUnits = 1.0f;
		dlg.m_fSpacing = 30.0f;
		dlg.m_bBigEndian = false;
		dlg.m_extents.SetToZero();
		g_bld->GetProjection(dlg.m_original);

		if (dlg.ShowModal() == wxID_OK)
		{
			success = m_pGrid->LoadFromRAW(fname, dlg.m_iWidth,
					dlg.m_iHeight, dlg.m_iBytes, dlg.m_fVUnits, dlg.m_bBigEndian,
					progress_callback);
		}
		if (success)
		{
			m_pGrid->SetEarthExtents(dlg.m_extents);
			m_pGrid->SetProjection(dlg.m_proj);
		}
	}
	else if (!strExt.CmpNoCase(_T("ntf")))
	{
		success = m_pGrid->LoadFromNTF5(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("txt")) ||
		!strExt.CmpNoCase(_T("xyz")))
	{
		success = m_pGrid->LoadFromXYZ(fname, progress_callback);
	}
	else if (!strExt.CmpNoCase(_T("hgt")))
	{
		success = m_pGrid->LoadFromHGT(fname, progress_callback);
	}
	else if (!strExt.Left(2).CmpNoCase(_T("db")))
	{
		success = ImportFromDB(fname, progress_callback);
	}
	if (!success)
		return false;

	vtProjection *pProj;
	if (m_pGrid)
		pProj = &m_pGrid->GetProjection();
	else
		pProj = &m_pTin->m_proj;

	// We should ask for a CRS before asking for extents
	if (!g_bld->ConfirmValidCRS(pProj))
	{
		if (err)
		{
			err->type = vtElevError::CANCELLED;
			err->message = "Cancelled";
		}
		return false;
	}

	if (m_pGrid != NULL)
	{
		if (m_pGrid->GetEarthExtents().IsEmpty())
		{
			// No extents.
			wxString msg = _("File lacks geographic location (extents). Would you like to specify extents?\n Yes - specify extents\n No - use some default values\n");
			int res = wxMessageBox(msg, _("Elevation Import"), wxYES_NO | wxCANCEL);
			if (res == wxYES)
			{
				DRECT ext;
				ext.SetToZero();
				ExtentDlg dlg(NULL, -1, _("Elevation Grid Extents"));
				dlg.SetArea(ext, (pProj->IsGeographic() != 0));
				if (dlg.ShowModal() == wxID_OK)
					m_pGrid->SetEarthExtents(dlg.m_area);
				else
					return false;
			}
			if (res == wxNO)
			{
				// Just make up some fake extents, assuming a regular even grid
				int xsize, ysize;
				m_pGrid->GetDimensions(xsize, ysize);

				DRECT ext;
				ext.left = ext.bottom = 0;
				if (pProj->IsGeographic())
				{
					ext.right = xsize * (1.0/3600);	// arc second
					ext.top = ysize * (1.0/3600);
				}
				else
				{
					ext.right = xsize * 10;	// 10 linear units (meters, feet..)
					ext.top = ysize * 10;
				}
				m_pGrid->SetEarthExtents(ext);
			}
			if (res == wxCANCEL)
			{
				if (err)
				{
					err->type = vtElevError::CANCELLED;
					err->message = "Cancelled";
				}
				return false;
			}
		}
		m_pGrid->SetupLocalCS(1.0f);
	}
	return true;
}
Example #7
0
bool vtElevLayer::WriteElevationTileset(TilingOptions &opts, BuilderView *pView)
{
	// Avoid trouble with '.' and ',' in Europe
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	// Check that options are valid
	CheckCompressionMethod(opts);

	// grid size
	int base_tilesize = opts.lod0size;

	int gridcols, gridrows;
	m_pGrid->GetDimensions(gridcols, gridrows);

	DRECT area = m_pGrid->GetEarthExtents();
	DPoint2 tile_dim(area.Width()/opts.cols, area.Height()/opts.rows);
	DPoint2 cell_size = tile_dim / base_tilesize;

	const vtProjection &proj = m_pGrid->GetProjection();
	vtString units = GetLinearUnitName(proj.GetUnits());
	units.MakeLower();
	int zone = proj.GetUTMZone();
	vtString crs;
	if (proj.IsGeographic())
		crs = "LL";
	else if (zone != 0)
		crs = "UTM";
	else
		crs = "Other";

	// Try to create directory to hold the tiles
	vtString dirname = opts.fname;
	RemoveFileExtensions(dirname);
	if (!vtCreateDir(dirname))
		return false;

	// We won't know the exact height extents until the tiles have generated,
	//  so gather extents as we produce the tiles and write the INI later.
	float minheight = 1E9, maxheight = -1E9;

	ColorMap cmap;
	vtElevLayer::SetupDefaultColors(cmap);	// defaults
	vtString dirname_image = opts.fname_images;
	RemoveFileExtensions(dirname_image);
	if (opts.bCreateDerivedImages)
	{
		if (!vtCreateDir(dirname_image))
			return false;

		vtString cmap_fname = opts.draw.m_strColorMapFile;
		vtString cmap_path = FindFileOnPaths(vtGetDataPath(), "GeoTypical/" + cmap_fname);
		if (cmap_path == "")
			DisplayAndLog("Couldn't find color map.");
		else
		{
			if (!cmap.Load(cmap_path))
				DisplayAndLog("Couldn't load color map.");
		}
	}

	ImageGLCanvas *pCanvas = NULL;
#if USE_OPENGL
	wxFrame *frame = new wxFrame;
	if (opts.bCreateDerivedImages && opts.bUseTextureCompression && opts.eCompressionType == TC_OPENGL)
	{
		frame->Create(g_bld->m_pParentWindow, -1, _T("Texture Compression OpenGL Context"),
			wxPoint(100,400), wxSize(280, 300), wxCAPTION | wxCLIP_CHILDREN);
		pCanvas = new ImageGLCanvas(frame);
	}
#endif

	// make a note of which lods exist
	LODMap lod_existence_map(opts.cols, opts.rows);

	bool bFloat = m_pGrid->IsFloatMode();
	bool bJPEG = (opts.bUseTextureCompression && opts.eCompressionType == TC_JPEG);

	int i, j, lod;
	int total = opts.rows * opts.cols, done = 0;
	for (j = 0; j < opts.rows; j++)
	{
		for (i = 0; i < opts.cols; i++)
		{
			// We might want to skip certain tiles
			if (opts.iMinRow != -1 &&
				(i < opts.iMinCol || i > opts.iMaxCol ||
				 j < opts.iMinRow || j > opts.iMaxRow))
				continue;

			DRECT tile_area;
			tile_area.left = area.left + tile_dim.x * i;
			tile_area.right = area.left + tile_dim.x * (i+1);
			tile_area.bottom = area.bottom + tile_dim.y * j;
			tile_area.top = area.bottom + tile_dim.y * (j+1);

			int col = i;
			int row = opts.rows-1-j;

			// draw our progress in the main view
			if (pView)
				pView->ShowGridMarks(area, opts.cols, opts.rows, col, opts.rows-1-row);

			// Extract the highest LOD we need
			vtElevationGrid base_lod(tile_area, IPoint2(base_tilesize+1, base_tilesize+1),
				bFloat, proj);

			bool bAllInvalid = true;
			bool bAllZero = true;
			int iNumInvalid = 0;
			DPoint2 p;
			int x, y;
			for (y = base_tilesize; y >= 0; y--)
			{
				p.y = area.bottom + (j*tile_dim.y) + ((double)y / base_tilesize * tile_dim.y);
				for (x = 0; x <= base_tilesize; x++)
				{
					p.x = area.left + (i*tile_dim.x) + ((double)x / base_tilesize * tile_dim.x);

					float fvalue = m_pGrid->GetFilteredValue(p);
					base_lod.SetFValue(x, y, fvalue);

					if (fvalue == INVALID_ELEVATION)
						iNumInvalid++;
					else
					{
						bAllInvalid = false;

						// Gather height extents
						if (fvalue < minheight)
							minheight = fvalue;
						if (fvalue > maxheight)
							maxheight = fvalue;
					}
					if (fvalue != 0)
						bAllZero = false;
				}
			}
			// Increment whether we omit or not
			done++;

			// If there is no real data there, omit this tile
			if (bAllInvalid)
				continue;

			// Omit all-zero tiles (flat sea-level) if desired
			if (opts.bOmitFlatTiles && bAllZero)
				continue;

			// Now we know this tile will be included, so note the LODs present
			int base_tile_exponent = vt_log2(base_tilesize);
			lod_existence_map.set(i, j, base_tile_exponent, base_tile_exponent-(opts.numlods-1));

			if (iNumInvalid > 0)
			{
				UpdateProgressDialog2(done*99/total, 0, _("Filling gaps"));

				bool bGood;
				int method = g_Options.GetValueInt(TAG_GAP_FILL_METHOD);
				if (method == 1)
					bGood = base_lod.FillGaps(NULL, progress_callback_minor);
				else if (method == 2)
					bGood = base_lod.FillGapsSmooth(NULL, progress_callback_minor);
				else if (method == 3)
					bGood = (base_lod.FillGapsByRegionGrowing(2, 5, progress_callback_minor) != -1);
				if (!bGood)
					return false;

				opts.iNoDataFilled += iNumInvalid;
			}

			// Create a matching derived texture tileset
			if (opts.bCreateDerivedImages)
			{
				// Create a matching derived texture tileset
				vtDIB dib;
				base_lod.ComputeHeightExtents();

				if (opts.bImageAlpha)
				{
					dib.Create(IPoint2(base_tilesize, base_tilesize), 32);
					base_lod.ColorDibFromElevation(&dib, &cmap, 4000, RGBAi(0,0,0,0));
				}
				else
				{
					dib.Create(IPoint2(base_tilesize, base_tilesize), 24);
					base_lod.ColorDibFromElevation(&dib, &cmap, 4000, RGBi(255,0,0));
				}

				if (opts.draw.m_bShadingQuick)
					base_lod.ShadeQuick(&dib, SHADING_BIAS, true);
				else if (opts.draw.m_bShadingDot)
				{
					FPoint3 light_dir = LightDirection(opts.draw.m_iCastAngle,
						opts.draw.m_iCastDirection);

					// Don't cast shadows for tileset; they won't cast
					//  correctly from one tile to the next.
					base_lod.ShadeDibFromElevation(&dib, light_dir, 1.0f,
						opts.draw.m_fAmbient, opts.draw.m_fGamma, true);
				}

				for (int k = 0; k < opts.numlods; k++)
				{
					vtString fname = MakeFilenameDB(dirname_image, col, row, k);

					int tilesize = base_tilesize >> k;

					vtMiniDatabuf output_buf;
					output_buf.xsize = tilesize;
					output_buf.ysize = tilesize;
					output_buf.zsize = 1;
					output_buf.tsteps = 1;
					output_buf.SetBounds(proj, tile_area);

					int depth = dib.GetDepth() / 8;
					int iUncompressedSize = tilesize * tilesize * depth;
					uchar *rgb_bytes = (uchar *) malloc(iUncompressedSize);

					uchar *dst = rgb_bytes;
					if (opts.bImageAlpha)
					{
						RGBAi rgba;
						for (int ro = 0; ro < base_tilesize; ro += (1<<k))
							for (int co = 0; co < base_tilesize; co += (1<<k))
							{
								dib.GetPixel32(co, ro, rgba);
								*dst++ = rgba.r;
								*dst++ = rgba.g;
								*dst++ = rgba.b;
								*dst++ = rgba.a;
							}
					}
					else
					{
						RGBi rgb;
						for (int ro = 0; ro < base_tilesize; ro += (1<<k))
							for (int co = 0; co < base_tilesize; co += (1<<k))
							{
								dib.GetPixel24(co, ro, rgb);
								*dst++ = rgb.r;
								*dst++ = rgb.g;
								*dst++ = rgb.b;
							}
					}

					// Write and optionally compress the image
					WriteMiniImage(fname, opts, rgb_bytes, output_buf,
						iUncompressedSize, pCanvas);

					// Free the uncompressed image
					free(rgb_bytes);
				}
			}

			for (lod = 0; lod < opts.numlods; lod++)
			{
				int tilesize = base_tilesize >> lod;

				vtString fname = MakeFilenameDB(dirname, col, row, lod);

				// make a message for the progress dialog
				wxString msg;
				msg.Printf(_("Writing tile '%hs', size %dx%d"),
					(const char *)fname, tilesize, tilesize);
				UpdateProgressDialog2(done*99/total, 0, msg);

				vtMiniDatabuf buf;
				buf.SetBounds(proj, tile_area);
				buf.alloc(tilesize+1, tilesize+1, 1, 1, bFloat ? 2 : 1);
				float *fdata = (float *) buf.data;
				short *sdata = (short *) buf.data;

				DPoint2 p;
				for (int y = base_tilesize; y >= 0; y -= (1<<lod))
				{
					p.y = area.bottom + (j*tile_dim.y) + ((double)y / base_tilesize * tile_dim.y);
					for (int x = 0; x <= base_tilesize; x += (1<<lod))
					{
						p.x = area.left + (i*tile_dim.x) + ((double)x / base_tilesize * tile_dim.x);

						if (bFloat)
						{
							*fdata = base_lod.GetFilteredValue(p);
							fdata++;
						}
						else
						{
							*sdata = (short) base_lod.GetFilteredValue(p);
							sdata++;
						}
					}
				}
				if (buf.savedata(fname) == 0)
				{
					// what should we do if writing a tile fails?
				}
			}
		}
	}
Example #8
0
void ProjectionDlg::OnProjChoice( wxCommandEvent &event )
{
	TransferDataFromWindow();

	// Even lightweight tasks can runs into trouble with the Locale ./, issue.
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	m_proj.SetGeogCSFromDatum(m_iDatum);

	m_eProj = (ProjType) m_iProj;

	if (m_eProj != PT_DYMAX)
		m_proj.SetDymaxion(false);

	switch (m_eProj)
	{
	case PT_GEO:
		// nothing more to do
		break;
	case PT_UTM:
		// To be polite, suggest a UTM zone based roughly on where the user
		//  might have some data.
		m_iZone = GuessZoneFromGeo(m_GeoRefPoint);
		m_proj.SetUTMZone(m_iZone);
		break;
	case PT_ALBERS:
		// Put in some default values
		m_proj.SetACEA( 60.0, 68.0, 59.0, -132.5, 500000, 500000 );
		break;
	case PT_HOM:
		// Put in some default values; these are for Alaska Zone 1
		m_proj.SetHOM( 57, -133.66666666666666,
			323.13010236111114, 323.13010236111114,
			0.9999, 5000000, -5000000 );
		break;
	case PT_KROVAK:
		// Put in some default values
		m_proj.SetKrovak(49.5, 24.83333333333333,
			30.28813975277778, 78.5, 0.9999, 0, 0);
		break;
	case PT_LAEA:
		// Put in some default values
		m_proj.SetLAEA( 51, -150, 1000000, 0 );
		break;
	case PT_LCC:
		// Put in some default values
		m_proj.SetLCC( 10, 20, 0, 15, 0, 0 );
		break;
	case PT_LCC1SP:
		// Put in some default values
		m_proj.SetLCC1SP( 30, 10, 1.0, 0, 0 );
		break;
	case PT_NZMG:
		// Put in some default values
		m_proj.SetNZMG( 41, 173, 2510000, 6023150 );
		break;
	case PT_MERC:
		// Put in some default values
		m_proj.SetMercator(0.0, 0.0, 1.0, 0, 0);
		break;
	case PT_TM:
		// Put in some default values
		// These are for the OSGB projection, a common case
		m_proj.SetTM(49.0, -2.0, 0.999601272, 400000, -100000);
		break;
	case PT_SINUS:
		// Put in some default values
		m_proj.SetSinusoidal(0, 0, 0); // dfCenterLong, dfFalseEasting, dfFalseNorthing
		break;
	case PT_STEREO:
		// Put in some default values
		m_proj.SetStereographic( 0.0, 0.0, 1.0, 0.0, 0.0);
		break;
	case PT_OS:
		// Put in some default values
		// These are for Stereo70 (Romania)
		m_proj.SetOS(45.0, 25.0, 0.999750,500000, 500000);
		break;
	case PT_PS:
		// Put in some default values
		// These are for the IBCAO polar bathymetry
		m_proj.SetPS(90.0, 0.0, 1.0, 0.0, 0.0);
		break;
	case PT_DYMAX:
		m_proj.SetDymaxion(true);
		break;
	}

	SetProjectionUI( (ProjType) m_iProj );
}
Example #9
0
void MapServerDlg::UpdateURL()
{
	if (m_iServer == -1)
		return;

	// Avoid problem with european decimal punctuation; the BBOX string in
	//  particular must have coords formatted as X.Y not X,Y
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

	OGCServer &server = m_pServers->at(m_iServer);
	vtString url = server.m_url;

	int has_qmark = (url.Find("?") != -1);

	if (has_qmark)
		url += "&REQUEST=GetMap";
	else
		url += "?REQUEST=GetMap";

	// Some servers seem to insist on a VERSION element
	url += "&VERSION=1.1.0";

	// some severs need the following to clarify we want WMS
	url += "&SERVICE=WMS";

	url += "&LAYERS=";  // required, even if left blank
	if (m_iLayer != -1)
	{
		vtTagArray *layer = server.m_layers.at(m_iLayer);
		vtString layername = layer->GetValueString("Name");
		url += layername;

		url += "&STYLES=";  // required, even if left blank
		if (m_iStyle != -1)
		{
			// TODO
		}
	}
	int epsg = m_proj.GuessEPSGCode();
	if (epsg == -1)
		epsg = 4326;		// 4326 = WGS84
	vtString str;
	str.Format("&SRS=EPSG:%d", epsg);
	url += str;

	str.Format("&BBOX=%lf,%lf,%lf,%lf", m_area.left, m_area.bottom, m_area.right, m_area.top);
	url += str;

	str.Format("&WIDTH=%d&HEIGHT=%d", m_iXSize, m_iYSize);
	url += str;
	if (m_iFormat == 0) url += "&FORMAT=image/jpeg";
	if (m_iFormat == 1) url += "&FORMAT=image/png";
	if (m_iFormat == 2) url += "&FORMAT=image/geotiff";

	url += "&TRANSPARENT=TRUE&EXCEPTIONS=WMS_XML&";

	m_strQueryURL = wxString(url, wxConvUTF8);

	m_bSetting = true;
	TransferDataToWindow();
	m_bSetting = false;
}
Example #10
0
/**
 * Extract data from a SHP/DBF file and intepret it as a vegetation layer.
 * This produces a single-valued polygonal coverage.
 *
 * 'iField' is the index of the field from which to pull the single value.
 * 'datatype' is either 0, 1, or 2 for whether the indicated field should be
 *		intepreted as a density value (double), the name of a biotype
 *		(string), or the ID of a biotype (int).
 */
bool vtVegLayer::AddElementsFromSHP_Polys(const wxString &filename,
										  const vtProjection &proj,
										  int iField, VegImportFieldType datatype)
{
	// When working with float field data, must use C locale
	ScopedLocale normal_numbers(LC_NUMERIC, "C");

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

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

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

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

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

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

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

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

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

	SetProjection(proj);

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

	// Read fields
	int biotype_id;
	for (uint i = 0; i < (uint) nElem; i++)
	{
		int record = m_pSet->AddRecord();
		// Read DBF Attributes per poly
		if (datatype == VIFT_Density)
		{
			// density
			m_pSet->SetValue(record, m_field_density, (float) DBFReadDoubleAttribute(db, i, iField));
		}
		if (datatype == VIFT_BiotypeName)
		{
			const char *str = DBFReadStringAttribute(db, i, iField);
			biotype_id = g_bld->GetBioRegion()->FindBiotypeIdByName(str);
			m_pSet->SetValue(record, m_field_biotype, biotype_id);
		}
		if (datatype == VIFT_BiotypeID)
		{
			biotype_id = DBFReadIntegerAttribute(db, i, iField);
			m_pSet->SetValue(record, m_field_biotype, biotype_id);
		}
	}
	DBFClose(db);
	return true;
}
Example #11
0
/**
 * Write footprints to a Canoma file.
 * Author of this code: BobMaX (Roberto Angeletti)
 */
bool vtStructureArray::WriteFootprintsToCanoma3DV(const char* filename, const DRECT *area,
												  const vtHeightField *pHF)
{
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	FILE *fp3DV;
	double x1, y1, x2, y2;
	double minX, minY, maxX, maxY;
	double centerX, centerY, centerZ;
	double deltaX, deltaY;
	double alpha, beta, gamma, focale;
	double CX, CY, EX, EY, EZ;
	double numPixelX, numPixelY, PixelRapp;
	int groupName =1, numero =-1;
	int iii;
	float fElev;

	const float SCALE = 1.0f;
	const float IMAGEFIXEDY = 800.0f;

	VTLOG1("WriteFootprintsToCanoma3DV\n");

	fp3DV = vtFileOpen(filename, "wt");
	if (fp3DV == NULL) {
		VTLOG(" couldn't open file.\n");
		return false;
	}

	x1 = area->left;
	y1 = area->bottom;
	x2 = area->right;
	y2 = area->top;

	fprintf(fp3DV, "version 1\n");

	uint i, j, count = GetSize(), record = 0;
	for (i = 0; i < count; i++)	//for each coordinate
	{
		vtBuilding *bld = GetAt(i)->GetBuilding();
		if (!bld)
			continue;

		const DLine2 &poly = bld->GetLevel(0)->GetOuterFootprint();
		int total = poly.GetSize() + 1;

		double *dX = new double[total];
		double *dY = new double[total];

		minX =  1E9;
		minY =  1E9;
		maxX = -1E9;
		maxY = -1E9;

		int vert = 0;
		for (j=0; j < poly.GetSize(); j++) //for each vertex
		{
			DPoint2 pt = poly.GetAt(j);

			if (pHF != NULL)
				pHF->FindAltitudeOnEarth(pt, fElev);
			else
				fElev = 0.00;

			if (pt.x < minX){minX = pt.x;}
			if (pt.y < minY){minY = pt.y;}
			if (pt.x > maxX){maxX = pt.x;}
			if (pt.y > maxY){maxY = pt.y;}

			dX[vert] = pt.x;
			dY[vert] = pt.y;
			vert++;
		}
		// duplicate first vertex, it's just what SHP files do.
		DPoint2 pt = poly.GetAt(0);
		dX[vert] = pt.x;
		dY[vert] = pt.y;
		vert++;

		//	float h = bld->GetHeight();
		float h = bld->GetTotalHeight();

		double Hight = h;

		//    WriteTranslationSweep();  quello che segue
		centerX = (maxX + minX)/2.;
		centerY = (maxY + minY)/2.;
		centerZ = 0.00;

		//VTLOG("EXPORTTOCANOMA center %lf %lf\n", centerX, centerY);
		numero++;

		if (centerX > x1 &&
			centerY > y1 &&
			centerX < x2 &&
			centerY < y2 )
		{
			//    	VTLOG("EXPORTTOCANOMA building contained\n");
			fprintf(fp3DV, "translationsweep TSW_%d 2 %d { \n",  numero, vert-1);
			fprintf(fp3DV, "	state { \n");
			fprintf(fp3DV, "		alpha { 0.00000 f } \n");
			fprintf(fp3DV, "		beta { 0.00000 f } \n");
			fprintf(fp3DV, "		gamma { 0.00000 f } \n");
			fprintf(fp3DV, "		X0 { %lf f } \n", (centerX - x1) / SCALE);
			fprintf(fp3DV, "		Y0 { %lf f } \n", (centerY - y1) / SCALE);
			fprintf(fp3DV, "		Z0 { %lf f } \n", fElev / SCALE);
			fprintf(fp3DV, "		majorAxis { %lf f }\n", Hight /SCALE);

			for (iii = 0; iii < vert-1; iii++)
			{
				fprintf(fp3DV, "		u%d { %lf f }\n", iii, (centerX - dX[iii]  ) / SCALE );
				fprintf(fp3DV, "		v%d { %lf f }\n", iii, (dY[iii] - centerY  ) / SCALE );
			}  // End For

			fprintf(fp3DV, "		} \n");
			fprintf(fp3DV, "	} \n");

		} // If CONTAINED

		delete [] dY;
		delete [] dX;

		// Because not every structure may be a building, there may be fewer
		//  records than structures.
		record++;
	}
	deltaX = x2-x1;
	deltaY = y2-y1;

	EX = deltaX/2.; //((x2 - x1) /2.); //+ x1;
	EX = EX / SCALE;
	EY = deltaY/2.; //((y2 - y1) /2.); //+ y1;
	EY = EY / SCALE;
	EZ = 202.020865;

	alpha = -3.14159; //0.000000; // -2.85841;  // 0.000000;
	beta = 0.000000;  // 0.03926;    // 1.110737;
	gamma = -3.14159; // 3.14159;   // 0.000000;
	focale = 60.343804;
	CX = 0.000000;
	CY = 0.000000;

	fprintf(fp3DV, "rectangle Floor {\n");
	fprintf(fp3DV, "	state { \n");
	fprintf(fp3DV, "		alpha { 0.00000 f } \n");
	fprintf(fp3DV, "		beta { 0.00000 f } \n");
	fprintf(fp3DV, "		gamma { 0.00000 f } \n");
	fprintf(fp3DV, "		X0 { %lf f }\n", deltaX/2. /SCALE);
	fprintf(fp3DV, "		Y0 { %lf f }\n", deltaY/2. /SCALE);
	fprintf(fp3DV, "		Z0 { 0.00000 f }\n");
	fprintf(fp3DV, "		L { %lf f }\n",deltaX /SCALE);
	fprintf(fp3DV, "		W { %lf f }\n",deltaY /SCALE);
	fprintf(fp3DV, "		}\n");
	fprintf(fp3DV, "	} \n");

	fprintf(fp3DV, "camera { \n");
	fprintf(fp3DV, "	state { \n");
	fprintf(fp3DV, "		EX { %lf } \n", EX);
	fprintf(fp3DV, "		EY { %lf } \n", EY);
	fprintf(fp3DV, "		EZ { %lf } \n", EZ);
	fprintf(fp3DV, "		alpha { %lf } \n", alpha);
	fprintf(fp3DV, "		beta { %lf } \n", beta);
	fprintf(fp3DV, "		gamma { %lf } \n", gamma);
	fprintf(fp3DV, "		f { %lf } \n", focale);
	fprintf(fp3DV, "		CX { %lf } \n", CX);
	fprintf(fp3DV, "		CY { %lf } \n", CY);
	fprintf(fp3DV, "		} \n");
	fprintf(fp3DV, "	} \n");

	numPixelY = IMAGEFIXEDY;
	PixelRapp = deltaY / numPixelY;
	numPixelX = deltaX / PixelRapp;

	fprintf(fp3DV, "controls {\n");
	fprintf(fp3DV, "	Point Floor 0 0.00000 0.00000 GEImage.jpg ;\n");
	fprintf(fp3DV, "	Point Floor 6 %lf 0.00000 GEImage.jpg ;\n", numPixelX);
	fprintf(fp3DV, "	Point Floor 9 %lf %lf GEImage.jpg ;\n", numPixelX, numPixelY);
	fprintf(fp3DV, "	Point Floor 3 0.00000 %lf GEImage.jpg ;\n", numPixelY);
	fprintf(fp3DV, "	}\n");

	fprintf(fp3DV, "image GEImage.jpg { \n");
	fprintf(fp3DV, "	camera { \n");
	fprintf(fp3DV, "		state { \n");
	fprintf(fp3DV, "			EX { %lf } \n", EX);
	fprintf(fp3DV, "			EY { %lf } \n", EY);
	fprintf(fp3DV, "			EZ { %lf } \n", EZ);
	fprintf(fp3DV, "			alpha { %lf } \n", alpha);
	fprintf(fp3DV, "			beta { %lf } \n", beta);
	fprintf(fp3DV, "			gamma { %lf } \n", gamma);
	fprintf(fp3DV, "			f { %lf } \n", focale);
	fprintf(fp3DV, "			CX { %lf } \n", CX);
	fprintf(fp3DV, "			CY { %lf } \n", CY);
	fprintf(fp3DV, "		      } \n");
	fprintf(fp3DV, "	        } \n");
	fprintf(fp3DV, "	{ %lf %lf } \n", numPixelX, numPixelY);
	fprintf(fp3DV, "	} \n");
	fprintf(fp3DV, "selection GEImage.jpg Floor n \n");
	fprintf(fp3DV, "calibration 1.00000 \n");

	fclose(fp3DV);

	return true;
}
Example #12
0
bool vtStructureArray::ReadXML(const char *pathname, bool progress_callback(int))
{
	// The locale might be set to something European that interprets '.' as ','
	//  and vice versa, which would break our usage of sscanf/atof terribly.
	//  So, push the 'standard' locale, it is restored when it goes out of scope.
	LocaleWrap normal_numbers(LC_NUMERIC, "C");

	// check to see if it's old or new format
	bool bOldFormat = false;
	gzFile fp = vtGZOpen(pathname, "r");
	if (!fp) return false;

	m_strFilename = pathname;

	gzseek(fp, 24, SEEK_SET);
	char buf[10];
	gzread(fp, buf, 10);
	if (!strncmp(buf, "structures", 10))
		bOldFormat = true;
	else
	{
		// RFJ quick hack for extra carriage returns
		gzseek(fp, 26, SEEK_SET);
		gzread(fp, buf, 10);
		if (!strncmp(buf, "structures", 10))
			bOldFormat = true;
	}

	gzclose(fp);

	bool success = false;
	if (bOldFormat)
	{
		StructureVisitor visitor(this);
		try
		{
			readXML(pathname, visitor, progress_callback);
			success = true;
		}
		catch (xh_exception &ex)
		{
			// TODO: would be good to pass back the error message.
			VTLOG("XML Error: ");
			VTLOG(ex.getFormattedMessage().c_str());
			return false;
		}
	}
	else
	{
		StructVisitorGML visitor(this);
		try
		{
			readXML(pathname, visitor, progress_callback);
			success = true;
		}
		catch (xh_exception &ex)
		{
			// TODO: would be good to pass back the error message.
			VTLOG("XML Error: ");
			VTLOG(ex.getFormattedMessage().c_str());
			return false;
		}
	}

	return success;
}