DeltaZN commited on
Commit
33a406f
·
1 Parent(s): 221eeed

feat: create 2 villages - with qwen control

Browse files
config/game.llm.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
@@ -47,5 +47,26 @@
47
  "enable_thinking": false
48
  }
49
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  }
51
  }
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
47
  "enable_thinking": false
48
  }
49
  }
50
+ },
51
+ "secondary_connectors": {
52
+ "qwen": {
53
+ "type": "openai_compatible",
54
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
55
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
56
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
57
+ "model": "qwen3.6-27b-h100-fp8",
58
+ "timeout_seconds": 600,
59
+ "max_tokens": 1200,
60
+ "temperature": 0.6,
61
+ "top_p": 0.95,
62
+ "tool_choice": "required",
63
+ "max_parallel_npc_calls": 6,
64
+ "fallback_to_deterministic": true,
65
+ "extra_body": {
66
+ "chat_template_kwargs": {
67
+ "enable_thinking": false
68
+ }
69
+ }
70
+ }
71
  }
72
  }
config/game.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
config/game.modal.a10.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
@@ -51,5 +51,26 @@
51
  "enable_thinking": false
52
  }
53
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
51
  "enable_thinking": false
52
  }
53
  }
54
+ },
55
+ "secondary_connectors": {
56
+ "qwen": {
57
+ "type": "openai_compatible",
58
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
59
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
60
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
61
+ "model": "qwen3.6-27b-h100-fp8",
62
+ "timeout_seconds": 600,
63
+ "max_tokens": 1200,
64
+ "temperature": 0.6,
65
+ "top_p": 0.95,
66
+ "tool_choice": "required",
67
+ "max_parallel_npc_calls": 6,
68
+ "fallback_to_deterministic": true,
69
+ "extra_body": {
70
+ "chat_template_kwargs": {
71
+ "enable_thinking": false
72
+ }
73
+ }
74
+ }
75
  }
76
  }
config/game.modal.b200.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
@@ -51,5 +51,26 @@
51
  "enable_thinking": false
52
  }
53
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
51
  "enable_thinking": false
52
  }
53
  }
54
+ },
55
+ "secondary_connectors": {
56
+ "qwen": {
57
+ "type": "openai_compatible",
58
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
59
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
60
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
61
+ "model": "qwen3.6-27b-h100-fp8",
62
+ "timeout_seconds": 600,
63
+ "max_tokens": 1200,
64
+ "temperature": 0.6,
65
+ "top_p": 0.95,
66
+ "tool_choice": "required",
67
+ "max_parallel_npc_calls": 6,
68
+ "fallback_to_deterministic": true,
69
+ "extra_body": {
70
+ "chat_template_kwargs": {
71
+ "enable_thinking": false
72
+ }
73
+ }
74
+ }
75
  }
76
  }
config/game.modal.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
@@ -51,5 +51,26 @@
51
  "enable_thinking": false
52
  }
53
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
51
  "enable_thinking": false
52
  }
53
  }
54
+ },
55
+ "secondary_connectors": {
56
+ "qwen": {
57
+ "type": "openai_compatible",
58
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
59
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
60
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
61
+ "model": "qwen3.6-27b-h100-fp8",
62
+ "timeout_seconds": 600,
63
+ "max_tokens": 1200,
64
+ "temperature": 0.6,
65
+ "top_p": 0.95,
66
+ "tool_choice": "required",
67
+ "max_parallel_npc_calls": 6,
68
+ "fallback_to_deterministic": true,
69
+ "extra_body": {
70
+ "chat_template_kwargs": {
71
+ "enable_thinking": false
72
+ }
73
+ }
74
+ }
75
  }
76
  }
config/game.modal.t4.local.json CHANGED
@@ -1,13 +1,13 @@
1
  {
2
  "world": {
3
- "width": 80,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
- "count": 10
11
  },
12
  "simulation": {
13
  "tick_ms": 500
@@ -51,5 +51,26 @@
51
  "enable_thinking": false
52
  }
53
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
 
1
  {
2
  "world": {
3
+ "width": 240,
4
  "depth": 80,
5
  "terrain": "plain_green",
6
  "seed": 42,
7
  "survival": true
8
  },
9
  "npcs": {
10
+ "count": 0
11
  },
12
  "simulation": {
13
  "tick_ms": 500
 
51
  "enable_thinking": false
52
  }
53
  }
54
+ },
55
+ "secondary_connectors": {
56
+ "qwen": {
57
+ "type": "openai_compatible",
58
+ "base_url_env": "GOD_CONSOLE_QWEN_BASE_URL",
59
+ "model_env": "GOD_CONSOLE_QWEN_MODEL",
60
+ "base_url": "https://georgij-sawin--god-simulator-qwen36-27b-h100-serve.modal.run/v1",
61
+ "model": "qwen3.6-27b-h100-fp8",
62
+ "timeout_seconds": 600,
63
+ "max_tokens": 1200,
64
+ "temperature": 0.6,
65
+ "top_p": 0.95,
66
+ "tool_choice": "required",
67
+ "max_parallel_npc_calls": 6,
68
+ "fallback_to_deterministic": true,
69
+ "extra_body": {
70
+ "chat_template_kwargs": {
71
+ "enable_thinking": false
72
+ }
73
+ }
74
+ }
75
  }
