C++ PROJ.4 Geographic information manipulation - c++

I am trying to include the C++ library PROJ.4 in my C++ project for manipulating map data. So far I have not been able to make any headway.
I am wondering if there is a good samaritan out there with experience integrating PROJ.4 in their projects on Windows. Do you have a step by step knowledge of how to integrate the source code into your project?
The downloaded file has an "src" folder separate from an "include" folder. Their website says to include the header "proj.h" which is located in the "src" folder. I tried that in a Sandbox to no avail.
I am missing the steps to prepare the source code to integrate in my C++ project. If anyone has gone through the steps from the source code and can walk me through it, I would greatly appreciate it.
#include <stdio.h>
#include <C:\PROJ4\src\proj.h>
int main(void) {
PJ_CONTEXT* C;
PJ* P;
PJ* P_for_GIS;
PJ_COORD a, b;
C = proj_context_create();
P = proj_create_crs_to_crs(C,
"EPSG:4326",
"+proj=utm +zone=32 +datum=WGS84", /* or EPSG:32632 */
NULL);
if (0 == P) {
fprintf(stderr, "Oops\n");
return 1;
}
/* This will ensure that the order of coordinates for the input CRS */
/* will be longitude, latitude, whereas EPSG:4326 mandates latitude, */
/* longitude */
P_for_GIS = proj_normalize_for_visualization(C, P);
if (0 == P_for_GIS) {
fprintf(stderr, "Oops\n");
return 1;
}
proj_destroy(P);
P = P_for_GIS;
/* a coordinate union representing Copenhagen: 55d N, 12d E */
/* Given that we have used proj_normalize_for_visualization(), the order of
/* coordinates is longitude, latitude, and values are expressed in degrees. */
a = proj_coord(12, 55, 0, 0);
/* transform to UTM zone 32, then back to geographical */
b = proj_trans(P, PJ_FWD, a);
printf("easting: %.3f, northing: %.3f\n", b.enu.e, b.enu.n);
b = proj_trans(P, PJ_INV, b);
printf("longitude: %g, latitude: %g\n", b.lp.lam, b.lp.phi);
/* Clean up */
proj_destroy(P);
proj_context_destroy(C); /* may be omitted in the single threaded case */
return 0;
}

Related

How to generate Bar Graph using Blackberry 10 Native method

