#include "tracker_frame.h" #include #include #include #include #include #include #include "achievements_pane.h" #include "ap_state.h" #include "connection_dialog.h" #include "settings_dialog.h" #include "subway_map.h" #include "tracker_config.h" #include "tracker_panel.h" #include "version.h" enum TrackerFrameIds { ID_CONNECT = 1, ID_CHECK_FOR_UPDATES = 2, ID_SETTINGS = 3, ID_ZOOM_IN = 4, ID_ZOOM_OUT = 5, }; wxDEFINE_EVENT(STATE_RESET, wxCommandEvent); wxDEFINE_EVENT(STATE_CHANGED, wxCommandEvent); wxDEFINE_EVENT(STATUS_CHANGED, wxCommandEvent); TrackerFrame::TrackerFrame() : wxFrame(nullptr, wxID_ANY, "Lingo Archipelago Tracker", wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE | wxFULL_REPAINT_ON_RESIZE) { ::wxInitAllImageHandlers(); AP_SetTrackerFrame(this); wxMenu *menuFile = new wxMenu(); menuFile->Append(ID_CONNECT, "&Connect"); menuFile->Append(ID_SETTINGS, "&Settings"); menuFile->Append(wxID_EXIT); wxMenu *menuView = new wxMenu(); zoom_in_menu_item_ = menuView->Append(ID_ZOOM_IN, "Zoom In\tCtrl-+"); zoom_out_menu_item_ = menuView->Append(ID_ZOOM_OUT, "Zoom Out\tCtrl--"); zoom_in_menu_item_->Enable(false); zoom_out_menu_item_->Enable(false); wxMenu *menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); menuHelp->Append(ID_CHECK_FOR_UPDATES, "Check for Updates"); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, "&File"); menuBar->Append(menuView, "&View"); menuBar->Append(menuHelp, "&Help"); SetMenuBar(menuBar); CreateStatusBar(); SetStatusText("Not connected to Archipelago."); Bind(wxEVT_MENU, &TrackerFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_MENU, &TrackerFrame::OnExit, this, wxID_EXIT); Bind(wxEVT_MENU, &TrackerFrame::OnConnect, this, ID_CONNECT); Bind(wxEVT_MENU, &TrackerFrame::OnSettings, this, ID_SETTINGS); Bind(wxEVT_MENU, &TrackerFrame::OnCheckForUpdates, this, ID_CHECK_FOR_UPDATES); Bind(wxEVT_MENU, &TrackerFrame::OnZoomIn, this, ID_ZOOM_IN); Bind(wxEVT_MENU, &TrackerFrame::OnZoomOut, this, ID_ZOOM_OUT); Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, &TrackerFrame::OnChangePage, this); Bind(STATE_RESET, &TrackerFrame::OnStateReset, this); Bind(STATE_CHANGED, &TrackerFrame::OnStateChanged, this); Bind(STATUS_CHANGED, &TrackerFrame::OnStatusChanged, this); achievements_pane_ = new AchievementsPane(this); wxChoicebook *choicebook = new wxChoicebook(this, wxID_ANY); choicebook->AddPage(achievements_pane_, "Achievements"); notebook_ = new wxNotebook(this, wxID_ANY); tracker_panel_ = new TrackerPanel(notebook_); subway_map_ = new SubwayMap(notebook_); notebook_->AddPage(tracker_panel_, "Map"); notebook_->AddPage(subway_map_, "Subway"); wxBoxSizer *top_sizer = new wxBoxSizer(wxHORIZONTAL); top_sizer->Add(choicebook, wxSizerFlags().Expand().Proportion(1)); top_sizer->Add(notebook_, wxSizerFlags().Expand().Proportion(3)); SetSizerAndFit(top_sizer); SetSize(1280, 728); if (!GetTrackerConfig().asked_to_check_for_updates) { GetTrackerConfig().asked_to_check_for_updates = true; if (wxMessageBox( "Check for updates automatically when the tracker is opened?", "Lingo AP Tracker", wxYES_NO) == wxYES) { GetTrackerConfig().should_check_for_updates = true; } else { GetTrackerConfig().should_check_for_updates = false; } GetTrackerConfig().Save(); } if (GetTrackerConfig().should_check_for_updates) { CheckForUpdates(/*manual=*/false); } } void TrackerFrame::SetStatusMessage(std::string message) { wxCommandEvent *event = new wxCommandEvent(STATUS_CHANGED); event->SetString(message.c_str()); QueueEvent(event); } void TrackerFrame::ResetIndicators() { QueueEvent(new wxCommandEvent(STATE_RESET)); } void TrackerFrame::UpdateIndicators() { QueueEvent(new wxCommandEvent(STATE_CHANGED)); } void TrackerFrame::OnAbout(wxCommandEvent &event) { wxAboutDialogInfo about_info; about_info.SetName("Lingo Archipelago Tracker"); about_info.SetVersion(kTrackerVersion.ToString()); about_info.AddDeveloper("hatkirby"); about_info.AddArtist("Brenton Wildes"); about_info.AddArtist("kinrah"); wxAboutBox(about_info); } void TrackerFrame::OnExit(wxCommandEvent &event) { Close(true); } void TrackerFrame::OnConnect(wxCommandEvent &event) { ConnectionDialog dlg; if (dlg.ShowModal() == wxID_OK) { GetTrackerConfig().connection_details.ap_server = dlg.GetServerValue(); GetTrackerConfig().connection_details.ap_player = dlg.GetPlayerValue(); GetTrackerConfig().connection_details.ap_password = dlg.GetPasswordValue(); std::deque new_history; new_history.push_back(GetTrackerConfig().connection_details); for (const ConnectionDetails &details : GetTrackerConfig().connection_history) { if (details != GetTrackerConfig().connection_details) { new_history.push_back(details); } } while (new_history.size() > 5) { new_history.pop_back(); } GetTrackerConfig().connection_history = std::move(new_history); GetTrackerConfig().Save(); AP_Connect(dlg.GetServerValue(), dlg.GetPlayerValue(), dlg.GetPasswordValue()); } } void TrackerFrame::OnSettings(wxCommandEvent &event) { SettingsDialog dlg; if (dlg.ShowModal() == wxID_OK) { GetTrackerConfig().should_check_for_updates = dlg.GetShouldCheckForUpdates(); GetTrackerConfig().hybrid_areas = dlg.GetHybridAreas(); GetTrackerConfig().show_hunt_panels = dlg.GetShowHuntPanels(); GetTrackerConfig().Save(); UpdateIndicators(); } } void TrackerFrame::OnCheckForUpdates(wxCommandEvent &event) { CheckForUpdates(/*manual=*/true); } void TrackerFrame::OnZoomIn(wxCommandEvent &event) { if (notebook_->GetSelection() == 1) { subway_map_->Zoom(true); } } void TrackerFrame::OnZoomOut(wxCommandEvent& event) { if (notebook_->GetSelection() == 1) { subway_map_->Zoom(false); } } void TrackerFrame::OnChangePage(wxBookCtrlEvent &event) { zoom_in_menu_item_->Enable(event.GetSelection() == 1); zoom_out_menu_item_->Enable(event.GetSelection() == 1); } void TrackerFrame::OnStateReset(wxCommandEvent& event) { tracker_panel_->UpdateIndicators(); achievements_pane_->UpdateIndicators(); subway_map_->OnConnect(); Refresh(); } void TrackerFrame::OnStateChanged(wxCommandEvent &event) { tracker_panel_->UpdateIndicators(); achievements_pane_->UpdateIndicators(); subway_map_->UpdateIndicators(); Refresh(); } void TrackerFrame::OnStatusChanged(wxCommandEvent &event) { SetStatusText(event.GetString()); } void TrackerFrame::CheckForUpdates(bool manual) { wxWebRequest request = wxWebSession::GetDefault().CreateRequest( this, "https://code.fourisland.com/lingo-ap-tracker/plain/VERSION"); if (!request.IsOk()) { if (manual) { wxMessageBox("Could not check for updates.", "Error", wxOK | wxICON_ERROR); } else { SetStatusText("Could not check for updates."); } return; } Bind(wxEVT_WEBREQUEST_STATE, [this, manual](wxWebRequestEvent &evt) { if (evt.GetState() == wxWebRequest::State_Completed) { std::string response = evt.GetResponse().AsString().ToStdString(); Version latest_version(response); if (kTrackerVersion < latest_version) { std::ostringstream message_text; message_text << "There is a newer version of Lingo AP Tracker " "available. You have " << kTrackerVersion.ToString() << ", and the latest version is " << latest_version.ToString() << ". Would you like to update?"; if (wxMessageBox(message_text.str(), "Update available", wxYES_NO) == wxYES) { wxLaunchDefaultBrowser( "https://code.fourisland.com/lingo-ap-tracker/about/" "CHANGELOG.md"); } } else if (manual) { wxMessageBox("Lingo AP Tracker is up to date!", "Lingo AP Tracker", wxOK); } } else if (evt.GetState() == wxWebRequest::State_Failed) { if (manual) { wxMessageBox("Could not check for updates.", "Error", wxOK | wxICON_ERROR); } else { SetStatusText("Could not check for updates."); } } }); request.Start(); } f='#n156'>156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
extends Node

