about summary refs log tree commit diff stats
path: root/src/tracker_frame.cpp
blob: e94470425e79fcabe6b9fab72de0968e8ae7ec46 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
#include "tracker_frame.h"

#include <wx/aboutdlg.h>
#include <wx/choicebk.h>
#include <wx/webrequest.h>

#include <nlohmann/json.hpp>
#include <sstream>

#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
};

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 *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(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(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");

  wxNotebook *rightpane = new wxNotebook(this, wxID_ANY);
  tracker_panel_ = new TrackerPanel(rightpane);
  subway_map_ = new SubwayMap(rightpane);
  rightpane->AddPage(tracker_panel_, "Map");
  rightpane->AddPage(subway_map_, "Subway");

  wxBoxSizer *top_sizer = new wxBoxSizer(wxHORIZONTAL);
  top_sizer->Add(choicebook, wxSizerFlags().Expand().Proportion(1));
  top_sizer->Add(rightpane, 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<ConnectionDetails> 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::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();
}
eset_state(): _should_process = false _authenticated = false _map_loaded = false _try_wss = false func _errored(): if _try_wss: global._print("Could not connect to AP with ws://, now trying wss://") connectToServer() else: global._print("AP connection failed") _reset_state() emit_signal( "could_not_connect", "Could not connect to Archipelago. Check that your server and port are correct. See the error log for more information." ) func _closed(_was_clean = true): global._print("Connection closed") _reset_state() if not _initiated_disconnect: emit_signal("could_not_connect", "Disconnected from Archipelago") _initiated_disconnect = false func _connected(_proto = ""): global._print("Connected!") _try_wss = false func disconnect_from_ap(): _initiated_disconnect = true _client.disconnect_from_host() func _on_data(): var packet = _client.get_peer(1).get_packet() global._print("Got data from server: " + packet.get_string_from_utf8()) var data = JSON.parse(packet.get_string_from_utf8()) if data.error != OK: global._print("Error parsing packet from AP: " + data.error_string) return for message in data.result: var cmd = message["cmd"] global._print("Received command: " + cmd) if cmd == "RoomInfo": _seed = message["seed_name"] _remote_version = message["version"] var needed_games = [] for game in message["datapackage_checksums"].keys(): if ( !_datapackages.has(game) or _datapackages[game]["checksum"] != message["datapackage_checksums"][game] ): needed_games.append(game) if !needed_games.empty(): _pending_packages = needed_games var cur_needed = _pending_packages.pop_front() requestDatapackages([cur_needed]) else: connectToRoom() elif cmd == "DataPackage": for game in message["data"]["games"].keys(): _datapackages[game] = message["data"]["games"][game] saveSettings() if !_pending_packages.empty(): var cur_needed = _pending_packages.pop_front() requestDatapackages([cur_needed]) else: processDatapackages() connectToRoom() elif cmd == "Connected": _authenticated = true _team = message["team"] _slot = message["slot"] _players = message["players"] _checked_locations = message["checked_locations"] _slot_data = message["slot_data"] for player in _players: _player_name_by_slot[player["slot"]] = player["alias"] _death_link = _slot_data.has("death_link") and _slot_data["death_link"] if _death_link: sendConnectUpdate(["DeathLink"]) if _slot_data.has("victory_condition"): _victory_condition = _slot_data["victory_condition"] if _slot_data.has("shuffle_colors"): _color_shuffle = _slot_data["shuffle_colors"] if _slot_data.has("shuffle_doors"): _door_shuffle = (_slot_data["shuffle_doors"] > 0) if _slot_data.has("shuffle_paintings"): _painting_shuffle = _slot_data["shuffle_paintings"] if _slot_data.has("shuffle_panels"): _panel_shuffle = _slot_data["shuffle_panels"] if _slot_data.has("seed"): _slot_seed = _slot_data["seed"] if _slot_data.has("painting_entrance_to_exit"): _paintings_mapping = _slot_data["painting_entrance_to_exit"] if _slot_data.has("mastery_achievements"): _mastery_achievements = _slot_data["mastery_achievements"] if _slot_data.has("level_2_requirement"): _level_2_requirement = _slot_data["level_2_requirement"] if _slot_data.has("location_checks"): if _slot_data["location_checks"] == kCLASSIFICATION_REMOTE_NORMAL: _location_classification_bit = kCLASSIFICATION_LOCAL_NORMAL elif _slot_data["location_checks"] == kCLASSIFICATION_REMOTE_REDUCED: _location_classification_bit = kCLASSIFICATION_LOCAL_REDUCED elif _slot_data["location_checks"] == kCLASSIFICATION_REMOTE_INSANITY: _location_classification_bit = kCLASSIFICATION_LOCAL_INSANITY if _slot_data.has("early_color_hallways"): _early_color_hallways = _slot_data["early_color_hallways"] _puzzle_skips = 0 _localdata_file = "user://archipelago_data/%s_%d" % [_seed, _slot] var ap_file = File.new() if ap_file.file_exists(_localdata_file): ap_file.open(_localdata_file, File.READ) var localdata = ap_file.get_var(true) ap_file.close() if localdata.size() > 0: _last_new_item = localdata[0] else: _last_new_item = -1 if localdata.size() > 1: _puzzle_skips = localdata[1] requestSync() emit_signal("client_connected") elif cmd == "ConnectionRefused": var error_message = "" for error in message["errors"]: var submsg = "" if error == "InvalidSlot": submsg = "Invalid player name." elif error == "InvalidGame": submsg = "The specified player is not playing Lingo." elif error == "IncompatibleVersion": submsg = ( "The Archipelago server is not the correct version for this client. Expected v%d.%d.%d. Found v%d.%d.%d." % [ ap_version["major"], ap_version["minor"], ap_version["build"], _remote_version["major"], _remote_version["minor"], _remote_version["build"] ] ) elif error == "InvalidPassword": submsg = "Incorrect password." elif error == "InvalidItemsHandling": submsg = "Invalid item handling flag. This is a bug with the client. Please report it to the lingo-archipelago GitHub." if submsg != "": if error_message != "": error_message += " " error_message += submsg if error_message == "": error_message = "Unknown error." _initiated_disconnect = true _client.disconnect_from_host() emit_signal("could_not_connect", error_message) global._print("Connection to AP refused") global._print(message) elif cmd == "ReceivedItems": var i = 0 for item in message["items"]: if _map_loaded: processItem(item["item"], message["index"] + i, item["player"], item["flags"]) else: _held_items.append( { "item": item["item"], "index": message["index"] + i, "from": item["player"], "flags": item["flags"] } ) i += 1 elif cmd == "PrintJSON": if ( !message.has("receiving") or !message.has("item") or message["item"]["player"] != _slot ): continue var item_name = "Unknown" if _item_id_to_name.has(message["item"]["item"]): item_name = _item_id_to_name[message["item"]["item"]] var location_name = "Unknown" if _location_id_to_name.has(message["item"]["location"]): location_name = _location_id_to_name[message["item"]["location"]] var player_name = "Unknown" if _player_name_by_slot.has(message["receiving"]): player_name = _player_name_by_slot[message["receiving"]] var item_color = colorForItemType(message["item"]["flags"]) var messages_node = get_tree().get_root().get_node("Spatial/Messages") if message["type"] == "Hint": var is_for = "" if message["receiving"] != _slot: is_for = " for %s" % player_name if !message.has("found") || !message["found"]: messages_node.showMessage( ( "Hint: [color=%s]%s[/color]%s is on %s" % [item_color, item_name, is_for, location_name] ) ) else: if message["receiving"] != _slot: messages_node.showMessage( "Sent [color=%s]%s[/color] to %s" % [item_color, item_name, player_name] ) elif cmd == "Bounced": if ( _death_link and message.has("tags") and message.has("data") and message["tags"].has("DeathLink") ): var messages_node = get_tree().get_root().get_node("Spatial/Messages") var first_sentence = "Received Death" var second_sentence = "" if message["data"].has("source"): first_sentence = "Received Death from %s" % message["data"]["source"] if message["data"].has("cause") and message["data"]["cause"] != "": second_sentence = ". Reason: %s" % message["data"]["cause"] messages_node.showMessage(first_sentence + second_sentence) # Return the player home. get_tree().get_root().get_node("Spatial/player/pause_menu")._reload() func _process(_delta): if _should_process: _client.poll() func saveSettings(): # Save the AP settings to disk. var dir = Directory.new() var path = "user://settings" if dir.dir_exists(path): pass else: dir.make_dir(path) var file = File.new() file.open("user://settings/archipelago", File.WRITE) var data = [ap_server, ap_user, ap_pass, _datapackages] file.store_var(data, true) file.close() func saveLocaldata(): # Save the MW/slot specific settings to disk. var dir = Directory.new() var path = "user://archipelago_data" if dir.dir_exists(path): pass else: dir.make_dir(path) var file = File.new() file.open(_localdata_file, File.WRITE) var data = [_last_new_item, _puzzle_skips] file.store_var(data, true) file.close() func getSaveFileName(): return "zzAP_%s_%d" % [_seed, _slot] func connectToServer(): _initiated_disconnect = false var url = "" if ap_server.begins_with("ws://") or ap_server.begins_with("wss://"): url = ap_server _try_wss = false elif _try_wss: url = "wss://" + ap_server _try_wss = false else: url = "ws://" + ap_server _try_wss = true var err = _client.connect_to_url(url) if err != OK: emit_signal( "could_not_connect", ( "Could not connect to Archipelago. Check that your server and port are correct. See the error log for more information. Error code: %d." % err ) ) global._print("Could not connect to AP: " + err) return _should_process = true emit_signal("connect_status", "Connecting...") func sendMessage(msg): var payload = JSON.print(msg) _client.get_peer(1).set_write_mode(WebSocketPeer.WRITE_MODE_TEXT) _client.get_peer(1).put_packet(payload.to_utf8()) func requestDatapackages(games): emit_signal("connect_status", "Downloading %s data package..." % games[0]) sendMessage([{"cmd": "GetDataPackage", "games": games}]) func processDatapackages(): _item_id_to_name = {} _location_id_to_name = {} for package in _datapackages.values(): for name in package["item_name_to_id"].keys(): _item_id_to_name[package["item_name_to_id"][name]] = name for name in package["location_name_to_id"].keys(): _location_id_to_name[package["location_name_to_id"][name]] = name if _datapackages.has("Lingo"): _item_name_to_id = _datapackages["Lingo"]["item_name_to_id"] _location_name_to_id = _datapackages["Lingo"]["location_name_to_id"] func connectToRoom(): emit_signal("connect_status", "Authenticating...") sendMessage( [ { "cmd": "Connect", "password": ap_pass, "game": "Lingo", "name": ap_user, "uuid": uuid_util.v4(), "version": ap_version, "items_handling": 0b111, # always receive our items "tags": [], "slot_data": true } ] ) func sendConnectUpdate(tags): sendMessage([{"cmd": "ConnectUpdate", "tags": tags}]) func requestSync(): sendMessage([{"cmd": "Sync"}]) func sendLocation(loc_id): if _map_loaded: sendMessage([{"cmd": "LocationChecks", "locations": [loc_id]}]) else: _held_locations.append(loc_id) func setValue(key, value): sendMessage( [ { "cmd": "Set", "key": "Lingo_%d_%s" % [_slot, key], "operations": [{"operation": "replace", "value": value}] } ] ) func completedGoal(): sendMessage([{"cmd": "StatusUpdate", "status": 30}]) # CLIENT_GOAL var messages_node = get_tree().get_root().get_node("Spatial/Messages") messages_node.showMessage("You have completed your goal!") func mapFinishedLoading(): if !_map_loaded: _received_indexes.clear() _progressive_progress.clear() _has_colors = ["white"] emit_signal("evaluate_solvability") for item in _held_items: processItem(item["item"], item["index"], item["from"], item["flags"]) sendMessage([{"cmd": "LocationChecks", "locations": _held_locations}]) _map_loaded = true _held_items = [] _held_locations = [] func processItem(item, index, from, flags): if index != null: if _received_indexes.has(index): # Do not re-process items. return _received_indexes.append(index) global._print(item) var gamedata = $Gamedata var item_name = "Unknown" if _item_id_to_name.has(item): item_name = _item_id_to_name[item] if gamedata.door_ids_by_item_id.has(int(item)): var doorsNode = get_tree().get_root().get_node("Spatial/Doors") for door_id in gamedata.door_ids_by_item_id[int(item)]: doorsNode.get_node(door_id).openDoor() if gamedata.painting_ids_by_item_id.has(int(item)): var real_parent_node = get_tree().get_root().get_node("Spatial/Decorations/Paintings") var fake_parent_node = get_tree().get_root().get_node_or_null("Spatial/AP_Paintings") for painting_id in gamedata.painting_ids_by_item_id[int(item)]: var painting_node = real_parent_node.get_node_or_null(painting_id) if painting_node != null: painting_node.movePainting() if _painting_shuffle: painting_node = fake_parent_node.get_node_or_null(painting_id) if painting_node != null: painting_node.get_node("Script").movePainting() # Handle progressive items. if item_name in progressive_items.keys(): if not item_name in _progressive_progress: _progressive_progress[item_name] = 0 if _progressive_progress[item_name] < progressive_items[item_name].size(): var subitem_name = progressive_items[item_name][_progressive_progress[item_name]]["item"] global._print(subitem_name) processItem(_item_name_to_id[subitem_name], null, null, null) _progressive_progress[item_name] += 1 if _color_shuffle and color_items.has(_item_id_to_name[item]): var lcol = _item_id_to_name[item].to_lower() if not _has_colors.has(lcol): _has_colors.append(lcol) emit_signal("evaluate_solvability") # Show a message about the item if it's new. Also apply effects here. if index != null and index > _last_new_item: _last_new_item = index saveLocaldata() if item_name in progressive_items: var subitem = progressive_items[item_name][_progressive_progress[item_name] - 1] item_name += " (%s)" % subitem["display"] var player_name = "Unknown" if _player_name_by_slot.has(from): player_name = _player_name_by_slot[from] var item_color = colorForItemType(flags) var messages_node = get_tree().get_root().get_node("Spatial/Messages") if from == _slot: messages_node.showMessage("Found [color=%s]%s[/color]" % [item_color, item_name]) else: messages_node.showMessage( "Received [color=%s]%s[/color] from %s" % [item_color, item_name, player_name] ) var effects_node = get_tree().get_root().get_node("Spatial/AP_Effects") if item_name == "Slowness Trap": effects_node.trigger_slowness_trap() if item_name == "Iceland Trap": effects_node.trigger_iceland_trap() if item_name == "Atbash Trap": effects_node.trigger_atbash_trap() if item_name == "Puzzle Skip": _puzzle_skips += 1 saveLocaldata() func doorIsVanilla(door): return !$Gamedata.mentioned_doors.has(door) func paintingIsVanilla(painting): return !$Gamedata.mentioned_paintings.has(painting) func evaluateSolvability(): emit_signal("evaluate_solvability") func getAvailablePuzzleSkips(): return _puzzle_skips func usePuzzleSkip(): _puzzle_skips -= 1 saveLocaldata() func colorForItemType(flags): var int_flags = int(flags) if int_flags & 1: # progression return "#bc51e0" elif int_flags & 2: # useful return "#2b67ff" elif int_flags & 4: # trap return "#d63a22" else: # filler return "#14de9e"