King's dream fractal with generativepy

Martin McBride, 2021-06-07
Tags kings dream fractal
Categories generativepy generative art
In Generative art

The king's dream fractal works in a similar way to the tinkerbell fractal. It is worth reading the tinkerbell fractal article, and the article on colorising tinkerbell before tackling the king's dream fractal in this article.

Kings dream formula

The fractal equations for king's dream are:

xnext = math.sin(A*x)+B*math.sin(A*y)
ynext = math.sin(C*x)+D*math.sin(C*y)


A = 2.879879
B = -0.765145
C = -0.966918
D = 0.744728

Here is the image it creates:

The code

Here is the full code for the image above:

from generativepy.bitmap import Scaler
from generativepy.nparray import make_nparray_data, save_nparray, load_nparray, make_npcolormap, apply_npcolormap, save_nparray_image
from generativepy.color import Color
import math
import numpy as np

MAX_COUNT = 10000000
A = 2.879879
B = -0.765145
C = -0.966918
D = 0.744728

def paint(image, pixel_width, pixel_height, frame_no, frame_count):
    scaler = Scaler(pixel_width, pixel_height, width=4, startx=-2, starty=-2)

    x = 2
    y = 2
    for i in range(MAX_COUNT):
        x, y = math.sin(A*x)+B*math.sin(A*y), math.sin(C*x)+D*math.sin(C*y)
        px, py = scaler.user_to_device(x, y)
        image[py, px] += 1

def colorise(counts):
    counts = np.reshape(counts, (counts.shape[0], counts.shape[1]))
    power_counts = np.power(counts, 0.25)
    maxcount = np.max(power_counts)
    normalised_counts = (power_counts * 1023 / max(maxcount, 1)).astype(np.uint32)

    colormap = make_npcolormap(1024, [Color('black'), Color('red'), Color('orange'), Color('yellow'), Color('white')])

    outarray = np.zeros((counts.shape[0], counts.shape[1], 3), dtype=np.uint8)
    apply_npcolormap(outarray, normalised_counts, colormap)
    return outarray

data = make_nparray_data(paint, 600, 600, channels=1)

save_nparray("/tmp/temp.dat", data)
data = load_nparray("/tmp/temp.dat")

frame = colorise(data)

save_nparray_image('kings-dream.png', frame)


You can try different values of the constants. A and B need to be in the range -3 tp +3, while C and D need to be in the range -1.5 to +1.5, otherwise the values wil fly off to infinity rather than creating a pattern.

Be aware that most numbers you choose will not create pleasing patterns. You will need to experiment to find something that looks nice, and then do even more fine tuning to get something really nice.

You can also try varying the function. You can replace sin with cos in some or all of the equations. This will give different but similar patterns.

See the fractals article for a list of other fractal examples.

If you found this article useful, you might be interested in the book Computer Graphics in Python or other books by the same author.