diff --git a/tools/assemble-realistic-stone-pack.py b/tools/assemble-realistic-stone-pack.py new file mode 100644 index 00000000..76d03aea --- /dev/null +++ b/tools/assemble-realistic-stone-pack.py @@ -0,0 +1,72 @@ +"""Build the two immutable resource packs from reviewed vanilla tile exports.""" + +import argparse +import hashlib +import json +from pathlib import Path +import struct + +from plugin_supplied_item_art import read_pack +from plugin_wild_update import write_archive + + +BASE_SOURCE = "e9c8db19a000dea4625db70e724f1e615ceebf89" +BASE = { + "arrakis": "09fc179ca0ecc018a6906e2cc948dd671b19f1d7312c0819bd99bbedfbd87416", + "fleet": "ec4b46f0c6362cd4284a18e84b799c850b44f2bf14a36589af3c3bcaa8f7f595", +} +CATALOG = Path(__file__).with_name("realistic-stone-family-paths.json") +PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452") + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def assemble(variant, baseline, export, receipt_sha, output, require_full=True): + if sha(baseline.read_bytes()) != BASE[variant]: + raise ValueError(f"{variant} pack differs from the accepted Soft Dune preimage") + receipt = (export / "stone-family.json").read_bytes() + if sha(receipt) != receipt_sha: + raise ValueError("Texture export receipt differs from the accepted hash") + manifest = json.loads(receipt) + catalog = set(json.loads(CATALOG.read_bytes())) + names = set(manifest["entries"]) + if manifest["size"] != 256 or not names or not names <= catalog or (require_full and names != catalog): + raise ValueError("Unexpected vanilla block texture scope") + retained = read_pack(baseline) + updated = {} + for key in sorted(names): + data = (export / key).read_bytes() + if sha(data) != manifest["entries"][key]["sha256"]: + raise ValueError(f"Texture differs from the verified export: {key}") + if not data.startswith(PNG) or struct.unpack(">II", data[16:24]) != (256, 256): + raise ValueError(f"Invalid tile dimensions: {key}") + if key + ".mcmeta" in retained: + raise ValueError(f"Review inherited animation metadata before replacing {key}") + updated[key] = data + final = retained | updated + payload = write_archive(final) + with output.open("xb") as file: + file.write(payload) + if read_pack(output) != final: + raise ValueError("Unexpected ZIP entry after material merge") + return { + "filename": output.name, + "variant": variant, + "textureCount": len(updated), + "changed": sum(retained.get(k) != v for k, v in updated.items()), + "sha1": hashlib.sha1(payload).hexdigest(), + "sha256": sha(payload), + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("variant", choices=BASE) + parser.add_argument("baseline", type=Path) + parser.add_argument("export", type=Path) + parser.add_argument("receipt_sha") + parser.add_argument("output", type=Path) + parser.add_argument("--allow-partial", action="store_false", dest="require_full") + print(json.dumps(assemble(**vars(parser.parse_args())), indent=2)) diff --git a/tools/compile-realistic-stone-family.py b/tools/compile-realistic-stone-family.py new file mode 100644 index 00000000..4b6d2fe7 --- /dev/null +++ b/tools/compile-realistic-stone-family.py @@ -0,0 +1,236 @@ +"""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 + +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") +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 image.width != image.height or image.width < SIZE: + raise ValueError(f"{path.name} must be a square image of at least {SIZE} pixels") + if mode == "RGBA": + alpha = image.convert("RGBA").getchannel("A") + if alpha.getextrema()[0] != 0 or alpha.getextrema()[1] < 128: + raise ValueError(f"{path.name} requires a transparent background and visible deposits") + return image.convert(mode).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")) + 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") + charts = "".join( + f'
' + f'
{Path(key).stem.replace("_", " ")}
' + for key in entries + ) + header = """Stone and ore tiles + +

Stone and ore tiles

