DEV Community

IshaqKassam
IshaqKassam

Posted on

3 2

Drawing a Crescent Moon with OpenGL - GLFW/GLEW C++

This is the 3rd article on OpenGL, drawing 2D objects in OpenGL using c++. If you haven't been following through, here is the first article where we started drawing a circle in OpenGL:

In this article, we are going to draw a Crescent Moon using the concepts of circle. We'll be using 2 Circles, with different fill colors, to give us the Crescent moon effect. Let's look at the code for circle:




void drawCircleFill(float cx, float cy, float r, int num_segments)
{
    float theta = 3.1415926 * 2 / float(num_segments);
    float tangetial_factor = tanf(theta);//calculate the tangential factor 
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    float radial_factor = cosf(theta);//calculate the radial factor 

    float x = r;//we start at angle = 0 

    float y = 0;

    glBegin(GL_POLYGON);
    for (int ii = 0; ii < num_segments; ii++)
    {
        glVertex2f(x + cx, y + cy);//output vertex 

        float tx = -y;
        float ty = x;

        x += tx * tangetial_factor;
        y += ty * tangetial_factor;

        x *= radial_factor;
        y *= radial_factor;
    }
    glEnd();
}


Enter fullscreen mode Exit fullscreen mode

We'll call the method twice, to give us 2 circles, giving them different positions and color, to give us the desired crescent.

Let's call the function in the main() as below:



glColor3f(0.8f, 0.6f, 0.2f);//golden color
drawCircleFill(500, 400, 40, 360);

glColor3f(1.0f, 1.0f, 1.0f); //white
drawCircleFill(525, 410, 40, 360);


Enter fullscreen mode Exit fullscreen mode

Notice how the glColor3f method works. If defined, the method implements the color to all the renders below the line, until reset. So the first Circle drawn takes the golden color, and the second Circle takes the color white. You can change the color of the second Circle to match the background, to attain the desired Crescent figure.

Image description

That's it for this article, see you in the upcoming!

Happy coding!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️