var SCRIPT_client
var SCRIPT_keyboard
var SCRIPT_locationListener
var SCRIPT_minimap
var SCRIPT_victoryListener
var SCRIPT_websocketserver

var ap_server = ""
var ap_user = ""
var ap_pass = ""
var connection_history = []
var show_compass = false
var show_locations = false
var show_minimap = false

var client
var keyboard

var _localdata_file = ""
var _last_new_item = -1
var _batch_locations = false
var _held_locations = []
var _held_location_scouts = []
var _location_scouts = {}
var _item_locks = {}
var _inverse_item_locks = {}
var _held_letters = {}
var _letters_setup = false
var _already_connected = false

const kSHUFFLE_LETTERS_VANILLA = 0
const kSHUFFLE_LETTERS_UNLOCKED = 1
const kSHUFFLE_LETTERS_PROGRESSIVE = 2
const kSHUFFLE_LETTERS_VANILLA_CYAN = 3
const kSHUFFLE_LETTERS_ITEM_CYAN = 4

const kLETTER_BEHAVIOR_VANILLA = 0
const kLETTER_BEHAVIOR_ITEM = 1
const kLETTER_BEHAVIOR_UNLOCKED = 2

const kCYAN_DOOR_BEHAVIOR_H2 = 0
const kCYAN_DOOR_BEHAVIOR_DOUBLE_LETTER = 1
const kCYAN_DOOR_BEHAVIOR_ITEM = 2

