plugins/tools/compile-realistic-stone-family.py
unimatrixgit 00147b2908
All checks were successful
DuneRealms Plugin CI / plugins (push) Successful in 13m6s
Give realistic stone families distinct vanilla colours and darken cobblestone
2026-12-04 00:37:54 +01:00

243 lines
11 KiB
Python

"""Compile supplied stone albedos into one repeatable vanilla material family."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageOps
SIZE = 256
EDGE = 12
TEXTURES = Path("assets/minecraft/textures/block")
CORE = ("stone", "cobblestone", "andesite", "granite", "diorite", "tuff", "deepslate")
OPTIONAL = ("calcite", "dripstone_block", "blackstone", "basalt", "sandstone", "red_sandstone",
"netherrack", "end_stone", "obsidian", "bedrock", "gravel")
MINERALS = ("coal", "copper", "diamond", "emerald", "gold", "iron", "lapis", "redstone")
VARIANTS = {
"stone": {
"smooth_stone": "polished",
"smooth_stone_slab_side": "slab",
"stone_bricks": "bricks",
"mossy_stone_bricks": "mossy_bricks",
"cracked_stone_bricks": "cracked_bricks",
"chiseled_stone_bricks": "chiseled",
},
"cobblestone": {"mossy_cobblestone": "moss"},
"andesite": {"polished_andesite": "polished"},
"granite": {"polished_granite": "polished"},
"diorite": {"polished_diorite": "polished"},
"tuff": {
"polished_tuff": "polished", "tuff_bricks": "bricks",
"chiseled_tuff": "chiseled", "chiseled_tuff_top": "polished",
"chiseled_tuff_bricks": "chiseled", "chiseled_tuff_bricks_top": "polished",
},
"deepslate": {
"deepslate_top": "top", "cobbled_deepslate": "rubble",
"polished_deepslate": "polished", "deepslate_bricks": "bricks",
"cracked_deepslate_bricks": "cracked_bricks", "deepslate_tiles": "tiles",
"cracked_deepslate_tiles": "cracked_tiles", "chiseled_deepslate": "chiseled",
},
"blackstone": {
"blackstone_top": "top", "polished_blackstone": "polished",
"polished_blackstone_bricks": "bricks", "cracked_polished_blackstone_bricks": "cracked_bricks",
"chiseled_polished_blackstone": "chiseled",
},
"basalt": {
"basalt_side": "plain", "basalt_top": "top", "polished_basalt_side": "polished",
"polished_basalt_top": "polished_top", "smooth_basalt": "polished",
},
"sandstone": {
"sandstone_top": "top", "sandstone_bottom": "bottom",
"cut_sandstone": "cut", "chiseled_sandstone": "chiseled",
},
"red_sandstone": {
"red_sandstone_top": "top", "red_sandstone_bottom": "bottom",
"cut_red_sandstone": "cut", "chiseled_red_sandstone": "chiseled",
},
"end_stone": {"end_stone_bricks": "bricks"},
}
def sha(data):
return hashlib.sha256(data).hexdigest()
def seamless(image):
pixels = np.asarray(image, dtype=np.float32).copy()
for axis in (0, 1):
strips = np.moveaxis(pixels, axis, 0)
for offset in range(EDGE):
weight = 0.5 * (1.0 + np.cos(np.pi * offset / (EDGE - 1)))
near = strips[offset].copy()
far = strips[-offset - 1].copy()
change = (far - near) * weight / 2
strips[offset] = near + change
strips[-offset - 1] = far - change
return Image.fromarray(np.rint(pixels).astype(np.uint8))
def source_tile(path, mode):
with Image.open(path) as image:
if min(image.size) < SIZE:
raise ValueError(f"{path.name} must be at least {SIZE} pixels on each side")
if mode == "RGBA":
layer = image.convert("RGBA")
minimum, maximum = layer.getchannel("A").getextrema()
if minimum != 0 or maximum < 128:
raise ValueError(f"{path.name} requires a transparent background and visible deposits")
return ImageOps.pad(layer, (SIZE, SIZE), method=Image.Resampling.LANCZOS, color=(0, 0, 0, 0))
if image.width != image.height:
raise ValueError(f"{path.name} must be a square albedo")
return image.convert("RGB").resize((SIZE, SIZE), Image.Resampling.LANCZOS)
def masonry(image, columns, rows, stagger):
y, x = np.indices((SIZE, SIZE))
width, height = SIZE // columns, SIZE // rows
u, v = (x + (y // height % 2) * (width // 2 if stagger else 0)) % width, y % height
lit = ((u == 2) | (v == 2)) * 0.12
mortar = (u < 2) | (v < 2)
shadow = (u >= width - 2) | (v >= height - 2)
face = 1 + lit - mortar * 0.41 - shadow * 0.17
return Image.fromarray(np.uint8(np.clip(np.asarray(image) * face[..., None], 0, 255)))
def smooth(image):
return ImageEnhance.Contrast(Image.blend(image, image.filter(ImageFilter.GaussianBlur(2.4)), 0.52)).enhance(0.82)
def moss(image):
random = np.random.default_rng(413)
mask = Image.fromarray(np.uint8(random.integers(0, 256, (16, 16)))).resize(image.size, Image.Resampling.BICUBIC)
alpha = mask.point(lambda n: max(0, min(140, (n - 118) * 2)))
tint = Image.blend(image, Image.new("RGB", image.size, (85, 104, 60)), 0.76)
return Image.composite(tint, image, alpha)
def carved(image, style):
surface = image.convert("RGBA")
relief = Image.new("RGBA", image.size)
draw = ImageDraw.Draw(relief)
if style == "chiseled":
draw.rounded_rectangle((41, 41, 214, 214), radius=13, outline=(22, 16, 13, 135), width=7)
draw.rounded_rectangle((48, 48, 207, 207), radius=10, outline=(255, 246, 223, 72), width=4)
draw.line(((128, 79), (176, 128), (128, 177), (79, 128), (128, 79)),
fill=(36, 27, 19, 110), width=6, joint="curve")
else:
draw.line(((74, 37), (69, 58), (88, 82), (80, 105), (108, 121), (124, 151),
(148, 157), (143, 180)), fill=(28, 22, 18, 139), width=3, joint="curve")
draw.line(((89, 84), (113, 80), (132, 93), (151, 87)), fill=(36, 27, 18, 97), width=2)
return Image.alpha_composite(surface, relief).convert("RGB")
def derive(tile, style):
if style == "plain":
return tile
if style == "top":
return tile.transpose(Image.Transpose.ROTATE_90)
if style == "bottom":
return ImageEnhance.Brightness(tile).enhance(0.90)
if style == "polished_top":
return smooth(tile.transpose(Image.Transpose.ROTATE_90))
if style in {"polished", "slab", "cut", "chiseled"}:
polished = smooth(tile)
if style == "polished":
return polished
if style == "chiseled":
return carved(polished, style)
return masonry(polished, 1, 2 if style == "slab" else 1, False)
if style == "moss":
return moss(tile)
columns, rows = (4, 4) if style in {"tiles", "cracked_tiles", "rubble"} else (2, 4)
built = masonry(tile, columns, rows, True)
if style.startswith("cracked"):
return carved(built, style)
return moss(built) if style == "mossy_bricks" else built
def compile_tiles(source, complete):
tiles = {}
bases = {}
for family in CORE + OPTIONAL:
path = source / f"{family}-source.png"
if family in OPTIONAL and not complete and not path.is_file():
continue
base = seamless(source_tile(path, "RGB"))
if family == "cobblestone":
# Keep the approved cobble structure; the requested colour change is exactly 10%.
base = ImageEnhance.Brightness(base).enhance(0.90)
bases[family] = (base, path)
if family != "basalt":
tiles[family] = (base, (path,))
for name, style in VARIANTS.get(family, {}).items():
tiles[name] = (seamless(derive(base, style)), (path,))
if "blackstone" in bases and (source / "gold-deposit.png").is_file():
ore_jobs = [("gilded_blackstone", "blackstone", "gold")]
else:
ore_jobs = []
ore_jobs += [(f"{prefix}{mineral}_ore", family, mineral)
for mineral in MINERALS for prefix, family in (("", "stone"), ("deepslate_", "deepslate"))]
ore_jobs += [(f"nether_{mineral}_ore", "netherrack", mineral) for mineral in ("gold", "quartz")]
ore_jobs += [("ancient_debris_side", "netherrack", "ancient_debris"),
("ancient_debris_top", "netherrack", "ancient_debris")]
deposits = {}
for name, base, mineral in ore_jobs:
path = source / f"{mineral}-deposit.png"
if not complete and (base not in bases or not path.is_file()):
continue
tile, albedo = bases[base]
if mineral not in deposits:
deposits[mineral] = source_tile(path, "RGBA")
layer = deposits[mineral]
if name == "ancient_debris_top":
layer = layer.transpose(Image.Transpose.ROTATE_90)
rendered = Image.alpha_composite(tile.convert("RGBA"), layer).convert("RGB")
tiles[name] = (seamless(rendered), (albedo, path))
return tiles
def write_tiles(source, output, complete=False):
tiles = compile_tiles(source, complete)
output.mkdir(parents=True, exist_ok=False)
(output / TEXTURES).mkdir(parents=True)
inputs = {}
entries = {}
for name, (texture, dependencies) in sorted(tiles.items()):
for path in dependencies:
if path.name not in inputs:
inputs[path.name] = sha(path.read_bytes())
key = (TEXTURES / f"{name}.png").as_posix()
path = output / key
texture.save(path, format="PNG", optimize=True)
a = np.asarray(texture)
if not (np.array_equal(a[0], a[-1]) and np.array_equal(a[:, 0], a[:, -1])):
raise ValueError(f"Unmatched tile edges: {key}")
entries[key] = {"sha256": sha(path.read_bytes()), "inputs": [p.name for p in dependencies]}
receipt = {"size": SIZE, "inputs": inputs, "entries": entries}
(output / "stone-family.json").write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8", newline="\n")
charts = "".join(
f'<figure><div style="background-image:url({key})"></div>'
f'<figcaption>{Path(key).stem.replace("_", " ")}</figcaption></figure>'
for key in entries
)
header = """<!doctype html><meta charset="utf-8"><title>Stone and ore tiles</title>
<style>body{background:#1b1a17;color:#eee8db;font:16px system-ui;margin:32px}
main{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:20px}
figure{margin:0}figure div{height:216px;background-size:108px;image-rendering:auto}
figcaption{padding:8px 0;text-transform:capitalize}</style>
<h1>Stone and ore tiles</h1><main>"""
(output / "preview.html").write_text(header + charts + "</main>", encoding="utf-8", newline="\n")
return receipt
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--complete", action="store_true", help="Require every listed source and ore layer")
args = parser.parse_args()
receipt = write_tiles(args.source, args.output, args.complete)
print(f"Compiled {len(receipt['entries'])} seamless {SIZE}x{SIZE} block tiles.")