""" + (output / "preview.html").write_text(header + charts + "
", encoding="utf-8") + 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.") diff --git a/tools/realistic-stone-family-paths.json b/tools/realistic-stone-family-paths.json new file mode 100644 index 00000000..6a5bd153 --- /dev/null +++ b/tools/realistic-stone-family-paths.json @@ -0,0 +1,82 @@ +[ + "assets/minecraft/textures/block/ancient_debris_side.png", + "assets/minecraft/textures/block/ancient_debris_top.png", + "assets/minecraft/textures/block/andesite.png", + "assets/minecraft/textures/block/basalt_side.png", + "assets/minecraft/textures/block/basalt_top.png", + "assets/minecraft/textures/block/bedrock.png", + "assets/minecraft/textures/block/blackstone.png", + "assets/minecraft/textures/block/blackstone_top.png", + "assets/minecraft/textures/block/calcite.png", + "assets/minecraft/textures/block/chiseled_deepslate.png", + "assets/minecraft/textures/block/chiseled_polished_blackstone.png", + "assets/minecraft/textures/block/chiseled_red_sandstone.png", + "assets/minecraft/textures/block/chiseled_sandstone.png", + "assets/minecraft/textures/block/chiseled_stone_bricks.png", + "assets/minecraft/textures/block/chiseled_tuff.png", + "assets/minecraft/textures/block/chiseled_tuff_bricks.png", + "assets/minecraft/textures/block/chiseled_tuff_bricks_top.png", + "assets/minecraft/textures/block/chiseled_tuff_top.png", + "assets/minecraft/textures/block/coal_ore.png", + "assets/minecraft/textures/block/cobbled_deepslate.png", + "assets/minecraft/textures/block/cobblestone.png", + "assets/minecraft/textures/block/copper_ore.png", + "assets/minecraft/textures/block/cracked_deepslate_bricks.png", + "assets/minecraft/textures/block/cracked_deepslate_tiles.png", + "assets/minecraft/textures/block/cracked_polished_blackstone_bricks.png", + "assets/minecraft/textures/block/cracked_stone_bricks.png", + "assets/minecraft/textures/block/cut_red_sandstone.png", + "assets/minecraft/textures/block/cut_sandstone.png", + "assets/minecraft/textures/block/deepslate.png", + "assets/minecraft/textures/block/deepslate_bricks.png", + "assets/minecraft/textures/block/deepslate_coal_ore.png", + "assets/minecraft/textures/block/deepslate_copper_ore.png", + "assets/minecraft/textures/block/deepslate_diamond_ore.png", + "assets/minecraft/textures/block/deepslate_emerald_ore.png", + "assets/minecraft/textures/block/deepslate_gold_ore.png", + "assets/minecraft/textures/block/deepslate_iron_ore.png", + "assets/minecraft/textures/block/deepslate_lapis_ore.png", + "assets/minecraft/textures/block/deepslate_redstone_ore.png", + "assets/minecraft/textures/block/deepslate_tiles.png", + "assets/minecraft/textures/block/deepslate_top.png", + "assets/minecraft/textures/block/diamond_ore.png", + "assets/minecraft/textures/block/diorite.png", + "assets/minecraft/textures/block/dripstone_block.png", + "assets/minecraft/textures/block/emerald_ore.png", + "assets/minecraft/textures/block/end_stone.png", + "assets/minecraft/textures/block/end_stone_bricks.png", + "assets/minecraft/textures/block/gilded_blackstone.png", + "assets/minecraft/textures/block/gold_ore.png", + "assets/minecraft/textures/block/granite.png", + "assets/minecraft/textures/block/iron_ore.png", + "assets/minecraft/textures/block/lapis_ore.png", + "assets/minecraft/textures/block/mossy_cobblestone.png", + "assets/minecraft/textures/block/mossy_stone_bricks.png", + "assets/minecraft/textures/block/nether_gold_ore.png", + "assets/minecraft/textures/block/nether_quartz_ore.png", + "assets/minecraft/textures/block/netherrack.png", + "assets/minecraft/textures/block/obsidian.png", + "assets/minecraft/textures/block/polished_andesite.png", + "assets/minecraft/textures/block/polished_basalt_side.png", + "assets/minecraft/textures/block/polished_basalt_top.png", + "assets/minecraft/textures/block/polished_blackstone.png", + "assets/minecraft/textures/block/polished_blackstone_bricks.png", + "assets/minecraft/textures/block/polished_deepslate.png", + "assets/minecraft/textures/block/polished_diorite.png", + "assets/minecraft/textures/block/polished_granite.png", + "assets/minecraft/textures/block/polished_tuff.png", + "assets/minecraft/textures/block/red_sandstone.png", + "assets/minecraft/textures/block/red_sandstone_bottom.png", + "assets/minecraft/textures/block/red_sandstone_top.png", + "assets/minecraft/textures/block/redstone_ore.png", + "assets/minecraft/textures/block/sandstone.png", + "assets/minecraft/textures/block/sandstone_bottom.png", + "assets/minecraft/textures/block/sandstone_top.png", + "assets/minecraft/textures/block/smooth_basalt.png", + "assets/minecraft/textures/block/smooth_stone.png", + "assets/minecraft/textures/block/smooth_stone_slab_side.png", + "assets/minecraft/textures/block/stone.png", + "assets/minecraft/textures/block/stone_bricks.png", + "assets/minecraft/textures/block/tuff.png", + "assets/minecraft/textures/block/tuff_bricks.png" +] diff --git a/tools/test_realistic_stone_family.py b/tools/test_realistic_stone_family.py new file mode 100644 index 00000000..7b62aae1 --- /dev/null +++ b/tools/test_realistic_stone_family.py @@ -0,0 +1,71 @@ +import hashlib +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest + +from PIL import Image, ImageDraw + +from plugin_supplied_item_art import read_pack +from plugin_wild_update import write_archive + + +def tool(name): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + ".py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +compiler = tool("compile-realistic-stone-family") +assembler = tool("assemble-realistic-stone-pack") + + +class StoneFamilyTest(unittest.TestCase): + def test_complete_catalog_composites_ores_and_keeps_unrelated_files(self): + with tempfile.TemporaryDirectory() as location: + root = Path(location) + inputs = root / "sources" + inputs.mkdir() + for name in compiler.CORE + compiler.OPTIONAL: + Image.new("RGB", (256, 256), (122, 118, 110)).save(inputs / f"{name}-source.png") + ore = Image.new("RGBA", (256, 256)) + ImageDraw.Draw(ore).rectangle((104, 104, 151, 151), fill=(200, 30, 55, 255)) + for name in compiler.MINERALS + ("quartz", "ancient_debris"): + ore.save(inputs / f"{name}-deposit.png") + output = root / "export" + result = compiler.write_tiles(inputs, output, complete=True) + self.assertEqual(set(result["entries"]), set(json.loads(assembler.CATALOG.read_bytes()))) + copper = compiler.TEXTURES / "copper_ore.png" + self.assertEqual(result["entries"][copper.as_posix()]["inputs"], ["stone-source.png", "copper-deposit.png"]) + with Image.open(output / copper) as texture: + self.assertEqual(texture.getpixel((0, 0)), (122, 118, 110)) + self.assertEqual(texture.getpixel((125, 125)), (200, 30, 55)) + retained = {"pack.mcmeta": b"metadata", "assets/dunerealms/test": b"custom"} + baseline = root / "base.zip" + baseline.write_bytes(write_archive(retained)) + original_pin = assembler.BASE["arrakis"] + assembler.BASE["arrakis"] = hashlib.sha256(baseline.read_bytes()).hexdigest() + try: + receipt = assembler.sha((output / "stone-family.json").read_bytes()) + final = root / "tested.zip" + with self.assertRaisesRegex(ValueError, "receipt"): + assembler.assemble("arrakis", baseline, output, "0" * 64, final) + self.assertEqual(assembler.assemble("arrakis", baseline, output, receipt, final)["changed"], 80) + packed = read_pack(final) + self.assertEqual({name: packed[name] for name in retained}, retained) + self.assertEqual(set(packed) - set(retained), set(result["entries"])) + finally: + assembler.BASE["arrakis"] = original_pin + + def test_opaque_ore_source_fails(self): + with tempfile.TemporaryDirectory() as location: + path = Path(location) / "opaque.png" + Image.new("RGB", (256, 256), (45, 80, 90)).save(path) + with self.assertRaisesRegex(ValueError, "transparent background"): + compiler.source_tile(path, "RGBA") + + +if __name__ == "__main__": + unittest.main()