I am trying to draw histogram using Bresenham Line drawing algorithm using OpenGL in CodeBlocks. When arguments to drawLine are changed (manually/ hardcoded) the program crashes. The code is not complete and I am just trying to experiment around. Why is the program crashing after certain loop before rendering anything?
I have tried different argument within the drawLine function inside drawHistogram function. Also there seems problem with loop itself. I can't work my head around there. Though the logic seems OK to me, the result is not quite as expected.
#include <iostream>
#include <GL/glut.h>
using namespace std;
void drawLine();
void inputData();
void CoordinateAxes();
void plot(float x, float y);
void drawBar(float );
void drawHistogram();
float x, y, dx, dy, D1, D2, xInc, yInc;
//int frequency[5] = {100, 200, 150, 300, 500} ;
int main(int argc, char** argv)
{
//inputData();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500,500);
glutCreateWindow("DDA Algorithm");
glutDisplayFunc(drawHistogram);
glutMainLoop();
return 0;
}
void drawLine(float x1, float y1, float x2, float y2)
{
glClear(GL_COLOR_BUFFER_BIT);
CoordinateAxes();
glColor3ub(255 ,255,255);
glBegin(GL_POINTS);
dx = x2 - x1;
dy = y2 - y1;
float P[int(dx)];
if (dy >= dx)
{
D1 = dx;
D2 = dy;
xInc = 0;
yInc = 1;
}
else
{
D1 = dy;
D2 = dx;
xInc = 1;
yInc = 0;
}
P[0] = 2*D1 - D2;
x = x1;
y = y1;
//plot(x, y);
//cout << "(" << x << "," << y << ") ";
//cout << D2;
for(int i = 0; i < D2 ; i++)
{
if (P[i] <= 0)
{
plot(x , y);
P[i+1] = P[i] + 2*D1;
x += xInc;
y += yInc;
//cout << "(" << x << "," << y << ")";
}
else
{
plot(x , y );
P[i+1] = P[i] + 2*D1 - 2*D2;
x += 1;
y += 1;
//cout << "(" << x << "," << y << ")";
}
}
glEnd();
glFlush();
}
//void inputData()
//{
// cout << "Enter frequencies of 5 data: ";
//
// for (int i = 0; i < 5; i++)
// {
// cin >> freq[i];
// }
//}
void CoordinateAxes()
{
glColor3ub(0,0,255);
glBegin(GL_LINES);
glVertex2f(0,1);
glVertex2f(0,-1);
glVertex2f(-1,0);
glVertex2f(1,0);
glEnd();
}
void plot(float x, float y)
{
glVertex2f(x/500, y/500);
cout << "(" << x << "," << y << ")";
}
//void drawBar(float freq)
//{
// drawLine(0, 0, 0, freq );
// drawLine(0, freq, 25, freq);
// drawLine(25, freq, 25, 0);
//}
void drawHistogram()
{
drawLine(10, 10, 10, 100 );
}
I expect a straight line to be rendered on OpenGL window.