I am trying to generate bar graph using JSON Data which i am getting from Web-services, basically my requirement is to show a "Bar Graph" using "JSON" data.
Basically I am Android Developer and very new to Blackberry 10 Native, so i don't know much about Blackberry, So If any one can guide me regarding generating graph in Blackberry-10.
I have searched a lot in google and every where else where i can, but i didn't come with any conclusion. Still i am searching a solution for it, So basically my "JSON" data is in following format.
{"Ax":"3:41","Ay":"04:41","Bx":"10:47 ","By":"12:47","Cx":"18:30","Cy":"19:30","Az":3,"Bz":2,"Cz":1,"condition":2}
Here "Ax":"3:41","Ay":"04:41" this is parameter is hour of starting and ending work, and at last it calculates the total number of hour like "Az":3,"Bz":2,"Cz":1 and generate graph based on that. So similarly my graph would look something like this
http://postimg.org/image/nb6dnpwax/
Please help me how can i generate graph based on this, some of the link which i have refered to generate graph is
http://elycharts.com/examples
http://g.raphaeljs.com/
How to make charts/graphs (such as line graphs, bar graphs, circle graphs), etc. in C++, Qt, QML, Blackberry 10 Cascades Beta 3 SDK?
http://devblog.blackberry.com/2014/01/conference-app-secrets-part-3-json-vs-xml/
One thing i am clearly mentioning is i want solution using qml and C++ way with Blackberry-10 so please do not suggest any other method like Java and other all.
Thank you in advance for helping me out.
So there is this article on BlackBerry Support Forums. All the basics are there, but I do so much work with runtime generated images I decided to create a class to encapsulate it. As requested here is a simple sample based on one of the Cascades templates. You should also become familiar with the documentation at:
http://qt-project.org/doc/qt-4.8/
https://developer.blackberry.com/native/documentation/cascades/
And the sample files at the BlackBerry GIT Hub.
QML file:
/*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import bb.cascades 1.2
Page {
Container {
layout: DockLayout {
}
Label {
// Localized text with the dynamic translation and locale updates support
text: qsTr("Bar Graph") + Retranslate.onLocaleOrLanguageChanged
textStyle.base: SystemDefaults.TextStyles.BigText
horizontalAlignment: HorizontalAlignment.Center
}
ImageView {
objectName: "barGraph"
verticalAlignment: VerticalAlignment.Center
horizontalAlignment: HorizontalAlignment.Center
}
}
}
Here is the header file:
/*
* DrawableImage.hpp
*
* Created on: Jul 11, 2014
* Author: richard
*/
#ifndef DRAWABLEIMAGE_HPP_
#define DRAWABLEIMAGE_HPP_
#include <bb/ImageData>
#include <QtGui/QImage>
#include <bb/cascades/ImageView>
namespace net
{
namespace test
{
class DrawableImage : public QImage
{
public:
DrawableImage();
DrawableImage(QSize imageSize, QImage::Format format);
virtual ~DrawableImage();
void emitRenderingBegin();
void emitRenderingFinished();
DrawableImage& operator = (const QImage &image) { QImage::operator =(image); return *this; }
QPainter &painter();
public:
void updateToView(bb::cascades::ImageView *imageView);
private:
void deleteBuffer();
QPainter m_painter;
QSize m_sizeInPixels;
unsigned char* m_buffer; // pixel data in PixelBufferData format
};
} /* namespace test */
} /* namespace net */
#endif /* DRAWABLEIMAGE_HPP_ */
And the cpp file:
/*
* DrawableImage.cpp
*
* Created on: Jul 11, 2014
* Author: richard
*/
#include <src/DrawableImage.hpp>
namespace net
{
namespace test
{
DrawableImage::DrawableImage()
: m_painter(), m_sizeInPixels(0,0), m_buffer(NULL)
{
// TODO Auto-generated constructor stub
}
DrawableImage::DrawableImage(QSize imageSize, QImage::Format format)
: QImage(imageSize, format), m_painter(), m_sizeInPixels(0,0), m_buffer(NULL)
{
}
DrawableImage::~DrawableImage() {
// TODO Auto-generated destructor stub
}
/*
void DrawableImage::emitRenderingBegin() {
emit renderingBegin();
}
void DrawableImage::emitRenderingFinished() {
emit renderingFinished();
}
*/
QPainter& DrawableImage::painter() {
if (!m_painter.isActive()) {
m_painter.begin(this);
}
return m_painter;
}
void DrawableImage::deleteBuffer()
{
if (m_buffer != 0)
{
delete [] m_buffer;
m_buffer = 0;
}
}
void DrawableImage::updateToView(bb::cascades::ImageView *imageView) {
if (m_painter.isActive()) {
m_painter.end();
}
Q_ASSERT(imageView != NULL);
QImage swapped = rgbSwapped();
QSize swappedSize = swapped.size();
int w = swappedSize.width();
int h = swappedSize.height();
int numBytes = w * h * 4;
if (swappedSize != m_sizeInPixels)
{
deleteBuffer();
m_sizeInPixels = QSize(w, h);
m_buffer = new uchar[numBytes];
}
// Copy the memory over.
// We'll add defensive code in case rgbSwapped has a different size
const uchar* from = swapped.constBits();
int numFromBytes = swapped.numBytes();
int numToCopy = std::min(numFromBytes, numBytes);
memcpy(m_buffer, from, numToCopy);
if (numToCopy < numBytes)
{
memset(m_buffer + numToCopy, 0x00, numBytes - numToCopy);
}
bb::ImageData imageData = bb::ImageData::fromPixels(m_buffer, bb::PixelFormat::RGBA_Premultiplied,
m_sizeInPixels.width(),
m_sizeInPixels.height(),
m_sizeInPixels.width() * 4);
imageView->setImage(imageData);
}
} /* namespace test */
} /* namespace net */
And here is the applicationui.cpp (applicationui.hpp is not modified):
/*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>
#include <src/DrawableImage.hpp>
using namespace bb::cascades;
using namespace net::test;
ApplicationUI::ApplicationUI() :
QObject()
{
// prepare the localization
m_pTranslator = new QTranslator(this);
m_pLocaleHandler = new LocaleHandler(this);
bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
// This is only available in Debug builds
Q_ASSERT(res);
// Since the variable is not used in the app, this is added to avoid a
// compiler warning
Q_UNUSED(res);
// initial load
onSystemLanguageChanged();
// Create scene document from main.qml asset, the parent is set
// to ensure the document gets destroyed properly at shut down.
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
// Create root object for the UI
AbstractPane *root = qml->createRootObject<AbstractPane>();
/*
* This code exercises the DrawableImage
*/
QSize graphImageSize(700, 700);
DrawableImage graph;
ImageView* graphImageView = root->findChild<ImageView*>("barGraph");
// Initialise graph and fill with transparent black.
graph = QImage(graphImageSize, QImage::Format_ARGB32_Premultiplied);
graph.fill(Qt::black);
// Set the background mode
graph.painter().setBackgroundMode(Qt::TransparentMode);
// Set rendering hints
graph.painter().setRenderHint(QPainter::Antialiasing, true);
for (int i = 0; i < 10; i++) {
int x = i * (graphImageSize.width()/10);
int h = i * (graphImageSize.height()/10) + graphImageSize.height()/20;
int w = graphImageSize.width()/10 - 20;
graph.painter().fillRect( x + 10, graphImageSize.height()-h, w, h, Qt::darkGreen);
}
// Once the image is drawn transfer it to the Cascades ImageView
graph.updateToView(graphImageView);
// Set created root object as the application scene
Application::instance()->setScene(root);
}
void ApplicationUI::onSystemLanguageChanged()
{
QCoreApplication::instance()->removeTranslator(m_pTranslator);
// Initiate, load and install the application translation files.
QString locale_string = QLocale().name();
QString file_name = QString("BarGraph_%1").arg(locale_string);
if (m_pTranslator->load(file_name, "app/native/qm")) {
QCoreApplication::instance()->installTranslator(m_pTranslator);
}
}
You will also need to add a LIBS line to the .pro file:
APP_NAME = BarGraph
CONFIG += qt warn_on cascades10
LIBS += -lbb
include(config.pri)
This is the result:

