| 1 |
#include "GameConnection.h" |
| 2 |
#include "DiffStatus.h" |
| 3 |
#include "DiffDoom3MapWriter.h" |
| 4 |
#include "AutomationEngine.h" |
| 5 |
|
| 6 |
#include "i18n.h" |
| 7 |
#include "igame.h" |
| 8 |
#include "icameraview.h" |
| 9 |
#include "inode.h" |
| 10 |
#include "imap.h" |
| 11 |
#include "ientity.h" |
| 12 |
#include "iselection.h" |
| 13 |
#include "ui/iuserinterface.h" |
| 14 |
#include "ui/imenumanager.h" |
| 15 |
#include "ui/imainframe.h" |
| 16 |
|
| 17 |
#include "scene/Traverse.h" |
| 18 |
#include "wxutil/Bitmap.h" |
| 19 |
#include "util/ScopedBoolLock.h" |
| 20 |
#include "registry/registry.h" |
| 21 |
|
| 22 |
#include <sigc++/signal.h> |
| 23 |
#include <sigc++/connection.h> |
| 24 |
#include <wx/toolbar.h> |
| 25 |
#include <wx/artprov.h> |
| 26 |
#include <wx/process.h> |
| 27 |
|
| 28 |
#include "GameConnectionControl.h" |
| 29 |
#include "messages/MapFileOperation.h" |
| 30 |
#include "messages/NotificationMessage.h" |
| 31 |
|
| 32 |
namespace gameconn |
| 33 |
{ |
| 34 |
|
| 35 |
namespace |
| 36 |
{ |
| 37 |
//this is how often this class "thinks" when idle |
| 38 |
constexpr int THINK_INTERVAL = 123; |
| 39 |
|
| 40 |
//all ordinary requests, executed synchronously |
| 41 |
constexpr int TAG_GENERIC = 5; |
| 42 |
//camera DR->TDM sync is continuous, executed asynchronously |
| 43 |
constexpr int TAG_CAMERA = 6; |
| 44 |
//multistep procedure for TDM game start/restart |
| 45 |
constexpr int TAG_RESTART = 7; |
| 46 |
|
| 47 |
inline std::string messagePreamble(const std::string& type) { |
| 48 |
return fmt::format("message \"{}\"\n", type); |
| 49 |
} |
| 50 |
|
| 51 |
inline std::string actionPreamble(const std::string& type) { |
| 52 |
return messagePreamble("action") + fmt::format("action \"{0}\"\n", type); |
| 53 |
} |
| 54 |
|
| 55 |
inline std::string queryPreamble(std::string type) { |
| 56 |
return messagePreamble("query") + fmt::format("query \"{}\"\n", type); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
GameConnection::GameConnection() |
| 61 |
{ |
| 62 |
_engine.reset(new AutomationEngine()); |
| 63 |
} |
| 64 |
|
| 65 |
std::string GameConnection::executeGenericRequest(const std::string& request) |
| 66 |
{ |
| 67 |
_engine->waitForTags(TAG_GENERIC); |
| 68 |
return _engine->executeRequestBlocking(TAG_GENERIC, request); |
| 69 |
} |
| 70 |
|
| 71 |
bool GameConnection::sendAnyPendingAsync() |
| 72 |
{ |
| 73 |
if (_mapObserver.getChanges().size() && _updateMapAlways) { |
| 74 |
//note: this is blocking |
| 75 |
doUpdateMap(); |
| 76 |
return true; |
| 77 |
} |
| 78 |
return sendPendingCameraUpdate(); |
| 79 |
} |
| 80 |
|
| 81 |
void GameConnection::think() |
| 82 |
{ |
| 83 |
if (_engine->hasLostConnection()) { |
| 84 |
//lost connection recently: disable everything |
| 85 |
disconnect(true); |
| 86 |
} |
| 87 |
|
| 88 |
if (_engine->areTagsInProgress(1 << TAG_RESTART) != _restartInProgress) { |
| 89 |
//restart game procedure has just ended: notify GUI |
| 90 |
_restartInProgress = !_restartInProgress; |
| 91 |
signal_StatusChanged.emit(0); |
| 92 |
} |
| 93 |
|
| 94 |
_engine->think(); |
| 95 |
|
| 96 |
if (!_engine->areTagsInProgress()) { |
| 97 |
//doing nothing now: send async command if present |
| 98 |
sendAnyPendingAsync(); |
| 99 |
//think now, don't delay to next frame |
| 100 |
_engine->think(); |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
void GameConnection::onTimerEvent(wxTimerEvent& ev) |
| 105 |
{ |
| 106 |
if (_timerInProgress) return; // avoid double-entering |
| 107 |
|
| 108 |
util::ScopedBoolLock guard(_timerInProgress); |
| 109 |
|
| 110 |
think(); |
| 111 |
} |
| 112 |
|
| 113 |
void GameConnection::setThinkLoop(bool enable) |
| 114 |
{ |
| 115 |
if (enable && !_thinkTimer) { |
| 116 |
_thinkTimer.reset(new wxTimer()); |
| 117 |
_thinkTimer->Bind(wxEVT_TIMER, &GameConnection::onTimerEvent, this); |
| 118 |
_thinkTimer->Start(THINK_INTERVAL); |
| 119 |
} |
| 120 |
if (!enable && _thinkTimer) { |
| 121 |
_thinkTimer->Stop(); |
| 122 |
_thinkTimer.reset(); |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
bool GameConnection::isAlive() const |
| 127 |
{ |
| 128 |
return _engine->isAlive(); |
| 129 |
} |
| 130 |
|
| 131 |
bool GameConnection::connect() |
| 132 |
{ |
| 133 |
if (_engine->isAlive()) |
| 134 |
return true; //good already: don't do anything |
| 135 |
|
| 136 |
if (_engine->hasLostConnection()) |
| 137 |
disconnect(true); //lost connection recently: disable everything |
| 138 |
|
| 139 |
if (!_engine->connect()) |
| 140 |
return false; //failed to connect |
| 141 |
|
| 142 |
setThinkLoop(true); |
| 143 |
|
| 144 |
_mapEventListener = GlobalMapModule().signal_mapEvent().connect( |
| 145 |
sigc::mem_fun(*this, &GameConnection::onMapEvent) |
| 146 |
); |
| 147 |
|
| 148 |
signal_StatusChanged.emit(0); |
| 149 |
|
| 150 |
return true; |
| 151 |
} |
| 152 |
|
| 153 |
void GameConnection::disconnect(bool force) |
| 154 |
{ |
| 155 |
_autoReloadMap = false; |
| 156 |
setAlwaysUpdateMapEnabled(false); |
| 157 |
setUpdateMapObserverEnabled(false); |
| 158 |
setCameraSyncEnabled(false); |
| 159 |
|
| 160 |
_engine->disconnect(force); |
| 161 |
assert(!_engine->isAlive() && !_engine->hasLostConnection()); |
| 162 |
|
| 163 |
setThinkLoop(false); |
| 164 |
_mapEventListener.disconnect(); |
| 165 |
|
| 166 |
signal_StatusChanged.emit(0); |
| 167 |
} |
| 168 |
|
| 169 |
GameConnection::~GameConnection() |
| 170 |
{ |
| 171 |
disconnect(true); |
| 172 |
}; |
| 173 |
|
| 174 |
void GameConnection::restartGame(bool dmap) |
| 175 |
{ |
| 176 |
enum Steps { |
| 177 |
STEP_START, |
| 178 |
STEP_ATTACH, |
| 179 |
STEP_SETMOD, |
| 180 |
STEP_DMAP, |
| 181 |
STEP_SETMAP, |
| 182 |
STEP_INGAME, |
| 183 |
STEP_FINISHED = -1, |
| 184 |
}; |
| 185 |
|
| 186 |
auto implementation = [this, dmap](int step) -> MultistepProcReturn { |
| 187 |
try { |
| 188 |
#ifdef _WIN32 |
| 189 |
static const char *TDM_EXE_NAME = "TheDarkModx64.exe"; |
| 190 |
#else |
| 191 |
static const char *TDM_EXE_NAME = "thedarkmod.x64"; |
| 192 |
#endif |
| 193 |
|
| 194 |
//perhaps it is not the best idea to store state in global/static variables... |
| 195 |
static std::string tdmDir, drModName, drMapName; |
| 196 |
static std::string savedViewPos; |
| 197 |
static bool savedCameraSyncEnabled, savedAutoReloadMapEnabled, savedAlwaysUpdateMapEnabled; |
| 198 |
static wxLongLong timestampStartAttach, timestampLastTry; |
| 199 |
static int pendingSeqno; |
| 200 |
|
| 201 |
if (step == STEP_START) { |
| 202 |
//fetch all settings: mission, map, TDM path |
| 203 |
if (GlobalMapModule().isUnnamed()) |
| 204 |
{ |
| 205 |
radiant::NotificationMessage::SendError("Cannot start TDM because no map file is opened."); |
| 206 |
return {STEP_FINISHED, {}}; |
| 207 |
} |
| 208 |
tdmDir = os::standardPathWithSlash(registry::getValue<std::string>(RKEY_ENGINE_PATH)); |
| 209 |
std::string fullModPath = registry::getValue<std::string>(RKEY_MOD_PATH); |
| 210 |
std::string fullMapPath = GlobalMapModule().getMapName(); |
| 211 |
if (!fullModPath.empty() && strchr("/\\", fullModPath.back())) |
| 212 |
fullModPath.pop_back(); |
| 213 |
drModName = fs::path(fullModPath).filename().string(); |
| 214 |
drMapName = fs::path(fullMapPath).filename().string(); |
| 215 |
|
| 216 |
//save enabled modes |
| 217 |
savedCameraSyncEnabled = isCameraSyncEnabled(); |
| 218 |
savedAutoReloadMapEnabled = isAutoReloadMapEnabled(); |
| 219 |
savedAlwaysUpdateMapEnabled = isAlwaysUpdateMapEnabled(); |
| 220 |
savedViewPos = ""; |
| 221 |
|
| 222 |
if (isAlive()) { |
| 223 |
//save current position |
| 224 |
_engine->waitForTags(TAG_CAMERA); |
| 225 |
savedViewPos = executeGenericRequest(composeConExecRequest("getviewpos")); |
| 226 |
//disable modes |
| 227 |
setCameraSyncEnabled(false); |
| 228 |
setAutoReloadMapEnabled(false); |
| 229 |
setAlwaysUpdateMapEnabled(false); |
| 230 |
setUpdateMapObserverEnabled(false); |
| 231 |
} |
| 232 |
|
| 233 |
//save .map file |
| 234 |
saveMapIfNeeded(); |
| 235 |
|
| 236 |
//try to attach to TDM with automation enabled |
| 237 |
bool attached = connect(); |
| 238 |
|
| 239 |
if (!attached) { |
| 240 |
//run new TDM process |
| 241 |
wxExecuteEnv env; |
| 242 |
env.cwd = tdmDir; |
| 243 |
fs::path exeFullPath = fs::path(tdmDir); |
| 244 |
exeFullPath.concat(TDM_EXE_NAME); |
| 245 |
wxString cmdline = wxString::Format("%s +set com_automation 1", exeFullPath.c_str()); |
| 246 |
long res = wxExecute(cmdline, wxEXEC_ASYNC, nullptr, &env); |
| 247 |
if (res <= 0) { |
| 248 |
radiant::NotificationMessage::SendError("Failed to run TheDarkMod executable."); |
| 249 |
return {STEP_FINISHED, {}}; |
| 250 |
} |
| 251 |
|
| 252 |
timestampStartAttach = wxGetUTCTimeMillis(); |
| 253 |
timestampLastTry = 0; |
| 254 |
return {STEP_ATTACH, {}}; |
| 255 |
} |
| 256 |
|
| 257 |
return {STEP_SETMOD, {}}; |
| 258 |
} |
| 259 |
|
| 260 |
if (step == STEP_ATTACH) { |
| 261 |
//attach to the new process |
| 262 |
static const int TDM_ATTACH_TIMEOUT = 10000; //in milliseconds |
| 263 |
static const int TDM_ATTACH_RETRY = 1000; |
| 264 |
|
| 265 |
wxLongLong timestampNow = wxGetUTCTimeMillis(); |
| 266 |
if (timestampNow - timestampLastTry > TDM_ATTACH_RETRY) { |
| 267 |
timestampLastTry = timestampNow; |
| 268 |
if (connect()) |
| 269 |
return {STEP_SETMOD, {}}; |
| 270 |
} |
| 271 |
if (timestampNow - timestampStartAttach > TDM_ATTACH_TIMEOUT) { |
| 272 |
radiant::NotificationMessage::SendError("Timeout when connecting to just started TheDarkMod process.\n" |
| 273 |
"Make sure the game is in main menu, has com_automation enabled, and firewall does not block it."); |
| 274 |
return {STEP_FINISHED, {}}; |
| 275 |
} |
| 276 |
|
| 277 |
//keep calling this step on every think |
| 278 |
return {STEP_ATTACH, {SEQNO_WAIT_POLL}}; |
| 279 |
} |
| 280 |
|
| 281 |
if (step == STEP_SETMOD) { |
| 282 |
//check the current status |
| 283 |
std::map<std::string, std::string> statusProps = executeQueryStatus(); |
| 284 |
|
| 285 |
if (statusProps["currentfm"] != drModName) { |
| 286 |
//TDM crashes if we restart engine from in-game or immediately after stopping it |
| 287 |
//workaround it by giving it a bit of time after stop |
| 288 |
executeGenericRequest(composeConExecRequest("disconnect")); |
| 289 |
wxMilliSleep(1000); |
| 290 |
|
| 291 |
//change mission/mod and restart TDM engine |
| 292 |
std::string request = actionPreamble("installfm") + "content:\n" + drModName + "\n"; |
| 293 |
pendingSeqno = _engine->executeRequestAsync(TAG_GENERIC, request); |
| 294 |
return {STEP_DMAP, {pendingSeqno}}; |
| 295 |
} |
| 296 |
|
| 297 |
pendingSeqno = 0; |
| 298 |
return {STEP_DMAP, {}}; |
| 299 |
} |
| 300 |
|
| 301 |
if (step == STEP_DMAP) { |
| 302 |
//handle response of mission/mod request |
| 303 |
if (pendingSeqno) { |
| 304 |
std::string response = _engine->getResponse(pendingSeqno); |
| 305 |
if (response != "done") { |
| 306 |
radiant::NotificationMessage::SendError("Failed to change installed mission in TheDarkMod.\n" |
| 307 |
"Make sure ?DR mission? is configured properly and game version is 2.09 or above."); |
| 308 |
return {STEP_FINISHED, {}}; |
| 309 |
} |
| 310 |
} |
| 311 |
//recheck currently installed FM just to be sure |
| 312 |
std::map<std::string, std::string> statusProps = executeQueryStatus(); |
| 313 |
if (statusProps["currentfm"] != drModName) { |
| 314 |
radiant::NotificationMessage::SendError(fmt::format("Installed mission is {} despite trying to change it.", statusProps["currentfm"])); |
| 315 |
return {STEP_FINISHED, {}}; |
| 316 |
} |
| 317 |
|
| 318 |
if (dmap) { |
| 319 |
//run dmap command |
| 320 |
std::string request = composeConExecRequest("dmap " + drMapName); |
| 321 |
pendingSeqno = _engine->executeRequestAsync(TAG_GENERIC, request); |
| 322 |
return {STEP_SETMAP, {pendingSeqno}}; |
| 323 |
} |
| 324 |
pendingSeqno = 0; |
| 325 |
return {STEP_SETMAP, {}}; |
| 326 |
} |
| 327 |
|
| 328 |
if (step == STEP_SETMAP) { |
| 329 |
//handle response of dmap command |
| 330 |
if (pendingSeqno) { |
| 331 |
std::string response = _engine->getResponse(pendingSeqno); |
| 332 |
if (response.find("ERROR:") != std::string::npos) { |
| 333 |
radiant::NotificationMessage::SendError("Dmap printed error.\nPlease look at TheDarkMod console."); |
| 334 |
return {STEP_FINISHED, {}}; |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
//start map |
| 339 |
std::string request = composeConExecRequest("map " + drMapName); |
| 340 |
pendingSeqno = _engine->executeRequestAsync(TAG_GENERIC, request); |
| 341 |
|
| 342 |
return {STEP_INGAME, {pendingSeqno}}; |
| 343 |
} |
| 344 |
|
| 345 |
if (step == STEP_INGAME) { |
| 346 |
//don't care what was written to console while loading map =) |
| 347 |
std::string response = _engine->getResponse(pendingSeqno); |
| 348 |
|
| 349 |
//last check: everything should match! |
| 350 |
std::map<std::string, std::string> statusProps = executeQueryStatus(); |
| 351 |
if (statusProps["currentfm"] != drModName) { |
| 352 |
radiant::NotificationMessage::SendError(fmt::format("Installed mission is still {}.", statusProps["currentfm"])); |
| 353 |
return {STEP_FINISHED, {}}; |
| 354 |
} |
| 355 |
if (statusProps["mapname"] != drMapName) { |
| 356 |
radiant::NotificationMessage::SendError(fmt::format("Active map is {} despite trying to start the map.", statusProps["mapname"])); |
| 357 |
return {STEP_FINISHED, {}}; |
| 358 |
} |
| 359 |
if (statusProps["guiactive"] != "") { |
| 360 |
radiant::NotificationMessage::SendError(fmt::format("GUI {} is active while we expect the game to start", statusProps["guiactive"])); |
| 361 |
return {STEP_FINISHED, {}}; |
| 362 |
} |
| 363 |
|
| 364 |
//confirm player is ready |
| 365 |
std::string waitUntilReady = executeGetCvarValue("tdm_player_wait_until_ready"); |
| 366 |
if (waitUntilReady != "0") { |
| 367 |
//button0 is "attack" button |
| 368 |
//numbers in parens mean: hold for 100 gameplay milliseconds (time is stopped at waiting screen) |
| 369 |
std::string request = actionPreamble("gamectrl") + "content:\n" + "timemode \"game\"\n" + "button0 (1 1 0 0 0 0.1)\n"; |
| 370 |
response = executeGenericRequest(request); |
| 371 |
} |
| 372 |
|
| 373 |
if (!savedViewPos.empty()) { |
| 374 |
//force god/noclip/notarget on |
| 375 |
enableGhostMode(); |
| 376 |
//restore camera position |
| 377 |
std::string request = composeConExecRequest(fmt::format("setviewpos {}", savedViewPos)); |
| 378 |
response = executeGenericRequest(request); |
| 379 |
} |
| 380 |
|
| 381 |
//enable back all the modes |
| 382 |
setCameraSyncEnabled(savedCameraSyncEnabled); |
| 383 |
setAutoReloadMapEnabled(savedAutoReloadMapEnabled); |
| 384 |
//if user has changed something, don't enable "update map" mode to avoid desync |
| 385 |
if (!GlobalMapModule().isModified()) { |
| 386 |
setUpdateMapObserverEnabled(true); |
| 387 |
setAlwaysUpdateMapEnabled(savedAlwaysUpdateMapEnabled); |
| 388 |
} |
| 389 |
|
| 390 |
return {STEP_FINISHED, {}}; |
| 391 |
} |
| 392 |
} |
| 393 |
catch(const DisconnectException&) { |
| 394 |
//connection was lost unexpectedly during some step |
| 395 |
//most likely user has closed TDM while it was still being prepared |
| 396 |
radiant::NotificationMessage::SendError("Game restart failed: connection lost unexpectedly."); |
| 397 |
} |
| 398 |
return {STEP_FINISHED, {}}; |
| 399 |
}; |
| 400 |
|
| 401 |
_engine->executeMultistepProc(TAG_RESTART, implementation, STEP_START); |
| 402 |
|
| 403 |
_restartInProgress = true; |
| 404 |
signal_StatusChanged.emit(0); |
| 405 |
|
| 406 |
//even if TDM is not yet started, we need our engine's think loop |
| 407 |
//because otherwise this multistep procedure won't start |
| 408 |
setThinkLoop(true); |
| 409 |
} |
| 410 |
|
| 411 |
bool GameConnection::isGameRestarting() const |
| 412 |
{ |
| 413 |
return _restartInProgress; |
| 414 |
} |
| 415 |
|
| 416 |
//------------------------------------------------------------- |
| 417 |
|
| 418 |
std::string GameConnection::composeConExecRequest(std::string consoleLine) |
| 419 |
{ |
| 420 |
//remove trailing spaces/EOLs |
| 421 |
while (!consoleLine.empty() && isspace(consoleLine.back())) |
| 422 |
consoleLine.pop_back(); |
| 423 |
return actionPreamble("conexec") + "content:\n" + consoleLine + "\n"; |
| 424 |
} |
| 425 |
|
| 426 |
void GameConnection::executeSetTogglableFlag(const std::string &toggleCommand, bool enable, const std::string &offKeyword) |
| 427 |
{ |
| 428 |
std::string text = composeConExecRequest(toggleCommand); |
| 429 |
int attempt; |
| 430 |
for (attempt = 0; attempt < 2; attempt++) { |
| 431 |
std::string response = executeGenericRequest(text); |
| 432 |
bool isEnabled = (response.find(offKeyword) == std::string::npos); |
| 433 |
if (enable == isEnabled) |
| 434 |
break; |
| 435 |
//wrong state: toggle it again |
| 436 |
} |
| 437 |
assert(attempt < 2); //two toggles not enough?... |
| 438 |
} |
| 439 |
|
| 440 |
std::string GameConnection::executeGetCvarValue(const std::string &cvarName, std::string *defaultValue) |
| 441 |
{ |
| 442 |
std::string text = composeConExecRequest(cvarName); |
| 443 |
std::string response = executeGenericRequest(text); |
| 444 |
|
| 445 |
//parse response (imagine how easy that would be with regex...) |
| 446 |
while (response.size() && isspace(response.back())) |
| 447 |
response.pop_back(); |
| 448 |
std::string expLeft = fmt::format("\"{0}\" is:\"", cvarName); |
| 449 |
std::string expMid = "\" default:\""; |
| 450 |
std::string expRight = "\""; |
| 451 |
int posLeft = response.find(expLeft); |
| 452 |
int posMid = response.find(expMid); |
| 453 |
if (posLeft < 0 || posMid < 0) { |
| 454 |
rError() << fmt::format("ExecuteGetCvarValue: can't parse value of {0}", cvarName); |
| 455 |
return ""; |
| 456 |
} |
| 457 |
int posLeftEnd = posLeft + expLeft.size(); |
| 458 |
int posMidEnd = posMid + expMid.size(); |
| 459 |
int posRight = response.size() - expRight.size(); |
| 460 |
std::string currValue = response.substr(posLeftEnd, posMid - posLeftEnd); |
| 461 |
std::string defValue = response.substr(posMidEnd, posRight - posMidEnd); |
| 462 |
|
| 463 |
//return results |
| 464 |
if (defaultValue) |
| 465 |
*defaultValue = defValue; |
| 466 |
return currValue; |
| 467 |
} |
| 468 |
|
| 469 |
std::map<std::string, std::string> GameConnection::executeQueryStatus() |
| 470 |
{ |
| 471 |
std::string request = queryPreamble("status") + "content:\n"; |
| 472 |
std::string response = executeGenericRequest(request); |
| 473 |
|
| 474 |
std::map<std::string, std::string> statusProps; |
| 475 |
int pos = 0; |
| 476 |
while (1) { |
| 477 |
int eolPos = response.find('\n', pos); |
| 478 |
if (eolPos < 0) |
| 479 |
break; |
| 480 |
int spacePos = response.find(' ', pos); |
| 481 |
if (spacePos >= eolPos) { |
| 482 |
rError() << fmt::format("ExecuteQueryStatus: can't parse response"); |
| 483 |
return {}; |
| 484 |
} |
| 485 |
|
| 486 |
std::string key = response.substr(pos, spacePos - pos); |
| 487 |
std::string value = response.substr((spacePos + 1), eolPos - (spacePos + 1)); |
| 488 |
pos = eolPos + 1; |
| 489 |
statusProps[key] = value; |
| 490 |
} |
| 491 |
|
| 492 |
return statusProps; |
| 493 |
} |
| 494 |
|
| 495 |
void GameConnection::updateCamera() |
| 496 |
{ |
| 497 |
try { |
| 498 |
auto& camera = GlobalCameraManager().getActiveView(); |
| 499 |
|
| 500 |
Vector3 orig = camera.getCameraOrigin(); |
| 501 |
Vector3 angles = camera.getCameraAngles(); |
| 502 |
|
| 503 |
_cameraOutData[0] = orig; |
| 504 |
_cameraOutData[1] = angles; |
| 505 |
//note: the update is not necessarily sent right now |
| 506 |
_cameraOutPending = true; |
| 507 |
} |
| 508 |
catch (const std::runtime_error&) { |
| 509 |
// no camera |
| 510 |
} |
| 511 |
|
| 512 |
think(); |
| 513 |
} |
| 514 |
|
| 515 |
bool GameConnection::sendPendingCameraUpdate() |
| 516 |
{ |
| 517 |
if (_cameraOutPending) { |
| 518 |
std::string text = composeConExecRequest(fmt::format( |
| 519 |
"setviewpos {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f}", |
| 520 |
_cameraOutData[0].x(), _cameraOutData[0].y(), _cameraOutData[0].z(), |
| 521 |
-_cameraOutData[1].x(), _cameraOutData[1].y(), _cameraOutData[1].z() |
| 522 |
)); |
| 523 |
|
| 524 |
_engine->executeRequestAsync(TAG_CAMERA, text); |
| 525 |
_cameraOutPending = false; |
| 526 |
|
| 527 |
return true; |
| 528 |
} |
| 529 |
return false; |
| 530 |
} |
| 531 |
|
| 532 |
void GameConnection::enableGhostMode() |
| 533 |
{ |
| 534 |
executeSetTogglableFlag("god", true, "OFF"); |
| 535 |
executeSetTogglableFlag("noclip", true, "OFF"); |
| 536 |
executeSetTogglableFlag("notarget", true, "OFF"); |
| 537 |
} |
| 538 |
|
| 539 |
void GameConnection::setCameraSyncEnabled(bool enable) |
| 540 |
{ |
| 541 |
try { |
| 542 |
if (!enable) { |
| 543 |
_cameraChangedSignal.disconnect(); |
| 544 |
} |
| 545 |
if (enable) { |
| 546 |
enableGhostMode(); |
| 547 |
|
| 548 |
_cameraChangedSignal.disconnect(); |
| 549 |
_cameraChangedSignal = GlobalCameraManager().signal_cameraChanged().connect( |
| 550 |
sigc::mem_fun(this, &GameConnection::updateCamera) |
| 551 |
); |
| 552 |
|
| 553 |
//sync camera location right now |
| 554 |
updateCamera(); |
| 555 |
_engine->waitForTags(1 << TAG_CAMERA); |
| 556 |
} |
| 557 |
|
| 558 |
signal_StatusChanged.emit(0); |
| 559 |
} |
| 560 |
catch (const DisconnectException&) { |
| 561 |
//disconnected: will be handled during next think |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
bool GameConnection::isCameraSyncEnabled() const |
| 566 |
{ |
| 567 |
return !_cameraChangedSignal.empty(); |
| 568 |
} |
| 569 |
|
| 570 |
void GameConnection::backSyncCamera() |
| 571 |
{ |
| 572 |
try { |
| 573 |
_engine->waitForTags(); |
| 574 |
std::string text = executeGenericRequest(composeConExecRequest("getviewpos")); |
| 575 |
|
| 576 |
Vector3 orig, angles; |
| 577 |
if (sscanf(text.c_str(), "%lf%lf%lf%lf%lf%lf", &orig.x(), &orig.y(), &orig.z(), &angles.x(), &angles.y(), &angles.z()) == 6) { |
| 578 |
try { |
| 579 |
auto& camera = GlobalCameraManager().getActiveView(); |
| 580 |
angles.x() *= -1.0; |
| 581 |
camera.setOriginAndAngles(orig, angles); |
| 582 |
} |
| 583 |
catch (const std::runtime_error&) { |
| 584 |
// no camera view |
| 585 |
} |
| 586 |
} |
| 587 |
} |
| 588 |
catch (const DisconnectException&) { |
| 589 |
//disconnected: will be handled during next think |
| 590 |
return; |
| 591 |
} |
| 592 |
} |
| 593 |
|
| 594 |
void GameConnection::togglePauseGame() |
| 595 |
{ |
| 596 |
try { |
| 597 |
std::string value = executeGetCvarValue("g_stopTime"); |
| 598 |
std::string oppositeValue = (value == "0" ? "1" : "0"); |
| 599 |
std::string text = composeConExecRequest(fmt::format("g_stopTime {}", oppositeValue)); |
| 600 |
executeGenericRequest(text); |
| 601 |
} |
| 602 |
catch (const DisconnectException&) { |
| 603 |
//disconnected: will be handled during next think |
| 604 |
return; |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
void GameConnection::respawnSelectedEntities() |
| 609 |
{ |
| 610 |
try { |
| 611 |
std::set<std::string> selectedEntityNames; |
| 612 |
GlobalSelectionSystem().foreachSelected([&](const scene::INodePtr &node) { |
| 613 |
//Node_isEntity |
| 614 |
if (Entity* entity = Node_getEntity(node)) { |
| 615 |
const std::string &name = entity->getKeyValue("name"); |
| 616 |
if (!name.empty()) { |
| 617 |
selectedEntityNames.insert(name); |
| 618 |
} |
| 619 |
} |
| 620 |
}); |
| 621 |
std::string command; |
| 622 |
for (const std::string &name : selectedEntityNames) |
| 623 |
command += "respawn " + name + "\n"; |
| 624 |
std::string text = composeConExecRequest(command); |
| 625 |
executeGenericRequest(text); |
| 626 |
} |
| 627 |
catch (const DisconnectException&) { |
| 628 |
//disconnected: will be handled during next think |
| 629 |
return; |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
void GameConnection::reloadMap() |
| 634 |
{ |
| 635 |
try { |
| 636 |
std::string text = composeConExecRequest("reloadMap nocheck"); |
| 637 |
executeGenericRequest(text); |
| 638 |
|
| 639 |
if (!GlobalMapModule().isModified()) { |
| 640 |
//TDM has reloaded .map file while we have no local changes |
| 641 |
//it means all three version of the map are in sync |
| 642 |
//so we can enable "update map" mode without fear for confusion |
| 643 |
setUpdateMapObserverEnabled(true); |
| 644 |
} |
| 645 |
else { |
| 646 |
//TDM has reloaded .map file but we have local changes |
| 647 |
//next "update map" will send diff based on our modified version |
| 648 |
//but it will be applied on top of TDM's state (which is different) |
| 649 |
//better disable the mode to avoid confusion! |
| 650 |
setUpdateMapObserverEnabled(false); |
| 651 |
} |
| 652 |
} |
| 653 |
catch (const DisconnectException&) { |
| 654 |
//disconnected: will be handled during next think |
| 655 |
return; |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
void GameConnection::onMapEvent(IMap::MapEvent ev) |
| 660 |
{ |
| 661 |
if (ev == IMap::MapSaved && _autoReloadMap) { |
| 662 |
reloadMap(); |
| 663 |
_mapObserver.clear(); |
| 664 |
} |
| 665 |
if (ev == IMap::MapLoading || ev == IMap::MapUnloading) { |
| 666 |
disconnect(); |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
void GameConnection::setAutoReloadMapEnabled(bool enable) |
| 671 |
{ |
| 672 |
if (enable && !_engine->isAlive()) |
| 673 |
return; |
| 674 |
|
| 675 |
_autoReloadMap = enable; |
| 676 |
signal_StatusChanged.emit(0); |
| 677 |
} |
| 678 |
|
| 679 |
bool GameConnection::isAutoReloadMapEnabled() const |
| 680 |
{ |
| 681 |
return _autoReloadMap; |
| 682 |
} |
| 683 |
|
| 684 |
void GameConnection::saveMapIfNeeded() |
| 685 |
{ |
| 686 |
if (GlobalMapModule().isModified()) |
| 687 |
GlobalCommandSystem().executeCommand("SaveMap"); |
| 688 |
} |
| 689 |
|
| 690 |
bool GameConnection::isUpdateMapObserverEnabled() const |
| 691 |
{ |
| 692 |
return _mapObserver.isEnabled(); |
| 693 |
} |
| 694 |
|
| 695 |
void GameConnection::setUpdateMapObserverEnabled(bool enable) |
| 696 |
{ |
| 697 |
_mapObserver.setEnabled(enable); |
| 698 |
if (!enable) |
| 699 |
setAlwaysUpdateMapEnabled(false); |
| 700 |
|
| 701 |
signal_StatusChanged.emit(0); |
| 702 |
} |
| 703 |
|
| 704 |
void GameConnection::setAlwaysUpdateMapEnabled(bool enable) |
| 705 |
{ |
| 706 |
if (enable) { |
| 707 |
if (!_engine->isAlive()) |
| 708 |
return; |
| 709 |
if (enable) |
| 710 |
setUpdateMapObserverEnabled(true); |
| 711 |
} |
| 712 |
|
| 713 |
_updateMapAlways = enable; |
| 714 |
signal_StatusChanged.emit(0); |
| 715 |
} |
| 716 |
|
| 717 |
bool GameConnection::isAlwaysUpdateMapEnabled() const |
| 718 |
{ |
| 719 |
return _updateMapAlways; |
| 720 |
} |
| 721 |
|
| 722 |
/** |
| 723 |
* stgatilov: Saves only entities with specified names to in-memory map patch. |
| 724 |
* This diff is intended to be consumed by TheDarkMod automation for HotReload purposes. |
| 725 |
* TODO: What about patches and brushes? |
| 726 |
*/ |
| 727 |
std::string saveMapDiff(const DiffEntityStatuses& entityStatuses) |
| 728 |
{ |
| 729 |
auto root = GlobalSceneGraph().root(); |
| 730 |
|
| 731 |
std::set<scene::INode*> subsetNodes; |
| 732 |
root->foreachNode([&](const scene::INodePtr& node) { |
| 733 |
if (entityStatuses.count(node->name())) |
| 734 |
subsetNodes.insert(node.get()); |
| 735 |
return true; |
| 736 |
}); |
| 737 |
|
| 738 |
std::ostringstream outStream; |
| 739 |
outStream << "// diff " << entityStatuses.size() << std::endl; |
| 740 |
|
| 741 |
DiffDoom3MapWriter writer(entityStatuses); |
| 742 |
|
| 743 |
//write removal stubs (no actual spawnargs) |
| 744 |
for (const auto& pNS : entityStatuses) { |
| 745 |
const auto& name = pNS.first; |
| 746 |
const auto& status = pNS.second; |
| 747 |
assert(status.isModified()); //(don't put untouched entities into map) |
| 748 |
if (status.isRemoved()) |
| 749 |
writer.writeRemoveEntityStub(name, outStream); |
| 750 |
} |
| 751 |
|
| 752 |
//write added/modified entities as usual |
| 753 |
{ |
| 754 |
registry::ScopedKeyChanger progressDisabler(RKEY_MAP_SUPPRESS_LOAD_STATUS_DIALOG, true); |
| 755 |
|
| 756 |
// Hack: disable recalculateBrushWindings for this export |
| 757 |
registry::ScopedKeyChanger<std::string> guard("MapExporter_IgnoreBrushes", "yes"); |
| 758 |
|
| 759 |
// Get a scoped exporter class |
| 760 |
auto exporter = GlobalMapModule().createMapExporter(writer, root, outStream); |
| 761 |
|
| 762 |
try |
| 763 |
{ |
| 764 |
// Pass the traversal function and the root of the subgraph to export |
| 765 |
exporter->exportMap(root, scene::traverseSubset(subsetNodes)); |
| 766 |
// end the life of the exporter instance here to finish the scene |
| 767 |
exporter.reset(); |
| 768 |
} |
| 769 |
catch (map::FileOperation::OperationCancelled&) |
| 770 |
{ |
| 771 |
radiant::NotificationMessage::SendInformation(_("Map export cancelled")); |
| 772 |
} |
| 773 |
} |
| 774 |
|
| 775 |
return outStream.str(); |
| 776 |
} |
| 777 |
|
| 778 |
void GameConnection::doUpdateMap() |
| 779 |
{ |
| 780 |
try { |
| 781 |
if (!_engine->isAlive()) |
| 782 |
return; //no connection, don't even try |
| 783 |
|
| 784 |
// Get map diff |
| 785 |
std::string diff = saveMapDiff(_mapObserver.getChanges()); |
| 786 |
if (diff.empty()) { |
| 787 |
return; //TODO: fail |
| 788 |
} |
| 789 |
|
| 790 |
std::string response = executeGenericRequest(actionPreamble("reloadmap-diff") + "content:\n" + diff); |
| 791 |
if (response.find("HotReload: SUCCESS") != std::string::npos) { |
| 792 |
//success: clear current diff, so that we don't reapply it next time |
| 793 |
_mapObserver.clear(); |
| 794 |
} |
| 795 |
} |
| 796 |
catch (const DisconnectException&) { |
| 797 |
//disconnected: will be handled during next think |
| 798 |
return; |
| 799 |
} |
| 800 |
} |
| 801 |
|
| 802 |
//------------------------------------------------------------- |
| 803 |
|
| 804 |
const std::string& GameConnection::getName() const |
| 805 |
{ |
| 806 |
static std::string _name("GameConnection"); |
| 807 |
return _name; |
| 808 |
} |
| 809 |
|
| 810 |
const StringSet& GameConnection::getDependencies() const |
| 811 |
{ |
| 812 |
static StringSet _dependencies { |
| 813 |
MODULE_CAMERA_MANAGER, MODULE_COMMANDSYSTEM, MODULE_MAP, |
| 814 |
MODULE_SCENEGRAPH, MODULE_SELECTIONSYSTEM, MODULE_EVENTMANAGER, |
| 815 |
MODULE_MENUMANAGER, MODULE_USERINTERFACE, MODULE_MAINFRAME |
| 816 |
}; |
| 817 |
return _dependencies; |
| 818 |
} |
| 819 |
|
| 820 |
void GameConnection::initialiseModule(const IApplicationContext& ctx) |
| 821 |
{ |
| 822 |
// Don't add any commands if the hot_reload feature is not enabled by the current Game |
| 823 |
if (!GlobalGameManager().currentGame()->hasFeature("hot_reload")) |
| 824 |
return; |
| 825 |
|
| 826 |
GlobalMenuManager().add("main/map", "GameConnectionPanel", ui::menu::ItemType::Item, _("Game Connection..."), |
| 827 |
"", fmt::format("{0}{1}", ui::TOGGLE_CONTROL_STATEMENT_PREFIX, ui::GameConnectionControl::Name)); |
| 828 |
|
| 829 |
GlobalUserInterface().registerControl(std::make_shared<ui::GameConnectionControl>()); |
| 830 |
|
| 831 |
// Add to mainframe after startup, set control default location |
| 832 |
GlobalMainFrame().signal_MainFrameConstructed().connect([&]() |
| 833 |
{ |
| 834 |
GlobalMainFrame().addControl(ui::GameConnectionControl::Name, { IMainFrame::Location::FloatingWindow, false }); |
| 835 |
}); |
| 836 |
|
| 837 |
// Restart game |
| 838 |
GlobalCommandSystem().addCommand( |
| 839 |
"GameConnectionRestartGame", |
| 840 |
[this](const cmd::ArgumentList& args) |
| 841 |
{ |
| 842 |
bool dmap = false; |
| 843 |
for (int i = 0; i < args.size(); i++) |
| 844 |
if (args[i].getString() == "dmap") |
| 845 |
dmap = true; |
| 846 |
restartGame(dmap); |
| 847 |
} |
| 848 |
); |
| 849 |
|
| 850 |
// Camera sync |
| 851 |
_event_toggleCameraSync = GlobalEventManager().addAdvancedToggle( |
| 852 |
"GameConnectionToggleCameraSync", |
| 853 |
[this](bool v) { |
| 854 |
bool oldEnabled = isCameraSyncEnabled(); |
| 855 |
setCameraSyncEnabled(v); |
| 856 |
return isCameraSyncEnabled() != oldEnabled; |
| 857 |
} |
| 858 |
); |
| 859 |
GlobalCommandSystem().addCommand("GameConnectionBackSyncCamera", |
| 860 |
[this](const cmd::ArgumentList&) { backSyncCamera(); }); |
| 861 |
_event_backSyncCamera = GlobalEventManager().addCommand( |
| 862 |
"GameConnectionBackSyncCamera", "GameConnectionBackSyncCamera", false |
| 863 |
); |
| 864 |
|
| 865 |
// Reload map |
| 866 |
GlobalCommandSystem().addCommand("GameConnectionReloadMap", |
| 867 |
[this](const cmd::ArgumentList&) { reloadMap(); }); |
| 868 |
GlobalEventManager().addAdvancedToggle( |
| 869 |
"GameConnectionToggleAutoMapReload", |
| 870 |
[this](bool v) { |
| 871 |
bool oldEnabled = isAutoReloadMapEnabled(); |
| 872 |
setAutoReloadMapEnabled(v); |
| 873 |
return isAutoReloadMapEnabled() != oldEnabled; |
| 874 |
} |
| 875 |
); |
| 876 |
|
| 877 |
// Update map |
| 878 |
GlobalCommandSystem().addCommand("GameConnectionUpdateMap", |
| 879 |
[this](const cmd::ArgumentList&) { doUpdateMap(); }); |
| 880 |
GlobalEventManager().addAdvancedToggle( |
| 881 |
"GameConnectionToggleAutoMapUpdate", |
| 882 |
[this](bool v) { |
| 883 |
bool oldEnabled = isAlwaysUpdateMapEnabled(); |
| 884 |
setAlwaysUpdateMapEnabled(v); |
| 885 |
return isAlwaysUpdateMapEnabled() != oldEnabled; |
| 886 |
|
| 887 |
} |
| 888 |
); |
| 889 |
|
| 890 |
// Respawn selected |
| 891 |
GlobalCommandSystem().addCommand( |
| 892 |
"GameConnectionRespawnSelected", |
| 893 |
[this](const cmd::ArgumentList&) { respawnSelectedEntities(); } |
| 894 |
); |
| 895 |
|
| 896 |
// Pause game |
| 897 |
GlobalCommandSystem().addCommand("GameConnectionPauseGame", |
| 898 |
[this](const cmd::ArgumentList&) { togglePauseGame(); }); |
| 899 |
|
| 900 |
// Toolbar button(s) |
| 901 |
GlobalMainFrame().signal_MainFrameConstructed().connect( |
| 902 |
sigc::mem_fun(this, &GameConnection::addToolbarItems) |
| 903 |
); |
| 904 |
} |
| 905 |
|
| 906 |
void GameConnection::shutdownModule() |
| 907 |
{ |
| 908 |
disconnect(true); |
| 909 |
} |
| 910 |
|
| 911 |
void GameConnection::addToolbarItems() |
| 912 |
{ |
| 913 |
wxToolBar* camTB = GlobalMainFrame().getToolbar(IMainFrame::Toolbar::CAMERA); |
| 914 |
if (camTB) |
| 915 |
{ |
| 916 |
// Separate GameConnection tools from regular camera tools |
| 917 |
camTB->AddSeparator(); |
| 918 |
|
| 919 |
// Add toggles for the camera sync functions |
| 920 |
auto camSyncT = camTB->AddTool( |
| 921 |
wxID_ANY, "L", wxutil::GetLocalBitmap("CameraSync.png"), |
| 922 |
_("Enable game camera sync with DarkRadiant camera"), |
| 923 |
wxITEM_CHECK |
| 924 |
); |
| 925 |
_event_toggleCameraSync->connectToolItem(camSyncT); |
| 926 |
auto camSyncBackT = camTB->AddTool( |
| 927 |
wxID_ANY, "B", wxutil::GetLocalBitmap("CameraSyncBack.png"), |
| 928 |
_("Move camera to current game position") |
| 929 |
); |
| 930 |
_event_backSyncCamera->connectToolItem(camSyncBackT); |
| 931 |
|
| 932 |
camTB->Realize(); |
| 933 |
} |
| 934 |
} |
| 935 |
|
| 936 |
} |
| 937 |
|
| 938 |
extern "C" void DARKRADIANT_DLLEXPORT RegisterModule(IModuleRegistry& registry) |
| 939 |
{ |
| 940 |
module::performDefaultInitialisation(registry); |
| 941 |
registry.registerModule(std::make_shared<gameconn::GameConnection>()); |
| 942 |
} |