diff --git a/docs/work-config.md b/docs/work-config.md index f45d745..ecfeb75 100644 --- a/docs/work-config.md +++ b/docs/work-config.md @@ -13,8 +13,8 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill | `[[scenes]]` | `heading` (as printed), `id`, `location`, `time_of_day`, optional `occurrence` and `format` (below). | | `[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 +48,19 @@ 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. diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py index 78eb170..c187471 100644 --- a/src/vnpipe/renpy_gen.py +++ b/src/vnpipe/renpy_gen.py @@ -54,6 +54,9 @@ 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."), @@ -99,6 +102,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 +293,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 +305,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 +365,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 +421,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 +430,32 @@ class SceneWriter: if self.mode == "nvl": self.emit("nvl clear") - def music(self, mood: str | None) -> None: - if mood is None: + def music(self, spec: str | None) -> None: + """Play/stop for a mood, ``track:`` or ``none``; never restarts what already plays.""" + if spec is None: return - if mood == "none": - if self.music_state["playing"]: + 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 --------------------------------------------------------------------- @@ -449,7 +528,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 +560,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 +573,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: @@ -700,11 +784,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]: @@ -758,6 +837,7 @@ 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: @@ -766,7 +846,7 @@ def generate( 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))), + ("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/options.rpy b/src/vnpipe/renpy_templates/game/options.rpy index 8d12ee3..621fe2b 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 diff --git a/tests/test_renpy_gen.py b/tests/test_renpy_gen.py index 4471a77..335d361 100644 --- a/tests/test_renpy_gen.py +++ b/tests/test_renpy_gen.py @@ -194,7 +194,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 +203,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 +252,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 +263,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 +272,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 +300,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 +389,80 @@ 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())