Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Barnsley Fern

dave1707dave1707 Mod
edited November 9 in Code Sharing Posts: 7,155

I saw this mentioned in another forum for calculator programming, so I thought I’d convert it and share it here. You can change the p1 thru p4 parameters then press Redraw for a different image. You can also change the number of points to draw to give a better image. It takes about 12 seconds for 500,000 points which is the default starting value. Run this in landscape mode. @Simeon Have you added anything yet to Codea for a fix for supportedOrientations(). For more info, do a google search for Barnsley Fern. I didn’t find an example in the forum, so I thought I’d add it. Slide the parameter panel down to show the Redraw button.

function setup()
    soc=require("socket")
    noSmooth()
    parameter.number("p1",.2,2,1)
    parameter.number("p2",.2,2,1)
    parameter.number("p3",.2,2,1)
    parameter.number("p4",.2,2,1)
    parameter.integer("pointsX1000",100,2000,500)
    parameter.action("Redraw",clrVars)
    backingMode(RETAINED)
    fill(0,255,0)
    clrVars()
end

function clrVars()
    output.clear()
    clr=true
    loop,x,y=0,0,0
    looping=false
    st=soc.gettime()
end

function draw()
    if clr then
        background(0)
        clr=false
    end
    if loop<pointsX1000 then
        loop=loop+1  
        for z=1,1000 do
            local rand=math.random()
            if rand<=0.01 then
                NewX=0
                NewY=.16*p4*y
            elseif rand<=0.08 then
                NewX=.2*p1*x+-.26*p2*y
                NewY=.23*p3*x+.22*p4*y+1.6
            elseif rand<=0.15 then
                NewX=-.15*p1*x+.28*p2*y
                NewY=.26*p3*x+.24*p4*y+.44
            elseif rand<=1 then --1
                NewX=.85*p1*x+.04*p2*y
                NewY=-.04*p3*x+.84*p4*y+1.6
            end
            x=NewX
            y=NewY  
            rect(x*100+300,y*75,.5,.5)
        end
    else
        if not looping then
            en=soc.gettime()-st
            print(string.format("%d points in %5.2f seconds",pointsX1000*1000,en))
            looping=true
        end
    end
end
Sign In or Register to comment.