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/_pixels.py ADDED
@@ -0,0 +1,276 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Loads libcuju_render, cuju's software renderer of GRF's frames, through ctypes.
5
+
6
+ One `Renderer` stands for one rendering GRF engine, a GameEnv, and its methods follow where
7
+ GameEnv touches graphics: the steps of a reset, the start of a match, and each render of a
8
+ RenderState, the bytes of `include/cuju/render/render_state.h`. The media come from cuju-grf-media
9
+ through `cuju._media` unless a folder is given. `CUJU_RENDER_LIBRARY` overrides the library's path.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ctypes
15
+ import os
16
+ import sys
17
+ import threading
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+
22
+ from . import _media
23
+ from .errors import ArgumentError, LibraryError, MissingFileError, StateError
24
+
25
+ # The C API this module speaks, `CUJU_RENDER_API_VERSION` of src/render/render_api.h.
26
+ API_VERSION = 2
27
+ # GRF's pixels and pixels_gray observations, `SMM_WIDTH` by `SMM_HEIGHT`.
28
+ PIXELS_WIDTH = 96
29
+ PIXELS_HEIGHT = 72
30
+
31
+ if os.name == 'nt':
32
+ _FILE = 'cuju_render.dll'
33
+ elif sys.platform == 'darwin':
34
+ _FILE = 'libcuju_render.dylib'
35
+ else:
36
+ _FILE = 'libcuju_render.so'
37
+ _VARIABLE = 'CUJU_RENDER_LIBRARY'
38
+ _ERRORS = {1: ArgumentError, 2: MissingFileError, 3: StateError, 4: LibraryError}
39
+ _lock = threading.Lock()
40
+ _library = None
41
+
42
+
43
+ def library_path() -> str:
44
+ """Returns the path of libcuju_render, from `CUJU_RENDER_LIBRARY` or beside this module."""
45
+ return os.environ.get(_VARIABLE) or os.path.join(os.path.dirname(__file__), _FILE)
46
+
47
+
48
+ def _load() -> ctypes.CDLL:
49
+ global _library
50
+ with _lock:
51
+ if _library is not None:
52
+ return _library
53
+ path = library_path()
54
+ if not os.path.isfile(path):
55
+ raise MissingFileError(
56
+ f"cuju's renderer library {path} does not exist; build cuju with the renderer, "
57
+ f'or set {_VARIABLE} to its path'
58
+ )
59
+ try:
60
+ handle = ctypes.CDLL(path)
61
+ except OSError as error:
62
+ raise LibraryError(f'cannot load the renderer library {path}: {error}') from None
63
+ handle.cuju_render_api_version.restype = ctypes.c_uint32
64
+ if handle.cuju_render_api_version() != API_VERSION:
65
+ raise LibraryError(
66
+ f'the renderer library {path} speaks C API {handle.cuju_render_api_version()}, '
67
+ f'and this cuju speaks {API_VERSION}; reinstall cuju'
68
+ )
69
+ pointer = ctypes.c_void_p
70
+ size = ctypes.c_size_t
71
+ handle.cuju_render_state_version.restype = ctypes.c_uint32
72
+ handle.cuju_render_state_size.restype = size
73
+ handle.cuju_render_last_error.restype = ctypes.c_char_p
74
+ handle.cuju_render_create.argtypes = [
75
+ ctypes.c_int,
76
+ ctypes.c_int,
77
+ ctypes.c_int,
78
+ ctypes.c_char_p,
79
+ ctypes.POINTER(pointer),
80
+ ]
81
+ handle.cuju_render_destroy.argtypes = [pointer]
82
+ handle.cuju_render_destroy.restype = None
83
+ for name in ('reset_begin', 'stop_match', 'loading_page', 'state_processed'):
84
+ getattr(handle, 'cuju_render_' + name).argtypes = [pointer]
85
+ handle.cuju_render_render_scene.argtypes = [pointer, ctypes.c_int]
86
+ handle.cuju_render_set_render.argtypes = [pointer, ctypes.c_int]
87
+ handle.cuju_render_start_match.argtypes = [pointer, pointer, size, ctypes.c_uint32]
88
+ handle.cuju_render_render.argtypes = [pointer, pointer, size, ctypes.c_int]
89
+ handle.cuju_render_frame.argtypes = [pointer, ctypes.c_int, pointer, size]
90
+ handle.cuju_render_pixels.argtypes = [pointer, ctypes.c_int, ctypes.c_int, pointer, size]
91
+ handle.cuju_render_pixels_gray.argtypes = handle.cuju_render_pixels.argtypes
92
+ handle.cuju_render_has_frame.argtypes = [pointer, ctypes.POINTER(ctypes.c_int)]
93
+ handle.cuju_render_digests.argtypes = [pointer, ctypes.c_char_p, size]
94
+ handle.cuju_render_digests.restype = size
95
+ _library = handle
96
+ return handle
97
+
98
+
99
+ def _check(status: int) -> None:
100
+ if status:
101
+ message = _load().cuju_render_last_error().decode('utf-8', 'replace')
102
+ raise _ERRORS.get(status, LibraryError)(message)
103
+
104
+
105
+ def state_size() -> int:
106
+ """Returns the bytes of one RenderState, as the library reads it."""
107
+ return _load().cuju_render_state_size()
108
+
109
+
110
+ def state_version() -> int:
111
+ """Returns `RENDER_STATE_VERSION`, the RenderState layout the library reads."""
112
+ return _load().cuju_render_state_version()
113
+
114
+
115
+ def _state(state: Any) -> tuple[Any, int, Any]:
116
+ """Returns a pointer to the bytes of a RenderState, their size, and what keeps them alive."""
117
+ try:
118
+ view = memoryview(state).cast('B')
119
+ except TypeError:
120
+ raise ArgumentError('a RenderState must be contiguous bytes') from None
121
+ keep = (ctypes.c_char * view.nbytes).from_buffer_copy(view)
122
+ return ctypes.cast(keep, ctypes.c_void_p), view.nbytes, keep
123
+
124
+
125
+ def _output(out, shape):
126
+ """Returns `out` checked to hold an image of `shape`, or a new array."""
127
+ if out is None:
128
+ return np.empty(shape, np.uint8)
129
+ if out.shape != shape or out.dtype != np.uint8 or not out.flags.c_contiguous:
130
+ raise ArgumentError(
131
+ f'expected a C-contiguous uint8 array of shape {shape}, got {out.dtype} {out.shape}'
132
+ )
133
+ if not out.flags.writeable:
134
+ raise ArgumentError('expected a writeable array')
135
+ return out
136
+
137
+
138
+ class Renderer:
139
+ """One rendering GRF engine's graphics, drawn by cuju's software renderer.
140
+
141
+ Args:
142
+ width: The frame's width in pixels, a multiple of 4.
143
+ height: The frame's height in pixels.
144
+ threads: The threads that draw each frame. The frame is the same for every count.
145
+ media: The folder of GRF's media, by default the installed cuju-grf-media.
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ width: int = 1280,
151
+ height: int = 720,
152
+ threads: int = 1,
153
+ media: str | os.PathLike | None = None,
154
+ ):
155
+ library = _load()
156
+ folder = os.fspath(media) if media is not None else str(_media.root())
157
+ handle = ctypes.c_void_p()
158
+ _check(
159
+ library.cuju_render_create(
160
+ int(width), int(height), int(threads), folder.encode('utf-8'), ctypes.byref(handle)
161
+ )
162
+ )
163
+ self._library = library
164
+ self._handle = handle
165
+ self.width = int(width)
166
+ self.height = int(height)
167
+ self.threads = int(threads)
168
+
169
+ def _call(self, name: str, *arguments: Any) -> None:
170
+ if not self._handle:
171
+ raise StateError('the renderer is closed')
172
+ _check(getattr(self._library, 'cuju_render_' + name)(self._handle, *arguments))
173
+
174
+ def reset_begin(self) -> None:
175
+ """GameEnv::reset's first graphics step: the unused resources go, the pages clear."""
176
+ self._call('reset_begin')
177
+
178
+ def stop_match(self) -> None:
179
+ """GameTask::StopMatch: the running match leaves the scene."""
180
+ self._call('stop_match')
181
+
182
+ def loading_page(self) -> None:
183
+ """The loading page that the first reset of an engine shows."""
184
+ self._call('loading_page')
185
+
186
+ def render_scene(self, swap: bool = True) -> None:
187
+ """GraphicsTask::Render alone, as the reset calls it between two matches."""
188
+ self._call('render_scene', int(bool(swap)))
189
+
190
+ def start_match(self, state: Any, seed: int) -> None:
191
+ """GameTask::StartMatch with the new match's RenderState and its engine seed."""
192
+ pointer, size, keep = _state(state)
193
+ self._call('start_match', pointer, size, int(seed) & 0xFFFFFFFF)
194
+ del keep
195
+
196
+ def state_processed(self) -> None:
197
+ """GameEnv::ProcessState of the rendering match, at each get_state and set_state."""
198
+ self._call('state_processed')
199
+
200
+ def set_render(self, render: bool) -> None:
201
+ """GRF's `game_config.render`, on at first.
202
+
203
+ Off, `start_match` builds GRF's match without rendering, on the pitch alone, and
204
+ captions keep their text.
205
+ """
206
+ self._call('set_render', int(bool(render)))
207
+
208
+ def render(self, state: Any, swap: bool = True) -> None:
209
+ """GameEnv::render of one RenderState; with `swap` the frame is read back."""
210
+ pointer, size, keep = _state(state)
211
+ self._call('render', pointer, size, int(bool(swap)))
212
+ del keep
213
+
214
+ def has_frame(self) -> bool:
215
+ """Whether a frame was read back."""
216
+ value = ctypes.c_int()
217
+ self._call('has_frame', ctypes.byref(value))
218
+ return bool(value.value)
219
+
220
+ def frame(self, top_down: bool = False, out: np.ndarray | None = None) -> np.ndarray:
221
+ """Returns the last frame, `[height, width, 3]` RGB bytes.
222
+
223
+ Rows run from the bottom as glReadPixels gives them, or from the top as GRF's
224
+ observation `frame` holds them when `top_down` is set. With `out`, a C-contiguous
225
+ `uint8` array of that shape, the bytes go there and `out` is returned.
226
+ """
227
+ out = _output(out, (self.height, self.width, 3))
228
+ self._call('frame', int(bool(top_down)), out.ctypes.data, out.nbytes)
229
+ return out
230
+
231
+ def pixels(
232
+ self, width: int = PIXELS_WIDTH, height: int = PIXELS_HEIGHT, out: np.ndarray | None = None
233
+ ) -> np.ndarray:
234
+ """Returns GRF's pixels of the last frame, `[height, width, 3]`, OpenCV's INTER_AREA."""
235
+ out = _output(out, (height, width, 3))
236
+ self._call('pixels', int(width), int(height), out.ctypes.data, out.nbytes)
237
+ return out
238
+
239
+ def pixels_gray(
240
+ self, width: int = PIXELS_WIDTH, height: int = PIXELS_HEIGHT, out: np.ndarray | None = None
241
+ ) -> np.ndarray:
242
+ """Returns GRF's pixels_gray of the last frame, `[height, width]`, RGB2GRAY then area."""
243
+ out = _output(out, (height, width))
244
+ self._call('pixels_gray', int(width), int(height), out.ctypes.data, out.nbytes)
245
+ return out
246
+
247
+ def digests(self) -> dict[str, str]:
248
+ """Returns the SHA-256 of the renderer's fixed data by name, for checks."""
249
+ if not self._handle:
250
+ raise StateError('the renderer is closed')
251
+ size = self._library.cuju_render_digests(self._handle, None, 0)
252
+ buffer = ctypes.create_string_buffer(size + 1)
253
+ self._library.cuju_render_digests(self._handle, buffer, size + 1)
254
+ out = {}
255
+ for line in buffer.value.decode('ascii').splitlines():
256
+ name, _, value = line.rpartition(' ')
257
+ out[name] = value
258
+ return out
259
+
260
+ def close(self) -> None:
261
+ """Frees the renderer. Closing twice does nothing."""
262
+ if self._handle:
263
+ self._library.cuju_render_destroy(self._handle)
264
+ self._handle = ctypes.c_void_p()
265
+
266
+ def __enter__(self) -> Renderer:
267
+ return self
268
+
269
+ def __exit__(self, *exception: Any) -> None:
270
+ self.close()
271
+
272
+ def __del__(self) -> None:
273
+ try:
274
+ self.close()
275
+ except Exception:
276
+ pass
cuju/_plugins.py ADDED
@@ -0,0 +1,106 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """What cuju knows of the packages that install beside it, as `cuju.<name>`, and one hook.
5
+
6
+ A package that installs beside cuju puts its module into the folder `cuju`, and an editable
7
+ install of it keeps the module in its own `cuju` folder, which `import cuju` joins to the
8
+ package. Nothing here names such a package. A `cuju.<name>` that no finder has gets a message that
9
+ suggests the package `cuju-<name>`, from one finder at the end of `sys.meta_path`, which Python
10
+ asks only after every other finder has found nothing.
11
+
12
+ Every batch that cuju creates while `CUJU_BATCH_HOOKS` names hooks hands itself to each, and a hook
13
+ is the entry point of that name in the group `cuju.batch_hooks`, a function that takes the batch. A
14
+ process that sets nothing imports nothing and reads no entry points.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import os
21
+ import sys
22
+ from typing import Any
23
+
24
+ # The variable that names the hooks of every batch of a process, separated by commas.
25
+ VARIABLE = 'CUJU_BATCH_HOOKS'
26
+ # The group of entry points that holds the hooks.
27
+ GROUP = 'cuju.batch_hooks'
28
+ _LOGGER = logging.getLogger('cuju')
29
+ # The hooks that a batch has already warned of as missing, once each.
30
+ _warned: set[str] = set()
31
+
32
+
33
+ def hint(module: str) -> str:
34
+ """Returns the message that suggests the package of a module `cuju.<name>` that is missing."""
35
+ package = 'cuju-' + module.partition('.')[2].partition('.')[0].replace('_', '-')
36
+ return (
37
+ f'No module named {module!r}. A package that installs beside cuju provides it, and '
38
+ f'{package} may be that package: pip install {package}'
39
+ )
40
+
41
+
42
+ class _Missing:
43
+ """Suggests the package of `cuju.<name>` when it is imported and no other finder has it.
44
+
45
+ It answers only for a module of one level below cuju whose name is public, so an import of a
46
+ module deeper down fails through its package, and every other module that no finder has fails as
47
+ it always does.
48
+ """
49
+
50
+ def find_spec(self, name: str, path: Any = None, target: Any = None) -> None:
51
+ parts = name.split('.')
52
+ if len(parts) == 2 and parts[0] == 'cuju' and not parts[1].startswith('_'):
53
+ raise ModuleNotFoundError(hint(name), name=name)
54
+ return None
55
+
56
+
57
+ def install_finder() -> None:
58
+ """Adds the finder of a missing package at the end of `sys.meta_path`, once."""
59
+ if not any(isinstance(finder, _Missing) for finder in sys.meta_path):
60
+ sys.meta_path.append(_Missing())
61
+
62
+
63
+ def is_missing(error: BaseException) -> bool:
64
+ """Returns whether an import failed because a module `cuju.<name>` itself is missing."""
65
+ name = getattr(error, 'name', None) or ''
66
+ return isinstance(error, ModuleNotFoundError) and name.count('.') == 1 and name[:5] == 'cuju.'
67
+
68
+
69
+ def requested() -> list[str]:
70
+ """Returns the hooks that `CUJU_BATCH_HOOKS` names."""
71
+ return [name.strip() for name in os.environ.get(VARIABLE, '').split(',') if name.strip()]
72
+
73
+
74
+ def on_batch_created(batch: Any) -> None:
75
+ """Hands a new batch to each hook that `CUJU_BATCH_HOOKS` names, and never fails the batch.
76
+
77
+ A hook that no package provides gives one warning through the logger `cuju` per process, and a
78
+ hook that fails gives one warning for the batch, which then runs as it would without the hook.
79
+ """
80
+ names = requested()
81
+ if not names:
82
+ return
83
+ from importlib import metadata
84
+
85
+ found = {entry.name: entry for entry in metadata.entry_points(group=GROUP)}
86
+ for name in names:
87
+ entry = found.get(name)
88
+ if entry is None:
89
+ if name not in _warned:
90
+ _warned.add(name)
91
+ _LOGGER.warning(
92
+ 'cuju: %s names the hook %r, which no installed package provides. '
93
+ 'Every batch runs without it.',
94
+ VARIABLE,
95
+ name,
96
+ )
97
+ continue
98
+ try:
99
+ entry.load()(batch)
100
+ except Exception as error:
101
+ _LOGGER.warning(
102
+ 'cuju: the hook %r gave the batch nothing, %s: %s',
103
+ name,
104
+ type(error).__name__,
105
+ error,
106
+ )
@@ -0,0 +1,224 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The players of `extra_players` that Python modules define, as GRF loads them.
6
+
7
+ The player `<name>` of a definition such as `<name>:right_players=1` loads from the module
8
+ `cuju.gfootball.env.players.<name>`, else from the module path `<name>`, and its class
9
+ `Player(player_config, env_config)` acts on the host each step on GRF's raw observations. The
10
+ player `replay` is cuju's, which reads its dump with `cuju.dumps`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import importlib
17
+ import re
18
+ from types import ModuleType
19
+ from typing import Any
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ from . import dumps
25
+ from .raw import grf_observations
26
+
27
+ _PACKAGE = 'cuju.gfootball.env.players'
28
+ _MODULE_PATH = re.compile(r'\w+(\.\w+)*')
29
+
30
+
31
+ def _import(name):
32
+ """Imports a module, or returns `None` if it does not exist."""
33
+ try:
34
+ return importlib.import_module(name)
35
+ except ModuleNotFoundError as error:
36
+ # A module that the player's module imports and lacks is the player's error.
37
+ if error.name is not None and (name == error.name or name.startswith(error.name + '.')):
38
+ return None
39
+ raise
40
+
41
+
42
+ def player_module(name: str) -> ModuleType | None:
43
+ """Returns the module that defines the player `name`, or `None`."""
44
+ if not _MODULE_PATH.fullmatch(name):
45
+ return None
46
+ # The replay player reads its dump with `cuju.dumps`, which takes the names of GRF's classes.
47
+ candidates = ('cuju._replay_player',) if name == 'replay' else (f'{_PACKAGE}.{name}', name)
48
+ for candidate in candidates:
49
+ module = _import(candidate)
50
+ if module is not None:
51
+ return module
52
+ return None
53
+
54
+
55
+ def _match_view(observation, sticky_names):
56
+ """Returns the observation of a right player as the match is, from the one turned for it.
57
+
58
+ GRF: `observation_rotation.flip_observation`, which turns the match back as well.
59
+ """
60
+ view = {}
61
+ for key in ('ball', 'ball_direction'):
62
+ point = observation[key]
63
+ view[key] = np.array([-point[0], -point[1], point[2]])
64
+ view['ball_rotation'] = observation['ball_rotation']
65
+ owned = observation['ball_owned_team']
66
+ view['ball_owned_team'] = 1 - owned if owned > -1 else -1
67
+ view['ball_owned_player'] = observation['ball_owned_player']
68
+ view['score'] = [observation['score'][1], observation['score'][0]]
69
+ view['game_mode'] = observation['game_mode']
70
+ view['steps_left'] = observation['steps_left']
71
+ for source, target in (('left', 'right'), ('right', 'left')):
72
+ view[f'{target}_team'] = -observation[f'{source}_team']
73
+ view[f'{target}_team_direction'] = -observation[f'{source}_team_direction']
74
+ for suffix in ('tired_factor', 'active', 'yellow_card', 'roles'):
75
+ view[f'{target}_team_{suffix}'] = observation[f'{source}_team_{suffix}']
76
+ view['designated'] = observation['designated']
77
+ view['active'] = observation['active']
78
+ view['sticky_actions'] = np.array(
79
+ dumps._flip_sticky(list(observation['sticky_actions']), sticky_names), dtype=np.uint8
80
+ )
81
+ return view
82
+
83
+
84
+ class PythonPlayer:
85
+ """One player of `extra_players` that a module defines, run on the host each step."""
86
+
87
+ def __init__(self, player: Any, slots: list[int], left: int, action_set: str) -> None:
88
+ self.player = player
89
+ self._slots = slots
90
+ self._left = left
91
+ self._names = dumps._ACTION_SETS[action_set]
92
+ self._sticky = [name for name in self._names if name in dumps._STICKY]
93
+ self._batch = None
94
+
95
+ def bind(self, batch: Any) -> PythonPlayer:
96
+ """Plays the agents `slots` of environment 0 of `batch`."""
97
+ self._batch = batch
98
+ return self
99
+
100
+ def _index(self, action, turned):
101
+ """Returns the index in the action set of an action of the player.
102
+
103
+ GRF: `football_action_set.named_action_from_action_set`.
104
+ """
105
+ names = self._names
106
+ if hasattr(action, '_name') and hasattr(action, '_backend_action'):
107
+ name = action._name
108
+ if name not in names:
109
+ raise ValueError(
110
+ f'expected an action of the set of the environment, found {name!r}, so create '
111
+ 'the environment with a set that holds it'
112
+ )
113
+ elif isinstance(action, (bool, int, np.int32, np.int64)):
114
+ index = int(action)
115
+ if not index < len(names):
116
+ raise ValueError(f'expected an action inside the action set, found {index}')
117
+ name = names[index]
118
+ else:
119
+ raise TypeError(f'expected an action index or a CoreAction, found {action!r}')
120
+ if turned:
121
+ name = dumps._FLIPPED.get(name, name)
122
+ return names.index(name)
123
+
124
+ def act(self) -> torch.Tensor:
125
+ """Returns the actions of the player's agents, from its `take_action`."""
126
+ observations = grf_observations(self._batch, 0, self._slots) if self._slots else []
127
+ # GRF: a player that plays the right side as it is sees the match as it is.
128
+ right_as_is = bool(self.player.can_play_right())
129
+ if right_as_is:
130
+ for index in range(self._left, len(observations)):
131
+ observations[index] = _match_view(observations[index], self._sticky)
132
+ actions = self.player.take_action(observations)
133
+ # GRF: `FootballEnv._action_to_list`.
134
+ if isinstance(actions, np.ndarray):
135
+ actions = actions.tolist()
136
+ if not isinstance(actions, list):
137
+ actions = [actions]
138
+ if len(actions) != len(observations):
139
+ raise ValueError(
140
+ f'Player provided {len(actions)} actions instead of {len(observations)}.'
141
+ )
142
+ indices = [
143
+ self._index(action, right_as_is and position >= self._left)
144
+ for position, action in enumerate(actions)
145
+ ]
146
+ return torch.tensor(indices, dtype=torch.int64)
147
+
148
+ def reset(self) -> None:
149
+ self.player.reset()
150
+
151
+
152
+ class PythonPlayers:
153
+ """The players of an environment that modules define, and GRF's `env_config` that they share.
154
+
155
+ Attributes:
156
+ config: GRF's `Config` of the environment, which each player's constructor receives as
157
+ `env_config`. It follows the episodes of the environment, as GRF's does.
158
+ scripted: The scripted players of the environment, each a name or a `PythonPlayer`, with
159
+ its agents.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ definitions: list[str],
165
+ parsed: list[tuple[Any, ...]],
166
+ scripted: list[tuple[str, list[int]]],
167
+ config: Any,
168
+ action_set: str,
169
+ ) -> None:
170
+ """Builds the players in the order of their definitions, as GRF's `FootballEnv` does.
171
+
172
+ Args:
173
+ definitions: GRF's player definitions of the environment.
174
+ parsed: Each definition's name, first left position, left players, first right
175
+ position, right players and parameters.
176
+ scripted: The environment's scripted players, names with their agents, in order.
177
+ config: GRF's `Config` of the environment, as it stands before the core's first reset.
178
+ action_set: The name of the action set.
179
+ """
180
+ from ._grf_config import parse_player_definition
181
+
182
+ self.config = config
183
+ others = {name for name, *_ in parsed if name not in ('agent', 'bot', 'lazy')}
184
+ built = []
185
+ shared: dict[str, Any] = {'index': 0}
186
+ for definition, (name, _, left, _, _, _) in zip(definitions, parsed, strict=True):
187
+ _, parameters = parse_player_definition(definition)
188
+ key = f'player_{name}'
189
+ shared[key] = shared[key] + 1 if key in shared else 0
190
+ if name in ('keyboard', 'gamepad'):
191
+ raise ValueError(
192
+ f'expected a player that acts on observations, found {definition!r}, one of '
193
+ "GRF's keyboard and gamepad players, which take a person's input in GRF's "
194
+ 'rendered game'
195
+ )
196
+ if name in others:
197
+ player_config = copy.deepcopy(shared)
198
+ player_config.update(parameters)
199
+ module = player_module(name)
200
+ if module is None:
201
+ raise ValueError(
202
+ f'expected the players agent, bot, lazy, or a module that defines the '
203
+ f'player, in {definition!r}, and found no module {_PACKAGE}.{name} or '
204
+ f'{name}'
205
+ )
206
+ player_class = getattr(module, 'Player', None)
207
+ if player_class is None:
208
+ raise ValueError(f'expected a class Player in the module {module.__name__}')
209
+ built.append((player_class(player_config, self.config), left))
210
+ shared['index'] += 1
211
+ players = iter(built)
212
+ self.scripted = []
213
+ self.players = []
214
+ for name, slots in scripted:
215
+ if name in others:
216
+ player, left = next(players)
217
+ name = PythonPlayer(player, slots, left, action_set)
218
+ self.players.append(name)
219
+ self.scripted.append((name, slots))
220
+
221
+ def reset(self) -> None:
222
+ """Resets each player, after a reset of the environment."""
223
+ for player in self.players:
224
+ player.reset()