forked from MUME/MMapper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapcanvas_gl.cpp
More file actions
997 lines (840 loc) · 32.6 KB
/
Copy pathmapcanvas_gl.cpp
File metadata and controls
997 lines (840 loc) · 32.6 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
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2019 The MMapper Authors
#include "../configuration/NamedConfig.h"
#include "../configuration/configuration.h"
#include "../global/Array.h"
#include "../global/ChangeMonitor.h"
#include "../global/ConfigConsts.h"
#include "../global/RuleOf5.h"
#include "../global/logging.h"
#include "../global/progresscounter.h"
#include "../global/utils.h"
#include "../map/coordinate.h"
#include "../mapdata/mapdata.h"
#include "../opengl/Font.h"
#include "../opengl/FontFormatFlags.h"
#include "../opengl/OpenGL.h"
#include "../opengl/OpenGLConfig.h"
#include "../opengl/OpenGLTypes.h"
#include "../opengl/legacy/Meshes.h"
#include "../opengl/legacy/TFO.h"
#include "../opengl/legacy/VAO.h"
#include "../opengl/legacy/VBO.h"
#include "../src/global/SendToUser.h"
#include "Connections.h"
#include "MapCanvasConfig.h"
#include "MapCanvasData.h"
#include "MapCanvasRoomDrawer.h"
#include "ProjectionUtils.h"
#include "Textures.h"
#include "connectionselection.h"
#include "mapcanvas.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <future>
#include <memory>
#include <optional>
#include <random>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <QApplication>
#include <QMessageBox>
#include <QMessageLogContext>
#include <QOpenGLWindow>
#include <QtCore>
#include <QtGui/qopengl.h>
#include <QtGui>
namespace MapCanvasConfig {
void registerChangeCallback(const ChangeMonitor::Lifetime &lifetime,
ChangeMonitor::Function callback)
{
return setConfig().canvas.advanced.registerChangeCallback(lifetime, std::move(callback));
}
bool isIn3dMode()
{
return getConfig().canvas.advanced.use3D.get();
}
void set3dMode(bool is3d)
{
setConfig().canvas.advanced.use3D.set(is3d);
}
bool isAutoTilt()
{
return getConfig().canvas.advanced.autoTilt.get();
}
void setAutoTilt(const bool val)
{
setConfig().canvas.advanced.autoTilt.set(val);
}
bool getShowPerfStats()
{
return getConfig().canvas.advanced.printPerfStats.get();
}
void setShowPerfStats(const bool show)
{
setConfig().canvas.advanced.printPerfStats.set(show);
}
} // namespace MapCanvasConfig
class NODISCARD MakeCurrentRaii final
{
private:
QOpenGLWindow &m_glWindow;
public:
explicit MakeCurrentRaii(QOpenGLWindow &window)
: m_glWindow{window}
{
m_glWindow.makeCurrent();
}
~MakeCurrentRaii() { m_glWindow.doneCurrent(); }
DELETE_CTORS_AND_ASSIGN_OPS(MakeCurrentRaii);
};
void MapCanvas::cleanupOpenGL()
{
// Make sure the context is current and then explicitly
// destroy all underlying OpenGL resources.
MakeCurrentRaii makeCurrentRaii{*this};
// note: m_batchedMeshes co-owns textures created by MapCanvasData,
// and it also owns the lifetime of some OpenGL objects (e.g. VBOs).
m_batches.resetExistingMeshesAndIgnorePendingRemesh();
m_weather.cleanup();
m_textures.destroyAll();
getGLFont().cleanup();
getOpenGL().cleanup();
m_logger.reset();
}
void MapCanvas::reportGLVersion()
{
auto &gl = getOpenGL();
auto logMsg = [this](const QByteArray &prefix, const QByteArray &msg) -> void {
qInfo() << prefix << msg;
emit sig_log("MapCanvas", prefix + " " + msg);
};
auto getString = [&gl](const GLenum name) -> QByteArray {
return QByteArray{gl.glGetString(name)};
};
auto logString = [&getString, &logMsg](const QByteArray &prefix, const GLenum name) -> void {
logMsg(prefix, getString(name));
};
logString("OpenGL Version:", GL_VERSION);
logString("OpenGL Renderer:", GL_RENDERER);
logString("OpenGL Vendor:", GL_VENDOR);
logString("OpenGL GLSL:", GL_SHADING_LANGUAGE_VERSION);
const auto version = std::invoke([this]() -> std::string {
const QSurfaceFormat &format = context()->format();
std::ostringstream oss;
switch (format.renderableType()) {
case QSurfaceFormat::OpenGL:
oss << "GL";
break;
case QSurfaceFormat::OpenGLES:
oss << "ES";
break;
case QSurfaceFormat::OpenVG:
oss << "VG";
break;
case QSurfaceFormat::DefaultRenderableType:
default:
oss << "UN";
break;
}
oss << format.majorVersion() << "." << format.minorVersion();
return std::move(oss).str();
});
logMsg("Current OpenGL Context:",
QString("%1 (%2)")
.arg(version.c_str())
// FIXME: This is a bit late to report an invalid context.
.arg(context()->isValid() ? "valid" : "invalid")
.toUtf8());
if constexpr (!NO_OPENGL) {
logMsg("Highest OpenGL:", mmqt::toQByteArrayUtf8(OpenGLConfig::getGLVersionString()));
}
if constexpr (!NO_GLES) {
logMsg("Highest GLES:", mmqt::toQByteArrayUtf8(OpenGLConfig::getESVersionString()));
}
logMsg("Display:", QString("%1 DPI").arg(QPaintDevice::devicePixelRatioF()).toUtf8());
}
bool MapCanvas::isBlacklistedDriver()
{
if constexpr (CURRENT_PLATFORM == PlatformEnum::Windows) {
auto &gl = getOpenGL();
auto getString = [&gl](const GLenum name) -> QByteArray {
return QByteArray{gl.glGetString(name)};
};
const QByteArray &vendor = getString(GL_VENDOR);
const QByteArray &renderer = getString(GL_RENDERER);
if (vendor == "Microsoft Corporation" && renderer == "GDI Generic") {
return true;
}
}
return false;
}
void MapCanvas::initializeGL()
{
OpenGL &gl = getOpenGL();
try {
gl.initializeOpenGLFunctions();
// TODO: Perform the blacklist test as a call from main() to minimize player headache.
if (isBlacklistedDriver()) {
throw std::runtime_error("unsupported driver");
}
} catch (const std::exception &) {
hide();
doneCurrent();
QMessageBox::critical(QApplication::activeWindow(),
"Unable to initialize OpenGL",
"Upgrade your video card drivers");
if constexpr (CURRENT_PLATFORM == PlatformEnum::Windows) {
// Link to Microsoft OpenGL Compatibility Pack
QDesktopServices::openUrl(
QUrl(QStringLiteral("ms-windows-store://pdp/?productid=9nqpsl29bfff")));
}
return;
}
reportGLVersion();
// NOTE: If you're adding code that relies on generating OpenGL errors (e.g. ANGLE),
// you *MUST* force it to complete those error probes before calling initLogger(),
// because the logger purposely calls std::abort() when it receives an error.
initLogger();
gl.initializeRenderer(static_cast<float>(QPaintDevice::devicePixelRatioF()));
gl.getUboManager()
.registerRebuildFunction(Legacy::SharedVboEnum::NamedColorsBlock,
[](Legacy::Functions &funcs) {
auto &uboManager = funcs.getUboManager();
uboManager.update<Legacy::SharedVboEnum::NamedColorsBlock>(
funcs, XNamedColor::getAllColorsAsBlock());
});
gl.getUboManager().registerRebuildFunction(
Legacy::SharedVboEnum::CameraBlock, [this](Legacy::Functions &funcs) {
auto &camera = funcs.getUboManager().get<Legacy::SharedVboEnum::CameraBlock>();
const auto playerPosCoord = m_data.tryGetPosition().value_or(Coordinate{0, 0, 0});
camera.viewProj = getViewProj();
camera.playerPos = glm::vec4(static_cast<float>(playerPosCoord.x),
static_cast<float>(playerPosCoord.y),
static_cast<float>(playerPosCoord.z),
ProjectionUtils::ROOM_Z_SCALE);
funcs.getUboManager().sync<Legacy::SharedVboEnum::CameraBlock>(funcs);
});
updateMultisampling();
// REVISIT: should the font texture have the lowest ID?
initTextures();
auto &font = getGLFont();
font.setTextureId(allocateTextureId());
font.init();
updateTextures();
// compile all shaders
{
auto &sharedFuncs = gl.getSharedFunctions(Badge<MapCanvas>{});
Legacy::Functions &funcs = deref(sharedFuncs);
Legacy::ShaderPrograms &programs = funcs.getShaderPrograms();
programs.early_init();
}
setConfig().canvas.showUnsavedChanges.registerChangeCallback(m_lifetime, [this]() {
if (getConfig().canvas.showUnsavedChanges.get() && m_diff.highlight.has_value()
&& m_diff.highlight->highlights.empty()) {
this->forceUpdateMeshes();
}
});
setConfig().canvas.showMissingMapId.registerChangeCallback(m_lifetime, [this]() {
if (getConfig().canvas.showMissingMapId.get() && m_diff.highlight.has_value()
&& m_diff.highlight->highlights.empty()) {
this->forceUpdateMeshes();
}
});
setConfig().canvas.showUnmappedExits.registerChangeCallback(m_lifetime, [this]() {
this->forceUpdateMeshes();
});
setConfig().canvas.antialiasingSamples.registerChangeCallback(m_lifetime, [this]() {
markMultisamplingDirty();
m_frameManager.requestUpdate();
});
setConfig().canvas.trilinearFiltering.registerChangeCallback(m_lifetime, [this]() {
this->updateTextures();
m_frameManager.requestUpdate();
});
// Clean up GL resources while the context is still current.
// The destructor is too late — Qt destroys the context before ~MapCanvas() runs.
connect(context(),
&QOpenGLContext::aboutToBeDestroyed,
this,
&MapCanvas::cleanupOpenGL,
Qt::DirectConnection);
}
/* Direct means it is always called from the emitter's thread */
void MapCanvas::slot_onMessageLoggedDirect(const QOpenGLDebugMessage &message)
{
using Type = QOpenGLDebugMessage::Type;
switch (message.type()) {
case Type::InvalidType:
case Type::ErrorType:
case Type::UndefinedBehaviorType:
break;
case Type::DeprecatedBehaviorType:
case Type::PortabilityType:
case Type::PerformanceType:
case Type::OtherType:
case Type::MarkerType:
case Type::GroupPushType:
case Type::GroupPopType:
case Type::AnyType:
qWarning() << message;
return;
}
qCritical() << message;
QMessageBox box;
box.setWindowTitle("Fatal OpenGL error");
box.setText(message.message());
box.exec();
std::abort();
}
void MapCanvas::initLogger()
{
m_logger = std::make_unique<QOpenGLDebugLogger>(this);
connect(m_logger.get(),
&QOpenGLDebugLogger::messageLogged,
this,
&MapCanvas::slot_onMessageLoggedDirect,
Qt::DirectConnection /* NOTE: executed in emitter's thread */);
if (!m_logger->initialize()) {
m_logger.reset();
qWarning() << "Failed to initialize OpenGL debug logger";
return;
}
m_logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
m_logger->disableMessages();
m_logger->enableMessages(QOpenGLDebugMessage::AnySource,
(QOpenGLDebugMessage::ErrorType
| QOpenGLDebugMessage::UndefinedBehaviorType),
QOpenGLDebugMessage::AnySeverity);
}
void MapCanvas::setMvp(const glm::mat4 &viewProj)
{
auto &gl = getOpenGL();
// Pushes the externally provided projection matrix into the viewport cache,
// which also ensures the dirty flag is cleared for the current state.
setMvpExtern(viewProj);
gl.setProjectionMatrix(viewProj);
}
void MapCanvas::setViewportAndMvp(int width, int height)
{
if (width != m_lastWidth || height != m_lastHeight) {
m_lastWidth = width;
m_lastHeight = height;
markViewProjDirty();
}
auto &gl = getOpenGL();
gl.glViewport(0, 0, width, height);
const auto size = getViewport().size;
assert(size.x == width);
assert(size.y == height);
gl.setProjectionMatrix(MapCanvasViewport::getViewProj());
}
void MapCanvas::onViewProjDirty() const
{
m_opengl.getUboManager().invalidate(Legacy::SharedVboEnum::CameraBlock);
}
void MapCanvas::resizeGL(int width, int height)
{
if (m_textures.room_highlight == nullptr) {
// resizeGL called but initializeGL was not called yet
return;
}
setViewportAndMvp(width, height);
markMultisamplingDirty();
m_frameManager.requestUpdate();
}
void MapCanvas::updateBatches()
{
updateMapBatches();
updateInfomarkBatches();
}
void MapCanvas::updateMapBatches()
{
RemeshCookie &remeshCookie = m_batches.remeshCookie;
if (remeshCookie.isPending()) {
return;
}
if (m_batches.mapBatches.has_value() && !m_data.getNeedsMapUpdate()) {
return;
}
if (m_data.getNeedsMapUpdate()) {
m_data.clearNeedsMapUpdate();
assert(!m_data.getNeedsMapUpdate());
MMLOG() << "[updateMapBatches] cleared 'needsUpdate' flag";
}
auto getFuture = [this]() {
MMLOG() << "[updateMapBatches] calling generateBatches";
return m_data.generateBatches(mctp::getProxy(m_textures),
getGLFont().getSharedFontMetrics());
};
remeshCookie.set(getFuture());
assert(remeshCookie.isPending());
m_diff.cancelUpdates(m_data.getSavedMap());
}
bool Batches::isInProgress() const
{
return remeshCookie.isPending() || next_mapBatches.has_value();
}
void MapCanvas::finishPendingMapBatches()
{
if (!m_batches.isInProgress()) {
return;
}
#define LOG() MMLOG() << prefix
static const std::string_view prefix = "[finishPendingMapBatches] ";
if (m_batches.next_mapBatches.has_value()) {
m_batches.mapBatches = std::exchange(m_batches.next_mapBatches, std::nullopt);
}
RemeshCookie &remeshCookie = m_batches.remeshCookie;
if (!remeshCookie.isPending() || !remeshCookie.isReady()) {
return;
}
LOG() << "Waiting for the cookie. This shouldn't take long.";
try {
SharedMapBatchFinisher pFuture = remeshCookie.get();
assert(!remeshCookie.isPending());
if (pFuture == nullptr) {
// REVISIT: Do we need to schedule another update now?
LOG() << "Got NULL (means the update was flagged to be ignored)";
return;
}
// REVISIT: should we pass a "fake" one and only swap to the correct one on success?
LOG() << "Clearing the map batches and call the finisher to create new ones";
DECL_TIMER(t, __FUNCTION__);
const IMapBatchesFinisher &future = *pFuture;
std::optional<MapBatches> &opt_mapBatches = m_batches.next_mapBatches;
opt_mapBatches.reset();
finish(future, opt_mapBatches, getOpenGL(), getGLFont());
assert(opt_mapBatches.has_value());
m_data.saveSnapshot();
// Swap immediately so this frame can use the new batches.
m_batches.mapBatches = std::exchange(m_batches.next_mapBatches, std::nullopt);
} catch (...) {
QString msg;
try {
std::rethrow_exception(std::current_exception());
} catch (const std::exception &ex) {
msg = ex.what();
} catch (...) {
msg = QStringLiteral("unknown");
}
const auto s = QString("ERROR: %1\nReverting map to previous snapshot. Please file a bug!\n")
.arg(msg);
qWarning().noquote() << s;
global::sendToUser(s);
// FIXME: This causes a cycle when the remeshing throws.
m_data.restoreSnapshot();
}
#undef LOG
}
void MapCanvas::actuallyPaintGL()
{
// DECL_TIMER(t, __FUNCTION__);
setViewportAndMvp(width(), height());
if (takeMultisamplingDirty()) {
updateMultisampling();
}
auto &gl = getOpenGL();
auto &funcs = deref(gl.getSharedFunctions(Badge<MapCanvas>{}));
gl.getUboManager().bind(funcs, Legacy::SharedVboEnum::NamedColorsBlock);
gl.bindFbo();
gl.clear(Color{getConfig().canvas.backgroundColor});
if (m_data.isEmpty()) {
getGLFont().renderTextCentered("No map loaded");
} else {
// Update animation state
m_weather.update();
paintMap();
paintBatchedInfomarks();
paintSelections();
paintCharacters();
paintDifferences();
m_weather.prepare();
gl.getUboManager().bind(funcs, Legacy::SharedVboEnum::TimeBlock);
m_weather.render(m_opengl.getDefaultRenderState());
}
gl.releaseFbo();
gl.blitFboToDefault();
}
NODISCARD bool MapCanvas::Diff::isUpToDate(const Map &saved, const Map ¤t) const
{
return highlight && highlight->saved.isSamePointer(saved)
&& highlight->current.isSamePointer(current);
}
// this differs from isUpToDate in that it allows display of a diff based on the current saved map,
// but it allows the "current" to be different (e.g. during the async remesh for the current map).
NODISCARD bool MapCanvas::Diff::hasRelatedDiff(const Map &saved) const
{
return highlight && highlight->saved.isSamePointer(saved);
}
void MapCanvas::Diff::cancelUpdates(const Map &saved)
{
futureHighlight.reset();
if (highlight) {
if (!hasRelatedDiff(saved)) {
highlight.reset();
}
}
}
void MapCanvas::Diff::maybeAsyncUpdate(const Map &saved, const Map ¤t)
{
auto &diff = *this;
// Pending takes precedence. This also usually guarantees at most one pending update at a time,
// but calling resetExistingMeshesAndIgnorePendingRemesh() could result in more than one diff
// mesh thread executing concurrently, where the old one will be ignored.
if (diff.futureHighlight) {
constexpr auto immediate = std::chrono::milliseconds(0);
if (diff.futureHighlight->wait_for(immediate) != std::future_status::timeout) {
try {
diff.highlight = diff.futureHighlight->get();
} catch (const std::exception &ex) {
MMLOG_ERROR() << "Exception: " << ex.what();
}
diff.futureHighlight.reset();
}
return;
}
// no change necessary
if (isUpToDate(saved, current)) {
return;
}
const auto &config = getConfig();
const auto &canvas = config.canvas;
const bool showNeedsServerId = canvas.showMissingMapId.get();
const bool showChanged = canvas.showUnsavedChanges.get();
diff.futureHighlight = std::async(
std::launch::async,
[saved, current, showNeedsServerId, showChanged]() -> Diff::HighlightDiff {
DECL_TIMER(t2,
"[async] actuallyPaintGL: highlight changes, temporary, and needs update");
auto getHighlights =
[&saved, ¤t, showChanged, showNeedsServerId]() -> Diff::MaybeDataOrMesh {
if (!showChanged && !showNeedsServerId) {
return Diff::MaybeDataOrMesh{};
}
DECL_TIMER(t3, "[async] actuallyPaintGL: compute highlights");
DiffQuadVector highlights;
auto drawQuad = [&highlights](const RawRoom &room, const NamedColorEnum color) {
const auto pos = room.getPosition().to_ivec3();
highlights.emplace_back(pos, 0, color);
};
// Handle rooms needing a server ID or that are temporary
if (showNeedsServerId) {
current.getRooms().for_each([¤t, &drawQuad](auto id) {
if (auto h = current.getRoomHandle(id)) {
if (h.isTemporary()) {
drawQuad(h.getRaw(), NamedColorEnum::HIGHLIGHT_TEMPORARY);
} else if (h.getServerId() == INVALID_SERVER_ROOMID) {
drawQuad(h.getRaw(), NamedColorEnum::HIGHLIGHT_NEEDS_SERVER_ID);
}
}
});
}
// Handle changed rooms
if (showChanged) {
ProgressCounter dummyPc;
Map::foreachChangedRoom(dummyPc,
saved,
current,
[&drawQuad](const RawRoom &room) {
drawQuad(room, NamedColorEnum::HIGHLIGHT_UNSAVED);
});
}
if (highlights.empty()) {
return Diff::MaybeDataOrMesh{};
}
return Diff::MaybeDataOrMesh{std::move(highlights)};
};
return Diff::HighlightDiff{saved, current, getHighlights()};
});
}
void MapCanvas::paintDifferences()
{
auto &diff = m_diff;
const auto &saved = m_data.getSavedMap();
const auto ¤t = m_data.getCurrentMap();
diff.maybeAsyncUpdate(saved, current);
if (!diff.hasRelatedDiff(saved)) {
return;
}
auto &highlight = deref(diff.highlight);
auto &gl = getOpenGL();
if (auto &highlights = highlight.highlights; !highlights.empty()) {
highlights.render(gl, m_textures.room_highlight->getArrayPosition().array);
}
}
void MapCanvas::paintMap()
{
const bool pending = m_batches.remeshCookie.isPending();
if (!m_batches.mapBatches.has_value()) {
if (!pending || m_batches.pendingUpdateFlashState.tick()) {
const QString msg = pending ? "Please wait... the map isn't ready yet." : "Batch error";
getGLFont().renderTextCentered(msg);
}
if (!pending) {
// REVISIT: does this need a better fix?
// pending already scheduled an update, but now we realize we need an update.
m_frameManager.requestUpdate();
}
return;
}
// TODO: add a GUI indicator for pending update?
renderMapBatches();
if (pending) {
if (m_batches.pendingUpdateFlashState.tick()) {
const QString msg = "CAUTION: Async map update pending!";
getGLFont().renderTextCentered(msg);
}
}
}
void MapCanvas::paintSelections()
{
paintSelectedRooms();
paintSelectedConnection();
paintSelectionArea();
paintSelectedInfomarks();
}
void MapCanvas::paintGL()
{
auto frame = m_frameManager.beginFrame();
if (!frame) {
// Blit the existing FBO on resize or expose
getOpenGL().blitFboToDefault();
return;
}
static thread_local double longestBatchMs = 0.0;
const bool showPerfStats = MapCanvasConfig::getShowPerfStats();
using Clock = std::chrono::high_resolution_clock;
std::optional<Clock::time_point> optStart;
std::optional<Clock::time_point> optAfterTextures;
std::optional<Clock::time_point> optAfterBatches;
if (showPerfStats) {
optStart = Clock::now();
}
{
if (showPerfStats) {
optAfterTextures = Clock::now();
}
// Note: The real work happens here!
updateBatches();
// And here
finishPendingMapBatches();
// For accurate timing of the update, we'd need to call glFinish(),
// or at least set up an OpenGL query object. The update will send
// a lot of data to the GPU, so it could take a while...
if (showPerfStats) {
optAfterBatches = Clock::now();
}
actuallyPaintGL();
}
if (!showPerfStats) {
return; /* don't wait to finish */
}
const auto &start = optStart.value();
const auto &afterTextures = optAfterTextures.value();
const auto &afterBatches = optAfterBatches.value();
const auto afterPaint = Clock::now();
const bool calledFinish = std::invoke([this]() -> bool {
if (auto *const ctxt = QOpenGLWindow::context()) {
if (auto *const func = ctxt->functions()) {
func->glFinish();
return true;
}
}
return false;
});
const auto end = Clock::now();
const auto ms = [](auto delta) -> double {
return double(std::chrono::duration_cast<std::chrono::nanoseconds>(delta).count()) * 1e-6;
};
const auto w = width();
const auto h = height();
const auto dpr = getOpenGL().getDevicePixelRatio();
auto &font = getGLFont();
std::vector<GLText> text;
const auto lineHeight = font.getFontHeight();
const float rightMargin = float(w) * dpr
- static_cast<float>(font.getGlyphAdvance('e').value_or(5));
// x and y are in physical (device) pixels
// TODO: change API to use logical pixels.
auto y = lineHeight;
const auto print = [lineHeight, rightMargin, &text, &y](const QString &msg) {
text.emplace_back(glm::vec3(rightMargin, y, 0),
mmqt::toStdStringLatin1(msg), // GL font is latin1
Colors::white,
Colors::black.withAlpha(0.4f),
FontFormatFlags{FontFormatFlagEnum::HALIGN_RIGHT});
y += lineHeight;
};
const auto texturesTime = ms(afterTextures - start);
const auto batchTime = ms(afterBatches - afterTextures);
const auto total = ms(end - start);
print(QString::asprintf(
"%.1f (updateTextures) + %.1f (updateBatches) + %.1f (paintGL) + %.1f (glFinish%s) = %.1f ms",
texturesTime,
batchTime,
ms(afterPaint - afterBatches),
ms(end - afterPaint),
calledFinish ? "" : "*",
total));
if (!calledFinish) {
print("* = unable to call glFinish()");
}
longestBatchMs = std::max(batchTime, longestBatchMs);
print(QString::asprintf("Worst updateBatches: %.1f ms", longestBatchMs));
const auto &advanced = getConfig().canvas.advanced;
const float zoom = getTotalScaleFactor();
const bool is3d = advanced.use3D.get();
if (is3d) {
const ViewportConfig config{advanced.use3D.get(),
advanced.autoTilt.get(),
advanced.fov.getFloat(),
advanced.verticalAngle.getFloat(),
advanced.horizontalAngle.getFloat(),
advanced.layerHeight.getFloat()};
print(QString::asprintf("3d mode: %.1f fovy, %.1f pitch, %.1f yaw, %.1f zscale",
advanced.fov.getDouble(),
static_cast<double>(
ProjectionUtils::calculatePitchDegrees(config, zoom)),
advanced.horizontalAngle.getDouble(),
advanced.layerHeight.getDouble()));
} else {
const glm::vec3 c = unproject_raw(glm::vec3{w / 2, h / 2, 0});
const glm::vec3 v = unproject_raw(glm::vec3{w / 2, 0, 0});
const auto dy = std::abs((v - c).y);
const auto dz = std::abs(c.z);
const float fovy = 2.f * glm::degrees(std::atan2(dy, dz));
print(QString::asprintf("2d mode; current fovy: %.1f", static_cast<double>(fovy)));
}
print(QString::asprintf("zoom: %.2f (1/%.1f)",
static_cast<double>(zoom),
1.0 / static_cast<double>(zoom)));
const auto ctr = m_mapScreen.getCenter();
print(QString::asprintf("center: %.1f, %.1f, %.1f",
static_cast<double>(ctr.x),
static_cast<double>(ctr.y),
static_cast<double>(ctr.z)));
font.render2dTextImmediate(text);
}
void MapCanvas::paintSelectionArea()
{
if (!hasSel1() || !hasSel2()) {
return;
}
const auto pos1 = getSel1().pos.to_vec2();
const auto pos2 = getSel2().pos.to_vec2();
// Mouse selected area
auto &gl = getOpenGL();
const auto layer = static_cast<float>(getCurrentLayer());
if (hasAreaSelection()) {
const glm::vec3 A{pos1, layer};
const glm::vec3 B{pos2.x, pos1.y, layer};
const glm::vec3 C{pos2, layer};
const glm::vec3 D{pos1.x, pos2.y, layer};
// REVISIT: why a dark colored selection?
const Color selBgColor = Colors::black.withAlpha(0.5f);
const auto rs
= GLRenderState().withBlend(BlendModeEnum::TRANSPARENCY).withDepthFunction(std::nullopt);
{
const std::vector<glm::vec3> verts{A, B, C, D};
const auto &fillStyle = rs;
gl.renderPlainQuads(verts, fillStyle.withColor(selBgColor));
}
const auto selFgColor = Colors::yellow;
{
static constexpr float SELECTION_AREA_LINE_WIDTH = 2.f;
const auto lineStyle = rs.withLineParams(LineParams{SELECTION_AREA_LINE_WIDTH});
const std::vector<glm::vec3> verts{A, B, B, C, C, D, D, A};
// FIXME: ASAN flags this as out-of-bounds memory access inside an assertion
//
// Q_ASSERT(QOpenGLFunctions::isInitialized(d_ptr));
//
// in QOpenGLFunctions::glDrawArrays(). However, it works without ASAN,
// so maybe the problem is in my OpenGL driver?
//
// "OpenGL Version:" "3.1 Mesa 20.2.6"
// "OpenGL Renderer:" "llvmpipe (LLVM 11.0.0, 256 bits)"
// "OpenGL Vendor:" "Mesa/X.org"
// "OpenGL GLSL:" "1.40"
// "Current OpenGL Context:" "3.1 (valid)"
//
gl.renderPlainLines(verts, lineStyle.withColor(selFgColor));
}
}
paintNewInfomarkSelection();
}
void MapCanvas::updateMultisampling()
{
const int wantMultisampling = getConfig().canvas.antialiasingSamples.get();
getOpenGL().configureFbo(wantMultisampling);
}
void MapCanvas::renderMapBatches()
{
std::optional<MapBatches> &mapBatches = m_batches.mapBatches;
if (!mapBatches.has_value()) {
// Hint: Use CREATE_ONLY first.
throw std::runtime_error("called in the wrong order");
}
MapBatches &batches = mapBatches.value();
const Configuration::CanvasSettings &settings = getConfig().canvas;
const float totalScaleFactor = getTotalScaleFactor();
const auto wantExtraDetail = totalScaleFactor >= settings.extraDetailScaleCutoff;
const auto wantDoorNames = settings.drawDoorNames
&& (totalScaleFactor >= settings.doorNameScaleCutoff);
auto &gl = getOpenGL();
BatchedMeshes &batchedMeshes = batches.batchedMeshes;
const auto drawLayer =
[&batches, &batchedMeshes, wantExtraDetail, wantDoorNames](const int thisLayer,
const int currentLayer) {
const auto it_mesh = batchedMeshes.find(thisLayer);
if (it_mesh != batchedMeshes.end()) {
LayerMeshes &meshes = it_mesh->second;
meshes.render(thisLayer, currentLayer);
}
if (wantExtraDetail) {
BatchedConnectionMeshes &connectionMeshes = batches.connectionMeshes;
const auto it_conn = connectionMeshes.find(thisLayer);
if (it_conn != connectionMeshes.end()) {
ConnectionMeshes &meshes = it_conn->second;
meshes.render(thisLayer, currentLayer);
}
// NOTE: This can display room names in lower layers, but the text
// isn't currently drawn with an appropriate Z-offset, so it doesn't
// stay aligned to its actual layer when you switch view layers.
if (wantDoorNames && thisLayer == currentLayer) {
BatchedRoomNames &roomNameBatches = batches.roomNameBatches;
const auto it_name = roomNameBatches.find(thisLayer);
if (it_name != roomNameBatches.end()) {
auto &roomNameBatch = it_name->second;
roomNameBatch.render(GLRenderState());
}
}
}
};
const auto fadeBackground = [&gl, &settings]() {
auto bgColor = Color{settings.backgroundColor.getColor(), 0.5f};
const auto blendedWithBackground
= GLRenderState().withBlend(BlendModeEnum::TRANSPARENCY).withColor(bgColor);
gl.renderPlainFullScreenQuad(blendedWithBackground);
};
const int currentLayer = getCurrentLayer();
for (const auto &layer : batchedMeshes) {
const int thisLayer = layer.first;
if (thisLayer == currentLayer) {
gl.clearDepth();
fadeBackground();
}
drawLayer(thisLayer, currentLayer);
}
}