2
votes

I have a series of 2d vertices that represent the lines used to draw a grid. There are about 900 line segments to draw (the grid uses spring physics to distort, which is why I don't just draw a single line for each row and col). cocos2D has a ccDrawLine function built in, which draws fine, but I think this may be inefficient since it is calling glDrawArrays for each line segment. How do you efficiently draw a large number of line segments? As a bonus, please recommend a source of good 2D drawing practices with openGL.

2

2 Answers

6
votes

Efficient drawing in OpenGL means sending the least information, and fewest batches of information possible. As with everything, it depends on the situation and you should try various things and benchmark for your situation. But as a rule of thumb, the most efficient way (if the vertices are stationary) is to store the vertices on the card once (in a buffer) and render many times, next best (when it makes sense) is to use a geometry shader to generate most vertices on the card, next best is to send all vertices at once, next best is to send batches, and finally the worst is to do one at a time.

900 really isn't very many, and it sounds like a buffer or shader wouldn't make sense in this context.

To send in a batch, you need to put your vertices in sequential memory, such as:

float coords[] = { 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 };

(That's x1, y1, x2, y2, etc. You probably want to malloc some memory so that it can be variable length)

Then you send it to OpenGL and render it:

glVertexPointer( 2, GL_FLOAT, 0, coords ); // 2 = dimensions
glDrawArrays( GL_LINES, 0, 4 ); // 4 = number of points, => 2 lines

GL_LINES will draw a line from 1 to 2, 3 to 4, etc. there are a lot of other options. You can be a bit looser with the memory; take a look at the stride parameter (0 above) if you need to. Here's the documentation:

http://www.opengl.org/sdk/docs/man2/xhtml/glVertexPointer.xml

http://www.opengl.org/sdk/docs/man2/xhtml/glDrawArrays.xml

3
votes

Cocos2d 2.0 has the CCDrawNode which batches drawing of primitives (lines, circles, ..).