how to pass data from terminal to a program?

i am using a GPS reciever that will print GPS message contiuously in terminal using a C++ program like this
Latitude:13.3 Longitude:80.25
Latitude:13.4 Longitude:80.27
Latitude:13.5 Longitude:80.28
I want to take this data inside my c++ program (QT Application)
Below is my full program code
void QgsGpsPlotPluginGui::on_buttonBox_accepted()
{
QString myPluginsDir = "usr/lib/qgis/plugins";
QgsProviderRegistry::instance(myPluginsDir);
QgsVectorLayer * mypLayer = new QgsVectorLayer("/home/mit/Documents/Dwl/GIS DataBase/india_placename.shp","GPS","ogr");
QgsSingleSymbolRenderer *mypRenderer = new
QgsSingleSymbolRenderer(mypLayer->geometryType());
QList <QgsMapCanvasLayer> myLayerSet;
mypLayer->setRenderer(mypRenderer);
if (mypLayer->isValid())
{
qDebug("Layer is valid");
}
else
{
qDebug("Layer is NOT valid");
}
// Add the Vector Layer to the Layer Registry
QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);
// Add the Layer to the Layer Set
myLayerSet.append(QgsMapCanvasLayer(mypLayer, TRUE));
QgsMapCanvas * mypMapCanvas = new QgsMapCanvas(0, 0);
mypMapCanvas->setExtent(mypLayer->extent());
mypMapCanvas->enableAntiAliasing(true);
mypMapCanvas->setCanvasColor(QColor(255, 255, 255));
mypMapCanvas->freeze(false);
QgsFeature * mFeature = new QgsFeature();
QgsGeometry * geom = QgsGeometry::fromPoint(*p);
QGis::GeometryType geometryType=QGis::Point;
QgsRubberBand * mrub = new QgsRubberBand (mypMapCanvas,geometryType);
QgsPoint * p = new QgsPoint();
double latitude =13.3;
double longitude = 80.25;
p->setX(latitude);
p->setY(longitude);
mrub->setToGeometry(geom,mypLayer);
mrub->show()
}
In the above code i have manually entered the value for Latitude and Longitude like this,
double latitude =13.3;
double longitude = 80.25;
p->setX(latitude);
p->setY(longitude);
but i need to get these value from terminal.
Both program are written in c++ but they belong to different framework.
I assume that your library doesn't have an API you can use.
Then one fairly straight forward way to integrate them would be to use pipes.
You can quickly do something like
gps_program | qt_program
And now you get the coordinates via stdin.
The more complex way to set it up is using exec and fork. You create pipe objects, then fork and run using exec the gps_programon one of the branches. This you can do entirely in your code without depending on bash or something like it. You still have to parse the data coming from the pipe the same way.
Just create a pipe:
#include <cstdio>
#include <iostream>
#define WWRITER 0
#if WWRITER
int main() {
while (true) {
std::cout << "Latitude:13.3 Longitude:80.25";
}
return 0;
}
#else
int main() {
FILE* fp = popen("Debug/Writer", "r");
if(fp == 0) perror(0);
else {
const std::size_t LatitudeLength = 9;
const std::size_t LongitudeLength = 10;
char latitude_name[LatitudeLength+1];
char longitude_name[LongitudeLength+1];
double latitude;
double longitude;
while(fscanf(fp, "%9s%lf%10s%lf",
latitude_name,
&latitude,
longitude_name,
&longitude) == 4)
{
std::cout << "Values: " << latitude << ", " << longitude << std::endl;
}
pclose(fp);
}
return 0;
}
#endif
Note: The example runs endlessly.
+1 to Sorin's answer, makes this nice and easy passing stdout to stdin :) but assuming you are running in linux / cigwin?
But if you have access to both program codes then a nicer solution is to use UdpSockets (or maybe Tcp, but Udp is simpler) and pass the data between programs in this way... not sure how big/long-term your solution needs to be but if you want to integrate them in a "long-term" and more maintainable way this would be a better approach.