const kEndingNameByVictoryValue = {
	0: "GRAY",
	1: "PURPLE",
	2: "MINT",
	3: "BLACK",
	4: "BLUE",
	5: "CYAN",
	6: "RED",
	7: "PLUM",
	8: "ORANGE",
	9: "GOLD",
	10: "YELLOW",
	11: "GREEN",
	12: "WHITE",
}

var apworld_version = [0, 0, 0]
var cyan_door_behavior = kCYAN_DOOR_BEHAVIOR_H2
var daedalus_roof_access = false
var enable_gift_maps = []
var keyholder_sanity = false
var port_pairings = {}
var shuffle_control_center_colors = false
var shuffle_doors = false
var shuffle_gallery_paintings = false
var shuffle_letters = kSHUFFLE_LETTERS_VANILLA
var shuffle_symbols = false
var shuffle_worldports = false
var strict_cyan_ending = false
var strict_purple_ending = false
var victory_condition = -1

var color_by_material_path = {}

signal could_not_connect
signal connect_status
signal ap_connected


func _init():
	# Read AP settings from file, if there are any
	if FileAccess.file_exists("user://ap_settings"):
		var file = FileAccess.open("user://ap_settings", FileAccess.READ)
		var data = file.get_var(true)
		file.close()

		if typeof(data) != TYPE_ARRAY:
			global._print("AP settings file is corrupted")
			data = []

		if data.size() > 0:
			ap_server = data[0]

		if data.size() > 1:
			ap_user = data[1]

		if data.size() > 2:
			ap_pass = data[2]

		if data.size() > 3:
			connection_history = data[3]

		if data.size() > 4:
			show_compass = data[4]

		if data.size() > 5:
			show_locations = data[5]

		if data.size() > 6:
			show_minimap = data[6]

	# We need to create a mapping from material paths to the original colors of
	# those materials. We force reload the materials, overwriting any custom
	# textures, and create the mapping. We then reload the textures in case the
	# player had a custom one enabled.
	var directory = DirAccess.open("res://assets/materials")
	for material_name in directory.get_files():
		var material = ResourceLoader.load(
			"res://assets/materials/" + material_name, "", ResourceLoader.CACHE_MODE_REPLACE
		)

		color_by_material_path[material.resource_path] = Color(material.albedo_color)

	settings.load_user_textures()


