Buckets:
| """THX-01 plays Doom: no vision, no text generation. | |
| Every few game tics the engine state (health, ammo, enemies with bearing / distance / visibility, | |
| items, depth ahead, recent actions) is written as text. THX-01 answers two typed questions in | |
| ONE forward pass: | |
| choice -> which of 7 actions to press | |
| noul -> is an enemy inside the crosshair | |
| The browser shows the game on the left and the model's decisions on the right. | |
| python doom/doom_live.py --model doofz/THX-01 --port 8096 | |
| """ | |
| import argparse, io, json, math, os, queue, sys, threading, time | |
| from collections import Counter, deque | |
| import numpy as np | |
| from PIL import Image | |
| # Option descriptions carry the condition under which each key is right, so the model's job is to | |
| # match the state against them -- the same skill as routing a ticket to the team whose description fits. | |
| ACTIONS = { | |
| "ATTACK": "shoot: the crosshair is ON an enemy", | |
| "TURN_LEFT": "turn left: the nearest visible enemy is to the LEFT", | |
| "TURN_RIGHT": "turn right: the nearest visible enemy is to the RIGHT", | |
| "MOVE_FORWARD": "run forward: no enemy is visible and the way ahead is open", | |
| "MOVE_LEFT": "strafe left: the enemy is to the LEFT", | |
| "MOVE_RIGHT": "strafe right: the enemy is to the RIGHT", | |
| "MOVE_BACKWARD": "step back: a wall is very close ahead", | |
| } | |
| IDLE = { # what to do when nothing is visible, appended to that scenario's idle action | |
| "defend_the_center": ("TURN_LEFT", ", or no enemy is visible"), | |
| "defend_the_line": ("TURN_LEFT", ", or no enemy is visible"), | |
| } | |
| ENEMIES = {"Zombieman", "ShotgunGuy", "ChaingunGuy", "Imp", "Demon", "Spectre", "Cacodemon", "LostSoul", | |
| "HellKnight", "BaronOfHell", "Revenant", "Arachnotron", "Mancubus", "MarineChainsawVzd"} | |
| ITEMS = ("Armor", "Medikit", "Stimpack", "Clip", "Shell", "Health") | |
| SCENARIOS = { | |
| "defend_the_center": ("You are a Doom marine standing in the centre of a round arena. Monsters come from every side.", | |
| "turn to scan for monsters"), | |
| "deadly_corridor": ("You are a Doom marine in a corridor with enemies shooting from both sides. The green armor at the end is the goal.", | |
| "run forward toward the green armor"), | |
| "defend_the_line": ("You are a Doom marine at one end of a hall. Monsters appear at the far end and walk toward you.", | |
| "turn to scan for monsters"), | |
| "basic": ("You are a Doom marine facing a room with one monster on the far wall.", | |
| "strafe left or right until the monster is in the crosshair"), | |
| } | |
| INSTRUCTION = "Which action fits the current situation of the Doom marine?" | |
| THREAT = "Is the crosshair ON an enemy?" | |
| def policy(ans, crit): | |
| """Key to press: fire when the model is confident the crosshair is on an enemy (noul), else its choice.""" | |
| if "ATTACK" in crit and ans["threat"]["noul"] >= 0.5: | |
| return "ATTACK" | |
| return ans["action"]["choice"] | |
| def bearing(px, py, pa, ox, oy): | |
| a = math.degrees(math.atan2(oy - py, ox - px)) - pa | |
| return (a + 180) % 360 - 180 | |
| def describe(game, st, history, stuck, vzd): | |
| hp = game.get_game_variable(vzd.GameVariable.HEALTH) | |
| ammo = game.get_game_variable(vzd.GameVariable.SELECTED_WEAPON_AMMO) | |
| kills = game.get_game_variable(vzd.GameVariable.KILLCOUNT) | |
| me = next((o for o in st.objects if o.name == "DoomPlayer"), None) | |
| seen = {l.object_id for l in (st.labels or [])} | |
| foes, items = [], [] | |
| if me is not None: | |
| for o in st.objects: | |
| if o.name == "DoomPlayer": | |
| continue | |
| d = math.hypot(o.position_x - me.position_x, o.position_y - me.position_y) / 32.0 | |
| b = bearing(me.position_x, me.position_y, me.angle, o.position_x, o.position_y) | |
| side = "ahead" if abs(b) < 12 else ("left" if b > 0 else "right") | |
| if o.name in ENEMIES: | |
| foes.append((not (o.id in seen), d, b, o.name, side)) | |
| elif any(k in o.name for k in ITEMS): | |
| items.append((d, f"{o.name} {d:.0f}m {side} {b:+.0f}deg")) | |
| foes.sort(); items.sort() | |
| if foes: | |
| hidden, d0, b0, n0, _ = foes[0] | |
| if not hidden and abs(b0) <= 6: | |
| aim = f"crosshair: ON {n0} ({b0:+.0f}deg) -> shooting now would hit" | |
| elif not hidden: | |
| aim = f"crosshair: empty; nearest VISIBLE enemy is {abs(b0):.0f}deg to the {'LEFT' if b0 > 0 else 'RIGHT'}" | |
| else: | |
| aim = f"crosshair: empty; no enemy visible (nearest hidden one {abs(b0):.0f}deg to the {'left' if b0 > 0 else 'right'})" | |
| else: | |
| aim = "crosshair: empty; no enemies left" | |
| depth = "" | |
| if st.depth_buffer is not None: | |
| h, w = st.depth_buffer.shape | |
| c = float(st.depth_buffer[h // 2 - 6:h // 2 + 6, w // 2 - 12:w // 2 + 12].mean()) | |
| depth = f"depth ahead: {c:.0f}/255 ({'wall very close' if c < 12 else 'open space' if c > 40 else 'obstacle near'})" | |
| lines = [f"health {hp:.0f}/100 | ammo {ammo:.0f} | kills {kills:.0f}", aim, | |
| "enemies: " + ("; ".join(f"{n} {d:.0f}m {s} {b:+.0f}deg{'' if h else ' VISIBLE'}" for h, d, b, n, s in foes[:4]) or "none"), | |
| "items: " + ("; ".join(t for _, t in items[:2]) or "none"), depth, | |
| "STUCK: position unchanged" if stuck else ""] | |
| return "\n".join(l for l in lines if l), hp, kills | |
| class Game(threading.Thread): | |
| def __init__(self, agent, scenario, skill, tics, realtime=True): | |
| super().__init__(daemon=True) | |
| self.agent, self.scenario, self.skill, self.tics, self.realtime = agent, scenario, skill, tics, realtime | |
| self.frame = None | |
| self.frame_lock = threading.Lock() | |
| self.subs = [] | |
| self.stats = {"episodes": [], "actions": Counter(), "decisions": 0} | |
| self.pending_scenario = None | |
| self.on_frame = None # optional recorder callback(frame_rgb, event) | |
| def publish(self, ev): | |
| data = json.dumps(ev) | |
| for q in list(self.subs): | |
| try: | |
| q.put_nowait(data) | |
| except queue.Full: | |
| pass | |
| def _make_game(self, vzd): | |
| g = vzd.DoomGame() | |
| g.load_config(os.path.join(vzd.scenarios_path, f"{self.scenario}.cfg")) | |
| g.set_window_visible(False) | |
| g.set_mode(vzd.Mode.PLAYER) | |
| g.set_screen_resolution(vzd.ScreenResolution.RES_640X480) | |
| g.set_screen_format(vzd.ScreenFormat.RGB24) | |
| g.set_objects_info_enabled(True); g.set_labels_buffer_enabled(True); g.set_depth_buffer_enabled(True) | |
| g.set_render_hud(True) | |
| g.set_doom_skill(self.skill) | |
| g.set_episode_timeout(35 * 90) | |
| g.init() | |
| return g | |
| def run(self): | |
| while True: | |
| try: | |
| self._play() | |
| except Exception as e: # engine died (killed, crashed): start a fresh one | |
| print("game loop restarted after:", repr(e)[:200], flush=True) | |
| time.sleep(1) | |
| def _play(self): | |
| import vizdoom as vzd | |
| while True: | |
| game = self._make_game(vzd) | |
| buttons = [b.name for b in game.get_available_buttons()] | |
| crit = {k: v for k, v in ACTIONS.items() if k in buttons} | |
| if self.scenario in IDLE and IDLE[self.scenario][0] in crit: | |
| k, extra = IDLE[self.scenario] | |
| crit[k] += extra | |
| questions = {"action": {"type": "choice", "instructions": INSTRUCTION, "criteria": crit}, | |
| "threat": {"type": "noul", "instructions": THREAT}} | |
| lat = deque(maxlen=30) | |
| while self.pending_scenario is None: | |
| game.new_episode() | |
| hist, last_pos, step = deque(maxlen=4), None, 0 | |
| ep_actions = Counter() | |
| while not game.is_episode_finished() and self.pending_scenario is None: | |
| st = game.get_state() | |
| me = next((o for o in st.objects if o.name == "DoomPlayer"), None) | |
| pos = (round(me.position_x), round(me.position_y)) if me else None | |
| stuck = bool(pos and pos == last_pos and hist and hist[-1].startswith("MOVE")); last_pos = pos | |
| text, hp, kills = describe(game, st, list(hist), stuck, vzd) | |
| t0 = time.perf_counter() | |
| ans = self.agent.predict(text, questions)["answers"] | |
| ms = (time.perf_counter() - t0) * 1000; lat.append(ms) | |
| act = policy(ans, crit) | |
| hist.append(act); step += 1 | |
| self.stats["actions"][act] += 1; ep_actions[act] += 1; self.stats["decisions"] += 1 | |
| ev = {"type": "decision", "scenario": self.scenario, "step": step, "state": text, "action": act, | |
| "probs": ans["action"]["probabilities"], "threat": ans["threat"]["noul"], "latency_ms": round(ms, 1), | |
| "dps": round(1000 / (sum(lat) / len(lat)), 1), "hp": hp, "kills": kills, | |
| "total_actions": dict(self.stats["actions"]), "decisions": self.stats["decisions"], | |
| "episodes": self.stats["episodes"][-12:]} | |
| self.publish(ev) | |
| vec = [0] * len(buttons); vec[buttons.index(act)] = 1 | |
| game.set_action(vec) | |
| for _ in range(self.tics): | |
| if game.is_episode_finished(): | |
| break | |
| t1 = time.perf_counter() | |
| game.advance_action(1) | |
| s2 = game.get_state() | |
| if s2 is not None: | |
| with self.frame_lock: | |
| self.frame = s2.screen_buffer | |
| if self.on_frame: | |
| self.on_frame(s2.screen_buffer, ev) | |
| if self.realtime: | |
| time.sleep(max(0.0, 1 / 35 - (time.perf_counter() - t1))) | |
| k = game.get_game_variable(vzd.GameVariable.KILLCOUNT) | |
| self.stats["episodes"].append({"scenario": self.scenario, "kills": int(k), "steps": step, | |
| "survived": game.get_game_variable(vzd.GameVariable.HEALTH) > 0}) | |
| self.publish({"type": "episode", "episodes": self.stats["episodes"][-12:]}) | |
| game.close() | |
| self.scenario, self.pending_scenario = self.pending_scenario, None | |
| PAGE = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "index.html")).read() | |
| def serve(g, port): | |
| from fastapi import FastAPI | |
| from fastapi.responses import HTMLResponse, StreamingResponse | |
| import uvicorn | |
| app = FastAPI() | |
| def index(): | |
| return PAGE | |
| def stream(): | |
| def gen(): | |
| last = None | |
| while True: | |
| with g.frame_lock: | |
| f = g.frame | |
| if f is not None and f is not last: | |
| last = f | |
| buf = io.BytesIO(); Image.fromarray(f).save(buf, "JPEG", quality=80) | |
| yield b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + buf.getvalue() + b"\r\n" | |
| time.sleep(1 / 35) | |
| return StreamingResponse(gen(), media_type="multipart/x-mixed-replace; boundary=frame") | |
| def events(): | |
| q = queue.Queue(maxsize=64) | |
| g.subs.append(q) | |
| def gen(): | |
| try: | |
| while True: | |
| try: | |
| yield f"data: {q.get(timeout=15)}\n\n" | |
| except queue.Empty: | |
| yield ": ping\n\n" | |
| finally: | |
| g.subs.remove(q) | |
| return StreamingResponse(gen(), media_type="text/event-stream") | |
| def scenario(name: str): | |
| if name in SCENARIOS: | |
| g.pending_scenario = name | |
| return {"scenario": name} | |
| uvicorn.run(app, host="0.0.0.0", port=port, log_level="warning") | |
| def load_agent(path): | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) | |
| import thx01 | |
| return thx01.load(path, device="cuda") | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model", default="doofz/THX-01") | |
| ap.add_argument("--scenario", default="defend_the_center", choices=sorted(SCENARIOS)) | |
| ap.add_argument("--skill", type=int, default=2) | |
| ap.add_argument("--tics", type=int, default=4) | |
| ap.add_argument("--port", type=int, default=8096) | |
| a = ap.parse_args() | |
| g = Game(load_agent(a.model), a.scenario, a.skill, a.tics) | |
| g.start() | |
| serve(g, a.port) | |
Xet Storage Details
- Size:
- 12.7 kB
- Xet hash:
- a9f3af1a5798556ddc20eb52971a3c43954e18ff64bfd1babc89763b80a94691
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.