76
  }
frontend/src/scene/KeyboardOrbitControls.tsx CHANGED
@@ -95,7 +95,7 @@ export function KeyboardOrbitControls({
95
  return;
96
  }
97
 
98
- movement.normalize().multiplyScalar(18 * delta);
99
  moveCamera(
100
  camera.position,
101
  movement,
 
95
  return;
96
  }
97
 
98
+ movement.normalize().multiplyScalar(54 * delta);
99
  moveCamera(
100
  camera.position,
101
  movement,
src/god_simulator/api/players.py CHANGED
@@ -260,7 +260,7 @@ class PlayerManager:
260
  def _spawn_position(self, world: WorldState) -> Vec3:
261
  half_width = world.terrain.width / 2
262
  half_depth = world.terrain.depth / 2
263
- # Spawn near the village centre, fanned out so multiple players do not
264
  # stack on the exact same tile.
265
  spawned_players = sum(1 for npc in world.npcs if npc.is_player)
266
  ring = [
 
260
  def _spawn_position(self, world: WorldState) -> Vec3:
261
  half_width = world.terrain.width / 2
262
  half_depth = world.terrain.depth / 2
263
+ # Spawn near the map centre, fanned out so multiple players do not
264
  # stack on the exact same tile.
265
  spawned_players = sum(1 for npc in world.npcs if npc.is_player)
266
  ring = [
src/god_simulator/config.py CHANGED
@@ -75,6 +75,7 @@ class GameConfig:
75
  )
76
  god_console: ConnectorConfig | None = None
77
  overseer: OverseerConfig = field(default_factory=OverseerConfig)
 
78
 
79
 
80
  def load_game_config(path: Path) -> GameConfig:
@@ -119,6 +120,15 @@ def parse_game_config(raw: dict[str, Any]) -> GameConfig:
119
  raise ValueError(f"Unsupported terrain kind: {terrain_raw}")
120
  terrain: TerrainKind = "plain_green"
121
 
 
 
 
 
 
 
 
 
 
122
  return GameConfig(
123
  world=WorldConfig(
124
  width=_required_positive_int(world, "width"),
@@ -136,6 +146,7 @@ def parse_game_config(raw: dict[str, Any]) -> GameConfig:
136
  connector=_parse_connector_config(connector),
137
  god_console=_parse_connector_config(god_console) if god_console else None,
138
  overseer=_parse_overseer_config(overseer),
 
139
  )
140
 
141
 
 
75
  )
76
  god_console: ConnectorConfig | None = None
77
  overseer: OverseerConfig = field(default_factory=OverseerConfig)
78
+ secondary_connectors: dict[str, ConnectorConfig] = field(default_factory=dict)
79
 
80
 
81
  def load_game_config(path: Path) -> GameConfig:
 
120
  raise ValueError(f"Unsupported terrain kind: {terrain_raw}")
121
  terrain: TerrainKind = "plain_green"
122
 
123
+ secondary_raw = raw.get("secondary_connectors", {})
124
+ if not isinstance(secondary_raw, dict):
125
+ raise ValueError("'secondary_connectors' must be an object.")
126
+ secondary_connectors = {
127
+ cid: _parse_connector_config(cfg)
128
+ for cid, cfg in secondary_raw.items()
129
+ if isinstance(cfg, dict)
130
+ }
131
+
132
  return GameConfig(
133
  world=WorldConfig(
134
  width=_required_positive_int(world, "width"),
 
146
  connector=_parse_connector_config(connector),
147
  god_console=_parse_connector_config(god_console) if god_console else None,
148
  overseer=_parse_overseer_config(overseer),
149
+ secondary_connectors=secondary_connectors,
150
  )
151
 
152
 
src/god_simulator/domain.py CHANGED
@@ -154,6 +154,9 @@ class Npc:
154
  # any action regardless of role. Player NPCs set this, but it can also be
155
  # given to special non-player NPCs.
156
  unrestricted_actions: bool = False
 
 
 
157
 
158
 
159
  @dataclass(slots=True)
 
154
  # any action regardless of role. Player NPCs set this, but it can also be
155
  # given to special non-player NPCs.
156
  unrestricted_actions: bool = False
157
+ # Routes this NPC to a named connector (from secondary_connectors in config).
158
+ # None means the default connector handles this NPC.
159
+ connector_id: str | None = None
160
 
161
 
162
  @dataclass(slots=True)
src/god_simulator/simulation/connectors/factory.py CHANGED
@@ -4,14 +4,36 @@ from god_simulator.config import GameConfig
4
  from god_simulator.simulation.connectors.base import WorldSimulator
5
  from god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulator
6
  from god_simulator.simulation.connectors.openai_compatible import OpenAICompatibleWorldSimulator
 
7
 
8
 
9
  def create_world_simulator(config: GameConfig) -> WorldSimulator:
10
  deterministic = DeterministicWorldSimulator()
11
 
12
- if config.connector.type == "deterministic":
13
  return deterministic
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  if config.connector.type == "openai_compatible":
16
  return OpenAICompatibleWorldSimulator(config.connector, fallback=deterministic)
17
 
 
4
  from god_simulator.simulation.connectors.base import WorldSimulator
5
  from god_simulator.simulation.connectors.deterministic import DeterministicWorldSimulator
6
  from god_simulator.simulation.connectors.openai_compatible import OpenAICompatibleWorldSimulator
7
+ from god_simulator.simulation.connectors.routing import RoutingWorldSimulator
8
 
9
 
10
  def create_world_simulator(config: GameConfig) -> WorldSimulator:
11
  deterministic = DeterministicWorldSimulator()
12
 
13
+ if config.connector.type == "deterministic" and not config.secondary_connectors:
14
  return deterministic
15
 
16
+ if config.secondary_connectors:
17
+ routes: dict[str, WorldSimulator] = {}
18
+ for connector_id, connector_cfg in config.secondary_connectors.items():
19
+ if connector_cfg.type == "openai_compatible":
20
+ routes[connector_id] = OpenAICompatibleWorldSimulator(
21
+ connector_cfg,
22
+ fallback=deterministic,
23
+ connector_id_filter=connector_id,
24
+ )
25
+
26
+ if config.connector.type == "openai_compatible":
27
+ default: WorldSimulator = OpenAICompatibleWorldSimulator(
28
+ config.connector,
29
+ fallback=deterministic,
30
+ connector_id_filter=None,
31
+ )
32
+ else:
33
+ default = deterministic
34
+
35
+ return RoutingWorldSimulator(routes=routes, default=default)
36
+
37
  if config.connector.type == "openai_compatible":
38
  return OpenAICompatibleWorldSimulator(config.connector, fallback=deterministic)
39
 
src/god_simulator/simulation/connectors/openai_compatible.py CHANGED
@@ -29,7 +29,7 @@ from god_simulator.simulation.mechanics import (
29
  VISIBLE_RADIUS,
30
  is_alive,
31
  )
32
- from god_simulator.simulation.memory import recent_meaningful_memories
33
  from god_simulator.simulation.perception import CitizenPerception
34
  from god_simulator.simulation.roles import normalize_role
35
  from god_simulator.simulation.survival import (
@@ -259,8 +259,12 @@ def survival_tools_for_role(role: str) -> list[dict[str, Any]]:
259
 
260
  Builders never see strike, only guards see patrol, only builders see build;
261
  everyone can go_home. The engine still re-validates every request.
 
262
  """
263
  tool_ids = list(PRIMITIVE_TOOL_IDS) + ["go_home"]
 
 
 
264
  normalized = normalize_role(role)
265
  if normalized == "guard":
266
  tool_ids.append("patrol")
@@ -270,6 +274,9 @@ def survival_tools_for_role(role: str) -> list[dict[str, Any]]:
270
  return [TOOL_DEFINITIONS[tool_id] for tool_id in tool_ids]
271
 
272
 
 
 
 
273
  class OpenAICompatibleWorldSimulator:
274
  name = "openai_compatible"
275
 
@@ -278,6 +285,7 @@ class OpenAICompatibleWorldSimulator:
278
  config: ConnectorConfig,
279
  *,
280
  fallback: WorldSimulator,
 
281
  chat_completer: ChatCompleter | None = None,
282
  ) -> None:
283
  base_url = _resolve_base_url(config)
@@ -289,6 +297,7 @@ class OpenAICompatibleWorldSimulator:
289
  self._config = config
290
  self._base_url = base_url
291
  self._fallback = fallback
 
292
  self._chat_completer = chat_completer or self._complete_with_openai
293
  self._client = OpenAI(
294
  api_key=_resolve_api_key(config),
@@ -341,7 +350,13 @@ class OpenAICompatibleWorldSimulator:
341
  assert self._config.model is not None
342
 
343
  directives: list[NpcDirective] = []
344
- living_npcs = [npc for npc in world.npcs if is_alive(npc)]
 
 
 
 
 
 
345
  directives.extend(self._call_model_for_npcs(world, next_tick, living_npcs))
346
 
347
  missing_npcs = _missing_npcs(living_npcs, directives)
@@ -383,6 +398,8 @@ class OpenAICompatibleWorldSimulator:
383
  next_tick: int,
384
  npc: Npc,
385
  ) -> list[NpcDirective]:
 
 
386
  request = self._build_request(world, next_tick, npc)
387
  try:
388
  response = self._chat_completer(request)
@@ -438,7 +455,8 @@ class OpenAICompatibleWorldSimulator:
438
  survival_goal = select_survival_goal(npc, world)
439
  suggested = suggested_actions_for_npc(npc, survival_goal)
440
  messages = _build_survival_messages(world, next_tick, npc, survival_goal, suggested)
441
- tools = survival_tools_for_role(npc.role)
 
442
  else:
443
  perception, goal = refresh_citizen_motivation(world, npc)
444
  hints = build_action_hints(world, npc, perception, goal)
@@ -505,7 +523,7 @@ def _build_messages(
505
  "rules": [
506
  f"x must be between {-half_width} and {half_width}",
507
  f"z must be between {-half_depth} and {half_depth}",
508
- f"the map is {GRID_BLOCKS} by {GRID_BLOCKS} blocks",
509
  f"one block is {BLOCK_SIZE:g} world coordinate units",
510
  "prefer target coordinates at block centers",
511
  "do not invent npc ids",
 
29
  VISIBLE_RADIUS,
30
  is_alive,
31
  )
32
+ from god_simulator.simulation.memory import llm_compact_memory, recent_meaningful_memories
33
  from god_simulator.simulation.perception import CitizenPerception
34
  from god_simulator.simulation.roles import normalize_role
35
  from god_simulator.simulation.survival import (
 
259
 
260
  Builders never see strike, only guards see patrol, only builders see build;
261
  everyone can go_home. The engine still re-validates every request.
262
+ Pass role="unrestricted" to expose every tool.
263
  """
264
  tool_ids = list(PRIMITIVE_TOOL_IDS) + ["go_home"]
265
+ if role == "unrestricted":
266
+ tool_ids += ["patrol", "build"]
267
+ return [TOOL_DEFINITIONS[tool_id] for tool_id in dict.fromkeys(tool_ids)]
268
  normalized = normalize_role(role)
269
  if normalized == "guard":
270
  tool_ids.append("patrol")
 
274
  return [TOOL_DEFINITIONS[tool_id] for tool_id in tool_ids]
275
 
276
 
277
+ _UNSET = object() # sentinel: handle all NPCs (backward-compatible default)
278
+
279
+
280
  class OpenAICompatibleWorldSimulator:
281
  name = "openai_compatible"
282
 
 
285
  config: ConnectorConfig,
286
  *,
287
  fallback: WorldSimulator,
288
+ connector_id_filter: object = _UNSET, # _UNSET=all, None=no connector_id, str=named
289
  chat_completer: ChatCompleter | None = None,
290
  ) -> None:
291
  base_url = _resolve_base_url(config)
 
297
  self._config = config
298
  self._base_url = base_url
299
  self._fallback = fallback
300
+ self._connector_id_filter = connector_id_filter
301
  self._chat_completer = chat_completer or self._complete_with_openai
302
  self._client = OpenAI(
303
  api_key=_resolve_api_key(config),
 
350
  assert self._config.model is not None
351
 
352
  directives: list[NpcDirective] = []
353
+ if self._connector_id_filter is _UNSET:
354
+ living_npcs = [npc for npc in world.npcs if is_alive(npc)]
355
+ else:
356
+ living_npcs = [
357
+ npc for npc in world.npcs
358
+ if is_alive(npc) and npc.connector_id == self._connector_id_filter
359
+ ]
360
  directives.extend(self._call_model_for_npcs(world, next_tick, living_npcs))
361
 
362
  missing_npcs = _missing_npcs(living_npcs, directives)
 
398
  next_tick: int,
399
  npc: Npc,
400
  ) -> list[NpcDirective]:
401
+ assert self._config.model is not None
402
+ llm_compact_memory(npc, self._chat_completer, self._config.model)
403
  request = self._build_request(world, next_tick, npc)
404
  try:
405
  response = self._chat_completer(request)
 
455
  survival_goal = select_survival_goal(npc, world)
456
  suggested = suggested_actions_for_npc(npc, survival_goal)
457
  messages = _build_survival_messages(world, next_tick, npc, survival_goal, suggested)
458
+ role_key = "unrestricted" if npc.unrestricted_actions else npc.role
459
+ tools = survival_tools_for_role(role_key)
460
  else:
461
  perception, goal = refresh_citizen_motivation(world, npc)
462
  hints = build_action_hints(world, npc, perception, goal)
 
523
  "rules": [
524
  f"x must be between {-half_width} and {half_width}",
525
  f"z must be between {-half_depth} and {half_depth}",
526
+ f"the map is {round(world.terrain.width / BLOCK_SIZE)} by {round(world.terrain.depth / BLOCK_SIZE)} blocks",
527
  f"one block is {BLOCK_SIZE:g} world coordinate units",
528
  "prefer target coordinates at block centers",
529
  "do not invent npc ids",
src/god_simulator/simulation/connectors/routing.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
4
+
5
+ from god_simulator.domain import WorldState
6
+ from god_simulator.simulation.connectors.base import NpcDirective, TickPlan, WorldSimulator
7
+
8
+
9
+ class RoutingWorldSimulator:
10
+ """Dispatches each NPC to a simulator based on npc.connector_id.
11
+
12
+ NPCs whose connector_id matches a key in `routes` are handled by that
13
+ simulator. All others go to `default`.
14
+ """
15
+
16
+ name = "routing"
17
+
18
+ def __init__(
19
+ self,
20
+ routes: dict[str, WorldSimulator],
21
+ default: WorldSimulator,
22
+ ) -> None:
23
+ self._routes = routes
24
+ self._default = default
25
+
26
+ def propose_tick(self, world: WorldState, next_tick: int) -> TickPlan:
27
+ npc_connector = {npc.id: npc.connector_id for npc in world.npcs}
28
+ routed_ids = {npc.id for npc in world.npcs if npc.connector_id in self._routes}
29
+
30
+ all_directives: list[NpcDirective] = []
31
+ source_parts: list[str] = []
32
+
33
+ # Run all route simulators and the default simulator in parallel.
34
+ tasks: dict[str, WorldSimulator] = {**self._routes, "__default__": self._default}
35
+ with ThreadPoolExecutor(
36
+ max_workers=len(tasks), thread_name_prefix="god-sim-router"
37
+ ) as executor:
38
+ futures = {executor.submit(sim.propose_tick, world, next_tick): key for key, sim in tasks.items()}
39
+ results: dict[str, TickPlan] = {}
40
+ for future in as_completed(futures):
41
+ key = futures[future]
42
+ results[key] = future.result()
43
+
44
+ for connector_id, sim in self._routes.items():
45
+ plan = results[connector_id]
46
+ filtered = [d for d in plan.directives if npc_connector.get(d.npc_id) == connector_id]
47
+ if filtered:
48
+ all_directives.extend(filtered)
49
+ source_parts.append(plan.source)
50
+
51
+ default_plan = results["__default__"]
52
+ filtered_default = [d for d in default_plan.directives if d.npc_id not in routed_ids]
53
+ if filtered_default:
54
+ all_directives.extend(filtered_default)
55
+ source_parts.append(default_plan.source)
56
+
57
+ seen: set[str] = set()
58
+ unique: list[NpcDirective] = []
59
+ for d in all_directives:
60
+ if d.npc_id not in seen:
61
+ seen.add(d.npc_id)
62
+ unique.append(d)
63
+
64
+ source = "+".join(dict.fromkeys(source_parts)) or self.name
65
+ return TickPlan(source=source, directives=unique)
src/god_simulator/simulation/memory.py CHANGED
@@ -1,10 +1,16 @@
1
  from __future__ import annotations
2
 
 
 
 
 
3
  from god_simulator.domain import MemoryEntry, Npc
4
 
5
  RECENT_MEMORY_LIMIT = 5
6
  MEMORY_SUMMARY_LIMIT = 900
7
 
 
 
8
 
9
  def remember(npc: Npc, tick: int, text: str) -> None:
10
  if _is_routine_memory(text):
@@ -45,6 +51,50 @@ def _merge_summary(previous_summary: str | None, older_memories: list[MemoryEntr
45
  return "..." + summary[-(MEMORY_SUMMARY_LIMIT - 3) :]
46
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def _is_routine_memory(text: str) -> bool:
49
  return (
50
  text == "You waited."
 
1
  from __future__ import annotations
2
 
3
+ import re
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
  from god_simulator.domain import MemoryEntry, Npc
8
 
9
  RECENT_MEMORY_LIMIT = 5
10
  MEMORY_SUMMARY_LIMIT = 900
11
 
12
+ ChatCompleter = Callable[[dict[str, Any]], dict[str, Any]]
13
+
14
 
15
  def remember(npc: Npc, tick: int, text: str) -> None:
16
  if _is_routine_memory(text):
 
51
  return "..." + summary[-(MEMORY_SUMMARY_LIMIT - 3) :]
52
 
53
 
54
+ def llm_compact_memory(
55
+ npc: Npc,
56
+ chat_completer: ChatCompleter,
57
+ model: str,
58
+ ) -> None:
59
+ """Replace a raw concatenated memory_summary with an LLM-generated narrative."""
60
+ if not npc.memory_summary or not _has_raw_tick_entries(npc.memory_summary):
61
+ return
62
+
63
+ try:
64
+ response = chat_completer({
65
+ "model": model,
66
+ "messages": [
67
+ {
68
+ "role": "system",
69
+ "content": (
70
+ f"You are summarizing past memories for {npc.name}, a {npc.role}. "
71
+ f"Write 1-2 sentences in first-person (as {npc.name}) capturing the key past events, "
72
+ "relationships, and experiences. Be concise."
73
+ ),
74
+ },
75
+ {
76
+ "role": "user",
77
+ "content": npc.memory_summary,
78
+ },
79
+ ],
80
+ "max_tokens": 120,
81
+ "temperature": 0.3,
82
+ })
83
+ content = (
84
+ response.get("choices", [{}])[0]
85
+ .get("message", {})
86
+ .get("content", "")
87
+ )
88
+ if content and content.strip():
89
+ npc.memory_summary = content.strip()
90
+ except Exception:
91
+ pass
92
+
93
+
94
+ def _has_raw_tick_entries(summary: str) -> bool:
95
+ return bool(re.search(r"\bTick \d+:", summary))
96
+
97
+
98
  def _is_routine_memory(text: str) -> bool:
99
  return (
100
  text == "You waited."
src/god_simulator/simulation/spawning.py CHANGED
@@ -41,6 +41,13 @@ _NAMES = [
41
 
42
  _ROLES = ["gatherer", "gatherer", "gatherer", "guard", "guard", "builder"]
43
 
 
 
 
 
 
 
 
44
 
45
  def create_world(config: GameConfig) -> WorldState:
46
  rng = random.Random(config.world.seed)
@@ -49,19 +56,23 @@ def create_world(config: GameConfig) -> WorldState:
49
  width=config.world.width,
50
  depth=config.world.depth,
51
  )
52
- npcs = [_spawn_npc(index=index, config=config, rng=rng) for index in range(config.npcs.count)]
 
 
53
  houses = _spawn_houses(config)
 
54
  if config.world.survival:
55
- _seed_survival_relationships(npcs)
56
- _assign_starting_homes(npcs, houses)
57
- _initialize_importance(npcs)
58
 
59
- population = sum(1 for npc in npcs if npc.health > 0)
 
60
  return WorldState(
61
  tick=0,
62
  seed=config.world.seed,
63
  terrain=terrain,
64
- npcs=npcs,
65
  resource_nodes=_spawn_resource_nodes(config),
66
  beasts=_spawn_beasts(config),
67
  houses=houses,
@@ -79,6 +90,8 @@ def _spawn_npc(*, index: int, config: GameConfig, rng: random.Random) -> Npc:
79
  name = _NAMES[index % len(_NAMES)]
80
  role = normalize_role(_ROLES[index % len(_ROLES)])
81
  if config.world.survival:
 
 
82
  ring = index % 6
83
  offsets = [
84
  (0.0, 0.0),
@@ -88,7 +101,8 @@ def _spawn_npc(*, index: int, config: GameConfig, rng: random.Random) -> Npc:
88
  (-3.4, 0.0),
89
  (0.0, 3.4),
90
  ]
91
- x, z = offsets[ring]
 
92
  else:
93
  x = _random_block_center(rng, half_width=half_width)
94
  z = _random_block_center(rng, half_width=half_depth)
@@ -126,6 +140,24 @@ def _spawn_resource_nodes(config: GameConfig) -> list[ResourceNode]:
126
  counts = {"food": 4, "herbs": 2, "wood": 3, "weapon": 1}
127
  max_amounts = {"food": 5, "herbs": 4, "wood": 6, "weapon": 2}
128
  nodes: list[ResourceNode] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  for resource_type, count in counts.items():
130
  for index in range(1, count + 1):
131
  max_amount = max_amounts[resource_type]
@@ -161,10 +193,11 @@ def _spawn_beasts(config: GameConfig) -> list[Beast]:
161
  def _spawn_houses(config: GameConfig) -> list[House]:
162
  if not config.world.survival:
163
  return []
 
164
  return [
165
  House(
166
  id="house_001",
167
- position=Vec3(x=0.0, y=0.0, z=0.0),
168
  hp=60.0,
169
  max_hp=60.0,
170
  state="completed",
@@ -200,13 +233,83 @@ def _initialize_importance(npcs: list[Npc]) -> None:
200
  npc.importance = round(1.0 + 2.0 * (1 / role_count), 3)
201
 
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  def _random_max_age(seed: int, index: int) -> int:
204
  return random.Random(f"{seed}:{index}:max_age").randint(320, 480)
205
 
206
 
207
  def _random_block_center(rng: random.Random, *, half_width: float) -> float:
208
  first_center = -half_width + (BLOCK_SIZE / 2)
209
- return first_center + (rng.randrange(GRID_BLOCKS) * BLOCK_SIZE)
 
210
 
211
 
212
  def _random_world_position(
 
41
 
42
  _ROLES = ["gatherer", "gatherer", "gatherer", "guard", "guard", "builder"]
43
 
44
+ _QWEN_NAMES = ["Kira", "Lena", "Mira", "Niko", "Oleg", "Pavel"]
45
+ _BARB_NAMES = [
46
+ "Borg", "Drak", "Hrag", "Krull", "Morg", "Ravn",
47
+ "Skur", "Thax", "Vrex", "Wulf", "Xorn", "Yrag",
48
+ "Zark", "Brox", "Crag", "Dusk",
49
+ ]
50
+
51
 
52
  def create_world(config: GameConfig) -> WorldState:
53
  rng = random.Random(config.world.seed)
 
56
  width=config.world.width,
57
  depth=config.world.depth,
58
  )
59
+ village_npcs = [_spawn_npc(index=index, config=config, rng=rng) for index in range(config.npcs.count)]
60
+ qwen_npcs = _spawn_qwen_npcs(config) if config.world.survival else []
61
+ barbarians = _spawn_barbarians(config) if config.world.survival else []
62
  houses = _spawn_houses(config)
63
+
64
  if config.world.survival:
65
+ _seed_survival_relationships(village_npcs + qwen_npcs)
66
+ _assign_starting_homes(village_npcs + qwen_npcs, houses)
67
+ _initialize_importance(village_npcs + qwen_npcs + barbarians)
68
 
69
+ all_npcs = village_npcs + qwen_npcs + barbarians
70
+ population = sum(1 for npc in all_npcs if npc.health > 0)
71
  return WorldState(
72
  tick=0,
73
  seed=config.world.seed,
74
  terrain=terrain,
75
+ npcs=all_npcs,
76
  resource_nodes=_spawn_resource_nodes(config),
77
  beasts=_spawn_beasts(config),
78
  houses=houses,
 
90
  name = _NAMES[index % len(_NAMES)]
91
  role = normalize_role(_ROLES[index % len(_ROLES)])
92
  if config.world.survival:
93
+ # Village is anchored on the left side of the map.
94
+ village_x = -(half_width * 2 / 3)
95
  ring = index % 6
96
  offsets = [
97
  (0.0, 0.0),
 
101
  (-3.4, 0.0),
102
  (0.0, 3.4),
103
  ]
104
+ dx, z = offsets[ring]
105
+ x = village_x + dx
106
  else:
107
  x = _random_block_center(rng, half_width=half_width)
108
  z = _random_block_center(rng, half_width=half_depth)
 
140
  counts = {"food": 4, "herbs": 2, "wood": 3, "weapon": 1}
141
  max_amounts = {"food": 5, "herbs": 4, "wood": 6, "weapon": 2}
142
  nodes: list[ResourceNode] = []
143
+
144
+ village_x = -(config.world.width / 2 * 2 / 3)
145
+ village_food_offsets = [
146
+ (2 * BLOCK_SIZE, BLOCK_SIZE),
147
+ (-2 * BLOCK_SIZE, 2 * BLOCK_SIZE),
148
+ (BLOCK_SIZE, -2 * BLOCK_SIZE),
149
+ ]
150
+ for i, (dx, dz) in enumerate(village_food_offsets, start=1):
151
+ nodes.append(
152
+ ResourceNode(
153
+ id=f"res_food_village_{i}",
154
+ resource_type="food",
155
+ position=Vec3(x=round(village_x + dx, 3), y=0.0, z=round(dz, 3)),
156
+ amount=5,
157
+ max_amount=5,
158
+ )
159
+ )
160
+
161
  for resource_type, count in counts.items():
162
  for index in range(1, count + 1):
163
  max_amount = max_amounts[resource_type]
 
193
  def _spawn_houses(config: GameConfig) -> list[House]:
194
  if not config.world.survival:
195
  return []
196
+ village_x = -(config.world.width / 2 * 2 / 3)
197
  return [
198
  House(
199
  id="house_001",
200
+ position=Vec3(x=village_x, y=0.0, z=0.0),
201
  hp=60.0,
202
  max_hp=60.0,
203
  state="completed",
 
233
  npc.importance = round(1.0 + 2.0 * (1 / role_count), 3)
234
 
235
 
236
+ def _spawn_qwen_npcs(config: GameConfig) -> list[Npc]:
237
+ half_width = config.world.width / 2
238
+ village_x = -(half_width * 2 / 3)
239
+ # Cluster around the house (which sits at village_x, z=0)
240
+ offsets = [
241
+ (0.0, 0.0),
242
+ (BLOCK_SIZE, 0.0),
243
+ (-BLOCK_SIZE, 0.0),
244
+ (0.0, BLOCK_SIZE),
245
+ (BLOCK_SIZE, BLOCK_SIZE),
246
+ (-BLOCK_SIZE, BLOCK_SIZE),
247
+ ]
248
+ npcs = []
249
+ inv_rng = random.Random(f"{config.world.seed}:qwen_inventory")
250
+ for i, (dx, dz) in enumerate(offsets):
251
+ name = _QWEN_NAMES[i]
252
+ npc = Npc(
253
+ id=f"qwen-{i + 1:03d}",
254
+ name=name,
255
+ role="gatherer",
256
+ position=Vec3(x=round(village_x + dx, 3), y=0.0, z=round(dz, 3)),
257
+ attack_damage=inv_rng.randint(5, 12),
258
+ memory=[MemoryEntry(tick=0, text=f"{name} joined the village as a free spirit.")],
259
+ age=25,
260
+ max_age=550,
261
+ unrestricted_actions=True,
262
+ connector_id="qwen",
263
+ personality="curious and resourceful",
264
+ hunger=15.0,
265
+ safety=60.0,
266
+ inventory_food=inv_rng.randint(1, 3),
267
+ inventory_herbs=inv_rng.randint(0, 1),
268
+ )
269
+ npcs.append(npc)
270
+ return npcs
271
+
272
+
273
+ def _spawn_barbarians(config: GameConfig) -> list[Npc]:
274
+ half_width = config.world.width / 2
275
+ half_depth = config.world.depth / 2
276
+ barb_x = half_width * 2 / 3
277
+ npcs = []
278
+ inv_rng = random.Random(f"{config.world.seed}:barb_inventory")
279
+ for i in range(16):
280
+ col = i % 4
281
+ row = i // 4
282
+ dx = (col - 1.5) * BLOCK_SIZE
283
+ dz = (row - 1.5) * (half_depth / 2)
284
+ name = _BARB_NAMES[i]
285
+ npc = Npc(
286
+ id=f"barb-{i + 1:03d}",
287
+ name=name,
288
+ role="guard",
289
+ position=Vec3(x=round(barb_x + dx, 3), y=0.0, z=round(dz, 3)),
290
+ attack_damage=inv_rng.randint(12, 20),
291
+ memory=[MemoryEntry(tick=0, text=f"{name} is a barbarian warrior on the warpath.")],
292
+ age=30,
293
+ max_age=350,
294
+ connector_id=None,
295
+ personality="aggressive barbarian",
296
+ hunger=35.0,
297
+ safety=0.0,
298
+ inventory_food=inv_rng.randint(0, 1),
299
+ inventory_weapon=1,
300
+ )
301
+ npcs.append(npc)
302
+ return npcs
303
+
304
+
305
  def _random_max_age(seed: int, index: int) -> int:
306
  return random.Random(f"{seed}:{index}:max_age").randint(320, 480)
307
 
308
 
309
  def _random_block_center(rng: random.Random, *, half_width: float) -> float:
310
  first_center = -half_width + (BLOCK_SIZE / 2)
311
+ num_blocks = round(half_width * 2 / BLOCK_SIZE)
312
+ return first_center + (rng.randrange(num_blocks) * BLOCK_SIZE)
313
 
314
 
315
  def _random_world_position(