func _ready():
	client = SCRIPT_client.new()
	client.SCRIPT_websocketserver = SCRIPT_websocketserver

	client.item_received.connect(_process_item)
	client.location_scout_received.connect(_process_location_scout)
	client.text_message_received.connect(_process_text_message)
	client.item_sent_notification.connect(_process_item_sent_notification)
	client.hint_received.connect(_process_hint_received)
	client.accessible_locations_updated.connect(_on_accessible_locations_updated)
	client.checked_locations_updated.connect(_on_checked_locations_updated)
	client.checked_worldports_updated.connect(_on_checked_worldports_updated)
	client.door_latched.connect(_on_door_latched)

	client.could_not_connect.connect(_client_could_not_connect)
	client.connect_status.connect(_client_connect_status)
	client.client_connected.connect(_client_connected)

	add_child(client)

	keyboard = SCRIPT_keyboard.new()
	add_child(keyboard)
	client.keyboard_update_received.connect(keyboard.remote_keyboard_updated)


func saveSettings():
	# Save the AP settings to disk.
	var path = "user://ap_settings"
	var file = FileAccess.open(path, FileAccess.WRITE)

	var data = [
		ap_server,
		ap_user,
		ap_pass,
		connection_history,
		show_compass,
		show_locations,
		show_minimap,
	]
	file.store_var(data, true)
	file.close()


func saveLocaldata():
	# Save the MW/slot specific settings to disk.
	var dir = DirAccess.open("user://")
	var folder = "archipelago_data"
	if not dir.dir_exists(folder):
		dir.make_dir(folder)

	var file = FileAccess.open(_localdata_file, FileAccess.WRITE)

	var data = [
		_last_new_item,
	]
	file.store_var(data, true)
	file.close()


func connectToServer():
	_last_new_item = -1
	_batch_locations = false
	_held_locations = []
	_held_location_scouts = []
	_location_scouts = {}
	_letters_setup = false
	_held_letters = {}
	_already_connected = false

	client.connectToServer(ap_server, ap_user, ap_pass)


func getSaveFileName():
	return "zzAP_%s_%d" % [client._seed, client._slot]


func disconnect_from_ap():
	_already_connected = false

	var effects = global.get_node("Effects")
	effects.set_connection_lost(false)

	client.disconnect_from_ap()


func get_item_id_for_door(door_id):
	return _item_locks.get(door_id, null)


func _process_item(item, amount):
	var gamedata = global.get_node("Gamedata")

	var item_id = int(item["id"])
	var prog_id = null
	if _inverse_item_locks.has(item_id):
		for lock in _inverse_item_locks.get(item_id):
			if lock[1] != amount:
				continue

			if gamedata.progressive_id_by_ap_id.has(item_id):
				prog_id = lock[0]

			if gamedata.get_door_map_name(lock[0]) != global.map:
				continue

			# TODO: fix doors opening from door groups
			var receivers = gamedata.get_door_receivers(lock[0])
			var scene = get_tree().get_root().get_node_or_null("scene")
			if scene != null:
				for receiver in receivers:
					var rnode = scene.get_node_or_null(receiver)
					if rnode != null:
						rnode.handleTriggered()

	var letter_id = gamedata.letter_id_by_ap_id.get(item_id, null)
	if letter_id != null:
		var letter = gamedata.objects.get_letters()[letter_id]
		if not letter.has_level2() or not letter.get_level2():
			_process_key_item(letter.get_key(), amount)

	if gamedata.symbol_item_ids.has(item_id):
		var player = get_tree().get_root().get_node_or_null("scene/player")
		if player != null:
			player.evaluate_solvability.emit()

	if item_id == gamedata.objects.get_special_ids()["A Job Well Done"]:
		update_job_well_done_sign()

	# Show a message about the item if it's new.
	if int(item["index"]) > _last_new_item:
		_last_new_item = int(item["index"])
		saveLocaldata()

		var full_item_name = item["text"]
		if prog_id != null:
			var door = gamedata.objects.get_doors()[prog_id]
			full_item_name = "%s (%s)" % [full_item_name, door.get_name()]

		var message
		if "sender" in item:
			message = (
				"Received %s from %s"
				% [wrapInItemColorTags(full_item_name, item["flags"]), item["sender"]]
			)
		else:
			message = "Found %s" % wrapInItemColorTags(full_item_name, item["flags"])

		if gamedata.anti_trap_ids.has(item):
			keyboard.block_letter(gamedata.anti_trap_ids[item])

		global._print(message)

		global.get_node("Messages").showMessage(message)


