/
GameConnection.cpp
547 lines (478 loc) · 17.1 KB
/
GameConnection.cpp
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
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
#include "GameConnection.h"
#include "MessageTcp.h"
#include "DiffStatus.h"
#include "DiffDoom3MapWriter.h"
#include "clsocket/ActiveSocket.h"
#include "i18n.h"
#include "icameraview.h"
#include "inode.h"
#include "ientity.h"
#include "iselection.h"
#include "iuimanager.h"
#include "ieventmanager.h"
#include "idialogmanager.h"
#include "scene/Traverse.h"
#include <sigc++/signal.h>
#include <sigc++/connection.h>
namespace gameconn
{
namespace
{
//this is how often this class "thinks" when idle
const int THINK_INTERVAL = 123;
const char* const DEFAULT_HOST = "localhost";
const int DEFAULT_PORT = 3879;
inline std::string seqnoPreamble(std::size_t seq) {
return fmt::format("seqno {0}\n", seq);
}
inline std::string messagePreamble(const std::string& type) {
return fmt::format("message \"{}\"\n", type);
}
inline std::string actionPreamble(const std::string& type) {
return messagePreamble("action") + fmt::format("action \"{0}\"\n", type);
}
#if 0
inline std::string queryPreamble(std::string type) {
return messagePreamble("query") + fmt::format("query \"{}\"\n", type);
}
#endif
}
std::size_t GameConnection::generateNewSequenceNumber() {
return ++_seqno;
}
void GameConnection::sendRequest(const std::string &request) {
if (!isAlive())
return; //connection is down, drop all requests
assert(_seqnoInProgress == 0);
auto seqno = generateNewSequenceNumber();
std::string fullMessage = seqnoPreamble(seqno) + request;
_connection->writeMessage(fullMessage.data(), fullMessage.size());
_seqnoInProgress = seqno;
}
bool GameConnection::sendAnyPendingAsync() {
if (_mapObserver.getChanges().size() && _updateMapAlways) {
//note: this is blocking
doUpdateMap();
return true;
}
return sendPendingCameraUpdate();
}
void GameConnection::think() {
if (!_connection)
return; //everything disabled, so just don't do anything
_connection->think();
if (_seqnoInProgress) {
//check if full response is here
if (_connection->readMessage(_response)) {
//validate and remove preamble
int responseSeqno, lineLen;
int ret = sscanf(_response.data(), "response %d\n%n", &responseSeqno, &lineLen);
assert(ret == 1);
assert(static_cast<std::size_t>(responseSeqno) == _seqnoInProgress);
_response.erase(_response.begin(), _response.begin() + lineLen);
//mark request as "no longer in progress"
//note: response can be used in outer function
_seqnoInProgress = 0;
}
}
else {
//doing nothing now: send async command if present
sendAnyPendingAsync();
}
_connection->think();
if (!_connection->isAlive()) {
//just lost connection: disable everything
disconnect(true);
}
}
void GameConnection::waitAction() {
while (_seqnoInProgress)
think();
}
void GameConnection::finish()
{
do
{
//wait for current request in progress to finish
waitAction();
//send pending async commands and wait for them to finish
} while (sendAnyPendingAsync());
}
std::string GameConnection::executeRequest(const std::string &request) {
//make sure current request is finished (if any)
waitAction();
assert(_seqnoInProgress == 0);
//prepend seqno line and send message
sendRequest(request);
//wait until response is ready
waitAction();
return std::string(_response.begin(), _response.end());
}
bool GameConnection::isAlive() const {
return _connection && _connection->isAlive();
}
namespace
{
void showError(const std::string& text)
{
auto dlg = GlobalDialogManager().createMessageBox(
_("Game connection error"), text, ui::IDialog::MESSAGE_ERROR
);
if (dlg)
dlg->run();
}
}
bool GameConnection::connect() {
if (isAlive())
return true; //already connected
if (_connection) {
//connection recently lost: disable everything
disconnect(true);
assert(!_connection);
}
// Make connection using clsocket
// TODO: make port configurable, as it is in TDM?
std::unique_ptr<CActiveSocket> connection(new CActiveSocket());
if (!connection->Initialize()
|| !connection->SetNonblocking()
|| !connection->Open(DEFAULT_HOST, DEFAULT_PORT))
{
showError(_("Failed to connect to game process"));
return false;
}
_connection.reset(new MessageTcp());
_connection->init(std::move(connection));
if (!_connection->isAlive())
{
showError(_("Failed to connect to game process"));
return false;
}
_thinkTimer.reset(new wxTimer());
_thinkTimer->Bind(wxEVT_TIMER, &GameConnection::onTimerEvent, this);
_thinkTimer->Start(THINK_INTERVAL);
_mapEventListener = GlobalMapModule().signal_mapEvent().connect(
sigc::mem_fun(*this, &GameConnection::onMapEvent)
);
return true;
}
void GameConnection::disconnect(bool force) {
setAutoReloadMapEnabled(false);
setUpdateMapLevel(false, false);
setCameraSyncEnabled(false);
if (force) {
//drop everything pending
_seqnoInProgress = 0;
_mapObserver.clear();
_cameraOutPending = false;
}
else {
//try to finish all pending
finish();
}
if (_connection)
_connection.reset();
if (_thinkTimer) {
_thinkTimer->Stop();
_thinkTimer.reset();
}
_mapEventListener.disconnect();
}
GameConnection::~GameConnection() {
disconnect(true);
};
//-------------------------------------------------------------
const std::string& GameConnection::getName() const
{
static std::string _name("GameConnection");
return _name;
}
const StringSet& GameConnection::getDependencies() const
{
static StringSet _dependencies {
MODULE_CAMERA_MANAGER, MODULE_COMMANDSYSTEM, MODULE_MAP, MODULE_SCENEGRAPH,
MODULE_SELECTIONSYSTEM, MODULE_EVENTMANAGER, MODULE_UIMANAGER
};
return _dependencies;
}
void GameConnection::initialiseModule(const IApplicationContext& ctx)
{
// Construct toggles
GlobalEventManager().addAdvancedToggle(
"GameConnectionToggleCameraSync",
[this](bool v) { return setCameraSyncEnabled(v); }
);
GlobalEventManager().addToggle(
"GameConnectionToggleAutoMapReload",
[this](bool v) { setAutoReloadMapEnabled(v); }
);
GlobalEventManager().addToggle(
"GameConnectionToggleHotReload",
[this](bool v) { setUpdateMapLevel(v, false); }
);
GlobalEventManager().addToggle(
"GameConnectionToggleHotReloadAlways",
[this](bool v) { setUpdateMapLevel(true, v); }
);
// Add commands
GlobalCommandSystem().addCommand("GameConnectionBackSyncCamera",
[this](const cmd::ArgumentList&) { backSyncCamera(); });
GlobalCommandSystem().addCommand("GameConnectionReloadMap",
[this](const cmd::ArgumentList&) { reloadMap(); });
GlobalCommandSystem().addCommand("GameConnectionUpdateMap",
[this](const cmd::ArgumentList&) { doUpdateMap(); });
GlobalCommandSystem().addCommand("GameConnectionPauseGame",
[this](const cmd::ArgumentList&) { togglePauseGame(); });
GlobalCommandSystem().addCommand("GameConnectionRespawnSelected",
[this](const cmd::ArgumentList&) { respawnSelectedEntities(); });
// Add menu items
IMenuManager& mm = GlobalUIManager().getMenuManager();
mm.insert("main/help", "connection", ui::menuFolder, _("Connection"), "", "");
mm.add("main/connection", "cameraSyncEnable", ui::menuItem,
_("Game position follows DarkRadiant camera"), "", "GameConnectionToggleCameraSync");
mm.add("main/connection", "backSyncCamera", ui::menuItem,
_("Move camera to current game position"), "", "GameConnectionBackSyncCamera");
mm.add("main/connection", "postCameraSep", ui::menuSeparator);
mm.add("main/connection", "reloadMapAutoEnable", ui::menuItem,
_("Game reloads .map file on save"), "", "GameConnectionToggleAutoMapReload");
mm.add("main/connection", "reloadMap", ui::menuItem,
_("Tell game to reload .map file now"), "", "GameConnectionReloadMap");
mm.add("main/connection", "postMapFileSep", ui::menuSeparator);
mm.add("main/connection", "updateMapOff", ui::menuItem,
_("Enable hot reload of unsaved map changes"), "", "GameConnectionToggleHotReload");
mm.add("main/connection", "updateMapAlways", ui::menuItem,
_("Hot reload after every change"), "", "GameConnectionToggleHotReloadAlways");
mm.add("main/connection", "updateMap", ui::menuItem,
_("Update map right now"), "", "GameConnectionUpdateMap");
mm.add("main/connection", "postHotReloadSep", ui::menuSeparator);
mm.add("main/connection", "pauseGame", ui::menuItem,
_("Pause game"), "", "GameConnectionPauseGame");
mm.add("main/connection", "respawnSelected", ui::menuItem,
_("Respawn selected entities"), "", "GameConnectionRespawnSelected");
}
void GameConnection::shutdownModule()
{
disconnect(true);
}
//-------------------------------------------------------------
std::string GameConnection::composeConExecRequest(std::string consoleLine) {
//remove trailing spaces/EOLs
while (!consoleLine.empty() && isspace(consoleLine.back()))
consoleLine.pop_back();
return actionPreamble("conexec") + "content:\n" + consoleLine + "\n";
}
void GameConnection::executeSetTogglableFlag(const std::string &toggleCommand, bool enable, const std::string &offKeyword) {
if (!connect())
return;
std::string text = composeConExecRequest(toggleCommand);
int attempt;
for (attempt = 0; attempt < 2; attempt++) {
std::string response = executeRequest(text);
bool isEnabled = (response.find(offKeyword) == std::string::npos);
if (enable == isEnabled)
break;
//wrong state: toggle it again
}
assert(attempt < 2); //two toggles not enough?...
}
std::string GameConnection::executeGetCvarValue(const std::string &cvarName, std::string *defaultValue) {
if (!connect())
return "";
std::string text = composeConExecRequest(cvarName);
std::string response = executeRequest(text);
//parse response (imagine how easy that would be with regex...)
while (response.size() && isspace(response.back()))
response.pop_back();
std::string expLeft = fmt::format("\"{0}\" is:\"", cvarName);
std::string expMid = "\" default:\"";
std::string expRight = "\"";
int posLeft = response.find(expLeft);
int posMid = response.find(expMid);
if (posLeft < 0 || posMid < 0) {
rError() << fmt::format("ExecuteGetCvarValue: can't parse value of {0}", cvarName);
return "";
}
int posLeftEnd = posLeft + expLeft.size();
int posMidEnd = posMid + expMid.size();
int posRight = response.size() - expRight.size();
std::string currValue = response.substr(posLeftEnd, posMid - posLeftEnd);
std::string defValue = response.substr(posMidEnd, posRight - posMidEnd);
//return results
if (defaultValue)
*defaultValue = defValue;
return currValue;
}
void GameConnection::updateCamera() {
connect();
try
{
auto& camera = GlobalCameraManager().getActiveView();
auto& orig = camera.getCameraOrigin();
auto& angles = camera.getCameraAngles();
_cameraOutData[0] = orig;
_cameraOutData[1] = angles;
//note: the update is not necessarily sent right now
_cameraOutPending = true;
}
catch (const std::runtime_error&)
{
// no camera
}
think();
}
bool GameConnection::sendPendingCameraUpdate() {
if (_cameraOutPending) {
std::string text = composeConExecRequest(fmt::format(
"setviewpos {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f} {:0.3f}",
_cameraOutData[0].x(), _cameraOutData[0].y(), _cameraOutData[0].z(),
-_cameraOutData[1].x(), _cameraOutData[1].y(), _cameraOutData[1].z()
));
sendRequest(text);
_cameraOutPending = false;
return true;
}
return false;
}
bool GameConnection::setCameraSyncEnabled(bool enable)
{
if (!enable) {
_cameraChangedSignal.disconnect();
}
if (enable) {
if (!connect())
return false;
_cameraChangedSignal.disconnect();
_cameraChangedSignal = GlobalCameraManager().signal_cameraChanged().connect(
sigc::mem_fun(this, &GameConnection::updateCamera)
);
executeSetTogglableFlag("god", true, "OFF");
executeSetTogglableFlag("noclip", true, "OFF");
executeSetTogglableFlag("notarget", true, "OFF");
//sync camera location right now
updateCamera();
finish();
}
return true;
}
void GameConnection::backSyncCamera() {
if (!connect())
return;
std::string text = executeRequest(composeConExecRequest("getviewpos"));
Vector3 orig, angles;
if (sscanf(text.c_str(), "%lf%lf%lf%lf%lf%lf", &orig.x(), &orig.y(), &orig.z(), &angles.x(), &angles.y(), &angles.z()) == 6) {
try
{
auto& camera = GlobalCameraManager().getActiveView();
angles.x() *= -1.0;
camera.setOriginAndAngles(orig, angles);
}
catch (const std::runtime_error&)
{
// no camera view
}
}
}
void GameConnection::togglePauseGame() {
if (!connect())
return;
std::string value = executeGetCvarValue("g_stopTime");
std::string oppositeValue = (value == "0" ? "1" : "0");
std::string text = composeConExecRequest(fmt::format("g_stopTime {}", oppositeValue));
executeRequest(text);
}
void GameConnection::respawnSelectedEntities() {
if (!connect())
return;
std::set<std::string> selectedEntityNames;
GlobalSelectionSystem().foreachSelected([&](const scene::INodePtr &node) {
//Node_isEntity
if (Entity* entity = Node_getEntity(node)) {
const std::string &name = entity->getKeyValue("name");
if (!name.empty()) {
selectedEntityNames.insert(name);
}
}
});
std::string command;
for (const std::string &name : selectedEntityNames)
command += "respawn " + name + "\n";
std::string text = composeConExecRequest(command);
executeRequest(text);
}
void GameConnection::reloadMap() {
if (!connect())
return;
std::string text = composeConExecRequest("reloadMap nocheck");
executeRequest(text);
}
void GameConnection::onMapEvent(IMap::MapEvent ev) {
if (ev == IMap::MapSaved && _autoReloadMap) {
reloadMap();
_mapObserver.clear();
}
if (ev == IMap::MapLoading || ev == IMap::MapUnloading) {
disconnect();
}
}
void GameConnection::setAutoReloadMapEnabled(bool enable) {
_autoReloadMap = enable;
}
void GameConnection::setUpdateMapLevel(bool on, bool always) {
if (on && !_mapObserver.isEnabled()) {
//save map to file, and reload from file, to ensure DR and TDM are in sync
GlobalCommandSystem().executeCommand("SaveMap");
reloadMap();
}
_mapObserver.setEnabled(on);
_updateMapAlways = always;
}
/**
* stgatilov: Saves only entities with specified names to in-memory map patch.
* This diff is intended to be consumed by TheDarkMod automation for HotReload purposes.
* TODO: What about patches and brushes?
*/
std::string saveMapDiff(const DiffEntityStatuses& entityStatuses)
{
auto root = GlobalSceneGraph().root();
std::set<scene::INode*> subsetNodes;
root->foreachNode([&](const scene::INodePtr& node) {
if (entityStatuses.count(node->name()))
subsetNodes.insert(node.get());
return true;
});
std::ostringstream outStream;
outStream << "// diff " << entityStatuses.size() << std::endl;
DiffDoom3MapWriter writer(entityStatuses);
//write removal stubs (no actual spawnargs)
for (const auto& pNS : entityStatuses) {
const auto& name = pNS.first;
const auto& status = pNS.second;
assert(status.isModified()); //(don't put untouched entities into map)
if (status.isRemoved())
writer.writeRemoveEntityStub(name, outStream);
}
//write added/modified entities as usual
{
// Get a scoped exporter class
auto exporter = GlobalMapModule().createMapExporter(writer, root, outStream);
exporter->exportMap(root, scene::traverseSubset(subsetNodes));
// end the life of the exporter instance here to finish the scene
}
return outStream.str();
}
void GameConnection::doUpdateMap() {
if (!connect())
return;
std::string diff = saveMapDiff(_mapObserver.getChanges());
if (diff.empty()) {
return; //TODO: fail
}
std::string response = executeRequest(actionPreamble("reloadmap-diff") + "content:\n" + diff);
if (response.find("HotReload: SUCCESS") != std::string::npos)
_mapObserver.clear();
}
}
extern "C" void DARKRADIANT_DLLEXPORT RegisterModule(IModuleRegistry& registry)
{
module::performDefaultInitialisation(registry);
registry.registerModule(std::make_shared<gameconn::GameConnection>());
}