What value should i insert there?

i'm trying to set up a driver or something alike for my keyboard. I'm editing somebody elses code according to instructions but one thing is bothering me.
here's code
/* to add a new device, simply create a new DEVICE() in this list */
/* Fields are: "Name",VendorID,ProductID,Capabilities */
const libg15_devices_t g15_devices[] = {
DEVICE("Logitech G510",0x46d,0xc22d, G15_LCD|G15_KEYS|G15_DEVICE_5BYTE_RETURN|G15_DEVICE_IS_SHARED),
DEVICE("Logitech G15",0x46d,0xc222,G15_LCD|G15_KEYS),
DEVICE("Logitech G11",0x46d,0xc225,G15_KEYS),
DEVICE("Logitech Z-10",0x46d,0x0a07,G15_LCD|G15_KEYS|G15_DEVICE_IS_SHARED),
DEVICE("Logitech G15 v2",0x46d,0xc227,G15_LCD|G15_KEYS|G15_DEVICE_5BYTE_RETURN),
DEVICE("Logitech Gamepanel",0x46d,0xc251,G15_LCD|G15_KEYS|G15_DEVICE_IS_SHARED),
DEVICE(NULL,0,0,0)
};
/* return device capabilities */
int g15DeviceCapabilities() {
if(found_devicetype>-1)
return g15_devices[found_devicetype].caps;
else
return -1;
}
The first DEVICE entry is what i'm aiming for and a part of the code i added. here is where i stop.
int setLEDs(unsigned int leds)
{
int retval = 0;
unsigned char m_led_buf[4] = { 2, 4, 0, 0 };
unsigned char g510_led_buf[2] = {4, 0};
m_led_buf[2] = ~(unsigned char)leds;
if(g15DeviceCapabilities() & G15_DEVICE_G510) {
on G15_DEVICE_G510 it stops. i do not know what value i should be replacing it with.
Here's a pastebin of the entire code if this info is insufficient.
Pastebin Link
Thanks. :)
EDIT: I found out the functions are defined in another file. here they are.
Pastebin Link
So what i really need to do is define G15_DEVICE_G510 somehow in that file.
This is how it was supposed to be done.
#define G15_DEVICE_G510 32
#define G510_STANDARD_KEYBOARD_INTERFACE 0x0
then at a later point in the code
int setG510LEDColor(unsigned char r, unsigned char g, unsigned char b);
i managed to find a file with it from here
then i'd need to edit a line i had to this.
DEVICE("Logitech G510",0x46d,0xc22d, G15_LCD|G15_KEYS|G15_DEVICE_5BYTE_RETURN|G15_DEVICE_IS_SHARED|G15_DEVICE_G510),
the code for it was originally written by a guy who calls himself "multitude"
So thanks multitude :)

