Skip to content

code readibility improvements and minor fixes #4

@grfrederic

Description

@grfrederic

i stumbled on your project when i was looking for a short code example of a fractal landscape, and while figuring it out i refractored a bit. my changes include:

  • fixing the 45 degree anisotropy
  • changing the plotting library to the more common matplotlib
  • cleaning up some of the cryptic xref/yref computation

if you like the code, feel free to merge it.

import numpy as np
import matplotlib.pyplot as plt
 
levels = 10
size = 2**levels + 1
height = np.zeros((size, size))

for level in range(1, levels + 1):
    step = 2**(levels - level)
    for y in range(0, size, step):
        yjumpover = (1 + y // step) % 2  # are we in a previously visited row?
        for x in range(step * yjumpover, size, step * (1 + yjumpover)):
            xjumpover = (1 + x // step) % 2  # [...] column?
            xref, yref = step * (1 - xjumpover), step * (1 - yjumpover)
            average = height[y-yref:y+yref+1:2*step, x-xref:x+xref+1:2*step].mean()
            variation = 2**(-level) * np.random.uniform(-1, 1)
            height[y, x] = average + variation

xg, yg = np.mgrid[-1:1:1j*size, -1:1:1j*size]

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(xg, yg, height, cmap='gist_earth', linewidth=0, antialiased=False)
ax.set_facecolor('skyblue'), ax.axis('off')
plt.show()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions