标签:
glBegin中的参数可以改为绘制点-GL_POINTS,也可以改为绘制线条-GL_LINES。颜色值也可以随机设定。
总体来说,就是设定一个步长,每次随机的在上下左右绘制。当到达边界时,回到初始点。
1 #include <windows.h> 2 #include <gl/glew.h> 3 #include <gl/glut.h> 4 #include <cstdio> 5 #include <cstdlib> 6 #include <cmath> 7 #include <time.h> 8 #define STEP 1 9 #define STEPNUMBER 500000 10 #define COLORSTEP 50 11 12 void Init(void) 13 { 14 glClearColor(0.0, 0.0, 0.0, 0.0); 15 glMatrixMode(GL_PROJECTION); 16 glLoadIdentity(); 17 gluOrtho2D(0.0, 800.0, 0.0, 600.0); 18 19 } 20 21 void lineSegment(void) 22 { 23 glClear(GL_COLOR_BUFFER_BIT); 24 int r; 25 int x = 400, y = 300; 26 float cr = 0, cg = 0, cb = 0; 27 srand(time(NULL)); 28 for (int i = 0; i != STEPNUMBER; ++i) { 29 r = rand()%4; 30 switch (r) { 31 case 0: x = x - STEP; break; 32 case 1: x = x + STEP; break; 33 case 2: y = y - STEP; break; 34 case 3: y = y + STEP; break; 35 default: break; 36 } 37 38 if (i % (2 * COLORSTEP) == 0) ++cr; 39 if (i % (3 * COLORSTEP) == 0) ++cg; 40 if (i % (5 * COLORSTEP) == 0) ++cb; 41 42 if (cg == 100 || cr == 100 || cb == 100) 43 cg = cr = cb = 0; 44 if (x > 0 && x < 800 && y > 0 && y < 600) { 45 glColor3f(cr/100,cg/100,cb/100); 46 glBegin(GL_POINTS); 47 glVertex2i(y, x); 48 glEnd(); 49 } 50 else { 51 x = 400; 52 y = 300; 53 } 54 } 55 glFlush(); 56 } 57 58 int main(int argc, char* argv[]) 59 { 60 glutInit(&argc, argv); 61 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); 62 glutInitWindowPosition(50, 100); 63 glutInitWindowSize(800, 600); 64 glutCreateWindow("An Example OpenGL Program"); 65 Init(); 66 glutDisplayFunc(lineSegment); 67 glutMainLoop(); 68 return 0; 69 }
标签:
原文地址:http://www.cnblogs.com/clairvoyant/p/5554253.html