cuju-engine 0.3.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. cuju/__init__.py +217 -0
  2. cuju/__main__.py +262 -0
  3. cuju/_batch/__init__.py +4 -0
  4. cuju/_batch/allocator.py +52 -0
  5. cuju/_batch/assets.py +68 -0
  6. cuju/_batch/environment.py +1890 -0
  7. cuju/_batch/frame_stack.py +114 -0
  8. cuju/_batch/library.py +190 -0
  9. cuju/_batch/log.py +103 -0
  10. cuju/_batch/memory.py +70 -0
  11. cuju/_batch/operators.py +55 -0
  12. cuju/_batch/pinned.py +39 -0
  13. cuju/_batch/pixels.py +207 -0
  14. cuju/_batch/state.py +77 -0
  15. cuju/_checksums.py +60 -0
  16. cuju/_cli_contract.py +244 -0
  17. cuju/_cli_parsers.py +191 -0
  18. cuju/_completion.py +277 -0
  19. cuju/_dump_to_txt.py +66 -0
  20. cuju/_grf_config.py +331 -0
  21. cuju/_library_path.py +141 -0
  22. cuju/_media.py +113 -0
  23. cuju/_pixels.py +276 -0
  24. cuju/_plugins.py +106 -0
  25. cuju/_python_players.py +224 -0
  26. cuju/_replay_command.py +109 -0
  27. cuju/_replay_player.py +42 -0
  28. cuju/_replays.py +414 -0
  29. cuju/_script_helpers.py +109 -0
  30. cuju/_version.py +6 -0
  31. cuju/action_log.py +371 -0
  32. cuju/check.py +596 -0
  33. cuju/cuju_cpu.dll +0 -0
  34. cuju/cuju_cuda.dll +0 -0
  35. cuju/cuju_render.dll +0 -0
  36. cuju/data/SHA256SUMS +20 -0
  37. cuju/data/animations.bin +0 -0
  38. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  41. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  42. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  43. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  44. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  53. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  54. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  55. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  56. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  57. cuju/data/digests.json +186 -0
  58. cuju/data/render_digests.json.z +0 -0
  59. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  60. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  61. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  62. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  63. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  64. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  65. cuju/data/scenarios/5_vs_5.py +33 -0
  66. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  67. cuju/data/scenarios/academy_corner.py +45 -0
  68. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  69. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  70. cuju/data/scenarios/academy_empty_goal.py +25 -0
  71. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  72. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  73. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  74. cuju/data/scenarios/academy_run_to_score.py +30 -0
  75. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  76. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  77. cuju/data/scenarios/test_example_multiagent.py +28 -0
  78. cuju/dumps.py +942 -0
  79. cuju/engine_status.py +106 -0
  80. cuju/env.py +1168 -0
  81. cuju/errors.py +108 -0
  82. cuju/gfootball/GRF_SOURCES +86 -0
  83. cuju/gfootball/__init__.py +60 -0
  84. cuju/gfootball/_cv2.py +43 -0
  85. cuju/gfootball/_gym/__init__.py +88 -0
  86. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  87. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  88. cuju/gfootball/_gym/_vendored/core.py +361 -0
  89. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  90. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  91. cuju/gfootball/_gym/_vendored/error.py +230 -0
  92. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  93. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  94. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  95. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  96. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  97. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  98. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  99. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  100. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  101. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  102. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  103. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  104. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  105. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  106. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  107. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  108. cuju/gfootball/_gym/_vendored/version.py +5 -0
  109. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  110. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  111. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  112. cuju/gfootball/dump_to_txt.py +49 -0
  113. cuju/gfootball/dump_to_video.py +33 -0
  114. cuju/gfootball/env/__init__.py +271 -0
  115. cuju/gfootball/env/config.py +163 -0
  116. cuju/gfootball/env/constants.py +33 -0
  117. cuju/gfootball/env/controller_base.py +114 -0
  118. cuju/gfootball/env/event_queue.py +54 -0
  119. cuju/gfootball/env/football_action_set.py +220 -0
  120. cuju/gfootball/env/football_action_set_test.py +76 -0
  121. cuju/gfootball/env/football_env.py +225 -0
  122. cuju/gfootball/env/football_env_core.py +447 -0
  123. cuju/gfootball/env/football_env_test.py +692 -0
  124. cuju/gfootball/env/gym_test.py +47 -0
  125. cuju/gfootball/env/observation_preprocessing.py +94 -0
  126. cuju/gfootball/env/observation_processor.py +526 -0
  127. cuju/gfootball/env/observation_rotation.py +163 -0
  128. cuju/gfootball/env/observation_rotation_test.py +84 -0
  129. cuju/gfootball/env/player_base.py +46 -0
  130. cuju/gfootball/env/players/__init__.py +16 -0
  131. cuju/gfootball/env/players/agent.py +39 -0
  132. cuju/gfootball/env/players/bot.py +217 -0
  133. cuju/gfootball/env/players/gamepad.py +81 -0
  134. cuju/gfootball/env/players/keyboard.py +72 -0
  135. cuju/gfootball/env/players/lazy.py +31 -0
  136. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  137. cuju/gfootball/env/players/replay.py +40 -0
  138. cuju/gfootball/env/remote_football_env.py +189 -0
  139. cuju/gfootball/env/scenario_builder.py +125 -0
  140. cuju/gfootball/env/script_helpers.py +130 -0
  141. cuju/gfootball/env/script_helpers_test.py +107 -0
  142. cuju/gfootball/env/wrappers.py +440 -0
  143. cuju/gfootball/env/wrappers_test.py +150 -0
  144. cuju/gfootball/eval_server/__init__.py +17 -0
  145. cuju/gfootball/eval_server/config.py +30 -0
  146. cuju/gfootball/eval_server/example_client.py +107 -0
  147. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  148. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  149. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  150. cuju/gfootball/eval_server/proto/master.proto +25 -0
  151. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  152. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  153. cuju/gfootball/eval_server/utils.py +52 -0
  154. cuju/gfootball/examples/__init__.py +16 -0
  155. cuju/gfootball/examples/models.py +66 -0
  156. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  157. cuju/gfootball/examples/run_ppo2.py +123 -0
  158. cuju/gfootball/play_game.py +73 -0
  159. cuju/gfootball/replay.py +43 -0
  160. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  161. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  163. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  164. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  165. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  166. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  167. cuju/gfootball/scenarios/__init__.py +31 -0
  168. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  169. cuju/gfootball/scenarios/academy_corner.py +59 -0
  170. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  171. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  172. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  173. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  174. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  175. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  176. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  177. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  178. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  179. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  183. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  184. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  185. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  186. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  187. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  188. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  189. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  190. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  191. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  192. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  193. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  194. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  195. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  196. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  197. cuju/gfootball_engine/__init__.py +31 -0
  198. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  199. cuju/gfootball_engine/_native.py +193 -0
  200. cuju/gfootball_engine/_pickle_names.py +114 -0
  201. cuju/gfootball_engine/_render_hooks.py +156 -0
  202. cuju/kaggle.py +425 -0
  203. cuju/multi_device.py +401 -0
  204. cuju/players.py +260 -0
  205. cuju/raw.py +93 -0
  206. cuju/scenarios.py +661 -0
  207. cuju/state.py +211 -0
  208. cuju/wrappers.py +325 -0
  209. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  210. cuju_engine-0.3.0.dist-info/RECORD +222 -0
  211. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  212. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  221. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  222. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/_grf_config.py ADDED
