Wierd C++ Problems, OpenGL game - c++

Aight so, I'm in the process of making a simple terrain program, not exactly a game, but hey maybe someday. I'll start with describing the basics of how my program works. I'm using an two-dimension array to store the coordinates of the vertexes which make up a grid of triangles. The x and z values are assigned in the follow code:
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
Okay, so the grid array is the one I use for storing the values of all the vertexes in the program, the first argument (the value in the first set of []) is used to choose a point, the second set of [] is the x, y, and z values, the code snippet above only sets values for the x and z coordinates.
The y value, height, is randomised at the start of the program using the following code:
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
And the code for drawing the triangles:
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
The problem I'm having is that I can't make the size of the grid bigger without the program breaking, I would like to be able to change the size of the grid of triangles to whatever I like. when I try to change the for loop which goes through the x values (first code snippet) the program breaks, my movement speed drastically increases, moving the mouse has no effect on the camera rotation. When I do manage to find a set of values to work the grid of triangles is messed up, any points after the 5th row are all set to 0, I'll post the whole program, I don't know if it will run for everyone, but I think the problem is something that requires the whole program to be looked at in order to solve.
I think the problem may be due to variables being shared by different parts of the program, I have looked and looked but can't seem to find any cause. This is my last resort to solving this nightmare of a problem...
main.cpp
/*
*/
#include <iostream>
#include <glut.h>
#include <gl\GL.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include "vector3f.h"
using namespace std;
//Variables
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Terrain";
const float WALKING_SPEED = 5.0;
const float MOUSE_SENSITIVITY = 0.3;
const float MAX_TILT = 90.0;
float grid[200][3];
float LAST_TIME;
float CURRENT_TIME;
float DELTA_TIME;
bool KEY[256];
int a;
int b;
int c;
int t;
int MOUSE_LAST_X;
int MOUSE_LAST_Y;
int MOUSE_CURRENT_X;
int MOUSE_CURRENT_Y;
int MOUSE_DELTA_X;
int MOUSE_DELTA_Y;
float red;
float green;
float blue;
bool fir = true;
//Object
vector3f CAMERA_POSITION;
vector3f CAMERA_ROTATION;
//Functions
void initialize();
void display();
void reshape(int w, int h);
void keyboardDown(unsigned char key, int x, int y);
void keyboardUp(unsigned char key, int x, int y);
void mouseMove(int x, int y);
void movement();
double degreesToRadians(double degrees);
double dsin(double theta);
double dcos(double theta);
double dtan(double theta);
void display() {
//cout << KEY[' '] << endl;
movement();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
//Camera transformations
glRotatef(CAMERA_ROTATION.x, 1, 0, 0);
glRotatef(CAMERA_ROTATION.y, 0, 1, 0);
glRotatef(CAMERA_ROTATION.z, 0, 0, 1);
glTranslatef(-CAMERA_POSITION.x, -CAMERA_POSITION.y, CAMERA_POSITION.z);
//Draw the basic triangle
glBegin(GL_TRIANGLES);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, -1.0, -3.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, -3.0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(10.0, -1.0, -3.0);
glEnd();
/*
1 0,0,0
2 2,0,0
3 4,0,0
4 6,0,0
5 0,0,2
6 2,0,2
7 4,0,2
8 6,0,2
9 0,0,4
10 2,0,4
11 4,0,4
12 6,0,4
13 0,0,6
14 2,0,6
15 4,0,6
16 6,0,6
*/
/*//Option 1 (2 for loops, four if statements)
for (int p = 0; p < 16; p++) {
for (int x = 0; x < 7; x += 2) {
grid[p][0] = x;
}
grid[p][1] = 0;
if (p < 4) {
grid[p][2] = 0;
}
if (p < 8 && p >= 4) {
grid[p][2] = 2;
}
if (p < 12 && p >= 8) {
grid[p][2] = 4;
}
if (p < 16 && p >= 12) {
grid[p][2] = 6;
}
}
*/
//Option 2 (three for loops)
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
//cout << "point 0: " << grid[0][0] << ", " << grid[0][1] << ", " << grid[0][2] << endl;
//cout << "point 1: " << grid[1][0] << ", " << grid[1][1] << ", " << grid[1][2] << endl;
//cout << "point 2: " << grid[2][0] << ", " << grid[2][1] << ", " << grid[2][2] << endl;
//cout << "point 3: " << grid[3][0] << ", " << grid[3][1] << ", " << grid[3][2] << endl;
//cout << "point 4: " << grid[4][0] << ", " << grid[4][1] << ", " << grid[4][2] << endl;
//cout << "point 5: " << grid[5][0] << ", " << grid[5][1] << ", " << grid[5][2] << endl;
//cout << "point 6: " << grid[6][0] << ", " << grid[6][1] << ", " << grid[6][2] << endl;
//cout << "point 7: " << grid[7][0] << ", " << grid[7][1] << ", " << grid[7][2] << endl;
//cout << "point 8: " << grid[8][0] << ", " << grid[8][1] << ", " << grid[8][2] << endl;
//cout << "point 9: " << grid[9][0] << ", " << grid[9][1] << ", " << grid[9][2] << endl;
//cout << "point 10: " << grid[10][0] << ", " << grid[10][1] << ", " << grid[10][2] << endl;
//cout << "point 11: " << grid[11][0] << ", " << grid[11][1] << ", " << grid[11][2] << endl;
//cout << "point 12: " << grid[12][0] << ", " << grid[12][1] << ", " << grid[12][2] << endl;
//cout << "point 13: " << grid[13][0] << ", " << grid[13][1] << ", " << grid[13][2] << endl;
//cout << "point 14: " << grid[14][0] << ", " << grid[14][1] << ", " << grid[14][2] << endl;
//cout << "point 15: " << grid[15][0] << ", " << grid[15][1] << ", " << grid[15][2] << endl;
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
void keyboardDown(unsigned char key, int x, int y) {
KEY[key] = true;
}
void keyboardUp(unsigned char key, int x, int y) {
KEY[key] = false;
}
void movement() {
CURRENT_TIME = ((float)glutGet(GLUT_ELAPSED_TIME) / 1000);
DELTA_TIME = CURRENT_TIME - LAST_TIME;
LAST_TIME = CURRENT_TIME;
MOUSE_DELTA_X = MOUSE_CURRENT_X - MOUSE_LAST_X;
MOUSE_DELTA_Y = MOUSE_CURRENT_Y - MOUSE_LAST_Y;
MOUSE_LAST_X = MOUSE_CURRENT_X;
MOUSE_LAST_Y = MOUSE_CURRENT_Y;
CAMERA_ROTATION.y += (float)MOUSE_DELTA_X * MOUSE_SENSITIVITY;
CAMERA_ROTATION.x += (float)MOUSE_DELTA_Y * MOUSE_SENSITIVITY;
if (CAMERA_ROTATION.x > MAX_TILT) {
CAMERA_ROTATION.x = MAX_TILT;
}
if (CAMERA_ROTATION.x < -MAX_TILT) {
CAMERA_ROTATION.x = -MAX_TILT;
}
if (KEY['w'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x + 180);
}
if (KEY['s'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x);
}
if (KEY['a'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 270);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 270);
}
if (KEY['d'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 90);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 90);
}
if (KEY[' '] == true) {
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME);
}
if (KEY['e'] == true) {
exit(1);
}
}
void mouseMove(int x, int y) {
MOUSE_CURRENT_X = x;
MOUSE_CURRENT_Y = y;
}
double degreesToRadians(double degrees){
return degrees * M_PI / 180;
}
double dsin(double theta) {
return sin(degreesToRadians(theta));
}
double dcos(double theta) {
return cos(degreesToRadians(theta));
}
double dtan(double theta) {
return tan(degreesToRadians(theta));
}
void reshape(int w, int h) {
//Stops the ratio from dividing by 0
if (h == 0) {
h = 1;
}
float fRatio = (float)w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(60, fRatio, 0.1, 1000);
glMatrixMode(GL_MODELVIEW);
}
void initialize() {
glClearColor(0.0, 0.0, 102.0 / 255.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cArgv) {
//Initialise OpenGL and GLUT
glutInit(&iArgc, cArgv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
//Setup window
glutInitWindowPosition(0, 0);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow(WINDOW_TITLE);
//Setup GLUT callback functions
initialize();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(display);
glutKeyboardFunc(keyboardDown);
glutKeyboardUpFunc(keyboardUp);
glutMotionFunc(mouseMove);
glutPassiveMotionFunc(mouseMove);
glEnable(GL_DEPTH_TEST);
//Enter main loop
glutMainLoop();
return 0;
}

Some quick remarks:
your loops access different number of points!
1st loop (r, x) initialize 50 points
2nd loop (h) initialize 64 points
3rd loop (q, dw) access 59 points
glColor3f values should be between 0 and 1 but, using your grid y values, you get 0, 1 or 2
beware of the gimbal lock problem when trying to rotate your view!

Related

Auto Gen Vertices not working?

I am creating a program using opengl to define 4 vertices (creating a box) and then shifting it over and generating a new one effectively creating a larger box of smaller boxes. But when I run it, the vertices go crazy and I reduced it down so you guys can understand what I mean. I want it to be 3 seperate boxes but using wireframe you can clearly tell that it is 2 boxes connected by one.
Here is my code:
#include "stdafx.h"
#include <GL/freeglut.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <GL/glut.h>
using namespace std;
//variables
const float bork = 0.2;
const float blep = -0.2;
float a = 0.2;
float b = -0.2;
float c = 0.2;
float d = -0.2;
float e = 0.2;
float f = -0.2;
float i = 0.2;
float h = 0.2;
float x = 0;
float y = 0;
float z = 0;
float r = 0;
float g = 0;
float u = 0;
float base = 0;
void stopGen() {
cout << "stopped generating" << endl;
}
//Functions for generating he vertices!
void generateVerticesYu() {
glVertex2f(bork, c);
glVertex2f(bork, d);
glVertex2f(blep, c);
glVertex2f(blep, d);
glColor3ub(r, g, u);
}
void generateVerticesXr() {
glVertex2f(e, c);
glVertex2f(e, d);
glVertex2f(f, c);
glVertex2f(f, d);
glColor3ub(r, g, u);
}
void generateVerticesXl() {
glVertex2f(a, c);
glVertex2f(a, d);
glVertex2f(b, c);
glVertex2f(b, d);
glColor3ub(r, g, u);
}
void generateVerticesYd() {
glVertex2f(bork, c);
glVertex2f(bork, d);
glVertex2f(blep, c);
glVertex2f(blep, d);
glColor3ub(r, g, u);
}
//Keybinds for wireframe and camera movement
void special(int key, int, int)
{
const float step = 0.1;
if (GLUT_KEY_LEFT == key)//camera left
x -= step;
if (GLUT_KEY_RIGHT == key)//camera right
x += step;
if (GLUT_KEY_UP == key)//camera up
y += step;
if (GLUT_KEY_DOWN == key)//camera down
y -= step;
if (GLUT_KEY_SHIFT_L == key)//wireframe ON
cout << "Wireframe Enabled" << endl;
/*
if (GLUT_KEY_CTRL_L == key)//wireframe OFF
//glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
glPolygonMode(GL_FRONT, GL_FILL);
cout << "Wireframe Disabled" << endl;
*/
if (GLUT_KEY_END == key)//RED rgb value UP
++r;
cout << "Red:";
cout << r << endl;
if ((GLUT_KEY_END + GLUT_KEY_SHIFT_R) == key)//RED rgb value DOWN
--r;
if (GLUT_KEY_PAGE_UP == key)//GREEN rgb value UP
++g;
if ((GLUT_KEY_PAGE_UP + GLUT_KEY_SHIFT_R) == key)//GREEN rgb value DOWN
--g;
if (GLUT_KEY_PAGE_DOWN == key)//BLUE rgb value UP
++u;
if ((GLUT_KEY_PAGE_DOWN + GLUT_KEY_SHIFT_R) == key)//BLUE rgb value DOWN
--u;
glutPostRedisplay();
}
//renders the vertices
void display()
{
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2, 2, -2, 2, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, z);
//actual rendering starts here
glBegin(GL_TRIANGLE_STRIP);
if (base != 5) {
base += 1;
generateVerticesXl();
a -= 0.4;
cout << "a:";
cout << (a) << endl;
b -= 0.4;
cout << "b:";
cout << (b) << endl;
generateVerticesXr();
e += 0.4;
cout << "e";
cout << (e) << endl;
f += 0.4;
cout << "f";
cout << (f) << endl;
}
/* do {
generateVerticesYd();
c += 0.4;
cout << "c:";
cout << (c) << endl;
d += 0.4;
cout << "d:";
cout << (d) << endl;
generateVerticesYu();
i += 0.4;
cout << "i";
cout << (i) << endl;
h += 0.4;
cout << "h";
cout << (h) << endl;
} while (base != 6);*/
glEnd();
glutSwapBuffers();
}
//main loop for everything!
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow("McDank");
glutSpecialFunc(special);
glutDisplayFunc(display);
//glutIdleFunc();<----TO BE DETERMINED!
glutMainLoop();
return 0;
}
There may be better ways of doing this but this is how I want to do it right now, but im getting this: screenshot
Also, if I press any key, it expands it like it is trying to generate another square: screenshot2

