-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathMQ2Navigation.cpp
More file actions
2169 lines (1764 loc) · 50.9 KB
/
MQ2Navigation.cpp
File metadata and controls
2169 lines (1764 loc) · 50.9 KB
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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// MQ2Navigation.cpp
//
#include "pch.h"
#include "MQ2Navigation.h"
#include "common/Logging.h"
#include "common/NavMesh.h"
#include "plugin/KeybindHandler.h"
#include "plugin/ModelLoader.h"
#include "plugin/PluginSettings.h"
#include "plugin/NavigationPath.h"
#include "plugin/NavigationType.h"
#include "plugin/NavMeshLoader.h"
#include "plugin/NavMeshRenderer.h"
#include "plugin/RenderHandler.h"
#include "plugin/SwitchHandler.h"
#include "plugin/MeshgenHandler.h"
#include "plugin/UiController.h"
#include "plugin/Utilities.h"
#include "plugin/Waypoints.h"
#include "imgui/ImGuiUtils.h"
#include "imgui/fonts/IconsFontAwesome.h"
#include <fmt/format.h>
#include <glm/gtc/constants.hpp>
#include <glm/gtx/norm.hpp>
#include <glm/trigonometric.hpp>
#include <imgui.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/msvc_sink.h>
#include <chrono>
#include <set>
using namespace std::chrono_literals;
//============================================================================
RenderHandler* g_renderHandler = nullptr;
ImGuiRenderer* g_imguiRenderer = nullptr;
enum MOVEMENT_DIR
{
GO_FORWARD = 1,
GO_BACKWARD,
GO_LEFT,
GO_RIGHT,
APPLY_TO_ALL,
};
void TrueMoveOn(MOVEMENT_DIR ucDirection)
{
switch (ucDirection)
{
case GO_FORWARD:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_BACK] = 0;
pEverQuestInfo->keyDown[CMD_BACK] = 0;
pKeypressHandler->CommandState[CMD_FORWARD] = 1;
pEverQuestInfo->keyDown[CMD_FORWARD]= 1;
break;
case GO_BACKWARD:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_FORWARD] = 0;
pEverQuestInfo->keyDown[CMD_FORWARD] = 0;
pKeypressHandler->CommandState[CMD_BACK] = 1;
pEverQuestInfo->keyDown[CMD_BACK] = 1;
break;
case GO_LEFT:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_STRAFE_RIGHT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_RIGHT] = 0;
pKeypressHandler->CommandState[CMD_STRAFE_LEFT] = 1;
pEverQuestInfo->keyDown[CMD_STRAFE_LEFT] = 1;
break;
case GO_RIGHT:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_STRAFE_LEFT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_LEFT] = 0;
pKeypressHandler->CommandState[CMD_STRAFE_RIGHT] = 1;
pEverQuestInfo->keyDown[CMD_STRAFE_RIGHT] = 1;
break;
}
};
void TrueMoveOff(MOVEMENT_DIR ucDirection)
{
switch (ucDirection)
{
case APPLY_TO_ALL:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_STRAFE_LEFT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_LEFT] = 0;
pKeypressHandler->CommandState[CMD_STRAFE_RIGHT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_RIGHT] = 0;
pKeypressHandler->CommandState[CMD_FORWARD] = 0;
pEverQuestInfo->keyDown[CMD_FORWARD] = 0;
pKeypressHandler->CommandState[CMD_BACK] = 0;
pEverQuestInfo->keyDown[CMD_BACK] = 0;
break;
case GO_FORWARD:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_FORWARD] = 0;
pEverQuestInfo->keyDown[CMD_FORWARD] = 0;
break;
case GO_BACKWARD:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_BACK] = 0;
pEverQuestInfo->keyDown[CMD_BACK] = 0;
break;
case GO_LEFT:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_STRAFE_LEFT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_LEFT] = 0;
break;
case GO_RIGHT:
pKeypressHandler->CommandState[CMD_AUTORUN] = 0;
pEverQuestInfo->AutoRun = 0;
pKeypressHandler->CommandState[CMD_STRAFE_RIGHT] = 0;
pEverQuestInfo->keyDown[CMD_STRAFE_RIGHT] = 0;
break;
}
};
//============================================================================
static void NavigateCommand(PSPAWNINFO pChar, PCHAR szLine)
{
if (g_mq2Nav)
{
g_mq2Nav->Command_Navigate(szLine);
}
}
static void ClickSwitch(CVector3 pos, EQSwitch* pSwitch)
{
pSwitch->UseSwitch(GetCharInfo()->pSpawn->SpawnID, 0xFFFFFFFF, 0, nullptr);
}
void ClickDoor(EQSwitch* pSwitch)
{
CVector3 click;
click.Y = pSwitch->X;
click.X = pSwitch->Y;
click.Z = pSwitch->Z;
ClickSwitch(click, pSwitch);
}
glm::vec3 GetSpawnPosition(PSPAWNINFO pSpawn)
{
if (pSpawn)
{
bool use_floor_height = nav::GetSettings().use_spawn_floor_height;
return glm::vec3{ pSpawn->X, pSpawn->Y, use_floor_height ? pSpawn->FloorHeight : pSpawn->Z };
}
return glm::vec3{};
}
glm::vec3 GetMyPosition()
{
if (PSPAWNINFO pSpawn = (PSPAWNINFO)pLocalPlayer)
{
return GetSpawnPosition(pSpawn);
}
return {};
}
float GetMyVelocity()
{
if (PSPAWNINFO pSpawn = (PSPAWNINFO)pLocalPlayer)
{
glm::vec3 veloXYZ = {
pSpawn->SpeedX,
pSpawn->SpeedY,
pSpawn->SpeedZ
};
return glm::length(veloXYZ) * 20.0f;
}
return 0.0f;
}
class WriteChatSink : public spdlog::sinks::base_sink<spdlog::details::null_mutex>
{
public:
void set_enabled(bool enabled) { enabled_ = enabled; }
bool enabled() const { return enabled_; }
protected:
void sink_it_(const spdlog::details::log_msg& msg) override
{
if (!enabled_)
return;
using namespace spdlog;
fmt::memory_buffer formatted;
switch (msg.level)
{
case level::critical:
case level::err:
fmt::format_to(fmt::appender(formatted), PLUGIN_MSG_LOG("\ar") "{}", msg.payload);
break;
case level::trace:
case level::debug:
fmt::format_to(fmt::appender(formatted), PLUGIN_MSG_LOG("\a#7f7f7f") "{}", msg.payload);
break;
case level::warn:
fmt::format_to(fmt::appender(formatted), PLUGIN_MSG_LOG("\ay") "{}", msg.payload);
break;
case level::info:
default:
fmt::format_to(fmt::appender(formatted), PLUGIN_MSG_LOG("\ag") "{}", msg.payload);
break;
}
WriteChatf("%s", fmt::to_string(formatted).c_str());
}
void flush_() override {}
bool enabled_ = true;
};
spdlog::level::level_enum ExtractLogLevel(std::string_view input,
spdlog::level::level_enum defaultLevel)
{
auto pos = input.find("log=");
if (pos == std::string_view::npos)
return defaultLevel;
pos += 4;
auto end = input.find_first_of(" \t\r\n", pos);
std::string_view fragment = input.substr(pos, (end == std::string_view::npos) ? end : end - pos);
int level = 0;
for (const auto& level_str : spdlog::level::level_string_views)
{
if (level_str == fragment)
return static_cast<spdlog::level::level_enum>(level);
level++;
}
return defaultLevel;
}
//============================================================================
class NavAPIImpl : public nav::NavAPI
{
public:
NavAPIImpl(MQ2NavigationPlugin* plugin)
: m_plugin(plugin)
{
}
virtual ~NavAPIImpl()
{
}
virtual bool IsInitialized() override
{
return m_plugin->IsInitialized();
}
virtual bool IsNavMeshLoaded() override
{
return m_plugin->IsMeshLoaded();
}
virtual bool IsNavPathActive() override
{
return m_plugin->IsActive();
}
virtual bool IsNavPathPaused() override
{
return m_plugin->IsPaused();
}
virtual bool IsDestinationReachable(std::string_view destination) override
{
return m_plugin->IsInitialized() && m_plugin->CanNavigateToPoint(destination);
}
virtual float GetPathLength(std::string_view destination) override
{
if (m_plugin->IsInitialized())
return m_plugin->GetNavigationPathLength(destination);
return -1.0f;
}
virtual bool ExecuteNavCommand(std::string_view command) override
{
if (m_plugin->IsInitialized())
{
m_plugin->Command_Navigate(command);
return true;
}
return false;
}
virtual const nav::NavCommandState* GetNavCommandState() override
{
if (m_plugin->IsInitialized())
return m_plugin->GetCurrentCommandState();
return nullptr;
}
virtual int RegisterNavObserver(nav::fObserverCallback callback, void* userData) override
{
int observerId = m_nextObserverId++;
ObserverRecord record;
record.callback = callback;
record.userData = userData;
record.observerId = observerId;
observerRecords.push_back(record);
return observerId;
}
virtual void UnregisterNavObserver(int observerId) override
{
observerRecords.erase(
std::remove_if(
observerRecords.begin(), observerRecords.end(),
[observerId](const ObserverRecord& rec) { return rec.observerId == observerId; }),
observerRecords.end());
}
//============================================================================
void DispatchObserverEvent(nav::NavObserverEvent event, nav::NavCommandState* state)
{
for (const ObserverRecord& record : observerRecords)
{
record.callback(event, *state, record.userData);
}
}
private:
MQ2NavigationPlugin* m_plugin;
int m_nextObserverId = 1;
struct ObserverRecord
{
nav::fObserverCallback callback;
void* userData;
int observerId;
};
std::vector<ObserverRecord> observerRecords;
};
NavAPIImpl* s_navAPIImpl = nullptr;
nav::NavAPI* GetNavAPI()
{
return s_navAPIImpl;
}
void UpdateCommandState(nav::NavCommandState* state, const DestinationInfo& destinationInfo)
{
state->command = destinationInfo.command;
state->destination = destinationInfo.eqDestinationPos;
state->paused = false;
state->type = destinationInfo.type;
state->options = destinationInfo.options;
state->tag = destinationInfo.tag;
}
//============================================================================
#pragma region MQ2Navigation Plugin Class
MQ2NavigationPlugin::MQ2NavigationPlugin()
{
s_navAPIImpl = new NavAPIImpl(this);
m_currentCommandState = std::make_unique<nav::NavCommandState>();
std::string logFile = std::string(gPathLogs) + "\\MQ2Nav.log";
// set up default logger
auto logger = spdlog::create<spdlog::sinks::basic_file_sink_mt>("MQ2Nav", logFile, true);
m_chatSink = std::make_shared<WriteChatSink>();
m_chatSink->set_level(spdlog::level::info);
logger->sinks().push_back(m_chatSink);
#if defined(_DEBUG)
logger->sinks().push_back(std::make_shared<spdlog::sinks::msvc_sink_mt>());
#endif
spdlog::set_default_logger(logger);
spdlog::set_pattern("%L %Y-%m-%d %T.%f [%n] %v (%@)");
spdlog::flush_on(spdlog::level::debug);
}
MQ2NavigationPlugin::~MQ2NavigationPlugin()
{
delete s_navAPIImpl;
s_navAPIImpl = nullptr;
}
void MQ2NavigationPlugin::Plugin_OnPulse()
{
if (!m_initialized)
{
return;
}
for (const auto& m : m_modules)
{
m.second->OnPulse();
}
if (m_initialized && nav::ValidIngame(true))
{
AttemptMovement();
StuckCheck();
}
}
void MQ2NavigationPlugin::Plugin_OnBeginZone()
{
if (!m_initialized)
return;
// stop active path if one exists
ResetPath();
UpdateCurrentZone();
for (const auto& m : m_modules)
{
m.second->OnBeginZone();
}
}
void MQ2NavigationPlugin::Plugin_OnEndZone()
{
if (!m_initialized)
return;
for (const auto& m : m_modules)
{
m.second->OnEndZone();
}
pSwitchTarget = nullptr;
mq::ClearGroundSpawn();
}
void MQ2NavigationPlugin::Plugin_SetGameState(DWORD GameState)
{
if (!m_initialized)
{
return;
}
if (GameState == GAMESTATE_INGAME) {
UpdateCurrentZone();
}
else if (GameState == GAMESTATE_CHARSELECT) {
SetCurrentZone(-1);
}
for (const auto& m : m_modules)
{
m.second->SetGameState(GameState);
}
}
void MQ2NavigationPlugin::Plugin_OnAddGroundItem(PGROUNDITEM pGroundItem)
{
}
void MQ2NavigationPlugin::Plugin_OnRemoveGroundItem(PGROUNDITEM pGroundItem)
{
// if the item we targetted for navigation has been removed, clear it out
if (m_endingGround == pGroundItem)
{
m_endingGround.Reset();
if (m_isActive)
{
auto info = m_activePath->GetDestinationInfo();
if (info->groundItem == pGroundItem)
{
info->groundItem = {};
}
}
}
}
void MQ2NavigationPlugin::Plugin_OnAddSpawn(PSPAWNINFO pSpawn)
{
}
void MQ2NavigationPlugin::Plugin_OnRemoveSpawn(PSPAWNINFO pSpawn)
{
// if the spawn is the current destination target we should clear i.t
if (m_isActive)
{
auto info = m_activePath->GetDestinationInfo();
if (info->pSpawn == pSpawn)
{
info->pSpawn = nullptr;
}
}
}
void MQ2NavigationPlugin::Plugin_OnUpdateImGui()
{
if (!m_initialized)
return;
if (auto ui = Get<UiController>())
{
ui->PerformUpdateUI();
}
}
void MQ2NavigationPlugin::Plugin_Initialize()
{
if (m_initialized)
return;
nav::LoadSettings();
g_renderHandler = new RenderHandler();
AddModule<KeybindHandler>();
NavMesh* mesh = AddModule<NavMesh>(GetDataDirectory());
AddModule<NavMeshLoader>(mesh);
AddModule<ModelLoader>();
AddModule<NavMeshRenderer>();
AddModule<UiController>();
AddModule<SwitchHandler>();
AddModule<MeshgenHandler>();
for (const auto& m : m_modules)
{
m.second->Initialize();
}
// get the keybind handler and connect it to our keypress handler
auto keybindHandler = Get<KeybindHandler>();
m_keypressConn = keybindHandler->OnMovementKeyPressed.Connect(
[this]() { OnMovementKeyPressed(); });
// initialize mesh loader's settings
auto meshLoader = Get<NavMeshLoader>();
meshLoader->SetAutoReload(nav::GetSettings().autoreload);
m_initialized = true;
Plugin_SetGameState(gGameState);
AddCommand("/navigate", NavigateCommand);
AddSettingsPanel("plugins/Nav", MQCallback_NavSettingsPanel);
InitializeMQ2NavMacroData();
auto ui = Get<UiController>();
m_updateTabConn = ui->OnTabUpdate.Connect([=](TabPage page) { OnUpdateTab(page); });
m_mapLine = std::make_shared<NavigationMapLine>();
m_gameLine = std::make_shared<NavigationLine>();
g_renderHandler->AddRenderable(m_gameLine.get());
MQRenderCallbacks callbacks;
callbacks.CreateDeviceObjects = MQCallback_CreateDeviceObjects;
callbacks.InvalidateDeviceObjects = MQCallback_InvalidateDeviceObjects;
callbacks.GraphicsSceneRender = MQCallback_GraphicsSceneRender;
m_renderCallbacks = AddRenderCallbacks(callbacks);
}
void MQ2NavigationPlugin::MQCallback_CreateDeviceObjects()
{
if (g_renderHandler)
{
g_renderHandler->CreateDeviceObjects();
}
}
void MQ2NavigationPlugin::MQCallback_InvalidateDeviceObjects()
{
if (g_renderHandler)
{
g_renderHandler->InvalidateDeviceObjects();
}
}
void MQ2NavigationPlugin::MQCallback_GraphicsSceneRender()
{
if (g_renderHandler)
{
g_renderHandler->PerformRender();
}
}
void MQ2NavigationPlugin::MQCallback_NavSettingsPanel()
{
if (g_mq2Nav)
{
g_mq2Nav->DrawNavSettingsPanel();
}
}
void MQ2NavigationPlugin::DrawNavSettingsPanel()
{
if (auto ui = Get<UiController>())
{
ui->DrawNavSettingsPanel();
}
}
void MQ2NavigationPlugin::Plugin_Shutdown()
{
if (!m_initialized)
return;
RemoveRenderCallbacks(m_renderCallbacks);
RemoveSettingsPanel("plugins/Nav");
RemoveCommand("/navigate");
ShutdownMQ2NavMacroData();
g_renderHandler->RemoveRenderable(m_gameLine.get());
Stop(false);
// shut down all of the modules
for (const auto& m : m_modules)
{
m.second->Shutdown();
}
// delete all of the modules
m_modules.clear();
g_renderHandler->Shutdown();
delete g_renderHandler;
g_renderHandler = nullptr;
m_initialized = false;
spdlog::shutdown();
}
std::string MQ2NavigationPlugin::GetDataDirectory() const
{
// the root path is where we look for all of our mesh files
return std::string(gPathResources) + "\\MQ2Nav";
}
void MQ2NavigationPlugin::SetLogLevel(spdlog::level::level_enum level)
{
m_chatSink->set_level(level);
}
spdlog::level::level_enum MQ2NavigationPlugin::GetLogLevel() const
{
return m_chatSink->level();
}
//----------------------------------------------------------------------------
static void DoHelp()
{
WriteChatf(PLUGIN_MSG "Usage:");
WriteChatf(PLUGIN_MSG "\ag/nav [save | load]\ax - save/load settings");
WriteChatf(PLUGIN_MSG "\ag/nav reload\ax - reload navmesh");
WriteChatf(PLUGIN_MSG "\ag/nav ui\ax - show ui");
WriteChatf(PLUGIN_MSG "\ag/nav recordwaypoint|rwp \"<waypoint name>\" [\"<waypoint description>\"]\ax - create a waypoint at current location");
WriteChatf(PLUGIN_MSG "\ag/nav listwp\ax - list waypoints");
WriteChatf(PLUGIN_MSG "\aoNavigation Commands:\ax");
WriteChatf(PLUGIN_MSG "\ag/nav target\ax - navigate to target");
WriteChatf(PLUGIN_MSG "\ag/nav id #\ax - navigate to target with ID = #");
WriteChatf(PLUGIN_MSG "\ag/nav loc[yxz] Y X Z\ax - navigate to coordinates");
WriteChatf(PLUGIN_MSG "\ag/nav locxyz X Y Z\ax - navigate to coordinates");
WriteChatf(PLUGIN_MSG "\ag/nav locyx Y X\ax - navigate to 2d coordinates");
WriteChatf(PLUGIN_MSG "\ag/nav locxy X Y\ax - navigate to 2d coordinates");
WriteChatf(PLUGIN_MSG "\ag/nav item [click]\ax - navigate to item (and click it)");
WriteChatf(PLUGIN_MSG "\ag/nav door [item_name | id #] [click]\ax - navigate to door/object (and click it)");
WriteChatf(PLUGIN_MSG "\ag/nav setopt [options | reset]\ax - Set the default value for options used for navigation. See \agOptions\ax below. Pass \"reset\" instead to reset them to their default values.");
WriteChatf(PLUGIN_MSG "\ag/nav spawn <spawn search> | [options]\ax - navigate to spawn via spawn search query. If you want to provide options to navigate, like distance, you need to separate them by a | (pipe)");
WriteChatf(PLUGIN_MSG "\ag/nav waypoint|wp <waypoint>\ax - navigate to waypoint");
WriteChatf(PLUGIN_MSG "\ag/nav stop\ax - stop navigation");
WriteChatf(PLUGIN_MSG "\ag/nav pause\ax - pause navigation");
WriteChatf(PLUGIN_MSG "\ag/nav ini <key> <value>\ax - Write a setting to the ini and reload settings");
WriteChatf(PLUGIN_MSG "\aoNavigation Options:\ax");
WriteChatf(PLUGIN_MSG "Options can be provided to navigation commands to alter their behavior.");
WriteChatf(PLUGIN_MSG " \aydistance=<num>\ax - set the distance to navigate from the destination. shortcut: \agdist\ax");
WriteChatf(PLUGIN_MSG " \aylineofsight=<on/off>\ax - when using distance, require visibility of target. Default is \ayon\ax. shortcut: \aglos\ax");
WriteChatf(PLUGIN_MSG " \aylog=<level>\ax - adjust log level for command. can be \aytrace\ax, \aydebug\ax, \ayinfo\ax, \aywarning\ax, \ayerror\ax, \aycritical\ax or \ayoff\ax. The default is \ayinfo.");
WriteChatf(PLUGIN_MSG " \aypaused\ax - start navigation in a paused state.");
WriteChatf(PLUGIN_MSG " \aynotrack\ax - disable tracking of spawn movement. By default, when navigating to a spawn, the destination location will track the spawn's position. This disables that behavior.");
WriteChatf(PLUGIN_MSG " \ayfacing=<forward|backward>\ax - face forward or backward while moving.");
// NYI:
//WriteChatf(PLUGIN_MSG "\ag/nav options set \ay[options]\ax - save options as defaults");
//WriteChatf(PLUGIN_MSG "\ag/nav options reset\ax - reset options to default");
}
void MQ2NavigationPlugin::Command_Navigate(std::string_view line)
{
char mutableLine[MAX_STRING] = { 0 };
strncpy_s(mutableLine, line.data(), line.length());
CHAR buffer[MAX_STRING] = { 0 };
int i = 0;
SPDLOG_DEBUG("Handling Command: {}", line);
spdlog::level::level_enum requestedLevel = ExtractLogLevel(line, m_defaultOptions.logLevel);
if (requestedLevel != m_defaultOptions.logLevel)
SPDLOG_DEBUG("Log level temporarily set to: {}", spdlog::level::to_string_view(requestedLevel));
ScopedLogLevel scopedLevel{ *m_chatSink, requestedLevel };
GetArg(buffer, mutableLine, 1);
// parse /nav ui
if (!_stricmp(buffer, "ui"))
{
nav::GetSettings().show_ui = !nav::GetSettings().show_ui;
nav::SaveSettings(false);
return;
}
// parse /nav pause
if (!_stricmp(buffer, "pause"))
{
if (!m_isActive)
{
SPDLOG_WARN("Navigation must be active to pause");
return;
}
SetPaused(!m_isPaused);
return;
}
// parse /nav stop
if (!_stricmp(buffer, "stop"))
{
if (m_isActive)
{
Stop(false);
}
else
{
SPDLOG_ERROR("No navigation path currently active");
}
return;
}
// parse /nav reload
if (!_stricmp(buffer, "reload"))
{
Get<NavMeshLoader>()->LoadNavMesh();
return;
}
// parse /nav recordwaypoint or /nav rwp
if (!_stricmp(buffer, "recordwaypoint") || !_stricmp(buffer, "rwp"))
{
GetArg(buffer, mutableLine, 2);
std::string waypointName(buffer);
GetArg(buffer, mutableLine, 3);
std::string desc(buffer);
if (waypointName.empty())
{
SPDLOG_INFO("Usage: /nav rwp <waypoint name> <waypoint description>");
return;
}
if (PSPAWNINFO pChar = (GetCharInfo() ? GetCharInfo()->pSpawn : nullptr))
{
glm::vec3 loc = GetSpawnPosition(pChar);
nav::AddWaypoint(nav::Waypoint{ waypointName, loc, desc });
SPDLOG_INFO("Recorded waypoint: {} at {}", waypointName, loc.yxz());
}
return;
}
if (!_stricmp(buffer, "listwp"))
{
WriteChatf(PLUGIN_MSG "\ag%d\ax waypoint(s) for \ag%s\ax:", nav::g_waypoints.size(), GetShortZone(m_zoneId));
for (const nav::Waypoint& wp : nav::g_waypoints)
{
WriteChatf(PLUGIN_MSG " \at%s\ax: \a-w%s\ax \ay(%.2f, %.2f, %.2f)",
wp.name.c_str(), wp.description.c_str(), wp.location.y, wp.location.x, wp.location.z);
}
return;
}
// parse /nav load
if (!_stricmp(buffer, "load"))
{
nav::LoadSettings(true);
return;
}
// parse /nav save
if (!_stricmp(buffer, "save"))
{
nav::SaveSettings(true);
return;
}
// parse /nav ini
if (!_stricmp(buffer, "ini"))
{
const char* pStr = GetNextArg(mutableLine, 1);
if (!nav::ParseIniCommand(pStr))
{
SPDLOG_ERROR("Usage: /nav ini <key> <value>");
}
return;
}
// parse /nav help
if (!_stricmp(buffer, "help"))
{
DoHelp();
return;
}
// parse /nav setopt [options]
if (!_stricmp(buffer, "setopt"))
{
int idx = 2;
GetArg(buffer, mutableLine, idx);
if (!_stricmp(buffer, "reset"))
{
// reset
m_defaultOptions = NavigationOptions{};
SPDLOG_INFO("Navigation options reset");
}
else
{
ParseOptions(mutableLine, idx, m_defaultOptions, nullptr);
SPDLOG_INFO("Navigation options updated");
SPDLOG_DEBUG("Navigation options updated: {}", mutableLine);
}
return;
}
scopedLevel.Release();
// all thats left is a navigation command. leave if it isn't a valid one.
auto destination = ParseDestination(mutableLine, requestedLevel);
if (!destination->valid)
return;
BeginNavigation(destination);
}
//----------------------------------------------------------------------------
void MQ2NavigationPlugin::UpdateCurrentZone()
{
int zoneId = -1;
if (PCHARINFO pChar = GetCharInfo())
{
zoneId = pChar->zoneId;
zoneId &= 0x7FFF;
if (zoneId >= MAX_ZONES)
zoneId = -1;
}
SetCurrentZone(zoneId);
}
void MQ2NavigationPlugin::SetCurrentZone(int zoneId)
{
if (m_zoneId != zoneId)
{
m_zoneId = zoneId;
if (m_zoneId == -1)
SPDLOG_DEBUG("Resetting zone");
else
SPDLOG_DEBUG("Switching to zone: {}", m_zoneId);
nav::LoadWaypoints(m_zoneId);
for (const auto& m : m_modules)
{
m.second->SetZoneId(m_zoneId);
}
}
}
void MQ2NavigationPlugin::BeginNavigation(const std::shared_ptr<DestinationInfo>& destInfo)
{
assert(destInfo);
// first clear existing state
ResetPath();
if (!destInfo->valid)
return;
auto mesh = Get<NavMesh>();
if (!mesh->IsNavMeshLoaded())
{
SPDLOG_ERROR("Cannot navigate - no mesh file loaded.");
return;
}
m_chatSink->set_level(destInfo->options.logLevel);
if (destInfo->clickType != ClickType::None)
{
m_pEndingSwitch = destInfo->pSwitch;
m_endingGround = destInfo->groundItem;
}
m_activePath = std::make_shared<NavigationPath>(destInfo);
// resolve the height parameter of a 2d coordinate
if (destInfo && destInfo->heightType == HeightType::Nearest)
{
glm::vec3 transformed = destInfo->eqDestinationPos.xzy();
auto heights = mesh->GetHeights(transformed);
// disable logging for these calculations
ScopedLogLevel logScope{ *m_chatSink, spdlog::level::off };
// we don't actually want to calculate the path at the current height since there
// is no guarantee it is on the mesh
float current_distance = std::numeric_limits<float>().max();
// create a destination location out of the given x/y coordinate and each z coordinate
// that was hit at that location. Calculate the length of each and take the z coordinate that
// creates the shortest path.
for (auto height : heights)
{
float current_height = destInfo->eqDestinationPos.z;
destInfo->eqDestinationPos.z = height;
if (!m_activePath->FindPath() || m_activePath->GetPathTraversalDistance() > current_distance)
{
destInfo->eqDestinationPos.z = current_height;
} // else leave it, it's a better height
}
}
if (m_activePath->FindPath())
{
m_activePath->SetShowNavigationPaths(nav::GetSettings().show_nav_path);
m_isActive = m_activePath->GetPathSize() > 0;
}
else if (m_activePath->IsFailed())
{
UpdateCommandState(m_currentCommandState.get(), *m_activePath->GetDestinationInfo());