Repository navigation
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
8347 lines (7458 loc) · 293 KB
/
Copy pathMainWindow.cpp
File metadata and controls
8347 lines (7458 loc) · 293 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
// SPDX-License-Identifier: MIT
/**
* @file MainWindow.cpp
* @brief RoboMaster 2026 主窗口实现文件
* @author Clear
* @date 2025-11-16
* @copyright Copyright (c) 2025 Fudan University EGA Team (复旦大学星云 EGA 机器人战队).
*
* 主窗口界面
* 包含顶部HUD区域(基地血条、轮次时间、比分经济)、中心信息区域和底部状态栏
* 采用2行布局设计,符合官方界面规范
*/
// --- Qt 头文件 ---
#include <algorithm>
#include <QApplication>
#include <QAudioOutput>
#include <QColor>
#include <QCoreApplication>
#include <QCursor>
#include <QDateTime>
#include <QDebug>
#include <QFileInfo>
#include <QGraphicsDropShadowEffect>
#include <QGridLayout>
#include <QJsonObject>
#include <QKeyEvent>
#include <QLabel>
#include <QMediaPlayer>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPainter>
#include <QPalette>
#include <QPushButton>
#include <QNetworkProxy>
#include <QQmlContext>
#include <QQuickImageProvider>
#include <QQuickWidget>
#include <QRegularExpression>
#include <QScreen>
#include <QTcpSocket>
#include <QTimer>
#include <QToolTip>
#include <QUuid>
#include <QWheelEvent>
#include <cmath>
// --- 项目头文件 ---
#include "../config/ConfigManager.h"
#include "../core/GameData.h"
#include "../core/GameConstants.h"
#include "../core/TimedEventRules.h"
#include "../core/TacticalAnalyzer.h"
#include "../core/DataFreshnessGuard.h"
#include "../core/ExecutionFusion.h"
#include "../core/MapCoordinateMapper.h"
#include "../core/ThreatRanker.h"
#include "../devhooks/ClientDevHooks.h"
#include "../network/MqttClient.h"
#include "../simulator/ProtocolSimulator.h"
#include "../network/S1ProtocolManager.h"
#include "../widgets/BattleMessageWidget.h"
// #include "../widgets/KillFeedWidget.h"
#include "../widgets/CrosshairWidget.h"
#include "../widgets/DebugLogWidget.h"
#include "../widgets/HealthBarWidget.h"
#include "../widgets/HeatRingWidget.h"
#include "../widgets/HeroVideoWidget.h"
#include "../widgets/HelpOverlayWidget.h"
#include "../widgets/InfoPanel.h"
#include "../widgets/MiniMapWidget.h"
#include "../widgets/OperationsPanel.h"
#include "../widgets/RobotStatusPanel.h"
#include "../widgets/RobotStatusWidget.h"
#include "InputHotkeyPolicy.h"
#include "MainWindowStatePolicy.h"
#include "ExchangeCommandPolicy.h"
#include "PopupOverlayPolicy.h"
#ifdef RM_HAS_AR_OVERLAY
#include "../widgets/AROverlayManager.h"
#include "../widgets/AROverlayWidget.h"
#endif
#include "MainWindow.h"
#include <QFontDatabase>
#include <QQmlContext>
#include <QQuickItem>
#include <QQuickView>
#include <QQuickWidget>
#include <QQuickWindow>
#include <QVariantMap>
#include "robomaster.pb.h"
// RuneData 由 GameData.h 提供,已通过 MainWindow.h 间接包含。
namespace RM {
namespace {
constexpr int kMqttReconnectIntervalMs = 5000;
bool keyboardMouseTraceEnabled() {
return qEnvironmentVariableIsSet("RM_KEYBOARD_MOUSE_TRACE");
}
bool shouldLogKeyboardMouseMoveTrace() {
if (!keyboardMouseTraceEnabled()) {
return false;
}
static qint64 lastTraceMs = 0;
const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
if (lastTraceMs > 0 && nowMs - lastTraceMs < 100) {
return false;
}
lastTraceMs = nowMs;
return true;
}
template <typename WidgetT>
void setVisibleIfNeeded(WidgetT *widget, bool visible) {
if (!widget) {
return;
}
if (widget->isVisible() == visible) {
return;
}
visible ? widget->show() : widget->hide();
}
int normalizedRobotIdFromSelection(const QString &robotType) {
static const QRegularExpression kRobotPattern(QStringLiteral("[RB](\\d+)"),
QRegularExpression::CaseInsensitiveOption);
const QRegularExpressionMatch match = kRobotPattern.match(robotType);
if (!match.hasMatch()) {
return 0;
}
bool ok = false;
const int robotId = match.captured(1).toInt(&ok);
if (!ok || robotId <= 0) {
return 0;
}
return robotId;
}
QString settingsRobotTypeLabelForNormalizedId(int robotId) {
switch (robotId) {
case 1:
return QStringLiteral("R1 - Hero");
case 2:
return QStringLiteral("R2 - Engineer");
case 3:
return QStringLiteral("R3 - Standard");
case 4:
return QStringLiteral("R4 - Standard");
case 5:
return QStringLiteral("R5 - Standard");
case 6:
return QStringLiteral("R6 - Aerial");
case 7:
return QStringLiteral("R7 - Sentry");
default:
return QStringLiteral("R1 - Hero");
}
}
bool isInfantryRobotId(int robotId) {
return robotId == 3 || robotId == 4 || robotId == 5 || robotId == 103 ||
robotId == 104 || robotId == 105;
}
// 将协议数字转化为底盘类型文本
QString chassisSelectionTextForValue(quint8 selection) {
switch (selection) {
case 1:
return QStringLiteral("血量优先");
case 2:
return QStringLiteral("功率优先");
case 3:
return QStringLiteral("英雄近战优先");
case 4:
return QStringLiteral("英雄远程优先");
default:
return QStringLiteral("初始设置");
}
}
QString shooterSelectionTextForValue(quint8 selection) {
switch (selection) {
case 1:
return QStringLiteral("冷却优先");
case 2:
return QStringLiteral("爆发优先");
case 3:
return QStringLiteral("英雄近战优先");
case 4:
return QStringLiteral("英雄远程优先");
default:
return QStringLiteral("初始设置");
}
}
int clampKeyboardMouseAxis(qint64 value) {
return static_cast<int>(std::clamp<qint64>(value, -32767, 32767));
}
bool isTacticalLayoutSwitchShortcut(const QKeyEvent *event) {
if (!event || event->isAutoRepeat()) {
return false;
}
const Qt::KeyboardModifiers expectedModifier = Qt::ControlModifier;
return event->key() == Qt::Key_Y && event->modifiers() == expectedModifier;
}
} // namespace
static RobotType toUiRobotType(::RobotType t) {
switch (t) {
case ::RobotType::HERO:
return RobotType::Hero;
case ::RobotType::ENGINEER:
return RobotType::Engineer;
case ::RobotType::AERIAL:
return RobotType::Aerial;
case ::RobotType::SENTRY:
return RobotType::Sentry;
case ::RobotType::DART:
return RobotType::Dart;
case ::RobotType::RADAR:
return RobotType::Radar;
case ::RobotType::INFANTRY_3:
case ::RobotType::INFANTRY_4:
case ::RobotType::INFANTRY_5:
default:
return RobotType::Standard;
}
}
// --- 辅助函数:设置 QQuickWidget 透明背景 (macOS 兼容) ---
static void makeQQuickWidgetTransparent(QQuickWidget *widget) {
if (!widget)
return;
// 1. 设置 Qt 窗口属性
widget->setAttribute(Qt::WA_TranslucentBackground);
widget->setAttribute(Qt::WA_NoSystemBackground);
widget->setAttribute(Qt::WA_OpaquePaintEvent, false);
// 2. 设置 QQuickWidget 清除颜色
widget->setClearColor(Qt::transparent);
// 3. 禁用自动填充背景
widget->setAutoFillBackground(false);
// 4. 设置透明调色板
QPalette pal = widget->palette();
pal.setColor(QPalette::Window, Qt::transparent);
pal.setColor(QPalette::Base, Qt::transparent);
widget->setPalette(pal);
// 5. 设置样式表
widget->setStyleSheet("background: transparent; border: none;");
// 6. [关键] 设置底层 QQuickWindow 的背景色为透明
// 这是 macOS 上 QQuickWidget 透明度的关键修复
if (QQuickWindow *qw = widget->quickWindow()) {
qw->setColor(Qt::transparent);
}
}
static void makeQQuickWidgetOpaque(QQuickWidget *widget,
const QColor &backgroundColor) {
if (!widget)
return;
widget->setAttribute(Qt::WA_TranslucentBackground, false);
widget->setAttribute(Qt::WA_NoSystemBackground, false);
widget->setAttribute(Qt::WA_OpaquePaintEvent, true);
widget->setAutoFillBackground(true);
widget->setClearColor(backgroundColor);
QPalette pal = widget->palette();
pal.setColor(QPalette::Window, backgroundColor);
pal.setColor(QPalette::Base, backgroundColor);
widget->setPalette(pal);
widget->setStyleSheet(
QStringLiteral("background: rgb(%1, %2, %3); border: none;")
.arg(backgroundColor.red())
.arg(backgroundColor.green())
.arg(backgroundColor.blue()));
if (QQuickWindow *qw = widget->quickWindow()) {
qw->setColor(backgroundColor);
}
}
class HeroVideoImageProvider final : public QQuickImageProvider {
public:
explicit HeroVideoImageProvider(GameData *gameData)
: QQuickImageProvider(QQuickImageProvider::Image), m_gameData(gameData) {}
QImage requestImage(const QString &id, QSize *size,
const QSize &requestedSize) override {
Q_UNUSED(id);
if (!m_gameData) {
if (size) {
*size = QSize();
}
return QImage();
}
QImage frame = m_gameData->heroFrame();
if (size) {
*size = frame.size();
}
if (!frame.isNull() && requestedSize.isValid()) {
frame = frame.scaled(requestedSize, Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
return frame;
}
private:
QPointer<GameData> m_gameData;
};
static void setQmlRootScale(QQuickWidget *widget, qreal scale) {
if (!widget) {
return;
}
auto *rootItem = qobject_cast<QQuickItem *>(widget->rootObject());
if (!rootItem) {
return;
}
rootItem->setTransformOrigin(QQuickItem::TopLeft);
rootItem->setScale(scale);
}
// --- QML 小地图桥接:将 C++ 调用转发到 MiniMap.qml 的 JS 函数 ---
static QObject *miniMapRootObject(QQuickWidget *map) {
if (!map) {
return nullptr;
}
return map->rootObject();
}
static void miniMapSetInteractionEnabled(QQuickWidget *map, bool enabled) {
QObject *root = miniMapRootObject(map);
if (!root) {
return;
}
root->setProperty("clickEnabled", enabled);
}
static void miniMapSetPendingMarkMode(QQuickWidget *map, int markType,
const QString &label) {
QObject *root = miniMapRootObject(map);
if (!root) {
return;
}
QMetaObject::invokeMethod(root, "setPendingMarkMode",
Q_ARG(QVariant, QVariant(markType)),
Q_ARG(QVariant, QVariant(label)));
}
static void miniMapClearPendingMarkMode(QQuickWidget *map) {
QObject *root = miniMapRootObject(map);
if (!root) {
return;
}
QMetaObject::invokeMethod(root, "clearPendingMarkMode");
}
static void miniMapAddCommandMarker(QQuickWidget *map, qreal x, qreal y,
int markType, const QString &label) {
QObject *root = miniMapRootObject(map);
if (!root) {
return;
}
QMetaObject::invokeMethod(root, "addCommandMarker",
Q_ARG(QVariant, QVariant(x)),
Q_ARG(QVariant, QVariant(y)),
Q_ARG(QVariant, QVariant(markType)),
Q_ARG(QVariant, QVariant(label)));
}
// 下方 QQuickWidget 显隐辅助函数的前向声明。
static void safeQuickHide(QWidget *w);
static void safeQuickShow(QWidget *w);
static QObject *tacticalTimedEventPopupRootObject(QQuickWidget *popup) {
if (!popup) {
return nullptr;
}
return popup->rootObject();
}
static bool isMiniMapCommandKey(int key) {
return key == Qt::Key_A || key == Qt::Key_B || key == Qt::Key_I;
}
//判断当前按键事件是否是~键(伤害面板)
static bool isOfficialEventPopupTestHotkey(const QKeyEvent *event) {
if (!event) {
return false;
}
// 事件提示弹窗临时调试键
return event->key() == Qt::Key_F9 &&
event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier);
}
static bool isTacticalTimedEventPopupTestHotkey(const QKeyEvent *event) {
if (!event) {
return false;
}
// 战术定时事件弹窗临时调试键
return event->key() == Qt::Key_F8 &&
event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier);
}
static int miniMapMarkTypeForKey(Qt::Key key) {
switch (key) {
case Qt::Key_A:
return 1;
case Qt::Key_B:
return 3;
case Qt::Key_I:
return 2;
default:
return -1;
}
}
static QString miniMapCommandLabelForKey(Qt::Key key) {
switch (key) {
case Qt::Key_A:
return QStringLiteral("攻击");
case Qt::Key_B:
return QStringLiteral("警戒");
case Qt::Key_I:
return QStringLiteral("防御");
default:
return QString();
}
}
static QString event8CounteredSoundFile(const QString &rawSelector) {
const QString selector = rawSelector.trimmed().toLower();
bool ok = false;
const int remainingCounterCount = selector.toInt(&ok);
// 协议约定:event=8 的 param 为“己方剩余可反制次数”。
if (ok) {
switch (remainingCounterCount) {
case 4:
return QStringLiteral("resources/sounds/反制无人机第一次.mp3");
case 3:
return QStringLiteral("resources/sounds/反制无人机第二次.mp3");
case 2:
return QStringLiteral("resources/sounds/反制无人机第三次.mp3");
default:
break;
}
}
// 兜底仍给一个占位音效,避免参数异常时完全静音。
return QStringLiteral("resources/sounds/反制无人机第一次.mp3");
}
QString MainWindow::allyBaseArmorOpenedSoundFileName() {
return QStringLiteral("我方基地护甲展开.mp3");
}
int MainWindow::allyBaseArmorOpenedSoundLoopCount() {
return 3;
}
QString MainWindow::paidRespawnSoundFileName(int robotId) {
switch (robotId % 100) {
case 1:
return QStringLiteral("enemy_buyback_hero_revived.mp3");
case 2:
return QStringLiteral("enemy_buyback_engineer_revived.mp3");
case 3:
return QStringLiteral("enemy_buyback_infantry_3_revived.mp3");
case 4:
return QStringLiteral("enemy_buyback_infantry_4_revived.mp3");
case 6:
return QStringLiteral("enemy_buyback_aerial_revived.mp3");
case 7:
return QStringLiteral("enemy_buyback_sentry_revived.mp3");
default:
return QString();
}
}
static void connectIfQmlSignalExists(QObject *sender,
const char *signalSignature,
QObject *receiver,
const char *slotSignature) {
if (!sender || !receiver) {
return;
}
if (sender->metaObject()->indexOfSignal(signalSignature) < 0) {
return;
}
const QByteArray signalSpec = "2" + QByteArray(signalSignature);
const QByteArray slotSpec = "1" + QByteArray(slotSignature);
QObject::connect(sender, signalSpec.constData(), receiver,
slotSpec.constData(), Qt::UniqueConnection);
}
static void connectMiniMapClickSignal(QObject *root, QObject *receiver,
const char *slotSignature) {
connectIfQmlSignalExists(root, "mapClicked(qreal,qreal)", receiver,
slotSignature);
connectIfQmlSignalExists(root, "mapClicked(double,double)", receiver,
slotSignature);
}
// --- 辅助函数:使用 QQuickView 创建透明 QML 容器 (macOS 更可靠) ---
static QWidget *createTransparentQmlContainer(const QUrl &source,
QQmlContext *context,
QWidget *parent,
QQuickView **outView = nullptr) {
// 创建 QQuickView
QQuickView *view = new QQuickView();
// 设置透明背景 (关键!)
view->setColor(Qt::transparent);
// 设置上下文属性
if (context) {
// 复制上下文属性到 view 的 rootContext
QQmlContext *viewContext = view->rootContext();
// 注意: 需要手动设置上下文属性
}
// 设置调整大小模式
view->setResizeMode(QQuickView::SizeRootObjectToView);
// 加载 QML
view->setSource(source);
// 创建容器 widget
QWidget *container = QWidget::createWindowContainer(view, parent);
// 设置容器透明属性
container->setAttribute(Qt::WA_TranslucentBackground);
container->setAttribute(Qt::WA_NoSystemBackground);
container->setAutoFillBackground(false);
// 返回 view 指针以便后续使用
if (outView) {
*outView = view;
}
return container;
}
void ensureAmmoPanel(QQuickWidget *&panel, QWidget *parent, GameData *gameData,
const QString &title, const QString &ammoName,
int commandType, int batchSize, int batchPrice,
int maxCount, QObject *receiver,
const char *requestSlot) {
if (!panel) {
panel = new QQuickWidget(parent);
panel->setResizeMode(QQuickWidget::SizeViewToRootObject);
panel->setAttribute(Qt::WA_TranslucentBackground);
panel->setClearColor(Qt::transparent);
panel->rootContext()->setContextProperty("gameData", gameData);
panel->setSource(QUrl("qrc:/qml/AmmoSupplyPanel.qml"));
panel->setFixedSize(520, 360);
if (QObject *root = panel->rootObject()) {
connectIfQmlSignalExists(root, "commonCommandRequested(int,int)",
receiver, requestSlot);
}
}
if (QObject *root = panel->rootObject()) {
root->setProperty("panelTitle", title);
root->setProperty("ammoName", ammoName);
root->setProperty("commandType", commandType);
root->setProperty("batchSize", batchSize);
root->setProperty("batchPrice", batchPrice);
root->setProperty("maxCount", maxCount);
}
}
// --- 构造函数 - 使用 C++11 类内初始化,简化初始化列表 ---
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
// 1. 核心模块初始化 (必须最先执行,创建 GameData)
initializeCore();
setupKeyboardMouseControlTimer();
setupOutpostForwardTimer();
// 2. UI初始化 (依赖 GameData)
setupFonts(); // 字体优先
applyStyles(); // 样式优先
initializeLayout();
setupTimer();
// 3. 信号-槽集中绑定
setupConnections();
// 先构造战术页,再按赛项和启动配置选择视图。
const QString defaultView = m_gameData && m_gameData->uses2027Protocol()
? QStringLiteral("tactical")
: QStringLiteral("map");
const QString startView = qEnvironmentVariable("RM_START_VIEW", defaultView).trimmed().toLower();
setTacticalLargeMapMode(startView == QStringLiteral("map"));
applyTacticalMode(startView != QStringLiteral("video"));
// 4. 启动服务(延迟到事件循环开始,避免构造函数中阻塞 UI 显示)
QTimer::singleShot(0, this, [this]() { startServices(); });
// 5. 安装全局事件过滤器 (用于拦截Tab键等全局快捷键)
QApplication::instance()->installEventFilter(this);
RM::InputHotkeyPolicy::enableMouseTrackingForWidgetTree(this);
QTimer::singleShot(0, this, [this]() {
if (QScreen *activeScreen = screen()) {
connect(activeScreen, &QScreen::geometryChanged, this,
[this](const QRect &geometry) {
if (isFullScreen()) {
setGeometry(geometry);
}
updatePopupResolutionScaling();
});
}
updatePopupResolutionScaling();
});
}
MainWindow::~MainWindow() { resetKeyboardMouseControlState(true); }
void MainWindow::toggleSettingsPanel() {
qInfo() << "[tactical-login] toggleSettingsPanel"
<< "settingsVisible="
<< (m_qmlSettingsPanel && m_qmlSettingsPanel->isVisible())
<< "status="
<< (m_qmlSettingsPanel ? static_cast<int>(m_qmlSettingsPanel->status())
: -1)
<< "hasRoot="
<< (m_qmlSettingsPanel && m_qmlSettingsPanel->rootObject())
<< "focusWidget=" << QApplication::focusWidget();
if (!m_qmlSettingsPanel) {
qWarning() << "[tactical-login] settings panel is null";
return;
}
const bool settingsVisible = m_qmlSettingsPanel->isVisible();
if (settingsVisible) {
safeQuickHide(m_qmlSettingsPanel);
updateSiloPanelVisibility();
setFocus();
m_settingsPanelVisible = false;
qDebug() << "Settings panel hidden";
return;
}
showPanel(m_qmlSettingsPanel);
m_settingsPanelVisible = true;
ensureInteractivePanelsRaisedIfVisible();
qDebug() << "Settings panel shown";
}
// --- 核心模块初始化 ---
void MainWindow::initializeCore() {
// 初始化比赛数据中心
m_gameData = new GameData(this);
m_gameData->setMatchProfile(
RM::parseMatchProfile(ConfigManager::instance().getMatchProfile()));
// 在创建界面和首个战况快照前确定登录车位。
const int initialRobotId = availableRobotId(ConfigManager::instance().getClientRobotId());
m_selectedRobotTypeFromSettings = settingsRobotTypeLabel(initialRobotId);
m_gameData->setCurrentRobotId(initialRobotId);
// 初始化网络管理器
m_networkManager = new NetworkManager(m_gameData, this);
#ifdef RM_HAS_MQTT
m_mqttReconnectTimer = new QTimer(this);
m_mqttReconnectTimer->setSingleShot(true);
m_mqttReconnectTimer->setInterval(kMqttReconnectIntervalMs);
connect(m_mqttReconnectTimer, &QTimer::timeout, this,
&MainWindow::triggerScheduledMqttReconnect);
#endif
// 初始化调试日志窗口
m_debugLogWidget = new DebugLogWidget(); // 独立窗口
// 默认兑换面板
m_exchangeQmlSource = "qrc:/qml/ExchangePanel.qml";
// 设置按键面板
setupKeyPanels();
// 设置音频
setupAudio();
#ifdef RM_HAS_AR_OVERLAY
// 初始化 AR 系统
m_arManager = new AROverlayManager(m_gameData, this);
connect(m_arManager, &AROverlayManager::initializationCompleted, this,
&MainWindow::onARInitializationCompleted);
#endif
// 初始化协议模拟器
m_simulator = new ProtocolSimulator(this);
// devhooks 依赖 m_videoBackground,需在 initializeLayout() 创建视频控件后再初始化
// 初始化 S1 协议管理器(可选,由 RM_S1_ENGINE_HOST 环境变量控制)
if (qEnvironmentVariableIsSet("RM_S1_ENGINE_HOST")) {
QString s1Host = QString::fromUtf8(qgetenv("RM_S1_ENGINE_HOST"));
quint16 s1Port = qEnvironmentVariableIntValue("RM_S1_ENGINE_PORT");
if (s1Port == 0) s1Port = 64998;
qInfo() << "MainWindow: S1 protocol manager is enabled, connecting to" << s1Host << ":" << s1Port;
m_s1ProtocolManager = new S1ProtocolManager(m_gameData, this);
// 配置凭据(可选,使用环境变量或默认值)
QString account = QString::fromUtf8(qgetenv("RM_S1_ACCOUNT"));
QString password = QString::fromUtf8(qgetenv("RM_S1_PASSWORD"));
if (!account.isEmpty() && !password.isEmpty()) {
m_s1ProtocolManager->setCredentials(account, password);
}
if (qEnvironmentVariableIsSet("RM_S1_TID")) {
m_s1ProtocolManager->setTid(qEnvironmentVariableIntValue("RM_S1_TID"));
}
if (qEnvironmentVariableIsSet("RM_S1_TEAMID")) {
m_s1ProtocolManager->setTeamId(qEnvironmentVariableIntValue("RM_S1_TEAMID"));
}
// 连接信号
connect(m_s1ProtocolManager, &S1ProtocolManager::connected, this, []() {
qInfo() << "[MainWindow] S1 protocol connected";
});
connect(m_s1ProtocolManager, &S1ProtocolManager::loginSucceeded, this, []() {
qInfo() << "[MainWindow] S1 protocol login succeeded";
});
connect(m_s1ProtocolManager, &S1ProtocolManager::loginFailed, this,
[](const QString &reason) {
qWarning() << "[MainWindow] S1 protocol login failed:" << reason;
});
connect(m_s1ProtocolManager, &S1ProtocolManager::gameStateReceived, this,
[](const QVariantMap &state) {
qDebug() << "[MainWindow] S1 game state received:" << state;
});
connect(m_s1ProtocolManager, &S1ProtocolManager::errorOccurred, this,
[](const QString &error) {
qWarning() << "[MainWindow] S1 protocol error:" << error;
});
// 开始连接
if (!m_s1ProtocolManager->connectToEngine(s1Host, s1Port)) {
qWarning() << "MainWindow: Failed to start S1 protocol manager";
delete m_s1ProtocolManager;
m_s1ProtocolManager = nullptr;
}
} else {
qDebug() << "MainWindow: S1 protocol manager is disabled (set RM_S1_ENGINE_HOST to enable)";
}
}
void MainWindow::setupDevHooks() {
#ifdef RM26_ENABLE_DEVTOOLS
if (m_devHooks) {
return;
}
if (!ClientDevHooks::isEnabled()) {
qDebug() << "MainWindow: Dev hooks are disabled (set RM_DEVTOOLS=1 to enable)";
return;
}
if (!m_gameData || !m_networkManager || !m_videoBackground) {
qWarning() << "MainWindow: Dev hooks prerequisites are not ready";
return;
}
VideoReceiver *videoReceiver = m_videoBackground->getVideoReceiver();
HevcDecoder *hevcDecoder = videoReceiver ? videoReceiver->decoder() : nullptr;
m_devHooks = new ClientDevHooks(m_gameData, m_networkManager, videoReceiver,
m_videoBackground, hevcDecoder, this, this);
if (!m_devHooks->start()) {
qWarning() << "MainWindow: Failed to start dev hooks";
delete m_devHooks;
m_devHooks = nullptr;
return;
}
#ifdef RM_HAS_MQTT
connect(m_networkManager, &NetworkManager::mqttMessageObserved, m_devHooks,
[this](const QString &topic, int payloadSize,
const QString &payloadSha1, qint64 receivedMs) {
if (!m_devHooks) {
return;
}
m_devHooks->recordTraceEvent(
QStringLiteral("mqtt_message_observed"),
QJsonObject{{"topic", topic},
{"payload_size", payloadSize},
{"payload_sha1", payloadSha1},
{"received_ms", receivedMs}});
});
#endif // RM_HAS_MQTT
qInfo() << "MainWindow: Dev hooks started on port" << m_devHooks->port();
#else
if (qEnvironmentVariableIsSet("RM_DEVTOOLS")) {
qWarning() << "MainWindow: RM26_ENABLE_DEVTOOLS is OFF, runtime dev hooks are not compiled";
}
#endif // RM26_ENABLE_DEVTOOLS
// MQTT 连接完成信号必须在 DEVTOOLS 外面,否则非dev构建下收不到回调
#ifdef RM_HAS_MQTT
connect(m_networkManager, &NetworkManager::mqttConnectCompleted, this,
[this](bool success, const QString &error) {
if (m_mqttIsBootstrapMode) {
onMqttBootstrapCompleted(success, error);
} else {
onMqttSwitchCompleted(success, error);
}
});
#endif // RM_HAS_MQTT
}
// --- 信号-槽集中绑定 ---
void MainWindow::setupConnections() {
// QML 上下文属性改在 initializeLayout 中绑定,确保初始化顺序正确。
// --- GameData 信号 ---
connect(m_gameData, &GameData::outpostDestroyed, this,
[this](bool isRed) {
if (m_battleMessage) {
m_battleMessage->showOutpostDestroyed(isRed);
}
});
m_lastEnemyOutpostHealthForDartSound = m_gameData->enemyOutpostHealth();
connect(m_gameData, &GameData::outpostHealthUpdated, this,
[this](TeamColor team) {
updateDartCanOpenSoundOnOutpostHealthChange(team);
});
connect(m_gameData, &GameData::baseDestroyed, this,
[this](bool isRed) {
if (m_battleMessage) {
m_battleMessage->showBaseDestroyed(isRed);
}
});
connect(m_gameData, &GameData::outpostStatusChanged, this,
[this](bool isRed, int status) {
updateOutpostReviveReminder(isRed, status);
if (m_battleMessage) {
//1:存活,解除无敌,中部装甲旋转;2:存活,解除无敌,中部装甲停转
if (status == 1 || status == 2) {
m_battleMessage->showOutpostStatusChange(isRed, status);
}
}
});
connect(m_gameData, &GameData::gameStageChanged, this,
[this](GameStage) {
const bool allyIsRed = m_gameData->currentRobotId() < 100;
const OutpostData &allyOutpost =
m_gameData->getOutpostByTeam(allyIsRed ? TeamColor::RED
: TeamColor::BLUE);
updateOutpostReviveReminder(allyIsRed, allyOutpost.status);
});
connect(m_gameData, &GameData::gameTimeUpdated, this, [this](quint16) {
const bool allyIsRed = m_gameData->currentRobotId() < 100;
const OutpostData &allyOutpost =
m_gameData->getOutpostByTeam(allyIsRed ? TeamColor::RED
: TeamColor::BLUE);
updateOutpostReviveReminder(allyIsRed, allyOutpost.status);
});
// 前哨站数据变化 -> 转发给机器人 (CustomControl 0x0311)
connect(m_gameData, &GameData::outpostStatusChanged, this,
[this](bool, int) { scheduleOutpostForward(); });
connect(m_gameData, &GameData::outpostHealthUpdated, this,
[this](TeamColor) { scheduleOutpostForward(); });
connect(m_gameData, &GameData::baseStatusChanged, this,
[this](bool isRed, int status) {
if (m_battleMessage) {
m_battleMessage->showBaseStatusChange(isRed, status);
}
});
connect(m_gameData, &GameData::gameStateUpdated, this,
&MainWindow::onGameStateUpdated);
connect(m_gameData, &GameData::runeVoicePromptRequested, this,
[this](int runeType, int remainingChances) {
playRuneVoicePrompt(runeType, remainingChances);
});
// 飞镖命中视图切回:需要跟随协议时间变化(gameTimeUpdated 每秒触发)而非仅
// gameStateUpdated(仅在阶段/比分/暂停等变化时触发),确保基于协议时间的计时。
connect(m_gameData, &GameData::gameTimeUpdated, this, [this](quint16) {
if (m_dartHitViewPending) {
checkDartHitViewSwitch();
}
});
connect(m_gameData, &GameData::myRobotUpdated, this, [this]() {
updateCurrentRobotPanel();
updateExchangeHintText(m_exchangeQmlSource);
syncSettingsPanelState();
});
connect(m_gameData, &GameData::gameResultReceived, this,
&MainWindow::onGameResultReceived);
// 击杀事件
connect(m_gameData, &GameData::killEventOccurred, this,
[this](const KillRecord &record) {
if (m_battleMessage) {
m_battleMessage->processKillEvent(record);
}
});
// --- 战场消息 (裁判警告等) ---
// 结构化判罚信息
connect(m_gameData, &GameData::refereeWarningUpdated, this,
[this](const robomaster::RefereeWarningData &data) {
if (m_battleMessage) {
m_battleMessage->showRefereeWarning(data.level(), data.offending_robot_id(),
data.penalty_effect_sec(), data.total_penalty_num());
}
});
// --- 飞镖目标选择状态同步 ---
connect(m_gameData, &GameData::siloCommandRequested, this,
[this](int targetId, bool open, bool launchConfirm) {
qDebug() << "[DartDebug] siloCommandRequested -> target:" << targetId
<< "open:" << open << "launchConfirm:" << launchConfirm;
if (!m_networkManager) {
qDebug() << "[DartDebug] siloCommandRequested -> NetworkManager unavailable";
return;
}
m_networkManager->sendDartCommand(static_cast<uint32_t>(targetId),
open, launchConfirm);
});
// --- 视频源变化 ---
connect(m_gameData, &GameData::videoSourceChanged, this,
&MainWindow::onVideoSourceChanged);
// --- 系统消息 ---
connect(m_gameData, &GameData::systemMessageReceived, this,
&MainWindow::onSystemMessageReceived);
connect(m_gameData, &GameData::officialEventPopupRequested, this,
&MainWindow::onOfficialEventPopupRequested);
connect(m_gameData, &GameData::runeActivable, this,
[this](int runeType) {
if (m_battleMessage) {
m_battleMessage->showRuneActivable(runeType);
}
});
connect(m_gameData, &GameData::runeActived, this,
[this](int runeType) {
if (m_battleMessage) {
m_battleMessage->showRuneActived(runeType);
}
if (m_gameData->airSupportIsBeingTargeted() == 1) {
return;
}
if (!m_qmlEventMessagePanel) {
return;
}
if (QObject *rootObject = m_qmlEventMessagePanel->rootObject()) {
rootObject->setProperty("panelMode", "rune");
}
const int displayToken =
m_qmlEventMessagePanel->property("displayToken").toInt() + 1;
m_qmlEventMessagePanel->setProperty("displayToken", displayToken);
m_qmlEventMessagePanel->show();
m_qmlEventMessagePanel->raise();
QTimer::singleShot(6000, this, [this, displayToken]() {
if (m_qmlEventMessagePanel &&
m_qmlEventMessagePanel->property("displayToken")
.toInt() == displayToken) {
m_qmlEventMessagePanel->hide();
}
});
});
connect(m_gameData, &GameData::dartMessageTriggered, this,
[this]() {
if (!m_qmlEventMessagePanel) {
return;
}
const bool laserTargeted =
m_gameData->airSupportIsBeingTargeted() == 1;
int displayToken =
m_qmlEventMessagePanel->property("displayToken").toInt();