Buckets:

download
raw
13.6 kB
from __future__ import annotations
import dataclasses
import typing
from randovania.game_description import default_database
from randovania.game_description.assignment import PickupAssignment, PickupTarget
from randovania.game_description.db.dock_node import DockNode
from randovania.game_description.db.node_identifier import NodeIdentifier
from randovania.game_description.db.pickup_node import PickupNode
from randovania.game_description.game_patches import GamePatches, StartingEquipment
from randovania.game_description.hint import BaseHint
from randovania.game_description.resources.pickup_index import PickupIndex
from randovania.game_description.resources.resource_collection import ResourceCollection
from randovania.game_description.resources.search import find_resource_info_with_long_name
from randovania.generator.pickup_pool import PoolResults, pool_creator
from randovania.layout import filtered_database
if typing.TYPE_CHECKING:
from randovania.game_description.db.area import Area
from randovania.game_description.db.node import Node
from randovania.game_description.db.region_list import RegionList
from randovania.game_description.game_database_view import GameDatabaseView
from randovania.game_description.game_description import GameDescription
from randovania.game_description.pickup.pickup_database import PickupDatabase
from randovania.game_description.pickup.pickup_entry import PickupEntry
from randovania.layout.base.base_configuration import BaseConfiguration
_NOTHING_PICKUP_NAME = "Nothing"
def _pickup_assignment_to_pickup_locations(
game: GameDatabaseView,
pickup_assignment: PickupAssignment,
current_world: int,
num_worlds: int,
) -> list[dict]:
pickup_locations = []
for _, _, node in game.iterate_nodes_of_type(PickupNode):
if node.pickup_index in pickup_assignment:
target = pickup_assignment[node.pickup_index]
item_name = target.pickup.name
if num_worlds > 1:
target_world = target.world
else:
target_world = 0
else:
item_name = _NOTHING_PICKUP_NAME
target_world = current_world
pickup_locations.append(
{
"node_identifier": node.identifier.as_json,
"index": node.pickup_index.index,
"pickup": item_name,
"owner": target_world,
}
)
return sorted(
pickup_locations,
key=lambda d: (
d["node_identifier"]["region"],
f"{d['node_identifier']['area']}/{d['node_identifier']['node']}",
),
)
def _find_area_with_teleporter(region_list: RegionList, teleporter: NodeIdentifier) -> Area:
return region_list.area_by_area_location(teleporter.area_identifier)
def serialize_single(world_index: int, num_worlds: int, patches: GamePatches) -> dict:
"""
Encodes a given GamePatches into a JSON-serializable dict.
:param world_index:
:param num_worlds:
:param patches:
:return:
"""
game = filtered_database.game_description_for_layout(patches.configuration)
dock_weakness_to_type = {}
for dock_type, weaknesses in game.dock_type_database.weaknesses.items():
for weakness in weaknesses.values():
dock_weakness_to_type[weakness] = dock_type
equipment_value: dict | list
if isinstance(patches.starting_equipment, ResourceCollection):
equipment_name = "items"
equipment_value = {
resource_info.long_name: quantity
for resource_info, quantity in patches.starting_equipment.as_resource_gain()
}
else:
equipment_name = "pickups"
equipment_value = [pickup.name for pickup in patches.starting_equipment]
result: dict = {
# This field helps schema migrations, if nothing else
"game": patches.configuration.game.value,
"starting_equipment": {
equipment_name: equipment_value,
},
"starting_location": patches.starting_location.as_string,
"dock_connections": {
dock.as_string: target.as_string for dock, target in patches.all_dock_connections_identifiers()
},
"dock_weakness": {
dock.identifier.as_string: {
"type": dock_weakness_to_type[weakness].short_name,
"name": weakness.name,
}
for dock, weakness in patches.all_dock_weaknesses(game)
},
"locations": _pickup_assignment_to_pickup_locations(game, patches.pickup_assignment, world_index, num_worlds),
"hints": {identifier.as_string: hint.as_json for identifier, hint in patches.hints.items()},
"game_specific": patches.game_specific,
}
if patches.custom_patcher_data:
result["custom_patcher_data"] = patches.custom_patcher_data
return result
def serialize_single_world_only(world_index: int, num_worlds: int, patches: GamePatches) -> dict:
"""
Like ``serialize_single``, but strips all data about other worlds: pickups owned by them become
Nothing, and hints are removed entirely.
The result is enough to compute the world's own logic (only self-owned pickups affect it),
without spoiling what the world's locations hold for other worlds. It can be decoded with
``decode_single`` using only this world's game and pool.
"""
def _adjust_location(location: dict) -> dict:
if location["owner"] != world_index:
location["pickup"] = _NOTHING_PICKUP_NAME
location["owner"] = 0
return location
result = serialize_single(world_index, num_worlds, patches)
result["locations"] = [_adjust_location(loc) for loc in result["locations"]]
result["hints"] = {}
return result
def _find_pickup_with_name(item_pool: list[PickupEntry], pickup_name: str) -> PickupEntry:
for pickup in item_pool:
if pickup.name == pickup_name:
return pickup
names = {pickup.name for pickup in item_pool}
raise ValueError(f"Unable to find a pickup with name {pickup_name}. Possible values: {sorted(names)}")
def _get_pickup_from_pool(pickup_list: list[PickupEntry], name: str) -> PickupEntry:
pickup = _find_pickup_with_name(pickup_list, name)
pickup_list.remove(pickup)
return pickup
def _decode_pickup_assignment(
player_index: int,
all_pools: list[PoolResults],
region_list: RegionList,
locations: dict,
) -> PickupAssignment:
"""Decodes the `locations` key."""
pickup_assignment: PickupAssignment = {}
initial_pickup_assignment = all_pools[player_index].assignment
for location in locations:
pickup_name = location["pickup"]
if pickup_name == _NOTHING_PICKUP_NAME:
continue
target_world: int = location["owner"]
pickup_index = PickupIndex(location["index"])
node = region_list.node_from_pickup_index(pickup_index)
if node.identifier.as_json != location["node_identifier"]:
raise ValueError(
f"The location {node.identifier.as_string} is specified to have "
f"index {pickup_index} but it should instead be index {node.pickup_index}."
)
pickup: PickupEntry | None
if pickup_index in initial_pickup_assignment:
pickup = initial_pickup_assignment[pickup_index]
if (pickup_name, target_world) != (pickup.name, player_index):
raise ValueError(f"{node.identifier.as_string} should be vanilla based on configuration")
elif pickup_name != _NOTHING_PICKUP_NAME:
pickup = _get_pickup_from_pool(all_pools[target_world].to_place, pickup_name)
else:
pickup = None
if pickup is not None:
if pickup_index in pickup_assignment:
raise ValueError(f"Duplicate entries for pickup index {pickup_index.index}.")
pickup_assignment[pickup_index] = PickupTarget(pickup, target_world)
return pickup_assignment
def decode_single(
world_index: int,
all_pools: list[PoolResults],
game: GameDescription,
game_modifications: dict,
configuration: BaseConfiguration,
all_games: list[GameDescription],
) -> GamePatches:
"""
Decodes a dict created by `serialize` back into a GamePatches.
:param world_index:
:param all_pools:
:param game:
:param game_modifications:
:param configuration:
:param all_games:
:return:
"""
region_list = game.region_list
weakness_db = game.dock_type_database
if game_modifications["game"] != game.game.value:
raise ValueError(f"Expected '{game.game.value}', got '{game_modifications['game']}'")
custom_patcher_data = game_modifications.get("custom_patcher_data", [])
game_specific = game_modifications["game_specific"]
# Starting Location
starting_location = NodeIdentifier.from_string(game_modifications["starting_location"])
# Starting Equipment
starting_equipment: StartingEquipment
if "items" in game_modifications["starting_equipment"]:
starting_equipment = ResourceCollection.from_dict(
game.resource_database,
{
find_resource_info_with_long_name(game.resource_database.item, resource_name): quantity
for resource_name, quantity in game_modifications["starting_equipment"]["items"].items()
},
)
else:
player_pool = all_pools[world_index]
starting_equipment = []
for starting in game_modifications["starting_equipment"]["pickups"]:
try:
pickup = _get_pickup_from_pool(player_pool.starting, starting)
except ValueError:
pickup = _get_pickup_from_pool(player_pool.to_place, starting)
starting_equipment.append(pickup)
# Dock Connection
def get_dock_source(ni: NodeIdentifier) -> DockNode:
return game.region_list.typed_node_by_identifier(ni, DockNode)
def get_dock_target(ni: NodeIdentifier) -> Node:
return game.region_list.node_by_identifier(ni)
dock_connections = [
(
get_dock_source(NodeIdentifier.from_string(source_name)),
get_dock_target(NodeIdentifier.from_string(target_name)),
)
for source_name, target_name in game_modifications["dock_connections"].items()
]
# Dock Weakness
dock_weakness = [
(
get_dock_source(NodeIdentifier.from_string(source_name)),
weakness_db.get_by_weakness(
weakness_data["type"],
weakness_data["name"],
),
)
for source_name, weakness_data in game_modifications["dock_weakness"].items()
]
# Pickups
pickup_assignment = _decode_pickup_assignment(
world_index,
all_pools,
region_list,
game_modifications["locations"],
)
# Hints
hints = {}
for identifier_str, hint in game_modifications["hints"].items():
extra: dict = {}
if hint["hint_type"] == "location":
pickup_db = default_database.pickup_database_for_game(game.game)
def get_target_pickup_db(target: PickupTarget) -> PickupDatabase:
target_game = all_games[target.world]
target_pickup_db = default_database.pickup_database_for_game(target_game.game)
return target_pickup_db
if (relative := hint["precision"].get("relative")) is not None:
if "other_index" in relative:
other_target = pickup_assignment.get(PickupIndex(relative["other_index"]))
if other_target is not None:
extra["other_pickup_db"] = get_target_pickup_db(other_target)
else:
extra["other_pickup_db"] = pickup_db
extra["game"] = game
target = pickup_assignment.get(PickupIndex(hint["target"]))
if target is not None:
extra["pickup_db"] = get_target_pickup_db(target)
else:
extra["pickup_db"] = pickup_db
hints[NodeIdentifier.from_string(identifier_str)] = BaseHint.from_json(hint, **extra)
patches = GamePatches.create_from_game(game, world_index, configuration)
patches = patches.assign_dock_connections(dock_connections)
patches = patches.assign_dock_weakness(dock_weakness)
return dataclasses.replace(
patches,
pickup_assignment=pickup_assignment, # PickupAssignment
starting_equipment=starting_equipment,
starting_location=starting_location, # NodeIdentifier
hints=hints,
custom_patcher_data=custom_patcher_data,
game_specific=game_specific,
)
def decode(
game_modifications: list[dict],
layout_configurations: list[BaseConfiguration],
) -> list[GamePatches]:
all_games = [
filtered_database.game_description_for_layout(configuration) for configuration in layout_configurations
]
all_pools = [
pool_creator.calculate_pool_results(configuration, game)
for configuration, game in zip(layout_configurations, all_games, strict=True)
]
return [
decode_single(index, all_pools, all_games[index], modifications, layout_configurations[index], all_games)
for index, modifications in enumerate(game_modifications)
]
def serialize(all_patches: list[GamePatches]) -> list[dict]:
return [serialize_single(index, len(all_patches), patches) for index, patches in enumerate(all_patches)]

Xet Storage Details

Size:
13.6 kB
·
Xet hash:
b3801c09201347264c9cbdaff4ef46309eeb131bc9b69a0f68621fe34fe971f5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.