diff --git a/docs/running.md b/docs/running.md index f47afea..d898830 100644 --- a/docs/running.md +++ b/docs/running.md @@ -105,7 +105,8 @@ The expected result is a statistics block with no warnings above it. Lint does not catch runtime errors (missing GUI images, display bugs). `--with-test` also writes `game/e2e_test.rpy`, a Ren'Py `testcase` that clicks "Start", advances through the -whole game up to the final card (`label the_end`) and back to the main menu, failing on any +whole game up to the final card (`label the_end`) and back to the main menu (then opens and +closes the Scenes and Credits screens), failing on any exception (`traceback.txt`). Use a throw-away output directory so the test file never ends up in `vn/` or in a build: diff --git a/docs/work-config.md b/docs/work-config.md index f45d745..fa5ed87 100644 --- a/docs/work-config.md +++ b/docs/work-config.md @@ -6,15 +6,16 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill | Table | Keys | |---|---| -| `[work]` | `id`, `title`, `subtitle`, `author`, `translator`, `language` (`es`/`en`, used for the About text), `lyric_voice` (cast id for verse nobody speaks; default `poet_voice`), `end_text`, `menu_bg` (background asset id for the main menu; default: first staged `bg`). | +| `[work]` | `id`, `title`, `subtitle`, `author`, `translator`, `language` (`es`/`en`: About, menu and credits texts), `lyric_voice` (cast id for verse nobody speaks; default `poet_voice`), `end_text`, `menu_bg` (legacy alias of `[ui].main_menu_bg`). | +| `[ui]` | `main_menu_bg` (background asset id of the main menu and, darker, the game menu; default: `[work].menu_bg`, else the first staged `bg`). | | `[source]` | `gutenberg_id`, `url`, `raw_file` (cache path, relative to the work root, gitignored). | | `[scope]` | `start_marker`, `end_marker` (whole stripped lines), `end_occurrence` (1-based, searched after the start; the end marker itself is excluded). | | `[speakers]` | Speaker heading as printed (upper case, without its italic note) → cast id. Several headings may share one id (anonymous crowd speakers). A key with punctuation or markup (`"CORO, TUTTI"`) is matched against the whole printed line first. An unknown speaker is a parse error. | -| `[[scenes]]` | `heading` (as printed), `id`, `location`, `time_of_day`, optional `occurrence` and `format` (below). | +| `[[scenes]]` | `heading` (as printed), `id`, `location`, `time_of_day`, optional `occurrence`, `format` (below) and `subtitle` (a short, already localized place/time line shown under the heading on the title card; absent = heading only). | | `[parser]` | `direction_headings`: whole lines in capitals that are stage directions or section titles (`"ENTRA FAUSTO"`), not speakers. Each becomes a `direction` line once the scene's first speech has started (before it, the line is treated as cast/setting). | | `[cast.]` | `name` (shown in the dialogue box), `color`, `sprite` (default `true`; `false` = never drawn), `expressions` (annotation emotion → sprite expression; needs `neutral`). | -| `[staging.]` | `bg` (background shown after the title card), `mode` (`adv` or `nvl`), `cast = { = "left\|center\|right" }` pins sprite characters for the whole scene. | -| `[[cues]]` | `at` (line id; fires right before it) plus any of `bg`, `transition` (`dissolve`, `fade`, `flash`, `slow`), `tint` (`none`, `dark`, `red`), `mode`, `hide_all`, `shake`, `move = { = "" }`. | +| `[staging.]` | `bg` (background shown after the title card), `mode` (`adv` or `nvl`), `cast = { = "left\|center\|right" }` pins sprite characters for the whole scene, `music` (see Audio; ignores the annotation moods for this scene). | +| `[[cues]]` | `at` (line id; fires right before it) plus any of `bg`, `transition` (`dissolve`, `fade`, `flash`, `slow`), `tint` (`none`, `dark`, `red`), `mode`, `hide_all`, `shake`, `move = { = "" }`, `music` (see Audio; applies from that line until the next cue or the scene end). | | `[[overrides]]` | `from`, `to` (inclusive line ids in one scene), `emotion`: forces the emotion before expression mapping. | ### Text structure @@ -48,3 +49,35 @@ Asset ids (`bg_*`, sprite names) and the art styles (`styles`, `default_style`, label and prompts) are defined in the work's `assets/assets.json` (manifest v2, see [running.md](running.md)); a missing image is replaced by a placeholder. Style names and labels are work data: nothing about them is hard-coded in the pipeline. + +### Audio + +`vnpipe renpy` copies `/audio/**/*.ogg` into `game/audio/` (subdirectories kept; other +files such as `credits.toml` are not copied). Music is chosen per line from the annotation +mood (`ann.music`), unless overridden: + +- `audio//*.ogg`: the mood plays its tracks as a looping playlist (sorted by path). + A lone `audio/.ogg` is a one-track mood. A mood without audio keeps what plays. +- `[staging.].music` and the cue key `music` take `""`, `"track:"` (a single looping file, e.g. `track:scenes/x.ogg`) or `"none"` (silence). + A scene override replaces the annotation moods for that scene; a cue switches from its line on. + `"auto"` (cues only) hands control back to the annotation moods. +- A track that is already playing is never restarted (`if_changed`); the first music statement + of each scene is always emitted so a scene entered from the scene select has music. +- Unknown `track:` paths, and moods with no audio when the work has audio, are errors. + +### Menus, credits and reading comfort + +- **Main menu**: the `[ui].main_menu_bg` background, darkened, with `[work].title` large and + `[work].subtitle` below it; entries Start, Scenes, Load, Preferences, About, Credits, Help, Quit. + The game menu uses the same background, darker. +- **Scenes** (main menu only): every scene the player has reached (a persistent set updated + when the scene starts), listed by heading; selecting one starts the game from that scene. + Unreached scenes show as an em dash. A heading shared by several scenes is told apart by + the scene's `subtitle` (else its number). +- **Credits**: text author/translator/Gutenberg source from `[work]` and `[source]`; the art + line from the manifest's renditions (non-placeholder `source`, e.g. "ChatGPT (OpenAI)"); + the music from `/audio/credits.toml` (`[[track]]` with `file`, `attribution`; only + tracks whose file exists). Attributions are printed verbatim. Labels follow `[work].language`. +- Defaults: `preferences.text_cps = 40`, `afm_time = 15`, `window auto`, a blinking + click-to-continue arrow. Verse boxes stay at 4 lines; NVL keeps stanza pages. diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py index 78eb170..d4fee44 100644 --- a/src/vnpipe/renpy_gen.py +++ b/src/vnpipe/renpy_gen.py @@ -12,6 +12,7 @@ import argparse import hashlib import json import shutil +import tomllib from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -54,11 +55,42 @@ TINTS = ("none", "dark", "red") DEFAULT_LYRIC_VOICE = "poet_voice" DEFAULT_END_TEXT = "Continuará…" MENU_BG_FALLBACK = "gui/main_menu.png" +MUSIC_FADE = "fadeout 1.0 fadein 1.0" +UNKNOWN_MUSIC = "?" # what plays is not known statically (start of a scene: it may be entered +# from the main menu), so the first music statement of every scene is always emitted ABOUT_LABELS = { "es": ("Texto", "Traducción", "Adaptación a novela visual generada con vnpipe."), "en": ("Text", "Translation", "Visual novel adaptation generated with vnpipe."), } +# Menu/credits strings per work language: scenes, credits, text, translation, source, music, +# illustrations, "illustrations generated with X", Gutenberg line, "no scene reached yet". +UI_LABELS = { + "es": { + "scenes": "Escenas", + "credits": "Créditos", + "text": "Texto", + "translation": "Traducción", + "source": "Fuente", + "music": "Música", + "art": "Ilustraciones", + "art_with": "Ilustraciones generadas con {}", + "gutenberg": "Proyecto Gutenberg, n.º {id}", + }, + "en": { + "scenes": "Scenes", + "credits": "Credits", + "text": "Text", + "translation": "Translation", + "source": "Source", + "music": "Music", + "art": "Illustrations", + "art_with": "Illustrations generated with {}", + "gutenberg": "Project Gutenberg #{id}", + }, +} +ART_SOURCE_NAMES = {"chatgpt-web": "ChatGPT (OpenAI)"} # manifest `source` -> display name +LOCKED_SCENE = "—" # (preferences title and picker heading, picker hint) per work language ART_STYLE_LABELS = { "es": ("Estilo visual", "Puedes cambiarlo más tarde en Preferencias."), @@ -99,6 +131,55 @@ def bg_image_name(asset_id: str) -> str: return "bg " + asset_id.removeprefix("bg_") +# --- audio ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Audio: + """The OGG files shipped in ``game/audio/``, as paths relative to ``game/``.""" + + moods: dict[str, list[str]] = field(default_factory=dict) # mood -> tracks (sorted) + files: frozenset[str] = frozenset() + + +def scan_audio(out: Path) -> Audio: + """``audio//*.ogg`` is a mood playlist; ``audio/.ogg`` a one-track mood.""" + game = out / "game" + root = game / "audio" + if not root.is_dir(): + return Audio() + paths = sorted(p.relative_to(game).as_posix() for p in root.rglob("*.ogg")) + moods: dict[str, list[str]] = {} + for rel in paths: + parts = rel.split("/")[1:] + mood = parts[0] if len(parts) > 1 else Path(parts[0]).stem + moods.setdefault(mood, []).append(rel) + return Audio(moods, frozenset(paths)) + + +def copy_audio(work: Work, out: Path) -> list[Path]: + """Copy ``/audio/**/*.ogg`` into ``game/audio/`` keeping subdirectories.""" + src_root = work.path("audio") + if not src_root.is_dir(): + return [] # no work audio: leave whatever the project already holds + dest_root = out / "game" / "audio" + shutil.rmtree(dest_root, ignore_errors=True) + written = [] + for src in sorted(src_root.rglob("*.ogg")): + dest = dest_root / src.relative_to(src_root) + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dest) + written.append(dest) + return written + + +def check_music_spec(spec: Any, where: str, allow_auto: bool) -> None: + if not isinstance(spec, str) or not spec or spec == "track:": + raise ValueError(f"{where}: music must be a mood, 'track:' or 'none'") + if spec == "auto" and not allow_auto: + raise ValueError(f"{where}: music 'auto' is only valid in a cue") + + # --- annotations ---------------------------------------------------------------- @@ -241,6 +322,10 @@ class Box: is_direction: bool = False +def _playlist(files: list[str]) -> str: + return "[" + ", ".join(_plain_quote(f) for f in files) + "]" + + def _is_direction(line: dict[str, Any]) -> bool: return line["kind"] == "direction" or line["ann"]["kind"] == "stage_direction" @@ -249,18 +334,23 @@ class SceneWriter: """Turns one scene's lines into Ren'Py statements, tracking staging state.""" def __init__( - self, work: Work, scene: dict[str, Any], moods: set[str], music_state: dict[str, str | None] + self, work: Work, scene: dict[str, Any], audio: Audio, music_state: dict[str, str | None] ): self.work = work self.scene = scene - self.moods = moods + self.audio = audio self.voice = lyric_voice(work) self.cues = {c["at"]: c for c in work.data.get("cues", [])} staging = work.data.get("staging", {}).get(scene["id"], {}) self.mode: str = staging.get("mode", "adv") self.bg: str | None = staging.get("bg") self.tint = "none" - self.music_state = music_state # {'playing': mood}, shared across scenes + self.music_state = music_state # {'playing': key}, shared across scenes + music_state["playing"] = UNKNOWN_MUSIC + # scene-wide or cue-set music; None = follow the annotation moods + self.music_spec: str | None = staging.get("music") + if self.music_spec == "auto": + self.music_spec = None self.shown: dict[str, str] = {} # character -> expression currently shown self.pinned: dict[str, str] = dict(staging.get("cast", {})) # always on stage in ADV self.positions: dict[str, str] = dict(self.pinned) # character -> position in this scene @@ -304,6 +394,8 @@ class SceneWriter: if transition not in TRANSITIONS: raise ValueError(f"cue at {cue['at']}: unknown transition {transition!r}") self.emit(f"with {TRANSITIONS[transition]}") + if "music" in cue: + self.music_spec = None if cue["music"] == "auto" else cue["music"] if cue.get("shake"): self.emit("show layer master at vn_shake") moved = False @@ -358,7 +450,7 @@ class SceneWriter: first, last = box.lines[0], box.lines[-1] ids = first["id"] if first is last else f"{first['id']} .. {last['id']}" self.emit(f"# {ids}") - self.music(first["ann"].get("music")) + self.music(self.music_spec or first["ann"].get("music")) if self.mode == "adv": self.stage(box) text = "\\n".join(escape_text(line["text"]) for line in box.lines) @@ -367,16 +459,32 @@ class SceneWriter: if self.mode == "nvl": self.emit("nvl clear") - def music(self, mood: str | None) -> None: - if mood is None: - return - if mood == "none": - if self.music_state["playing"]: + def music(self, spec: str | None) -> None: + """Play/stop for a mood, ``track:`` or ``none``; never restarts what already plays.""" + if spec is None or (not self.audio.files and spec != "none"): + return # nothing to play (a work without audio) + if spec == "none": + if self.music_state["playing"] is not None: self.emit("stop music fadeout 1.0") self.music_state["playing"] = None - elif mood in self.moods and self.music_state["playing"] != mood: - self.emit(f'play music "audio/{mood}.ogg" fadeout 1.0 fadein 1.0') - self.music_state["playing"] = mood + return + if spec.startswith("track:"): + rel = "audio/" + spec.removeprefix("track:") + if rel not in self.audio.files: + raise ValueError(f"{self.scene['id']}: music track {rel!r} not found in audio/") + files = [rel] + else: + files = self.audio.moods.get(spec, []) + if not files: + if self.audio.moods and (self.music_spec == spec): + raise ValueError(f"{self.scene['id']}: no audio for music mood {spec!r}") + return # annotation mood without audio: keep what plays + if self.music_state["playing"] == spec: + return + target = _plain_quote(files[0]) if len(files) == 1 else _playlist(files) + # if_changed: no restart if the engine already plays it (e.g. entered via scene select) + self.emit(f"play music {target} {MUSIC_FADE} if_changed") + self.music_state["playing"] = spec # -- sprites --------------------------------------------------------------------- @@ -420,6 +528,8 @@ class SceneWriter: def render(self) -> list[str]: scene = self.scene self.out.append(f"label scene_{scene['id']}:") + self.emit(f'$ vn_mark_scene("scene_{scene["id"]}")') # unlocks it in the scene select + self.emit("window auto") # also when entered from the scene select, not via `start` self.emit("scene black") self.emit(f"show card_{scene['id']} at truecenter") self.emit("with fade") @@ -449,7 +559,11 @@ def validate_staging(work: Work, annotated: dict[str, Any]) -> None: raise ValueError(f"[staging.{sid}].cast: unknown character {cid!r}") if pos not in VALID_POSITIONS: raise ValueError(f"[staging.{sid}].cast: unknown position {pos!r}") + if "music" in cfg: + check_music_spec(cfg["music"], f"[staging.{sid}]", allow_auto=False) for cue in work.data.get("cues", []): + if "music" in cue: + check_music_spec(cue["music"], f"cue at {cue['at']}", allow_auto=True) for cid, pos in cue.get("move", {}).items(): if cid not in cast: raise ValueError(f"cue at {cue['at']}: move of unknown character {cid!r}") @@ -477,7 +591,7 @@ def apply_overrides(work: Work, annotated: dict[str, Any]) -> dict[str, Any]: return result -def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str: +def render_script(work: Work, annotated: dict[str, Any], audio: Audio | None = None) -> str: validate_staging(work, annotated) annotated = apply_overrides(work, annotated) out = [ @@ -490,9 +604,10 @@ def render_script(work: Work, annotated: dict[str, Any], moods: set[str]) -> str ] known = {c["at"] for c in work.data.get("cues", [])} seen: set[str] = set() - music_state: dict[str, str | None] = {"playing": None} + audio = audio or Audio() + music_state: dict[str, str | None] = {"playing": UNKNOWN_MUSIC} for scene in annotated["scenes"]: - out.extend(SceneWriter(work, scene, moods, music_state).render()) + out.extend(SceneWriter(work, scene, audio, music_state).render()) seen |= {line["id"] for line in scene["lines"]} missing = known - seen if missing: @@ -595,15 +710,16 @@ testsuite global: testcase default: $ _test.transition_timeout = 0.05 $ _test.timeout = 30.0 + $ preferences.text_cps = 0 pause 1.0 click "Start" @@PICK@@ advance until eval (e2e_state["end"]) timeout 900 advance until screen "main_menu" timeout 60 - assert eval (e2e_state["end"]) +@@MENUS@@ assert eval (e2e_state["end"]) """ -def render_e2e(styles: dict[str, Any]) -> str: +def render_e2e(styles: dict[str, Any], ui: dict[str, str]) -> 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 = "" @@ -615,7 +731,17 @@ def render_e2e(styles: dict[str, Any]) -> str: f" click {_plain_quote(cfg['label'])}\n" f" assert eval (persistent.art_style == {sid!r})\n" ) - return E2E_TESTCASE.replace("@@PICK@@", pick) + menus = ( + f" click {_plain_quote(ui['credits'])}\n" + ' assert screen "vn_credits"\n' + ' click "Return"\n' + ' assert screen "main_menu"\n' + f" click {_plain_quote(ui['scenes'])}\n" + ' assert screen "vn_scene_select"\n' + ' click "Return"\n' + ' assert screen "main_menu"\n' + ) + return E2E_TESTCASE.replace("@@PICK@@", pick).replace("@@MENUS@@", menus) # --- static project files ----------------------------------------------------------------- @@ -636,6 +762,7 @@ def render_characters(work: Work) -> str: props.append(f"what_color={_plain_quote(color)}") if cid == "narrator": props.append("what_italic=True") + props += ['ctc="vn_ctc"', 'ctc_position="nestled"'] adv = ", ".join([who, *props]) nvl_props = ["kind=nvl", *props] if not name: @@ -646,12 +773,28 @@ def render_characters(work: Work) -> str: return "\n".join(out) -def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, str]: - cards = {f"card_{sc['id']}": sc["heading"] for sc in annotated["scenes"]} - cards["card_end"] = work.data["work"].get("end_text", DEFAULT_END_TEXT) +def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, tuple[str, str | None]]: + """Image name -> (heading, optional subtitle line: place/time, from ``[[scenes]].subtitle``).""" + subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])} + cards: dict[str, tuple[str, str | None]] = { + f"card_{sc['id']}": (sc["heading"], subtitles.get(sc["id"])) for sc in annotated["scenes"] + } + cards["card_end"] = (work.data["work"].get("end_text", DEFAULT_END_TEXT), None) return cards +def render_card(heading: str, subtitle: str | None) -> str: + """A heading, plus a smaller italic line below it when the scene has a subtitle.""" + props = "size=60, text_align=0.5" + if not subtitle: + return f'Text("{escape_text(heading)}", {props})' + sub_props = 'size=30, italic=True, color="#c9a25b", text_align=0.5' + return ( + f'VBox(Text("{escape_text(heading)}", {props}, xalign=0.5), ' + f'Text("{escape_text(subtitle)}", {sub_props}, xalign=0.5), spacing=28)' + ) + + 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] @@ -666,10 +809,10 @@ def render_image_entry(e: ImageEntry) -> str: return f"image {e.name} = ConditionSwitch({', '.join(parts)})" -def render_images(entries: list[ImageEntry], cards: dict[str, str]) -> str: +def render_images(entries: list[ImageEntry], cards: dict[str, tuple[str, str | None]]) -> 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 name, (heading, subtitle) in cards.items(): # title cards: plain images, not `show text` + out.append(f"image {name} = {render_card(heading, subtitle)}") out.extend(render_image_entry(e) for e in entries) out.append("") return "\n".join(out) @@ -687,6 +830,94 @@ def _about(work: Work) -> str: return "\\n\\n".join(escape_text(p) for p in parts if p) +def ui_labels(work: Work) -> dict[str, str]: + return UI_LABELS.get(work.data["work"].get("language", "es"), UI_LABELS["en"]) + + +def _markup(text: str) -> str: + """Escape Ren'Py text markup only (for strings shown by `text`, not quoted in a script).""" + return text.replace("[", "[[").replace("{", "{{") + + +def credit_tracks(work: Work) -> list[dict[str, Any]]: + """Tracks of ``/audio/credits.toml`` whose file ships with the game.""" + path = work.path("audio/credits.toml") + if not path.is_file(): + return [] + with path.open("rb") as fh: + tracks = tomllib.load(fh).get("track", []) + return [t for t in tracks if work.path(t["file"]).is_file()] + + +def art_sources(manifest: dict[str, Any] | None) -> list[str]: + """Display names of the generators behind the shipped (non-placeholder) renditions.""" + found = set() + for asset in (manifest or {}).get("assets", []): + for rendition in asset["renditions"].values(): + source = rendition.get("source") + if source and source != "placeholder" and rendition["status"] != "placeholder": + found.add(ART_SOURCE_NAMES.get(source, source)) + return sorted(found) + + +def credits_sections(work: Work, manifest: dict[str, Any] | None) -> list[tuple[str, list[str]]]: + info = work.data["work"] + ui = ui_labels(work) + sections: list[tuple[str, list[str]]] = [] + text = [info["author"]] if info.get("author") else [] + if info.get("translator"): + text.append(f"{ui['translation']}: {info['translator']}") + gutenberg = work.data.get("source", {}).get("gutenberg_id") + if gutenberg: + text.append( + f"{ui['source']}: {ui['gutenberg'].format(id=gutenberg)}" + f" (https://www.gutenberg.org/ebooks/{gutenberg})" + ) + if text: + sections.append((ui["text"], text)) + sources = art_sources(manifest) + if sources: + sections.append((ui["art"], [ui["art_with"].format(", ".join(sources))])) + tracks = credit_tracks(work) + if tracks: # attributions are printed verbatim (CC BY-SA requires them) + sections.append((ui["music"], [t["attribution"] for t in tracks])) + about_tail = ABOUT_LABELS.get(info.get("language", "es"), ABOUT_LABELS["en"])[2] + sections.append(("vnpipe", [about_tail])) + return [(title, [_markup(e) for e in entries]) for title, entries in sections] + + +def scene_menu_titles(work: Work, annotated: dict[str, Any]) -> list[tuple[str, str]]: + """(label, title) per scene; a repeated heading gets its subtitle, else its number.""" + subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])} + headings = [sc["heading"] for sc in annotated["scenes"]] + seen: dict[str, int] = {} + result = [] + for sc in annotated["scenes"]: + title = sc["heading"] + if headings.count(title) > 1: + seen[title] = seen.get(title, 0) + 1 + title += f" ({subtitles.get(sc['id']) or seen[title]})" + result.append((f"scene_{sc['id']}", _markup(title))) + return result + + +def render_menu_data(work: Work, annotated: dict[str, Any], manifest: dict[str, Any] | None) -> str: + def py(value: Any) -> str: # JSON strings are valid Python literals + return json.dumps(value, ensure_ascii=False) + + subtitle = _markup(work.data["work"].get("subtitle", "")) + return "\n".join( + [ + "## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", + "", + f"define vn_subtitle = {py(subtitle)}", + f"define vn_scenes = {py(scene_menu_titles(work, annotated))}", + f"define vn_credits = {py(credits_sections(work, manifest))}", + "", + ] + ) + + def _substitute(text: str, values: dict[str, str]) -> str: for key, value in values.items(): text = text.replace(f"@@{key}@@", value) @@ -700,11 +931,6 @@ def write_text(path: Path, text: str) -> None: path.write_text(text, encoding="utf-8", newline="\n") -def _audio_moods(out: Path) -> set[str]: - audio = out / "game" / "audio" - return {p.stem for p in audio.glob("*.ogg")} if audio.is_dir() else set() - - def generate( work: Work, annotated: dict[str, Any], out: Path, with_test: bool = False ) -> list[Path]: @@ -721,13 +947,18 @@ def generate( # GUI template: copy binaries, substitute tokens in .rpy files. menu_bg = MENU_BG_FALLBACK staging = work.data.get("staging", {}) - first_bg = info.get("menu_bg") or next((c["bg"] for c in staging.values() if c.get("bg")), None) + first_bg = ( + work.data.get("ui", {}).get("main_menu_bg") + or 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"] ) + ui = ui_labels(work) values = { "ART_STYLES": repr([(sid, cfg["label"]) for sid, cfg in styles.items()]), "DEFAULT_STYLE": default_style, @@ -739,6 +970,9 @@ def generate( "BUILD_NAME": f"{info['id']}-vn", "SAVE_DIR": f"{info['id']}-vn", "MENU_BG": menu_bg, + "UI_SCENES": ui["scenes"], + "UI_CREDITS": ui["credits"], + "LOCKED": LOCKED_SCENE, } written: list[Path] = [] for src in sorted((TEMPLATE_DIR / "game").rglob("*")): @@ -758,15 +992,17 @@ def generate( if not dest.exists(): # never override an image shipped by the template img.save(dest, "PNG") written.append(dest) + written.extend(copy_audio(work, out)) test_file = game / E2E_FILE test_file.unlink(missing_ok=True) if with_test: - write_text(test_file, render_e2e(styles)) + write_text(test_file, render_e2e(styles, ui)) written.append(test_file) for name, text in ( ("characters.rpy", render_characters(work)), ("images.rpy", render_images(entries, title_cards(work, annotated))), - ("script.rpy", render_script(work, annotated, _audio_moods(out))), + ("menu_data.rpy", render_menu_data(work, annotated, manifest)), + ("script.rpy", render_script(work, annotated, scan_audio(out))), ): write_text(game / name, text) written.append(game / name) diff --git a/src/vnpipe/renpy_templates/game/menus.rpy b/src/vnpipe/renpy_templates/game/menus.rpy new file mode 100644 index 0000000..6b3faca --- /dev/null +++ b/src/vnpipe/renpy_templates/game/menus.rpy @@ -0,0 +1,68 @@ +## Scene select and credits screens, reached from the main menu. The data they show +## (`vn_scenes`, `vn_credits`) is generated in menu_data.rpy; static otherwise. + +## Labels of the scenes the player has reached; updated when a scene starts. +default persistent.vn_seen_scenes = set() + +init python: + def vn_mark_scene(label): + if label not in persistent.vn_seen_scenes: + persistent.vn_seen_scenes.add(label) + renpy.save_persistent() + +screen vn_scene_select(): + + tag menu + + use game_menu("@@UI_SCENES@@", scroll="viewport"): + + style_prefix "vn_scenes" + + vbox: + spacing 6 + + for scene_label, scene_title in vn_scenes: + if scene_label in persistent.vn_seen_scenes: + textbutton scene_title action Start(scene_label) + else: + textbutton "@@LOCKED@@" action NullAction() sensitive False + +style vn_scenes_button is gui_button +style vn_scenes_button_text is gui_button_text + +style vn_scenes_button: + properties gui.button_properties("navigation_button") + xalign 0.0 + +style vn_scenes_button_text: + properties gui.text_properties("navigation_button") + xalign 0.0 + size 30 + +screen vn_credits(): + + tag menu + + use game_menu("@@UI_CREDITS@@", scroll="viewport"): + + style_prefix "vn_credits" + + vbox: + spacing 6 + + for section_title, entries in vn_credits: + null height 20 + label section_title + for entry in entries: + text entry + +style vn_credits_label is gui_label +style vn_credits_label_text is gui_label_text +style vn_credits_text is gui_text + +style vn_credits_label_text: + size gui.label_text_size + +style vn_credits_text: + size 26 + xmaximum 1100 diff --git a/src/vnpipe/renpy_templates/game/options.rpy b/src/vnpipe/renpy_templates/game/options.rpy index 8d12ee3..ef91a3d 100644 --- a/src/vnpipe/renpy_templates/game/options.rpy +++ b/src/vnpipe/renpy_templates/game/options.rpy @@ -46,7 +46,7 @@ define build.name = "@@BUILD_NAME@@" ## appropriate mixer. define config.has_sound = False -define config.has_music = False +define config.has_music = True define config.has_voice = True @@ -119,7 +119,7 @@ define config.window_hide_transition = Dissolve(.2) ## Controls the default text speed. The default, 0, is infinite, while any other ## number is the number of characters per second to type out. -default preferences.text_cps = 0 +default preferences.text_cps = 40 ## The default auto-forward delay. Larger numbers lead to longer waits, with 0 diff --git a/src/vnpipe/renpy_templates/game/screens.rpy b/src/vnpipe/renpy_templates/game/screens.rpy index 43dbeb7..7705f0c 100644 --- a/src/vnpipe/renpy_templates/game/screens.rpy +++ b/src/vnpipe/renpy_templates/game/screens.rpy @@ -301,6 +301,8 @@ screen navigation(): textbutton _("Start") action Start() + textbutton "@@UI_SCENES@@" action ShowMenu("vn_scene_select") + else: textbutton _("History") action ShowMenu("history") @@ -321,6 +323,8 @@ screen navigation(): textbutton _("About") action ShowMenu("about") + textbutton "@@UI_CREDITS@@" action ShowMenu("vn_credits") + if renpy.variant("pc") or (renpy.variant("web") and not renpy.variant("mobile")): ## Help isn't necessary or relevant to mobile devices. @@ -357,12 +361,14 @@ screen main_menu(): add gui.main_menu_background - ## This empty frame darkens the main menu. + ## Darkens the background so the title reads well. + add Solid("#000000a8") + + ## The left strip behind the navigation. frame: style "main_menu_frame" - ## The use statement includes another screen inside this one. The actual - ## contents of the main menu are in the navigation screen. + ## The actual contents of the main menu are in the navigation screen. use navigation if gui.show_name: @@ -373,6 +379,10 @@ screen main_menu(): text "[config.name!t]": style "main_menu_title" + if vn_subtitle: + text "[vn_subtitle!t]": + style "main_menu_subtitle" + text "[config.version]": style "main_menu_version" @@ -381,6 +391,7 @@ style main_menu_frame is empty style main_menu_vbox is vbox style main_menu_text is gui_text style main_menu_title is main_menu_text +style main_menu_subtitle is main_menu_text style main_menu_version is main_menu_text style main_menu_frame: @@ -390,20 +401,35 @@ style main_menu_frame: background "gui/overlay/main_menu.png" style main_menu_vbox: - xalign 1.0 - xoffset -30 - xmaximum 1200 - yalign 1.0 - yoffset -30 + xpos 420 + xsize 1500 + yalign 0.42 + spacing 36 style main_menu_text: properties gui.text_properties("main_menu", accent=True) style main_menu_title: properties gui.text_properties("title") + size 132 + kerning 10 + xalign 0.5 + text_align 0.5 + color "#efe6d2" + outlines [(4, "#000000b0", 0, 3)] + +style main_menu_subtitle: + size 46 + italic True + kerning 3 + xalign 0.5 + text_align 0.5 + color "#c9a25b" + outlines [(3, "#000000b0", 0, 2)] style main_menu_version: properties gui.text_properties("version") + xalign 0.5 ## Game Menu screen ############################################################ @@ -424,6 +450,9 @@ screen game_menu(title, scroll=None, yinitial=0.0, spacing=0): else: add gui.game_menu_background + ## The game menu is darker than the main menu so text stays legible. + add Solid("#000000d0") + frame: style "game_menu_outer_frame" diff --git a/src/vnpipe/renpy_templates/game/support.rpy b/src/vnpipe/renpy_templates/game/support.rpy index c5b21f9..59ad80a 100644 --- a/src/vnpipe/renpy_templates/game/support.rpy +++ b/src/vnpipe/renpy_templates/game/support.rpy @@ -36,3 +36,13 @@ init python: "fonts/RobotoSlab-Bold.ttf", False, False) define vn_move = MoveTransition(0.8) + +## Click-to-continue indicator: a blinking arrow at the end of the text (every Character +## uses it, see characters.rpy). +transform vn_ctc_blink: + alpha 1.0 + linear 0.7 alpha 0.2 + linear 0.7 alpha 1.0 + repeat + +image vn_ctc = At(Text("▾", font="DejaVuSans.ttf", size=34, color="#c9a25b"), vn_ctc_blink) diff --git a/tests/test_renpy_gen.py b/tests/test_renpy_gen.py index 4471a77..85e6343 100644 --- a/tests/test_renpy_gen.py +++ b/tests/test_renpy_gen.py @@ -155,8 +155,12 @@ def test_sprite_false_never_shown(script): def test_characters_and_images(project): chars = (project / "game/characters.rpy").read_text(encoding="utf-8") - assert 'define c_director = Character("El Director", who_color="#c9a25b")' in chars + assert ( + 'define c_director = Character("El Director", who_color="#c9a25b", ' + 'ctc="vn_ctc", ctc_position="nestled")' in chars + ) assert 'define c_director_nvl = Character("El Director", kind=nvl' in chars + assert chars.count('ctc="vn_ctc"') == chars.count("Character(") assert "define c_narrator = Character(None, what_color=" in chars assert "what_italic=True" in chars nameless_nvl = next(ln for ln in chars.split("\n") if ln.startswith("define c_poet_voice_nvl")) @@ -194,7 +198,7 @@ def test_music_only_when_audio_exists(work, annotated, tmp_path): (out / "game/audio/sacred.ogg").write_bytes(b"OggS") renpy_gen.generate(work, annotated, out) text = (out / "game/script.rpy").read_text(encoding="utf-8") - assert 'play music "audio/sacred.ogg" fadeout 1.0 fadein 1.0' in text + assert 'play music "audio/sacred.ogg" fadeout 1.0 fadein 1.0 if_changed' in text assert "stop music fadeout 1.0" in text # mood "none" on the Lord's first line assert (out / "game/audio/sacred.ogg").is_file() # regeneration keeps user audio @@ -203,14 +207,14 @@ def test_unknown_cue_target_fails(work, annotated): broken = json.loads(json.dumps(annotated)) broken["scenes"][1]["lines"] = broken["scenes"][1]["lines"][:5] with pytest.raises(ValueError, match="unknown line ids"): - renpy_gen.render_script(work, broken, set()) + renpy_gen.render_script(work, broken) def test_unknown_speaker_fails(work, annotated): broken = json.loads(json.dumps(annotated)) broken["scenes"][1]["lines"][1]["ann"]["speaker"] = "ghost" with pytest.raises(ValueError, match="ghost"): - renpy_gen.render_script(work, broken, set()) + renpy_gen.render_script(work, broken) def tree(root: Path) -> dict[str, bytes]: @@ -252,7 +256,7 @@ def test_pinned_cast(work, annotated): data = json.loads(json.dumps(work.data)) data["staging"]["talk"]["cast"] = {"poet": "left", "director": "center"} pinned = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(pinned, annotated, set()), "talk") + block = scene_block(renpy_gen.render_script(pinned, annotated), "talk") first_box = block.index("# talk_0002 .. talk_0005") assert "show poet neutral at vn_left" in block[first_box:] assert any(ln.startswith("show director") and ln.endswith("vn_center") for ln in block) @@ -263,7 +267,7 @@ def test_stage_direction_keeps_on_stage(work, annotated): ann = json.loads(json.dumps(annotated)) direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010") direction["ann"]["on_stage"] = [] - block = scene_block(renpy_gen.render_script(work, ann, set()), "talk") + block = scene_block(renpy_gen.render_script(work, ann), "talk") i = block.index('c_narrator "Se aleja."') assert not any(ln.startswith("hide ") for ln in block[i - 3 : i]) @@ -272,22 +276,20 @@ def test_cue_move(work, annotated): data = json.loads(json.dumps(work.data)) data["cues"][0]["move"] = {"poet": "left"} moved = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") + block = scene_block(renpy_gen.render_script(moved, annotated), "talk") # sprites are hidden by that cue's hide_all, so nothing to slide; position is updated assert "with vn_move" not in block data["cues"][0].pop("hide_all") data["cues"][0]["move"] = {"poet": "left"} moved = type(work)(root=work.root, data=data) - block = scene_block(renpy_gen.render_script(moved, annotated, set()), "talk") + block = scene_block(renpy_gen.render_script(moved, annotated), "talk") i = block.index("with vn_move") assert block[i - 1].startswith("show poet ") and block[i - 1].endswith("vn_left") def test_overrides(work, annotated): ov = [{"from": "talk_0011", "to": "talk_0013", "emotion": "angry"}] - block = scene_block( - renpy_gen.render_script(_with_cfg(work, overrides=ov), annotated, set()), "talk" - ) + block = scene_block(renpy_gen.render_script(_with_cfg(work, overrides=ov), annotated), "talk") assert "show poet indignant at vn_right" in block[block.index("# talk_0011 .. talk_0013") :] @@ -302,22 +304,22 @@ def test_overrides(work, annotated): ) def test_invalid_overrides(work, annotated, change, match): with pytest.raises(ValueError, match=match): - renpy_gen.render_script(_with_cfg(work, **change), annotated, set()) + renpy_gen.render_script(_with_cfg(work, **change), annotated) def test_invalid_staging_cast_and_move(work, annotated): data = json.loads(json.dumps(work.data)) data["staging"]["talk"]["cast"] = {"ghost": "left"} with pytest.raises(ValueError, match="ghost"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated) data = json.loads(json.dumps(work.data)) data["staging"]["talk"]["cast"] = {"poet": "up"} with pytest.raises(ValueError, match="position"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated) data = json.loads(json.dumps(work.data)) data["cues"][0]["move"] = {"poet": "nowhere"} with pytest.raises(ValueError, match="position"): - renpy_gen.render_script(type(work)(root=work.root, data=data), annotated, set()) + renpy_gen.render_script(type(work)(root=work.root, data=data), annotated) def test_every_gui_image_exists(project): @@ -391,3 +393,155 @@ def test_cli_defaults_to_current_directory(work, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path / "w") assert cli.main(["renpy"]) == 0 assert (tmp_path / "w/vn/game/script.rpy").is_file() + + +def _audio(): + files = [ + "audio/sacred/a.ogg", + "audio/sacred/b.ogg", + "audio/comic.ogg", + "audio/scenes/x.ogg", + ] + return renpy_gen.Audio( + {"sacred": files[:2], "comic": [files[2]], "scenes": [files[3]]}, frozenset(files) + ) + + +def _music_lines(block): + return [ln for ln in block if "music" in ln] + + +def test_scan_and_copy_audio(work, tmp_path): + root = tmp_path / "w" + (root / "audio/sacred").mkdir(parents=True) + (root / "audio/scenes").mkdir() + for rel in ("sacred/b.ogg", "sacred/a.ogg", "scenes/x.ogg", "comic.ogg"): + (root / "audio" / rel).write_bytes(b"OggS") + (root / "audio/credits.toml").write_text("", encoding="utf-8") + out = tmp_path / "out" + copied = renpy_gen.copy_audio(type(work)(root=root, data=work.data), out) + assert len(copied) == 4 and not (out / "game/audio/credits.toml").exists() + audio = renpy_gen.scan_audio(out) + assert audio.moods["sacred"] == ["audio/sacred/a.ogg", "audio/sacred/b.ogg"] # sorted + assert audio.moods["comic"] == ["audio/comic.ogg"] + assert "audio/scenes/x.ogg" in audio.files + + +def test_mood_directory_is_a_playlist(work, annotated): + block = scene_block(renpy_gen.render_script(work, annotated, _audio()), "lyric") + assert _music_lines(block) == [ + 'play music ["audio/sacred/a.ogg", "audio/sacred/b.ogg"] fadeout 1.0 fadein 1.0 if_changed' + ] + + +def test_scene_music_override_and_no_restart(work, annotated): + # the scene override ignores annotation moods (here a stop on talk_0014) + w = _with_cfg( + work, staging={**work.data["staging"], "talk": {"bg": "bg_theatre", "mode": "adv"}} + ) + w.data["staging"]["talk"]["music"] = "track:scenes/x.ogg" + block = scene_block(renpy_gen.render_script(w, annotated, _audio()), "talk") + assert _music_lines(block) == [ + 'play music "audio/scenes/x.ogg" fadeout 1.0 fadein 1.0 if_changed' + ] # once, not at every box + + +def test_cue_music_and_auto(work, annotated): + cues = [{"at": "talk_0004", "music": "comic"}, {"at": "talk_0014", "music": "auto"}] + w = _with_cfg(work, cues=cues) + block = scene_block(renpy_gen.render_script(w, annotated, _audio()), "talk") + music = _music_lines(block) + # comic from talk_0004 on, until `auto` hands control back to the annotation (stop at 0014) + assert music == [ + 'play music "audio/comic.ogg" fadeout 1.0 fadein 1.0 if_changed', + "stop music fadeout 1.0", + ] + box = next(i for i, ln in enumerate(block) if ln.startswith("#") and "talk_0014" in ln) + assert block.index(music[0]) < box < block.index(music[1]) + + +def test_music_config_errors(work, annotated): + w = _with_cfg(work, cues=[{"at": "talk_0004", "music": "track:nope.ogg"}]) + with pytest.raises(ValueError, match="not found"): + renpy_gen.render_script(w, annotated, _audio()) + w = _with_cfg(work, staging={"talk": {"music": "auto"}}) + with pytest.raises(ValueError, match="only valid in a cue"): + renpy_gen.render_script(w, annotated, _audio()) + w = _with_cfg(work, staging={"talk": {"music": "loud"}}) + with pytest.raises(ValueError, match="no audio for music mood"): + renpy_gen.render_script(w, annotated, _audio()) + + +def _project(work, annotated, tmp_path, **cfg): + out = tmp_path / "p" + renpy_gen.generate(_with_cfg(work, **cfg) if cfg else work, annotated, out) + return out + + +def test_title_card_subtitle(work, annotated, tmp_path): + scenes = [{"heading": "CONVERSACIÓN", "id": "talk", "subtitle": "Escenario · Día"}] + out = _project(work, annotated, tmp_path, scenes=scenes) + images = (out / "game/images.rpy").read_text(encoding="utf-8") + assert 'image card_talk = VBox(Text("CONVERSACIÓN", size=60' in images + assert 'Text("Escenario · Día", size=30, italic=True' in images + assert 'image card_lyric = Text("LÍRICA", size=60, text_align=0.5)' in images # no subtitle + + +def test_scene_labels_and_menus(project, script): + assert 'label scene_talk:\n $ vn_mark_scene("scene_talk")\n window auto' in script + data = (project / "game/menu_data.rpy").read_text(encoding="utf-8") + assert 'define vn_scenes = [["scene_lyric", "LÍRICA"], ["scene_talk", "CONVERSACIÓN"]]' in data + assert 'define vn_subtitle = "Fixture work"' in data + menus = (project / "game/menus.rpy").read_text(encoding="utf-8") + assert "Start(scene_label)" in menus and "@@" not in menus + screens = (project / "game/screens.rpy").read_text(encoding="utf-8") + assert 'textbutton "Escenas" action ShowMenu("vn_scene_select")' in screens + assert 'textbutton "Créditos" action ShowMenu("vn_credits")' in screens + assert "@@" not in screens + + +def test_repeated_headings_are_told_apart(work, annotated): + ann = json.loads(json.dumps(annotated)) + ann["scenes"][1]["heading"] = ann["scenes"][0]["heading"] + scenes = [{"id": "talk", "heading": "x", "subtitle": "Día"}] + titles = renpy_gen.scene_menu_titles(_with_cfg(work, scenes=scenes), ann) + assert [t for _, t in titles] == ["LÍRICA (1)", "LÍRICA (Día)"] + + +def test_credits_from_work_audio_and_manifest(work, tmp_path): + root = tmp_path / "w" + (root / "audio").mkdir(parents=True) + (root / "audio/a.ogg").write_bytes(b"OggS") + (root / "audio/credits.toml").write_text( + '[[track]]\nfile = "audio/a.ogg"\nattribution = "Bach [x]. CC BY-SA 4.0."\n' + '[[track]]\nfile = "audio/missing.ogg"\nattribution = "not shipped"\n', + encoding="utf-8", + ) + data = json.loads(json.dumps(work.data)) + data["source"] = {"gutenberg_id": 42} + w = type(work)(root=root, data=data) + manifest = { + "assets": [ + {"renditions": {"s": {"source": "chatgpt-web", "status": "approved"}}}, + {"renditions": {"s": {"source": "placeholder", "status": "placeholder"}}}, + ] + } + sections = dict(renpy_gen.credits_sections(w, manifest)) + assert sections["Texto"][0] == "A. Author" + assert sections["Texto"][1] == "Traducción: T. Translator" + assert "Proyecto Gutenberg, n.º 42" in sections["Texto"][2] + assert sections["Ilustraciones"] == ["Ilustraciones generadas con ChatGPT (OpenAI)"] + assert sections["Música"] == ["Bach [[x]. CC BY-SA 4.0."] # verbatim, markup-escaped only + + +def test_main_menu_background_from_ui(work, annotated, tmp_path): + out = _project(work, annotated, tmp_path, ui={"main_menu_bg": "bg_theatre"}) + gui = (out / "game/gui.rpy").read_text(encoding="utf-8") + assert 'gui.main_menu_background = "bg theatre"' in gui + + +def test_reading_comfort_defaults(project): + options = (project / "game/options.rpy").read_text(encoding="utf-8") + assert "default preferences.text_cps = 40" in options + assert "default preferences.afm_time = 15" in options + assert "define config.has_music = True" in options