#!/usr/bin/env python3
"""
Generate a 4096×4096 image of a 2D projection of a Calabi–Yau–like height map,
using each of the 16,777,216 24-bit RGB colors exactly once.
Colors are ordered along a 3D Morton (Z-order) curve through RGB space,
yielding smooth local transitions in color as you traverse the manifold.
"""
import numpy as np
from PIL import Image
# Image dimensions
W, H = 4096, 4096
N = W * H # 16,777,216 pixels
# 1) Build a “height field” sampling a 2D slice of a Calabi–Yau–style function:
u = np.linspace(0, 2*np.pi, W, endpoint=False)
v = np.linspace(0, 2*np.pi, H, endpoint=False)
U, V = np.meshgrid(u, v, indexing='xy')
height = (
np.cos(5*U) * np.cos(5*V) +
0.5 * np.cos(3*U + 2*V) * np.cos(2*U - 4*V) +
0.25 * np.sin(7*U + 3*V)
)
height = (height - height.min()) / (height.max() - height.min())
# 2) Flatten and sort pixels by height:
pixel_order = np.argsort(height.ravel(order='C'))
# 3) Generate all 24-bit colors and compute their Morton Z-order index:
vals = np.arange(N, dtype=np.uint32)
r = (vals >> 16) & 0xFF
g = (vals >> 8) & 0xFF
b = vals & 0xFF
def morton_index(r, g, b):
"""Interleave the 8 bits of each channel into a 24-bit Morton code."""
idx = np.zeros_like(r, dtype=np.uint32)
for bit in range(8):
mask = 1 << bit
idx |= ((r & mask) << (2*bit + 2)) \
| ((g & mask) << (2*bit + 1)) \
| ((b & mask) << (2*bit ))
return idx
morton_codes = morton_index(r, g, b)
color_order = np.argsort(morton_codes)
# 4) Map the Morton-ordered palette onto the height-sorted pixels:
palette = np.stack([r, g, b], axis=1)[color_order]
canvas = np.empty((N, 3), dtype=np.uint8)
canvas[pixel_order] = palette
# 5) Reshape to image and save:
img = canvas.reshape((H, W, 3), order='C')
Image.fromarray(img, mode='RGB').save('calabi_yau_morton_palette.png')
print("Done: calabi_yau_morton_palette.png")