ProjectDepthToCamera returns 0 for all the xyz of pos3d

I am not sure why all the x, y, z values happen to be zero in pos3d in the following code. Please suggest fixes:
/***
Reads the depth data from the sensor and fills in the matrix
***/
void SR300Camera::fillInZCoords()
{
PXCImage::ImageData depthImage;
PXCImage *depthMap = sample->depth;
depthMap->AcquireAccess(PXCImage::ACCESS_READ, &depthImage);
PXCImage::ImageInfo imgInfo = depthMap->QueryInfo();
cout << "inImg->QueryInfo() " << depthImage.format << endl;
PXCPoint3DF32 * pos2d = new PXCPoint3DF32[depth_width*depth_height];
int depth_stride = depthImage.pitches[0] / sizeof(pxcU16);
for (int y = 0, k = 0; y < depth_height; y++) {
for (int x = 0; x < depth_width; x++, k++) {
pos2d[k].x = (pxcF32)x;
pos2d[k].y = (pxcF32)y;
pos2d[k].z = ((short *)depthImage.planes[0])[y* depth_stride + x];
}
}
//Point3DF32 * pos3d = NULL;
PXCPoint3DF32 * pos3d = new Point3DF32[depth_width*depth_height];
PXCPoint3DF32 * vertices = new PXCPoint3DF32[depth_width * depth_height];
Projection * projection = device->CreateProjection();
projection->ProjectDepthToCamera(depth_width*depth_height, pos2d, pos3d);
cout << "x is " << pos3d->x*1000 << endl;
cout << "y is " << pos3d->y*1000 << endl;
cout << "z is " << pos3d->z*1000 << endl;
}
Here's a correct verified answer to get the XYZ Map out of depth image UV-Map:
Status sts = sm ->AcquireFrame(true);
if (sts < STATUS_NO_ERROR) {
if (sts == Status::STATUS_STREAM_CONFIG_CHANGED) {
wprintf_s(L"Stream configuration was changed, re-initilizing\n");
sm ->Close();
}
}
sample = sm->QuerySample();
PXCImage *depthMap = sample->depth;
renderd.RenderFrame(sample->depth);
PXCImage::ImageData depthImage;
depthMap->AcquireAccess(PXCImage::ACCESS_READ, &depthImage);
PXCImage::ImageInfo imgInfo = depthMap->QueryInfo();
int depth_stride = depthImage.pitches[0] / sizeof(pxcU16);
PXCProjection * projection = device->CreateProjection();
pxcU16 *dpixels = (pxcU16*)depthImage.planes[0];
unsigned int dpitch = depthImage.pitches[0] / sizeof(pxcU16);
PXCPoint3DF32 *pos3D = new PXCPoint3DF32[num_pixels];
sts = projection->QueryVertices(depthMap, &pos3D[0]);
if (sts < Status::STATUS_NO_ERROR) {
wprintf_s(L"Projection was unsuccessful! \n");
sm->Close();
}
for (int k = 0; k < num_pixels; k++) {
if (pos3D[k].x != 0) {
cout << " xx is: " << pos3D[k].x << endl;
}
if (pos3D[k].y != 0) {
cout << " yy is: " << pos3D[k].y << endl;
}
if (pos3D[k].z != 0) {
cout << " zz is: " << pos3D[k].z << endl;
}
}

