• Advertisement
Sign in to follow this  

Most Optimized way to draw a circle DirectX

This topic is 2056 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

[code]
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);

Vector2 vec(Radius,0);

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
[/code] Edited by Muzzy A

Share this post


Link to post
Share on other sites
Advertisement
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:
[url="http://www.gamedev.net/topic/259860-drawing-circle-in-directx/"]http://www.gamedev.net/topic/259860-drawing-circle-in-directx/[/url]

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.

Share this post


Link to post
Share on other sites
Thanks all look into that when i get home tomorrow, but for now bed. night, thanks!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[quote name='___' timestamp='1338372759' post='4944616']
vertex arrays
[/quote]
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.

[quote name='Olof Hedman' timestamp='1338365865' post='4944597']
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.
[/quote]
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

Share this post


Link to post
Share on other sites
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.


[CODE]
#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

}
[/CODE]

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

Share this post


Link to post
Share on other sites
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. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] This is all assuming that the latest D3D still has vertex / index buffers. Edited by taby

Share this post


Link to post
Share on other sites
[quote]This is all assuming that the latest D3D still has vertex / index buffers.[/quote]
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

Share this post


Link to post
Share on other sites
[quote name='Bacterius' timestamp='1338560290' post='4945310']
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).
[/quote]

Ya know, that's actually pretty brilliant!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 [s]quadratic[/s] quartic equation, is there any better method? Edited by apatriarca

Share this post


Link to post
Share on other sites
[quote]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)?[/quote]
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.

[quote]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?[/quote]
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 [url="http://planetmath.org/encyclopedia/quarticformula.html"]analytic solution[/url], but there are numerical solutions which are satisfying (if convoluted). A quadratic equation is for a sphere.

Share this post


Link to post
Share on other sites
[quote name='Bacterius' timestamp='1338649733' post='4945594']
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.
[/quote]
Yes, sure. It was a typo. A quadratic equation is actually very simple math.. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] 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...

[quote name='Bacterius' timestamp='1338649733' post='4945594']
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.
[/quote]
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

Share this post


Link to post
Share on other sites
[quote name='apatriarca' timestamp='1338648247' post='4945587']
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
[/quote]

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.

[CODE]
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);
}
[/CODE] Edited by Ripiz

Share this post


Link to post
Share on other sites
[img]http://public.gamedev.net//public/style_emoticons/default/ohmy.png[/img] 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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement