I an trying to write c++ code using openGl to render Sierpinski_gasket. I have defined tow new data types using typedef
, and then i create a pointer to one of those new datatypes:
typedef GLfloat point2[2];
typedef point2 myTriangle[3];
myTriangle *triangle;
I write a function init
that takes three points, then create a new myTriangle
and then assign it to *triangle
void init(point2 p1, point2 p2, point2 p3){
myTriangle t;
t[0][0] = p1[0];
t[0][1] = p1[1];
t[1][0] = p2[0];
t[1][1] = p2[1];
t[2][0] = p3[0];
t[2][1] = p3[1];
triangle = &t;
}
this is my diplay
function:
void display(void){
static point2 p = {1,1};
int i;
//pick a random vertex
i = rand() % 3; //i in the range 0 to 2
p[0] = (p[0] + *triangle[i][0])/2;
p[1] = (p[1] + *triangle[i][1])/2;
cout << p[0] << ' , ' << p[1] << endl;
//display new points
glBegin(GL_POINTS);
glVertex2fv(p);
glEnd();
}
the problem is that the values of *triangle
changes after each call to display
..
Can anyone tell me why and how to fix that ?
the full code is below
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <cstdlib>
#include <iostream>
using namespace std;
typedef GLfloat point2[2];
typedef point2 myTriangle[3];
myTriangle *triangle;
void init(point2 p1, point2 p2, point2 p3);
void display(void);
int main(int argc, char** argv) {
//initialize the GLUT library
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("OpenGL");
//openGL Code
glClearColor(0.0, 1.0, 0.0, 0.0 );
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(-5.0, 15.0, -5, 15.0, -1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
glEnable(GL_POINT_SMOOTH);
glPointSize(5);
//triangle points
point2 p1, p2, p3;
p1[0] = 5.0;
p1[1] = 0.0;
p2[0] = 10.0;
p2[1] = 0.0;
p3[0] = 7.5;
p3[1] = 10.0;
init(p1,p2,p3);
// glBegin(GL_TRIANGLES);
// glVertex2fv(p1);
// glVertex2fv(p2);
// glVertex2fv(p3);
// glEnd();
for(int j=0 ; j< 10000; j++){
display();
}
glFlush();
glutSwapBuffers();
glutMainLoop();
return 0;
}
void init(point2 p1, point2 p2, point2 p3){
myTriangle t;
t[0][0] = p1[0];
t[0][1] = p1[1];
t[1][0] = p2[0];
t[1][1] = p2[1];
t[2][0] = p3[0];
t[2][1] = p3[1];
triangle = &t;
}
void display(void){
static point2 p = {1,1};
int i;
//pick a random vertex
i = rand() % 3; //i in the range 0 to 2
p[0] = (p[0] + *triangle[i][0])/2;
p[1] = (p[1] + *triangle[i][1])/2;
cout << p[0] << ' , ' << p[1] << endl;
//display new points
glBegin(GL_POINTS);
glVertex2fv(p);
glEnd();
}