swift
Loading...
Searching...
No Matches
simulatorfsxcommon.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <type_traits>
7
8#include <QElapsedTimer>
9#include <QPointer>
10#include <QStringBuilder>
11#include <QTimer>
12
14#include "simconnectsymbols.h"
15
16#include "config/buildconfig.h"
17#include "core/application.h"
19#include "misc/country.h"
21#include "misc/logmessage.h"
22#include "misc/math/mathutils.h"
33#include "misc/threadutils.h"
34#include "misc/verify.h"
35
36using namespace swift::config;
37using namespace swift::misc;
38using namespace swift::misc::aviation;
39using namespace swift::misc::physical_quantities;
40using namespace swift::misc::geo;
41using namespace swift::misc::network;
42using namespace swift::misc::math;
43using namespace swift::misc::simulation;
44using namespace swift::misc::simulation::fscommon;
45using namespace swift::misc::simulation::fsx;
46using namespace swift::misc::simulation::settings;
47using namespace swift::core;
48using namespace swift::simplugin::fscommon;
49
50namespace swift::simplugin::fsxcommon
51{
53 IOwnAircraftProvider *ownAircraftProvider,
54 IRemoteAircraftProvider *remoteAircraftProvider,
55 IClientProvider *clientProvider, QObject *parent)
56 : CSimulatorFsCommon(info, ownAircraftProvider, remoteAircraftProvider, clientProvider, parent)
57 {
58 Q_ASSERT_X(ownAircraftProvider, Q_FUNC_INFO, "Missing provider");
59 Q_ASSERT_X(remoteAircraftProvider, Q_FUNC_INFO, "Missing provider");
60 Q_ASSERT_X(sApp, Q_FUNC_INFO, "Missing global object");
61
62 m_simObjectTimer.setInterval(AddPendingAircraftIntervalMs);
63 // default model will be set in derived class
64
66 connect(&m_simObjectTimer, &QTimer::timeout, this, &CSimulatorFsxCommon::timerBasedObjectAddOrRemove);
67 }
68
70
71 bool CSimulatorFsxCommon::isConnected() const { return m_simConnected && m_hSimConnect; }
72
73 bool CSimulatorFsxCommon::isSimulating() const { return m_simSimulating && this->isConnected(); }
74
76 {
77 if (this->isConnected())
78 {
79 return true;
80 }
81 this->reset();
82
83 const HRESULT hr = SimConnect_Open(&m_hSimConnect, sApp->swiftVersionChar(), nullptr, 0, nullptr, 0);
84 if (isFailure(hr))
85 {
86 // reset state as expected for unconnected
87 this->reset();
88 return false;
89 }
90
91 // set structures and move on
92 this->triggerAutoTraceSendId(); // we trace the init phase, so in case something goes wrong there
93 this->initEvents();
94 this->initEventsP3D();
95 this->initDataDefinitionsWhenConnected();
96
97 m_timerId = this->startTimer(DispatchIntervalMs);
98 // do not start m_addPendingAircraftTimer here, it will be started when object was added
99 return true;
100 }
101
103 {
104 if (!m_simConnected)
105 {
106 return true;
107 }
108 m_simSimulating = false; // thread as stopped, just setting the flag here avoids overhead of on onSimStopped
109 m_traceAutoUntilTs = -1;
110 m_traceSendId = false;
111 this->reset(); // mark as disconnected and reset all values
112
113 if (m_hSimConnect)
114 {
115 SimConnect_Close(m_hSimConnect);
116 m_hSimConnect = nullptr;
117 m_simConnected = false;
118 }
119
120 // emit status
122 }
123
125 {
126 this->logAddingAircraftModel(newRemoteAircraft);
127 return this->physicallyAddRemoteAircraftImpl(newRemoteAircraft, ExternalCall);
128 }
129
130 bool CSimulatorFsxCommon::updateCOMFromSwiftToSimulator(const CFrequency &newFreq, const CFrequency &lastSimFreq,
131 CFrequency &last25kHzSimFreq, EventIds id)
132 {
133 if (newFreq == lastSimFreq)
134 {
135 return false;
136 }
137
138 if (CComSystem::isExclusiveWithin8_33kHzChannel(newFreq) && last25kHzSimFreq.isNull())
139 {
140 // Switch from 25 to 8.33
141 // Store last 25 kHz frequency and do not send to simulator
142 last25kHzSimFreq = lastSimFreq;
143 return false;
144 }
145
147 {
148 // Send to simulator
149 last25kHzSimFreq.setNull();
150 SimConnect_TransmitClientEvent(m_hSimConnect, 0, id, CBcdConversions::comFrequencyToBcdHz(newFreq),
151 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
152 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY);
153 return true;
154 }
155
156 // Already 8.33 -> nothing to do
157 return false;
158 }
159
161 const CIdentifier &originator)
162 {
163 if (originator == this->identifier())
164 {
165 return false;
166 }
167 if (!this->isSimulating())
168 {
169 return false;
170 }
171
172 // actually those data should be the same as ownAircraft
173 const CComSystem newCom1 = ownAircraft.getCom1System();
174 const CComSystem newCom2 = ownAircraft.getCom2System();
175 const CTransponder newTransponder = ownAircraft.getTransponder();
176
177 bool changed = false;
178
179 changed |= updateCOMFromSwiftToSimulator(newCom1.getFrequencyActive(), m_simCom1.getFrequencyActive(),
180 m_lastCom1Active, EventSetCom1Active);
181 changed |= updateCOMFromSwiftToSimulator(newCom1.getFrequencyStandby(), m_simCom1.getFrequencyStandby(),
182 m_lastCom1Standby, EventSetCom1Standby);
183 changed |= updateCOMFromSwiftToSimulator(newCom2.getFrequencyActive(), m_simCom2.getFrequencyActive(),
184 m_lastCom2Active, EventSetCom2Active);
185 changed |= updateCOMFromSwiftToSimulator(newCom2.getFrequencyStandby(), m_simCom2.getFrequencyStandby(),
186 m_lastCom2Standby, EventSetCom2Standby);
187
188 if (newTransponder.getTransponderMode() != m_simTransponder.getTransponderMode())
189 {
190 if (m_useSbOffsets)
191 {
192 byte ident = newTransponder.isIdentifying() ? 1U : 0U; // 1 is ident
193 byte standby = newTransponder.isInStandby() ? 1U : 0U; // 1 is standby
194 HRESULT hr = s_ok();
195
196 hr += SimConnect_SetClientData(m_hSimConnect, ClientAreaSquawkBox,
198 SIMCONNECT_CLIENT_DATA_SET_FLAG_DEFAULT, 0, 1, &ident);
199 hr += SimConnect_SetClientData(m_hSimConnect, ClientAreaSquawkBox,
201 SIMCONNECT_CLIENT_DATA_SET_FLAG_DEFAULT, 0, 1, &standby);
202 if (isFailure(hr))
203 {
205 CLogMessage(this).warning(u"Setting transponder mode failed (SB offsets)");
206 }
207 else
208 {
209 if (m_logSbOffsets)
210 {
211 const QString lm =
212 "SB sent: ident " % QString::number(ident) % u" standby " % QString::number(standby);
213 CLogMessage(this).info(lm);
214 }
215 }
216 changed = true;
217 }
218 else if (this->getSimulatorPluginInfo().getSimulatorInfo().isMSFS())
219 {
221 t.transponderMode = (newTransponder.isInStandby() ? 1 : 4);
222 t.ident = newTransponder.isIdentifying();
223
224 HRESULT hr = s_ok();
225
226 hr += SimConnect_SetDataOnSimObject(m_hSimConnect, CSimConnectDefinitions::DataTransponderModeMSFS,
227 SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_DATA_SET_FLAG_DEFAULT, 0,
229
230 if (isFailure(hr))
231 {
232 CLogMessage(this).warning(u"Setting transponder mode failed (MSFS)");
233 }
234
235 changed = true;
236 }
237 }
238
239 // avoid changes of cockpit back to old values due to an outdated read back value
240 if (changed)
241 {
242 m_skipCockpitUpdateCycles = SkipUpdateCyclesForCockpit;
243 }
244
245 // bye
246 return changed;
247 }
248
250 {
251 if (originator == this->identifier())
252 {
253 return false;
254 }
255 if (!this->isSimulating())
256 {
257 return false;
258 }
259
262 m_selcal = selcal;
263 return false;
264 }
265
267 {
268 QByteArray m = message.getMessage().toLatin1().constData();
269 m.append('\0');
270
271 SIMCONNECT_TEXT_TYPE type = SIMCONNECT_TEXT_TYPE_PRINT_BLACK;
272 switch (message.getSeverity())
273 {
275 case CStatusMessage::SeverityInfo: type = SIMCONNECT_TEXT_TYPE_PRINT_GREEN; break;
276 case CStatusMessage::SeverityWarning: type = SIMCONNECT_TEXT_TYPE_PRINT_YELLOW; break;
277 case CStatusMessage::SeverityError: type = SIMCONNECT_TEXT_TYPE_PRINT_RED; break;
278 }
279 const HRESULT hr =
280 SimConnect_Text(m_hSimConnect, type, 7.5, EventTextMessage, static_cast<DWORD>(m.size()), m.data());
281 Q_UNUSED(hr)
282 }
283
285 {
286 QByteArray m = message.asString(true, true).toLatin1().constData();
287 m.append('\0');
288
289 SIMCONNECT_TEXT_TYPE type = SIMCONNECT_TEXT_TYPE_PRINT_BLACK;
290 if (message.isSupervisorMessage())
291 {
292 type = SIMCONNECT_TEXT_TYPE_PRINT_RED;
293 }
294 else if (message.isPrivateMessage())
295 {
296 type = SIMCONNECT_TEXT_TYPE_PRINT_YELLOW;
297 }
298 else if (message.isRadioMessage())
299 {
300 type = SIMCONNECT_TEXT_TYPE_PRINT_GREEN;
301 }
302
303 const HRESULT hr =
304 SimConnect_Text(m_hSimConnect, type, 7.5, EventTextMessage, static_cast<DWORD>(m.size()), m.data());
305 Q_UNUSED(hr)
306 }
307
309 {
310 return m_simConnectObjects.contains(callsign);
311 }
312
314 {
315 CCallsignSet callsigns(m_simConnectObjects.keys());
316 callsigns.push_back(
317 m_addAgainAircraftWhenRemoved.getCallsigns()); // not really rendered right now, but very soon
318 callsigns.push_back(
319 m_addPendingAircraft.keys()); // not really rendered, but for the logic it should look like it is
320 return CCallsignSet(m_simConnectObjects.keys());
321 }
322
324 {
327 {
328 return msgs;
329 }
331 if (!m_simConnectObjects.isEmpty())
332 {
333 msgs.push_back(CStatusMessage(this).error(u"m_simConnectObjects not empty: '%1'")
334 << m_simConnectObjects.getAllCallsignStringsAsString(true));
335 }
336 if (!m_simConnectObjectsPositionAndPartsTraces.isEmpty())
337 {
338 msgs.push_back(CStatusMessage(this).error(u"m_simConnectObjectsPositionAndPartsTraces not empty: '%1'")
339 << m_simConnectObjectsPositionAndPartsTraces.getAllCallsignStringsAsString(true));
340 }
341 if (!m_addAgainAircraftWhenRemoved.isEmpty())
342 {
343 msgs.push_back(CStatusMessage(this).error(u"m_addAgainAircraftWhenRemoved not empty: '%1'")
344 << m_addAgainAircraftWhenRemoved.getCallsignStrings(true).join(", "));
345 }
346 return msgs;
347 }
348
350 {
351 static const QString specificInfo(
352 "dispatch #: %1 %2 times (cur/max): %3ms (%4ms) %5ms (%6ms) %7 %8 simData#: %9");
353 return specificInfo.arg(m_dispatchProcCount)
354 .arg(m_dispatchProcEmptyCount)
355 .arg(m_dispatchTimeMs)
356 .arg(m_dispatchProcTimeMs)
357 .arg(m_dispatchMaxTimeMs)
358 .arg(m_dispatchProcMaxTimeMs)
359 .arg(CSimConnectUtilities::simConnectReceiveIdToString(static_cast<DWORD>(m_dispatchReceiveIdMaxTime)),
360 requestIdToString(m_dispatchRequestIdMaxTime))
361 .arg(m_requestSimObjectDataCount);
362 }
363
364 bool CSimulatorFsxCommon::requestElevation(const ICoordinateGeodetic &reference, const CCallsign &aircraftCallsign)
365 {
366 // this is the 32bit FSX version, the P3D x64 is overridden!
367
369 {
370 return false;
371 }
372 if (!this->isUsingFsxTerrainProbe())
373 {
374 return false;
375 }
376 if (reference.isNull())
377 {
378 return false;
379 }
380 const CSimConnectObject simObject = m_simConnectObjects.getOldestNotPendingProbe(); // probes round robin
381 if (!simObject.isConfirmedAdded())
382 {
383 return false;
384 }
385 m_simConnectObjects[simObject.getCallsign()].resetTimestampToNow(); // mark probe as just used
386
387 CCoordinateGeodetic pos(reference);
388 pos.setGeodeticHeight(terrainProbeAltitude());
389
390 SIMCONNECT_DATA_INITPOSITION position = this->coordinateToFsxPosition(pos);
391 const HRESULT hr = this->logAndTraceSendId(
393 simObject.getObjectId(), 0, 0, sizeof(SIMCONNECT_DATA_INITPOSITION),
394 &position),
395 simObject, "Cannot request AI elevation", Q_FUNC_INFO, "SimConnect_SetDataOnSimObject");
396
397 if (isFailure(hr))
398 {
399 return false;
400 }
401
402 const bool ok = this->requestTerrainProbeData(simObject, aircraftCallsign);
403 if (ok)
404 {
405 emit this->requestedElevation(aircraftCallsign);
406 }
407 return ok;
408 }
409
411 {
412 if (m_traceSendId)
413 {
414 return true;
415 } // explicit
416 if (m_traceAutoUntilTs < 0)
417 {
418 return false;
419 } // no auto
420 const qint64 ts = QDateTime::currentMSecsSinceEpoch();
421 const bool trace = ts <= m_traceAutoUntilTs;
422 return trace;
423 }
424
426 {
427 m_traceSendId = trace;
428 m_traceAutoUntilTs = -1;
429 }
430
432 {
433 m_useAddSimulatedObj = enabled;
434 const CSimulatorInfo sim = this->getSimulatorInfo();
435 CFsxP3DSettings settings = m_detailsSettings.getSettings(sim);
436 settings.setAddingAsSimulatedObjectEnabled(enabled);
437 m_detailsSettings.setSettings(settings, sim);
438 }
439
441 {
442 m_useSbOffsets = enabled;
443 const CSimulatorInfo sim = this->getSimulatorInfo();
444 CFsxP3DSettings settings = m_detailsSettings.getSettings(sim);
445 settings.setSbOffsetsEnabled(enabled);
446 m_detailsSettings.setSettings(settings, sim);
447 }
448
450 {
451 m_dispatchProcCount = 0;
452 m_dispatchProcEmptyCount = 0;
453 m_dispatchMaxTimeMs = -1;
454 m_dispatchProcMaxTimeMs = -1;
455 m_dispatchTimeMs = -1;
456 m_dispatchProcTimeMs = -1;
457 m_requestSimObjectDataCount = 0;
458 m_dispatchReceiveIdLast = SIMCONNECT_RECV_ID_NULL;
459 m_dispatchReceiveIdMaxTime = SIMCONNECT_RECV_ID_NULL;
460 m_dispatchRequestIdLast = CSimConnectDefinitions::RequestEndMarker;
461 m_dispatchRequestIdMaxTime = CSimConnectDefinitions::RequestEndMarker;
462 CSimulatorPluginCommon::resetAircraftStatistics();
463 }
464
466 {
467 // toggled?
468 if (connected == !this->isFlightNetworkConnected())
469 {
470 // toggling, we trace for a while to better monitor those "critical" phases
472 }
473
474 // update SB area network connected
475 byte sbNetworkConnected = connected ? 1u : 0u;
476 const HRESULT hr = SimConnect_SetClientData(m_hSimConnect, ClientAreaSquawkBox,
478 SIMCONNECT_CLIENT_DATA_SET_FLAG_DEFAULT, 0, 1, &sbNetworkConnected);
479 if (isFailure(hr))
480 {
481 CLogMessage(this).warning(u"Setting network connected failed (SB offsets)");
482 }
483
485 }
486
488 {
489 if (!m_simConnectObjects.contains(callsign))
490 {
491 return CStatusMessageList();
492 }
494 this->getInterpolationSetupConsolidated(callsign, false);
495 return (m_simConnectObjects[callsign]).getInterpolationMessages(setup.getInterpolatorMode());
496 }
497
499 const CAircraftParts &parts)
500 {
501 if (!m_simConnectObjects.contains(callsign))
502 {
503 return false;
504 }
505 CSimConnectObject simObject = m_simConnectObjects.value(callsign);
506 int u = 0;
507 if (!parts.isNull())
508 {
509 this->sendRemoteAircraftPartsToSimulator(simObject, parts);
510 u++;
511 }
512 if (!situation.isNull())
513 {
514 SIMCONNECT_DATA_INITPOSITION position = this->aircraftSituationToFsxPosition(situation, true);
515 const bool doTraceSendId = this->isTracingSendId();
516 const HRESULT hr = this->logAndTraceSendId(
518 static_cast<SIMCONNECT_OBJECT_ID>(simObject.getObjectId()), 0, 0,
519 sizeof(SIMCONNECT_DATA_INITPOSITION), &position),
520 doTraceSendId, simObject, "Failed to set position", Q_FUNC_INFO, "SimConnect_SetDataOnSimObject");
521 if (hr == S_OK)
522 {
523 u++;
524 }
525 }
526 return u > 0;
527 }
528
530 {
532 if (isRequestForSimObjAircraft(requestId))
533 {
534 v = (requestId - RequestSimObjAircraftStart) / MaxSimObjAircraft;
535 }
536 else if (isRequestForSimObjTerrainProbe(requestId))
537 {
538 v = (requestId - RequestSimObjTerrainProbeStart) / MaxSimObjProbes;
539 }
540 Q_ASSERT_X(v <= CSimConnectDefinitions::SimObjectEndMarker, Q_FUNC_INFO, "Invalid value");
541 return static_cast<CSimConnectDefinitions::SimObjectRequest>(v);
542 }
543
544 bool CSimulatorFsxCommon::stillDisplayReceiveExceptions()
545 {
546 m_receiveExceptionCount++;
547 return m_receiveExceptionCount < IgnoreReceiveExceptions;
548 }
549
550 CSimConnectObject CSimulatorFsxCommon::getSimObjectForObjectId(DWORD objectId) const
551 {
552 return this->getSimConnectObjects().getSimObjectForObjectId(objectId);
553 }
554
555 void CSimulatorFsxCommon::setSimConnected()
556 {
557 m_simConnected = true;
560
561 // Internals depends on simulator data which take a while to be read
562 // this is a trick and I re-init again after a while (which is not really expensive)
563 const QPointer<CSimulatorFsxCommon> myself(this);
564 QTimer::singleShot(2500, this, [myself] {
565 if (!myself)
566 {
567 return;
568 }
569 myself->initSimulatorInternals();
570 });
571 }
572
573 void CSimulatorFsxCommon::onSimRunning()
574 {
575 const QPointer<CSimulatorFsxCommon> myself(this);
576 QTimer::singleShot(DeferSimulatingFlagMs, this, [=] {
577 if (!myself)
578 {
579 return;
580 }
581 m_simulatingChangedTs = QDateTime::currentMSecsSinceEpoch();
582 this->onSimRunningDeferred(m_simulatingChangedTs);
583 });
584 }
585
586 void CSimulatorFsxCommon::onSimRunningDeferred(qint64 referenceTs)
587 {
588 if (m_simSimulating)
589 {
590 return;
591 } // already simulatig
592 if (referenceTs != m_simulatingChangedTs)
593 {
594 return;
595 } // changed, so no longer valid
596 m_simSimulating = true; // only place where this should be set to true
597 m_simConnected = true;
598
599 const CFsxP3DSettings settings = m_detailsSettings.getSettings(this->getSimulatorInfo());
600 m_useAddSimulatedObj = settings.isAddingAsSimulatedObjectEnabled();
601 m_useSbOffsets = settings.isSbOffsetsEnabled();
602 if (this->getSimulatorPluginInfo().getSimulatorInfo().isMSFS() ||
603 this->getSimulatorPluginInfo().getSimulatorInfo().isMSFS2024())
604 {
605 m_useSbOffsets = false; // Always disable SbOffsets for MSFS. Using new transponder mode property directly
606 }
607
608 HRESULT hr = s_ok();
609 hr += this->logAndTraceSendId(
610 SimConnect_RequestDataOnSimObject(m_hSimConnect, CSimConnectDefinitions::RequestOwnAircraft,
611 CSimConnectDefinitions::DataOwnAircraft, SIMCONNECT_OBJECT_ID_USER,
612 SIMCONNECT_PERIOD_VISUAL_FRAME),
613 "Cannot request own aircraft data", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
614
615 hr += this->logAndTraceSendId(
616 SimConnect_RequestDataOnSimObject(m_hSimConnect, CSimConnectDefinitions::RequestOwnAircraftTitle,
617 CSimConnectDefinitions::DataOwnAircraftTitle, SIMCONNECT_OBJECT_ID_USER,
618 SIMCONNECT_PERIOD_SECOND, SIMCONNECT_DATA_REQUEST_FLAG_CHANGED),
619 "Cannot request title", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
620
621 // TODO TZ use MSFS2024 FSUIPC?
622 if (!this->getSimulatorPluginInfo().getSimulatorInfo().isMSFS() &&
623 !this->getSimulatorPluginInfo().getSimulatorInfo().isMSFS2024())
624 {
625 // Request the data from SB only when its changed and only ONCE so we don't have to run a 1sec event to
626 // get/set this info ;) there was a bug with SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET, see
627 // https://www.prepar3d.com/forum/viewtopic.php?t=124789
628 hr += this->logAndTraceSendId(SimConnect_RequestClientData(m_hSimConnect, ClientAreaSquawkBox,
631 SIMCONNECT_CLIENT_DATA_PERIOD_SECOND,
632 SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_CHANGED),
633 "Cannot request client data", Q_FUNC_INFO, "SimConnect_RequestClientData");
634 }
635 else
636 {
637 hr += this->logAndTraceSendId(
638 SimConnect_RequestDataOnSimObject(m_hSimConnect, CSimConnectDefinitions::RequestMSFSTransponder,
639 CSimConnectDefinitions::DataTransponderModeMSFS,
640 SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_VISUAL_FRAME,
641 SIMCONNECT_DATA_REQUEST_FLAG_CHANGED),
642 "Cannot request MSFS transponder data", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
643 }
644
645 if (isFailure(hr))
646 {
647 return;
648 }
649 this->emitSimulatorCombinedStatus(); // force sending status
650 }
651
652 void CSimulatorFsxCommon::onSimStopped()
653 {
654 // stopping events in FSX: Load menu, weather and season
655 CLogMessage(this).info(u"Simulator stopped: %1") << this->getSimulatorDetails();
656 const SimulatorStatus oldStatus = this->getSimulatorStatus();
657 m_simSimulating = false;
658 m_simulatingChangedTs = QDateTime::currentMSecsSinceEpoch();
659 this->emitSimulatorCombinedStatus(oldStatus);
660 }
661
662 void CSimulatorFsxCommon::onSimFrame()
663 {
665 {
666 return;
667 }
668 QPointer<CSimulatorFsxCommon> myself(this);
669 QTimer::singleShot(0, this, [=] {
670 // run decoupled from simconnect event queue
671 if (!myself)
672 {
673 return;
674 }
675 myself->updateRemoteAircraft();
676 });
677 }
678
679 void CSimulatorFsxCommon::onSimExit()
680 {
681 CLogMessage(this).info(u"Simulator exit: %1") << this->getSimulatorDetails();
682
683 // reset complete state, we are going down
684 m_simulatingChangedTs = QDateTime::currentMSecsSinceEpoch();
685 this->safeKillTimer();
686
687 // if called from dispatch function, avoid that SimConnectProc disconnects itself while in SimConnectProc
688 QPointer<CSimulatorFsxCommon> myself(this);
689 QTimer::singleShot(0, this, [=] {
690 if (!myself)
691 {
692 return;
693 }
694 this->disconnectFrom();
695 });
696 }
697
699 {
700 const SIMCONNECT_DATA_REQUEST_ID id = m_requestIdSimObjAircraft++;
701 if (id > RequestSimObjAircraftEnd)
702 {
703 m_requestIdSimObjAircraft = RequestSimObjAircraftStart;
704 }
705 return id;
706 }
707
709 {
710 const SIMCONNECT_DATA_REQUEST_ID id = m_requestIdSimObjTerrainProbe++;
711 if (id > RequestSimObjTerrainProbeEnd)
712 {
713 m_requestIdSimObjTerrainProbe = RequestSimObjTerrainProbeStart;
714 }
715 return id;
716 }
717
718 bool CSimulatorFsxCommon::releaseAIControl(const CSimConnectObject &simObject, SIMCONNECT_DATA_REQUEST_ID requestId)
719 {
720 const SIMCONNECT_OBJECT_ID objectId = simObject.getObjectId();
721 const HRESULT hr1 =
722 this->logAndTraceSendId(SimConnect_AIReleaseControl(m_hSimConnect, objectId, requestId), simObject,
723 "Release control", Q_FUNC_INFO, "SimConnect_AIReleaseControl");
724 const HRESULT hr2 =
725 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeLatLng, 1,
726 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
727 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
728 simObject, "EventFreezeLatLng", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
729 const HRESULT hr3 =
730 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeAlt, 1,
731 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
732 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
733 simObject, "EventFreezeAlt", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
734 const HRESULT hr4 =
735 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeAtt, 1,
736 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
737 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
738 simObject, "EventFreezeAtt", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
739
740 return isOk(hr1, hr2, hr3, hr4);
741 }
742
744 {
745 if (!simObject.hasValidRequestAndObjectId())
746 {
747 return false;
748 }
749 if (simObject.isPendingRemoved())
750 {
751 return false;
752 }
753 if (!m_simConnectObjects.contains(simObject.getCallsign()))
754 {
755 return false;
756 } // removed in meantime
757 return true;
758 }
759
761 {
762 return m_simConnectObjects.getSimObjectForOtherSimObject(trace.simObject);
763 }
764
766 {
767 return m_simConnectObjects.removeByOtherSimObject(trace.simObject);
768 }
769
771 {
772 // not in FSX
773 Q_UNUSED(simObject)
774 }
775
777 {
778 // not in FSX
779 Q_UNUSED(simObject)
780 }
781
783 {
784 if (m_traceSendId)
785 {
786 return false;
787 } // no need
789 {
790 return false;
791 }
792 const qint64 ts = QDateTime::currentMSecsSinceEpoch();
793 const qint64 traceUntil = traceTimeMs + ts;
794 if (traceUntil <= m_traceAutoUntilTs)
795 {
796 return false;
797 }
798 m_traceAutoUntilTs = traceUntil;
799
800 static const QString format("hh:mm:ss.zzz");
801 const QString untilString = QDateTime::fromMSecsSinceEpoch(traceUntil).toString(format);
802 CLogMessage(this).info(u"Triggered FSX/P3D auto trace until %1") << untilString;
803 const QPointer<CSimulatorFsxCommon> myself(this);
804 QTimer::singleShot(traceTimeMs * 1.2, this, [=] {
805 // triggered by mself (ts check), otherwise ignore
806 if (!myself)
807 {
808 return;
809 }
810 if (m_traceAutoUntilTs > QDateTime::currentMSecsSinceEpoch())
811 {
812 return;
813 }
814 if (m_traceAutoUntilTs < 0)
815 {
816 return;
817 } // alread off
818 CLogMessage(this).info(u"Auto trace id off");
819 m_traceAutoUntilTs = -1;
820 });
821 return true;
822 }
823
825 const DataDefinitionOwnAircraft &simulatorOwnAircraft)
826 {
827 aircraftSituation.setAltitude(
829 }
830
831 void CSimulatorFsxCommon::updateOwnAircraftFromSimulator(const DataDefinitionOwnAircraft &simulatorOwnAircraft)
832 {
833 const qint64 ts = QDateTime::currentMSecsSinceEpoch();
834
836 CCoordinateGeodetic position;
837 position.setLatitude(CLatitude(simulatorOwnAircraft.latitudeDeg, CAngleUnit::deg()));
838 position.setLongitude(CLongitude(simulatorOwnAircraft.longitudeDeg, CAngleUnit::deg()));
839
840 if (simulatorOwnAircraft.pitchDeg < -90.0 || simulatorOwnAircraft.pitchDeg >= 90.0)
841 {
842 CLogMessage(this).warning(u"FSX: Pitch value (own aircraft) out of limits: %1")
843 << simulatorOwnAircraft.pitchDeg;
844 }
845 CAircraftSituation aircraftSituation;
846 aircraftSituation.setMSecsSinceEpoch(ts);
847 aircraftSituation.setPosition(position);
848 // MSFS has inverted pitch and bank angles
849 aircraftSituation.setPitch(CAngle(-simulatorOwnAircraft.pitchDeg, CAngleUnit::deg()));
850 aircraftSituation.setBank(CAngle(-simulatorOwnAircraft.bankDeg, CAngleUnit::deg()));
851 aircraftSituation.setHeading(CHeading(simulatorOwnAircraft.trueHeadingDeg, CHeading::True, CAngleUnit::deg()));
852 aircraftSituation.setGroundSpeed(CSpeed(simulatorOwnAircraft.velocity, CSpeedUnit::kts()));
853 aircraftSituation.setGroundElevation(
856 setTrueAltitude(aircraftSituation, simulatorOwnAircraft);
857 aircraftSituation.setPressureAltitude(CAltitude(simulatorOwnAircraft.pressureAltitudeM, CAltitude::MeanSeaLevel,
859 // set on ground also in situation for consistency and future usage
860 // it is duplicated in parts
861 aircraftSituation.setOnGroundInfo(
862 { dtb(simulatorOwnAircraft.simOnGround) ? COnGroundInfo::OnGround : COnGroundInfo::NotOnGround,
864
865 CAircraftVelocity aircraftVelocity(
866 simulatorOwnAircraft.velocityWorldX, simulatorOwnAircraft.velocityWorldY,
867 simulatorOwnAircraft.velocityWorldZ, CSpeedUnit::ft_s(), simulatorOwnAircraft.rotationVelocityBodyX,
868 simulatorOwnAircraft.rotationVelocityBodyZ, simulatorOwnAircraft.rotationVelocityBodyY, CAngleUnit::rad(),
869 CTimeUnit::s());
870 aircraftSituation.setVelocity(aircraftVelocity);
871
872 const CAircraftLights lights(dtb(simulatorOwnAircraft.lightStrobe), dtb(simulatorOwnAircraft.lightLanding),
873 dtb(simulatorOwnAircraft.lightTaxi), dtb(simulatorOwnAircraft.lightBeacon),
874 dtb(simulatorOwnAircraft.lightNav), dtb(simulatorOwnAircraft.lightLogo));
875
876 CAircraftEngineList engines;
877 const QList<bool> helperList { dtb(simulatorOwnAircraft.engine1Combustion),
878 dtb(simulatorOwnAircraft.engine2Combustion),
879 dtb(simulatorOwnAircraft.engine3Combustion),
880 dtb(simulatorOwnAircraft.engine4Combustion) };
881 const QList<double> powerList { simulatorOwnAircraft.engine1RpmPct, simulatorOwnAircraft.engine2RpmPct,
882 simulatorOwnAircraft.engine3RpmPct, simulatorOwnAircraft.engine4RpmPct };
883
884 for (int index = 0; index < simulatorOwnAircraft.numberOfEngines; ++index)
885 {
886 // this is a bit of a guess, but it seems that idle is around 30% in the sim, so
887 // I use that as 0% for better resolution
888 // because we read "GENERAL ENG PCT MAX RPM" and send "GENERAL ENG THROTTLE LEVER POSITION"
889 const double factor = 30.0;
890 double engineRpm = (powerList.value(index, 0) - factor) * 100 / (100 - factor);
891 if (engineRpm < 0) engineRpm = 0;
892 engines.push_back(CAircraftEngine(index + 1, helperList.value(index, false), engineRpm));
893 }
894
895 const CAircraftParts parts(lights, dtb(simulatorOwnAircraft.gearHandlePosition),
896 qRound(simulatorOwnAircraft.flapsHandlePosition * 100),
897 dtb(simulatorOwnAircraft.spoilersHandlePosition), engines,
898 dtb(simulatorOwnAircraft.simOnGround), ts);
899
900 // set values
901 this->updateOwnSituationAndGroundElevation(aircraftSituation);
902 this->updateOwnParts(parts);
903
904 // When I change cockpit values in the sim (from GUI to simulator, not originating from simulator)
905 // it takes a little while before these values are set in the simulator.
906 // To avoid jitters, I wait some update cylces to stabilize the values
908 {
909 // defaults
910 CComSystem com1(myAircraft.getCom1System()); // set defaults
911 CComSystem com2(myAircraft.getCom2System());
912
913 // updates:
914 // https://www.fsdeveloper.com/forum/threads/com-unit-receiving-status-com-transmit-x-com-test-1-and-volume.445187/
915 // COM: If you're set to transmit on a unit, you WILL receive that unit.
916 // Otherwise if you're NOT set to transmit on a unit, then it will only receive if COM RECEIVE ALL is true.
917 // There is no control of COM volume.
918 com1.setFrequencyActive(CFrequency(simulatorOwnAircraft.com1ActiveMHz, CFrequencyUnit::MHz()));
919 com1.setFrequencyStandby(CFrequency(simulatorOwnAircraft.com1StandbyMHz, CFrequencyUnit::MHz()));
920 const bool comReceiveAll = dtb(simulatorOwnAircraft.comReceiveAll);
921 const bool com1Test = dtb(simulatorOwnAircraft.comTest1);
922 const bool com1Transmit = dtb(simulatorOwnAircraft.comTransmit1);
923 const int com1Status =
924 qRound(simulatorOwnAircraft.comStatus1); // Radio status flag : -1 =Invalid 0 = OK 1 = Does not exist 2
925 // = No electricity 3 = Failed
926 com1.setTransmitEnabled(com1Status == 0 && com1Transmit);
927 com1.setReceiveEnabled(com1Status == 0 && (comReceiveAll || com1Transmit));
928
929 const bool changedCom1Active =
930 myAircraft.getCom1System().getFrequencyActive() != com1.getFrequencyActive() &&
931 com1.getFrequencyActive() != m_lastCom1Active;
932 const bool changedCom1Standby =
933 myAircraft.getCom1System().getFrequencyStandby() != com1.getFrequencyStandby() &&
934 com1.getFrequencyStandby() != m_lastCom1Standby;
935
936 // Avoid overwrite of 8.33 kHz frequency with data from simulator
937 if (!changedCom1Active)
938 {
939 com1.setFrequencyActive(myAircraft.getCom1System().getFrequencyActive());
940 }
941 else
942 {
943 m_lastCom1Active.setNull();
944 }
945
946 if (!changedCom1Standby)
947 {
948 com1.setFrequencyStandby(myAircraft.getCom1System().getFrequencyStandby());
949 }
950 else
951 {
952 m_lastCom1Standby.setNull();
953 }
954
955 const bool changedCom1 = myAircraft.getCom1System() != com1;
956
957 m_simCom1 = com1;
958 Q_UNUSED(com1Test)
959
960 com2.setFrequencyActive(CFrequency(simulatorOwnAircraft.com2ActiveMHz, CFrequencyUnit::MHz()));
961 com2.setFrequencyStandby(CFrequency(simulatorOwnAircraft.com2StandbyMHz, CFrequencyUnit::MHz()));
962 const bool com2Test = dtb(simulatorOwnAircraft.comTest2);
963 const bool com2Transmit = dtb(simulatorOwnAircraft.comTransmit2);
964 const int com2Status =
965 qRound(simulatorOwnAircraft.comStatus2); // Radio status flag : -1 =Invalid 0 = OK 1 = Does not exist 2
966 // = No electricity 3 = Failed
967 com2.setTransmitEnabled(com2Status == 0 && com2Transmit);
968 com2.setReceiveEnabled(com2Status == 0 && (comReceiveAll || com2Transmit));
969 const bool changedCom2Active =
970 myAircraft.getCom2System().getFrequencyActive() != com2.getFrequencyActive() &&
971 com2.getFrequencyActive() != m_lastCom2Active;
972 const bool changedCom2Standby =
973 myAircraft.getCom2System().getFrequencyStandby() != com2.getFrequencyStandby() &&
974 com2.getFrequencyStandby() != m_lastCom2Standby;
975
976 // Avoid overwrite of 8.33 kHz frequency with data from simulator
977 if (!changedCom2Active)
978 {
979 com2.setFrequencyActive(myAircraft.getCom2System().getFrequencyActive());
980 }
981 else
982 {
983 m_lastCom2Active.setNull();
984 }
985
986 if (!changedCom2Standby)
987 {
988 com2.setFrequencyStandby(myAircraft.getCom2System().getFrequencyStandby());
989 }
990 else
991 {
992 m_lastCom2Standby.setNull();
993 }
994
995 const bool changedCom2 = myAircraft.getCom2System() != com2;
996
997 m_simCom2 = com2;
998 Q_UNUSED(com2Test)
999
1000 CTransponder transponder(myAircraft.getTransponder());
1001 transponder.setTransponderCode(qRound(simulatorOwnAircraft.transponderCode));
1002 m_simTransponder = transponder;
1003
1004 // if the simulator ever sends SELCAL, add it here.
1005 // m_selcal SELCAL sync.would go here
1006
1007 const bool changedXpr = (myAircraft.getTransponderCode() != transponder.getTransponderCode());
1008
1009 if (changedCom1 || changedCom2 || changedXpr)
1010 {
1011 // set in own aircraft provider
1012 this->updateCockpit(com1, com2, transponder, identifier());
1013 }
1014 }
1015 else
1016 {
1018 }
1019
1020 // slower updates
1021 if (m_ownAircraftUpdateCycles % 10 == 0)
1022 {
1023 // init terrain probes here has the advantage we can also switch it on/off at runtime
1025 {
1026 this->physicallyInitAITerrainProbes(position, 2); // init probe
1027 }
1028
1029 // SB3 offsets updating
1030 m_simulatorInternals.setValue(QStringLiteral("fsx/sb3"), boolToEnabledDisabled(m_useSbOffsets));
1031 m_simulatorInternals.setValue(QStringLiteral("fsx/sb3packets"), m_useSbOffsets ?
1032 QString::number(m_sbDataReceived) :
1033 QStringLiteral("disabled"));
1034
1035 // CG
1036 const CLength cg(simulatorOwnAircraft.cgToGroundFt, CLengthUnit::ft());
1037 this->updateOwnCG(cg);
1038
1039 // Simulated objects instead of NON ATC
1040 m_simulatorInternals.setValue(QStringLiteral("fsx/addAsSimulatedObject"),
1041 boolToEnabledDisabled(m_useAddSimulatedObj));
1042
1043 } // slow updates
1044
1045 m_ownAircraftUpdateCycles++; // with 50 updates/sec long enough even for 32bit
1046 }
1047
1048 void CSimulatorFsxCommon::triggerUpdateRemoteAircraftFromSimulator(const CSimConnectObject &simObject,
1049 const DataDefinitionPosData &remoteAircraftData)
1050 {
1051 if (this->isShuttingDownOrDisconnected())
1052 {
1053 return;
1054 }
1055 QPointer<CSimulatorFsxCommon> myself(this);
1056 QTimer::singleShot(0, this, [=] {
1057 if (!myself)
1058 {
1059 return;
1060 }
1061 myself->updateRemoteAircraftFromSimulator(simObject, remoteAircraftData);
1062 });
1063 }
1064
1065 void CSimulatorFsxCommon::triggerUpdateRemoteAircraftFromSimulator(
1066 const CSimConnectObject &simObject, const DataDefinitionRemoteAircraftModel &remoteAircraftModel)
1067 {
1068 if (this->isShuttingDownOrDisconnected())
1069 {
1070 return;
1071 }
1072 QPointer<CSimulatorFsxCommon> myself(this);
1073 QTimer::singleShot(0, this, [=] {
1074 if (!myself)
1075 {
1076 return;
1077 }
1078 myself->updateRemoteAircraftFromSimulator(simObject, remoteAircraftModel);
1079 });
1080 }
1081
1082 void CSimulatorFsxCommon::updateRemoteAircraftFromSimulator(const CSimConnectObject &simObject,
1083 const DataDefinitionPosData &remoteAircraftData)
1084 {
1085 if (this->isShuttingDownOrDisconnected())
1086 {
1087 return;
1088 }
1089
1090 // Near ground we use faster updates
1091 const CCallsign cs(simObject.getCallsign());
1092 CAircraftSituation lastSituation = m_lastSentSituations[cs];
1093 const bool moving = lastSituation.isMoving();
1094 const bool onGround = remoteAircraftData.isOnGround();
1095
1096 // CElevationPlane: deg, deg, feet
1097 // we only remember near ground
1098 const CElevationPlane elevation =
1099 CElevationPlane(remoteAircraftData.latitudeDeg, remoteAircraftData.longitudeDeg,
1100 remoteAircraftData.elevationFt, CElevationPlane::singlePointRadius());
1101 if (remoteAircraftData.aboveGroundFt() < 250)
1102 {
1103 const CLength cg(remoteAircraftData.cgToGroundFt, CLengthUnit::ft());
1104 this->rememberElevationAndSimulatorCG(cs, simObject.getAircraftModel(), onGround, elevation, cg);
1105 }
1106
1107 const bool log = this->isLogCallsign(cs);
1108 if (log)
1109 {
1110 // update lat/lng/alt with real data from sim
1111 const CAltitude alt(remoteAircraftData.altitudeFt, CAltitude::MeanSeaLevel, CAltitude::TrueAltitude,
1112 CLengthUnit::ft());
1113 lastSituation.setPosition(elevation);
1114 lastSituation.setAltitude(alt);
1115 lastSituation.setGroundElevation(elevation, CAircraftSituation::FromProvider);
1116 this->addLoopbackSituation(lastSituation);
1117 }
1118
1119 if (moving && remoteAircraftData.aboveGroundFt() <= 100.0)
1120 {
1121 // switch to fast updates
1122 if (simObject.getSimDataPeriod() != SIMCONNECT_PERIOD_VISUAL_FRAME)
1123 {
1124 this->requestPositionDataForSimObject(simObject, SIMCONNECT_PERIOD_VISUAL_FRAME);
1125 }
1126 }
1127 else
1128 {
1129 // switch to slow updates
1130 if (simObject.getSimDataPeriod() != SIMCONNECT_PERIOD_SECOND)
1131 {
1132 this->requestPositionDataForSimObject(simObject, SIMCONNECT_PERIOD_SECOND);
1133 }
1134 }
1135 }
1136
1137 void
1138 CSimulatorFsxCommon::updateRemoteAircraftFromSimulator(const CSimConnectObject &simObject,
1139 const DataDefinitionRemoteAircraftModel &remoteAircraftModel)
1140 {
1141 const CCallsign cs(simObject.getCallsign());
1142 if (!m_simConnectObjects.contains(cs))
1143 {
1144 return;
1145 } // no longer existing
1146 CSimConnectObject &so = m_simConnectObjects[cs];
1147 if (so.isPendingRemoved())
1148 {
1149 return;
1150 }
1151
1152 const QString modelString(remoteAircraftModel.title);
1153 const CLength cg(remoteAircraftModel.cgToGroundFt, CLengthUnit::ft());
1154 so.setAircraftCG(cg);
1155 so.setAircraftModelString(modelString);
1156
1157 // update in 2 providers
1158 this->rememberElevationAndSimulatorCG(cs, simObject.getAircraftModel(), false, CElevationPlane::null(),
1159 cg); // env. provider
1160 this->updateCGAndModelString(cs, cg, modelString); // remote aircraft provider
1161 }
1162
1163 void CSimulatorFsxCommon::updateProbeFromSimulator(const CCallsign &callsign,
1164 const DataDefinitionPosData &remoteAircraftData)
1165 {
1166 const CElevationPlane elevation(remoteAircraftData.latitudeDeg, remoteAircraftData.longitudeDeg,
1167 remoteAircraftData.elevationFt, CElevationPlane::singlePointRadius());
1168 this->callbackReceivedRequestedElevation(elevation, callsign, false);
1169 }
1170
1171 void CSimulatorFsxCommon::updateOwnAircraftFromSimulator(const DataDefinitionClientAreaSb &sbDataArea)
1172 {
1174 {
1175 return;
1176 }
1177
1178 // log SB offset
1179 if (m_logSbOffsets)
1180 {
1181 CLogMessage(this).info(u"SB from sim: " % sbDataArea.toQString());
1182 }
1183
1184 // SB XPDR mode
1186 if (!sbDataArea.isIdent())
1187 {
1188 newMode = sbDataArea.isStandby() ? CTransponder::StateStandby : CTransponder::ModeC;
1189 }
1190 const CSimulatedAircraft myAircraft(this->getOwnAircraft());
1191 const bool changed = (myAircraft.getTransponderMode() != newMode);
1192 if (!changed)
1193 {
1194 return;
1195 }
1196 CTransponder xpdr = myAircraft.getTransponder();
1197 xpdr.setTransponderMode(newMode);
1198 this->updateCockpit(myAircraft.getCom1System(), myAircraft.getCom2System(), xpdr, this->identifier());
1199 }
1200
1201 void CSimulatorFsxCommon::updateTransponderMode(const CTransponder::TransponderMode xpdrMode)
1202 {
1204 {
1205 return;
1206 }
1207 const CSimulatedAircraft myAircraft(this->getOwnAircraft());
1208 const bool changed = (myAircraft.getTransponderMode() != xpdrMode);
1209 if (!changed)
1210 {
1211 return;
1212 }
1213 CTransponder myXpdr = myAircraft.getTransponder();
1214 myXpdr.setTransponderMode(xpdrMode);
1215 this->updateCockpit(myAircraft.getCom1System(), myAircraft.getCom2System(), myXpdr, this->identifier());
1216 }
1217
1218 void CSimulatorFsxCommon::updateMSFSTransponderMode(const DataDefinitionMSFSTransponderMode transponderMode)
1219 {
1220 auto mode = CTransponder::StateIdent;
1221 if (!transponderMode.ident)
1222 {
1223 qRound(transponderMode.transponderMode) >= 3 ? mode = CTransponder::ModeC :
1225 }
1226 this->updateTransponderMode(mode);
1227 }
1228
1229 bool CSimulatorFsxCommon::simulatorReportedObjectAdded(DWORD objectId)
1230 {
1231 if (this->isShuttingDownOrDisconnected())
1232 {
1233 return true;
1234 } // pretend everything is fine
1235 const CSimConnectObject simObject = m_simConnectObjects.getSimObjectForObjectId(objectId);
1236 const CCallsign callsign(simObject.getCallsign());
1237 if (!simObject.hasValidRequestAndObjectId() || callsign.isEmpty())
1238 {
1239 return false;
1240 }
1241
1242 // we know the object has been created. But it can happen it is directly removed afterwards
1243 const CSimulatedAircraft verifyAircraft(simObject.getAircraft());
1244 const QPointer<CSimulatorFsxCommon> myself(this);
1245 QTimer::singleShot(1000, this, [=] {
1246 // verify aircraft and also triggers new add if required
1247 // do not do this in the event loop, so we do this deferred
1248 if (!myself || this->isShuttingDownOrDisconnected())
1249 {
1250 return;
1251 }
1252 this->verifyAddedRemoteAircraft(verifyAircraft);
1253 });
1254 return true;
1255 }
1256
1257 void CSimulatorFsxCommon::verifyAddedRemoteAircraft(const CSimulatedAircraft &remoteAircraftIn)
1258 {
1259 if (this->isShuttingDownOrDisconnected())
1260 {
1261 return;
1262 }
1263 if (remoteAircraftIn.isTerrainProbe())
1264 {
1265 this->verifyAddedTerrainProbe(remoteAircraftIn);
1266 return;
1267 }
1268
1269 CStatusMessage msg;
1270 CSimulatedAircraft remoteAircraft = remoteAircraftIn;
1271 const CCallsign callsign(remoteAircraft.getCallsign());
1272
1273 do
1274 {
1275 // no callsign
1276 if (callsign.isEmpty())
1277 {
1278 msg = CLogMessage(this).error(u"Cannot confirm AI object, empty callsign");
1279 break;
1280 }
1281
1282 // removed in meantime
1283 const bool aircraftStillInRange = this->isAircraftInRange(callsign);
1284 if (!m_simConnectObjects.contains(callsign))
1285 {
1286 if (aircraftStillInRange)
1287 {
1288 msg = CLogMessage(this).warning(
1289 u"Callsign '%1' removed in meantime from AI objects, but still in range")
1290 << callsign.toQString();
1291 }
1292 else
1293 {
1294 this->removeFromAddPendingAndAddAgainAircraft(callsign);
1295 msg = CLogMessage(this).info(u"Callsign '%1' removed in meantime and no longer in range")
1296 << callsign.toQString();
1297 }
1298 break;
1299 }
1300
1301 CSimConnectObject &simObject = m_simConnectObjects[callsign];
1302 remoteAircraft = simObject.getAircraft(); // update, if something has changed
1303
1304 if (!simObject.hasValidRequestAndObjectId() || simObject.isPendingRemoved())
1305 {
1306 msg = CStatusMessage(this).warning(u"Object for callsign '%1'/id: %2 removed in meantime/invalid")
1307 << callsign.toQString() << simObject.getObjectId();
1308 break;
1309 }
1310
1311 // P3D also has SimConnect_AIReleaseControlEx which also allows to destroy the aircraft
1312 const SIMCONNECT_DATA_REQUEST_ID requestReleaseId = this->obtainRequestIdForSimObjAircraft();
1313 const bool released = this->releaseAIControl(simObject, requestReleaseId);
1314
1315 if (!released)
1316 {
1317 msg = CStatusMessage(this).error(u"Cannot confirm model '%1' %2")
1318 << remoteAircraft.getModelString() << simObject.toQString();
1319 break;
1320 }
1321
1322 // confirm as added, this is also required to request light, etc
1323 Q_ASSERT_X(simObject.isPendingAdded(), Q_FUNC_INFO, "Already confirmed, this should be the only place");
1324 simObject.setConfirmedAdded(true); // aircraft
1325
1326 // request data on object
1327 this->requestPositionDataForSimObject(simObject);
1328 this->requestLightsForSimObject(simObject);
1329 this->requestModelInfoForSimObject(simObject);
1330
1331 this->removeFromAddPendingAndAddAgainAircraft(callsign); // no longer try to add
1332 const bool updated = this->updateAircraftRendered(callsign, true);
1333 if (updated)
1334 {
1335 static const QString debugMsg("CS: '%1' model: '%2' verified, request/object id: %3 %4");
1336 if (this->showDebugLogMessage())
1337 {
1338 this->debugLogMessage(Q_FUNC_INFO,
1339 debugMsg.arg(callsign.toQString(), remoteAircraft.getModelString())
1340 .arg(simObject.getRequestId())
1341 .arg(simObject.getObjectId()));
1342 }
1343
1344 this->sendRemoteAircraftAtcDataToSimulator(simObject);
1345 emit this->aircraftRenderingChanged(simObject.getAircraft());
1346 }
1347 else
1348 {
1349 CLogMessage(this).warning(
1350 u"Verified aircraft '%1' model '%2', request/object id: %3 %4 was already marked rendered")
1351 << callsign.asString() << remoteAircraft.getModelString() << simObject.getRequestId()
1352 << simObject.getObjectId();
1353 }
1354
1355 if (simObject.isConfirmedAdded() && simObject.getType() == CSimConnectObject::AircraftSimulatedObject)
1356 {
1357 CLogMessage(this).warning(u"Confirm added model '%1' '%2', but as '%3'")
1358 << remoteAircraft.getCallsignAsString() << remoteAircraft.getModelString()
1359 << simObject.getTypeAsString();
1360 this->triggerAutoTraceSendId(); // trace for some time (issues regarding this workaround?)
1361 simObject.decreaseAddingExceptions(); // if previously increased and now working, reset
1362 }
1363 }
1364 while (false);
1365
1366 // log errors and emit signal
1367 if (!msg.isEmpty() && msg.isWarningOrAbove())
1368 {
1370 emit this->physicallyAddingRemoteModelFailed(CSimulatedAircraft(), false, false, msg);
1371 }
1372
1373 // trigger adding pending aircraft if there are any
1374 if (!m_addPendingAircraft.isEmpty())
1375 {
1376 this->addPendingAircraftAfterAdded();
1377 }
1378 }
1379
1380 void CSimulatorFsxCommon::addingAircraftFailed(const CSimConnectObject &simObject)
1381 {
1383 {
1384 Q_ASSERT_X(simObject.isAircraft(), Q_FUNC_INFO, "Need aircraft");
1385 }
1386 if (!simObject.isAircraft())
1387 {
1388 return;
1389 }
1390
1391 // clean up
1392 m_simConnectObjects.removeByOtherSimObject(simObject);
1393 this->removeFromAddPendingAndAddAgainAircraft(simObject.getCallsign());
1394
1395 CLogMessage(this).warning(u"Model failed to be added: '%1' details: %2")
1396 << simObject.getAircraftModelString() << simObject.getAircraft().toQString(true);
1397 CStatusMessage verifyMsg;
1398 const bool verifiedAircraft = this->verifyFailedAircraftInfo(simObject, verifyMsg); // aircraft.cfg existing?
1399 if (!verifyMsg.isEmpty())
1400 {
1401 CLogMessage::preformatted(verifyMsg);
1402 }
1403
1404 CSimConnectObject simObjAddAgain(simObject);
1405 simObjAddAgain.increaseAddingExceptions();
1406 if (!simObject.hasCallsign())
1407 {
1408 SWIFT_VERIFY_X(false, Q_FUNC_INFO, "Missing callsign");
1409 return;
1410 }
1411
1412 if (!verifiedAircraft || simObjAddAgain.getAddingExceptions() > ThresholdAddException)
1413 {
1414 const CStatusMessage msg =
1415 verifiedAircraft ?
1416 CLogMessage(this).warning(u"Model '%1' %2 failed %3 time(s) before and will be disabled")
1417 << simObjAddAgain.getAircraftModelString() << simObjAddAgain.toQString()
1418 << simObjAddAgain.getAddingExceptions() :
1419 CLogMessage(this).warning(u"Model '%1' %2 failed verification and will be disabled")
1420 << simObjAddAgain.getAircraftModelString() << simObjAddAgain.toQString();
1421 this->updateAircraftEnabled(simObjAddAgain.getCallsign(), false); // disable
1422 emit this->physicallyAddingRemoteModelFailed(simObjAddAgain.getAircraft(), true, true,
1423 msg); // verify failed
1424 }
1425 else
1426 {
1427 CLogMessage(this).info(u"Will try '%1' again, aircraft: %2")
1428 << simObject.getAircraftModelString() << simObject.getAircraft().toQString(true);
1429 QPointer<CSimulatorFsxCommon> myself(this);
1430 QTimer::singleShot(2000, this, [=] {
1431 if (!myself)
1432 {
1433 return;
1434 }
1435 if (this->isShuttingDownOrDisconnected())
1436 {
1437 return;
1438 }
1439 m_addPendingAircraft.insert(simObjAddAgain, true); // add failed object
1440 });
1441 }
1442 }
1443
1444 bool CSimulatorFsxCommon::verifyFailedAircraftInfo(const CSimConnectObject &simObject,
1445 CStatusMessage &details) const
1446 {
1447 CAircraftModel model = simObject.getAircraftModel();
1448
1449 const CSpecializedSimulatorSettings settings = this->getSimulatorSettings();
1450 const bool fileExists = CFsCommonUtil::adjustFileDirectory(model, settings.getModelDirectoriesOrDefault());
1451 bool canBeUsed = true;
1452
1453 CStatusMessageList messages;
1454 if (fileExists)
1455 {
1456 // we can access the aircraft.cfg file
1457 bool parsed = false;
1458 const CAircraftCfgEntriesList entries =
1460 if (parsed)
1461 {
1462 if (entries.containsTitle(model.getModelString()))
1463 {
1464 messages.push_back(CStatusMessage(this).info(u"Model '%1' exists in re-parsed file '%2'.")
1465 << model.getModelString() << model.getFileName());
1466 canBeUsed = true; // all OK
1467 }
1468 else
1469 {
1470 messages.push_back(
1471 CStatusMessage(this).warning(u"Model '%1' no longer in re-parsed file '%2'. Models are: %3.")
1472 << model.getModelString() << model.getFileName() << entries.getTitlesAsString(true));
1473 canBeUsed = false; // absolute no chance to use that one
1474 }
1475 }
1476 else
1477 {
1478 messages.push_back(CStatusMessage(this).warning(u"CS: '%1' Cannot parse file: '%2' (existing: %3)")
1479 << model.getCallsign().asString() << model.getFileName()
1481 }
1482 }
1483 else
1484 {
1485 // the file cannot be accessed right now, but the pilot client necessarily has access to them
1486 // so we just carry on
1487 messages = model.verifyModelData();
1488 }
1489
1490 // as single message
1491 details = messages.toSingleMessage();
1492
1493 // status
1494 return canBeUsed;
1495 }
1496
1497 bool CSimulatorFsxCommon::logVerifyFailedAircraftInfo(const CSimConnectObject &simObject) const
1498 {
1499 CStatusMessage m;
1500 const bool r = verifyFailedAircraftInfo(simObject, m);
1501 if (!m.isEmpty())
1502 {
1504 }
1505 return r;
1506 }
1507
1508 void CSimulatorFsxCommon::verifyAddedTerrainProbe(const CSimulatedAircraft &remoteAircraftIn)
1509 {
1510 bool verified = false;
1511 CCallsign cs;
1512
1513 // no simObject reference outside that block, because it will be deleted
1514 {
1515 CSimConnectObject &simObject = m_simConnectObjects[remoteAircraftIn.getCallsign()];
1516 simObject.setConfirmedAdded(true); // terrain probe
1517 simObject.resetTimestampToNow();
1518 cs = simObject.getCallsign();
1519 CLogMessage(this).info(u"Probe: '%1' '%2' confirmed, %3")
1520 << simObject.getCallsignAsString() << simObject.getAircraftModelString() << simObject.toQString();
1521
1522 // fails for probe
1523 // SIMCONNECT_DATA_REQUEST_ID requestId = this->obtainRequestIdForSimObjTerrainProbe();
1524 // verified = this->releaseAIControl(simObject, requestId); // release probe
1525 verified = true;
1526 }
1527
1528 if (!verified) // cppcheck-suppress knownConditionTrueFalse
1529 {
1530 CLogMessage(this).info(u"Disable probes: '%1' failed to relase control") << cs.asString();
1531 m_useFsxTerrainProbe = false;
1532 }
1533
1534 // trigger new adding from pending if any
1535 if (!m_addPendingAircraft.isEmpty())
1536 {
1537 this->addPendingAircraftAfterAdded();
1538 }
1539 }
1540
1541 void CSimulatorFsxCommon::timerBasedObjectAddOrRemove()
1542 {
1543 this->addPendingAircraft(AddByTimer);
1544 if (!this->isTestMode())
1545 {
1546 this->physicallyRemoveAircraftNotInProvider();
1547 }
1548 }
1549
1550 void CSimulatorFsxCommon::addPendingAircraftAfterAdded()
1551 {
1552 this->addPendingAircraft(AddAfterAdded); // addPendingAircraft is already "non blocking"
1553 }
1554
1555 void CSimulatorFsxCommon::addPendingAircraft(AircraftAddMode mode)
1556 {
1557 if (m_addPendingAircraft.isEmpty())
1558 {
1559 return;
1560 }
1561 const CCallsignSet aircraftCallsignsInRange(this->getAircraftInRangeCallsigns());
1562 CSimulatedAircraftList toBeAddedAircraft; // aircraft still to be added
1563 CCallsignSet toBeRemovedCallsigns;
1564
1565 for (const CSimConnectObject &pendingSimObj : std::as_const(m_addPendingAircraft))
1566 {
1567 SWIFT_VERIFY_X(pendingSimObj.hasCallsign(), Q_FUNC_INFO, "missing callsign");
1568 if (!pendingSimObj.hasCallsign())
1569 {
1570 continue;
1571 }
1572 if (pendingSimObj.isTerrainProbe() || aircraftCallsignsInRange.contains(pendingSimObj.getCallsign()))
1573 {
1574 toBeAddedAircraft.push_back(pendingSimObj.getAircraft());
1575 }
1576 else
1577 {
1578 toBeRemovedCallsigns.push_back(pendingSimObj.getCallsign());
1579 }
1580 }
1581
1582 // no longer required to be added
1583 m_addPendingAircraft.removeCallsigns(toBeRemovedCallsigns);
1584 m_addAgainAircraftWhenRemoved.removeByCallsigns(toBeRemovedCallsigns);
1585
1586 // add aircraft, but "non blocking"
1587 if (!toBeAddedAircraft.isEmpty())
1588 {
1589 const CSimConnectObject oldestSimObject = m_addPendingAircraft.getOldestObject();
1590 const CSimulatedAircraft nextPendingAircraft = oldestSimObject.getAircraft();
1591 if (nextPendingAircraft.hasModelString())
1592 {
1593 const QPointer<CSimulatorFsxCommon> myself(this);
1594 QTimer::singleShot(100, this, [=] {
1595 if (!myself)
1596 {
1597 return;
1598 }
1599 if (this->isShuttingDownDisconnectedOrNoAircraft(nextPendingAircraft.isTerrainProbe()))
1600 {
1601 return;
1602 }
1603 this->physicallyAddRemoteAircraftImpl(nextPendingAircraft, mode, oldestSimObject);
1604 });
1605 }
1606 else
1607 {
1608 CLogMessage(this).warning(u"Pending aircraft without model string will be removed");
1609 m_addPendingAircraft.removeByOtherSimObject(oldestSimObject);
1610 }
1611 }
1612 }
1613
1614 CSimConnectObject CSimulatorFsxCommon::removeFromAddPendingAndAddAgainAircraft(const CCallsign &callsign)
1615 {
1616 CSimConnectObject simObjectOld;
1617 if (callsign.isEmpty())
1618 {
1619 return simObjectOld;
1620 }
1621
1622 m_addAgainAircraftWhenRemoved.removeByCallsign(callsign);
1623 if (m_addPendingAircraft.contains(callsign))
1624 {
1625 simObjectOld = m_addPendingAircraft[callsign];
1626 m_addPendingAircraft.remove(callsign);
1627 }
1628 return simObjectOld;
1629 }
1630
1631 bool CSimulatorFsxCommon::simulatorReportedObjectRemoved(DWORD objectID)
1632 {
1633 if (this->isShuttingDownOrDisconnected())
1634 {
1635 return false;
1636 }
1637 CSimConnectObject simObject = m_simConnectObjects.getSimObjectForObjectId(objectID);
1638 if (!simObject.hasValidRequestAndObjectId())
1639 {
1640 return false;
1641 } // object id from somewhere else
1642
1643 const CCallsign callsign(simObject.getCallsign());
1644 Q_ASSERT_X(!callsign.isEmpty(), Q_FUNC_INFO, "Missing callsign for removed object");
1645
1646 if (simObject.isPendingRemoved())
1647 {
1648 // good case, object has been removed
1649 // we can remove the simulator object
1650 }
1651 else
1652 {
1653 // object was removed, but removal was not requested by us
1654 // this means we are out of the reality bubble or something else went wrong
1655 // Possible reasons:
1656 // 1) out of reality bubble, because we move to another airport or other reasons
1657 // 2) wrong position (in ground etc.)
1658 // 3) Simulator not running (ie in stopped mode)
1659 CStatusMessage msg;
1660 if (!simObject.getAircraftModelString().isEmpty() &&
1661 simObject.getAddingDirectlyRemoved() < ThresholdAddedAndDirectlyRemoved)
1662 {
1663 simObject.increaseAddingDirectlyRemoved();
1664 m_addPendingAircraft.insert(simObject, true); // insert removed objects and update ts
1665 m_simConnectObjects.removeByOtherSimObject(
1666 simObject); // we have it in pending now, no need to keep it in this list
1667
1668 const CInterpolationAndRenderingSetupPerCallsign setup =
1670 msg = CLogMessage(this).warning(u"Aircraft removed, '%1' '%2' object id '%3' out of reality bubble or "
1671 u"other reason. Interpolator: '%4'")
1672 << callsign.toQString() << simObject.getAircraftModelString() << objectID
1673 << simObject.getInterpolatorInfo(setup.getInterpolatorMode());
1674 }
1675 else if (simObject.getAddingDirectlyRemoved() < ThresholdAddedAndDirectlyRemoved)
1676 {
1677 const CStatusMessage m =
1678 CLogMessage(this).warning(
1679 u"Aircraft removed again multiple times and will be disabled, '%1' '%2' object id '%3'")
1680 << callsign.toQString() << simObject.getAircraftModelString() << objectID;
1681 this->updateAircraftEnabled(simObject.getCallsign(), false);
1682 emit this->physicallyAddingRemoteModelFailed(simObject.getAircraft(), true, true,
1683 m); // directly removed again
1684 }
1685 else
1686 {
1687 msg = CLogMessage(this).warning(
1688 u"Removed '%1' from simulator, but was not initiated by us (swift): %1 '%2' object id %3")
1689 << callsign.toQString() << simObject.getAircraftModelString() << objectID;
1690 }
1691
1692 // in all cases add verification details
1693 this->logVerifyFailedAircraftInfo(simObject);
1694
1695 // relay messages
1696 if (!msg.isEmpty())
1697 {
1698 emit this->driverMessages(msg);
1699 }
1700 }
1701
1702 // in all cases we remove the object
1703 const int c = m_simConnectObjects.remove(callsign);
1704 const bool removedAny = (c > 0);
1705 const bool updated = this->updateAircraftRendered(simObject.getCallsign(), false);
1706 if (updated)
1707 {
1708 emit this->aircraftRenderingChanged(simObject.getAircraft());
1709 }
1710
1711 // models we have to add again after removing
1712 if (m_addAgainAircraftWhenRemoved.containsCallsign(callsign))
1713 {
1714 const CSimulatedAircraft aircraftAddAgain = m_addAgainAircraftWhenRemoved.findFirstByCallsign(callsign);
1715 m_addAgainAircraftWhenRemoved.removeByCallsign(callsign);
1716 QPointer<CSimulatorFsxCommon> myself(this);
1717 QTimer::singleShot(2500, this, [=] {
1718 if (!myself)
1719 {
1720 return;
1721 }
1722 if (this->isShuttingDownOrDisconnected())
1723 {
1724 return;
1725 }
1726 myself->physicallyAddRemoteAircraftImpl(aircraftAddAgain, AddedAfterRemoved);
1727 });
1728 }
1729 return removedAny;
1730 }
1731
1732 bool CSimulatorFsxCommon::setSimConnectObjectId(DWORD requestId, DWORD objectId)
1733 {
1734 return m_simConnectObjects.setSimConnectObjectIdForRequestId(requestId, objectId);
1735 }
1736
1737 bool CSimulatorFsxCommon::setCurrentLights(const CCallsign &callsign, const CAircraftLights &lights)
1738 {
1739 if (!m_simConnectObjects.contains(callsign))
1740 {
1741 return false;
1742 }
1743 m_simConnectObjects[callsign].setCurrentLightsInSimulator(lights);
1744 return true;
1745 }
1746
1747 bool CSimulatorFsxCommon::setLightsAsSent(const CCallsign &callsign, const CAircraftLights &lights)
1748 {
1749 if (!m_simConnectObjects.contains(callsign))
1750 {
1751 return false;
1752 }
1753 m_simConnectObjects[callsign].setLightsAsSent(lights);
1754 return true;
1755 }
1756
1758 {
1759 Q_UNUSED(event)
1760 if (this->isShuttingDown())
1761 {
1762 return;
1763 }
1764 this->dispatch();
1765 }
1766
1768
1770 {
1771 // .driver sendid on|off
1772 if (parser.matchesPart(1, "sendid") && parser.hasPart(2))
1773 {
1774 const bool trace = parser.toBool(2);
1775 this->setTraceSendId(trace);
1776 CLogMessage(this, CLogCategories::cmdLine()).info(u"Tracing %1 driver sendIds is '%2'")
1777 << this->getSimulatorPluginInfo().getIdentifier() << boolToOnOff(trace);
1778 return true;
1779 }
1780
1781 // .driver sboffsets on|off
1782 if (parser.matchesPart(1, "sboffsets") && parser.hasPart(2))
1783 {
1784 const bool on = parser.toBool(2);
1785 this->setUsingSbOffsetValues(on);
1786 CLogMessage(this, CLogCategories::cmdLine()).info(u"SB offsets is '%1'") << boolToOnOff(on);
1787 return true;
1788 }
1789
1790 // .driver sblog on|off
1791 if (parser.matchesPart(1, "sblog") && parser.hasPart(2))
1792 {
1793 const bool on = parser.toBool(2);
1794 m_logSbOffsets = on;
1795 CLogMessage(this, CLogCategories::cmdLine()).info(u"SB log. offsets is '%1'") << boolToOnOff(on);
1796 return true;
1797 }
1798
1799 return CSimulatorFsCommon::parseDetails(parser);
1800 }
1801
1803 {
1804 if (CSimpleCommandParser::registered("swift::simplugin::fsxcommon::CSimulatorFsxCommon::CSimulatorFsxCommon"))
1805 {
1806 return;
1807 }
1808 CSimpleCommandParser::registerCommand({ ".drv", "alias: .driver .plugin" });
1809 CSimpleCommandParser::registerCommand({ ".drv sendid on|off", "Trace simConnect sendId on|off" });
1810 CSimpleCommandParser::registerCommand({ ".drv sboffsets on|off", "SB offsets via simConnect on|off" });
1811 CSimpleCommandParser::registerCommand({ ".drv sblog on|off", "SB offsets logging on|off" });
1812 }
1813
1815 {
1816 const CCallsign cs = m_pendingProbeRequests.value(requestId);
1817 if (remove)
1818 {
1819 m_pendingProbeRequests.remove(requestId);
1820 }
1821 return cs;
1822 }
1823
1824 const QString &CSimulatorFsxCommon::modeToString(CSimulatorFsxCommon::AircraftAddMode mode)
1825 {
1826 static const QString e("external call");
1827 static const QString pt("add pending by timer");
1828 static const QString oa("add pending after object added");
1829 static const QString ar("add again after removed");
1830 static const QString dontKnow("???");
1831
1832 switch (mode)
1833 {
1834 case ExternalCall: return e;
1835 case AddByTimer: return pt;
1836 case AddAfterAdded: return oa;
1837 case AddedAfterRemoved: return ar;
1838 default: break;
1839 }
1840 return dontKnow;
1841 }
1842
1843 void CSimulatorFsxCommon::dispatch()
1844 {
1845 // call CSimulatorFsxCommon::SimConnectProc or specialized P3D version
1846 Q_ASSERT_X(m_dispatchProc, Q_FUNC_INFO, "Missing DispatchProc");
1847
1848 // statistics
1849 m_dispatchReceiveIdLast = SIMCONNECT_RECV_ID_NULL;
1850 m_dispatchRequestIdLast = CSimConnectDefinitions::RequestEndMarker;
1851 const qint64 start = QDateTime::currentMSecsSinceEpoch();
1852
1853 // process
1854 const HRESULT hr = SimConnect_CallDispatch(m_hSimConnect, m_dispatchProc, this);
1855
1856 // statistics
1857 const qint64 end = QDateTime::currentMSecsSinceEpoch();
1858 m_dispatchTimeMs = end - start; // cppcheck-suppress duplicateExpression
1859 if (m_dispatchMaxTimeMs < m_dispatchTimeMs)
1860 {
1861 m_dispatchMaxTimeMs = m_dispatchTimeMs;
1862 m_dispatchReceiveIdMaxTime = m_dispatchReceiveIdLast;
1863 m_dispatchRequestIdMaxTime = m_dispatchRequestIdLast;
1864 }
1865
1866 // error handling
1867 if (isFailure(hr))
1868 {
1869 // on FSX we normally receive this one here when simulator goes down, and NOT onSimExit
1870 // in that case sim status is Connected, but not PAUSED or SIMULATING
1871 const SimulatorStatus simStatus = this->getSimulatorStatus();
1872 const bool disconnectedOrNotSimulating =
1873 simStatus.testFlag(Disconnected) || !simStatus.testFlag(Simulating);
1874
1875 m_dispatchErrors++;
1876 this->triggerAutoTraceSendId();
1877 if (m_dispatchErrors == 2)
1878 {
1879 // 2nd time, an error / avoid multiple messages
1880 // idea: if it happens once ignore
1881 const QString msg =
1882 QStringLiteral(u"%1: Dispatch error, sim.status: %2")
1883 .arg(this->getSimulatorPluginInfo().getIdentifier(), ISimulator::statusToString(simStatus));
1884 CLogMessage(this).log(
1885 disconnectedOrNotSimulating ? CStatusMessage::SeverityWarning : CStatusMessage::SeverityError, msg);
1886 }
1887 else if (m_dispatchErrors > 5)
1888 {
1889 // this normally happens during a FSX crash or shutdown with simconnect
1890 const QString msg =
1891 QStringLiteral(u"%1: Multiple dispatch errors, disconnecting. Sim.status: %2")
1892 .arg(this->getSimulatorPluginInfo().getIdentifier(), ISimulator::statusToString(simStatus));
1893 CLogMessage(this).log(
1894 disconnectedOrNotSimulating ? CStatusMessage::SeverityWarning : CStatusMessage::SeverityError, msg);
1895 this->disconnectFrom();
1896 }
1897 return;
1898 }
1899 m_dispatchErrors = 0;
1900 }
1901
1902 bool CSimulatorFsxCommon::physicallyAddRemoteAircraftImpl(const CSimulatedAircraft &newRemoteAircraft,
1903 CSimulatorFsxCommon::AircraftAddMode addMode,
1904 const CSimConnectObject &correspondingSimObject)
1905 {
1906 const CCallsign callsign(newRemoteAircraft.getCallsign());
1907 const bool probe = newRemoteAircraft.isTerrainProbe();
1908
1909 // entry checks
1910 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
1911 Q_ASSERT_X(!callsign.isEmpty(), Q_FUNC_INFO, "empty callsign");
1912 Q_ASSERT_X(newRemoteAircraft.hasModelString(), Q_FUNC_INFO, "missing model string");
1913
1914 // reset timer
1915 m_simObjectTimer.start(AddPendingAircraftIntervalMs); // restart
1916
1917 // remove outdated objects
1918 const CSimConnectObjects outdatedAdded =
1919 m_simConnectObjects.removeOutdatedPendingAdded(CSimConnectObject::AllTypes);
1920 if (!outdatedAdded.isEmpty())
1921 {
1922 const CCallsignSet callsigns = outdatedAdded.getAllCallsigns(false);
1923 CLogMessage(this).warning(u"Removed %1 outdated object(s) pending for added: %2")
1924 << outdatedAdded.size() << callsigns.getCallsignsAsString(true);
1925 this->updateMultipleAircraftEnabled(callsigns, false);
1926
1927 static const QString msgText("%1 outdated adding, %2");
1928 for (const CSimConnectObject &simObjOutdated : outdatedAdded)
1929 {
1930 const CStatusMessage msg = CStatusMessage(this).warning(
1931 msgText.arg(simObjOutdated.getCallsign().asString(), simObjOutdated.toQString()));
1932 emit this->physicallyAddingRemoteModelFailed(simObjOutdated.getAircraft(), true, true, msg); // outdated
1933 }
1934
1935 // if this aircraft is also outdated, ignore
1936 if (callsigns.contains(newRemoteAircraft.getCallsign()))
1937 {
1938 return false;
1939 }
1940 }
1941
1942 const bool hasPendingAdded = m_simConnectObjects.containsPendingAdded();
1943 bool canAdd = this->isSimulating() && !hasPendingAdded;
1944
1945 Q_ASSERT_X(!hasPendingAdded || m_simConnectObjects.countPendingAdded() < 2, Q_FUNC_INFO,
1946 "There must be only 0..1 pending objects");
1947 if (this->showDebugLogMessage())
1948 {
1949 this->debugLogMessage(Q_FUNC_INFO, QStringLiteral("CS: '%1' mode: '%2' model: '%3'")
1950 .arg(newRemoteAircraft.getCallsignAsString(), modeToString(addMode),
1951 newRemoteAircraft.getModelString()));
1952 this->debugLogMessage(
1953 Q_FUNC_INFO, QStringLiteral("CS: '%1' pending callsigns: '%2', pending objects: '%3'")
1954 .arg(newRemoteAircraft.getCallsignAsString(),
1955 m_addPendingAircraft.getAllCallsignStrings(true).join(", "),
1956 m_simConnectObjects.getPendingAddedCallsigns().getCallsignStrings().join(", ")));
1957 }
1958
1959 // do we need to remove/add again because something has changed?
1960 // this handles changed model strings or an update of the model
1961 if (m_simConnectObjects.contains(callsign))
1962 {
1963 const CSimConnectObject simObject = m_simConnectObjects[callsign];
1964 const QString newModelString(newRemoteAircraft.getModelString());
1965 const QString simObjModelString(simObject.getAircraftModelString());
1966 const bool sameModel =
1967 (simObjModelString ==
1968 newModelString); // compare on string only (other attributes might change such as mode)
1969
1970 // same model, nothing will change, otherwise add again when removed
1971 if (sameModel)
1972 {
1973 CLogMessage(this).info(u"CS: '%1' re-added same model '%2'")
1974 << newRemoteAircraft.getCallsignAsString() << newModelString;
1975
1976 // we restore rendered flag in case we are sure we are rendered
1977 // this is used with rematching
1978 const bool rendered = simObject.isConfirmedAdded() && simObject.isPending();
1979 if (rendered)
1980 {
1981 this->updateAircraftRendered(callsign, rendered);
1982 }
1983 return true;
1984 }
1985
1986 this->physicallyRemoveRemoteAircraft(newRemoteAircraft.getCallsign());
1987 m_addAgainAircraftWhenRemoved.replaceOrAddByCallsign(newRemoteAircraft);
1988 if (this->showDebugLogMessage())
1989 {
1990 this->debugLogMessage(Q_FUNC_INFO,
1991 QStringLiteral("CS: '%1' re-added changed model '%2', will be added again")
1992 .arg(newRemoteAircraft.getCallsignAsString(), newModelString));
1993 }
1994 return false;
1995 }
1996
1997 // situation check
1998 CAircraftSituation situation(newRemoteAircraft.getSituation());
1999 if (canAdd && situation.isPositionOrAltitudeNull())
2000 {
2001 // invalid position because position or altitude is null
2002 const CAircraftSituationList situations(this->remoteAircraftSituations(callsign));
2003 if (situations.isEmpty())
2004 {
2005 CLogMessage(this).warning(u"No valid situations for '%1', will be added as pending")
2006 << callsign.asString();
2007 }
2008 else
2009 {
2010 CLogMessage(this).warning(u"Invalid aircraft situation for new aircraft '%1', use closest situation")
2011 << callsign.asString();
2012 situation = situations.findClosestTimeDistanceAdjusted(QDateTime::currentMSecsSinceEpoch());
2013 Q_ASSERT_X(!situation.isPositionOrAltitudeNull(), Q_FUNC_INFO, "Invalid situation for new aircraft");
2014 }
2015
2016 // still invalid?
2017 canAdd = situation.isPositionOrAltitudeNull();
2019 {
2020 SWIFT_VERIFY_X(canAdd, Q_FUNC_INFO, "Expect valid situation");
2021 CLogMessage(this).warning(u"Invalid situation for '%1'") << callsign;
2022 }
2023 }
2024
2025 // check if we can add, do not add if simulator is stopped or other objects pending
2026 if (!canAdd)
2027 {
2028 CSimConnectObject &addPendingObj = m_addPendingAircraft[newRemoteAircraft.getCallsign()];
2029 addPendingObj.setAircraft(newRemoteAircraft);
2030 addPendingObj.resetTimestampToNow();
2031 return false;
2032 }
2033
2034 // remove from pending and keep for later to remember fail counters
2035 const CSimConnectObject removedPendingObj = this->removeFromAddPendingAndAddAgainAircraft(callsign);
2036
2037 // create AI after crosschecking it
2038 if (!probe && !this->isAircraftInRangeOrTestMode(callsign))
2039 {
2040 CLogMessage(this).info(u"Skipping adding of '%1' since it is no longer in range") << callsign.asString();
2041 return false;
2042 }
2043
2044 // setup
2045 const CInterpolationAndRenderingSetupPerCallsign setup =
2046 this->getInterpolationSetupConsolidated(callsign, true);
2047 const bool sendGround = setup.isSendingGndFlagToSimulator();
2048
2049 // FSX/P3D adding
2050 bool adding = false; // will be added flag
2051 const SIMCONNECT_DATA_REQUEST_ID requestId =
2053
2054 // Initial situation, if possible from interpolation
2055 CAircraftSituation initialSituation = newRemoteAircraft.getSituation(); // default
2056 {
2057 // Dummy CSimConnectObject just for interpolation
2058 const CSimConnectObject dummyObject = CSimConnectObject(
2059 newRemoteAircraft, 0, this, this, this->getRemoteAircraftProvider(), &m_interpolationLogger);
2060 const CInterpolationResult result =
2061 dummyObject.getInterpolation(QDateTime::currentMSecsSinceEpoch(), setup, 0);
2063 {
2064 initialSituation = result.getInterpolatedSituation();
2065 }
2066 }
2067
2068 // under flow can cause a model not to be added
2069 // FSX: underflow and NO(!) gnd flag can cause adding/remove issue
2070 // P3D: underflow did not cause such issue
2071 CStatusMessage underflowStatus;
2072 const SIMCONNECT_DATA_INITPOSITION initialPosition =
2073 CSimulatorFsxCommon::aircraftSituationToFsxPosition(initialSituation, sendGround, true, &underflowStatus);
2074
2075 const QString modelString(newRemoteAircraft.getModelString());
2076 if (this->showDebugLogMessage())
2077 {
2078 this->debugLogMessage(Q_FUNC_INFO, QStringLiteral("CS: '%1' model: '%2' request: %3, init pos: %4")
2079 .arg(callsign.toQString(), modelString)
2080 .arg(requestId)
2081 .arg(fsxPositionToString(initialPosition)));
2082 }
2083
2084 const QByteArray modelStringBa = toFsxChar(modelString);
2085 const QByteArray csBa = toFsxChar(callsign.toQString().left(12));
2086 CSimConnectObject::SimObjectType type = CSimConnectObject::AircraftNonAtc;
2087 HRESULT hr = S_OK;
2088
2089 if (probe)
2090 {
2091 hr = SimConnect_AICreateSimulatedObject(m_hSimConnect, modelStringBa.constData(), initialPosition,
2092 requestId);
2093 type = CSimConnectObject::TerrainProbe;
2094 }
2095 else
2096 {
2097 if (this->isAddingAsSimulatedObjectEnabled() && correspondingSimObject.hasCallsign() &&
2098 correspondingSimObject.getAddingExceptions() > 0 &&
2099 correspondingSimObject.getType() == CSimConnectObject::AircraftNonAtc)
2100 {
2101 CStatusMessage(this).warning(
2102 u"Model '%1' for '%2' failed %1 time(s) before, using AICreateSimulatedObject now")
2103 << newRemoteAircraft.getModelString() << callsign.toQString();
2104 hr = SimConnect_AICreateSimulatedObject(m_hSimConnect, modelStringBa.constData(), initialPosition,
2105 requestId);
2106 type = CSimConnectObject::AircraftSimulatedObject;
2107 }
2108 else
2109 {
2110 hr = SimConnect_AICreateNonATCAircraft(m_hSimConnect, modelStringBa.constData(), csBa.constData(),
2111 initialPosition, requestId);
2112 type = CSimConnectObject::AircraftNonAtc;
2113 }
2114 }
2115
2116 if (!underflowStatus.isEmpty())
2117 {
2118 CStatusMessage(this).warning(u"Underflow detecion for '%1', details '%2'")
2119 << callsign.asString() << underflowStatus.getMessage();
2120 }
2121
2122 if (isFailure(hr))
2123 {
2124 const CStatusMessage msg = CStatusMessage(this).error(u"SimConnect, can not create AI traffic: '%1' '%2'")
2125 << callsign.toQString() << modelString;
2127 emit this->physicallyAddingRemoteModelFailed(newRemoteAircraft, true, true, msg); // SimConnect error
2128 }
2129 else
2130 {
2131 // we will request a new aircraft by request ID, later we will receive its object id
2132 // so far this object id is 0 (DWORD)
2133 const CSimConnectObject simObject =
2134 this->insertNewSimConnectObject(newRemoteAircraft, requestId, type, removedPendingObj);
2135 this->traceSendId(simObject, Q_FUNC_INFO,
2136 QStringLiteral("mode: %1").arg(CSimulatorFsxCommon::modeToString(addMode)), true);
2137 adding = true;
2138 }
2139 return adding;
2140 }
2141
2142 bool CSimulatorFsxCommon::physicallyAddAITerrainProbe(const ICoordinateGeodetic &coordinate, int number)
2143 {
2144 if (coordinate.isNull())
2145 {
2146 return false;
2147 }
2148 if (!this->isUsingFsxTerrainProbe())
2149 {
2150 return false;
2151 }
2152 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
2153
2154 // static const QString modelString("OrcaWhale");
2155 // static const QString modelString("Water Drop"); // not working on P3Dx86/FSX, no requests on that id possible
2156 // static const QString modelString("A321ACA");
2157 // static const QString modelString("AI_Tracker_Object_0");
2158 // static const QString modelString("Piper Cub"); // P3Dv86 works as nonATC/SimulatedObject
2159 // static const QString modelString("Discovery Spaceshuttle"); // P3Dx86 works as nonATC/SimulatedObject
2160 static const QString modelString("swiftTerrainProbe0");
2161 static const QString pseudoCallsign("PROBE%1"); // max 12 chars
2162 static const CCountry ctry("SW", "SWIFT");
2163 static const CAirlineIcaoCode swiftAirline("SWI", "swift probe", ctry, "SWIFT", false, false);
2164 static const CLivery swiftLivery(CLivery::getStandardCode(swiftAirline), swiftAirline, "swift probe");
2165
2166 const CCallsign cs(pseudoCallsign.arg(number));
2167 const CAircraftModel model(modelString, CAircraftModel::TypeTerrainProbe, QStringLiteral("swift terrain probe"),
2168 CAircraftIcaoCode::unassignedIcao(), swiftLivery);
2169 CAircraftSituation situation(cs, coordinate);
2170 situation.setAltitude(terrainProbeAltitude());
2171 situation.setZeroPBH();
2172 const CSimulatedAircraft pseudoAircraft(cs, model, CUser("123456", "swift", cs), situation);
2173 return this->physicallyAddRemoteAircraftImpl(pseudoAircraft, ExternalCall);
2174 }
2175
2176 int CSimulatorFsxCommon::physicallyInitAITerrainProbes(const ICoordinateGeodetic &coordinate, int number)
2177 {
2178 if (number < 1)
2179 {
2180 return 0;
2181 }
2183 {
2184 return m_addedProbes;
2185 }
2186 m_initFsxTerrainProbes = true; // no multiple inits
2187 this->triggerAutoTraceSendId();
2188
2189 int c = 0;
2190 for (int n = 0; n < number; ++n)
2191 {
2192 if (this->physicallyAddAITerrainProbe(coordinate, n))
2193 {
2194 c++;
2195 }
2196 }
2197
2198 CLogMessage(this).info(u"Adding %1 FSX terrain probes") << number;
2199 m_addedProbes = c;
2200 return c;
2201 }
2202
2204 {
2205 // only remove from sim
2206 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "wrong thread");
2207 if (callsign.isEmpty())
2208 {
2209 return false;
2210 } // can happen if an object is not an aircraft
2211
2212 // clean up anyway
2213 this->removeFromAddPendingAndAddAgainAircraft(callsign);
2214
2215 // really remove from simulator
2216 if (!m_simConnectObjects.contains(callsign))
2217 {
2218 return false;
2219 } // already fully removed or not yet added
2220 CSimConnectObject &simObject = m_simConnectObjects[callsign];
2221 if (simObject.isPendingRemoved())
2222 {
2223 return true;
2224 }
2225 if (simObject.isTerrainProbe())
2226 {
2227 return false;
2228 }
2229
2230 // check for pending objects
2231 m_addPendingAircraft.remove(callsign); // just in case still in list of pending aircraft
2232 const bool pendingAdded = simObject.isPendingAdded(); // already added in simulator, but not yet confirmed
2233 const bool stillWaitingForLights = !simObject.hasCurrentLightsInSimulator();
2234 if (!simObject.isRemovedWhileAdding() && (pendingAdded || stillWaitingForLights))
2235 {
2236 // problem: we try to delete an aircraft just requested to be added
2237 // best solution so far, call remove again with a delay
2238 CLogMessage(this).warning(u"'%1' requested to be removed, but pending added (%2) / or pending lights(%3). "
2239 u"Object will be removed again: %4")
2240 << callsign.asString() << boolToYesNo(pendingAdded) << boolToYesNo(stillWaitingForLights)
2241 << simObject.toQString();
2242 simObject.setRemovedWhileAdding(true); // next time kill
2243 QPointer<CSimulatorFsxCommon> myself(this);
2244 QTimer::singleShot(2000, this, [=] {
2245 if (!myself)
2246 {
2247 return;
2248 }
2249 CLogMessage(this).info(u"Next trial to remove '%1'") << callsign.asString();
2250 myself->physicallyRemoveRemoteAircraft(callsign);
2251 });
2252 return false; // not yet deleted
2253 }
2254
2255 // no more data from simulator
2256 this->stopRequestingDataForSimObject(simObject);
2257
2258 // mark as removed
2259 simObject.setPendingRemoved(true);
2260 if (this->showDebugLogMessage())
2261 {
2262 this->debugLogMessage(Q_FUNC_INFO, QStringLiteral("CS: '%1' request/object id: %2/%3")
2263 .arg(callsign.toQString())
2264 .arg(simObject.getRequestId())
2265 .arg(simObject.getObjectId()));
2266 }
2267
2268 // call in SIM
2269 const SIMCONNECT_DATA_REQUEST_ID requestId = simObject.getRequestId(CSimConnectDefinitions::SimObjectRemove);
2270 this->removeCamera(simObject);
2271 this->removeObserver(simObject);
2272 const HRESULT result = SimConnect_AIRemoveObject(
2273 m_hSimConnect, static_cast<SIMCONNECT_OBJECT_ID>(simObject.getObjectId()), requestId);
2274 if (isOk(result))
2275 {
2276 if (this->isTracingSendId())
2277 {
2278 this->traceSendId(simObject, Q_FUNC_INFO);
2279 }
2280 }
2281 else
2282 {
2283 CLogMessage(this).warning(u"Removing aircraft '%1' from simulator failed") << callsign.asString();
2284 }
2285
2286 // mark in provider
2287 const bool updated = this->updateAircraftRendered(callsign, false);
2288 if (updated)
2289 {
2290 CSimulatedAircraft aircraft(simObject.getAircraft());
2291 aircraft.setRendered(false);
2292 emit this->aircraftRenderingChanged(aircraft);
2293 }
2294
2295 // cleanup function, actually this should not be needed
2296 this->physicallyRemoveAircraftNotInProviderAsync();
2297
2298 // bye
2299 return CSimulatorPluginCommon::physicallyRemoveRemoteAircraft(callsign);
2300 }
2301
2303 {
2304 // make sure they are not added again
2305 // cleaning here is somewhat redundant, but double checks
2306 m_addPendingAircraft.clear();
2308
2309 // remove one by one
2310 int r = 0;
2311 const CCallsignSet callsigns = m_simConnectObjects.getAllCallsigns();
2312 for (const CCallsign &cs : callsigns)
2313 {
2314 if (this->physicallyRemoveRemoteAircraft(cs))
2315 {
2316 r++;
2317 }
2318 }
2319
2321 return r;
2322 }
2323
2324 HRESULT CSimulatorFsxCommon::initEvents()
2325 {
2326 HRESULT hr = s_ok();
2327 // System events, see http://msdn.microsoft.com/en-us/library/cc526983.aspx#SimConnect_SubscribeToSystemEvent
2328 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventSimStatus, "Sim");
2329 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventObjectAdded, "ObjectAdded");
2330 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventObjectRemoved, "ObjectRemoved");
2331 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventFrame, "Frame");
2332 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventPause, "Pause");
2333 hr += SimConnect_SubscribeToSystemEvent(m_hSimConnect, SystemEventFlightLoaded, "FlightLoaded");
2334 if (isFailure(hr))
2335 {
2336 CLogMessage(this).error(u"FSX plugin error: %1") << "SimConnect_SubscribeToSystemEvent failed";
2337 return hr;
2338 }
2339
2340 // Mapped events, see event ids here:
2341 // http://msdn.microsoft.com/en-us/library/cc526980.aspx
2342 // http://www.prepar3d.com/SDKv2/LearningCenter/utilities/variables/event_ids.html
2343 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventPauseToggle, "PAUSE_TOGGLE");
2344 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, SystemEventSlewToggle, "SLEW_TOGGLE");
2345 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventFreezeLatLng,
2346 "FREEZE_LATITUDE_LONGITUDE_SET"); // FSX old standard
2347 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventFreezeAlt,
2348 "FREEZE_ALTITUDE_SET"); // FSX old standard
2349 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventFreezeAtt,
2350 "FREEZE_ATTITUDE_SET"); // FSX old standard
2351 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetCom1Active, "COM_RADIO_SET");
2352 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetCom1Standby, "COM_STBY_RADIO_SET");
2353 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetCom2Active, "COM2_RADIO_SET");
2354 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetCom2Standby, "COM2_STBY_RADIO_SET");
2355 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetTransponderCode, "XPNDR_SET");
2356
2357 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetTimeZuluYear, "ZULU_YEAR_SET");
2358 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetTimeZuluDay, "ZULU_DAY_SET");
2359 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetTimeZuluHours, "ZULU_HOURS_SET");
2360 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventSetTimeZuluMinutes, "ZULU_MINUTES_SET");
2361
2362 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventLandingLightsOff, "LANDING_LIGHTS_OFF");
2363 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventLandinglightsOn, "LANDING_LIGHTS_ON");
2364 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventLandingLightsSet, "LANDING_LIGHTS_SET");
2365 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventLandingLightsToggle, "LANDING_LIGHTS_TOGGLE");
2366 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventPanelLightsOff, "PANEL_LIGHTS_OFF");
2367 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventPanelLightsOn, "PANEL_LIGHTS_ON");
2368 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventPanelLightsSet, "PANEL_LIGHTS_SET");
2369 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventStrobesOff, "STROBES_OFF");
2370 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventStrobesOn, "STROBES_ON");
2371 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventStrobesSet, "STROBES_SET");
2372 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventStrobesToggle, "STROBES_TOGGLE");
2373 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleBeaconLights, "TOGGLE_BEACON_LIGHTS");
2374 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleCabinLights, "TOGGLE_CABIN_LIGHTS");
2375 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleLogoLights, "TOGGLE_LOGO_LIGHTS");
2376 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleNavLights, "TOGGLE_NAV_LIGHTS");
2377 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleRecognitionLights,
2378 "TOGGLE_RECOGNITION_LIGHTS");
2379 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleTaxiLights, "TOGGLE_TAXI_LIGHTS");
2380 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventToggleWingLights, "TOGGLE_WING_LIGHTS");
2381
2382 hr += SimConnect_MapClientEventToSimEvent(m_hSimConnect, EventFlapsSet, "FLAPS_SET");
2383
2384 if (isFailure(hr))
2385 {
2386 CLogMessage(this).error(u"FSX plugin error: %1") << "SimConnect_MapClientEventToSimEvent failed";
2387 return hr;
2388 }
2389
2390 // facility
2391 SIMCONNECT_DATA_REQUEST_ID requestId =
2392 static_cast<SIMCONNECT_DATA_REQUEST_ID>(CSimConnectDefinitions::RequestFacility);
2393 hr += SimConnect_SubscribeToFacilities(m_hSimConnect, SIMCONNECT_FACILITY_LIST_TYPE_AIRPORT, requestId);
2394 if (isFailure(hr))
2395 {
2396 CLogMessage(this).error(u"FSX plugin error: %1") << "SimConnect_SubscribeToFacilities failed";
2397 return hr;
2398 }
2399 return hr;
2400 }
2401
2402 HRESULT CSimulatorFsxCommon::initDataDefinitionsWhenConnected()
2403 {
2406 }
2407
2408 HRESULT CSimulatorFsxCommon::initWhenConnected()
2409 {
2410 // called when connected
2411
2412 HRESULT hr = this->initEvents();
2413 if (isFailure(hr))
2414 {
2415 CLogMessage(this).error(u"FSX plugin: initEvents failed");
2416 return hr;
2417 }
2418
2419 // init data definitions and SB data area
2420 hr += this->initDataDefinitionsWhenConnected();
2421 if (isFailure(hr))
2422 {
2423 CLogMessage(this).error(u"FSX plugin: initDataDefinitionsWhenConnected failed");
2424 return hr;
2425 }
2426
2427 return hr;
2428 }
2429
2430 void CSimulatorFsxCommon::updateRemoteAircraft()
2431 {
2432 static_assert(sizeof(DataDefinitionRemoteAircraftPartsWithoutLights) == sizeof(double) * 14,
2433 "DataDefinitionRemoteAircraftPartsWithoutLights has an incorrect size.");
2434 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
2435
2436 // nothing to do, reset request id and exit
2437 const int remoteAircraftNo = this->getAircraftInRangeCount();
2438 if (remoteAircraftNo < 1)
2439 {
2441 return;
2442 }
2443
2444 // values used for position and parts
2445 const qint64 currentTimestamp = QDateTime::currentMSecsSinceEpoch();
2446 if (this->isUpdateAircraftLimitedWithStats(currentTimestamp))
2447 {
2448 this->finishUpdateRemoteAircraftAndSetStatistics(currentTimestamp, true);
2449 return;
2450 }
2452
2453 // interpolation for all remote aircraft
2454 const QList<CSimConnectObject> simObjects(m_simConnectObjects.values());
2455
2456 uint32_t simObjectNumber = 0;
2457 const bool doTraceSendId = this->isTracingSendId();
2458 const bool updateAllAircraft = this->isUpdateAllRemoteAircraft(currentTimestamp);
2459 for (const CSimConnectObject &simObject : simObjects)
2460 {
2461 // happening if aircraft is not yet added to simulator or to be deleted
2462 if (!simObject.isReadyToSend())
2463 {
2464 continue;
2465 }
2466 if (!simObject.hasCurrentLightsInSimulator())
2467 {
2468 continue;
2469 } // wait until we have light state
2470
2471 const CCallsign callsign(simObject.getCallsign());
2472 const bool hasCs = !callsign.isEmpty();
2473 const bool hasValidIds = simObject.hasValidRequestAndObjectId();
2474 SWIFT_VERIFY_X(hasCs, Q_FUNC_INFO, "missing callsign");
2475 SWIFT_AUDIT_X(hasValidIds, Q_FUNC_INFO, "Missing ids");
2476 if (!hasCs || !hasValidIds)
2477 {
2478 continue;
2479 } // not supposed to happen
2480 const DWORD objectId = simObject.getObjectId();
2481
2482 // setup
2483 const CInterpolationAndRenderingSetupPerCallsign setup =
2484 this->getInterpolationSetupConsolidated(callsign, updateAllAircraft);
2485 const bool sendGround = setup.isSendingGndFlagToSimulator();
2486
2487 // Interpolated situation
2488 // simObjectNumber is passed to equally distributed steps like guessing parts
2489 const bool slowUpdate = (((m_statsUpdateAircraftRuns + simObjectNumber) % 40) == 0);
2490 const CInterpolationResult result = simObject.getInterpolation(currentTimestamp, setup, simObjectNumber++);
2491 const bool forceUpdate = slowUpdate || updateAllAircraft || setup.isForcingFullInterpolation();
2493 {
2494 // update situation
2495 if (forceUpdate || !this->isEqualLastSent(result.getInterpolatedSituation()))
2496 {
2497 // adjust altitude to compensate for FS2020 temperature effect
2498 CAircraftSituation situation = result;
2499 const CLength relativeAltitude =
2501 const double altitudeDeltaWeight =
2502 2 - qBound(3000.0, relativeAltitude.abs().value(CLengthUnit::ft()), 6000.0) / 3000;
2503 situation.setAltitude({ situation.getAltitude() + m_altitudeDelta * altitudeDeltaWeight,
2504 situation.getAltitude().getReferenceDatum() });
2505
2506 SIMCONNECT_DATA_INITPOSITION position = this->aircraftSituationToFsxPosition(situation, sendGround);
2507 const HRESULT hr = this->logAndTraceSendId(
2508 SimConnect_SetDataOnSimObject(m_hSimConnect,
2510 static_cast<SIMCONNECT_OBJECT_ID>(objectId), 0, 0,
2511 sizeof(SIMCONNECT_DATA_INITPOSITION), &position),
2512 doTraceSendId, simObject, "Failed to set position", Q_FUNC_INFO,
2513 "SimConnect_SetDataOnSimObject");
2514 if (isOk(hr))
2515 {
2516 this->rememberLastSent(result); // remember situation
2517 }
2518 }
2519 }
2520 else
2521 {
2522 // already logged in interpolator
2523 continue;
2524 }
2525
2526 // Interpolated parts
2527 const bool updatedParts = this->updateRemoteAircraftParts(simObject, result, forceUpdate);
2528 Q_UNUSED(updatedParts)
2529
2530 } // all callsigns
2531
2532 // stats
2533 this->finishUpdateRemoteAircraftAndSetStatistics(currentTimestamp);
2534 }
2535
2536 bool CSimulatorFsxCommon::updateRemoteAircraftParts(const CSimConnectObject &simObject,
2537 const CInterpolationResult &result, bool forcedUpdate)
2538 {
2539 if (!simObject.hasValidRequestAndObjectId())
2540 {
2541 return false;
2542 }
2543 if (!simObject.isConfirmedAdded())
2544 {
2545 return false;
2546 }
2547
2548 const CAircraftParts parts = result;
2549 if (parts.isNull())
2550 {
2551 return false;
2552 }
2553 if (parts.getPartsDetails() != CAircraftParts::GuessedParts && !result.getPartsStatus().isSupportingParts())
2554 {
2555 return false;
2556 }
2557
2558 const CCallsign cs = simObject.getCallsign();
2559 if (!forcedUpdate && (result.getPartsStatus().isReusedParts() || this->isEqualLastSent(parts, cs)))
2560 {
2561 return true;
2562 }
2563
2564 const bool ok = this->sendRemoteAircraftPartsToSimulator(simObject, parts);
2565 if (ok)
2566 {
2567 this->rememberLastSent(parts, cs);
2568 }
2569 return ok;
2570 }
2571
2572 bool CSimulatorFsxCommon::sendRemoteAircraftPartsToSimulator(const CSimConnectObject &simObject,
2573 const CAircraftParts &parts)
2574 {
2575 Q_ASSERT(m_hSimConnect);
2576 if (!simObject.isReadyToSend())
2577 {
2578 return false;
2579 }
2580
2581 const DWORD objectId = simObject.getObjectId();
2582 const bool traceId = this->isTracingSendId();
2583
2584 DataDefinitionRemoteAircraftPartsWithoutLights ddRemoteAircraftPartsWithoutLights(parts);
2585 const CAircraftLights lights = parts.getAdjustedLights();
2586
2587 // in case we sent, we sent everything
2588 const bool simObjectAircraftType = simObject.isAircraftSimulatedObject(); // no real aircraft type
2589 const HRESULT hr1 =
2590 simObjectAircraftType ?
2591 S_OK :
2592 this->logAndTraceSendId(
2593 SimConnect_SetDataOnSimObject(
2594 m_hSimConnect, CSimConnectDefinitions::DataRemoteAircraftPartsWithoutLights,
2595 static_cast<SIMCONNECT_OBJECT_ID>(objectId), SIMCONNECT_DATA_SET_FLAG_DEFAULT, 0,
2596 sizeof(DataDefinitionRemoteAircraftPartsWithoutLights), &ddRemoteAircraftPartsWithoutLights),
2597 traceId, simObject, "Failed so set parts", Q_FUNC_INFO,
2598 "SimConnect_SetDataOnSimObject::ddRemoteAircraftPartsWithoutLights");
2599
2600 // Sim variable version, not working, setting the value, but flaps retracting to 0 again
2601 // Sets flap handle to closest increment (0 to 16383)
2602 const DWORD flapsDw = static_cast<DWORD>(qMin(16383, qRound((parts.getFlapsPercent() / 100.0) * 16383)));
2603 const HRESULT hr2 = this->logAndTraceSendId(
2604 SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFlapsSet, flapsDw,
2605 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2606 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2607 traceId, simObject, "Failed so set flaps", Q_FUNC_INFO, "SimConnect_TransmitClientEvent::EventFlapsSet");
2608
2609 // lights we can set directly
2610 const HRESULT hr3 = this->logAndTraceSendId(
2611 SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventLandingLightsSet,
2612 lights.isLandingOn() ? 1.0 : 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2613 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2614 traceId, simObject, "Failed so set landing lights", Q_FUNC_INFO,
2615 "SimConnect_TransmitClientEvent::EventLandingLightsSet");
2616
2617 const HRESULT hr4 =
2618 this->logAndTraceSendId(SimConnect_TransmitClientEvent(
2619 m_hSimConnect, objectId, EventStrobesSet, lights.isStrobeOn() ? 1.0 : 0.0,
2620 SIMCONNECT_GROUP_PRIORITY_HIGHEST, SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2621 traceId, simObject, "Failed to set strobe lights", Q_FUNC_INFO,
2622 "SimConnect_TransmitClientEvent::EventStrobesSet");
2623
2624 // lights we need to toggle
2625 // (potential risk with quickly changing values that we accidentally toggle back, also we need the light state
2626 // before we can toggle)
2627 this->sendToggledLightsToSimulator(simObject, lights);
2628
2629 // done
2630 return isOk(hr1, hr2, hr3, hr4);
2631 }
2632
2633 bool CSimulatorFsxCommon::sendRemoteAircraftAtcDataToSimulator(const CSimConnectObject &simObject)
2634 {
2635 if (!simObject.isReadyToSend())
2636 {
2637 return false;
2638 }
2639 if (simObject.isTerrainProbe())
2640 {
2641 return false;
2642 }
2643 // if (simObject.getType() != CSimConnectObject::AircraftNonAtc) { return false; } // otherwise errors
2644
2645 const DWORD objectId = simObject.getObjectId();
2646 const bool traceId = this->isTracingSendId();
2647
2648 DataDefinitionRemoteAtc ddAtc;
2649 ddAtc.setDefaultValues();
2650 const QByteArray csBa = simObject.getCallsignByteArray();
2651 const QByteArray airlineBa = simObject.getAircraft().getAirlineIcaoCode().getName().toLatin1();
2652 const QByteArray flightNumberBa = QString::number(simObject.getObjectId()).toLatin1();
2653
2654 ddAtc.copyAtcId(csBa.constData());
2655 ddAtc.copyAtcAirline(airlineBa.constData());
2656 ddAtc.copyFlightNumber(flightNumberBa.constData());
2657
2658 // in case we sent, we sent everything
2659 const HRESULT hr = this->logAndTraceSendId(
2661 static_cast<SIMCONNECT_OBJECT_ID>(objectId), SIMCONNECT_DATA_SET_FLAG_DEFAULT,
2662 0, sizeof(DataDefinitionRemoteAtc), &ddAtc),
2663 traceId, simObject, "Failed so aircraft ATC data", Q_FUNC_INFO, "SimConnect_SetDataOnSimObject");
2664 // done
2665 return isOk(hr);
2666 }
2667
2668 void CSimulatorFsxCommon::sendToggledLightsToSimulator(const CSimConnectObject &simObj,
2669 const CAircraftLights &lightsWanted, bool force)
2670 {
2671 if (!simObj.isReadyToSend())
2672 {
2673 return;
2674 } // stale
2675
2676 const CAircraftLights lightsIsState = simObj.getCurrentLightsInSimulator();
2677 if (lightsWanted == lightsIsState)
2678 {
2679 return;
2680 }
2681 if (!force && lightsWanted == simObj.getLightsAsSent())
2682 {
2683 return;
2684 }
2685 const CCallsign callsign(simObj.getCallsign());
2686
2687 // Update data
2688 if (m_simConnectObjects.contains(callsign))
2689 {
2690 CSimConnectObject &simObjToUpdate = m_simConnectObjects[callsign];
2691 simObjToUpdate.setLightsAsSent(lightsWanted);
2692 }
2693
2694 // state available, then I can toggle
2695 if (!lightsIsState.isNull())
2696 {
2697 const DWORD objectId = simObj.getObjectId();
2698 const bool trace = this->isTracingSendId();
2699
2700 if (lightsWanted.isTaxiOn() != lightsIsState.isTaxiOn())
2701 {
2702 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleTaxiLights,
2703 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2704 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2705 trace, simObj, "Toggle taxi lights", Q_FUNC_INFO, "EventToggleTaxiLights");
2706 }
2707 if (lightsWanted.isNavOn() != lightsIsState.isNavOn())
2708 {
2709 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleNavLights,
2710 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2711 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2712 trace, simObj, "Toggle nav.lights", Q_FUNC_INFO, "EventToggleNavLights");
2713 }
2714 if (lightsWanted.isBeaconOn() != lightsIsState.isBeaconOn())
2715 {
2716 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleBeaconLights,
2717 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2718 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2719 trace, simObj, "Toggle becon lights", Q_FUNC_INFO, "EventToggleBeaconLights");
2720 }
2721 if (lightsWanted.isLogoOn() != lightsIsState.isLogoOn())
2722 {
2723 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleLogoLights,
2724 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2725 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2726 trace, simObj, "Toggle logo lights", Q_FUNC_INFO, "EventToggleLogoLights");
2727 }
2728 if (lightsWanted.isRecognitionOn() != lightsIsState.isRecognitionOn())
2729 {
2730 this->logAndTraceSendId(
2731 SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleRecognitionLights, 0.0,
2732 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2733 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2734 trace, simObj, "Toggle recognition lights", Q_FUNC_INFO, "EventToggleRecognitionLights");
2735 }
2736 if (lightsWanted.isCabinOn() != lightsIsState.isCabinOn())
2737 {
2738 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventToggleCabinLights,
2739 0.0, SIMCONNECT_GROUP_PRIORITY_HIGHEST,
2740 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
2741 trace, simObj, "Toggle cabin lights", Q_FUNC_INFO, "EventToggleCabinLights");
2742 }
2743 return;
2744 }
2745
2746 // missing lights info from simulator so far
2747 if (this->showDebugLogMessage())
2748 {
2749 this->debugLogMessage(Q_FUNC_INFO, QStringLiteral("Missing light state in simulator for '%1', model '%2'")
2750 .arg(callsign.asString(), simObj.getAircraftModelString()));
2751 }
2752
2753 const QPointer<CSimulatorFsxCommon> myself(this);
2754 QTimer::singleShot(DeferResendingLights, this, [=] {
2755 if (!myself)
2756 {
2757 return;
2758 }
2759 if (!m_simConnectObjects.contains(callsign))
2760 {
2761 return;
2762 }
2763 const CSimConnectObject currentSimObject = m_simConnectObjects[callsign];
2764 if (!currentSimObject.isReadyToSend())
2765 {
2766 return;
2767 } // stale
2768 if (lightsWanted != currentSimObject.getLightsAsSent())
2769 {
2770 return;
2771 } // changed in between, so another call sendToggledLightsToSimulator is pending
2772 if (this->showDebugLogMessage())
2773 {
2774 this->debugLogMessage(Q_FUNC_INFO, QStringLiteral("Resending light state for '%1', model '%2'")
2775 .arg(callsign.asString(), simObj.getAircraftModelString()));
2776 }
2777 this->sendToggledLightsToSimulator(currentSimObject, lightsWanted, true);
2778 });
2779 }
2780
2781 SIMCONNECT_DATA_INITPOSITION
2783 bool forceUnderflowDetection, CStatusMessage *details)
2784 {
2785 Q_ASSERT_X(!situation.isGeodeticHeightNull(), Q_FUNC_INFO, "Missing height (altitude)");
2786 Q_ASSERT_X(!situation.isPositionNull(), Q_FUNC_INFO, "Missing position");
2787
2788 // lat/Lng, NO PBH
2789 CAircraftSituation::AltitudeCorrection altCorrection = CAircraftSituation::UnknownCorrection;
2790 SIMCONNECT_DATA_INITPOSITION position = CSimulatorFsxCommon::coordinateToFsxPosition(situation);
2791 if (forceUnderflowDetection)
2792 {
2793 const CAltitude alt = situation.getCorrectedAltitude(true, &altCorrection);
2794 position.Altitude = alt.value(CLengthUnit::ft());
2795 }
2796
2797 // MSFS has inverted pitch and bank angles
2798 position.Pitch = -situation.getPitch().value(CAngleUnit::deg());
2799 position.Bank = -situation.getBank().value(CAngleUnit::deg());
2800 position.Heading = situation.getHeading().value(CAngleUnit::deg());
2801 position.OnGround = 0U; // not on ground
2802
2803 const double gsKts = situation.getGroundSpeed().value(CSpeedUnit::kts());
2804 position.Airspeed = static_cast<DWORD>(qRound(gsKts));
2805
2806 // sanity check
2807 if (gsKts < 0.0)
2808 {
2809 // we get negative GS for pushback and helicopters
2810 // here we handle them her with DWORD (unsigned)
2811 position.Airspeed = 0U;
2812 }
2813 else
2814 {
2815 position.Airspeed = static_cast<DWORD>(qRound(gsKts));
2816 }
2817
2818 // send GND flag also when underflow detection is available
2819 if ((sendGnd || forceUnderflowDetection) && situation.isOnGroundInfoAvailable())
2820 {
2821 const bool onGround = situation.isOnGround();
2822 position.OnGround = onGround ? 1U : 0U;
2823 }
2824
2825 // if we have no GND flag yet (gnd flag prevents underflow)
2826 if (forceUnderflowDetection && position.OnGround == 0 &&
2828 {
2829 // logical resolution failed so far, likely we have no CG or elevantion
2830 // primitive guessing
2831 do
2832 {
2833 if (position.Airspeed < 2)
2834 {
2835 position.OnGround = 1U;
2836 if (details)
2837 {
2838 *details = CStatusMessage(static_cast<CSimulatorFsxCommon *>(nullptr))
2839 .warning(u"Force GND flag for underflow protection");
2840 }
2841 break;
2842 }
2843 }
2844 while (false);
2845 }
2846
2847 // crosscheck
2849 {
2850 SWIFT_VERIFY_X(isValidFsxPosition(position), Q_FUNC_INFO, "Invalid FSX pos.");
2851 }
2852
2853 return position;
2854 }
2855
2857 {
2858 // MSFS has inverted pitch and bank angles
2860 pbh.Pitch = -situation.getPitch().value(CAngleUnit::deg());
2861 pbh.Bank = -situation.getBank().value(CAngleUnit::deg());
2862 pbh.Heading = situation.getHeading().value(CAngleUnit::deg());
2863 return pbh;
2864 }
2865
2866 SIMCONNECT_DATA_INITPOSITION CSimulatorFsxCommon::coordinateToFsxPosition(const ICoordinateGeodetic &coordinate)
2867 {
2868 SIMCONNECT_DATA_INITPOSITION position;
2869 position.Latitude = coordinate.latitude().value(CAngleUnit::deg());
2870 position.Longitude = coordinate.longitude().value(CAngleUnit::deg());
2871 position.Altitude = coordinate.geodeticHeight().value(
2872 CLengthUnit::ft()); // already corrected in interpolator if there is an underflow
2873 position.Heading = 0;
2874 position.Airspeed = 0;
2875 position.Pitch = 0;
2876 position.Bank = 0;
2877 position.OnGround = 0;
2878 return position;
2879 }
2880
2881 SIMCONNECT_DATA_LATLONALT CSimulatorFsxCommon::coordinateToFsxLatLonAlt(const ICoordinateGeodetic &coordinate)
2882 {
2883 SIMCONNECT_DATA_LATLONALT lla;
2884 lla.Latitude = coordinate.latitude().value(CAngleUnit::deg());
2885 lla.Longitude = coordinate.longitude().value(CAngleUnit::deg());
2886 lla.Altitude = coordinate.geodeticHeight().value(
2887 CLengthUnit::ft()); // already corrected in interpolator if there is an underflow
2888 return lla;
2889 }
2890
2891 bool CSimulatorFsxCommon::isValidFsxPosition(const SIMCONNECT_DATA_INITPOSITION &fsxPos)
2892 {
2893 // double Latitude; // degrees | double Longitude; // degrees | double Altitude; // feet
2894 // double Pitch; // degrees | double Bank; // degrees | double Heading; // degrees
2895 // DWORD OnGround; // 1=force to be on the ground | DWORD Airspeed; // knots
2896 // https://www.prepar3d.com/SDKv4/sdk/simconnect_api/references/simobject_functions.html
2897 // examples show heaading 180 => we assume values +-180deg
2898 if (!isValid180Deg(fsxPos.Pitch))
2899 {
2900 return false;
2901 }
2902 if (!isValid180Deg(fsxPos.Bank))
2903 {
2904 return false;
2905 }
2906 if (!isValid180Deg(fsxPos.Heading))
2907 {
2908 return false;
2909 }
2910 if (!isValid180Deg(fsxPos.Latitude))
2911 {
2912 return false;
2913 }
2914 if (!isValid180Deg(fsxPos.Longitude))
2915 {
2916 return false;
2917 }
2918 return true;
2919 }
2920
2921 bool CSimulatorFsxCommon::requestPositionDataForSimObject(const CSimConnectObject &simObject,
2922 SIMCONNECT_PERIOD period)
2923 {
2924 if (this->isShuttingDownOrDisconnected())
2925 {
2926 return false;
2927 }
2928 if (!simObject.hasValidRequestAndObjectId())
2929 {
2930 return false;
2931 }
2932 if (simObject.isPending())
2933 {
2934 return false;
2935 } // wait until confirmed
2936 if (simObject.getSimDataPeriod() == period)
2937 {
2938 return true;
2939 } // already queried like this
2940 if (!m_simConnectObjects.contains(simObject.getCallsign()))
2941 {
2942 return false;
2943 } // removed in meantime
2944
2945 // always request, not only when something has changed
2946 const SIMCONNECT_DATA_REQUEST_ID reqId = static_cast<SIMCONNECT_DATA_REQUEST_ID>(
2947 simObject.getRequestId(CSimConnectDefinitions::SimObjectPositionData));
2948 const HRESULT result = this->logAndTraceSendId(
2949 SimConnect_RequestDataOnSimObject(m_hSimConnect, reqId,
2951 simObject.getObjectId(), period),
2952 simObject, "Cannot request simulator data", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
2953
2954 if (isOk(result))
2955 {
2956 m_requestSimObjectDataCount++;
2957 m_simConnectObjects[simObject.getCallsign()].setSimDataPeriod(period);
2958 return true;
2959 }
2960 return false;
2961 }
2962
2963 bool CSimulatorFsxCommon::requestTerrainProbeData(const CSimConnectObject &simObject,
2964 const CCallsign &aircraftCallsign)
2965 {
2966 static const QString w("Cannot request terrain probe data for id '%1'");
2967 const SIMCONNECT_DATA_REQUEST_ID requestId =
2968 simObject.getRequestId(CSimConnectDefinitions::SimObjectPositionData);
2969 const DWORD objectId = simObject.getObjectId();
2970 const HRESULT result = this->logAndTraceSendId(
2971 SimConnect_RequestDataOnSimObject(m_hSimConnect, static_cast<SIMCONNECT_DATA_REQUEST_ID>(requestId),
2973 static_cast<SIMCONNECT_OBJECT_ID>(objectId), SIMCONNECT_PERIOD_ONCE),
2974 simObject, w.arg(requestId), Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
2975 const bool ok = isOk(result);
2976 if (ok)
2977 {
2978 m_pendingProbeRequests.insert(requestId, aircraftCallsign);
2979 }
2980 return ok;
2981 }
2982
2983 bool CSimulatorFsxCommon::requestLightsForSimObject(const CSimConnectObject &simObject)
2984 {
2985 if (!this->isValidSimObjectNotPendingRemoved(simObject))
2986 {
2987 return false;
2988 }
2989 if (!m_hSimConnect)
2990 {
2991 return false;
2992 }
2993
2994 // always request, not only when something has changed
2995 const SIMCONNECT_DATA_REQUEST_ID requestId = simObject.getRequestId(CSimConnectDefinitions::SimObjectLights);
2996 const HRESULT result = this->logAndTraceSendId(
2997 SimConnect_RequestDataOnSimObject(m_hSimConnect, requestId,
2998 CSimConnectDefinitions::DataRemoteAircraftLights, simObject.getObjectId(),
2999 SIMCONNECT_PERIOD_SECOND),
3000 simObject, "Cannot request lights data", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
3001 return isOk(result);
3002 }
3003
3004 bool CSimulatorFsxCommon::requestModelInfoForSimObject(const CSimConnectObject &simObject)
3005 {
3006 if (!this->isValidSimObjectNotPendingRemoved(simObject))
3007 {
3008 return false;
3009 }
3010 if (!m_hSimConnect)
3011 {
3012 return false;
3013 }
3014
3015 // always request, not only when something has changed
3016 const SIMCONNECT_DATA_REQUEST_ID requestId = simObject.getRequestId(CSimConnectDefinitions::SimObjectModel);
3017 const HRESULT result = this->logAndTraceSendId(
3018 SimConnect_RequestDataOnSimObject(m_hSimConnect, requestId,
3020 simObject.getObjectId(), SIMCONNECT_PERIOD_ONCE),
3021 simObject, "Cannot request model info", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
3022 return isOk(result);
3023 }
3024
3025 bool CSimulatorFsxCommon::stopRequestingDataForSimObject(const CSimConnectObject &simObject)
3026 {
3027 if (!simObject.hasValidRequestAndObjectId())
3028 {
3029 return false;
3030 }
3031 if (!m_hSimConnect)
3032 {
3033 return false;
3034 }
3035
3036 // stop by setting SIMCONNECT_PERIOD_NEVER
3037 SIMCONNECT_DATA_REQUEST_ID requestId = simObject.getRequestId(CSimConnectDefinitions::SimObjectPositionData);
3038 const HRESULT hr1 = this->logAndTraceSendId(
3039 SimConnect_RequestDataOnSimObject(m_hSimConnect, requestId,
3041 simObject.getObjectId(), SIMCONNECT_PERIOD_NEVER),
3042 simObject, "Stopping position request", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
3043
3044 requestId = simObject.getRequestId(CSimConnectDefinitions::SimObjectLights);
3045 const HRESULT hr2 = this->logAndTraceSendId(
3046 SimConnect_RequestDataOnSimObject(m_hSimConnect, requestId,
3047 CSimConnectDefinitions::DataRemoteAircraftLights, simObject.getObjectId(),
3048 SIMCONNECT_PERIOD_NEVER),
3049 simObject, "Stopping lights request", Q_FUNC_INFO, "SimConnect_RequestDataOnSimObject");
3050 return isOk(hr1, hr2);
3051 }
3052
3054 {
3056 m_simulatorInternals.setValue("fsx/simConnectVersion", m_simConnectVersion);
3057 }
3058
3060 {
3061 this->safeKillTimer();
3062
3063 // cleared below:
3064 // physicallyRemoveAllRemoteAircraft
3065 // m_simConnectObjects
3066 // m_simConnectObjectsPositionAndPartsTraces
3067 // m_addPendingAircraft
3068 // m_updateRemoteAircraftInProgress
3069 CSimulatorFsCommon::reset(); // clears all pending aircraft etc
3070
3071 // reset values
3072 m_simulatingChangedTs = -1;
3073 m_simConnected = false;
3074 m_simSimulating = false;
3075 m_sbDataReceived = 0;
3076 m_requestIdSimObjAircraft = static_cast<SIMCONNECT_DATA_REQUEST_ID>(RequestSimObjAircraftStart);
3077 m_dispatchErrors = 0;
3078 m_receiveExceptionCount = 0;
3079 m_addedProbes = 0;
3080 m_initFsxTerrainProbes = false;
3081 m_sendIdTraces.clear();
3082 }
3083
3085 {
3086 const bool reinitProbe =
3087 m_useFsxTerrainProbe && m_initFsxTerrainProbes; // re-init if enabled and was initialized
3088 this->removeAllProbes();
3089
3090 // m_addAgainAircraftWhenRemoved cleared below
3091 CSimulatorFsCommon::clearAllRemoteAircraftData(); // also removes aircraft
3092 m_simConnectObjects.clear();
3093 m_addPendingAircraft.clear();
3094 m_simConnectObjectsPositionAndPartsTraces.clear();
3095
3096 if (reinitProbe)
3097 {
3098 // if we are still alive we re-init the probes
3099 QPointer<CSimulatorFsxCommon> myself(this);
3100 QTimer::singleShot(2000, this, [=] {
3101 // Shutdown or unloaded
3102 if (this->isShuttingDown() || !myself)
3103 {
3104 return;
3105 }
3106 m_initFsxTerrainProbes = false; // probes will re-init
3107 });
3108 }
3109 }
3110
3112 {
3113 m_sbDataReceived = 0;
3115 }
3116
3117 QString CSimulatorFsxCommon::fsxPositionToString(const SIMCONNECT_DATA_INITPOSITION &position)
3118 {
3119 static const QString positionStr(
3120 "Lat: %1deg lng: %2deg alt: %3ft pitch: %4deg bank: %5deg hdg: %6deg airspeed: %7kts onGround: %8");
3121 return positionStr.arg(position.Latitude)
3122 .arg(position.Longitude)
3123 .arg(position.Altitude)
3124 .arg(position.Pitch)
3125 .arg(position.Bank)
3126 .arg(position.Heading)
3127 .arg(position.Airspeed)
3128 .arg(position.OnGround);
3129 }
3130
3131 CCallsignSet CSimulatorFsxCommon::getCallsignsMissingInProvider() const
3132 {
3134 {
3135 return CCallsignSet();
3136 }
3137 const CCallsignSet simObjectCallsigns(m_simConnectObjects.getAllCallsigns(true));
3138 const CCallsignSet providerCallsigns(this->getAircraftInRangeCallsigns());
3139 return simObjectCallsigns.difference(providerCallsigns);
3140 }
3141
3142 void CSimulatorFsxCommon::traceSendId(const CSimConnectObject &simObject, const QString &functionName,
3143 const QString &details, bool forceTrace)
3144 {
3145 if (!forceTrace && !this->isTracingSendId())
3146 {
3147 return;
3148 }
3149 if (MaxSendIdTraces < 1)
3150 {
3151 return;
3152 } // cppcheck-suppress knownConditionTrueFalse
3153 DWORD dwLastId = 0;
3154 const HRESULT hr = SimConnect_GetLastSentPacketID(m_hSimConnect, &dwLastId);
3155 if (isFailure(hr))
3156 {
3157 return;
3158 }
3159 if (m_sendIdTraces.size() > MaxSendIdTraces)
3160 {
3161 m_sendIdTraces.removeLast();
3162 }
3163 const TraceFsxSendId trace(dwLastId, simObject,
3164 details.isEmpty() ? functionName : details % u", " % functionName);
3165 m_sendIdTraces.push_front(trace);
3166 }
3167
3168 HRESULT CSimulatorFsxCommon::logAndTraceSendId(HRESULT hr, const QString &warningMsg, const QString &functionName,
3169 const QString &functionDetails)
3170 {
3171 const CSimConnectObject empty;
3172 return this->logAndTraceSendId(hr, empty, warningMsg, functionName, functionDetails);
3173 }
3174
3175 HRESULT CSimulatorFsxCommon::logAndTraceSendId(HRESULT hr, const CSimConnectObject &simObject,
3176 const QString &warningMsg, const QString &functionName,
3177 const QString &functionDetails)
3178 {
3179 return this->logAndTraceSendId(hr, this->isTracingSendId(), simObject, warningMsg, functionName,
3180 functionDetails);
3181 }
3182
3183 HRESULT CSimulatorFsxCommon::logAndTraceSendId(HRESULT hr, bool doTraceSendId, const CSimConnectObject &simObject,
3184 const QString &warningMsg, const QString &functionName,
3185 const QString &functionDetails)
3186 {
3187 if (doTraceSendId)
3188 {
3189 this->traceSendId(simObject, functionName, functionDetails);
3190 }
3191 if (isOk(hr))
3192 {
3193 return hr;
3194 }
3195 if (!warningMsg.isEmpty())
3196 {
3197 CLogMessage(this).warning(warningMsg % u" SimObject: " % simObject.toQString());
3198 }
3199 this->triggerAutoTraceSendId();
3200 return hr;
3201 }
3202
3203 QByteArray CSimulatorFsxCommon::toFsxChar(const QString &string) { return string.toLatin1(); }
3204
3205 TraceFsxSendId CSimulatorFsxCommon::getSendIdTrace(DWORD sendId) const
3206 {
3207 for (const TraceFsxSendId &trace : m_sendIdTraces)
3208 {
3209 if (trace.sendId == sendId)
3210 {
3211 return trace;
3212 }
3213 }
3214 return TraceFsxSendId::invalid();
3215 }
3216
3217 QString CSimulatorFsxCommon::getSendIdTraceDetails(DWORD sendId) const
3218 {
3219 const TraceFsxSendId trace = this->getSendIdTrace(sendId);
3220 if (trace.sendId == sendId)
3221 {
3222 return this->getSendIdTraceDetails(trace);
3223 }
3224 return {};
3225 }
3226
3227 QString CSimulatorFsxCommon::getSendIdTraceDetails(const TraceFsxSendId &trace) const
3228 {
3229 static const QString d("Send id: %1 obj.id.: %2 SimObj: %3 | '%4'");
3230 if (trace.isInvalid())
3231 {
3232 return QString();
3233 }
3234
3235 // update with latest sim object
3236 const CSimConnectObject simObject = this->getSimObjectForTrace(trace);
3237 return d.arg(trace.sendId).arg(simObject.getObjectId()).arg(simObject.toQString(), trace.comment);
3238 }
3239
3240 int CSimulatorFsxCommon::removeAllProbes()
3241 {
3242 if (!m_hSimConnect)
3243 {
3244 return 0;
3245 } // already disconnected
3246 const QList<CSimConnectObject> probes = m_simConnectObjects.getProbes();
3247
3248 int c = 0;
3249 for (const CSimConnectObject &probeSimObject : probes)
3250 {
3251 if (!probeSimObject.isConfirmedAdded())
3252 {
3253 continue;
3254 }
3255 const SIMCONNECT_DATA_REQUEST_ID requestId =
3256 probeSimObject.getRequestId(CSimConnectDefinitions::SimObjectRemove);
3257 const HRESULT result = SimConnect_AIRemoveObject(
3258 m_hSimConnect, static_cast<SIMCONNECT_OBJECT_ID>(probeSimObject.getObjectId()), requestId);
3259 if (isOk(result))
3260 {
3261 c++;
3262 }
3263 else
3264 {
3265 CLogMessage(this).warning(u"Removing probe '%1' from simulator failed") << probeSimObject.getObjectId();
3266 }
3267 }
3268 m_simConnectObjects.removeAllProbes();
3269 m_pendingProbeRequests.clear();
3270 return c;
3271 }
3272
3273 CSimConnectObject CSimulatorFsxCommon::insertNewSimConnectObject(const CSimulatedAircraft &aircraft,
3274 DWORD requestId,
3276 const CSimConnectObject &removedPendingObject)
3277 {
3278 if (m_simConnectObjects.contains(aircraft.getCallsign()))
3279 {
3280 // error, ...?
3281 CSimConnectObject &simObject = m_simConnectObjects[aircraft.getCallsign()];
3282 simObject.copyAddingFailureCounters(removedPendingObject);
3283 simObject.resetTimestampToNow();
3284 return simObject;
3285 }
3286
3287 CSimConnectObject simObject;
3288 if (m_simConnectObjectsPositionAndPartsTraces.contains(aircraft.getCallsign()))
3289 {
3290 // if in traces, get the object and reuse it
3291 simObject = m_simConnectObjectsPositionAndPartsTraces[aircraft.getCallsign()];
3292 m_simConnectObjectsPositionAndPartsTraces.remove(aircraft.getCallsign());
3293 simObject.resetState();
3294 simObject.setRequestId(requestId);
3295 simObject.setAircraft(aircraft);
3296 simObject.attachInterpolatorLogger(&m_interpolationLogger); // setting a logger does not start logging
3297 }
3298 else
3299 {
3300 simObject = CSimConnectObject(aircraft, requestId, this, this, this->getRemoteAircraftProvider(),
3302 }
3303 simObject.copyAddingFailureCounters(removedPendingObject);
3304 simObject.setType(type);
3305 m_simConnectObjects.insert(simObject, true); // update timestamp
3306 return simObject;
3307 }
3308
3309 const CAltitude &CSimulatorFsxCommon::terrainProbeAltitude()
3310 {
3311 static const CAltitude alt(50000, CLengthUnit::ft());
3312 return alt;
3313 }
3314
3315 QString CSimulatorFsxCommon::fsxCharToQString(const char *fsxChar, int size)
3316 {
3317 return QString::fromLatin1(fsxChar, size);
3318 }
3319
3320 QString CSimulatorFsxCommon::requestIdToString(DWORD requestId)
3321 {
3323 {
3325 }
3326
3329
3330 static const QString req("%1 %2 %3");
3331 return req.arg(requestId)
3332 .arg(CSimConnectObject::typeToString(simType))
3334 }
3335
3336 DWORD CSimulatorFsxCommon::unitTestRequestId(CSimConnectObject::SimObjectType type)
3337 {
3338 int start;
3339 int end;
3340 switch (type)
3341 {
3342 case CSimConnectObject::TerrainProbe:
3343 start = RequestSimObjTerrainProbeStart;
3344 end = RequestSimObjTerrainProbeEnd;
3345 break;
3346 case CSimConnectObject::AircraftNonAtc:
3347 case CSimConnectObject::AircraftSimulatedObject:
3348 default:
3349 start = RequestSimObjAircraftStart;
3350 end = RequestSimObjAircraftEnd;
3351 break;
3352 }
3353
3354 const int id = CMathUtils::randomInteger(start, end);
3355 return static_cast<DWORD>(id);
3356 }
3357
3358 CCallsignSet CSimulatorFsxCommon::physicallyRemoveAircraftNotInProvider()
3359 {
3360 const CCallsignSet callsignsToBeRemoved(this->getCallsignsMissingInProvider());
3361 if (callsignsToBeRemoved.isEmpty())
3362 {
3363 return callsignsToBeRemoved;
3364 }
3365 for (const CCallsign &callsign : callsignsToBeRemoved)
3366 {
3367 this->physicallyRemoveRemoteAircraft(callsign);
3368 }
3369
3370 if (this->showDebugLogMessage())
3371 {
3372 this->debugLogMessage(Q_FUNC_INFO,
3373 QStringLiteral("CS: '%1'").arg(callsignsToBeRemoved.toStringList().join(", ")));
3374 }
3375 return callsignsToBeRemoved;
3376 }
3377
3378 void CSimulatorFsxCommon::physicallyRemoveAircraftNotInProviderAsync()
3379 {
3380 const QPointer<CSimulatorFsxCommon> myself(this);
3381 QTimer::singleShot(100, this, [=] {
3382 if (!myself || this->isShuttingDown())
3383 {
3384 return;
3385 }
3386 CSimulatorFsxCommon::physicallyRemoveAircraftNotInProvider();
3387 });
3388 }
3389
3391 : ISimulatorListener(info)
3392 {
3393 m_timer.setInterval(MinQueryIntervalMs);
3394 m_timer.setObjectName(this->objectName().append(":m_timer"));
3395 connect(&m_timer, &QTimer::timeout, this, &CSimulatorFsxCommonListener::checkConnection);
3396 }
3397
3399 {
3400 m_simulatorVersion.clear();
3401 m_simConnectVersion.clear();
3402 m_simulatorName.clear();
3403 m_simulatorDetails.clear();
3404
3405 m_timer.start();
3406 }
3407
3409 {
3410 m_timer.stop();
3411 this->disconnectFromSimulator();
3412 }
3413
3415 {
3416 if (!m_timer.isActive())
3417 {
3418 return;
3419 }
3420 if (this->isShuttingDown())
3421 {
3422 return;
3423 }
3424
3426 QTimer::singleShot(0, this, [=] {
3427 if (!myself || !sApp || sApp->isShuttingDown())
3428 {
3429 return;
3430 }
3431 this->checkConnection();
3432 });
3433
3434 // restart because we have just checked now
3435 m_timer.start();
3436 }
3437
3439 {
3440 if (m_simulatorName.isEmpty())
3441 {
3443 }
3444 return m_simulatorDetails;
3445 }
3446
3447 void CSimulatorFsxCommonListener::checkConnection()
3448 {
3449 Q_ASSERT_X(!CThreadUtils::thisIsMainThread(), Q_FUNC_INFO, "Expect to run in background");
3450
3451 // check before we access the sim. connection
3452 if (this->isShuttingDown() || this->thread()->isInterruptionRequested())
3453 {
3454 this->stopImpl();
3455 return;
3456 }
3457
3458 QElapsedTimer t;
3459 t.start();
3460 bool check = false;
3461 do
3462 {
3463 // if we can connect, but not dispatch, it can mean a previously started FSX/P3D
3464 // blocks remote calls -> RESTART
3465 if (!this->connectToSimulator())
3466 {
3467 break;
3468 }
3469
3470 // check if we have the right sim.
3471 // this check on a remote FSX/P3D not running/existing might TAKE LONG!
3472 const HRESULT result =
3473 SimConnect_CallDispatch(m_hSimConnect, CSimulatorFsxCommonListener::SimConnectProc, this);
3474
3475 // make sure we did not stop in meantime
3476 if (this->isShuttingDown() || this->thread()->isInterruptionRequested())
3477 {
3478 this->stopImpl();
3479 return;
3480 }
3481
3482 if (isFailure(result))
3483 {
3484 break;
3485 } // means serious failure
3486 check = this->checkVersionAndSimulator();
3487 }
3488 while (false);
3489
3490 this->adjustTimerInterval(t.elapsed());
3491 if (check)
3492 {
3493 emit this->simulatorStarted(this->getPluginInfo());
3494 }
3495 }
3496
3497 void CSimulatorFsxCommonListener::adjustTimerInterval(qint64 checkTimeMs)
3498 {
3499 const QString sim = this->getPluginInfo().getSimulatorInfo().toQString(true);
3500 CLogMessage(this).debug(u"Checked sim.'%1' connection in %2ms") << sim << checkTimeMs;
3501 if (checkTimeMs > qRound(1.25 * MinQueryIntervalMs))
3502 {
3503 const int newIntervalMs = qRound(1.2 * checkTimeMs / 1000.0) * 1000;
3504 CLogMessage(this).debug(u"Check for simulator sim.'%1' connection in %2ms, too slow. Setting %3ms")
3505 << sim << checkTimeMs << newIntervalMs;
3506 if (m_timer.interval() != newIntervalMs)
3507 {
3508 m_timer.setInterval(newIntervalMs);
3509 }
3510 }
3511 else
3512 {
3513 if (m_timer.interval() != MinQueryIntervalMs)
3514 {
3515 m_timer.setInterval(MinQueryIntervalMs);
3516 }
3517 }
3518
3519 // restart
3520 m_timer.start();
3521 }
3522
3523 bool CSimulatorFsxCommonListener::checkVersionAndSimulator() const
3524 {
3525 const CSimulatorInfo pluginSim(getPluginInfo().getIdentifier());
3526 const QString connectedSimName = m_simulatorName.toLower().trimmed();
3527
3528 if (connectedSimName.isEmpty())
3529 {
3530 return false;
3531 }
3532 if (pluginSim.isP3D())
3533 {
3534 // P3D drivers only works with P3D
3535 return connectedSimName.contains("lockheed") || connectedSimName.contains("martin") ||
3536 connectedSimName.contains("p3d") || connectedSimName.contains("prepar");
3537 }
3538 else if (pluginSim.isMSFS())
3539 {
3540 // MSFS 2020 drivers only works with MSFS
3541 return connectedSimName.contains("kittyhawk");
3542 }
3543 else if (pluginSim.isMSFS2024())
3544 {
3545 // MSFS2024 drivers only works with MSFS2024
3546 return connectedSimName.contains("sunrise");
3547 }
3548 return false;
3549 }
3550
3551 bool CSimulatorFsxCommonListener::checkSimConnectDll() const
3552 {
3553 static const CWinDllUtils::DLLInfo simConnectInfo = CSimConnectUtilities::simConnectDllInfo();
3554 if (!simConnectInfo.errorMsg.isEmpty())
3555 {
3556 return false;
3557 }
3558 return true;
3559 }
3560
3561 bool CSimulatorFsxCommonListener::connectToSimulator()
3562 {
3563 if (m_simConnected)
3564 {
3565 return true;
3566 }
3567 const HRESULT result = SimConnect_Open(&m_hSimConnect, sApp->swiftVersionChar(), nullptr, 0, nullptr, 0);
3568 const bool ok = isOk(result);
3569 m_simConnected = ok;
3570 return ok;
3571 }
3572
3573 bool CSimulatorFsxCommonListener::disconnectFromSimulator()
3574 {
3575 if (!m_simConnected)
3576 {
3577 return false;
3578 }
3579 SimConnect_Close(m_hSimConnect);
3580 m_hSimConnect = nullptr;
3581 m_simConnected = false;
3582 return true;
3583 }
3584
3585 void CSimulatorFsxCommonListener::SimConnectProc(SIMCONNECT_RECV *pData, DWORD cbData, void *pContext)
3586 {
3587 Q_UNUSED(cbData)
3588 CSimulatorFsxCommonListener *simListener = static_cast<CSimulatorFsxCommonListener *>(pContext);
3589 switch (pData->dwID)
3590 {
3591 case SIMCONNECT_RECV_ID_OPEN:
3592 {
3593 SIMCONNECT_RECV_OPEN *event = static_cast<SIMCONNECT_RECV_OPEN *>(pData);
3594 simListener->m_simulatorVersion = QStringLiteral("%1.%2.%3.%4")
3595 .arg(event->dwApplicationVersionMajor)
3596 .arg(event->dwApplicationVersionMinor)
3597 .arg(event->dwApplicationBuildMajor)
3598 .arg(event->dwApplicationBuildMinor);
3599 simListener->m_simConnectVersion = QStringLiteral("%1.%2.%3.%4")
3600 .arg(event->dwSimConnectVersionMajor)
3601 .arg(event->dwSimConnectVersionMinor)
3602 .arg(event->dwSimConnectBuildMajor)
3603 .arg(event->dwSimConnectBuildMinor);
3604 simListener->m_simulatorName = CSimulatorFsxCommon::fsxCharToQString(event->szApplicationName);
3605 simListener->m_simulatorDetails = QStringLiteral("Name: '%1' Version: %2 SimConnect: %3")
3606 .arg(simListener->m_simulatorName, simListener->m_simulatorVersion,
3607 simListener->m_simConnectVersion);
3608 const CStatusMessage msg = CStatusMessage(simListener).info(u"Connect to %1: '%2'")
3609 << simListener->getPluginInfo().getIdentifier() << simListener->backendInfo();
3610
3611 // avoid the same message over and over again
3612 if (msg.getMessage() != simListener->m_lastMessage.getMessage())
3613 {
3615 simListener->m_lastMessage = msg;
3616 }
3617 break;
3618 }
3619 case SIMCONNECT_RECV_ID_EXCEPTION: break;
3620 default: break;
3621 }
3622 }
3623} // namespace swift::simplugin::fsxcommon
SWIFT_CORE_EXPORT swift::core::CApplication * sApp
Single instance of application object.
static CAngleUnit rad()
Radians.
Definition units.h:268
static CAngleUnit deg()
Degrees.
Definition units.h:276
static CFrequencyUnit MHz()
Megahertz.
Definition units.h:380
static bool isLocalDeveloperDebugBuild()
Local build for developers.
const char * swiftVersionChar()
swift info string
static QString statusToString(SimulatorStatus status)
Status to string.
virtual void callbackReceivedRequestedElevation(const swift::misc::geo::CElevationPlane &plane, const swift::misc::aviation::CCallsign &callsign, bool isWater)
A requested elevation has been received.
virtual void setFlightNetworkConnected(bool connected)
Flight network has been connected.
bool showDebugLogMessage() const
Show log messages?
bool addLoopbackSituation(const swift::misc::aviation::CAircraftSituation &situation)
Add a loopback situation if logging is enabled.
bool isEqualLastSent(const swift::misc::aviation::CAircraftSituation &compare) const
Equal to last sent situation.
bool updateOwnSituationAndGroundElevation(const swift::misc::aviation::CAircraftSituation &situation)
Update own aircraft position and if suitable use it to update ground elevation.
virtual void onOwnModelChanged(const swift::misc::simulation::CAircraftModel &newModel)
Own model has been changed.
bool isUpdateAllRemoteAircraft(qint64 currentTimestamp=-1) const
Do update all remote aircraft?
virtual bool isShuttingDown() const
Is overall (swift) application shutting down.
Definition simulator.h:214
int m_timerId
dispatch timer id
Definition simulator.h:561
void requestedElevation(const swift::misc::aviation::CCallsign &callsign)
Requested elevation, call pending.
bool m_updateRemoteAircraftInProgress
currently updating remote aircraft
Definition simulator.h:559
virtual bool isShuttingDownDisconnectedOrNoAircraft() const
Shutting down, disconnected, or no remote aircraft.
Definition simulator.h:220
virtual void clearAllRemoteAircraftData()
Clear all aircraft related data, but do not physically remove the aircraft.
void physicallyAddingRemoteModelFailed(const swift::misc::simulation::CSimulatedAircraft &remoteAircraft, bool disabled, bool requestFailover, const swift::misc::CStatusMessage &message)
Adding the remote model failed.
void rememberElevationAndSimulatorCG(const swift::misc::aviation::CCallsign &callsign, const swift::misc::simulation::CAircraftModel &model, bool likelyOnGroundElevation, const swift::misc::geo::CElevationPlane &elevation, const swift::misc::physical_quantities::CLength &simulatorCG)
Set elevation and CG in the providers and for auto publishing.
bool isAircraftInRangeOrTestMode(const swift::misc::aviation::CCallsign &callsign) const
Test version aware version of isAircraftInRange.
void finishUpdateRemoteAircraftAndSetStatistics(qint64 startTime, bool limited=false)
Update stats and flags.
bool isTestMode() const
Test mode? (driver can skip code parts etc., driver dependent).
Definition simulator.h:183
void debugLogMessage(const QString &msg)
Display a debug log message based on swift::misc::simulation::CInterpolationAndRenderingSetup remark ...
virtual swift::misc::CStatusMessageList debugVerifyStateAfterAllAircraftRemoved() const
Debug function to check state after all aircraft have been removed.
void emitSimulatorCombinedStatus(SimulatorStatus oldStatus=Unspecified)
Emit the combined status.
int m_statsUpdateAircraftRuns
statistics update count
Definition simulator.h:562
swift::misc::simulation::CSimulatedAircraftList m_addAgainAircraftWhenRemoved
add this model again when removed, normally used to change model
Definition simulator.h:590
swift::misc::simulation::CSimulatorInternals m_simulatorInternals
setup read from the sim
Definition simulator.h:581
virtual int physicallyRemoveAllRemoteAircraft()
Remove all remote aircraft and their data via ISimulator::clearAllRemoteAircraftData.
void logAddingAircraftModel(const swift::misc::simulation::CSimulatedAircraft &aircraft) const
Unified qeeing aircraft message.
@ Disconnected
not connected, and hence not simulating/paused
Definition simulator.h:69
@ Simulating
Is the simulator actually simulating?
Definition simulator.h:71
swift::misc::simulation::CInterpolationAndRenderingSetupPerCallsign getInterpolationSetupConsolidated(const swift::misc::aviation::CCallsign &callsign, bool forceFullUpdate) const
Consolidate setup with other data like from swift::misc::simulation::IRemoteAircraftProvider.
virtual SimulatorStatus getSimulatorStatus() const
Combined status.
Definition simulator.cpp:54
swift::misc::simulation::settings::CSpecializedSimulatorSettings getSimulatorSettings() const
Settings for current simulator.
Definition simulator.h:162
swift::misc::simulation::CInterpolationLogger m_interpolationLogger
log.interpolation
Definition simulator.h:582
bool isUpdateAircraftLimitedWithStats(qint64 startTime=-1)
Limited as ISimulator::isUpdateAircraftLimited plus updating statistics.
void safeKillTimer()
Kill timer if id is valid.
void aircraftRenderingChanged(const swift::misc::simulation::CSimulatedAircraft &aircraft)
Aircraft rendering changed.
bool isFlightNetworkConnected() const
Is the flight network connected.
Definition simulator.h:159
virtual bool isShuttingDownOrDisconnected() const
Shutting down or disconnected?
Definition simulator.h:217
void driverMessages(const swift::misc::CStatusMessageList &messages)
Relevant simulator messages to be explicitly displayed.
virtual bool parseDetails(const swift::misc::CSimpleCommandParser &parser)=0
Parsed in derived classes.
swift::misc::aviation::CAircraftSituationPerCallsign m_lastSentSituations
last situations sent to simulator
Definition simulator.h:585
void rememberLastSent(const swift::misc::aviation::CAircraftSituation &sent)
Remember as last sent.
void simulatorStarted(const swift::misc::simulation::CSimulatorPluginInfo &info)
Emitted when the listener discovers the simulator running.
const swift::misc::simulation::CSimulatorPluginInfo & getPluginInfo() const
Corresponding info.
Definition simulator.h:641
ISimulatorListener(const swift::misc::simulation::CSimulatorPluginInfo &info)
Constructor.
virtual bool isShuttingDown() const
Overall (swift) application shutting down.
void check()
Check simulator availability.
virtual QString backendInfo() const
Info about the backend system (if available).
iterator push_back(const T &value)
Synonym for insert.
Definition collection.h:244
const CIdentifier & identifier() const
Get identifier.
Value object encapsulating information identifying a component of a modular distributed swift process...
Definition identifier.h:29
static const QString & cmdLine()
Cmd.line parsing.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
bool isEmpty() const
Message empty.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
Derived & log(StatusSeverity s, const char16_t(&m)[N])
Set the severity and format string.
bool contains(const T &object) const
Return true if there is an element equal to given object. Uses the most efficient implementation avai...
Definition range.h:109
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Utility methods for simple line parsing used with the command line.
static void registerCommand(const CommandHtmlHelp &command)
Register a command.
bool toBool(int index, bool def=false) const
Part as bool.
bool matchesPart(int index, const QString &toMatch, Qt::CaseSensitivity cs=Qt::CaseInsensitive) const
Matches given part.
bool hasPart(int index) const
Existing part.
static bool registered(const QString &helpContext)
Help already registered.
Streamable status message, e.g.
bool isWarningOrAbove() const
Warning or above.
static constexpr auto SeverityInfo
Status severities.
static constexpr auto SeverityError
Status severities.
StatusSeverity getSeverity() const
Message severity.
QString getMessage() const
Message.
static constexpr auto SeverityDebug
Status severities.
static constexpr auto SeverityWarning
Status severities.
Status messages, e.g. from Core -> GUI.
CStatusMessage toSingleMessage() const
Merge into a single message.
static bool thisIsMainThread()
Is the current thread the application thread?
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
void setMSecsSinceEpoch(qint64 mSecsSinceEpoch)
Timestamp as ms value.
Value object encapsulating a list of aircraft engines.
static const CAircraftIcaoCode & unassignedIcao()
Unassigned ICAO code "ZZZZ".
Value object encapsulating information about aircraft's lights.
bool isRecognitionOn() const
Recognition lights on?
bool isCabinOn() const
Cabin lights on?
bool isLandingOn() const
Landing lights on?
bool isBeaconOn() const
Beacon lights on?
bool isNavOn() const
Nac lights on?
bool isLogoOn() const
Logo lights on?
bool isTaxiOn() const
Taxi lights on?
bool isStrobeOn() const
Strobes lights on?
Value object encapsulating information of aircraft's parts.
bool isNull() const
NULL parts object?
CAircraftLights getAdjustedLights() const
Lights adjusted depending on engines.
PartsDetails getPartsDetails() const
Get parts details.
int getFlapsPercent() const
Get flaps position in percent.
Value object encapsulating information of an aircraft's situation.
void setPressureAltitude(const CAltitude &altitude)
Set pressure altitude.
void setGroundSpeed(const physical_quantities::CSpeed &groundspeed)
Set ground speed.
bool setGroundElevation(const aviation::CAltitude &altitude, GndElevationInfo info, bool transferred=false)
Elevation of the ground directly beneath at the given situation.
void setBank(const physical_quantities::CAngle &bank)
Set bank (angle).
const CHeading & getHeading() const
Get heading.
void setHeading(const CHeading &heading)
Set heading.
AltitudeCorrection
How was altitude corrected?
const physical_quantities::CAngle & getBank() const
Get bank (angle).
@ FromProvider
from swift::misc::simulation::ISimulationEnvironmentProvider
bool isOnGroundInfoAvailable() const
On ground info available?
void setAltitude(const CAltitude &altitude)
Set altitude.
const CAltitude & geodeticHeight() const
Height, ellipsoidal or geodetic height (used in GPS).
static bool isCorrectedAltitude(AltitudeCorrection correction)
Means corrected altitude?
CAltitude getCorrectedAltitude(bool enableDragToGround=true, AltitudeCorrection *correction=nullptr) const
Get altitude under consideration of ground elevation and ground flag.
void setOnGroundInfo(const aviation::COnGroundInfo &info)
Set the on ground info.
const physical_quantities::CAngle & getPitch() const
Get pitch.
void setPitch(const physical_quantities::CAngle &pitch)
Set pitch.
const CAltitude & getAltitude() const
Get altitude.
const physical_quantities::CSpeed & getGroundSpeed() const
Get ground speed.
void setVelocity(const CAircraftVelocity &velocity)
Set 6DOF velocity.
bool isMoving() const
Is moving? Means ground speed > epsilon.
void setPosition(const geo::CCoordinateGeodetic &position)
Set position.
Velocity and angular velocity for 6DOF bodies.
Altitude as used in aviation, can be AGL or MSL altitude.
Definition altitude.h:52
@ PressureAltitude
Altitude above the standard datum plane.
Definition altitude.h:82
@ TrueAltitude
Height of the airplane above Mean Sea Level (MSL).
Definition altitude.h:83
ReferenceDatum getReferenceDatum() const
Get reference datum (MSL or AGL).
Definition altitude.h:145
Value object encapsulating information of a callsign.
Definition callsign.h:30
const QString & asString() const
Get callsign (normalized).
Definition callsign.h:96
bool isEmpty() const
Is empty?
Definition callsign.h:63
Value object for a set of callsigns.
Definition callsignset.h:26
QString getCallsignsAsString(bool sorted=false, const QString &separator=", ") const
Callsigns as string.
COM system (aka "radio").
Definition comsystem.h:37
static bool isWithin25kHzChannel(const physical_quantities::CFrequency &freq)
Is frequency within 25 kHz frequency spacing.
static bool isExclusiveWithin8_33kHzChannel(const physical_quantities::CFrequency &freq)
Is frequency a "new" 8.33 kHz frequency and not within 25 kHz spacing E.g. returns false for 122....
Heading as used in aviation, can be true or magnetic heading.
Definition heading.h:41
static QString getStandardCode(const aviation::CAirlineIcaoCode &airline)
Standard code for airline.
Definition livery.cpp:333
swift::misc::physical_quantities::CFrequency getFrequencyStandby() const
Standby frequency.
Definition modulator.cpp:36
swift::misc::physical_quantities::CFrequency getFrequencyActive() const
Active frequency.
Definition modulator.cpp:30
@ OutOnGroundOwnAircraft
sending on ground
Value object for SELCAL.
Definition selcal.h:31
bool isIdentifying() const
Standby?
Definition transponder.h:89
bool isInStandby() const
Standby?
Definition transponder.h:86
bool setTransponderMode(TransponderMode mode)
Set transponder mode.
@ StateStandby
not a real mode, more a state
Definition transponder.h:33
@ StateIdent
not a real mode, more a state
Definition transponder.h:39
TransponderMode getTransponderMode() const
Transponder mode.
Definition transponder.h:95
void setLatitude(const CLatitude &latitude)
Set latitude.
void setGeodeticHeight(const aviation::CAltitude &height)
Set height (ellipsoidal or geodetic height).
const aviation::CAltitude & geodeticHeight() const
Height, ellipsoidal or geodetic height (used in GPS).
void setLongitude(const CLongitude &longitude)
Set longitude.
static const physical_quantities::CLength & singlePointRadius()
Radius for single point.
static const CElevationPlane & null()
NULL plane.
Geodetic coordinate, a position in 3D space relative to the reference geoid.
virtual CLongitude longitude() const =0
Longitude.
virtual const aviation::CAltitude & geodeticHeight() const =0
Height, ellipsoidal or geodetic height (used in GPS).
virtual bool isNull() const
Is null, means vector x, y, z == 0.
bool isGeodeticHeightNull() const
Geodetic height null?
virtual CLatitude latitude() const =0
Latitude.
static int randomInteger(int low, int high)
Random number between low and high.
Definition mathutils.cpp:77
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
Value object encapsulating information of a text message.
Definition textmessage.h:31
bool isPrivateMessage() const
Is private message?
QString asString(bool withSender, bool withRecipient, const QString &separator=", ") const
Whole message as formatted string. Used to display message in a console window.
bool isRadioMessage() const
Is radio message?
bool isSupervisorMessage() const
Supervisor message?
Direct in memory access to client (network client) data.
Physical unit angle (radians, degrees).
Definition angle.h:23
static CLengthUnit m()
Meter m.
Definition units.h:140
static CLengthUnit ft()
Foot ft.
Definition units.h:157
double value(MU unit) const
Value in given unit.
static CSpeedUnit ft_s()
Feet/second ft/s.
Definition units.h:834
static CSpeedUnit kts()
Knots.
Definition units.h:817
static CTimeUnit s()
Second s.
Definition units.h:938
Aircraft model (used by another pilot, my models on disk).
bool hasExistingCorrespondingFile() const
Does the corresponding file exist?
const aviation::CCallsign & getCallsign() const
Corresponding callsign if applicable.
@ TypeTerrainProbe
peudo aircraft used for terrain probing (FSX)
CStatusMessageList verifyModelData() const
Verify the model data.
const QString & getFileName() const
File name (corresponding data for simulator, only available if representing simulator model.
const QString & getModelString() const
Model key, either queried or loaded from simulator model.
bool isForcingFullInterpolation() const
Full interpolation (skip optimizations like checking if aircraft moves etc.).
Value object for interpolator and rendering per callsign.
const CInterpolationStatus & getInterpolationStatus() const
Get status.
const CPartsStatus & getPartsStatus() const
Get status.
const aviation::CAircraftSituation & getInterpolatedSituation() const
Get situation.
bool hasValidSituation() const
Is the corresponding position valid?
bool isInterpolated() const
Did interpolation succeed?
bool updateOwnParts(const aviation::CAircraftParts &parts)
Update own parts.
bool updateOwnCG(const physical_quantities::CLength &cg)
Update own aircraft's CG (aka vertical offset).
bool updateCockpit(const swift::misc::simulation::CSimulatedAircraft &aircraft, const swift::misc::CIdentifier &originator)
Update cockpit, but only send signals when applicable.
swift::misc::geo::CCoordinateGeodetic getOwnAircraftPosition() const
Own aircraft's position.
CSimulatedAircraft getOwnAircraft() const
Own aircraft.
bool isReusedParts() const
Is a reused parts object?
Definition partsstatus.h:33
bool isSupportingParts() const
Supporting parts.
Definition partsstatus.h:26
aviation::CCallsignSet getAircraftInRangeCallsigns() const
Unique callsigns for aircraft in range.
bool isAircraftInRange(const aviation::CCallsign &callsign) const
Is aircraft in range?
IRemoteAircraftProvider * getRemoteAircraftProvider() const
Get the aircraft provider.
bool updateMultipleAircraftEnabled(const aviation::CCallsignSet &callsigns, bool enabledForRendering)
Enable/disable aircraft.
aviation::CAircraftSituationList remoteAircraftSituations(const aviation::CCallsign &callsign) const
Rendered aircraft situations (per callsign, time history).
int getAircraftInRangeCount() const
Count remote aircraft.
bool updateAircraftEnabled(const aviation::CCallsign &callsign, bool enabledForRendering)
Enable/disable aircraft and follow up logic like sending signals.
bool updateCGAndModelString(const aviation::CCallsign &callsign, const physical_quantities::CLength &cg, const QString &modelString)
Update the CG and model string.
bool updateAircraftRendered(const aviation::CCallsign &callsign, bool rendered)
Set aircraft rendered.
Comprehensive information of an aircraft.
bool hasModelString() const
Has model string?
const aviation::CComSystem & getCom2System() const
Get COM2 system.
const aviation::CComSystem & getCom1System() const
Get COM1 system.
const QString & getModelString() const
Get model string.
const aviation::CCallsign & getCallsign() const
Get callsign.
const aviation::CTransponder & getTransponder() const
Get transponder.
const aviation::CAircraftSituation & getSituation() const
Get situation.
QString getCallsignAsString() const
Get callsign.
Simple hardcoded info about the corresponding simulator.
const CSimulatorInfo & getSimulatorInfo() const
Simulator info object.
const QString & getIdentifier() const
Identifier.
bool isLogCallsign(const aviation::CCallsign &callsign) const
Is callsign marked for logging.
CInterpolationAndRenderingSetupPerCallsign getInterpolationSetupPerCallsignOrDefault(const aviation::CCallsign &callsign) const
Get the setup for callsign, if not existing the global setup.
Direct threadsafe in memory access to own aircraft.
Direct thread safe in memory access to remote aircraft.
CSimulatorPluginInfo getSimulatorPluginInfo() const
Get the represented plugin.
CSimulatorInfo getSimulatorInfo() const
Get the represented simulator.
QString getSimulatorDetails() const
Simulator details as set from the running simulator.
QString getTitlesAsString(bool sorted, const QString &separator=", ") const
All titles as string.
bool containsTitle(const QString &title) const
Can check if a title (model string) is known.
static CAircraftCfgEntriesList performParsingOfSingleFile(const QString &fileName, bool &ok, CStatusMessageList &msgs)
Parse a single file.
static quint32 comFrequencyToBcdHz(const swift::misc::physical_quantities::CFrequency &comFrequency)
COM Frequency to BCD.
static bool adjustFileDirectory(CAircraftModel &model, const QString &simObjectsDirectory)
Adjust file directory.
static swift::misc::CWinDllUtils::DLLInfo simConnectDllInfo()
Get info about SimConnect DLL.
static QString simConnectReceiveIdToString(DWORD type)
Receive id to string.
bool isAddingAsSimulatedObjectEnabled() const
Use simulated object adding.
void setSbOffsetsEnabled(bool enable)
Use SB offsets?
void setAddingAsSimulatedObjectEnabled(bool enable)
Use simulated object adding.
bool isSbOffsetsEnabled() const
Are SB offsets enabled.
QStringList getModelDirectoriesOrDefault() const
Model directories or default.
virtual bool disconnectFrom()
Disconnect from simulator.
swift::misc::aviation::CComSystem m_simCom1
cockpit COM1 state in simulator
swift::misc::aviation::CSelcal m_selcal
SELCAL as in cockpit.
swift::misc::aviation::CComSystem m_simCom2
cockpit COM2 state in simulator
int m_ownAircraftUpdateCycles
own aircraft updates, even with 50 updates/sec long enough even for 32bit
CSimulatorFsCommon(const swift::misc::simulation::CSimulatorPluginInfo &info, swift::misc::simulation::IOwnAircraftProvider *ownAircraftProvider, swift::misc::simulation::IRemoteAircraftProvider *renderedAircraftProvider, swift::misc::network::IClientProvider *clientProvider, QObject *parent=nullptr)
Constructor.
swift::misc::aviation::CTransponder m_simTransponder
cockpit xpdr state in simulator
int m_skipCockpitUpdateCycles
skip some update cycles to allow changes in simulator cockpit to be set
virtual void initSimulatorInternals()
Init the internal objects.
SimObjectRequest
SimObject requests used for AI aircraft and probes.
@ SimObjectEndMarker
end marker, do NOT remove, also means invalid
static const QString & requestToString(Request request)
Request to string.
static HRESULT initDataDefinitionsWhenConnected(const HANDLE hSimConnect, const swift::misc::simulation::CSimulatorInfo &simInfo)
Initialize all data definitions.
static const QString & simObjectRequestToString(SimObjectRequest simObjectRequest)
Request to string.
@ DataClientAreaSbConnected
SB connected with network 0x7b81/1.
@ DataClientAreaSb
whole SB area, see http://squawkbox.ca/doc/sdk/fsuipc.php
@ DataRemoteAircraftModelData
model data eventually used and reported back from simulator
@ DataRemoteAircraftGetPosition
get position to evaluate altitude / AGL
Class representing a SimConnect object.
bool isPendingAdded() const
Object is requested in simulator, not yet confirmed added.
bool isConfirmedAdded() const
Adding is confirmed.
const swift::misc::aviation::CCallsign & getCallsign() const
Get callsign.
DWORD getObjectId() const
Get SimConnect object id.
QString toQString() const
SimObject as string.
bool hasValidRequestAndObjectId() const
Was the object really added to simulator.
bool hasCurrentLightsInSimulator() const
Received lights in simulator.
bool isPending() const
Pending added or removed?
static SimObjectType requestIdToType(DWORD requestId)
Type of id.
static const QString & typeToString(SimObjectType type)
Type to string.
DWORD getRequestId() const
Get SimConnect request id.
const swift::misc::simulation::CSimulatedAircraft & getAircraft() const
Simulated aircraft (as added).
SIMCONNECT_PERIOD getSimDataPeriod() const
How often do we request data from simulator for this remote aircraft.
void setRemovedWhileAdding(bool removedWhileAdding)
Special states.
bool isPendingRemoved() const
Removing is pending.
void copyAddingFailureCounters(const CSimConnectObject &otherObject)
Copy the counters from another object.
void setPendingRemoved(bool pending)
Marked as pending for removal.
swift::misc::aviation::CCallsignSet getAllCallsigns(bool withoutProbes=true) const
Get all callsigns.
CSimConnectObject getSimObjectForObjectId(DWORD objectId) const
Get object per object id.
bool isUsingFsxTerrainProbe() const
FSX Terrain probe.
virtual bool updateOwnSimulatorSelcal(const swift::misc::aviation::CSelcal &selcal, const swift::misc::CIdentifier &originator)
Update own aircraft cockpit (usually from context).
virtual bool isPhysicallyRenderedAircraft(const swift::misc::aviation::CCallsign &callsign) const
Is the aircraft rendered (displayed in simulator)? This shall only return true if the aircraft is rea...
virtual void setTrueAltitude(swift::misc::aviation::CAircraftSituation &aircraftSituation, const swift::simplugin::fsxcommon::DataDefinitionOwnAircraft &simulatorOwnAircraft)
Customization point for adjusting altitude to compensate for temperature effect.
virtual void displayTextMessage(const swift::misc::network::CTextMessage &message) const
Display a text message.
virtual swift::misc::CStatusMessageList debugVerifyStateAfterAllAircraftRemoved() const
Debug function to check state after all aircraft have been removed.
SIMCONNECT_DATA_REQUEST_ID obtainRequestIdForSimObjTerrainProbe()
Get new request id, overflow safe.
static bool isValid180Deg(double deg)
Valid 180degrees value.
bool removeSimObjectForTrace(const TraceFsxSendId &trace)
Remove the CSimConnectObject linked in the trace.
virtual void setFlightNetworkConnected(bool connected)
Flight network has been connected.
CSimConnectObjects m_simConnectObjects
AI objects and their object and request ids.
swift::misc::physical_quantities::CLength m_altitudeDelta
FS2020 effect of temperature on altitude.
QMap< DWORD, swift::misc::aviation::CCallsign > m_pendingProbeRequests
pending elevation requests: requestId/aircraft callsign
static QString fsxCharToQString(const char *fsxChar, int size=-1)
Encapsulates creating QString from FSX string data.
static SIMCONNECT_DATA_INITPOSITION coordinateToFsxPosition(const swift::misc::geo::ICoordinateGeodetic &coordinate)
Format conversion.
virtual bool requestElevation(const swift::misc::geo::ICoordinateGeodetic &reference, const swift::misc::aviation::CCallsign &aircraftCallsign)
Request elevation, there is no guarantee the requested elevation will be available in the provider.
static bool isRequestForSimObjTerrainProbe(DWORD requestId)
Request for probe (elevation)?
virtual void displayStatusMessage(const swift::misc::CStatusMessage &message) const
Display a status message in the simulator.
void setTractingSendId(bool trace)
Set tracing on/off.
HRESULT logAndTraceSendId(HRESULT hr, const QString &warningMsg, const QString &functionName, const QString &functionDetails={})
Trace if required, log errors.
virtual void removeCamera(CSimConnectObject &simObject)
Remove camera if any.
virtual int physicallyRemoveAllRemoteAircraft()
Remove all remote aircraft and their data via ISimulator::clearAllRemoteAircraftData.
CSimulatorFsxCommon(const swift::misc::simulation::CSimulatorPluginInfo &info, swift::misc::simulation::IOwnAircraftProvider *ownAircraftProvider, swift::misc::simulation::IRemoteAircraftProvider *remoteAircraftProvider, swift::misc::network::IClientProvider *clientProvider, QObject *parent=nullptr)
Constructor, parameters as in.
HANDLE m_hSimConnect
handle to SimConnect object
void setUsingSbOffsetValues(bool use)
Use SB offset values.
virtual bool physicallyAddRemoteAircraft(const swift::misc::simulation::CSimulatedAircraft &newRemoteAircraft)
Add new remote aircraft physically to the simulator.
SIMCONNECT_DATA_REQUEST_ID obtainRequestIdForSimObjAircraft()
Get new request id, overflow safe.
DispatchProc m_dispatchProc
called function for dispatch, can be overriden by specialized P3D function
virtual void removeObserver(CSimConnectObject &simObject)
Remove observer if any.
virtual void initSimulatorInternals()
Init the internal objects.
virtual bool testSendSituationAndParts(const swift::misc::aviation::CCallsign &callsign, const swift::misc::aviation::CAircraftSituation &situation, const swift::misc::aviation::CAircraftParts &parts)
Send situation/parts for testing.
virtual bool releaseAIControl(const CSimConnectObject &simObject, SIMCONNECT_DATA_REQUEST_ID requestId)
Release AI control.
virtual HRESULT initEventsP3D()
Specific P3D events.
virtual bool disconnectFrom()
Disconnect from simulator.
swift::misc::aviation::CCallsign getCallsignForPendingProbeRequests(DWORD requestId, bool remove)
Callsign for pending request.
bool isAddingAsSimulatedObjectEnabled() const
Allow adding as simulated object instead of non ATC.
void setAddingAsSimulatedObjectEnabled(bool enabled)
Allow adding as simulated object instead of non ATC.
virtual void onOwnModelChanged(const swift::misc::simulation::CAircraftModel &newModel)
Own model has been changed.
virtual swift::misc::aviation::CCallsignSet physicallyRenderedAircraft() const
Physically rendered (displayed in simulator) This shall only return aircraft handled in the simulator...
virtual bool isConnected() const
Are we connected to the simulator?
virtual void resetAircraftStatistics()
Reset the statistics.
virtual bool isSimulating() const
Simulator running?
static SIMCONNECT_DATA_INITPOSITION aircraftSituationToFsxPosition(const swift::misc::aviation::CAircraftSituation &situation, bool sendGnd=true, bool forceUnderflowDetection=false, swift::misc::CStatusMessage *details=nullptr)
Format conversion.
bool m_initFsxTerrainProbes
initialized terrain probes
static CSimConnectDefinitions::SimObjectRequest requestToSimObjectRequest(DWORD requestId)
Sub request type.
virtual QString getStatisticsSimulatorSpecific() const
Allows to print out simulator specific statistics.
static SIMCONNECT_DATA_LATLONALT coordinateToFsxLatLonAlt(const swift::misc::geo::ICoordinateGeodetic &coordinate)
Format conversion.
virtual bool updateOwnSimulatorCockpit(const swift::misc::simulation::CSimulatedAircraft &ownAircraft, const swift::misc::CIdentifier &originator)
Update own aircraft cockpit (usually from context).
bool triggerAutoTraceSendId(qint64 traceTimeMs=AutoTraceOffsetMs)
Trigger tracing ids for some while.
static bool isRequestForSimObjAircraft(DWORD requestId)
Request for sim data (request in range of sim data)?
virtual void timerEvent(QTimerEvent *event)
Timer event (our SimConnect event loop), runs dispatch.
static QByteArray toFsxChar(const QString &string)
Convert to FSX char array.
virtual bool connectTo()
Connect to simulator.
bool isValidSimObjectNotPendingRemoved(const CSimConnectObject &simObject) const
Valid CSimConnectObject which is NOT pendig removed.
static bool isValidFsxPosition(const SIMCONNECT_DATA_INITPOSITION &fsxPos)
Valid FSX/P3D position.
virtual void clearAllRemoteAircraftData()
Clear all aircraft related data, but do not physically remove the aircraft.
virtual swift::misc::CStatusMessageList getInterpolationMessages(const swift::misc::aviation::CCallsign &callsign) const
Interpolation messages for callsign.
CSimConnectObject getSimObjectForTrace(const TraceFsxSendId &trace) const
CSimConnectObject for trace.
static SIMCONNECT_DATA_PBH aircraftSituationToFsxPBH(const swift::misc::aviation::CAircraftSituation &situation)
Format conversion.
virtual bool physicallyRemoveRemoteAircraft(const swift::misc::aviation::CCallsign &callsign)
Remove remote aircraft from simulator.
virtual void startImpl()
Plugin specific implementation to start listener.
CSimulatorFsxCommonListener(const swift::misc::simulation::CSimulatorPluginInfo &info)
Constructor.
virtual void stopImpl()
Plugin specific implementation to stop listener.
virtual void checkImpl()
Plugin specific implementation to check.
virtual QString backendInfo() const
Info about the backend system (if available).
virtual bool parseDetails(const swift::misc::CSimpleCommandParser &parser)
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
SWIFT_MISC_EXPORT const QString & boolToEnabledDisabled(bool v)
Bool to enabled/disabled.
SWIFT_MISC_EXPORT const QString & boolToOnOff(bool v)
Bool to on/off.
SWIFT_MISC_EXPORT const QString & boolToYesNo(bool v)
Bool to yes/no.
T::const_iterator end(const LockFreeReader< T > &reader)
Non-member begin() and end() for so LockFree containers can be used in ranged for loops.
Definition lockfree.h:264
QByteArray & append(QByteArrayView data)
const char * constData() const const
char * data()
qsizetype size() const const
qint64 currentMSecsSinceEpoch()
QDateTime fromMSecsSinceEpoch(qint64 msecs)
QString toString(QStringView format) const const
qint64 elapsed() const const
bool isEmpty() const const
T value(qsizetype i) const const
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
virtual bool event(QEvent *e)
QObject * parent() const const
int startTimer(int interval, Qt::TimerType timerType)
QThread * thread() const const
QString arg(Args &&... args) const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
QString fromLatin1(QByteArrayView str)
bool isEmpty() const const
QString left(qsizetype n) &&
QString number(double n, char format, int precision)
QByteArray toLatin1() const const
void timeout()
unsigned long DWORD
Fake Windows DWORD.
HRESULT s_ok()
Correctly casted values/checks.
bool isFailure(HRESULT result)
Correctly casted values/checks.
bool dtb(double doubleBool)
Correctly casted values/checks.
EventIds
SimConnect Event IDs.
adding struct SIMCONNECT_DATA_PBH not existing in SimConnect FSX
QString errorMsg
error message if any
Definition windllutils.h:27
Data structure for MSFS transponder mode information.
double comTransmit1
COM1 transmit, means also receiving.
double comReceiveAll
all COMs receiving, or COM:x transmitting or receiving
double comTransmit2
COM2 transmit, means also receiving.
double flapsHandlePosition
Flaps handle position in percent.
Data for AI object and probe sent back from simulator.
static const TraceFsxSendId & invalid()
Invalid object.
CSimConnectObject simObject
CSimConnectObject at the time of the trace.
#define SWIFT_AUDIT_X(COND, WHERE, WHAT)
A weaker kind of verify.
Definition verify.h:38
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26