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/_batch/pixels.py ADDED
@@ -0,0 +1,207 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """GRF's frames for a batch in render mode: one renderer per environment, which draws the renders
5
+ that each reset and step recorded, in GRF's order, and the `pixels` observations of the frames.
6
+
7
+ The environments draw side by side on `CUJU_RENDER_WORKERS` threads, each renderer with
8
+ `CUJU_RENDER_THREADS` threads of its own, and every frame is the same for every split."""
9
+
10
+ from __future__ import annotations
11
+
12
+ import concurrent.futures
13
+ import ctypes
14
+ import os
15
+
16
+ import numpy as np
17
+ import torch
18
+
19
+ from .. import _media, _pixels
20
+ from ..errors import ConfigurationError, LibraryError, MissingFileError
21
+
22
+ # The render events one call records per environment at most. A stoppage with a card renders
23
+ # about 150 times before play restarts.
24
+ CAPACITY = 512
25
+ # GRF: `start_game` resets to `ScenarioConfig::make()`, whose seed is 42.
26
+ INTERNAL_SEED = 42
27
+ _START, _RENDER = 1, 2
28
+ MESSAGE = (
29
+ "the representations pixels and pixels_gray and render_frames need cuju's renderer, "
30
+ "libcuju_render, and GRF's media, the package cuju-grf-media; install them with "
31
+ "pip install 'cuju-engine[pixels]'"
32
+ )
33
+
34
+
35
+ def _cpus():
36
+ try:
37
+ return len(os.sched_getaffinity(0))
38
+ except (AttributeError, OSError):
39
+ return os.cpu_count() or 1
40
+
41
+
42
+ def _count(name):
43
+ """The positive count that the environment variable `name` sets, or None."""
44
+ value = os.environ.get(name, '')
45
+ if not value:
46
+ return None
47
+ try:
48
+ count = int(value)
49
+ except ValueError:
50
+ raise ConfigurationError(f'expected {name} to be a whole number, got {value!r}') from None
51
+ return max(1, count)
52
+
53
+
54
+ def split(environments, cpus=None):
55
+ """Returns the renderers drawn at once and the threads of each for a batch of `environments`.
56
+
57
+ `CUJU_RENDER_WORKERS` and `CUJU_RENDER_THREADS` set either; by default the workers take one
58
+ environment each up to the processors there are, and share the processors out.
59
+ """
60
+ cpus = cpus or _cpus()
61
+ workers, threads = _count('CUJU_RENDER_WORKERS'), _count('CUJU_RENDER_THREADS')
62
+ if workers is None:
63
+ workers = cpus // threads if threads else cpus
64
+ workers = max(1, min(workers, environments))
65
+ if threads is None:
66
+ threads = max(1, cpus // workers)
67
+ return workers, threads
68
+
69
+
70
+ class Frames:
71
+ """The renderers of a batch and their last frames."""
72
+
73
+ def __init__(self, batch, kind, width, height, frame_size=(1280, 720)):
74
+ library = batch._library
75
+ self._batch = batch
76
+ self._library = library
77
+ self.kind = kind # 'pixels', 'pixels_gray' or None for frames alone
78
+ self.width, self.height = width, height
79
+ self.frame_width, self.frame_height = frame_size
80
+ self.event_size = library.cuju_environment_render_event_size()
81
+ self.state_size = library.cuju_engine_render_state_size()
82
+ count = batch.environment_count
83
+ batch._check(library.cuju_environment_enable_render_events(batch._handle(), CAPACITY))
84
+ self._buffer = ctypes.create_string_buffer(self.event_size * CAPACITY)
85
+ self.workers, self.threads = split(count)
86
+ self._pool = concurrent.futures.ThreadPoolExecutor(
87
+ max_workers=self.workers, thread_name_prefix='cuju-render'
88
+ )
89
+ self.renderers = []
90
+ try:
91
+ if not os.path.isfile(_pixels.library_path()):
92
+ raise MissingFileError(f'the renderer library {_pixels.library_path()} is missing')
93
+ media = os.environ.get('CUJU_GRF_MEDIA') or str(_media.root())
94
+ self.renderers = [
95
+ _pixels.Renderer(self.frame_width, self.frame_height, self.threads, media)
96
+ for _ in range(count)
97
+ ]
98
+ except (MissingFileError, LibraryError) as error:
99
+ self.close()
100
+ raise MissingFileError(f'{MESSAGE}: {error}') from None
101
+ state = ctypes.create_string_buffer(self.state_size)
102
+ # GRF: a rendering engine's `start_game` builds the first match of its graphics.
103
+ library.cuju_engine_internal_render_state(state, self.state_size, 1)
104
+ state = state.raw
105
+ self._started = [False] * count
106
+
107
+ def start(environment):
108
+ renderer = self.renderers[environment]
109
+ self._reset_steps(renderer, environment)
110
+ renderer.start_match(state, INTERNAL_SEED)
111
+
112
+ self._each(start, range(count))
113
+ channels = 3 if kind == 'pixels' else 1
114
+ agents = batch.agents
115
+ self.observation = torch.zeros((count, agents, height, width, channels), dtype=torch.uint8)
116
+ self.final_observation = torch.zeros_like(self.observation)
117
+ self.frame = torch.zeros((count, self.frame_height, self.frame_width, 3), dtype=torch.uint8)
118
+ self.final_frame = torch.zeros_like(self.frame)
119
+
120
+ def _each(self, work, environments):
121
+ """Runs `work(environment)` for each environment on the workers, raising the first error."""
122
+ environments = list(environments)
123
+ if self.workers <= 1 or len(environments) <= 1:
124
+ for environment in environments:
125
+ work(environment)
126
+ return
127
+ for future in [self._pool.submit(work, environment) for environment in environments]:
128
+ future.result()
129
+
130
+ def _reset_steps(self, renderer, environment):
131
+ """GRF's `GameEnv::reset` with rendering, up to `StartMatch`."""
132
+ renderer.reset_begin()
133
+ renderer.stop_match()
134
+ if not self._started[environment]:
135
+ renderer.loading_page()
136
+ self._started[environment] = True
137
+ renderer.render_scene(True)
138
+
139
+ def _capture(self, environment, observation, frame):
140
+ renderer = self.renderers[environment]
141
+ # The pixels go straight into the first agent's observation, and the others copy them.
142
+ # An environment without agents has no observation to fill.
143
+ agents = observation.shape[1]
144
+ if self.kind == 'pixels' and agents:
145
+ renderer.pixels(self.width, self.height, out=observation[environment, 0].numpy())
146
+ elif self.kind == 'pixels_gray' and agents:
147
+ renderer.pixels_gray(
148
+ self.width, self.height, out=observation[environment, 0, ..., 0].numpy()
149
+ )
150
+ if self.kind is not None and agents > 1:
151
+ observation[environment, 1:] = observation[environment, :1]
152
+ renderer.frame(top_down=True, out=frame[environment].numpy())
153
+
154
+ def _events(self, environment):
155
+ """The render events of the last call of `environment`, as bytes."""
156
+ count = ctypes.c_int()
157
+ batch = self._batch
158
+ batch._check(
159
+ self._library.cuju_environment_render_events(
160
+ batch._handle(), environment, self._buffer, CAPACITY, ctypes.byref(count)
161
+ )
162
+ )
163
+ if count.value < 0:
164
+ raise LibraryError(
165
+ f'environment {environment} rendered more than {CAPACITY} times in one call'
166
+ )
167
+ return count.value, self._buffer.raw[: count.value * self.event_size]
168
+
169
+ def draw(self, environments):
170
+ """Draws the events of the last call of `environments` and keeps their frames."""
171
+ environments = list(environments)
172
+ events = {environment: self._events(environment) for environment in environments}
173
+ self._each(lambda environment: self._draw(environment, *events[environment]), environments)
174
+
175
+ def _draw(self, environment, count, data):
176
+ size, state_size = self.event_size, self.state_size
177
+ renderer = self.renderers[environment]
178
+ kinds = [int(np.frombuffer(data, '<i4', 1, index * size)[0]) for index in range(count)]
179
+ rendered = False
180
+ for index in range(count):
181
+ at = index * size
182
+ state = data[at + 8 : at + 8 + state_size]
183
+ if kinds[index] == _START:
184
+ if rendered:
185
+ # The step ended the episode and the next began: its last frame is final.
186
+ self._capture(environment, self.final_observation, self.final_frame)
187
+ seed = int(np.frombuffer(data, '<u4', 1, at + 4)[0])
188
+ self._reset_steps(renderer, environment)
189
+ renderer.start_match(state, seed)
190
+ else:
191
+ # Speed: only the last render before a capture is read, and the renderer
192
+ # rasterizes none of the others, whose pixels the next render draws again.
193
+ read = index + 1 == count or kinds[index + 1] == _START
194
+ renderer.render(state, read)
195
+ rendered = True
196
+ if rendered:
197
+ self._capture(environment, self.observation, self.frame)
198
+
199
+ def state_processed(self, environment):
200
+ """GRF: a save or a load makes the next render draw the nets afresh."""
201
+ self.renderers[environment].state_processed()
202
+
203
+ def close(self):
204
+ for renderer in self.renderers:
205
+ renderer.close()
206
+ self.renderers = []
207
+ self._pool.shutdown(wait=True)
cuju/_batch/state.py ADDED
@@ -0,0 +1,77 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The pickle of a state in GRF's format, written by opcode and read back without GRF."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import pickle
9
+ import struct
10
+
11
+ from . import frame_stack as _frame_stack
12
+
13
+ # GRF's class of the episode logic, as the pickle of a state names it.
14
+ _EPISODE_CLASS = ('gfootball.env.football_env_core', 'EnvState')
15
+
16
+
17
+ class _EpisodeState:
18
+ """Stands in for GRF's `EnvState` when the pickle of a state loads."""
19
+
20
+
21
+ class _StateUnpickler(pickle.Unpickler):
22
+ """Unpickles a state, resolving only GRF's episode logic and the globals of a stacked state."""
23
+
24
+ stacked = False
25
+
26
+ def find_class(self, module, name):
27
+ if (module, name) == _EPISODE_CLASS:
28
+ return _EpisodeState
29
+ found = _frame_stack.find_class(module, name) if self.stacked else None
30
+ if found is not None:
31
+ return found
32
+ raise pickle.UnpicklingError(f'expected only the episode logic, found `{module}.{name}`')
33
+
34
+
35
+ def _pickle_integer(value):
36
+ """Returns the pickle opcode of a signed 32-bit integer."""
37
+ return b'J' + struct.pack('<i', value)
38
+
39
+
40
+ def _pickle_string(value):
41
+ """Returns the pickle opcode of a string."""
42
+ data = value.encode()
43
+ return b'X' + struct.pack('<I', len(data)) + data
44
+
45
+
46
+ def _pickle_episode(episode, collected, frames=None):
47
+ """Returns GRF's state pickle, written by opcode so that `EnvState` needs no import.
48
+
49
+ `frames` holds the opcodes of the `FrameStack` deque, or `None` without a stack.
50
+ """
51
+ module, name = _EPISODE_CLASS
52
+ logic = b''.join(
53
+ _pickle_string(key) + _pickle_integer(value)
54
+ for key, value in zip(
55
+ ('previous_score_diff', 'previous_game_mode', 'prev_ball_owned_team'),
56
+ episode,
57
+ strict=True,
58
+ )
59
+ )
60
+ data = (
61
+ b'\x80\x02}('
62
+ + _pickle_string('FootballEnvCore')
63
+ + f'c{module}\n{name}\n'.encode()
64
+ + b')\x81}('
65
+ + logic
66
+ + b'ub'
67
+ )
68
+ if collected is not None:
69
+ checkpoints = b''.join(
70
+ _pickle_integer(agent) + _pickle_integer(count)
71
+ for agent, count in enumerate(collected)
72
+ if count
73
+ )
74
+ data += _pickle_string('CheckpointRewardWrapper') + b'}(' + checkpoints + b'u'
75
+ if frames is not None:
76
+ data += _pickle_string('FrameStack') + frames
77
+ return data + b'u.'
cuju/_checksums.py ADDED
@@ -0,0 +1,60 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The SHA-256 of files, and the list in `data/SHA256SUMS` of the bundles and `animations.bin`."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import os
9
+
10
+ DATA_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
11
+ # The list, in the format of `sha256sum`, so `sha256sum -c SHA256SUMS` in `data` checks it too.
12
+ CHECKSUMS = os.path.join(DATA_DIRECTORY, 'SHA256SUMS')
13
+
14
+
15
+ def file_sha256(path: str | os.PathLike) -> str:
16
+ """Returns the SHA-256 of a file's bytes, in hexadecimal."""
17
+ digest = hashlib.sha256()
18
+ with open(path, 'rb') as handle:
19
+ for block in iter(lambda: handle.read(1 << 20), b''):
20
+ digest.update(block)
21
+ return digest.hexdigest()
22
+
23
+
24
+ def data_files(directory: str = DATA_DIRECTORY) -> list[str]:
25
+ """Returns the paths that the list covers, relative to `directory` and with `/`.
26
+
27
+ The animation tables come first, then every shipped bundle by name.
28
+ """
29
+ names = ['animations.bin'] if os.path.isfile(os.path.join(directory, 'animations.bin')) else []
30
+ assets = os.path.join(directory, 'assets')
31
+ if os.path.isdir(assets):
32
+ names += sorted(f'assets/{name}' for name in os.listdir(assets) if name.endswith('.cjb'))
33
+ return names
34
+
35
+
36
+ def data_checksums(directory: str = DATA_DIRECTORY) -> dict[str, str]:
37
+ """Returns the SHA-256 of each file of `data_files`, by its relative path."""
38
+ return {name: file_sha256(os.path.join(directory, name)) for name in data_files(directory)}
39
+
40
+
41
+ def format_checksums(checksums: dict[str, str]) -> str:
42
+ """Returns the text of the list, one `<SHA-256> <path>` line per file as `sha256sum` writes."""
43
+ return ''.join(f'{digest} {name}\n' for name, digest in checksums.items())
44
+
45
+
46
+ def read_checksums(path: str = CHECKSUMS) -> dict[str, str]:
47
+ """Returns the SHA-256 of each file that the list at `path` names, by its relative path.
48
+
49
+ Raises:
50
+ FileNotFoundError: If there is no list at `path`.
51
+ ValueError: If a line of the list is not `<SHA-256> <path>`.
52
+ """
53
+ checksums = {}
54
+ with open(path, encoding='ascii') as handle:
55
+ for number, line in enumerate(handle, 1):
56
+ digest, separator, name = line.rstrip('\r\n').partition(' ')
57
+ if not separator or len(digest) != 64 or digest.strip('0123456789abcdef') or not name:
58
+ raise ValueError(f'expected `<SHA-256> <path>` at line {number} of {path}')
59
+ checksums[name] = digest
60
+ return checksums
cuju/_cli_contract.py ADDED
@@ -0,0 +1,244 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Private command line helpers for the family contract."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import errno
10
+ import json
11
+ import os
12
+ import re
13
+ import sys
14
+ import traceback
15
+ import unicodedata
16
+ from collections.abc import Callable, Sequence
17
+
18
+ EXIT_NO = 1
19
+ EXIT_USAGE = 2
20
+ EXIT_ENVIRONMENT = 3
21
+ EXIT_INTERNAL = 70
22
+ EXIT_INTERRUPTED = 130
23
+
24
+ GLOBAL_FLAGS = ('-q', '--quiet', '-v', '--verbose')
25
+
26
+
27
+ def is_global(flag: str) -> bool:
28
+ return flag in GLOBAL_FLAGS or (
29
+ flag.startswith('-') and len(flag) > 1 and set(flag[1:]) <= {'q', 'v'}
30
+ )
31
+
32
+
33
+ def options(arguments: Sequence[str]) -> Sequence[str]:
34
+ """Returns the arguments before the end of options."""
35
+ return arguments[: arguments.index('--')] if '--' in arguments else arguments
36
+
37
+
38
+ def emit(schema: str, payload: dict) -> None:
39
+ """Prints the JSON answer with its schema first."""
40
+ print(json.dumps({'schema': schema, **payload}, indent=2))
41
+
42
+
43
+ def quote_path(path: str | os.PathLike[str]) -> str:
44
+ """Quotes a path for an error or hint line."""
45
+ text = os.fspath(path)
46
+ if (
47
+ "'" in text
48
+ or '"' in text
49
+ or any(unicodedata.category(char) in ('Cc', 'Cf', 'Cs', 'Zl', 'Zp') for char in text)
50
+ ):
51
+ return repr(text)
52
+ return f"'{text}'"
53
+
54
+
55
+ def fail(
56
+ prog: str,
57
+ error: str,
58
+ *,
59
+ hint: str | None = None,
60
+ as_json: bool = False,
61
+ status: int = EXIT_NO,
62
+ error_id: str | None = None,
63
+ values: dict | None = None,
64
+ ) -> int:
65
+ """Prints an error and returns its status."""
66
+ error = ' '.join(error.splitlines())
67
+ print(f'{prog}: error: {error}', file=sys.stderr)
68
+ if hint:
69
+ print(f'{prog}: hint: {hint}', file=sys.stderr)
70
+ if as_json:
71
+ emit(
72
+ 'error/1',
73
+ {
74
+ 'error': error,
75
+ 'error_id': error_id,
76
+ 'error_values': values or {},
77
+ 'hint': hint,
78
+ 'exit': status,
79
+ },
80
+ )
81
+ return status
82
+
83
+
84
+ class _HelpFormatter(argparse.RawDescriptionHelpFormatter):
85
+ """Wraps single-line descriptions and preserves the layout of examples."""
86
+
87
+ def _fill_text(self, text, width, indent):
88
+ if '\n' not in text:
89
+ return argparse.HelpFormatter._fill_text(self, text, width, indent)
90
+ return super()._fill_text(text, width, indent)
91
+
92
+
93
+ class Parser(argparse.ArgumentParser):
94
+ """Prints usage errors in the family format."""
95
+
96
+ def __init__(self, *args, **kwargs):
97
+ kwargs.setdefault('formatter_class', _HelpFormatter)
98
+ kwargs.setdefault('allow_abbrev', False)
99
+ super().__init__(*args, **kwargs)
100
+ self._as_json = False
101
+
102
+ def parse_known_args(self, args=None, namespace=None):
103
+ flags = options(sys.argv[1:] if args is None else args)
104
+ self._as_json = '--json' in self._option_string_actions and any(
105
+ flag == '--json' or flag.startswith('--json=') for flag in flags
106
+ )
107
+ return super().parse_known_args(args, namespace)
108
+
109
+ def parse_args(self, args=None, namespace=None):
110
+ parsed, remaining = self.parse_known_args(args, namespace)
111
+ if remaining:
112
+ selected = getattr(parsed, '_command_parser', self)
113
+ selected.error(
114
+ f'expected arguments accepted by {selected.prog}, found '
115
+ + ', '.join(map(repr, remaining))
116
+ )
117
+ return parsed
118
+
119
+ def _check_value(self, action, value):
120
+ if action.choices is not None and value not in action.choices:
121
+ accepted = ', '.join(map(str, action.choices))
122
+ name = action.option_strings[-1] if action.option_strings else action.metavar
123
+ raise argparse.ArgumentError(
124
+ action, f'expected {name} to be one of {accepted}, found {value!r}'
125
+ )
126
+
127
+ def error(self, message, *, hint=None):
128
+ missing = 'the following arguments are required: '
129
+ if message.startswith(missing):
130
+ message = f'expected {message[len(missing) :]}, found missing arguments'
131
+ elif match := re.fullmatch(r'argument (.+): ignored explicit argument (.+)', message):
132
+ message = f'expected {match[1]} without a value, found {match[2]}'
133
+ elif match := re.fullmatch(r'argument (.+?): (.+)', message):
134
+ name, detail = match.groups()
135
+ if detail == 'expected one argument':
136
+ message = f'expected a value for {name}, found none'
137
+ elif detail.startswith('invalid int value: '):
138
+ value = detail.removeprefix('invalid int value: ')
139
+ message = f'expected an integer for {name}, found {value}'
140
+ elif detail.startswith('expected '):
141
+ message = detail
142
+ else:
143
+ message = f'{name}, {detail}'
144
+ self.print_usage(sys.stderr)
145
+ raise SystemExit(
146
+ fail(
147
+ self.prog,
148
+ message,
149
+ hint=hint or f'run {self.prog} --help for the options.',
150
+ as_json=self._as_json,
151
+ status=EXIT_USAGE,
152
+ error_id='usage',
153
+ )
154
+ )
155
+
156
+
157
+ def add_globals(parser: argparse.ArgumentParser) -> None:
158
+ """Adds options that work at the root and on each command."""
159
+ parser.add_argument(
160
+ '-q',
161
+ '--quiet',
162
+ action='store_true',
163
+ default=argparse.SUPPRESS,
164
+ help='print nothing on standard error but errors',
165
+ )
166
+ parser.add_argument(
167
+ '-v',
168
+ '--verbose',
169
+ action='store_true',
170
+ default=argparse.SUPPRESS,
171
+ help='print debug lines and the traceback of an error',
172
+ )
173
+
174
+
175
+ def add_json(parser: argparse.ArgumentParser) -> None:
176
+ parser.add_argument(
177
+ '--json', action='store_true', help='print one JSON object on standard output'
178
+ )
179
+
180
+
181
+ def examples(*lines: str) -> str:
182
+ return 'Examples\n' + '\n'.join(f' {line}' for line in lines)
183
+
184
+
185
+ def _close_output() -> None:
186
+ """Redirects standard output so the final flush can finish."""
187
+ try:
188
+ with open(os.devnull, 'wb') as sink:
189
+ os.dup2(sink.fileno(), sys.stdout.fileno())
190
+ except (OSError, ValueError):
191
+ pass
192
+
193
+
194
+ def _is_closed_pipe(error: BaseException) -> bool:
195
+ return isinstance(error, BrokenPipeError) or (
196
+ sys.platform == 'win32' and isinstance(error, OSError) and error.errno == errno.EINVAL
197
+ )
198
+
199
+
200
+ def guarded(prog: str, function: Callable[[], int | None], arguments: Sequence[str]) -> int:
201
+ """Runs a command and converts exceptions to exit statuses."""
202
+ flags = options(arguments)
203
+ try:
204
+ try:
205
+ status = function()
206
+ except SystemExit as error:
207
+ status = error.code
208
+ if status is not None and not isinstance(status, int):
209
+ status = fail(prog, str(status), as_json='--json' in flags)
210
+ except Exception as error:
211
+ if _is_closed_pipe(error):
212
+ raise
213
+ status = fail(
214
+ prog,
215
+ f'internal error, {type(error).__name__}, {error}',
216
+ hint='rerun with --verbose and report the traceback.',
217
+ as_json='--json' in flags,
218
+ status=EXIT_INTERNAL,
219
+ error_id='internal',
220
+ values={'type': type(error).__name__},
221
+ )
222
+ if any(is_global(flag) and 'v' in flag for flag in flags):
223
+ traceback.print_exc()
224
+ sys.stdout.flush()
225
+ return status or 0
226
+ except OSError as error:
227
+ if not _is_closed_pipe(error):
228
+ raise
229
+ _close_output()
230
+ return 0
231
+ except KeyboardInterrupt:
232
+ return EXIT_INTERRUPTED
233
+
234
+
235
+ def run_command(
236
+ parser: Parser, execute: Callable[[argparse.Namespace], int], argv: list[str] | None
237
+ ) -> int:
238
+ arguments = sys.argv[1:] if argv is None else argv
239
+ return guarded(parser.prog, lambda: execute(parser.parse_args(arguments)), arguments)
240
+
241
+
242
+ def subcommands(tree: argparse.ArgumentParser):
243
+ """Yields the subparser groups of a command."""
244
+ return (action for action in tree._actions if isinstance(action, argparse._SubParsersAction))