Image processing : luminance weighted 2

I would like to weigh values of luminance on a new image.
I have an image (5px.jpg) of 5 pixels with these luminance :50,100,150,200,250.
I have a vector of coefficient.
I created a new Mat Z which combine luminance of 5px.jpg and the coefficient.
So, my first value of luminance is 50 (lum[0]=50) and I want it to be applied on the 5.1 (coef[0]=5.1) first pixel of my matrix. To do that, I need to weight the 6th pixel with the first and the second value of luminance. In my case,the luminance of my 6th pixel will be 95 because (0.1*50)+(0.9*100)=95
And so on...
But I do not know why my code does not works.
I had already asked a similar question for a vector here and now, I'm try to adapt to an image.
My picture in input :
My output :
#define MPI 3.14159265358979323846264338327950288419716939937510
#define RAD2DEG (180./MPI)
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <cmath>
#include <math.h>
#include <string.h>
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("5px.jpg", 1);
if (image.empty())
{
cout << "Couldn't load " << image << endl;
}
else
{
cout << "Image upload, go" << endl;
}
namedWindow("ImageIn", CV_WINDOW_AUTOSIZE);
imshow("ImageIn", image);
Mat imgGrayScale;
cvtColor(image, imgGrayScale, CV_BGR2GRAY);
float *deltaP = new float[imgGrayScale.cols];
float *angle = new float[imgGrayScale.cols];
float *coeff = new float[imgGrayScale.cols];
int col;
for (col = 0; col < imgGrayScale.cols; ++col)
{
//cout << "position x = " << col << endl;
deltaP[col] = imgGrayScale.at<uchar>(0, col);
//cout << "luminance = " << deltaP[col] << endl;
angle[col] = acos(deltaP[col] / 255);
//cout << "angle =" << angle[col] << endl;
coeff[col] = (1 / cos(angle[col]));
cout << "coeff = " << coeff[col] << endl;
}
int width = imgGrayScale.size().width;
int height = imgGrayScale.size().height;
int width2 = width * 5;
int idx_coef = 0;
Mat Z = Mat::zeros(height, width2, CV_8UC1);
//for (int r = 0; r < imgGrayScale.rows; r++)
//{
//cout << "Saut de ligne " << endl << endl << endl;
for (int t = 0; t < imgGrayScale.cols; t++)
{
//cout << "Saut de colonne " << endl;
// Attribue le coeff à une variable
int c = int(coeff[idx_coef]);
//cout << "x" << t << endl;
for (int i = 0; i < c; ++i)
{
Z.at<uchar>(0, c) = imgGrayScale.at<uchar>(0, t);
}
float alpha = fmod(coeff[idx_coef], 1.f);
float beta = 1.f - alpha;
Z.at<uchar>(0, c + 1) = (alpha * imgGrayScale.at<uchar>(0, t) + beta * imgGrayScale.at<uchar>(0, t + 1));
idx_coef++;
coeff[idx_coef] = coeff[idx_coef] - beta;
if (idx_coef >= width - 1)
{
int cc = int(coeff[idx_coef]);
for (int i = 0; i < cc; ++i)
{
Z.at<uchar>(0, c) = imgGrayScale.at<uchar>(0, t);
}
idx_coef = 0;
break;
}
}
//}
namedWindow("m", CV_WINDOW_AUTOSIZE);
imshow("m", Z);
imwrite("lumianacetest.jpg", Z);
int t = waitKey();
if ((char)t == 27)
return 0;
}
You messed up with the indices while accessing the matrix Z. You shoudn't access Z at column c, but you need access the current column (as a vector::push_back would do). So you can keep the current index column in a variable, here idx_z, and increment it every time you access Z
Here your Z is CV_8U, so you lose accuracy since your values are float. You can create Z as CV_32F, and if you need to store values in CV_8U format to save the image, you can convert to CV_8U later, eventually.
The last columns of Z won't be set to any value (so I initialized them with value 0). If you need them to have the last value as in the imgGrayScale, just decomment the relevant part of the code.
Here the code:
#define MPI 3.14159265358979323846264338327950288419716939937510
#define RAD2DEG (180./MPI)
#include <opencv2\opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
Mat1b imgGrayScale = (Mat1b(2, 5) << 50, 100, 150, 200, 250,
50, 100, 150, 200, 250);
vector<float> deltaP(imgGrayScale.cols);
vector<float> angle(imgGrayScale.cols);
vector<float> coeff(imgGrayScale.cols);
int col;
for (col = 0; col < imgGrayScale.cols; ++col)
{
//cout << "position x = " << col << endl;
deltaP[col] = imgGrayScale.at<uchar>(0, col);
//cout << "luminance = " << deltaP[col] << endl;
angle[col] = acos(deltaP[col] / 255);
//cout << "angle =" << angle[col] << endl;
coeff[col] = (1 / cos(angle[col]));
cout << "coeff = " << coeff[col] << endl;
}
int width = imgGrayScale.size().width;
int height = imgGrayScale.size().height;
int width2 = width * 5;
Mat1f Z(height, width2, 0.f);
for (int r = 0; r < imgGrayScale.rows; r++)
{
int idx_lum = 0;
int idx_coef = 0;
int idx_z = 0;
vector<float> coef = coeff;
// Set all values in Z to the last value in imgGrayScale
Z.row(r) = imgGrayScale(r, imgGrayScale.cols-1);
while (true)
{
int c = int(coef[idx_coef]);
for (int i = 0; i < c; ++i)
{
Z(r, idx_z++) = imgGrayScale(r, idx_lum);
}
float alpha = fmod(coef[idx_coef], 1.f);
float beta = 1.f - alpha;
Z(r, idx_z++) = (alpha * imgGrayScale(r, idx_lum) + beta * imgGrayScale(r, idx_lum + 1));
idx_coef++;
idx_lum++;
coef[idx_coef] = coef[idx_coef] - beta;
if (idx_lum >= imgGrayScale.cols - 1 || idx_coef >= coef.size() - 1)
{
int cc = int(coef[idx_coef]);
for (int i = 0; i < cc; ++i)
{
Z(r, idx_z++) = imgGrayScale(r, idx_lum);
}
idx_coef = 0;
break;
}
}
}
Mat1b ZZ;
Z.convertTo(ZZ, CV_8U);
cout << "Float values:" << endl;
cout << Z << endl << endl;
cout << "Uchar values:" << endl;
cout << ZZ << endl << endl;
namedWindow("m", CV_WINDOW_AUTOSIZE);
imshow("m", Z);
imwrite("lumianacetest.png", ZZ);
waitKey();
return 0;
}

