• Create Account

## Most Optimized way to draw a circle DirectX

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

15 replies to this topic

### #1Muzzy A  Members

Posted 29 May 2012 - 09:35 PM

Hello, I've made a 2D scale model of the solar system, it shows the orbits, which is a circle i draw. There is a circle being drawn for each planet, as I'm adding more features the program is getting extremely laggy sometimes due to all of the circles. I'm looking for a more optimized way to draw circles.

The way I'm doing it now is HIGHLY unoptimized I'm pretty sure, I'm using D3DXLine the circle gets drawn with however many lines i tell it. For planets that are farther away i have to give it a whopping 100 sides (D3DXlines) to draw separately for the circle to not show straight edges.

I KNOW there's a better way to do it than the way I am

void DrawCircle( const Vector2 &Center,float Radius,Color color,unsigned short Sides /*= 30*/ )
{
float Angle = ToRadian(360.0f/Sides);

float Cos = cos(Angle);
float Sin = sin(Angle);

for(unsigned short i = 0;i < Sides;++i)
{
Vector2 rot( Cos*vec.x - Sin*vec.y , Sin*vec.x + Cos*vec.y );
rot += Center;
vec += Center;
DrawLine(vec,rot,color);
vec = rot - Center;
}
}
void DrawLine( const Vector2 &Point1,const Vector2 &Point2,Color &color,unsigned short BorderWidth /*= 1*/ )
{
Vector2 points[2] = { Point1,Point2 };

d3dLine->Begin();

d3dLine->Draw(points,2,color);

d3dLine->End();
}

// Anyone have a better way to draw a circle in Direct X, a 2D simulation of the Solar System should'nt lag like mine does
// As soon as I stop drawing the circles, the program is runs smoothly no lag at all


Edited by Muzzy A, 29 May 2012 - 09:36 PM.

### #2jefferytitan  Members

Posted 29 May 2012 - 11:32 PM

I'm always astonished that the latest platforms on the latest computers still offer opportunities for 286-like performance. ;)

I'm not a D3D expert, but this thread might help:
http://www.gamedev.net/topic/259860-drawing-circle-in-directx/

I'm guessing the speed problem is because you're doing many drawcalls in separate batches, e.g. each line drawn starts with d3dLine->Begin() and ends with d3dLine->End(). The sample code in that forum post uses a D3DPT_LINESTRIP, which is probably a more optimal way to draw a series of lines.

### #3Muzzy A  Members

Posted 30 May 2012 - 12:33 AM

Thanks all look into that when i get home tomorrow, but for now bed. night, thanks!

### #4Olof Hedman  Members

Posted 30 May 2012 - 02:17 AM

Yeah, 100 lines is nothing, batch them up!

Drawing a circle as a bunch of lines is actually nothing strange and standard practice for drawing curves on graphics hardware.

You probably will see a big improvement by just moving the "Begin" and "End" to outside of the loop.
You could even put the Begin and End outside of the loop drawing all your circles.

Next step is building the vertex buffer from all the points in the circle and, as jeffery suggests, send them all in with a single Draw-call.

### #5WiredCat  Members

Posted 30 May 2012 - 04:12 AM

vertex arrays

### #6Muzzy A  Members

Posted 30 May 2012 - 03:53 PM

vertex arrays

ah you reminded me of something

ID3DLine::Draw(); takes a list of vectors, and the 2nd parameter is how many vectors there are in the list. I can make alot of use out of that. Thanks.

Yeah, 100 lines is nothing, batch them up!

Drawing a circle as a bunch of lines is actually nothing strange and standard practice for drawing curves on graphics hardware.

I actually assumed that the way I was doing it was not really a good way to go, Good to know I was in the right direction with it =D. I don't know why I couldn't notice that doing a 'begin()' and 'end()' over and over to draw a circle wasn't good. It's like having a word on the tip of your tongue and you just can't get it lol.

Thanks for the support guys - Muzzy A

### #7HappyCoder  Members

Posted 31 May 2012 - 10:59 PM

One thing you can do to greatly optimize this little piece of code is to create the vertices for a circle beforehand.

make the circle have a radius of 1 with the center at (0,0), then use matrix transformations to move and scale the circle.

#define CircleResolution     100

static Vector2 gCircleData[CircleResolution];

void InitCircle()
{
for (int i = 0; i < CircleResolution; ++i)
{
gCircleData[i].x = cos(2 * PI * i / CircleResolution);
gCircleData[i].y = sin(2 * PI * i / CircleResolution);
}
}

// then to draw your cirlce
void DrawCircle( const Vector2 &Center,float Radius,Color color)
{
// save word matrix transformation
// set worldtransform = TranslateMatrix(Center) * ScaleMatrix(Radius) * currentWordTransform

d3dLine->Begin();

d3dLine->Draw(gCircleData, CircleResolution,color);

d3dLine->End();

// restore previous world transform

}


By doing it this way you avoid calculating sin/cos all the time which can be expensive. If you want to use lower resolution circles for smaller circles I would have a few premade circles at different resolutions and you choose from those few. Anyway, those are my two cents.

By doing it this way you
My current game project Platform RPG

### #8sjhalayka  Members

Posted 01 June 2012 - 07:10 AM

I haven't used D3D in many years, but last time I used it, I recall that the UP (user pointer to CPU memory... which would often mean a copy from CPU to GPU RAM every time you call DrawPrimitiveUP) functions were inherently not as fast as using a vertex buffer and non-UP functions. I assume that this ID3DXLine::Draw function that takes a user pointer to CPU memory would suffer from the same "problem".

