---
deprecated: true
excerpt_separator: <br/>
category: technology
layout: post
title: 'Project Treewars: Going in Circles'
date: '2011-12-18T09:00:00.000-05:00'
author: Anna Wiggins
tags:
- Programming
- OpenGL
- C++
- TreeWars
- circles
- GLSL
modified_time: '2013-10-22T11:19:51.866-04:00'
blogger_id: tag:blogger.com,1999:blog-4209116010564764361.post-1786093955840700947
blogger_orig_url: http://www.stringofbits.net/2011/12/project-treewars-going-in-circles.html
---

It's been quite a while since I actually worked on TreeWars. Various things have distracted me, including some other programming projects. But I actually made some progress way back in July, before I shelved the project temporarily. So, let's talk about circles.<br/><br/>OpenGL gives us a few different ways to draw things, which I've talked about before. When we were using the fixed-pipeline functions (glBegin(), glEnd(), etc), I could draw a circle the same way I drew it in SDL: draw a bunch of same-sized rectangles, shifting the coordinates around a central point so that they overlap. Do enough of them (using small enough increments), and it makes a very smooth-looking circle. I never did this in OpenGL, but the SDL code looked like this:<br/><br/>[sourcecode language="cpp" gutter="false"]<br/>void DrawUtils::draw_circle_filled(SDL_Surface* dest, Sint16 int_x, Sint16 int_y, Uint16 int_r, Uint32 colour)<br/>{<br/>    float x = static_cast&lt;float&gt; (int_x);<br/>    float y = static_cast&lt;float&gt; (int_y);<br/>    float r = static_cast&lt;float&gt; (int_r);<br/><br/>    SDL_Rect pen;<br/>    float i;<br/><br/>    for (i=0; i &lt; 6.28318531; i += 0.0034906585)<br/>    {<br/>        pen.x = static_cast&lt;int&gt; (x + cos(i) * r);<br/>        pen.y = static_cast&lt;int&gt; (y + sin(i) * r);<br/>        int w = static_cast&lt;int&gt; (x - pen.x);<br/>        int h = static_cast&lt;int&gt; (y - pen.y);<br/><br/>        if (w == 0) pen.w = 1;<br/>        else if (w &lt; 0)<br/>        {<br/>            pen.x = x;<br/>            pen.w = abs(w);<br/>        }<br/>        else pen.w = w;<br/><br/>        if (h == 0) pen.h = 1;<br/>        else if (h &lt; 0)<br/>        {<br/>            pen.y = y;<br/>            pen.h = abs(h);<br/>        }<br/>        else pen.h = h;<br/>        if (pen.x &gt;= dest-&gt;clip_rect.x &amp;&amp;<br/>            pen.y &gt;= dest-&gt;clip_rect.y &amp;&amp;<br/>            pen.x + pen.w &lt;= dest-&gt;clip_rect.w &amp;&amp;<br/>            pen.y + pen.h &lt;= dest-&gt;clip_rect.h)<br/>            SDL_FillRect(dest, &amp;pen,<br/>                         SDL_MapRGBA(dest-&gt;format,<br/>                                     (colour &gt;&gt; 16) &amp; 0xff,<br/>                                     (colour &gt;&gt; 8) &amp; 0xff,<br/>                                     colour &amp; 0xff, 1));<br/>    }<br/>}<br/>[/sourcecode]<br/><br/>I was pretty proud of this code when I wrote it. The magic is at the top of the <code>for</code> loop: from 0 to 2π, it increments a tiny bit and finds a new rectangle that has one vertex at the center of the circle, and the opposing vertex at some point along the circle. It does this 1800 times per circle, which isn't terribly efficient, but it got the job done.<br/><br/>With OpenGL and the shader pipeline, we *could* still do that. We could do the following in a loop, 1800 times:<br/><br/>[sourcecode lang="cpp" gutter="false"]<br/>    GLushort Quad::rect_elements[] = {0, 1, 2, 3};<br/>    GLfloat buffer_data[] = {x1f, y1f, x2f, y1f, x1f, y2f, x2f, y2f};<br/><br/>    GLuint vertex_buffer;<br/>    glGenBuffers(1, &amp;vertex_buffer);<br/>    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);<br/>    glBufferData(GL_ARRAY_BUFFER, sizeof(buffer_data), buffer_data, GL_STATIC_DRAW);<br/><br/>    GLuint element_buffer;<br/>    glGenBuffers(1, &amp;element_buffer);<br/>    glBindBuffer(GL_ELEMENT_BUFFER, element_buffer);<br/>    glBufferData(GL_ELEMENT_BUFFER, sizeof(rect_elements), rect_elements, GL_STATIC_DRAW);<br/><br/>    glUseProgram(program); // the shader program, created earlier<br/>    glUniform4f(shader-&gt;uniforms.colour,<br/>    GLUtils::convert_colour((colour &gt;&gt; 16) &amp; 0xff),<br/>    GLUtils::convert_colour((colour &gt;&gt; 8) &amp; 0xff),<br/>    GLUtils::convert_colour(colour &amp; 0xff), 1.0);<br/><br/>    // Put the vertices in an attribute<br/>    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);<br/>    glVertexAttribPointer(shader-&gt;attributes.position, 2, GL_FLOAT,<br/>                          GL_FALSE, sizeof(GLfloat)*2, (void*)0);<br/>    glEnableVertexAttribArray(shader-&gt;attributes.position);<br/><br/>    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer); <br/>    glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, (void*)0);<br/><br/>    // Clean up the GL state machine <br/>    glDisableVertexAttribArray(shader-&gt;attributes.position);<br/>[/sourcecode]<br/><br/><br/>Now, that's a lot of fairly hairy OpenGL code. In my actual program, that's abstracted out into several function calls within several different classes - a Quad object inherits from Drawable, and uses a GLUtils library to create the vertex and element buffers. The actual render code is in Drawable, but it calls a subclassable sub_render function that helps it know how to draw a rectangle specifically.<br/><br/>But we don't want to call that code 1800 times for a single circle - where it was a bit inefficient in SDL, here we're making 1800 separate calls to the OpenGL hardware system (well, actually more as we copy data into GPU buffers and such, but 1800 <code>glDrawElements()</code> calls). That's 1800 different writes into GPU memory. It's ugly. It'd be a horrible idea.<br/><br/>Luckily, we can draw a circle with a *single* call to <code>glDrawElements()</code>. The secret is in 'GL_TRIANGLE_STRIP'. OpenGL defines several different methods it can use to interpret the vertex data we send to it. In 'Triangle Strip', it uses the first three vertexes to draw a triangle. The next vertex you add creates a triangle from it and the previous two vertexes (the last two of the previous triangle). If you 6 vertices in your vertex buffer, and the element buffer was just 0-5, it might look something like this:<br/><br/><a href="http://stringofbits.files.wordpress.com/2012/12/gl_triangle_strip.png"><img src="http://stringofbits.files.wordpress.com/2012/12/gl_triangle_strip.png" alt="Visual explanation of GL_TRIANGLE_STRIP" title="gl_triangle_strip" width="429" height="400" class="alignnone size-full wp-image-666" /></a><br/><br/>We could use THAT to draw a circle too, but it would be cumbersome. Instead, we'll use GL_TRIANGLE_FAN. Like GL_TRIANGLE_STRIP, the first three vertices are used to make a triangle. Subsequent vertices, however, use the previous vertex and the <em>first</em> vertex to form the next triangle. In effect, this gives you a 'center point' and lets you draw triangles outward from it. Its drawing pattern looks like this:<br/><br/><a href="http://stringofbits.files.wordpress.com/2011/12/gl_triangle_fan.png"><img src="http://stringofbits.files.wordpress.com/2011/12/gl_triangle_fan.png" alt="" title="gl_triangle_fan" width="258" height="276" class="alignnone size-full wp-image-675" /></a><br/><br/>This lets us do some really elegant, simple drawing of curved shapes.<br/><br/>Of course, we still need some trigonometry here:<br/><br/>[sourcecode lang="cpp" gutter="false"]<br/>for (unsigned int i = 2; i &lt; 122; i+=2)<br/>{<br/>    unsigned int j = i/2;<br/>    float rad = j * 0.104719755; // 2*Pi / 60<br/>    buffer_data[i] = x + (cos(rad) * rx);<br/>    buffer_data[i+1] = y + (sin(rad) * ry);<br/>    element_data[j] = j;<br/>}<br/>[/sourcecode]<br/><br/><br/>But that logic is much more concise and easy to understand than any of the previous approaches. I've chosen to use 60 points around the circle somewhat arbitrarily - using more of these will the circle look smoother, but cost more in terms of rendering power. Even 1800 points would probably be pretty trivial for the program in its current state, but better to form good optimization habits now, I suppose. Also, the circles look pretty perfectly smooth at 60 points.<br/><br/>And most importantly, it works!<br/><br/><a href="http://stringofbits.files.wordpress.com/2012/12/treewars_circles.png"><img src="http://stringofbits.files.wordpress.com/2012/12/treewars_circles.png" alt="TreeWars in its current state" title="treewars_circles" width="480" height="366" class="alignnone size-full wp-image-665" /></a><br/><br/><br/>Of course, this still doesn't look quite the same (or as good) as the SDL version. I have some positioning issues to work out, and a lot of stuff still isn't implemented that I had there. But I'm definitely on the right track.<br/><br/>Of course, as I said at the top of this post, I've had this project shelved since July. There may be some new updates in the future, but this is probably the last Project TreeWars post for a while.