Use recursion to draw a Sierpinski triangle fractal

Started by Theo Gottwald, April 13, 2024, 09:42:46 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Theo Gottwald

Here's an example program that uses recursion to draw a Sierpinski triangle fractal:
' Sierpinski Triangle Fractal
' Oxygen Basic, ConsoleG, OpenGL
' frank bruebach, 12-04-2024

#compact
%filename "sierpinski.exe"
'uses RTL64
% Title "Sierpinski Triangle Fractal"

'% WindowStyle WS_OVERLAPPEDWINDOW
'% Animated
'% ScaleUp
% PlaceCentral
% AnchorCentral

% shaders

uses consoleG

BeginScript

procedure drawTriangle(float x1, float y1, float x2, float y2, float x3, float y3) {
    glBegin(GL_LINE_LOOP);
    glVertex2f(x1, y1);
    glVertex2f(x2, y2);
    glVertex2f(x3, y3);
    glEnd();
}

procedure sierpinski(float x1, float y1, float x2, float y2, float x3, float y3, int level) {
    if (level == 0) {
        return;
    }

    float midX1 = (x1 + x2) / 2.0;
    float midY1 = (y1 + y2) / 2.0;
    float midX2 = (x2 + x3) / 2.0;
    float midY2 = (y2 + y3) / 2.0;
    float midX3 = (x1 + x3) / 2.0;
    float midY3 = (y1 + y3) / 2.0;

    drawTriangle(x1, y1, x2, y2, x3, y3);

    sierpinski(x1, y1, midX1, midY1, midX3, midY3, level-1);
    sierpinski(midX1, midY1, x2, y2, midX2, midY2, level-1);
    sierpinski(midX3, midY3, midX2, midY2, x3, y3, level-1);
}

procedure main() {
    cls();
    shading();

    float x1 = -0.5;
    float y1 = -0.5;
    float x2 = 0.5;
    float y2 = -0.5;
    float x3 = 0.0;
    float y3 = 0.5;
    int level = 5;

    sierpinski(x1, y1, x2, y2, x3, y3, level);

    waitkey();
}

EndScript

In this program, we define a `drawTriangle` procedure that takes six arguments specifying the coordinates of the three vertices of a triangle, and draws the triangle using OpenGL. We also define a `sierpinski` procedure that takes the same six arguments as `drawTriangle`, as well as an additional `level` argument that specifies the level of recursion to use when drawing the Sierpinski triangle.

The `sierpinski` procedure works by first calculating the coordinates of the midpoints of the three sides of the triangle. It then draws the triangle using `drawTriangle`, and recursively calls itself three times to draw smaller triangles inside the original triangle, with each smaller triangle having its vertices at the midpoints of the sides of the original triangle. The recursion continues until the specified `level` is reached.

When you run this program, you should see a Sierpinski triangle fractal with the specified level of recursion. You can experiment with different values of `level` to see how they affect the appearance of the fractal. Note that larger values of `level` will result in a more detailed fractal, but will also take longer to draw.