import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from noise import pnoise2
def generate_terrain_height(x, y, scale=1.0, octaves=8, persistence=0.5, lacunarity=2.0):
"""
Generate realistic terrain height using fractal Brownian motion (fBm) based on Perlin noise.
Args:
- x, y: 2D numpy arrays of coordinates (from np.meshgrid).
- scale: Initial frequency scale for the noise (controls overall feature size).
- octaves: Number of noise layers (higher = more detail).
- persistence: Amplitude multiplier per octave (0.5 is typical for natural terrain).
- lacunarity: Frequency multiplier per octave (2.0 is standard).
Returns:
- Normalized height values in [-1, 1].
"""
total = 0.0
amplitude = 1.0
frequency = scale
max_value = 0.0
for _ in range(octaves):
total += amplitude * pnoise2(frequency * x, frequency * y, octaves=1)
max_value += amplitude
amplitude *= persistence
frequency *= lacunarity
return total / max_value
# Parameters for terrain generation
width, height = 256, 256 # Resolution of the heightmap
world_size = 20.0 # World size in "units" (controls macro features)
scale = 0.05 # Base noise scale (tune for feature size)
height_scale = 5.0 # Vertical exaggeration for visualization
# Generate coordinate grid
x = np.linspace(0, world_size, width)
z = np.linspace(0, world_size, height)
X, Z = np.meshgrid(x, z)
# Generate heightmap
print("Generating terrain heightmap...")
H = generate_terrain_height(X, Z, scale=scale, octaves=8, persistence=0.5, lacunarity=2.0)
# Optional: Normalize and shift to positive heights for more realistic terrain (sea level at 0)
H = (H + 1.0) / 2.0 * height_scale # [0, height_scale]
# 3D Surface Plot
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Z, H, cmap='terrain', linewidth=0, antialiased=True, alpha=0.8)
# Customize the plot
ax.set_title('Procedural Terrain using Perlin Noise (fBm)', fontsize=16, fontweight='bold')
ax.set_xlabel('X')
ax.set_ylabel('Z')
ax.set_zlabel('Height')
ax.set_zlim(0, np.max(H) * 1.1)
# Add colorbar
fig.colorbar(surf, shrink=0.5, aspect=5, label='Height')
plt.tight_layout()
plt.show()
# Optional: Save heightmap as grayscale image
from PIL import Image
heightmap_img = Image.fromarray(((H / np.max(H)) * 255).astype(np.uint8), mode='L')
heightmap_img.save('terrain_heightmap.png')
print("Heightmap saved as 'terrain_heightmap.png'")
# Optional: 2D top-down view
fig2, ax2 = plt.subplots(figsize=(10, 8))
im = ax2.imshow(H, cmap='terrain', origin='lower', extent=[0, world_size, 0, world_size])
ax2.set_title('Terrain Heightmap (Top-Down)')
ax2.set_xlabel('X')
ax2.set_ylabel('Z')
fig2.colorbar(im, ax=ax2, label='Height')
plt.tight_layout()
plt.show()
Installation Requirements
Run this before executing the code:
pip install noise numpy matplotlib pillow
How It Works
- Perlin Noise with fBm: Layers multiple octaves of Perlin noise with exponentially decreasing amplitude and increasing frequency to create fractal-like, natural terrain variations (mountains, hills, valleys).
- Realism Tweaks:
persistence=0.5: Ensures higher frequencies contribute less, mimicking natural roughness.
lacunarity=2.0: Doubles frequency each octave for fine details on large features.
- Normalization keeps heights balanced.
terrain colormap simulates real earth tones.
- Customization:
- Increase
octaves for more detail (but slower).
- Adjust
scale for larger/smaller features.
world_size controls the terrain chunk size.
- Outputs: Interactive 3D plot, 2D heightmap view, and PNG heightmap image.
This produces highly realistic procedural terrain suitable for games, simulations, or art! Experiment with parameters for different biomes (e.g., lower persistence for smoother plains).