How to convert 3D coordinates into 2D screen space

I know stackoverflow has already some questions and answers about this topic but I cannot deal with them for my specific Problem.
Here is my Code:
int main()
{
std::vector <int> v;
double x_screen, y_screen;
double screen_width = 640.0;
double screen_height = 480.0;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
double half_screen_width = screen_width / 2;
double half_screen_height = screen_height / 2;
double window_aspect = screen_width / screen_height;
double x_3D, y_3D, z_3D;
for (int i = 0; i < 3; i++){
v.push_back(i);
++v[i];
}
std::cout << "3D Point:" << std::endl;
for (int j = 0; j < v.size(); j++)
std::cout << v[j] << std::endl;
x_3D = v[0] - viewport[0];
y_3D = v[1] - viewport[1];
z_3D = v[2] - viewport[2];
x_screen = (+(x_3D / z_3D)+half_screen_width)*half_screen_width;
y_screen = (-(y_3D / z_3D)+half_screen_height)*half_screen_height;
if (window_aspect > 1.0)
x_screen = x_screen / window_aspect;
else
y_screen = y_screen*window_aspect;
std::cout << "2D Point :" << std::endl;
std::cout << "[" << x_screen << "," << y_screen << "]" << std::endl;
getchar();
getchar();
return 0;
}
Output:
3D Point : [1,2,3]
2D Point : [77040,57360]
The Tutorial where i got the mathematic Background is here :
http://www.flipcode.com/archives/Plotting_A_3D_Point_On_A_2D_Screen.shtml
Can anyone tell me if this result is logical? I am new on this topic and cannot interpret the result.