@@ -0,0 +1,331 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The configuration of `cuju.env`, GRF's `Config` and `Scenario` for levels that are bundles.
6
+
7
+ `Config` holds GRF's values with the current episode's on top, and builds each episode's scenario
8
+ as GRF does, which draws its seed from Python's `random`. `Scenario(config)` builds the scenario of
9
+ a configuration's current episode. Unlike GRF's `Config`, which `cuju.gfootball` holds, a level may
10
+ name a bundle or a scenario file by its path.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import os
17
+ import platform
18
+ import random
19
+ import re
20
+ import tempfile
21
+ from collections.abc import Callable
22
+ from typing import Any
23
+
24
+ from . import scenarios
25
+ from .env import _SEED_LIMIT, _scenario_facts
26
+
27
+ __all__ = [
28
+ 'Config',
29
+ 'Scenario',
30
+ 'count_left_players',
31
+ 'count_players',
32
+ 'count_right_players',
33
+ 'get_agent_number_of_players',
34
+ 'parse_player_definition',
35
+ ]
36
+
37
+
38
+ def parse_player_definition(definition: str) -> tuple[str, dict[str, Any]]:
39
+ """Returns the name of a player definition, such as `agent:left_players=2`, and its parameters.
40
+
41
+ GRF: a definition that names no count gets one left player, and the counts that it names stay
42
+ strings.
43
+ """
44
+ name = definition
45
+ parameters = {'left_players': 0, 'right_players': 0}
46
+ if ':' in definition:
47
+ # GRF: on Windows the path of a replay may hold a colon.
48
+ if (
49
+ platform.system() == 'Windows'
50
+ and definition.startswith('replay:')
51
+ and len(definition.split(':')) > 2
52
+ ):
53
+ name, text = 'replay', definition.split('replay:')[-1]
54
+ else:
55
+ name, text = definition.split(':')
56
+ for parameter in text.split(','):
57
+ key, value = parameter.split('=')
58
+ parameters[key] = value
59
+ if parameters['left_players'] == 0 and parameters['right_players'] == 0:
60
+ parameters['left_players'] = 1
61
+ return name, parameters
62
+
63
+
64
+ def count_players(definition: str) -> int:
65
+ """Returns the players of a player definition, on both sides."""
66
+ _, parameters = parse_player_definition(definition)
67
+ return int(parameters['left_players']) + int(parameters['right_players'])
68
+
69
+
70
+ def count_left_players(definition: str) -> int:
71
+ """Returns the left players of a player definition."""
72
+ return int(parse_player_definition(definition)[1]['left_players'])
73
+
74
+
75
+ def count_right_players(definition: str) -> int:
76
+ """Returns the right players of a player definition."""
77
+ return int(parse_player_definition(definition)[1]['right_players'])
78
+
79
+
80
+ def get_agent_number_of_players(players: list[str]) -> int:
81
+ """Returns the players of the `agent` definitions among `players`."""
82
+ return sum([count_players(player) for player in players if player.startswith('agent')])
83
+
84
+
85
+ # GRF's scenario files of the shipped scenarios, from which cuju's bundles were built.
86
+ _SCENARIO_FILES = os.path.join(os.path.dirname(scenarios.__file__), 'data', 'scenarios')
87
+ # The `build_scenario` of each scenario file loaded, by absolute path. GRF imports a scenario
88
+ # module once per process, so a module keeps its globals from one episode to the next.
89
+ _LOADED: dict[str, Callable[[Any], Any]] = {}
90
+
91
+
92
+ def _scenario_function(level: Any) -> Callable[[Any], Any]:
93
+ """Returns the `build_scenario` of a level, a shipped scenario or a scenario file."""
94
+ path = None
95
+ if isinstance(level, str):
96
+ if level.endswith('.py') and os.path.isfile(level):
97
+ path = level
98
+ elif re.fullmatch(r'\w+', level):
99
+ shipped = os.path.join(_SCENARIO_FILES, level + '.py')
100
+ path = shipped if os.path.isfile(shipped) else None
101
+ if path is None:
102
+ raise NotImplementedError(
103
+ f'expected a shipped scenario or the path of a scenario file as the level, found '
104
+ f'{level!r}, and a bundle holds no scenario file to build'
105
+ )
106
+ key = os.path.abspath(path)
107
+ if key not in _LOADED:
108
+ _LOADED[key] = scenarios.load_scenario(path)
109
+ return _LOADED[key]
110
+
111
+
112
+ def _run_scenario(config: Config, builder: scenarios.Builder) -> scenarios.ScenarioConfig:
113
+ """Runs the level's `build_scenario` on `builder` and sets the agents, as GRF's `Scenario`.
114
+
115
+ It leaves out the seed and the team order, which `_build_scenario` and the `Scenario` of
116
+ `scenario_builder` set each in its own way.
117
+ """
118
+ _scenario_function(config['level'])(builder)
119
+ # GRF: `_FakePlayersForEmptyTeam` gives an empty team a lazy goalkeeper.
120
+ for team in (scenarios.Team.e_Left, scenarios.Team.e_Right):
121
+ builder.SetTeam(team)
122
+ built = builder.config()
123
+ if not (built.left_team if team == scenarios.Team.e_Left else built.right_team):
124
+ builder.AddPlayer(-1.000000, 0.420000, scenarios.PlayerRole.e_PlayerRole_GK, True)
125
+ built = builder.config()
126
+ # GRF: `_BuildScenarioConfig`.
127
+ built.real_time = config['real_time']
128
+ built.left_agents = config.number_of_left_players()
129
+ built.right_agents = config.number_of_right_players()
130
+ return built
131
+
132
+
133
+ def _build_scenario(config: Config) -> scenarios.ScenarioConfig:
134
+ """Returns the episode's scenario as GRF's `Scenario` builds it, after the seed is drawn."""
135
+ built = _run_scenario(config, scenarios.Builder(config['episode_number']))
136
+ if not built.deterministic and 'game_engine_random_seed' in config:
137
+ built.game_engine_random_seed = config['game_engine_random_seed']
138
+ if 'reverse_team_processing' in config:
139
+ built.reverse_team_processing = config['reverse_team_processing']
140
+ return built
141
+
142
+
143
+ def _defaults() -> dict[str, Any]:
144
+ """Returns GRF's default values of a `Config`, in GRF's order."""
145
+ values = {
146
+ 'action_set': 'default',
147
+ 'custom_display_stats': None,
148
+ 'display_game_stats': True,
149
+ 'dump_full_episodes': False,
150
+ 'dump_scores': False,
151
+ 'players': ['agent:left_players=1'],
152
+ 'level': '11_vs_11_stochastic',
153
+ 'physics_steps_per_frame': 10,
154
+ 'render_resolution_x': 1280,
155
+ 'real_time': False,
156
+ 'tracesdir': os.path.join(tempfile.gettempdir(), 'dumps'),
157
+ 'video_format': 'avi',
158
+ 'video_quality_level': 0,
159
+ 'write_video': False,
160
+ }
161
+ values['render_resolution_y'] = int(0.5625 * values['render_resolution_x'])
162
+ return values
163
+
164
+
165
+ def _deterministic(level: Any, episode_number: int) -> bool | None:
166
+ """Returns whether an episode's scenario is deterministic, `None` if only its bundle knows."""
167
+ if isinstance(level, str) and level.endswith('.py') and os.path.isfile(level):
168
+ from . import scenarios
169
+
170
+ # GRF: a scenario file may build another scenario for each parity of the episode number.
171
+ return bool(scenarios.describe(level)[episode_number % 2]['values']['deterministic'])
172
+ return _scenario_facts(level)[0]
173
+
174
+
175
+ class Config:
176
+ """GRF's `Config`, the values of an environment with the values of the current episode on top.
177
+
178
+ `config[key]` reads the episode's value first, `config[key] = value` and `update` set the
179
+ environment's, and `get_dictionary` returns both merged, as the configuration of GRF's dumps.
180
+ """
181
+
182
+ def __init__(self, values: dict[str, Any] | None = None) -> None:
183
+ """Holds GRF's defaults updated with `values`, and builds the first episode's scenario.
184
+
185
+ The scenario draws its seed from Python's `random` unless `values` holds
186
+ `game_engine_random_seed`.
187
+ """
188
+ self._values = _defaults()
189
+ if values:
190
+ self._values.update(values)
191
+ self.NewScenario()
192
+
193
+ def number_of_left_players(self) -> int:
194
+ return sum([count_left_players(player) for player in self._values['players']])
195
+
196
+ def number_of_right_players(self) -> int:
197
+ return sum([count_right_players(player) for player in self._values['players']])
198
+
199
+ def number_of_players_agent_controls(self) -> int:
200
+ return get_agent_number_of_players(self._values['players'])
201
+
202
+ def __eq__(self, other: object) -> bool:
203
+ assert isinstance(other, self.__class__)
204
+ return self._values == other._values and self._scenario_values == other._scenario_values
205
+
206
+ def __ne__(self, other: object) -> bool:
207
+ return not self.__eq__(other)
208
+
209
+ def __getitem__(self, key: str) -> Any:
210
+ if key in self._scenario_values:
211
+ return self._scenario_values[key]
212
+ return self._values[key]
213
+
214
+ def __setitem__(self, key: str, value: Any) -> None:
215
+ self._values[key] = value
216
+
217
+ def __contains__(self, key: str) -> bool:
218
+ return key in self._scenario_values or key in self._values
219
+
220
+ def get_dictionary(self) -> dict[str, Any]:
221
+ """Returns a copy of the values, with the episode's on top."""
222
+ merged = copy.deepcopy(self._values)
223
+ merged.update(self._scenario_values)
224
+ return merged
225
+
226
+ def set_scenario_value(self, key: str, value: Any) -> None:
227
+ """Sets a value for the current episode only."""
228
+ self._scenario_values[key] = value
229
+
230
+ def serialize(self) -> dict[str, Any]:
231
+ """Returns the values of the environment, without the episode's."""
232
+ return self._values
233
+
234
+ def update(self, config: dict[str, Any]) -> None:
235
+ self._values.update(config)
236
+
237
+ def ScenarioConfig(self) -> scenarios.ScenarioConfig:
238
+ """Returns the current episode's scenario as GRF's `scenario_builder` builds it.
239
+
240
+ The result is a `cuju.scenarios.ScenarioConfig` with GRF's fields, built at the first call
241
+ of each episode from the values of that moment. Its floats
242
+ keep the double values of the scenario, which GRF's engine rounds to `float32`.
243
+
244
+ Raises:
245
+ NotImplementedError: If the level is a bundle, which holds no scenario file.
246
+ """
247
+ if getattr(self, '_scenario_cfg', None) is None:
248
+ self._scenario_cfg = _build_scenario(self)
249
+ return self._scenario_cfg
250
+
251
+ def NewScenario(self, inc: int = 1) -> None:
252
+ """Builds the scenario of the episode number `inc` ahead, as GRF's method.
253
+
254
+ GRF: the scenario draws the seed of the episode unless the values hold one, and a scenario
255
+ that is not deterministic takes the team order from the parity of that seed unless the
256
+ values hold an order.
257
+ """
258
+ seed = None
259
+ if 'game_engine_random_seed' not in self._values:
260
+ seed = random.randint(0, _SEED_LIMIT)
261
+ self._new_scenario(inc, seed)
262
+ deterministic = _deterministic(self['level'], self['episode_number'])
263
+ if deterministic is False and 'reverse_team_processing' not in self:
264
+ self['reverse_team_processing'] = bool(self['game_engine_random_seed'] % 2)
265
+
266
+ def _new_scenario(self, inc: int, seed: int | None) -> None:
267
+ """Moves the episode number `inc` ahead with `seed` or no seed, as `NewScenario` does."""
268
+ if 'episode_number' not in self._values:
269
+ self._values['episode_number'] = 0
270
+ self._values['episode_number'] += inc
271
+ self._scenario_values = {}
272
+ self._scenario_cfg = None
273
+ if seed is not None:
274
+ self.set_scenario_value('game_engine_random_seed', seed)
275
+
276
+
277
+ def _without_draw(values: dict[str, Any]) -> Config:
278
+ """Returns a `Config` of `values` without building a scenario, so nothing is drawn.
279
+
280
+ The values already hold the episode number and the team order that the scenario set.
281
+ """
282
+ config = Config.__new__(Config)
283
+ config._values = _defaults()
284
+ config._values.update(values)
285
+ config._scenario_values = {}
286
+ return config
287
+
288
+
289
+ class Scenario(scenarios.Builder):
290
+ """GRF's `Scenario(config)`, which builds the scenario of a configuration's current episode.
291
+
292
+ It runs the `build_scenario` of the configuration's level, a shipped scenario or a scenario
293
+ file, with itself as the builder, gives an empty team a lazy goalkeeper and sets the agents
294
+ from the players, as GRF's does. Then, as GRF's `_BuildScenarioConfig`, it draws the seed of
295
+ the episode from Python's `random` into the configuration's values of the episode unless the
296
+ configuration holds one of its own, and a scenario that is not deterministic takes that seed,
297
+ and the team order from its parity unless the configuration holds an order.
298
+ `ScenarioConfig()` and `config()` return the scenario.
299
+ """
300
+
301
+ def __init__(self, config: Config) -> None:
302
+ """Builds the scenario of `config`.
303
+
304
+ Args:
305
+ config: A `Config`, as GRF's `Scenario` takes.
306
+
307
+ Raises:
308
+ TypeError: If `config` is not a `Config`.
309
+ NotImplementedError: If the level is a bundle, which holds no scenario file.
310
+ """
311
+ if not isinstance(config, Config):
312
+ raise TypeError(
313
+ f"expected a Config of cuju.env, as GRF's Scenario takes, found "
314
+ f'{type(config).__name__}'
315
+ )
316
+ super().__init__(config['episode_number'])
317
+ self._environment_config = config
318
+ built = _run_scenario(config, self)
319
+ # GRF: the seed is a value of the episode, so that the dump records it.
320
+ if 'game_engine_random_seed' not in config._values:
321
+ config.set_scenario_value('game_engine_random_seed', random.randint(0, _SEED_LIMIT))
322
+ if not built.deterministic:
323
+ built.game_engine_random_seed = config['game_engine_random_seed']
324
+ if 'reverse_team_processing' not in config:
325
+ config['reverse_team_processing'] = bool(config['game_engine_random_seed'] % 2)
326
+ if 'reverse_team_processing' in config:
327
+ built.reverse_team_processing = config['reverse_team_processing']
328
+
329
+ def EpisodeNumber(self) -> Any:
330
+ """Returns the configuration's episode number, as GRF's method reads it."""
331
+ return self._environment_config['episode_number']
cuju/_library_path.py ADDED
@@ -0,0 +1,141 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The path of each backend's library and the processor check of the CPU library, without PyTorch.
5
+
6
+ PyTorch loads only to read a device that is neither `cpu` nor `cuda`, or to resolve `auto`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ctypes
12
+ import os
13
+ import platform
14
+ import sys
15
+ from typing import Any
16
+
17
+ from .errors import ChoiceError
18
+
19
+ # The directory of the package, where the libraries sit.
20
+ _PACKAGE_DIRECTORY = os.path.dirname(__file__)
21
+ # The library of each device, and the environment variable that overrides its path.
22
+ if os.name == 'nt':
23
+ _LIBRARY_FILE = '{}.dll'
24
+ elif sys.platform == 'darwin':
25
+ _LIBRARY_FILE = 'lib{}.dylib'
26
+ else:
27
+ _LIBRARY_FILE = 'lib{}.so'
28
+ _LIBRARIES = {
29
+ 'cuda': (_LIBRARY_FILE.format('cuju_cuda'), 'CUJU_CUDA_LIBRARY'),
30
+ 'cpu': (_LIBRARY_FILE.format('cuju_cpu'), 'CUJU_CPU_LIBRARY'),
31
+ }
32
+
33
+
34
+ def _backend(device: Any) -> str:
35
+ """Returns `cuda` or `cpu`, the backend of a device such as `cuda:1` or a `torch.device`."""
36
+ if isinstance(device, str) and device in _LIBRARIES:
37
+ return device
38
+ import torch
39
+
40
+ try:
41
+ kind = torch.device(device).type
42
+ except (RuntimeError, TypeError):
43
+ kind = None
44
+ if kind not in _LIBRARIES:
45
+ raise ChoiceError(
46
+ f"expected the device 'cuda', 'cuda:N', 'cpu' or a torch.device, found {device!r}"
47
+ )
48
+ return kind
49
+
50
+
51
+ def _automatic(device: Any) -> Any:
52
+ """Returns the CUDA device for `auto` if a GPU and the CUDA library exist, else `cpu`."""
53
+ if not (isinstance(device, str) and device == 'auto'):
54
+ return device
55
+ name, variable = _LIBRARIES['cuda']
56
+ library = os.environ.get(variable) or os.path.join(_PACKAGE_DIRECTORY, name)
57
+ # A `CUJU_CUDA_LIBRARY` that names no file still picks the GPU, whose load then says so.
58
+ present = bool(os.environ.get(variable)) or os.path.isfile(library)
59
+ if not present:
60
+ return 'cpu'
61
+ import torch
62
+
63
+ if torch.cuda.is_available():
64
+ return f'cuda:{torch.cuda.current_device()}'
65
+ return 'cpu'
66
+
67
+
68
+ def library_path(device: Any = 'cuda') -> str:
69
+ """Returns the path of the library that `BatchEnvironment` loads by default for a device.
70
+
71
+ Args:
72
+ device: `cuda`, `cuda:N` or a `torch.device` for `libcuju_cuda.so`, `cpu` for
73
+ `libcuju_cpu.so`, or `auto` for the one that `device='auto'` picks (`cuju_cuda.dll`
74
+ and `cuju_cpu.dll` on Windows, `libcuju_cpu.dylib` on macOS). The library sits inside
75
+ the package unless `CUJU_CUDA_LIBRARY` or `CUJU_CPU_LIBRARY` names another path.
76
+
77
+ Raises:
78
+ ChoiceError: If `device` names neither. It is a `ValueError` and a `KeyError`.
79
+ """
80
+ name, variable = _LIBRARIES[_backend(_automatic(device))]
81
+ return os.environ.get(variable) or os.path.join(_PACKAGE_DIRECTORY, name)
82
+
83
+
84
+ # The sysctl keys under which macOS reports each feature.
85
+ _MACOS_FEATURES = (
86
+ ('AVX2', 'hw.optional.avx2_0'),
87
+ ('BMI2', 'hw.optional.bmi2'),
88
+ ('FMA', 'hw.optional.fma'),
89
+ )
90
+
91
+
92
+ def _macos_feature(key):
93
+ """Returns whether macOS reports the processor feature `key`, true when it cannot tell."""
94
+ try:
95
+ sysctl = ctypes.CDLL(None).sysctlbyname
96
+ except (OSError, AttributeError):
97
+ return True
98
+ value = ctypes.c_int(0)
99
+ size = ctypes.c_size_t(ctypes.sizeof(value))
100
+ if sysctl(key.encode(), ctypes.byref(value), ctypes.byref(size), None, ctypes.c_size_t(0)):
101
+ return True
102
+ return value.value != 0
103
+
104
+
105
+ def _missing_processor_features():
106
+ """Returns the features among AVX2, BMI2 and FMA that the processor lacks, as far as known."""
107
+ if os.name == 'nt':
108
+ # Windows answers for AVX2 (`PF_AVX2_INSTRUCTIONS_AVAILABLE`, 40), not for BMI2 or FMA.
109
+ return [] if ctypes.windll.kernel32.IsProcessorFeaturePresent(40) else ['AVX2']
110
+ if sys.platform == 'darwin':
111
+ return [name for name, key in _MACOS_FEATURES if not _macos_feature(key)]
112
+ try:
113
+ with open('/proc/cpuinfo', encoding='ascii', errors='replace') as handle:
114
+ for line in handle:
115
+ if line.startswith('flags'):
116
+ flags = set(line.partition(':')[2].split())
117
+ return [name.upper() for name in ('avx2', 'bmi2', 'fma') if name not in flags]
118
+ except OSError:
119
+ pass
120
+ return []
121
+
122
+
123
+ def _check_processor(path):
124
+ """Raises `DeviceError` for the packaged CPU library on a CPU without AVX2, BMI2 or FMA."""
125
+ from .errors import DeviceError
126
+
127
+ # The packaged library targets x86-64-v3, so elsewhere it stops Python with an illegal
128
+ # instruction; a library at another path is a build of its own. An aarch64 build targets the
129
+ # base Armv8-A, which every aarch64 processor has.
130
+ if platform.machine().lower() not in ('x86_64', 'amd64'):
131
+ return
132
+ if os.path.abspath(path) != os.path.join(
133
+ os.path.abspath(_PACKAGE_DIRECTORY), _LIBRARIES['cpu'][0]
134
+ ):
135
+ return
136
+ missing = _missing_processor_features()
137
+ if missing:
138
+ raise DeviceError(
139
+ 'the CPU library of cuju needs a processor with AVX2, BMI2 and FMA, and this one lacks '
140
+ + ', '.join(missing)
141
+ )
cuju/_media.py ADDED
@@ -0,0 +1,113 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Finds GRF's media for the renderer, the package cuju-grf-media of the extra `pixels`.
5
+
6
+ The package holds GRF's files unchanged, with `manifest.json`, which names each file, its source in
7
+ GRF, its size, its SHA-256 and its license, and `SHA256SUMS`. A missing package, or one whose
8
+ manifest is of another format, raises `MissingFileError` with one message naming the extra.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import importlib.resources
14
+ import json
15
+ import os
16
+ import pathlib
17
+ from typing import Any
18
+
19
+ from . import _checksums
20
+ from .errors import MissingFileError
21
+
22
+ DISTRIBUTION = 'cuju-grf-media'
23
+ PACKAGE = 'cuju_grf_media'
24
+ # The format of the manifest that this cuju reads, which `ci/make_render_media.py` writes.
25
+ FORMAT = 1
26
+ INSTALL = "pip install 'cuju-engine[pixels]'"
27
+ MESSAGE = (
28
+ f"GRF's media for cuju's renderer, the package {DISTRIBUTION}, is not installed; "
29
+ f'install it with {INSTALL}'
30
+ )
31
+
32
+
33
+ def root() -> pathlib.Path:
34
+ """Returns the folder of the installed media.
35
+
36
+ Raises:
37
+ MissingFileError: If cuju-grf-media is not installed, or its folder lacks the manifest.
38
+ """
39
+ try:
40
+ folder = importlib.resources.files(PACKAGE)
41
+ except ModuleNotFoundError:
42
+ raise MissingFileError(MESSAGE) from None
43
+ path = pathlib.Path(str(folder))
44
+ if not (path / 'manifest.json').is_file():
45
+ raise MissingFileError(
46
+ f'{DISTRIBUTION} at {path} lacks its manifest.json; reinstall it with {INSTALL}'
47
+ )
48
+ return path
49
+
50
+
51
+ def manifest(folder: str | os.PathLike | None = None) -> dict[str, Any]:
52
+ """Returns the manifest of the media in `folder`, by default the installed package.
53
+
54
+ Raises:
55
+ MissingFileError: If the media are missing, or their manifest is of another format.
56
+ """
57
+ path = pathlib.Path(folder) if folder is not None else root()
58
+ try:
59
+ with open(path / 'manifest.json', encoding='ascii') as handle:
60
+ content = json.load(handle)
61
+ except FileNotFoundError:
62
+ raise MissingFileError(f'{path} holds no manifest.json of {DISTRIBUTION}') from None
63
+ if content.get('format') != FORMAT:
64
+ raise MissingFileError(
65
+ f'{DISTRIBUTION} {content.get("version")} at {path} holds media of format '
66
+ f'{content.get("format")}, and this cuju reads format {FORMAT}; install the version '
67
+ f'that fits with {INSTALL}'
68
+ )
69
+ return content
70
+
71
+
72
+ def path(name: str, folder: str | os.PathLike | None = None) -> pathlib.Path:
73
+ """Returns the path of the file `name` of the manifest, such as `data/media/shaders/noise.bmp`.
74
+
75
+ Raises:
76
+ MissingFileError: If the media are missing, or the manifest or the folder lacks the file.
77
+ """
78
+ base = pathlib.Path(folder) if folder is not None else root()
79
+ content = manifest(base)
80
+ listed = {entry['path'] for entry in content['files'] + content['generated']}
81
+ if name not in listed:
82
+ raise MissingFileError(f'the manifest of {DISTRIBUTION} at {base} lists no {name}')
83
+ file = base.joinpath(*name.split('/'))
84
+ if not file.is_file():
85
+ raise MissingFileError(
86
+ f'{DISTRIBUTION} at {base} lacks {name}; reinstall it with {INSTALL}'
87
+ )
88
+ return file
89
+
90
+
91
+ def problems(folder: str | os.PathLike | None = None) -> list[str]:
92
+ """Returns what differs between the media in `folder` and their lists, or an empty list.
93
+
94
+ Every file of the manifest must be in `SHA256SUMS` with the manifest's SHA-256, and every file
95
+ of `SHA256SUMS` must have its listed SHA-256.
96
+ """
97
+ base = pathlib.Path(folder) if folder is not None else root()
98
+ content = manifest(base)
99
+ try:
100
+ listed = _checksums.read_checksums(str(base / 'SHA256SUMS'))
101
+ except (FileNotFoundError, ValueError) as error:
102
+ return [str(error)]
103
+ found = []
104
+ for entry in content['files'] + content['generated']:
105
+ if listed.get(entry['path']) != entry['sha256']:
106
+ found.append(f'SHA256SUMS and the manifest disagree on {entry["path"]}')
107
+ for name, digest in listed.items():
108
+ file = base.joinpath(*name.split('/'))
109
+ if not file.is_file():
110
+ found.append(f'missing {name}')
111
+ elif _checksums.file_sha256(file) != digest:
112
+ found.append(f'{name} differs from its SHA-256 in SHA256SUMS')
113
+ return found