You asked for the most optimal... like ____ hints at, if your circles are static from frame to frame, then stuff them all into a vertex buffer / index buffer pair and go to town (yes, an index buffer does make a difference in performance). This way you only transfer the data across the bus once (and well, once again whenever the device is lost and regained, but you get the idea). That would likely be the most optimal, if you want to get nitpicky. This is all assuming that the latest D3D still has vertex / index buffers.

Edited by taby, 01 June 2012 - 07:14 AM.

### #9Bacterius  Members

Posted 01 June 2012 - 08:18 AM

This is all assuming that the latest D3D still has vertex / index buffers.

It does, and furthermore starting from D3D10, devices can no longer be lost (they can, however, be removed, such as when a laptop switches between two graphics cards or your graphics driver fails, but recovery is easier as you pretty much just go through the whole graphics initialization code again instead of picking specific objects to recreate).

Note that for D3D9 which is being used here, I'm pretty sure a vertex/index buffer solution would be good enough. But it depends on what you use the circles for - perhaps it is, in fact, more efficient to simply render a quad and draw a texture of a circle over it (especially if you are already drawing a texture on top of the circle).

Edited by Bacterius, 01 June 2012 - 08:20 AM.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

### #10sjhalayka  Members

Posted 01 June 2012 - 05:06 PM

Note that for D3D9 which is being used here, I'm pretty sure a vertex/index buffer solution would be good enough. But it depends on what you use the circles for - perhaps it is, in fact, more efficient to simply render a quad and draw a texture of a circle over it (especially if you are already drawing a texture on top of the circle).

Ya know, that's actually pretty brilliant!

### #11Ripiz  Members

Posted 02 June 2012 - 06:28 AM

If you can use shaders you could draw fullscreen quad and specify circle position/radius. With little maths inside shader you could have different colors, position, line width, etc.

### #12apatriarca  Members

Posted 02 June 2012 - 08:44 AM

Why are you using a fullscreen quad (using a constant buffer for the circle positions and orientations?) instead of drawing a quad for each circle (using a geometry shader or point sprites to create it from a single point for example)? What method would you use to render the circles with different line widths? The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math*.

* Well, I would try to solve a quadratic quartic equation, is there any better method?

Edited by apatriarca, 02 June 2012 - 09:59 AM.

### #13Bacterius  Members

Posted 02 June 2012 - 09:08 AM

Why are you using a fullscreen quad (using a constant buffer for the circle positions and orientations?) instead of drawing a quad for each circle (using a geometry shader or point sprites to create it from a single point for example)?

I believe the OP is using D3D9, making geometry shaders a no-go. That said, I was merely referring to the possibility of drawing the circle using a texture overlay instead of actual vertices, the cost could then be negated by the circle already being textured anyway later on. Vertices aren't always the be all end all of rendering geometry.

The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math*. * Well, I would try to solve a quadratic equation, is there any better method?

Off-topic, but ray-tracing a torus is in fact solving a quartic equation (which gets really messy very quickly). You most definitely don't want to use the analytic solution, but there are numerical solutions which are satisfying (if convoluted). A quadratic equation is for a sphere.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

### #14apatriarca  Members

Posted 02 June 2012 - 10:12 AM

Off-topic, but ray-tracing a torus is in fact solving a quartic equation (which gets really messy very quickly). You most definitely don't want to use the analytic solution, but there are numerical solutions which are satisfying (if convoluted). A quadratic equation is for a sphere.

Yes, sure. It was a typo. A quadratic equation is actually very simple math.. For a quartic equation you surely use numerical methods (Ferrari's method is not really well suited for GPUs). I was just curious whether there is a better solution to render a circle with different line widths in a shader...

I believe the OP is using D3D9, making geometry shaders a no-go. That said, I was merely referring to the possibility of drawing the circle using a texture overlay instead of actual vertices, the cost could then be negated by the circle already being textured anyway later on. Vertices aren't always the be all end all of rendering geometry.

I was actually replying to Ripiz. The only problem I see in your method is that it may give "wrong" results at some angles, i.e. when the circle axis is perpendicular to the eye vector. But I would probably use your solution anyway.

Edited by apatriarca, 02 June 2012 - 10:14 AM.

### #15Ripiz  Members

Posted 02 June 2012 - 05:40 PM

What method would you use to render the circles with different line widths? The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math

Lets say vertexes in fullscreen quad contain 2D positions as texture coordinate (4 vertices = 4 different values). In the pixel shader they'll get interpolated giving 2D position at any given pixel. Then in pixel shader you can calculate whatever is needed.

float4 CirclePS(coord : TEXCOORD0) : COLOR0 {
float2 circleCenter = g_Center; // comes from constant buffer
float circleRadius = g_Radius; // comes from constant buffer
float lineWidth = g_Width; // comes from constant buffer
float2 currentPos = coord; // comes from interpolator

float distance = length(currentPos - currentPos); // distance from center to current position in space (2D plane)

if(distance >= circleRadius) // we're not too close
if(distance <= circleRadius + lineWidth) // and not too far
return float4(1, 0, 0, 1); // it's a line!

return float4(0, 0, 0, 0);
}


Edited by Ripiz, 02 June 2012 - 05:40 PM.

### #16apatriarca  Members

Posted 02 June 2012 - 06:45 PM

We are working in 2D!! It looks like I completely misunderstood the problem.. I was thinking about the rendering of circles in 3D and it was the reason I considered ray-tracing a torus. If we are in 2D, it is surely possible to draw circles with any line width in a shader and there is no problem with the texture solution.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.