|
8 | 8 | """ |
9 | 9 |
|
10 | 10 | import json |
| 11 | +import os |
| 12 | +import sys |
| 13 | +import subprocess |
11 | 14 | from pathlib import Path |
12 | 15 |
|
| 16 | +# Windows consoles default to cp949 in a Korean locale; the pipeline's progress |
| 17 | +# logs contain emoji (🔎, ⚠️, …). Without this, the first such print() raises |
| 18 | +# UnicodeEncodeError and bubbles up as a /generate failure. Force UTF-8 so logs |
| 19 | +# never crash a request. |
| 20 | +for _stream in (sys.stdout, sys.stderr): |
| 21 | + try: |
| 22 | + _stream.reconfigure(encoding="utf-8") |
| 23 | + except Exception: |
| 24 | + pass |
| 25 | + |
13 | 26 | from fastapi import FastAPI |
14 | 27 | from fastapi.middleware.cors import CORSMiddleware |
15 | 28 | from pydantic import BaseModel |
|
19 | 32 | CURRENT_DIR = Path(__file__).resolve().parent |
20 | 33 | DB_DIR = CURRENT_DIR / "db" |
21 | 34 | INFO_DIR = CURRENT_DIR / "info" |
| 35 | +RULE_CODES_DIR = DB_DIR / "rule" / "codes" |
| 36 | + |
| 37 | +# The full BAR launcher lives in the bundled v4 project. Its game_simulator |
| 38 | +# converts a config (same JSON shape this backend emits) into a Spring start |
| 39 | +# script and launches spring.exe. It reads its own .env (SPRING_DATADIR, |
| 40 | +# BAR_ENGINE_PATH, GAME_VERSION) via load_dotenv inside main.py. |
| 41 | +V4_DIR = CURRENT_DIR.parent / "minigame_generator_v4" |
| 42 | +SIM_DIR = V4_DIR / "game_simulator" |
| 43 | +SIM_MAIN = SIM_DIR / "main.py" |
22 | 44 |
|
23 | 45 | app = FastAPI(title="RTSGame Minigame Generator", version="0.1.0") |
24 | 46 |
|
@@ -79,6 +101,77 @@ def generate(req: GenerateRequest): |
79 | 101 | return {"error": str(e), "config": None} |
80 | 102 |
|
81 | 103 |
|
| 104 | +class LaunchRequest(BaseModel): |
| 105 | + config: dict |
| 106 | + # "gadget" = run the scenario's own gadgets only (no movement/vlm AI); |
| 107 | + # "movement"/"vlm" enable the v4 experiment gadgets. |
| 108 | + mode: str = "gadget" |
| 109 | + |
| 110 | + |
| 111 | +def _resolve_gadgets(config: dict) -> list: |
| 112 | + """Each customize key corresponds to a rule gadget whose Lua lives at |
| 113 | + db/rule/codes/<key>.lua. The launcher copies these into the engine and |
| 114 | + enables them; the per-key config is delivered via the scenariooptions blob. |
| 115 | + Missing files are skipped (the scenario still launches without them).""" |
| 116 | + gadgets = [] |
| 117 | + for key in (config.get("customize") or {}): |
| 118 | + lua = RULE_CODES_DIR / f"{key}.lua" |
| 119 | + if lua.exists(): |
| 120 | + gadgets.append(str(lua)) |
| 121 | + return gadgets |
| 122 | + |
| 123 | + |
| 124 | +@app.post("/launch") |
| 125 | +def launch(req: LaunchRequest): |
| 126 | + """Launch the generated config in the actual BAR client via the bundled |
| 127 | + v4 game_simulator. Fire-and-forget: spring.exe opens its own window and the |
| 128 | + request returns as soon as the process is spawned.""" |
| 129 | + if not SIM_MAIN.exists(): |
| 130 | + return {"launched": False, "error": f"BAR launcher not found at {SIM_MAIN}"} |
| 131 | + |
| 132 | + config = req.config or {} |
| 133 | + if not config.get("information", {}).get("map_name"): |
| 134 | + return {"launched": False, "error": "config has no information.map_name"} |
| 135 | + |
| 136 | + # Prefer the v4 venv interpreter — it has the deps (PIL/numpy/dotenv) that |
| 137 | + # game_simulator/utils import; fall back to whatever `python` is on PATH. |
| 138 | + venv_py = V4_DIR / ".venv" / "Scripts" / "python.exe" |
| 139 | + python_exe = str(venv_py) if venv_py.exists() else "python" |
| 140 | + |
| 141 | + gen_dir = SIM_DIR / "_generated" |
| 142 | + gen_dir.mkdir(exist_ok=True) |
| 143 | + cfg_path = gen_dir / "launch_config.json" |
| 144 | + with open(cfg_path, "w", encoding="utf-8") as f: |
| 145 | + json.dump(config, f, ensure_ascii=False, indent=2) |
| 146 | + |
| 147 | + gadgets = _resolve_gadgets(config) |
| 148 | + |
| 149 | + cmd = [python_exe, str(SIM_MAIN), "--config", str(cfg_path), "--mode", req.mode] |
| 150 | + if gadgets: |
| 151 | + cmd += ["--gadgets"] + gadgets |
| 152 | + |
| 153 | + log_dir = CURRENT_DIR / "log" |
| 154 | + log_dir.mkdir(exist_ok=True) |
| 155 | + try: |
| 156 | + log_fh = open(log_dir / "launch.log", "a", encoding="utf-8") |
| 157 | + # New process group so the game survives a uvicorn reload/restart. |
| 158 | + creationflags = subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0 |
| 159 | + subprocess.Popen( |
| 160 | + cmd, cwd=str(SIM_DIR), |
| 161 | + stdout=log_fh, stderr=subprocess.STDOUT, |
| 162 | + creationflags=creationflags, |
| 163 | + ) |
| 164 | + except Exception as e: |
| 165 | + return {"launched": False, "error": str(e)} |
| 166 | + |
| 167 | + return { |
| 168 | + "launched": True, |
| 169 | + "mode": req.mode, |
| 170 | + "map": config["information"]["map_name"], |
| 171 | + "gadgets": [Path(g).stem for g in gadgets], |
| 172 | + } |
| 173 | + |
| 174 | + |
82 | 175 | if __name__ == "__main__": |
83 | 176 | import uvicorn |
84 | 177 | uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True) |
0 commit comments