因为我正在渲染数千个圆圈,所以调整大小和绘图变得非常缓慢
仅使用顶点数组,在具有 10,000 个圆圈的 Intel HD Graphics 3000 上每帧大约需要 60 毫秒:
// g++ -O3 circles.cpp -o circles -lglut -lGL
#include <GL/glut.h>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
// returns a GL_TRIANGLE_FAN-able buffer containing a unit circle
vector< float > glCircle( unsigned int subdivs = 20 )
{
vector< float > buf;
buf.push_back( 0 );
buf.push_back( 0 );
for( unsigned int i = 0; i <= subdivs; ++i )
{
float angle = i * ((2.0f * 3.14159f) / subdivs);
buf.push_back( cos(angle) );
buf.push_back( sin(angle) );
}
return buf;
}
struct Circle
{
Circle()
{
x = ( rand() % 200 ) - 100;
y = ( rand() % 200 ) - 100;
scale = ( rand() % 10 ) + 4;
r = rand() % 255;
g = rand() % 255;
b = rand() % 255;
a = 1;
}
float x, y;
float scale;
unsigned char r, g, b, a;
};
vector< Circle > circles;
vector< float > circleGeom;
void init()
{
srand( 0 );
for( size_t i = 0; i < 10000; ++i )
circles.push_back( Circle() );
circleGeom = glCircle( 100 );
}
void display()
{
int beg = glutGet( GLUT_ELAPSED_TIME );
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
double ar = w / h;
glOrtho( -100 * ar, 100 * ar, -100, 100, -1, 1);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 2, GL_FLOAT, 0, &circleGeom[0] );
for( size_t i = 0; i < circles.size(); ++i )
{
Circle& c = circles[i];
c.scale = ( rand() % 10 ) + 4;
glPushMatrix();
glTranslatef( c.x, c.y, 0 );
glScalef( c.scale, c.scale, 0 );
glColor3ub( c.r, c.g, c.b );
glDrawArrays( GL_TRIANGLE_FAN, 0, circleGeom.size() / 2 );
glPopMatrix();
}
glDisableClientState( GL_VERTEX_ARRAY );
glutSwapBuffers();
int end = glutGet( GLUT_ELAPSED_TIME );
double elapsed = (double)( end - beg );
cout << elapsed << "ms" << endl;
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "Circles" );
init();
glutDisplayFunc( display );
glutTimerFunc(0, timer, 0);
glutMainLoop();
return 0;
}