feat(renpy): ConditionSwitch images, first-launch style picker and preference

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 04:09:00 +02:00
1 parent 1cf5b1460d
commit 05ce0bca65
4 files changed
+134 -32

No files matched your search

+82 -27
View File
@@ -19,12 +19,12 @@ from typing import Any
from PIL import Image, ImageDraw
from vnpipe import PACKAGE_DIR
from vnpipe.assets import USABLE, load_manifest, placeholder
from vnpipe.assets import load_manifest, placeholder, style_file, usable_rendition
from vnpipe.config import Work, load_work
from vnpipe.schema import validate
TEMPLATE_DIR = PACKAGE_DIR / "renpy_templates"
USABLE_STATUS = USABLE | {"placeholder"}
NO_MANIFEST_STYLE = {"default": {"label": "Default"}} # work without an asset manifest
ADV_MAX_LINES = 4
NVL_MAX_LINES = 8
@@ -59,6 +59,11 @@ ABOUT_LABELS = {
"es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."),
"en": ("Text", "Translation", "Visual novel adaptation generated with vnpipe."),
}
# (preferences title and picker heading, picker hint) per work language
ART_STYLE_LABELS = {
"es": ("Estilo visual", "Puedes cambiarlo más tarde en Preferencias."),
"en": ("Visual style", "You can change this later in Preferences."),
}
# --- text helpers -------------------------------------------------------------
@@ -155,9 +160,11 @@ def annotations_from_parsed(work: Work, parsed: dict[str, Any]) -> dict[str, Any
@dataclass
class ImageEntry:
name: str # Ren'Py image name, e.g. "bg heaven" or "hero neutral"
rel: str # path below game/images/
asset: dict[str, Any]
source: Path | None # file to copy, or None to generate a placeholder
default: str # default style id: always present, the ConditionSwitch fallback
# (style, path below game/images/, file to copy or None for a placeholder), default style
# first, then the other styles with an approved rendition in manifest order
variants: list[tuple[str, str, Path | None]]
def _sprite_asset(character: str, expression: str) -> dict[str, Any]:
@@ -166,16 +173,12 @@ def _sprite_asset(character: str, expression: str) -> dict[str, Any]:
"kind": "sprite",
"character": character,
"expression": expression,
"file": f"sprites/{character}_{expression}.webp",
"renditions": {},
}
def _bg_asset(asset_id: str) -> dict[str, Any]:
return {
"id": asset_id,
"kind": "background",
"file": f"bg/{asset_id.removeprefix('bg_')}.webp",
}
return {"id": asset_id, "kind": "background", "renditions": {}}
def _needed_bg_ids(work: Work) -> list[str]:
@@ -184,8 +187,16 @@ def _needed_bg_ids(work: Work) -> list[str]:
return ids
def art_styles(manifest: dict[str, Any] | None) -> tuple[dict[str, Any], str]:
"""(styles by id, default style id); a single pseudo-style when there is no manifest."""
if manifest is None:
return NO_MANIFEST_STYLE, next(iter(NO_MANIFEST_STYLE))
return manifest["styles"], manifest["default_style"]
def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEntry]:
"""Every image the project declares: manifest assets plus anything the staging needs."""
styles, default = art_styles(manifest)
assets: dict[str, dict[str, Any]] = {}
for asset in (manifest or {}).get("assets", []):
assets[asset["id"]] = asset
@@ -204,12 +215,18 @@ def collect_images(work: Work, manifest: dict[str, Any] | None) -> list[ImageEnt
name = bg_image_name(asset_id)
else:
name = f"{asset['character']} {asset['expression']}"
source = None
if asset.get("status") in USABLE_STATUS and asset.get("file"):
candidate = work.path("assets") / asset["file"]
if candidate.is_file():
source = candidate
entries.append(ImageEntry(name, asset["file"], asset, source))
variants: list[tuple[str, str, Path | None]] = []
for style in [default, *(s for s in styles if s != default)]:
rendition = asset["renditions"].get(style)
rel = (rendition or {}).get("file") or style_file(asset, style)
candidate = work.path("assets") / rel
if style == default:
# the fallback may also be a placeholder; otherwise one is generated
ok = rendition and rendition["status"] in {"processed", "approved", "placeholder"}
variants.append((style, rel, candidate if ok and candidate.is_file() else None))
elif usable_rendition(asset, style) and candidate.is_file():
variants.append((style, rel, candidate))
entries.append(ImageEntry(name, asset, default, variants))
return entries
@@ -467,6 +484,7 @@ def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str
"## Generated by `vnpipe renpy`. Do not edit: regenerate instead.",
"",
"label start:",
" call vn_pick_art_style",
" window auto",
"",
]
@@ -579,12 +597,27 @@ testcase default:
$ _test.timeout = 30.0
pause 1.0
click "Start"
advance until eval (e2e_state["end"]) timeout 900
@@PICK@@ advance until eval (e2e_state["end"]) timeout 900
advance until screen "main_menu" timeout 60
assert eval (e2e_state["end"])
"""
def render_e2e(styles: dict[str, Any]) -> str:
"""The playthrough testcase; with a style choice it also exercises the first-launch picker
(picking the last style, so the non-default switch branch is the one in use)."""
pick = ""
if len(styles) > 1:
sid, cfg = list(styles.items())[-1]
pick = (
" pause 1.0\n"
' assert screen "vn_art_style_picker"\n'
f" click {_plain_quote(cfg['label'])}\n"
f" assert eval (persistent.art_style == {sid!r})\n"
)
return E2E_TESTCASE.replace("@@PICK@@", pick)
# --- static project files -----------------------------------------------------------------
@@ -619,12 +652,25 @@ def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, str]:
return cards
def render_image_entry(e: ImageEntry) -> str:
"""Plain image, or a ConditionSwitch on ``persistent.art_style`` with the default last."""
default_rel = e.variants[0][1]
if len(e.variants) == 1:
return f"image {e.name} = {_plain_quote('images/' + default_rel)}"
parts = []
for style, rel, _ in e.variants[1:]:
parts.append(
f"{_plain_quote(f'persistent.art_style == {style!r}')}, {_plain_quote('images/' + rel)}"
)
parts.append(f'"True", {_plain_quote("images/" + default_rel)}')
return f"image {e.name} = ConditionSwitch({', '.join(parts)})"
def render_images(entries: list[ImageEntry], cards: dict[str, str]) -> str:
out = ["## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", ""]
for name, text in cards.items(): # title cards: plain images, not `show text`
out.append(f'image {name} = Text("{escape_text(text)}", size=60, text_align=0.5)')
for e in entries:
out.append(f"image {e.name} = {_plain_quote('images/' + e.rel)}")
out.extend(render_image_entry(e) for e in entries)
out.append("")
return "\n".join(out)
@@ -678,7 +724,15 @@ def generate(
first_bg = info.get("menu_bg") or next((c["bg"] for c in staging.values() if c.get("bg")), None)
if first_bg:
menu_bg = bg_image_name(first_bg)
styles, default_style = art_styles(manifest)
picker_title, picker_hint = ART_STYLE_LABELS.get(
info.get("language", "es"), ART_STYLE_LABELS["en"]
)
values = {
"ART_STYLES": repr([(sid, cfg["label"]) for sid, cfg in styles.items()]),
"DEFAULT_STYLE": default_style,
"ART_STYLE_TITLE": picker_title,
"ART_STYLE_HINT": picker_hint,
"TITLE": escape_text(info["title"]),
"VERSION": "0.1",
"ABOUT": _about(work),
@@ -707,7 +761,7 @@ def generate(
test_file = game / E2E_FILE
test_file.unlink(missing_ok=True)
if with_test:
write_text(test_file, E2E_TESTCASE)
write_text(test_file, render_e2e(styles))
written.append(test_file)
for name, text in (
("characters.rpy", render_characters(work)),
@@ -718,13 +772,14 @@ def generate(
written.append(game / name)
for e in entries:
dest = game / "images" / e.rel
dest.parent.mkdir(parents=True, exist_ok=True)
written.append(dest)
if e.source:
shutil.copyfile(e.source, dest)
else:
placeholder(e.asset).save(dest, "WEBP", quality=90)
for _, rel, source in e.variants:
dest = game / "images" / rel
dest.parent.mkdir(parents=True, exist_ok=True)
written.append(dest)
if source:
shutil.copyfile(source, dest)
else:
placeholder(e.asset).save(dest, "WEBP", quality=90)
return sorted(written)
@@ -756,6 +756,14 @@ screen preferences():
textbutton _("After Choices") action Preference("after choices", "toggle")
textbutton _("Transitions") action InvertSelected(Preference("transitions", "toggle"))
if len(vn_art_styles) > 1:
vbox:
style_prefix "radio"
label "@@ART_STYLE_TITLE@@"
for style_id, style_label in vn_art_styles:
textbutton style_label action SetField(persistent, "art_style", style_id)
## Additional vboxes of type "radio_pref" or "check_pref" can be
## added here, to add additional creator-defined preferences.
@@ -0,0 +1,39 @@
## Art styles: the player picks one at first launch and can change it in Preferences.
## Every image is a ConditionSwitch on `persistent.art_style` (see images.rpy), so a
## change takes effect on the next interaction without moving anything on stage.
## Static except for the substituted style list; copied by `vnpipe renpy`.
default persistent.art_style = "@@DEFAULT_STYLE@@"
default persistent.art_style_chosen = False
## (style id, label) pairs, in manifest order.
define vn_art_styles = @@ART_STYLES@@
screen vn_art_style_picker():
modal True
add Solid("#000000")
vbox:
xalign 0.5
yalign 0.5
spacing 30
text "@@ART_STYLE_TITLE@@" xalign 0.5 size 60
text "@@ART_STYLE_HINT@@" xalign 0.5 size 28
null height 20
for style_id, style_label in vn_art_styles:
textbutton style_label:
xalign 0.5
action [SetField(persistent, "art_style", style_id),
SetField(persistent, "art_style_chosen", True), Return()]
## Shown once, before the first scene, when there is a choice to make.
label vn_pick_art_style:
if len(vn_art_styles) > 1 and not persistent.art_style_chosen:
scene black
call screen vn_art_style_picker
return
+5 -5
View File
@@ -162,11 +162,11 @@ def test_characters_and_images(project):
nameless_nvl = next(ln for ln in chars.split("\n") if ln.startswith("define c_poet_voice_nvl"))
assert "None" in nameless_nvl and "nvl_thought" in nameless_nvl
images = (project / "game/images.rpy").read_text(encoding="utf-8")
assert 'image bg dedication = "images/bg/dedication.webp"' in images
assert 'image director pleased = "images/sprites/director_pleased.webp"' in images
assert (project / "game/images/sprites/poet_indignant.webp").is_file()
assert (project / "game/images/bg/theatre.webp").is_file()
assert not (project / "game/images/sprites/lord_neutral.webp").exists()
assert 'image bg dedication = "images/bg/default/dedication.webp"' in images
assert 'image director pleased = "images/sprites/default/director_pleased.webp"' in images
assert (project / "game/images/sprites/default/poet_indignant.webp").is_file()
assert (project / "game/images/bg/default/theatre.webp").is_file()
assert not (project / "game/images/sprites/default/lord_neutral.webp").exists()
def test_title_card_images(project):