func _process_item_sent_notification(message):
	var sentMsg = (
		"Sent %s to %s"
		% [
			wrapInItemColorTags(message["item_name"], message["item_flags"]),
			message["receiver_name"]
		]
	)
	#if _hinted_locations.has(message["item"]["location"]):
	#	sentMsg += " ([color=#fafad2]Hinted![/color])"
	global.get_node("Messages").showMessage(sentMsg)


func _process_hint_received(message):
	var is_for = ""
	if message["self"] == 0:
		is_for = " for %s" % message["receiver_name"]

	global.get_node("Messages").showMessage(
		(
			"Hint: %s%s is on %s"
			% [
				wrapInItemColorTags(message["item_name"], message["item_flags"]),
				is_for,
				message["location_name"]
			]
		)
	)


func _process_text_message(message):
	var parts = []
	for message_part in message:
		if message_part["type"] == "text":
			parts.append(message_part["text"])
		elif message_part["type"] == "player":
			if message_part["self"] == 1:
				parts.append("[color=#ee00ee]%s[/color]" % message_part["text"])
			else:
				parts.append("[color=#fafad2]%s[/color]" % message_part["text"])
		elif message_part["type"] == "item":
			parts.append(wrapInItemColorTags(message_part["text"], int(message_part["flags"])))
		elif message_part["type"] == "location":
			parts.append("[color=#00ff7f]%s[/color]" % message_part["text"])

	var textclient_node = global.get_node("Textclient")
	if textclient_node != null:
		textclient_node.parse_printjson("".join(parts))


func _process_location_scout(location_id, item_name, player_name, flags, for_self):
	_location_scouts[location_id] = {
		"item": item_name, "player": player_name, "flags": flags, "for_self": for_self
	}

	if for_self and flags & 4 != 0:
		# This is a trap for us, so let's not display it.
		return

	var gamedata = global.get_node("Gamedata")
	var map_id = gamedata.map_id_by_name.get(global.map)

	var letter_id = gamedata.letter_id_by_ap_id.get(location_id, null)
	if letter_id != null:
		var letter = gamedata.objects.get_letters()[letter_id]
		var room = gamedata.objects.get_rooms()[letter.get_room_id()]
		if room.get_map_id() == map_id:
			var collectable = get_tree().get_root().get_node("scene").get_node_or_null(
				letter.get_path()
			)
			if collectable != null:
				collectable.setScoutedText(item_name)


func _on_accessible_locations_updated():
	var textclient_node = global.get_node("Textclient")
	if textclient_node != null:
		textclient_node.update_locations()


func _on_checked_locations_updated():
	var textclient_node = global.get_node("Textclient")
	if textclient_node != null:
		textclient_node.update_locations(false)


func _on_checked_worldports_updated():
	var textclient_node = global.get_node("Textclient")
	if textclient_node != null:
		textclient_node.update_locations()
		textclient_node.update_worldports()


func _on_door_latched(door_id):
	var gamedata = global.get_node("Gamedata")
	if gamedata.get_door_map_name(door_id) != global.map:
		return

	var receivers = gamedata.get_door_receivers(door_id)
	var scene = get_tree().get_root().get_node_or_null("scene")
	if scene != null:
		for receiver in receivers:
			var rnode = scene.get_node_or_null(receiver)
			if rnode != null:
				rnode.handleTriggered()


func _client_could_not_connect(message):
	could_not_connect.emit(message)

	if global.loaded:
		var effects = global.get_node("Effects")
		effects.set_connection_lost(true)

		var messages = global.get_node("Messages")
		messages.showMessage("Connection to multiworld lost.")


func _client_connect_status(message):
	connect_status.emit(message)