NLOpt with windows forms

I am suffering serious problems while trying to use nlopt library (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) in windows forms application. I have created following namespace which runs perfectly in console application.
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
It optimizes simple nonlinear constrained minimization problem. The problem arises when I try to use this namespace in windows form application. I am constantly getting unhandled exception in myfunc which sees "x" as empty pointer for some reason and therefore causes error when trying to access its location. I believe that the problem is somehow caused by the fact that windows forms uses CLR but I dont know if it is solvable or not. I am using visual studio 2008 and the test programs are simple console project (which works fine) and windows forms project (that causes aforementioned errors).
My test code is based on tutorial for C from the provided link. I although tried C++ version which once again works fine in console application but gives debug assertion failed error in windows forms application.
So I guess my questions is : I have working windows forms application and I would like to use NLOpt. Is there a way to make this work ?

Lib svm, how to convert MyModel.mat to MyModel.model

I have a .mat file which could be easily read by matlab, but I need to convert it a C++ readable .model file. is there a way to do it (by hands, or maybe programmatically)?
You could load the data matrix in MATLAB as any regular MAT-file:
load data.mat
then use the MEX function libsvmwrite which comes with the libsvm MATLAB interface, to write it to the so called "sparse" format:
libsvmwrite('data.txt', label_vector, instance_matrix)
If you are talking about trained models not data, a quick search revealed this page (I haven't personally tested it).
EDIT:
Ok, it appears that the code I mentioned needs some tweaking. Below is my modified version. I tested it using the latest libSVM-3.12, with VS2010 as compiler:
svm_savemodel.c
#include "../svm.h"
#include "mex.h"
#include "svm_model_matlab.h"
static void fake_answer(mxArray *plhs[])
{
plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
struct svm_model *model;
char *filename;
const char *error_msg;
int status;
// check input
if(nrhs != 2) {
mexPrintf("Usage: svm_savemodel(model, 'filename');\n");
fake_answer(plhs);
return;
}
if(!mxIsStruct(prhs[0])) {
mexPrintf("model file should be a struct array\n");
fake_answer(plhs);
return;
}
if(!mxIsChar(prhs[1]) || mxGetM(prhs[1])!=1) {
mexPrintf("filename should be given as char(s)\n");
fake_answer(plhs);
return;
}
// convert MATLAB struct to C struct
model = matlab_matrix_to_model(prhs[0], &error_msg);
if(model == NULL) {
mexPrintf("Error: can't read model: %s\n", error_msg);
fake_answer(plhs);
return;
}
// get filename
filename = mxArrayToString(prhs[1]);
// save model to file
status = svm_save_model(filename,model);
if (status != 0) {
mexWarnMsgTxt("Error occured while writing to file.");
}
// destroy model
svm_free_and_destroy_model(&model);
mxFree(filename);
// return status value (0: success, -1: failure)
plhs[0] = mxCreateDoubleScalar(status);
return;
}
Assuming you compiled the above MEX file, here is an example usage:
[labels, data] = libsvmread('./heart_scale');
model = svmtrain(labels, data, '-c 1 -g 0.07');
svm_savemodel(model, 'mymodel.model');
The text file created looks like:
mymodel.model
svm_type c_svc
kernel_type rbf
gamma 0.07
nr_class 2
total_sv 130
rho 0.426412
label 1 -1
nr_sv 63 67
SV
1 1:0.166667 2:1 3:-0.333333 4:-0.433962 5:-0.383562 6:-1 7:-1 8:0.0687023 9:-1 10:-0.903226 11:-1 12:-1 13:1
0.6646947579781318 1:0.125 2:1 3:0.333333 4:-0.320755 5:-0.406393 6:1 7:1 8:0.0839695 9:1 10:-0.806452 12:-0.333333 13:0.5
.
.