How to check if mouseclick is in an area

Ok So I have a few images I am putting on a screen, Really all you would need to know is each glvertex2f() is a point, thus 4 points connected is an area. Each glVertex2f is created by and X,Y . I would like to save this area range so when i do a mouse click and get the x,y result, I can test to see if the mouseclick x,y is inside this area.
So here is where i create the area
for( int z = 0; z < 6; z++ )
{
if( game->player1.Blockbestand[z] > 0 )
{
glLoadIdentity();
xoff = (z/4.0f);
yoff = (floor(xoff))/4.0f;
glBegin(GL_QUADS);
glTexCoord2f(0/4 + xoff,0/4 + yoff); glVertex2f( x1,game->camera.height-y1);
glTexCoord2f(0/4 + xoff,1.0/4 + yoff); glVertex2f( x2,game->camera.height-y1 );
glTexCoord2f(1.0/4 + xoff,1.0/4 + yoff); glVertex2f( x2,game->camera.height-y2 );
glTexCoord2f(1.0/4 + xoff,0/4 + yoff); glVertex2f( x1,game->camera.height-y2 );
glEnd();
x1= x2+10;
x2 = x1+30;
xoff = (z/4.0f);
yoff = (floor(xoff))/4.0f;
}
}
and here is where i get the mouse click
for (std::list<MouseState>::iterator it = clicks->begin(); it != clicks->end(); it++) {
if (it->leftButton == true){
std::cout << "Left click!\n";
std::cout << "x: " << it->x << "\n";
std::cout << "y: " << it->y << "\n";
}
}
So i assume i can save the area in an array somehow. and then when ever a leftbutton click is true , i get the x, y and look in the array to see if its in the area.. but no clue how to do this..
First save the 4 points in an array
locationCheck[m][n] = x1;
locationCheck[m][n+1] = x2;
locationCheck[m][n+2] = game->camera.height-y1;
locationCheck[m][n+3] = game->camera.height-y2;
m++;
then check if the x/y of mouse is between the 4 points like so.
void GameScreen::menuClickCheck(int x,int y){
int m = 0;
int n=0;
while (m < 32){
if (locationCheck[m][n] < x && locationCheck[m][n+1] > x)
if (locationCheck[m][n+2] > y && locationCheck[m][n+3] < y)
{
switch (m)
{
case 0 : cout << "Type=DefaultLand \n";
break;
case 1 : cout << "Type=Lava \n";
break;
case 2 : cout << "Type=Stone \n";
break;
}//end switch
m=32;
}//endif
m++;
}//whileloop
}