func _client_connected(slot_data):
	var effects = global.get_node("Effects")
	effects.set_connection_lost(false)

	if _already_connected:
		var messages = global.get_node("Messages")
		messages.showMessage("Reconnected to multiworld!")
		return

	_already_connected = true

	var gamedata = global.get_node("Gamedata")

	_localdata_file = "user://archipelago_data/%s_%d" % [client._seed, client._slot]
	_last_new_item = -1

	if FileAccess.file_exists(_localdata_file):
		var ap_file = FileAccess.open(_localdata_file, FileAccess.READ)
		var localdata = []
		if ap_file != null:
			localdata = ap_file.get_var(true)
			ap_file.close()

		if typeof(localdata) != TYPE_ARRAY:
			print("AP localdata file is corrupted")
			localdata = []

		if localdata.size() > 0:
			_last_new_item = localdata[0]

	# Read slot data.
	cyan_door_behavior = int(slot_data.get("cyan_door_behavior", 0))
	daedalus_roof_access = bool(slot_data.get("daedalus_roof_access", false))
	enable_gift_maps = slot_data.get("enable_gift_maps", [])
	keyholder_sanity = bool(slot_data.get("keyholder_sanity", false))
	shuffle_control_center_colors = bool(slot_data.get("shuffle_control_center_colors", false))
	shuffle_doors = bool(slot_data.get("shuffle_doors", false))
	shuffle_gallery_paintings = bool(slot_data.get("shuffle_gallery_paintings", false))
	shuffle_letters = int(slot_data.get("shuffle_letters", 0))
	shuffle_symbols = bool(slot_data.get("shuffle_symbols", false))
	shuffle_worldports = bool(slot_data.get("shuffle_worldports", false))
	strict_cyan_ending = bool(slot_data.get("strict_cyan_ending", false))
	strict_purple_ending = bool(slot_data.get("strict_purple_ending", false))
	victory_condition = int(slot_data.get("victory_condition", 0))

	if slot_data.has("version"):
		var version_msg = slot_data["version"]
		apworld_version = [int(version_msg[0]), int(version_msg[1]), 0]
		if version_msg.size() > 2:
			apworld_version[2] = int(version_msg[2])

	port_pairings.clear()
	if slot_data.has("port_pairings"):
		var raw_pp = slot_data.get("port_pairings")

		for p1 in raw_pp.keys():
			port_pairings[int(p1)] = int(raw_pp[p1])

	# Set up item locks.
	_item_locks = {}

	if shuffle_doors:
		for door in gamedata.objects.get_doors():
			if (
				door.get_type() == gamedata.SCRIPT_proto.DoorType.STANDARD
				or door.get_type() == gamedata.SCRIPT_proto.DoorType.ITEM_ONLY
			):
				_item_locks[door.get_id()] = [door.get_ap_id(), 1]

		for progressive in gamedata.objects.get_progressives():
			for i in range(0, progressive.get_doors().size()):
				var door = gamedata.objects.get_doors()[progressive.get_doors()[i]]
				_item_locks[door.get_id()] = [progressive.get_ap_id(), i + 1]

		for door_group in gamedata.objects.get_door_groups():
			if door_group.get_type() == gamedata.SCRIPT_proto.DoorGroupType.CONNECTOR:
				if shuffle_worldports:
					continue
			elif door_group.get_type() != gamedata.SCRIPT_proto.DoorGroupType.SHUFFLE_GROUP:
				continue

			for door in door_group.get_doors():
				_item_locks[door] = [door_group.get_ap_id(), 1]

	if shuffle_control_center_colors:
		for door in gamedata.objects.get_doors():
			if door.get_type() == gamedata.SCRIPT_proto.DoorType.CONTROL_CENTER_COLOR:
				_item_locks[door.get_id()] = [door.get_ap_id(), 1]

		for door_group in gamedata.objects.get_door_groups():
			if (
				door_group.get_type() == gamedata.SCRIPT_proto.DoorGroupType.COLOR_CONNECTOR
				and not shuffle_worldports
			):
				for door in door_group.get_doors():
					_item_locks[door] = [door_group.get_ap_id(), 1]

	if shuffle_gallery_paintings:
		for door in gamedata.objects.get_doors():
			if door.get_type() == gamedata.SCRIPT_proto.DoorType.GALLERY_PAINTING:
				_item_locks[door.get_id()] = [door.get_ap_id(), 1]

	if cyan_door_behavior == kCYAN_DOOR_BEHAVIOR_ITEM:
		for door_group in gamedata.objects.get_door_groups():
			if door_group.get_type() == gamedata.SCRIPT_proto.DoorGroupType.CYAN_DOORS:
				for door in door_group.get_doors():
					if not _item_locks.has(door):
						_item_locks[door] = [door_group.get_ap_id(), 1]

	# Create a reverse item locks map for processing items.
	_inverse_item_locks = {}

	for door_id in _item_locks.keys():
		var lock = _item_locks.get(door_id)

		if not _inverse_item_locks.has(lock[0]):
			_inverse_item_locks[lock[0]] = []

		_inverse_item_locks[lock[0]].append([door_id, lock[1]])

	if shuffle_worldports:
		var textclient = global.get_node("Textclient")
		textclient.setup_worldports()

	ap_connected.emit()


