dotomata 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dotomata/__init__.py +1 -0
- dotomata/__main__.py +5 -0
- dotomata/art.py +575 -0
- dotomata/artcli.py +143 -0
- dotomata/assemble.py +234 -0
- dotomata/background.py +184 -0
- dotomata/build.py +216 -0
- dotomata/checks.py +52 -0
- dotomata/cli.py +535 -0
- dotomata/codexrun.py +430 -0
- dotomata/common.py +215 -0
- dotomata/convert.py +265 -0
- dotomata/default_config.json +372 -0
- dotomata/fixes.py +82 -0
- dotomata/generate.py +328 -0
- dotomata/imaging.py +98 -0
- dotomata/parts.py +210 -0
- dotomata/reduce.py +76 -0
- dotomata/refadopt.py +121 -0
- dotomata/selftest.py +1299 -0
- dotomata/selftest_art.py +488 -0
- dotomata/selftest_data/exec_events_json_item.jsonl +6 -0
- dotomata/selftest_data/exec_events_rollout.jsonl +5 -0
- dotomata/selftest_data/fake_codex.py +122 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_mask.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_motion.json +62 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_preview.gif +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_report.json +56 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_sheet.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/beast/silhouette_beast_zoom.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_mask.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_motion.json +62 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_preview.gif +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_report.json +56 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_sheet.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/boss/silhouette_boss_zoom.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_mask.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_motion.json +62 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_preview.gif +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_report.json +56 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_sheet.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/humanoid/silhouette_humanoid_zoom.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_mask.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_motion.json +62 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_preview.gif +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_report.json +56 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_sheet.png +0 -0
- dotomata/selftest_data/golden/output/Silhouettes/slime/silhouette_slime_zoom.png +0 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/down.txt +18 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/grid.txt +52 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/palette.json +5 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/parts.json +20 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/parts_mask.txt +52 -0
- dotomata/selftest_data/golden/source/Silhouettes/beast/unit.json +11 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/down.txt +31 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/grid.txt +112 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/palette.json +5 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/parts.json +20 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/parts_mask.txt +112 -0
- dotomata/selftest_data/golden/source/Silhouettes/boss/unit.json +11 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/down.txt +23 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/grid.txt +80 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/palette.json +5 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/parts.json +20 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/parts_mask.txt +80 -0
- dotomata/selftest_data/golden/source/Silhouettes/humanoid/unit.json +11 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/down.txt +12 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/grid.txt +40 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/palette.json +5 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/parts.json +20 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/parts_mask.txt +40 -0
- dotomata/selftest_data/golden/source/Silhouettes/slime/unit.json +11 -0
- dotomata/selftest_data/rollout_extension_two_calls.jsonl +11 -0
- dotomata/selftest_data/rollout_two_calls.jsonl +6 -0
- dotomata/selftest_provenance.py +156 -0
- dotomata/selftest_refadopt.py +156 -0
- dotomata/selftest_rigs.py +218 -0
- dotomata-0.1.1.dist-info/METADATA +134 -0
- dotomata-0.1.1.dist-info/RECORD +82 -0
- dotomata-0.1.1.dist-info/WHEEL +4 -0
- dotomata-0.1.1.dist-info/entry_points.txt +2 -0
- dotomata-0.1.1.dist-info/licenses/LICENSE +21 -0
dotomata/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""dotomata: pixel-art battle sprites, card art and backgrounds from codex image generation."""
|
dotomata/__main__.py
ADDED
dotomata/art.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
"""Card art: generation through the shared codex
|
|
2
|
+
runner, the user's adoption, the bust crop, the recolour of a palette-swap unit, placeholders,
|
|
3
|
+
the build into paths.art_output and verify.
|
|
4
|
+
|
|
5
|
+
Only the adopted candidate is kept in the source (source/<unit>/art/); the
|
|
6
|
+
other candidates stay in the ignored preview folder, and the generation record
|
|
7
|
+
keeps every candidate's prompt and sha256."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import csv
|
|
12
|
+
import datetime
|
|
13
|
+
import shutil
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Callable
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
19
|
+
|
|
20
|
+
from .codexrun import Target, calls_used, check_banned, check_batch, display_path, load_record, run_batch, write_sheet
|
|
21
|
+
from .common import (Context, SpriteError, Unit, json_bytes, load_unit, parse_hex, read_json, sha256_file,
|
|
22
|
+
unit_paths_by_id)
|
|
23
|
+
from .generate import require_design
|
|
24
|
+
from .imaging import png_bytes, same_png
|
|
25
|
+
from .reduce import block_image
|
|
26
|
+
|
|
27
|
+
STAGE = "base"
|
|
28
|
+
GENERATION = "art_generation.json"
|
|
29
|
+
ADOPTION = "art.json"
|
|
30
|
+
RECOLOR = "recolor.json"
|
|
31
|
+
DOT_REF = "dot_ref.png"
|
|
32
|
+
PREFIX = "art_candidate"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def art_source(unit: Unit) -> Path:
|
|
36
|
+
return unit.source / "art"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def art_out(ctx: Context, unit: Unit) -> Path:
|
|
40
|
+
return ctx.preview_dir / unit.path / "art"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def art_output_dir(ctx: Context, unit: Unit) -> Path:
|
|
44
|
+
return ctx.root / ctx.project["paths"]["art_output"] / unit.id
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def output_names(unit_id: str, stage: str) -> tuple[str, str]:
|
|
48
|
+
return f"{unit_id}_{stage}_full.png", f"{unit_id}_{stage}_bust.png"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def art_target(ctx: Context, unit: Unit) -> Target:
|
|
52
|
+
a = ctx.project["art"]
|
|
53
|
+
return Target(label=f"card art of '{unit.id}'", header={"unit": unit.id}, record=art_source(unit) / GENERATION,
|
|
54
|
+
out_dir=art_out(ctx, unit), prefix=PREFIX, cap=a["cap_per_unit"], batch_max=a["batch_max"],
|
|
55
|
+
keep_dirs=[art_source(unit)])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_recolor(unit: Unit) -> bool:
|
|
59
|
+
return (art_source(unit) / RECOLOR).is_file()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _refuse_recolor(unit: Unit) -> None:
|
|
63
|
+
# A palette-swap unit is recoloured from its base's art, never drawn on its own.
|
|
64
|
+
if is_recolor(unit) or unit.data.get("palette_swap"):
|
|
65
|
+
raise SpriteError(f"unit '{unit.id}' gets its card art by recolouring its base unit's art "
|
|
66
|
+
f"({RECOLOR}); it is never generated, adopted or given a {DOT_REF}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------- dot reference
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def has_built_sheet(ctx: Context, unit: Unit) -> bool:
|
|
73
|
+
return (ctx.output_dir / unit.path / f"{unit.id}_motion.json").is_file()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def dot_reference_bytes(ctx: Context, unit: Unit) -> bytes:
|
|
77
|
+
"""Idle frame 0 of the built sheet, cropped to its opaque pixels and enlarged
|
|
78
|
+
in ref_block squares on the reference magenta, like the size-pass reference."""
|
|
79
|
+
folder = ctx.output_dir / unit.path
|
|
80
|
+
motion_path = folder / f"{unit.id}_motion.json"
|
|
81
|
+
if not motion_path.is_file():
|
|
82
|
+
raise SpriteError(f"unit '{unit.id}' has no built sheet ({motion_path}); build its sprite first")
|
|
83
|
+
motion = read_json(motion_path)
|
|
84
|
+
idle = [a for a in motion["actions"] if a["name"] == "idle"]
|
|
85
|
+
if not idle or not idle[0]["frames"]:
|
|
86
|
+
raise SpriteError(f"unit '{unit.id}': {motion_path.name} has no idle frame")
|
|
87
|
+
frame = idle[0]["frames"][0]
|
|
88
|
+
cw, ch = motion["cell"]["width"], motion["cell"]["height"]
|
|
89
|
+
with Image.open(folder / motion["sheet"]) as im:
|
|
90
|
+
sheet = np.array(im.convert("RGBA"))
|
|
91
|
+
cell = sheet[frame["y"]:frame["y"] + ch, frame["x"]:frame["x"] + cw]
|
|
92
|
+
ys, xs = np.nonzero(cell[..., 3] == 255)
|
|
93
|
+
if not len(ys):
|
|
94
|
+
raise SpriteError(f"unit '{unit.id}': idle frame 0 is empty")
|
|
95
|
+
return png_bytes(block_image(cell[ys.min():ys.max() + 1, xs.min():xs.max() + 1], ctx.project["reduce"]))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def write_dot_reference(ctx: Context, unit: Unit, force: bool) -> Path:
|
|
99
|
+
_refuse_recolor(unit)
|
|
100
|
+
path = art_source(unit) / DOT_REF
|
|
101
|
+
if path.exists() and not force:
|
|
102
|
+
raise SpriteError(f"refusing to overwrite {path} (pass --force to replace it)")
|
|
103
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
path.write_bytes(dot_reference_bytes(ctx, unit))
|
|
105
|
+
return path
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def refresh_dot_reference(ctx: Context, unit: Unit) -> Path | None:
|
|
109
|
+
"""After a sprite build: rewrites an existing dot_ref.png from the new sheet (the
|
|
110
|
+
build makes it), so verify and art generate keep
|
|
111
|
+
matching. Returns the path when the pixels changed."""
|
|
112
|
+
path = art_source(unit) / DOT_REF
|
|
113
|
+
if not path.is_file():
|
|
114
|
+
return None
|
|
115
|
+
data = dot_reference_bytes(ctx, unit)
|
|
116
|
+
if same_png(path.read_bytes(), data):
|
|
117
|
+
return None
|
|
118
|
+
path.write_bytes(data)
|
|
119
|
+
return path
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _current_dot_reference(ctx: Context, unit: Unit) -> Path | None:
|
|
123
|
+
"""The dot reference a unit with a built sprite must send; None for a unit without one."""
|
|
124
|
+
if not has_built_sheet(ctx, unit):
|
|
125
|
+
return None
|
|
126
|
+
path = art_source(unit) / DOT_REF
|
|
127
|
+
if not path.is_file():
|
|
128
|
+
raise SpriteError(f"unit '{unit.id}' has a sprite but no {DOT_REF}; run: art dot-ref {unit.path}")
|
|
129
|
+
if not same_png(path.read_bytes(), dot_reference_bytes(ctx, unit)):
|
|
130
|
+
raise SpriteError(f"unit '{unit.id}': {DOT_REF} is older than the built sheet; "
|
|
131
|
+
f"run: art dot-ref {unit.path} --force")
|
|
132
|
+
return path
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def style_reference(ctx: Context) -> Path | None:
|
|
136
|
+
"""The picture every card art run gets as its style reference (art.style_reference);
|
|
137
|
+
None when the config sets none, and then no style image or sentence is sent."""
|
|
138
|
+
configured = ctx.project["art"].get("style_reference")
|
|
139
|
+
if not configured:
|
|
140
|
+
return None
|
|
141
|
+
path = ctx.root / configured
|
|
142
|
+
if not path.is_file():
|
|
143
|
+
raise SpriteError(f"card art: the style reference {path} is missing (art.style_reference)")
|
|
144
|
+
return path
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# ---------------------------------------------------------------- generate
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def art_prompt(ctx: Context, unit: Unit, notes: list[str], dot_reference: bool, variant: str | None = None) -> str:
|
|
151
|
+
gen, a = ctx.project["generation"], ctx.project["art"]
|
|
152
|
+
design = require_design(unit)
|
|
153
|
+
lines = [gen["tool_instruction"],
|
|
154
|
+
"Image: " + " ".join([a["common_prompt"], a["composition_sentence"], a["design_rule_sentence"], design])]
|
|
155
|
+
if notes:
|
|
156
|
+
lines.append("Changes from the previous candidate: " + " ".join(notes))
|
|
157
|
+
if a.get("style_reference"):
|
|
158
|
+
lines.append(a["style_reference_sentence"])
|
|
159
|
+
if dot_reference:
|
|
160
|
+
lines.append(a["dot_reference_sentence"])
|
|
161
|
+
if variant:
|
|
162
|
+
lines.append("For this candidate: " + variant)
|
|
163
|
+
prompt = "\n".join(lines)
|
|
164
|
+
check_banned(ctx, f"card art of '{unit.id}'", prompt)
|
|
165
|
+
return prompt
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def generate_art(ctx: Context, unit: Unit, notes: list[str], batch: int = 1, variants: list[str] | None = None) -> dict:
|
|
169
|
+
"""One codex run per candidate, all at once. Every run sends the style reference
|
|
170
|
+
when the config sets one; a unit with a built sprite also sends its dot reference."""
|
|
171
|
+
_refuse_recolor(unit)
|
|
172
|
+
require_design(unit)
|
|
173
|
+
variants = list(variants or [])
|
|
174
|
+
target = art_target(ctx, unit)
|
|
175
|
+
used = check_batch(target, batch, variants)
|
|
176
|
+
reference = _current_dot_reference(ctx, unit)
|
|
177
|
+
style = style_reference(ctx)
|
|
178
|
+
run_variants = [variants[i] if i < len(variants) else None for i in range(batch)]
|
|
179
|
+
prompts = [art_prompt(ctx, unit, notes, reference is not None, v) for v in run_variants]
|
|
180
|
+
ref_record = ({"mode": "dot", "path": display_path(ctx, reference), "sha256": sha256_file(reference)}
|
|
181
|
+
if reference is not None else None)
|
|
182
|
+
references = ([style] if style is not None else []) + ([reference] if reference is not None else [])
|
|
183
|
+
style_record = {"path": display_path(ctx, style), "sha256": sha256_file(style)} if style is not None else None
|
|
184
|
+
result = run_batch(ctx, target, prompts, run_variants, references, ref_record, {"style_reference": style_record})
|
|
185
|
+
sheet = write_comparison_sheet(ctx, target, [r["entry"] for r in result["runs"]],
|
|
186
|
+
art_source(unit) / f"art_batch_{result['first']}-{result['last']}.jpg")
|
|
187
|
+
return {"runs": result["runs"], "sheet": str(sheet), "cap": target.cap,
|
|
188
|
+
"used": used + sum(r["entry"]["image_generation_calls"] for r in result["runs"])}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _size_label(folder: Path) -> Callable[[dict], str]:
|
|
192
|
+
def label(e: dict) -> str:
|
|
193
|
+
if e["candidate"]:
|
|
194
|
+
try:
|
|
195
|
+
with Image.open(folder / e["candidate"]) as im:
|
|
196
|
+
return f"{im.width}x{im.height}" + (f" - {e['variant']}" if e["variant"] else "")
|
|
197
|
+
except OSError:
|
|
198
|
+
return "unreadable image"
|
|
199
|
+
return e["error"] or "no image"
|
|
200
|
+
return label
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def write_comparison_sheet(ctx: Context, target: Target, entries: list[dict], out: Path) -> Path:
|
|
204
|
+
"""The candidates the user chose from, as a small JPEG kept in the source."""
|
|
205
|
+
s = ctx.project["comparison_sheet"]
|
|
206
|
+
return write_sheet(ctx, target.out_dir, entries, out, s["panel_height"], _size_label(target.out_dir),
|
|
207
|
+
long_side=s["long_side"], jpeg_quality=s["jpeg_quality"])
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ---------------------------------------------------------------- adoption
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def load_image_rgb(path: Path, what: str) -> np.ndarray:
|
|
214
|
+
try:
|
|
215
|
+
with Image.open(path) as im:
|
|
216
|
+
im.load()
|
|
217
|
+
rgba = np.array(im.convert("RGBA"))
|
|
218
|
+
except OSError as e:
|
|
219
|
+
raise SpriteError(f"{what}: cannot read {path.name}: {e}") from e
|
|
220
|
+
if (rgba[..., 3] < 255).any():
|
|
221
|
+
raise SpriteError(f"{what}: {path.name} has transparent pixels; card art and backgrounds are opaque")
|
|
222
|
+
return rgba[..., :3].copy()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def adopt_candidate(target: Target, source: Path, name: str, check: Callable[[Path], None]) -> dict:
|
|
226
|
+
"""Checks a recorded candidate against its record, copies it into the source
|
|
227
|
+
and returns the start of an adoption entry."""
|
|
228
|
+
entries = [g for g in load_record(target)["generations"] if g.get("candidate") == name]
|
|
229
|
+
if not entries:
|
|
230
|
+
raise SpriteError(f"{target.label}: {name} is not in {target.record.name}")
|
|
231
|
+
if entries[-1].get("invalid"):
|
|
232
|
+
raise SpriteError(f"{target.label}: {name} is marked invalid in {target.record.name}: {entries[-1]['invalid']}")
|
|
233
|
+
found = [d / name for d in (source, target.out_dir) if (d / name).is_file()]
|
|
234
|
+
if not found:
|
|
235
|
+
raise SpriteError(f"{target.label}: {name} is in neither {source} nor {target.out_dir}")
|
|
236
|
+
digest = sha256_file(found[0])
|
|
237
|
+
if digest != entries[-1]["output_sha256"]:
|
|
238
|
+
raise SpriteError(f"{target.label}: {found[0]} does not match the sha256 recorded for {name}")
|
|
239
|
+
check(found[0])
|
|
240
|
+
if found[0].parent != source:
|
|
241
|
+
source.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
shutil.copyfile(found[0], source / name)
|
|
243
|
+
return {"candidate": name, "sha256": digest}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def retire_candidate(target: Target, source: Path, name: str, still_used: set[str]) -> None:
|
|
247
|
+
"""An earlier adopted candidate leaves the source; its record stays. It goes
|
|
248
|
+
back to the preview folder so it can still be looked at on this machine."""
|
|
249
|
+
if name in still_used or not (source / name).is_file():
|
|
250
|
+
return
|
|
251
|
+
target.out_dir.mkdir(parents=True, exist_ok=True)
|
|
252
|
+
if (target.out_dir / name).exists():
|
|
253
|
+
(source / name).unlink()
|
|
254
|
+
else:
|
|
255
|
+
shutil.move(str(source / name), str(target.out_dir / name))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def load_adoption(unit: Unit) -> dict:
|
|
259
|
+
path = art_source(unit) / ADOPTION
|
|
260
|
+
return read_json(path) if path.is_file() else {"unit": unit.id, "stages": {}}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def current_adoption(data: dict, stage: str, what: str) -> dict:
|
|
264
|
+
adoptions = data.get("stages", {}).get(stage, {}).get("adoptions") or []
|
|
265
|
+
if not adoptions:
|
|
266
|
+
raise SpriteError(f"{what}: stage '{stage}' has no adoption in {ADOPTION}")
|
|
267
|
+
return adoptions[-1]
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def check_art_image(ctx: Context, what: str) -> Callable[[Path], None]:
|
|
271
|
+
def check(path: Path) -> None:
|
|
272
|
+
rgb = load_image_rgb(path, what)
|
|
273
|
+
h, w = rgb.shape[:2]
|
|
274
|
+
if w * 3 != h * 2:
|
|
275
|
+
raise SpriteError(f"{what}: {path.name} is {w}x{h}, not a 2:3 portrait")
|
|
276
|
+
return check
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def check_bust(rect, width: int, height: int, min_side: int, what: str) -> dict:
|
|
280
|
+
"""The bust crop: whole pixels, inside the image, square, at least min_side."""
|
|
281
|
+
keys = ("x", "y", "width", "height")
|
|
282
|
+
if not isinstance(rect, dict) or sorted(rect) != sorted(keys):
|
|
283
|
+
raise SpriteError(f"{what}: bust must be {{x, y, width, height}} (got {rect})")
|
|
284
|
+
if not all(isinstance(rect[k], int) and not isinstance(rect[k], bool) for k in keys):
|
|
285
|
+
raise SpriteError(f"{what}: bust values must be whole pixels (got {rect})")
|
|
286
|
+
x, y, w, h = (rect[k] for k in keys)
|
|
287
|
+
if x < 0 or y < 0 or x + w > width or y + h > height:
|
|
288
|
+
raise SpriteError(f"{what}: bust {rect} is outside the {width}x{height} image")
|
|
289
|
+
if w != h:
|
|
290
|
+
raise SpriteError(f"{what}: bust {rect} is not square")
|
|
291
|
+
if w < min_side:
|
|
292
|
+
raise SpriteError(f"{what}: bust side {w} is smaller than {min_side} px (the bust is never enlarged)")
|
|
293
|
+
return {k: rect[k] for k in keys}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def rect_from(values: list[int] | None) -> dict | None:
|
|
297
|
+
return None if values is None else dict(zip(("x", "y", "width", "height"), values))
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def adopt_art(ctx: Context, unit: Unit, name: str, note: str, bust: dict | None, stage: str = STAGE) -> dict:
|
|
301
|
+
_refuse_recolor(unit)
|
|
302
|
+
if not note.strip():
|
|
303
|
+
raise SpriteError("an adoption needs a note (the user's reason)")
|
|
304
|
+
target, source = art_target(ctx, unit), art_source(unit)
|
|
305
|
+
what = f"card art of '{unit.id}'"
|
|
306
|
+
checked_bust = [None]
|
|
307
|
+
|
|
308
|
+
# The bust is checked with the picture, before adopt_candidate copies it, so a bad
|
|
309
|
+
# rectangle leaves no unadopted candidate in the source.
|
|
310
|
+
def check(path: Path) -> None:
|
|
311
|
+
check_art_image(ctx, what)(path)
|
|
312
|
+
if bust is not None:
|
|
313
|
+
rgb = load_image_rgb(path, what)
|
|
314
|
+
checked_bust[0] = check_bust(bust, rgb.shape[1], rgb.shape[0], ctx.project["art"]["bust_min_side"], what)
|
|
315
|
+
|
|
316
|
+
entry = adopt_candidate(target, source, name, check)
|
|
317
|
+
bust = checked_bust[0]
|
|
318
|
+
data = load_adoption(unit)
|
|
319
|
+
adoptions = data.setdefault("stages", {}).setdefault(stage, {}).setdefault("adoptions", [])
|
|
320
|
+
previous = adoptions[-1]["candidate"] if adoptions else None
|
|
321
|
+
adoptions.append({**entry, "note": note, "date": datetime.date.today().isoformat(), "bust": bust})
|
|
322
|
+
(source / ADOPTION).write_bytes(json_bytes(data))
|
|
323
|
+
if previous and previous != name:
|
|
324
|
+
in_use = {current_adoption(data, s, what)["candidate"] for s in data["stages"]}
|
|
325
|
+
retire_candidate(target, source, previous, in_use)
|
|
326
|
+
return adoptions[-1]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def set_bust(ctx: Context, unit: Unit, bust: dict, stage: str = STAGE) -> dict:
|
|
330
|
+
"""Sets the bust crop of the current adoption (a later adoption needs its own)."""
|
|
331
|
+
what = f"card art of '{unit.id}'"
|
|
332
|
+
data = load_adoption(unit)
|
|
333
|
+
current = current_adoption(data, stage, what)
|
|
334
|
+
rgb = load_image_rgb(art_source(unit) / current["candidate"], what)
|
|
335
|
+
current["bust"] = check_bust(bust, rgb.shape[1], rgb.shape[0], ctx.project["art"]["bust_min_side"], what)
|
|
336
|
+
(art_source(unit) / ADOPTION).write_bytes(json_bytes(data))
|
|
337
|
+
return current
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def art_status(ctx: Context, unit: Unit) -> dict:
|
|
341
|
+
calls, candidates = calls_used(art_target(ctx, unit))
|
|
342
|
+
data = load_adoption(unit)
|
|
343
|
+
stages = {s: v["adoptions"][-1] for s, v in sorted(data.get("stages", {}).items()) if v.get("adoptions")}
|
|
344
|
+
return {"unit": unit.id, "image_generation_calls": calls, "cap": ctx.project["art"]["cap_per_unit"],
|
|
345
|
+
# recolor: never generated (a palette swap also before its rule exists); recolor_rule: recolor.json is written.
|
|
346
|
+
"candidates": candidates, "recolor": is_recolor(unit) or bool(unit.data.get("palette_swap")),
|
|
347
|
+
"recolor_rule": is_recolor(unit), "dot_reference": has_built_sheet(ctx, unit),
|
|
348
|
+
"adopted": stages}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ---------------------------------------------------------------- build
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def bust_image(rgb: np.ndarray, rect: dict, size: int) -> np.ndarray:
|
|
355
|
+
"""The square crop scaled down to size x size (never up: check_bust keeps the side >= size)."""
|
|
356
|
+
x, y, side = rect["x"], rect["y"], rect["width"]
|
|
357
|
+
crop = Image.fromarray(rgb[y:y + side, x:x + side], "RGB")
|
|
358
|
+
if side != size:
|
|
359
|
+
crop = crop.resize((size, size), Image.Resampling.LANCZOS)
|
|
360
|
+
return np.array(crop)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def recolor(rgb: np.ndarray, rule: dict, what: str) -> np.ndarray:
|
|
364
|
+
"""Turns the hues in rule["hue_from"] (degrees, inclusive) so that the range's
|
|
365
|
+
middle lands on rule["hue_to"], for pixels at least rule["min_saturation"]
|
|
366
|
+
percent saturated; everything else keeps its exact colour. The optional
|
|
367
|
+
rule["saturation"] and rule["value"] (percent, 100 = unchanged) scale the
|
|
368
|
+
turned pixels, capped at full."""
|
|
369
|
+
try:
|
|
370
|
+
lo, hi = rule["hue_from"]
|
|
371
|
+
to, min_s = rule["hue_to"], rule["min_saturation"]
|
|
372
|
+
sat, val = rule.get("saturation", 100), rule.get("value", 100)
|
|
373
|
+
except (KeyError, TypeError, ValueError) as e:
|
|
374
|
+
raise SpriteError(f"{what}: {RECOLOR} needs hue_from [lo, hi], hue_to and min_saturation") from e
|
|
375
|
+
if not all(isinstance(v, int) and not isinstance(v, bool) for v in (lo, hi, to, min_s, sat, val)):
|
|
376
|
+
raise SpriteError(f"{what}: {RECOLOR} values must be whole numbers")
|
|
377
|
+
if not (0 <= lo < hi <= 360 and 0 <= to < 360 and 0 <= min_s <= 100):
|
|
378
|
+
raise SpriteError(f"{what}: {RECOLOR} needs 0 <= lo < hi <= 360, 0 <= hue_to < 360, 0 <= min_saturation <= 100")
|
|
379
|
+
if not (0 < sat and 0 < val):
|
|
380
|
+
raise SpriteError(f"{what}: {RECOLOR} needs saturation > 0 and value > 0 (percent, 100 = unchanged)")
|
|
381
|
+
# Pillow's HSV keeps hue, saturation and value in 0..255.
|
|
382
|
+
hsv = np.array(Image.fromarray(rgb, "RGB").convert("HSV")).astype(np.int64)
|
|
383
|
+
hue = (hsv[..., 0] * 360 + 127) // 255
|
|
384
|
+
mask = (hue >= lo) & (hue <= hi) & (hsv[..., 1] * 100 >= min_s * 255)
|
|
385
|
+
turned = (hue + to - (lo + hi) // 2) % 360
|
|
386
|
+
shifted = hsv.copy()
|
|
387
|
+
shifted[..., 0] = np.where(mask, (turned * 255 + 180) // 360 % 256, hsv[..., 0])
|
|
388
|
+
# At 100 the rounded scale gives back the same channel, so a rule without the keys is byte-identical.
|
|
389
|
+
shifted[..., 1] = np.where(mask, np.minimum(255, (hsv[..., 1] * sat + 50) // 100), hsv[..., 1])
|
|
390
|
+
shifted[..., 2] = np.where(mask, np.minimum(255, (hsv[..., 2] * val + 50) // 100), hsv[..., 2])
|
|
391
|
+
back = np.array(Image.fromarray(shifted.astype(np.uint8), "HSV").convert("RGB"))
|
|
392
|
+
return np.where(mask[..., None], back, rgb).astype(np.uint8)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _stage_outputs(ctx: Context, unit_id: str, stage: str, full: np.ndarray, bust: dict, what: str) -> dict[str, bytes]:
|
|
396
|
+
a = ctx.project["art"]
|
|
397
|
+
rect = check_bust(bust, full.shape[1], full.shape[0], a["bust_min_side"], what)
|
|
398
|
+
full_name, bust_name = output_names(unit_id, stage)
|
|
399
|
+
# The full picture is the candidate's pixels as they are (no crop, no resampling),
|
|
400
|
+
# written without the generator's metadata chunks.
|
|
401
|
+
return {full_name: png_bytes(full), bust_name: png_bytes(bust_image(full, rect, a["bust_size"]))}
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def adopted_outputs(ctx: Context, unit: Unit) -> dict[str, bytes]:
|
|
405
|
+
what = f"card art of '{unit.id}'"
|
|
406
|
+
data = load_adoption(unit)
|
|
407
|
+
if not data.get("stages"):
|
|
408
|
+
raise SpriteError(f"{what}: {ADOPTION} has no stage")
|
|
409
|
+
files = {}
|
|
410
|
+
for stage in sorted(data["stages"]):
|
|
411
|
+
current = current_adoption(data, stage, what)
|
|
412
|
+
path = art_source(unit) / current["candidate"]
|
|
413
|
+
if not path.is_file():
|
|
414
|
+
raise SpriteError(f"{what}: the adopted {current['candidate']} is not in {art_source(unit)}")
|
|
415
|
+
if sha256_file(path) != current["sha256"]:
|
|
416
|
+
raise SpriteError(f"{what}: {current['candidate']} does not match the sha256 in {ADOPTION}")
|
|
417
|
+
if current.get("bust") is None:
|
|
418
|
+
raise SpriteError(f"{what}: stage '{stage}' has no bust crop; run: art bust {unit.path} --rect X Y W H")
|
|
419
|
+
files.update(_stage_outputs(ctx, unit.id, stage, load_image_rgb(path, what), current["bust"], what))
|
|
420
|
+
return files
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def recolor_outputs(ctx: Context, unit: Unit) -> dict[str, bytes]:
|
|
424
|
+
"""A recolour unit: the base unit's adopted art with one hue range turned, same bust crop."""
|
|
425
|
+
what = f"card art of '{unit.id}'"
|
|
426
|
+
rule = read_json(art_source(unit) / RECOLOR)
|
|
427
|
+
base = load_unit(ctx, rule.get("base") or "")
|
|
428
|
+
if is_recolor(base):
|
|
429
|
+
raise SpriteError(f"{what}: the recolour base '{base.id}' is itself a recolour")
|
|
430
|
+
data = load_adoption(base)
|
|
431
|
+
current = current_adoption(data, STAGE, f"{what} (base '{base.id}')")
|
|
432
|
+
path = art_source(base) / current["candidate"]
|
|
433
|
+
if sha256_file(path) != current["sha256"]:
|
|
434
|
+
raise SpriteError(f"{what}: the base's {current['candidate']} does not match its {ADOPTION}")
|
|
435
|
+
if current.get("bust") is None:
|
|
436
|
+
raise SpriteError(f"{what}: the base '{base.id}' has no bust crop yet")
|
|
437
|
+
full = recolor(load_image_rgb(path, what), rule, what)
|
|
438
|
+
return _stage_outputs(ctx, unit.id, STAGE, full, current["bust"], what)
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
# ---------------------------------------------------------------- placeholders
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def english_name(ctx: Context, key: str | None, what: str) -> str:
|
|
445
|
+
"""unit.json `name`: a key into the paths.strings CSV (its `en` column) when the
|
|
446
|
+
config sets one, else the English name itself."""
|
|
447
|
+
if not key:
|
|
448
|
+
raise SpriteError(f"{what}: unit.json has no 'name'")
|
|
449
|
+
strings = ctx.project["paths"].get("strings")
|
|
450
|
+
if not strings:
|
|
451
|
+
return key
|
|
452
|
+
path = ctx.root / strings
|
|
453
|
+
try:
|
|
454
|
+
with open(path, encoding="utf-8-sig", newline="") as f:
|
|
455
|
+
for row in csv.DictReader(f):
|
|
456
|
+
if row.get("key") == key:
|
|
457
|
+
return row["en"]
|
|
458
|
+
except OSError as e:
|
|
459
|
+
raise SpriteError(f"{what}: cannot read the string table {path}: {e}") from e
|
|
460
|
+
raise SpriteError(f"{what}: string key '{key}' is not in {path.name}")
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def main_color(unit: Unit, what: str) -> tuple[int, int, int]:
|
|
464
|
+
colors = unit.data.get("colors")
|
|
465
|
+
if not colors:
|
|
466
|
+
raise SpriteError(f"{what}: unit.json has no 'colors'; the placeholder uses the first one")
|
|
467
|
+
return parse_hex(colors[0], f"{what} colors[0]")
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def placeholder_canvas(size: tuple[int, int], color: tuple[int, int, int], lines: list[tuple[str, int, int]]) -> np.ndarray:
|
|
471
|
+
"""A flat colour with centred text lines (text, font size, centre y), drawn by code, never by AI."""
|
|
472
|
+
img = Image.new("RGB", size, color)
|
|
473
|
+
draw = ImageDraw.Draw(img)
|
|
474
|
+
ink = (24, 22, 28) if sum(c * w for c, w in zip(color, (299, 587, 114))) > 140_000 else (246, 242, 232)
|
|
475
|
+
for text, font_size, y in lines:
|
|
476
|
+
font = ImageFont.load_default(size=font_size)
|
|
477
|
+
draw.text((size[0] // 2, y), text, fill=ink, font=font, anchor="mm")
|
|
478
|
+
return np.array(img)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def wrap(text: str, font_size: int, width: int) -> list[str]:
|
|
482
|
+
font = ImageFont.load_default(size=font_size)
|
|
483
|
+
lines, line = [], ""
|
|
484
|
+
for word in text.split():
|
|
485
|
+
trial = f"{line} {word}".strip()
|
|
486
|
+
if line and font.getlength(trial) > width:
|
|
487
|
+
lines.append(line)
|
|
488
|
+
line = word
|
|
489
|
+
else:
|
|
490
|
+
line = trial
|
|
491
|
+
return lines + ([line] if line else [])
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def placeholder_outputs(ctx: Context, unit: Unit) -> dict[str, bytes]:
|
|
495
|
+
"""A 2:3 flat-colour card with the unit id and English name, until an adoption replaces it."""
|
|
496
|
+
what = f"card art placeholder of '{unit.id}'"
|
|
497
|
+
a = ctx.project["art"]
|
|
498
|
+
w, h = a["size"]
|
|
499
|
+
name_lines = wrap(english_name(ctx, unit.data.get("name"), what), 88, w - 128)
|
|
500
|
+
lines = [(unit.id, 240, 330)] + [(t, 88, 560 + 100 * i) for i, t in enumerate(name_lines)] + [("PLACEHOLDER", 56, 1380)]
|
|
501
|
+
full = placeholder_canvas((w, h), main_color(unit, what), lines)
|
|
502
|
+
return _stage_outputs(ctx, unit.id, STAGE, full, a["placeholder_bust"], what)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
# ---------------------------------------------------------------- build and verify
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def art_outputs(ctx: Context, unit: Unit) -> tuple[dict[str, bytes], str]:
|
|
509
|
+
"""(files, how): from the recolour rule, the adoption, or a placeholder."""
|
|
510
|
+
if is_recolor(unit):
|
|
511
|
+
return recolor_outputs(ctx, unit), "recolour"
|
|
512
|
+
if (art_source(unit) / ADOPTION).is_file():
|
|
513
|
+
return adopted_outputs(ctx, unit), "adopted"
|
|
514
|
+
return placeholder_outputs(ctx, unit), "placeholder (no art.json yet)"
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def build_art(ctx: Context, unit: Unit, force: bool) -> tuple[list[Path], str]:
|
|
518
|
+
files, how = art_outputs(ctx, unit)
|
|
519
|
+
out = art_output_dir(ctx, unit)
|
|
520
|
+
existing = [n for n in files if (out / n).exists()]
|
|
521
|
+
if existing and not force:
|
|
522
|
+
raise SpriteError(f"refusing to overwrite {existing} in {out} (pass --force to replace them)")
|
|
523
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
524
|
+
written = []
|
|
525
|
+
for name, data in files.items():
|
|
526
|
+
(out / name).write_bytes(data)
|
|
527
|
+
written.append(out / name)
|
|
528
|
+
return written, how
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def art_units(ctx: Context) -> list[str]:
|
|
532
|
+
"""Unit paths that have card art: committed outputs or an art source."""
|
|
533
|
+
root = ctx.root / ctx.project["paths"]["art_output"]
|
|
534
|
+
built = {p.name for p in root.iterdir() if p.is_dir()} if root.is_dir() else set()
|
|
535
|
+
# Card art folders are named by unit id, which may differ from the unit's source path.
|
|
536
|
+
paths, ids = [], set()
|
|
537
|
+
for uid, path in unit_paths_by_id(ctx).items():
|
|
538
|
+
source = ctx.source_dir / path / "art"
|
|
539
|
+
if uid in built or (source / ADOPTION).is_file() or (source / RECOLOR).is_file():
|
|
540
|
+
paths.append(path)
|
|
541
|
+
ids.add(uid)
|
|
542
|
+
unknown = built - ids
|
|
543
|
+
if unknown:
|
|
544
|
+
raise SpriteError(f"card art folders without a unit.json: {sorted(unknown)}")
|
|
545
|
+
return paths
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def verify_art(ctx: Context, unit_paths: list[str] | None) -> list[str]:
|
|
549
|
+
"""Rebuilds card art (and dot references) in memory and compares pixels with the committed files."""
|
|
550
|
+
problems = []
|
|
551
|
+
for path in unit_paths if unit_paths is not None else art_units(ctx):
|
|
552
|
+
unit = load_unit(ctx, path)
|
|
553
|
+
before = len(problems)
|
|
554
|
+
dot = art_source(unit) / DOT_REF
|
|
555
|
+
if dot.is_file():
|
|
556
|
+
try:
|
|
557
|
+
if not same_png(dot.read_bytes(), dot_reference_bytes(ctx, unit)):
|
|
558
|
+
problems.append(f"{path}: {DOT_REF} differs from the rebuild; run: art dot-ref {path} --force")
|
|
559
|
+
except SpriteError as e:
|
|
560
|
+
problems.append(f"{path}: {DOT_REF} rebuild failed: {e}")
|
|
561
|
+
try:
|
|
562
|
+
files, how = art_outputs(ctx, unit)
|
|
563
|
+
except SpriteError as e:
|
|
564
|
+
problems.append(f"{path}: card art rebuild failed: {e}")
|
|
565
|
+
continue
|
|
566
|
+
out = art_output_dir(ctx, unit)
|
|
567
|
+
names = sorted(p.name for p in out.glob("*.png")) if out.is_dir() else []
|
|
568
|
+
if sorted(files) != names:
|
|
569
|
+
problems.append(f"{path}: card art file set differs: committed {names}, rebuilt {sorted(files)}")
|
|
570
|
+
for name in sorted(set(files) & set(names)):
|
|
571
|
+
if not same_png((out / name).read_bytes(), files[name]):
|
|
572
|
+
problems.append(f"{path}: {name} differs from the rebuild ({how})")
|
|
573
|
+
if len(problems) == before:
|
|
574
|
+
print(f"ok {path}: card art {len(files)} files match ({how})")
|
|
575
|
+
return problems
|