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.
- cuju/__init__.py +217 -0
- cuju/__main__.py +262 -0
- cuju/_batch/__init__.py +4 -0
- cuju/_batch/allocator.py +52 -0
- cuju/_batch/assets.py +68 -0
- cuju/_batch/environment.py +1890 -0
- cuju/_batch/frame_stack.py +114 -0
- cuju/_batch/library.py +190 -0
- cuju/_batch/log.py +103 -0
- cuju/_batch/memory.py +70 -0
- cuju/_batch/operators.py +55 -0
- cuju/_batch/pinned.py +39 -0
- cuju/_batch/pixels.py +207 -0
- cuju/_batch/state.py +77 -0
- cuju/_checksums.py +60 -0
- cuju/_cli_contract.py +244 -0
- cuju/_cli_parsers.py +191 -0
- cuju/_completion.py +277 -0
- cuju/_dump_to_txt.py +66 -0
- cuju/_grf_config.py +331 -0
- cuju/_library_path.py +141 -0
- cuju/_media.py +113 -0
- cuju/_pixels.py +276 -0
- cuju/_plugins.py +106 -0
- cuju/_python_players.py +224 -0
- cuju/_replay_command.py +109 -0
- cuju/_replay_player.py +42 -0
- cuju/_replays.py +414 -0
- cuju/_script_helpers.py +109 -0
- cuju/_version.py +6 -0
- cuju/action_log.py +371 -0
- cuju/check.py +596 -0
- cuju/cuju_cpu.dll +0 -0
- cuju/cuju_cuda.dll +0 -0
- cuju/cuju_render.dll +0 -0
- cuju/data/SHA256SUMS +20 -0
- cuju/data/animations.bin +0 -0
- cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
- cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
- cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
- cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
- cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
- cuju/data/digests.json +186 -0
- cuju/data/render_digests.json.z +0 -0
- cuju/data/scenarios/11_vs_11_competition.py +45 -0
- cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
- cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
- cuju/data/scenarios/1_vs_1_easy.py +25 -0
- cuju/data/scenarios/5_vs_5.py +33 -0
- cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
- cuju/data/scenarios/academy_corner.py +45 -0
- cuju/data/scenarios/academy_counterattack_easy.py +45 -0
- cuju/data/scenarios/academy_counterattack_hard.py +45 -0
- cuju/data/scenarios/academy_empty_goal.py +25 -0
- cuju/data/scenarios/academy_empty_goal_close.py +25 -0
- cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_to_score.py +30 -0
- cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
- cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
- cuju/data/scenarios/test_example_multiagent.py +28 -0
- cuju/dumps.py +942 -0
- cuju/engine_status.py +106 -0
- cuju/env.py +1168 -0
- cuju/errors.py +108 -0
- cuju/gfootball/GRF_SOURCES +86 -0
- cuju/gfootball/__init__.py +60 -0
- cuju/gfootball/_cv2.py +43 -0
- cuju/gfootball/_gym/__init__.py +88 -0
- cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
- cuju/gfootball/_gym/_vendored/__init__.py +43 -0
- cuju/gfootball/_gym/_vendored/core.py +361 -0
- cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
- cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
- cuju/gfootball/_gym/_vendored/error.py +230 -0
- cuju/gfootball/_gym/_vendored/logger.py +56 -0
- cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
- cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
- cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
- cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
- cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
- cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
- cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
- cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
- cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
- cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
- cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
- cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
- cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
- cuju/gfootball/_gym/_vendored/version.py +5 -0
- cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
- cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
- cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
- cuju/gfootball/dump_to_txt.py +49 -0
- cuju/gfootball/dump_to_video.py +33 -0
- cuju/gfootball/env/__init__.py +271 -0
- cuju/gfootball/env/config.py +163 -0
- cuju/gfootball/env/constants.py +33 -0
- cuju/gfootball/env/controller_base.py +114 -0
- cuju/gfootball/env/event_queue.py +54 -0
- cuju/gfootball/env/football_action_set.py +220 -0
- cuju/gfootball/env/football_action_set_test.py +76 -0
- cuju/gfootball/env/football_env.py +225 -0
- cuju/gfootball/env/football_env_core.py +447 -0
- cuju/gfootball/env/football_env_test.py +692 -0
- cuju/gfootball/env/gym_test.py +47 -0
- cuju/gfootball/env/observation_preprocessing.py +94 -0
- cuju/gfootball/env/observation_processor.py +526 -0
- cuju/gfootball/env/observation_rotation.py +163 -0
- cuju/gfootball/env/observation_rotation_test.py +84 -0
- cuju/gfootball/env/player_base.py +46 -0
- cuju/gfootball/env/players/__init__.py +16 -0
- cuju/gfootball/env/players/agent.py +39 -0
- cuju/gfootball/env/players/bot.py +217 -0
- cuju/gfootball/env/players/gamepad.py +81 -0
- cuju/gfootball/env/players/keyboard.py +72 -0
- cuju/gfootball/env/players/lazy.py +31 -0
- cuju/gfootball/env/players/ppo2_cnn.py +119 -0
- cuju/gfootball/env/players/replay.py +40 -0
- cuju/gfootball/env/remote_football_env.py +189 -0
- cuju/gfootball/env/scenario_builder.py +125 -0
- cuju/gfootball/env/script_helpers.py +130 -0
- cuju/gfootball/env/script_helpers_test.py +107 -0
- cuju/gfootball/env/wrappers.py +440 -0
- cuju/gfootball/env/wrappers_test.py +150 -0
- cuju/gfootball/eval_server/__init__.py +17 -0
- cuju/gfootball/eval_server/config.py +30 -0
- cuju/gfootball/eval_server/example_client.py +107 -0
- cuju/gfootball/eval_server/proto/game_server.proto +62 -0
- cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
- cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
- cuju/gfootball/eval_server/proto/master.proto +25 -0
- cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
- cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
- cuju/gfootball/eval_server/utils.py +52 -0
- cuju/gfootball/examples/__init__.py +16 -0
- cuju/gfootball/examples/models.py +66 -0
- cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
- cuju/gfootball/examples/run_ppo2.py +123 -0
- cuju/gfootball/play_game.py +73 -0
- cuju/gfootball/replay.py +43 -0
- cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
- cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
- cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
- cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
- cuju/gfootball/scenarios/5_vs_5.py +46 -0
- cuju/gfootball/scenarios/__init__.py +31 -0
- cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
- cuju/gfootball/scenarios/academy_corner.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
- cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
- cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
- cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
- cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
- cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
- cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
- cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
- cuju/gfootball/scenarios/tests/__init__.py +31 -0
- cuju/gfootball/scenarios/tests/corner_test.py +38 -0
- cuju/gfootball/scenarios/tests/goal_test.py +35 -0
- cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
- cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
- cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
- cuju/gfootball/scenarios/tests/offside_test.py +39 -0
- cuju/gfootball/scenarios/tests/penalty.py +34 -0
- cuju/gfootball/scenarios/tests/second_half.py +33 -0
- cuju/gfootball/scenarios/tests/symmetric.py +53 -0
- cuju/gfootball_engine/__init__.py +31 -0
- cuju/gfootball_engine/_gameplayfootball.py +1624 -0
- cuju/gfootball_engine/_native.py +193 -0
- cuju/gfootball_engine/_pickle_names.py +114 -0
- cuju/gfootball_engine/_render_hooks.py +156 -0
- cuju/kaggle.py +425 -0
- cuju/multi_device.py +401 -0
- cuju/players.py +260 -0
- cuju/raw.py +93 -0
- cuju/scenarios.py +661 -0
- cuju/state.py +211 -0
- cuju/wrappers.py +325 -0
- cuju_engine-0.3.0.dist-info/METADATA +325 -0
- cuju_engine-0.3.0.dist-info/RECORD +222 -0
- cuju_engine-0.3.0.dist-info/WHEEL +5 -0
- cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
- cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/scenarios.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# Copyright 2019 Google LLC
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""Builds the asset bundle of a GRF scenario file, without GRF.
|
|
6
|
+
|
|
7
|
+
`build_bundle` runs the file's `build_scenario(builder)` with a builder that behaves as GRF's, for
|
|
8
|
+
episodes of both parities, and writes the bundle without agents (`l0_r0`) through the C API. It
|
|
9
|
+
raises `ScenarioError` for a scenario that GRF refuses or that a bundle cannot hold; the
|
|
10
|
+
repository's `docs/custom-scenarios.md` lists the cases.
|
|
11
|
+
|
|
12
|
+
from cuju import scenarios
|
|
13
|
+
scenarios.build_bundle('my_scenario.py', 'my_scenario_l0_r0.cjb')
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ctypes
|
|
19
|
+
import enum
|
|
20
|
+
import hashlib
|
|
21
|
+
import importlib.util
|
|
22
|
+
import os
|
|
23
|
+
import random
|
|
24
|
+
import sys
|
|
25
|
+
import tempfile
|
|
26
|
+
import types
|
|
27
|
+
import warnings
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from . import _checksums
|
|
32
|
+
from ._batch import log as _log
|
|
33
|
+
from ._library_path import _automatic, _backend, _check_processor, library_path
|
|
34
|
+
from .errors import ConfigurationError, _from_library
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
'Builder',
|
|
38
|
+
'PlayerRole',
|
|
39
|
+
'ScenarioConfig',
|
|
40
|
+
'ScenarioError',
|
|
41
|
+
'Team',
|
|
42
|
+
'build_bundle',
|
|
43
|
+
'cache_directory',
|
|
44
|
+
'cached_bundle',
|
|
45
|
+
'describe',
|
|
46
|
+
'load_scenario',
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
_ANIMATIONS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'animations.bin')
|
|
50
|
+
# GRF: a team holds at most 11 players, for 11 formation slots and 11 persons.
|
|
51
|
+
_MAXIMUM_TEAM_PLAYERS = 11
|
|
52
|
+
# GRF: creating an environment builds episode 1 twice, and the first episode played is 2. Pairs of
|
|
53
|
+
# distant episode numbers, up to 10**9, also catch a scenario that keys on more than the parity,
|
|
54
|
+
# such as one that changes every 1,000 episodes.
|
|
55
|
+
_EPISODES = tuple(range(1, 9)) + tuple(
|
|
56
|
+
10**power + parity for power in range(2, 10) for parity in (0, 1)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class PlayerRole(enum.IntEnum):
|
|
61
|
+
"""The roles of `e_PlayerRole` of GRF."""
|
|
62
|
+
|
|
63
|
+
e_PlayerRole_GK = 0
|
|
64
|
+
e_PlayerRole_CB = 1
|
|
65
|
+
e_PlayerRole_LB = 2
|
|
66
|
+
e_PlayerRole_RB = 3
|
|
67
|
+
e_PlayerRole_DM = 4
|
|
68
|
+
e_PlayerRole_CM = 5
|
|
69
|
+
e_PlayerRole_LM = 6
|
|
70
|
+
e_PlayerRole_RM = 7
|
|
71
|
+
e_PlayerRole_AM = 8
|
|
72
|
+
e_PlayerRole_CF = 9
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Team(enum.IntEnum):
|
|
76
|
+
"""The teams of `e_Team` of GRF."""
|
|
77
|
+
|
|
78
|
+
e_Left = 0
|
|
79
|
+
e_Right = 1
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class ScenarioError(ConfigurationError):
|
|
83
|
+
"""A scenario that GRF refuses or that a bundle cannot hold. It is a `ValueError`."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# GRF: boost.python converts the values of a scenario to C++ as these helpers check.
|
|
87
|
+
def _to_float(name, value):
|
|
88
|
+
# A Python float or int, a bool included, converts to a float or a double.
|
|
89
|
+
if not isinstance(value, (int, float)):
|
|
90
|
+
raise ScenarioError(f'expected a number for {name}, found {value!r}')
|
|
91
|
+
return float(value)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _to_integer(name, value, low=-(2**31), high=2**31 - 1):
|
|
95
|
+
# Only a Python int, a bool included, converts to an int, and a value out of range overflows.
|
|
96
|
+
if not isinstance(value, int):
|
|
97
|
+
raise ScenarioError(f'expected an integer for {name}, found {value!r}')
|
|
98
|
+
if not low <= value <= high:
|
|
99
|
+
raise ScenarioError(f'expected {name} from {low} to {high}, found {value}')
|
|
100
|
+
return int(value)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _to_unsigned(name, value):
|
|
104
|
+
return _to_integer(name, value, 0, 2**32 - 1)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _to_bool(name, value):
|
|
108
|
+
# None and any Python int, a bool included, convert to a bool.
|
|
109
|
+
if value is not None and not isinstance(value, int):
|
|
110
|
+
raise ScenarioError(f'expected True or False for {name}, found {value!r}')
|
|
111
|
+
return bool(value)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# The fields of GRF's `ScenarioConfig` that a scenario sets, with their defaults (`main.hpp`).
|
|
115
|
+
_FIELDS = {
|
|
116
|
+
'use_magnet': (True, _to_bool),
|
|
117
|
+
'offsides': (True, _to_bool),
|
|
118
|
+
'real_time': (False, _to_bool),
|
|
119
|
+
'left_team_difficulty': (1.0, _to_float),
|
|
120
|
+
'right_team_difficulty': (0.6, _to_float),
|
|
121
|
+
'deterministic': (False, _to_bool),
|
|
122
|
+
'end_episode_on_score': (False, _to_bool),
|
|
123
|
+
'end_episode_on_possession_change': (False, _to_bool),
|
|
124
|
+
'end_episode_on_out_of_play': (False, _to_bool),
|
|
125
|
+
'game_duration': (3000, _to_integer),
|
|
126
|
+
'second_half': (999999999, _to_integer),
|
|
127
|
+
'control_all_players': (False, _to_bool),
|
|
128
|
+
'game_engine_random_seed': (42, _to_unsigned),
|
|
129
|
+
'reverse_team_processing': (False, _to_bool),
|
|
130
|
+
'left_agents': (1, _to_integer),
|
|
131
|
+
'right_agents': (0, _to_integer),
|
|
132
|
+
}
|
|
133
|
+
# GRF: after `build_scenario`, the configuration of the environment replaces these, and the seed
|
|
134
|
+
# and the order of the teams unless the scenario is deterministic.
|
|
135
|
+
_REPLACED = ('left_agents', 'right_agents', 'real_time')
|
|
136
|
+
# The fields that GRF computes and a scenario only reads.
|
|
137
|
+
_READ_ONLY = ('dynamic_player_selection', 'controllable_left_players', 'controllable_right_players')
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class FormationEntry:
|
|
141
|
+
"""One player of a team, as `libgame.FormationEntry` holds it."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, x, y, role, lazy, controllable):
|
|
144
|
+
self.x = _to_float('x', x)
|
|
145
|
+
self.y = _to_float('y', y)
|
|
146
|
+
engine = sys.modules.get('cuju.gfootball_engine._gameplayfootball')
|
|
147
|
+
# The roles of `cuju.gfootball.scenarios` are those of cuju's `gfootball_engine`.
|
|
148
|
+
if engine is not None and isinstance(role, engine.e_PlayerRole) and 0 <= role <= 9:
|
|
149
|
+
role = PlayerRole(int(role))
|
|
150
|
+
if not isinstance(role, PlayerRole):
|
|
151
|
+
raise ScenarioError(f'expected a role such as e_PlayerRole_GK, found {role!r}')
|
|
152
|
+
self.role = role
|
|
153
|
+
self.lazy = _to_bool('lazy', lazy)
|
|
154
|
+
self.controllable = _to_bool('controllable', controllable)
|
|
155
|
+
|
|
156
|
+
def key(self):
|
|
157
|
+
return (self.x, self.y, int(self.role), self.lazy, self.controllable)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class ScenarioConfig:
|
|
161
|
+
"""The configuration that `builder.config()` returns, with the fields of GRF.
|
|
162
|
+
|
|
163
|
+
An attribute that GRF does not know is kept and ignored, as an instance of
|
|
164
|
+
boost.python keeps it.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def __init__(self):
|
|
168
|
+
object.__setattr__(self, '_values', {name: value for name, (value, _) in _FIELDS.items()})
|
|
169
|
+
object.__setattr__(self, 'left_team', [])
|
|
170
|
+
object.__setattr__(self, 'right_team', [])
|
|
171
|
+
object.__setattr__(self, 'ball_position', [0.0, 0.0, 0.0])
|
|
172
|
+
object.__setattr__(self, '_cache_read', False)
|
|
173
|
+
|
|
174
|
+
def __getattr__(self, name):
|
|
175
|
+
values = object.__getattribute__(self, '_values')
|
|
176
|
+
if name in values:
|
|
177
|
+
return values[name]
|
|
178
|
+
if name in _READ_ONLY:
|
|
179
|
+
return self._read_only(name)
|
|
180
|
+
raise AttributeError(name)
|
|
181
|
+
|
|
182
|
+
def __setattr__(self, name, value):
|
|
183
|
+
if name in _READ_ONLY:
|
|
184
|
+
raise AttributeError(f"can't set attribute {name}")
|
|
185
|
+
if name in _FIELDS:
|
|
186
|
+
self._values[name] = _FIELDS[name][1](name, value)
|
|
187
|
+
elif name in ('left_team', 'right_team', 'ball_position'):
|
|
188
|
+
raise ScenarioError(f'set {name} through AddPlayer or SetBallPosition')
|
|
189
|
+
else:
|
|
190
|
+
# GRF keeps and ignores it, so a misspelt option would change nothing silently.
|
|
191
|
+
warnings.warn(
|
|
192
|
+
f'the scenario sets {name!r}, which GRF does not know and ignores', stacklevel=2
|
|
193
|
+
)
|
|
194
|
+
object.__setattr__(self, name, value)
|
|
195
|
+
|
|
196
|
+
def _read_only(self, name):
|
|
197
|
+
# GRF: the three values are computed once, at the first read, and kept.
|
|
198
|
+
object.__setattr__(self, '_cache_read', True)
|
|
199
|
+
left = sum(1 for player in self.left_team if player.controllable)
|
|
200
|
+
right = sum(1 for player in self.right_team if player.controllable)
|
|
201
|
+
if name == 'controllable_left_players':
|
|
202
|
+
return left
|
|
203
|
+
if name == 'controllable_right_players':
|
|
204
|
+
return right
|
|
205
|
+
agents_left, agents_right = self._values['left_agents'], self._values['right_agents']
|
|
206
|
+
return not (
|
|
207
|
+
(left == agents_left or agents_left == 0)
|
|
208
|
+
and (right == agents_right or agents_right == 0)
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class Builder:
|
|
213
|
+
"""The `builder` argument of `build_scenario`, as `gfootball.env.scenario_builder.Scenario`."""
|
|
214
|
+
|
|
215
|
+
def __init__(self, episode_number):
|
|
216
|
+
self._config = ScenarioConfig()
|
|
217
|
+
self._active_team = Team.e_Left
|
|
218
|
+
self._episode_number = episode_number
|
|
219
|
+
|
|
220
|
+
def config(self):
|
|
221
|
+
return self._config
|
|
222
|
+
|
|
223
|
+
def ScenarioConfig(self):
|
|
224
|
+
return self._config
|
|
225
|
+
|
|
226
|
+
def SetTeam(self, team):
|
|
227
|
+
self._active_team = team
|
|
228
|
+
|
|
229
|
+
def AddPlayer(self, x, y, role, lazy=False, controllable=True):
|
|
230
|
+
player = FormationEntry(x, y, role, lazy, controllable)
|
|
231
|
+
if self._active_team == Team.e_Left:
|
|
232
|
+
self._config.left_team.append(player)
|
|
233
|
+
else:
|
|
234
|
+
self._config.right_team.append(player)
|
|
235
|
+
|
|
236
|
+
def SetBallPosition(self, ball_x, ball_y):
|
|
237
|
+
self._config.ball_position[0] = _to_float('ball_x', ball_x)
|
|
238
|
+
self._config.ball_position[1] = _to_float('ball_y', ball_y)
|
|
239
|
+
|
|
240
|
+
def EpisodeNumber(self):
|
|
241
|
+
return self._episode_number
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# The package that a scenario file imports its names from with `from . import *`.
|
|
245
|
+
_PACKAGE = 'cuju._scenario_files'
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _scenario_package():
|
|
249
|
+
package = sys.modules.get(_PACKAGE)
|
|
250
|
+
if package is None:
|
|
251
|
+
package = types.ModuleType(_PACKAGE)
|
|
252
|
+
package.__path__ = []
|
|
253
|
+
for role in PlayerRole:
|
|
254
|
+
setattr(package, role.name, role)
|
|
255
|
+
package.Team = Team
|
|
256
|
+
package.__all__ = [role.name for role in PlayerRole] + ['Team']
|
|
257
|
+
sys.modules[_PACKAGE] = package
|
|
258
|
+
return package
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def load_scenario(path):
|
|
262
|
+
"""Imports a scenario file and returns its `build_scenario` function.
|
|
263
|
+
|
|
264
|
+
Args:
|
|
265
|
+
path: The path of a scenario file of GRF.
|
|
266
|
+
|
|
267
|
+
Raises:
|
|
268
|
+
ScenarioError: If Python cannot load the file as a module or it defines no
|
|
269
|
+
`build_scenario`. An error that the file itself raises while it runs, such as an
|
|
270
|
+
`ImportError`, passes through unchanged.
|
|
271
|
+
"""
|
|
272
|
+
_scenario_package()
|
|
273
|
+
name = os.path.splitext(os.path.basename(path))[0]
|
|
274
|
+
spec = importlib.util.spec_from_file_location(f'{_PACKAGE}.{name}', path)
|
|
275
|
+
if spec is None or spec.loader is None:
|
|
276
|
+
raise ScenarioError(f'cannot load the scenario file {path}')
|
|
277
|
+
module = importlib.util.module_from_spec(spec)
|
|
278
|
+
sys.modules[spec.name] = module
|
|
279
|
+
try:
|
|
280
|
+
spec.loader.exec_module(module)
|
|
281
|
+
finally:
|
|
282
|
+
sys.modules.pop(spec.name, None)
|
|
283
|
+
build = getattr(module, 'build_scenario', None)
|
|
284
|
+
if not callable(build):
|
|
285
|
+
raise ScenarioError(f'expected a build_scenario function in {path}')
|
|
286
|
+
return build
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _numpy_state():
|
|
290
|
+
numpy = sys.modules.get('numpy')
|
|
291
|
+
if numpy is None:
|
|
292
|
+
return None
|
|
293
|
+
state = numpy.random.get_state()
|
|
294
|
+
return (state[0], state[1].tobytes(), state[2], state[3], state[4])
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _build(build_scenario: Callable[[Builder], Any], episode_number):
|
|
298
|
+
"""Runs `build_scenario` for one episode number and returns its description."""
|
|
299
|
+
python_state = random.getstate()
|
|
300
|
+
numpy_state = _numpy_state()
|
|
301
|
+
builder = Builder(episode_number)
|
|
302
|
+
build_scenario(builder)
|
|
303
|
+
if random.getstate() != python_state:
|
|
304
|
+
raise ScenarioError(
|
|
305
|
+
'the scenario draws from the random module of Python; GRF draws the seed '
|
|
306
|
+
'of every episode from that generator right after the scenario, so a bundle '
|
|
307
|
+
'cannot hold it'
|
|
308
|
+
)
|
|
309
|
+
if _numpy_state() != numpy_state:
|
|
310
|
+
raise ScenarioError('the scenario draws from the global random generator of NumPy')
|
|
311
|
+
config = builder.config()
|
|
312
|
+
if config._cache_read:
|
|
313
|
+
raise ScenarioError(
|
|
314
|
+
'the scenario reads controllable_left_players, controllable_right_players or '
|
|
315
|
+
'dynamic_player_selection, which GRF computes once at that read, before it '
|
|
316
|
+
'sets the agents, and keeps for the match, so a bundle cannot hold it'
|
|
317
|
+
)
|
|
318
|
+
# GRF: `Scenario._FakePlayersForEmptyTeam` gives an empty team a lazy goalkeeper.
|
|
319
|
+
for side, team in (('left', config.left_team), ('right', config.right_team)):
|
|
320
|
+
if not team:
|
|
321
|
+
team.append(FormationEntry(-1.0, 0.42, PlayerRole.e_PlayerRole_GK, True, True))
|
|
322
|
+
if len(team) > _MAXIMUM_TEAM_PLAYERS:
|
|
323
|
+
raise ScenarioError(f'a team has {len(team)} players, more than the 11 that GRF holds')
|
|
324
|
+
# GRF: `TeamAIController::CalculateDynamicRoles` seeks the goalkeeper without advancing its
|
|
325
|
+
# iterator, so it loops forever in open play unless each team's first player is one.
|
|
326
|
+
if team[0].role != PlayerRole.e_PlayerRole_GK:
|
|
327
|
+
raise ScenarioError(
|
|
328
|
+
f'the first player of the {side} team is not a goalkeeper, which hangs GRF once '
|
|
329
|
+
'the match is in open play'
|
|
330
|
+
)
|
|
331
|
+
values = {name: value for name, value in config._values.items() if name not in _REPLACED}
|
|
332
|
+
if values['deterministic']:
|
|
333
|
+
if values['reverse_team_processing']:
|
|
334
|
+
raise ScenarioError('a deterministic scenario that turns reverse_team_processing on')
|
|
335
|
+
else:
|
|
336
|
+
# GRF: the seed of the episode replaces the seed and the order of the teams.
|
|
337
|
+
values['game_engine_random_seed'] = 42
|
|
338
|
+
values.pop('reverse_team_processing')
|
|
339
|
+
return {
|
|
340
|
+
'values': values,
|
|
341
|
+
'ball': (config.ball_position[0], config.ball_position[1]),
|
|
342
|
+
'left': [player.key() for player in config.left_team],
|
|
343
|
+
'right': [player.key() for player in config.right_team],
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def describe(scenario, episodes=_EPISODES):
|
|
348
|
+
"""Runs a scenario for several episode numbers and returns its even and odd descriptions.
|
|
349
|
+
|
|
350
|
+
Args:
|
|
351
|
+
scenario: The path of a scenario file, or a `build_scenario` function.
|
|
352
|
+
episodes: The episode numbers to run, which hold both parities. The descriptions of the
|
|
353
|
+
episode numbers of one parity must be equal.
|
|
354
|
+
|
|
355
|
+
Returns:
|
|
356
|
+
The pair of the descriptions of the even and of the odd episodes.
|
|
357
|
+
|
|
358
|
+
Raises:
|
|
359
|
+
ScenarioError: If GRF refuses the scenario or a bundle cannot hold it.
|
|
360
|
+
"""
|
|
361
|
+
build = load_scenario(scenario) if isinstance(scenario, (str, os.PathLike)) else scenario
|
|
362
|
+
by_parity = {}
|
|
363
|
+
for episode in episodes:
|
|
364
|
+
description = _build(build, episode)
|
|
365
|
+
first, first_episode = by_parity.setdefault(episode % 2, (description, episode))
|
|
366
|
+
if first != description:
|
|
367
|
+
raise ScenarioError(
|
|
368
|
+
f'the scenario differs between episodes {first_episode} and {episode}, which have '
|
|
369
|
+
'the same parity; a bundle holds one template for each parity only'
|
|
370
|
+
)
|
|
371
|
+
if set(by_parity) != {0, 1}:
|
|
372
|
+
raise ScenarioError('expected episode numbers of both parities')
|
|
373
|
+
even, odd = by_parity[0][0], by_parity[1][0]
|
|
374
|
+
if len(even['left']) != len(odd['left']) or len(even['right']) != len(odd['right']):
|
|
375
|
+
raise ScenarioError('the team sizes change with the parity of the episode')
|
|
376
|
+
return even, odd
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
class _Player(ctypes.Structure):
|
|
380
|
+
"""`cuju_scenario_player` of the C API."""
|
|
381
|
+
|
|
382
|
+
_fields_ = [
|
|
383
|
+
('x', ctypes.c_double),
|
|
384
|
+
('y', ctypes.c_double),
|
|
385
|
+
('role', ctypes.c_int),
|
|
386
|
+
('lazy', ctypes.c_int),
|
|
387
|
+
('controllable', ctypes.c_int),
|
|
388
|
+
]
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class _Description(ctypes.Structure):
|
|
392
|
+
"""`cuju_scenario_description` of the C API."""
|
|
393
|
+
|
|
394
|
+
_fields_ = [
|
|
395
|
+
('version', ctypes.c_int),
|
|
396
|
+
('ball_x', ctypes.c_double),
|
|
397
|
+
('ball_y', ctypes.c_double),
|
|
398
|
+
('left_team', ctypes.POINTER(_Player)),
|
|
399
|
+
('left_size', ctypes.c_int),
|
|
400
|
+
('right_team', ctypes.POINTER(_Player)),
|
|
401
|
+
('right_size', ctypes.c_int),
|
|
402
|
+
('use_magnet', ctypes.c_int),
|
|
403
|
+
('offsides', ctypes.c_int),
|
|
404
|
+
('real_time', ctypes.c_int),
|
|
405
|
+
('left_team_difficulty', ctypes.c_double),
|
|
406
|
+
('right_team_difficulty', ctypes.c_double),
|
|
407
|
+
('deterministic', ctypes.c_int),
|
|
408
|
+
('end_episode_on_score', ctypes.c_int),
|
|
409
|
+
('end_episode_on_possession_change', ctypes.c_int),
|
|
410
|
+
('end_episode_on_out_of_play', ctypes.c_int),
|
|
411
|
+
('game_duration', ctypes.c_int),
|
|
412
|
+
('second_half', ctypes.c_int),
|
|
413
|
+
('control_all_players', ctypes.c_int),
|
|
414
|
+
('game_engine_random_seed', ctypes.c_uint),
|
|
415
|
+
]
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# `CUJU_SCENARIO_VERSION` of the C API.
|
|
419
|
+
_DESCRIPTION_VERSION = 1
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _c_description(description, keep):
|
|
423
|
+
"""Returns the C layout of a description. `keep` holds the arrays that it points into."""
|
|
424
|
+
teams = []
|
|
425
|
+
for side in ('left', 'right'):
|
|
426
|
+
players = (_Player * len(description[side]))(
|
|
427
|
+
*[_Player(*player) for player in description[side]]
|
|
428
|
+
)
|
|
429
|
+
keep.append(players)
|
|
430
|
+
teams.append(players)
|
|
431
|
+
values = description['values']
|
|
432
|
+
return _Description(
|
|
433
|
+
version=_DESCRIPTION_VERSION,
|
|
434
|
+
ball_x=description['ball'][0],
|
|
435
|
+
ball_y=description['ball'][1],
|
|
436
|
+
left_team=teams[0],
|
|
437
|
+
left_size=len(description['left']),
|
|
438
|
+
right_team=teams[1],
|
|
439
|
+
right_size=len(description['right']),
|
|
440
|
+
use_magnet=values['use_magnet'],
|
|
441
|
+
offsides=values['offsides'],
|
|
442
|
+
# The configuration of the environment sets it, and the simulation does not read it.
|
|
443
|
+
real_time=False,
|
|
444
|
+
left_team_difficulty=values['left_team_difficulty'],
|
|
445
|
+
right_team_difficulty=values['right_team_difficulty'],
|
|
446
|
+
deterministic=values['deterministic'],
|
|
447
|
+
end_episode_on_score=values['end_episode_on_score'],
|
|
448
|
+
end_episode_on_possession_change=values['end_episode_on_possession_change'],
|
|
449
|
+
end_episode_on_out_of_play=values['end_episode_on_out_of_play'],
|
|
450
|
+
game_duration=values['game_duration'],
|
|
451
|
+
second_half=values['second_half'],
|
|
452
|
+
control_all_players=values['control_all_players'],
|
|
453
|
+
game_engine_random_seed=values['game_engine_random_seed'],
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def build_bundle(scenario, out, name=None, device='cpu', library=None, animations=None):
|
|
458
|
+
"""Writes the asset bundle without agents of a scenario file.
|
|
459
|
+
|
|
460
|
+
Args:
|
|
461
|
+
scenario: The path of a GRF scenario file, or a `build_scenario` function.
|
|
462
|
+
out: The path of the bundle to write.
|
|
463
|
+
name: The name of the scenario that the bundle records. `None` takes the name of the file or
|
|
464
|
+
of the module of the function.
|
|
465
|
+
device: The library that builds the bundle, `cpu`, `cuda`, `cuda:N` or `auto`. All give the
|
|
466
|
+
same bytes.
|
|
467
|
+
library: The path of that library, or `None` for `library_path(device)`.
|
|
468
|
+
animations: The path of `animations.bin`, or `None` for the tables that the package ships.
|
|
469
|
+
|
|
470
|
+
Returns:
|
|
471
|
+
`out`.
|
|
472
|
+
|
|
473
|
+
Warns:
|
|
474
|
+
UserWarning: If the scenario lasts longer than a batch holds at GRF's default of 10 ticks a
|
|
475
|
+
step. The warning names the `physics_steps_per_frame` that plays it.
|
|
476
|
+
|
|
477
|
+
Raises:
|
|
478
|
+
ScenarioError: If GRF refuses the scenario or a bundle cannot hold it.
|
|
479
|
+
LibraryError: If the library fails to build the bundle. It is a `RuntimeError`.
|
|
480
|
+
"""
|
|
481
|
+
even, odd = describe(scenario)
|
|
482
|
+
_warn_if_too_long([even, odd])
|
|
483
|
+
if name is None:
|
|
484
|
+
if isinstance(scenario, (str, os.PathLike)):
|
|
485
|
+
name = os.path.splitext(os.path.basename(scenario))[0]
|
|
486
|
+
else:
|
|
487
|
+
name = getattr(scenario, '__module__', 'scenario').rsplit('.', 1)[-1]
|
|
488
|
+
device = _backend(_automatic(device))
|
|
489
|
+
path = library or library_path(device)
|
|
490
|
+
if device == 'cpu':
|
|
491
|
+
_check_processor(path)
|
|
492
|
+
handle = ctypes.CDLL(path)
|
|
493
|
+
handle.cuju_last_error.restype = ctypes.c_char_p
|
|
494
|
+
build = handle.cuju_scenario_build_bundle
|
|
495
|
+
build.restype = ctypes.c_int
|
|
496
|
+
build.argtypes = [
|
|
497
|
+
ctypes.POINTER(_Description),
|
|
498
|
+
ctypes.POINTER(_Description),
|
|
499
|
+
ctypes.c_char_p,
|
|
500
|
+
ctypes.c_char_p,
|
|
501
|
+
ctypes.c_char_p,
|
|
502
|
+
]
|
|
503
|
+
keep = []
|
|
504
|
+
descriptions = [_c_description(even, keep), _c_description(odd, keep)]
|
|
505
|
+
status = build(
|
|
506
|
+
ctypes.byref(descriptions[0]),
|
|
507
|
+
ctypes.byref(descriptions[1]),
|
|
508
|
+
name.encode(),
|
|
509
|
+
os.fsencode(animations or _ANIMATIONS),
|
|
510
|
+
os.fsencode(out),
|
|
511
|
+
)
|
|
512
|
+
if status != 0:
|
|
513
|
+
raise _from_library(handle.cuju_last_error().decode())
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# A batch keeps 512 seconds of each player's position history, where GRF keeps all of it. So it
|
|
518
|
+
# refuses a match of `game_duration * physics_steps_per_frame // 100 + 1` seconds beyond that,
|
|
519
|
+
# so a match lasts at most 51,199 ticks.
|
|
520
|
+
_HISTORY_SECONDS = 512
|
|
521
|
+
_LONGEST_TICKS = _HISTORY_SECONDS * 100 - 1
|
|
522
|
+
# GRF's default `physics_steps_per_frame`.
|
|
523
|
+
_DEFAULT_TICKS = 10
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _warn_if_too_long(descriptions):
|
|
527
|
+
"""Warns if a batch at GRF's default of 10 ticks a step refuses a form of the scenario."""
|
|
528
|
+
duration = max(description['values']['game_duration'] for description in descriptions)
|
|
529
|
+
if duration * _DEFAULT_TICKS <= _LONGEST_TICKS:
|
|
530
|
+
return
|
|
531
|
+
ticks = _LONGEST_TICKS // duration
|
|
532
|
+
advice = f'physics_steps_per_frame={ticks} or fewer plays it' if ticks else 'no batch plays it'
|
|
533
|
+
warnings.warn(
|
|
534
|
+
f'the scenario lasts {duration} steps, and a batch holds at most '
|
|
535
|
+
f'{_LONGEST_TICKS // _DEFAULT_TICKS} steps of {_DEFAULT_TICKS} ticks, the default '
|
|
536
|
+
f'physics_steps_per_frame, since it keeps {_HISTORY_SECONDS} seconds of position history '
|
|
537
|
+
f'for each player; {advice}',
|
|
538
|
+
stacklevel=3,
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
# The cache is off unless this variable names its directory, or is 1 for the default directory.
|
|
543
|
+
_CACHE_VARIABLE = 'CUJU_BUNDLE_CACHE'
|
|
544
|
+
# Part of every key, so that a change to the key's layout builds anew.
|
|
545
|
+
_CACHE_FORMAT = b'cuju bundle cache 1'
|
|
546
|
+
# The SHA-256 of a file, by its real path, size and modification time.
|
|
547
|
+
_file_digests = {}
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _file_digest(path):
|
|
551
|
+
"""Returns the SHA-256 of a file, which a process reads only once while the file stays."""
|
|
552
|
+
status = os.stat(path)
|
|
553
|
+
key = (os.path.realpath(path), status.st_size, status.st_mtime_ns)
|
|
554
|
+
if key not in _file_digests:
|
|
555
|
+
_file_digests[key] = _checksums.file_sha256(path)
|
|
556
|
+
return _file_digests[key]
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def cache_directory() -> str | None:
|
|
560
|
+
"""Returns the directory of the bundle cache, or `None` while the cache is off.
|
|
561
|
+
|
|
562
|
+
`CUJU_BUNDLE_CACHE` turns the cache on with a directory, or with `1` for
|
|
563
|
+
`$XDG_CACHE_HOME/cuju/bundles`, which is `~/.cache/cuju/bundles` without `XDG_CACHE_HOME`.
|
|
564
|
+
Unset, empty or `0`, it leaves the cache off, and a batch builds each scenario file at each
|
|
565
|
+
creation.
|
|
566
|
+
"""
|
|
567
|
+
value = os.environ.get(_CACHE_VARIABLE, '')
|
|
568
|
+
if value in ('', '0'):
|
|
569
|
+
return None
|
|
570
|
+
return _default_cache_directory() if value == '1' else value
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _default_cache_directory():
|
|
574
|
+
base = os.environ.get('XDG_CACHE_HOME') or os.path.join(os.path.expanduser('~'), '.cache')
|
|
575
|
+
return os.path.join(base, 'cuju', 'bundles')
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def cached_bundle(scenario, directory=None, device='cpu', library=None, animations=None):
|
|
579
|
+
"""Returns the bundle of a scenario file in a cache directory, which builds it only once.
|
|
580
|
+
|
|
581
|
+
The bundle is the one that `build_bundle` writes with the name of the file. Its key is the
|
|
582
|
+
SHA-256 of the file's bytes, its name, the animation tables, the library that builds it and this
|
|
583
|
+
builder, so a change to any of them builds anew. A batch with `CUJU_BUNDLE_CACHE` set takes its
|
|
584
|
+
scenario files from the cache through this function.
|
|
585
|
+
|
|
586
|
+
The file runs only when its key is new. A file that reads anything besides its own bytes, such
|
|
587
|
+
as another file or `os.environ`, keeps the bundle of its first build until the file changes or
|
|
588
|
+
the cache is cleared. The cache is safe to delete at any time.
|
|
589
|
+
|
|
590
|
+
Args:
|
|
591
|
+
scenario: The path of a GRF scenario file.
|
|
592
|
+
directory: The cache directory, created if missing. `None` takes `cache_directory()`, or
|
|
593
|
+
the directory of `CUJU_BUNDLE_CACHE=1` while the variable leaves the cache off.
|
|
594
|
+
device: The library that builds the bundle on a miss, `cpu` or `cuda`. Both give the same
|
|
595
|
+
bytes, under keys of their own.
|
|
596
|
+
library: The path of that library, or `None` for `library_path(device)`.
|
|
597
|
+
animations: The path of `animations.bin`, or `None` for the tables that the package ships.
|
|
598
|
+
|
|
599
|
+
Returns:
|
|
600
|
+
The path of the bundle in the cache.
|
|
601
|
+
|
|
602
|
+
Raises:
|
|
603
|
+
ScenarioError: If GRF refuses the scenario or a bundle cannot hold it.
|
|
604
|
+
LibraryError: If the library fails to build the bundle. It is a `RuntimeError`.
|
|
605
|
+
OSError: If the file cannot be read, or the cache directory cannot be created or written.
|
|
606
|
+
"""
|
|
607
|
+
if directory is None:
|
|
608
|
+
directory = cache_directory() or _default_cache_directory()
|
|
609
|
+
name = os.path.splitext(os.path.basename(scenario))[0]
|
|
610
|
+
with open(scenario, 'rb') as handle:
|
|
611
|
+
source = handle.read()
|
|
612
|
+
key = hashlib.sha256()
|
|
613
|
+
for part in (
|
|
614
|
+
_CACHE_FORMAT,
|
|
615
|
+
source,
|
|
616
|
+
name.encode(),
|
|
617
|
+
_file_digest(animations or _ANIMATIONS).encode(),
|
|
618
|
+
_file_digest(library or library_path(device)).encode(),
|
|
619
|
+
_file_digest(os.path.abspath(__file__)).encode(),
|
|
620
|
+
):
|
|
621
|
+
key.update(len(part).to_bytes(8, 'little') + part)
|
|
622
|
+
path = os.path.join(directory, f'{name}-{key.hexdigest()[:40]}.cjb')
|
|
623
|
+
if os.path.isfile(path):
|
|
624
|
+
return path
|
|
625
|
+
os.makedirs(directory, exist_ok=True)
|
|
626
|
+
# Another process may build the same key at once, so each writes a file of its own and the
|
|
627
|
+
# rename puts one whole bundle in place.
|
|
628
|
+
descriptor, partial = tempfile.mkstemp(prefix=f'.{name}-', suffix='.partial', dir=directory)
|
|
629
|
+
os.close(descriptor)
|
|
630
|
+
try:
|
|
631
|
+
build_bundle(
|
|
632
|
+
scenario, partial, name=name, device=device, library=library, animations=animations
|
|
633
|
+
)
|
|
634
|
+
os.replace(partial, path)
|
|
635
|
+
finally:
|
|
636
|
+
if os.path.exists(partial):
|
|
637
|
+
os.remove(partial)
|
|
638
|
+
return path
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _batch_bundle(scenario, device, library, animations=None):
|
|
642
|
+
"""Returns the cached bundle of a scenario file, or `None` if the cache is off or unwritable.
|
|
643
|
+
|
|
644
|
+
The bundle and its key take the animation tables at `animations`, the batch's.
|
|
645
|
+
"""
|
|
646
|
+
directory = cache_directory()
|
|
647
|
+
if directory is None:
|
|
648
|
+
return None
|
|
649
|
+
try:
|
|
650
|
+
path = cached_bundle(
|
|
651
|
+
scenario, directory, device=device, library=library, animations=animations
|
|
652
|
+
)
|
|
653
|
+
except OSError as error:
|
|
654
|
+
warnings.warn(
|
|
655
|
+
f'the bundle cache {directory!r} of {_CACHE_VARIABLE} cannot be used ({error}), so '
|
|
656
|
+
'the batch builds the scenario file without it',
|
|
657
|
+
stacklevel=3,
|
|
658
|
+
)
|
|
659
|
+
return None
|
|
660
|
+
_log.info(f'the bundle of {scenario} is {path}, from the bundle cache')
|
|
661
|
+
return path
|