func start_batching_locations():
	_batch_locations = true


func send_location(loc_id):
	if client._checked_locations.has(loc_id):
		return

	if _batch_locations:
		_held_locations.append(loc_id)
	else:
		client.sendLocation(loc_id)


func scout_location(loc_id):
	if _location_scouts.has(loc_id):
		return _location_scouts.get(loc_id)

	if _batch_locations:
		_held_location_scouts.append(loc_id)
	else:
		client.scoutLocation(loc_id)

	return null


func stop_batching_locations():
	_batch_locations = false

	if not _held_locations.is_empty():
		client.sendLocations(_held_locations)
		_held_locations.clear()

	if not _held_location_scouts.is_empty():
		client.scoutLocations(_held_location_scouts)
		_held_location_scouts.clear()


func colorForItemType(flags):
	var int_flags = int(flags)
	if int_flags & 1:  # progression
		if int_flags & 2:  # proguseful
			return "#f0d200"
		else:
			return "#bc51e0"
	elif int_flags & 2:  # useful
		return "#2b67ff"
	elif int_flags & 4:  # trap
		return "#d63a22"
	else:  # filler
		return "#14de9e"


func wrapInItemColorTags(text, flags):
	var int_flags = int(flags)
	if int_flags & 1 and int_flags & 2:  # proguseful
		return "[rainbow]%s[/rainbow]" % text
	else:
		return "[color=%s]%s[/color]" % [colorForItemType(flags), text]


func get_letter_behavior(key, level2):
	if shuffle_letters == kSHUFFLE_LETTERS_UNLOCKED:
		return kLETTER_BEHAVIOR_UNLOCKED

	if [kSHUFFLE_LETTERS_VANILLA_CYAN, kSHUFFLE_LETTERS_ITEM_CYAN].has(shuffle_letters):
		if level2:
			if shuffle_letters == kSHUFFLE_LETTERS_VANILLA_CYAN:
				return kLETTER_BEHAVIOR_VANILLA
			else:
				return kLETTER_BEHAVIOR_ITEM
		else:
			return kLETTER_BEHAVIOR_UNLOCKED

	if not level2 and ["h", "i", "n", "t"].has(key):
		# This differs from the equivalent function in the apworld. Logically it is
		# the same as UNLOCKED since they are in the starting room, but VANILLA
		# means the player still has to actually pick up the letters.
		return kLETTER_BEHAVIOR_VANILLA

	if shuffle_letters == kSHUFFLE_LETTERS_PROGRESSIVE:
		return kLETTER_BEHAVIOR_ITEM

	return kLETTER_BEHAVIOR_VANILLA


func setup_keys():
	keyboard.load_seed()

	_letters_setup = true

	for k in _held_letters.keys():
		_process_key_item(k, _held_letters[k])

	_held_letters.clear()


func _process_key_item(key, level):
	if not _letters_setup:
		_held_letters[key] = max(_held_letters.get(key, 0), level)
		return

	if shuffle_letters == kSHUFFLE_LETTERS_ITEM_CYAN:
		level += 1

	keyboard.collect_remote_letter(key, level)


func update_job_well_done_sign():
	if global.map != "daedalus":
		return

	var gamedata = global.get_node("Gamedata")
	var job_item = gamedata.objects.get_special_ids()["A Job Well Done"]
	var jobs_done = client.getItemAmount(job_item)

	var sign2 = get_tree().get_root().get_node_or_null("scene/Meshes/Miscellaneous/sign2")
	var sign3 = get_tree().get_root().get_node_or_null("scene/Meshes/Miscellaneous/sign3")

	if sign2 != null and sign3 != null:
		if jobs_done == 0:
			sign2.text = "what are you doing"
			sign3.text = "?"
		elif jobs_done == 1:
			sign2.text = "a job well done"
			sign3.text = "is its own reward"
		else:
			sign2.text = "%d jobs well done" % jobs_done
			sign3.text = "are their own reward"

		sign2.get_node("MeshInstance3D").mesh.text = sign2.text
		sign3.get_node("MeshInstance3D").mesh.text = sign3.text