swift
Loading...
Searching...
No Matches
simulatorp3d.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2017 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "simulatorp3d.h"
5
8
10#include "misc/logmessage.h"
11#include "misc/threadutils.h"
12
13using namespace swift::config;
14using namespace swift::misc;
15using namespace swift::misc::aviation;
16using namespace swift::misc::physical_quantities;
17using namespace swift::misc::geo;
18using namespace swift::misc::network;
19using namespace swift::misc::simulation;
20using namespace swift::misc::simulation::fscommon;
21using namespace swift::simplugin::fsxcommon;
22using namespace swift::core;
23using namespace swift::simplugin::fscommon;
24
25namespace swift::simplugin::p3d
26{
28 IRemoteAircraftProvider *remoteAircraftProvider, IClientProvider *clientProvider,
30 : CSimulatorFsxCommon(info, ownAircraftProvider, remoteAircraftProvider, clientProvider, parent)
31 {
32 // set build/sim specific SimConnectProc, which is the FSX SimConnectProc on WIN32 systems
35 {
36 // modern x64 P3D
37 this->setUsingFsxTerrainProbe(false);
39 }
41 "Constellation in TWA livery", CAircraftIcaoCode("CONI", "L4P")));
42 }
43
45 {
46#ifdef Q_OS_WIN64
47 if (!loadAndResolveP3DSimConnectByString(m_p3dVersion.get()))
48 {
49 return false;
50 }
52#else
53 if (!loadAndResolveFsxSimConnect(true))
54 {
55 return false;
56 }
58#endif
59 }
60
61#ifdef Q_OS_WIN64
62 void CSimulatorP3D::SimConnectProc(SIMCONNECT_RECV *pData, DWORD cbData, void *pContext)
63 {
64 CSimulatorP3D *simulatorP3D = static_cast<CSimulatorP3D *>(pContext);
65 Q_ASSERT_X(simulatorP3D, Q_FUNC_INFO, "Cannot convert context to CSimulatorP3D");
66
67 switch (pData->dwID)
68 {
69 // case SIMCONNECT_RECV_ID_CAMERA_6DOF: break;
70 // case SIMCONNECT_RECV_ID_CAMERA_FOV: break;
71 // case SIMCONNECT_RECV_ID_CAMERA_SENSOR_MODE: break;
72 // case SIMCONNECT_RECV_ID_CAMERA_WINDOW_POSITION: break;
73 // case SIMCONNECT_RECV_ID_CAMERA_WINDOW_SIZE: break;
74
75 case SIMCONNECT_RECV_ID_GROUND_INFO:
76 {
77 // https://www.prepar3d.com/SDKv4/sdk/simconnect_api/references/structures_and_enumerations.html#SIMCONNECT_RECV_GROUND_INFO
78 const SIMCONNECT_RECV_GROUND_INFO *pObjData = static_cast<SIMCONNECT_RECV_GROUND_INFO *>(pData);
79 const DWORD requestId = pObjData->dwRequestID;
81 {
82 break;
83 }
84 // valid elevation request
85 // https://www.prepar3d.com/SDKv4/sdk/simconnect_api/references/structures_and_enumerations.html#SIMCONNECT_DATA_GROUND_INFO
86 if (pObjData->dwArraySize != 1)
87 {
88 break;
89 }
90 const SIMCONNECT_DATA_GROUND_INFO gi = pObjData->rgData[0];
91 if (!gi.bIsValid)
92 {
93 break;
94 }
95 const CLatitude lat(gi.fLat, CAngleUnit::deg());
96 const CLongitude lng(gi.fLon, CAngleUnit::deg());
98 const CCoordinateGeodetic coordinate(lat, lng, alt);
100
101 const CCallsign cs(simulatorP3D->getCallsignForPendingProbeRequests(requestId, true));
102 simulatorP3D->callbackReceivedRequestedElevation(ep, cs, false);
103 }
104 break;
105 default: CSimulatorFsxCommon::SimConnectProc(pData, cbData, pContext); break;
106 }
107 }
108
109 // P3D version with new P3D simconnect functions
110 bool CSimulatorP3D::requestElevation(const ICoordinateGeodetic &reference, const CCallsign &callsign)
111 {
112 if (reference.isNull())
113 {
114 return false;
115 }
116 if (this->isShuttingDown())
117 {
118 return false;
119 }
120 if (!this->isConnected())
121 {
122 return false;
123 }
124
125 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "thread");
126 const bool hasHeight = reference.hasMSLGeodeticHeight();
127 const double latDeg = reference.latitude().value(CAngleUnit::deg());
128 const double lngDeg = reference.longitude().value(CAngleUnit::deg());
129 const double maxAltFt = hasHeight ? reference.geodeticHeight().value(CLengthUnit::ft()) : 50000;
130 const DWORD dwGridWidth = 1.0;
131 const DWORD dwGridHeight = 1.0;
132
133 const SIMCONNECT_DATA_REQUEST_ID requestId =
134 this->obtainRequestIdForSimObjTerrainProbe(); // P3D we use new request id each time (no simobject)
135
136 // returns SIMCONNECT_RECV_GROUND_INFO -> SIMCONNECT_DATA_GROUND_INFO
137 const HRESULT hr = this->logAndTraceSendId(
138 SimConnect_RequestGroundInfo(m_hSimConnect, requestId, latDeg, lngDeg, 0, latDeg, lngDeg, maxAltFt,
139 dwGridWidth, dwGridHeight, SIMCONNECT_GROUND_INFO_LATLON_FORMAT_DEGREES,
140 SIMCONNECT_GROUND_INFO_ALT_FORMAT_FEET,
141 SIMCONNECT_GROUND_INFO_SOURCE_FLAG_PLATFORMS),
142 Q_FUNC_INFO, "SimConnect_RequestGroundInfo");
143
144 bool ok = false;
145 if (isOk(hr))
146 {
147 ok = true;
148 emit this->requestedElevation(callsign);
149 m_pendingProbeRequests.insert(requestId, callsign);
150 }
151 else
152 {
153 const CStatusMessage msg = CStatusMessage(this).error(u"SimConnect, can not request ground info: '%1' '%2'")
154 << requestId << callsign.asString();
156 }
157
158 return ok;
159 }
160
161 bool CSimulatorP3D::followAircraft(const CCallsign &callsign)
162 {
164 {
165 return false;
166 }
167
168 CSimConnectObject &simObject = m_simConnectObjects[callsign];
169 if (!simObject.hasValidRequestAndObjectId())
170 {
171 return false;
172 }
173 if (simObject.getCallsignByteArray().isEmpty())
174 {
175 return false;
176 }
177 HRESULT hr = s_false();
178
179 //
180 // Experimental code
181 //
182
211
218
219 // Observer is P3D only, not FSX
220 const CAircraftSituation situation = m_lastSentSituations[callsign];
221 if (situation.isNull())
222 {
223 return false;
224 }
225 SIMCONNECT_DATA_OBSERVER obs;
226 SIMCONNECT_DATA_PBH pbh;
227 pbh.Pitch = pbh.Bank = pbh.Heading = 0;
228 obs.Rotation = pbh;
229 obs.Position = coordinateToFsxLatLonAlt(situation);
230 obs.Regime = SIMCONNECT_OBSERVER_REGIME_GHOST;
231 obs.RotateOnTarget = TRUE;
232 obs.FocusFixed = TRUE;
233 obs.FieldOfViewH = 30; // deg.
234 obs.FieldOfViewV = 30; // deg.
235 obs.LinearStep = 20; // meters
236 obs.AngularStep = 10; // deg.
237
238 const char *observerName = simObject.getCallsignByteArray().constData();
239 hr = SimConnect_CreateObserver(m_hSimConnect, observerName, obs);
240 if (isOk(hr))
241 {
242 SIMCONNECT_DATA_XYZ offset;
243 offset.x = offset.y = 30;
244 offset.z = 0;
245 hr = SimConnect_ObserverAttachToEntityOn(m_hSimConnect, observerName, simObject.getObjectId(), offset);
246 if (isOk(hr))
247 {
248 SimConnect_SetObserverLookAt(m_hSimConnect, observerName, obs.Position);
249
250 // const QByteArray viewName = QStringLiteral("Observer %1").arg(callsign.asString()).toLatin1();
251 hr = SimConnect_OpenView(m_hSimConnect, observerName);
252
253 simObject.setObserverName(callsign.asString());
254 }
255 }
256
257 return isOk(hr);
258 }
259
261 {
262 HRESULT hr = s_ok();
263 if (isFailure(hr))
264 {
265 CLogMessage(this).error(u"P3D plugin error: %1") << "initEventsP3D failed";
266 return hr;
267 }
268 return hr;
269 }
270
271 void CSimulatorP3D::removeCamera(fsxcommon::CSimConnectObject &simObject)
272 {
273 if (!simObject.hasCamera())
274 {
275 return;
276 }
277 simObject.removeCamera();
278 // const char *cameraName = simObject.getCallsignByteArray().constData();
279 // SimConnect_DeleteCameraInstance(m_hSimConnect, simObject.getCameraGUID(), 0);
280 // SimConnect_CloseView(m_hSimConnect, cameraName);
281 }
282
283 void CSimulatorP3D::removeObserver(CSimConnectObject &simObject)
284 {
285 if (simObject.getObserverName().isEmpty())
286 {
287 return;
288 }
289
290 QByteArray viewName = simObject.getObserverName().toLatin1();
291 SimConnect_CloseView(m_hSimConnect, viewName.constData());
292 }
293
294 bool CSimulatorP3D::releaseAIControl(const CSimConnectObject &simObject, SIMCONNECT_DATA_REQUEST_ID requestId)
295 {
296 // completely remove AI control
297 const SIMCONNECT_OBJECT_ID objectId = simObject.getObjectId();
298 const HRESULT hr1 =
299 this->logAndTraceSendId(SimConnect_AIReleaseControlEx(m_hSimConnect, objectId, requestId, TRUE), simObject,
300 "Release control", Q_FUNC_INFO, "SimConnect_AIReleaseControlEx");
301 const HRESULT hr2 =
302 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeLatLng, 1,
303 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
304 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
305 simObject, "EventFreezeLatLng", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
306 const HRESULT hr3 =
307 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeAlt, 1,
308 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
309 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
310 simObject, "EventFreezeAlt", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
311 const HRESULT hr4 =
312 this->logAndTraceSendId(SimConnect_TransmitClientEvent(m_hSimConnect, objectId, EventFreezeAtt, 1,
313 SIMCONNECT_GROUP_PRIORITY_HIGHEST,
314 SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY),
315 simObject, "EventFreezeAtt", Q_FUNC_INFO, "SimConnect_TransmitClientEvent");
316
317 return isOk(hr1, hr2, hr3, hr4);
318 }
319#else
320 HRESULT CSimulatorP3D::initEventsP3D() { return s_ok(); }
321
322 void CSimulatorP3D::SimConnectProc(SIMCONNECT_RECV *pData, DWORD cbData, void *pContext)
323 {
324 CSimulatorFsxCommon::SimConnectProc(pData, cbData, pContext);
325 }
326#endif
327
329 {
330#ifdef Q_OS_WIN64
331 if (!loadAndResolveP3DSimConnectByString(m_p3dVersion.get()))
332 {
333 return;
334 }
336#else
337 if (!loadAndResolveFsxSimConnect(true))
338 {
339 return;
340 }
342#endif
343 }
344
345} // namespace swift::simplugin::p3d
static CAngleUnit deg()
Degrees.
Definition units.h:276
static constexpr bool isRunningOnWindowsNtPlatform()
Running on Windows NT platform?
static constexpr bool isCompiledWithP3DSupport()
with P3D support?
static int buildWordSize()
Whether this swift application is build as 32 or 64bit application.
virtual void callbackReceivedRequestedElevation(const swift::misc::geo::CElevationPlane &plane, const swift::misc::aviation::CCallsign &callsign, bool isWater)
A requested elevation has been received.
virtual bool followAircraft(const swift::misc::aviation::CCallsign &callsign)
Follow aircraft.
virtual bool isShuttingDown() const
Is overall (swift) application shutting down.
Definition simulator.h:214
void requestedElevation(const swift::misc::aviation::CCallsign &callsign)
Requested elevation, call pending.
bool requestElevation(const swift::misc::geo::ICoordinateGeodetic &reference, const swift::misc::aviation::CCallsign &callsign)
Request elevation, there is no guarantee the requested elevation will be available in the provider.
virtual bool isShuttingDownOrDisconnected() const
Shutting down or disconnected?
Definition simulator.h:217
swift::misc::aviation::CAircraftSituationPerCallsign m_lastSentSituations
last situations sent to simulator
Definition simulator.h:585
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
Value object for ICAO classification.
Altitude as used in aviation, can be AGL or MSL altitude.
Definition altitude.h:52
@ TrueAltitude
Height of the airplane above Mean Sea Level (MSL).
Definition altitude.h:83
Value object encapsulating information of a callsign.
Definition callsign.h:30
const QString & asString() const
Get callsign (normalized).
Definition callsign.h:96
Plane of same elevation, can be a single point or larger area (e.g. airport).
static const physical_quantities::CLength & singlePointRadius()
Radius for single point.
bool hasMSLGeodeticHeight() const
Geodetic height not null and aviation::CAltitude::MeanSeaLevel.
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.
virtual CLatitude latitude() const =0
Latitude.
Direct in memory access to client (network client) data.
static CLengthUnit ft()
Foot ft.
Definition units.h:157
double value(MU unit) const
Value in given unit.
Aircraft model (used by another pilot, my models on disk).
@ TypeModelMatchingDefaultModel
a default model assigned by model matching
Direct threadsafe in memory access to own aircraft.
Direct thread safe in memory access to remote aircraft.
void setDefaultModel(const CAircraftModel &defaultModel)
Default model.
const QByteArray & getCallsignByteArray() const
Callsign as LATIN1.
DWORD getObjectId() const
Get SimConnect object id.
bool hasValidRequestAndObjectId() const
Was the object really added to simulator.
const QString & getObserverName() const
Observer name.
void setObserverName(const QString &observer)
Set observer.
SIMCONNECT_DATA_REQUEST_ID obtainRequestIdForSimObjTerrainProbe()
Get new request id, overflow safe.
CSimConnectObjects m_simConnectObjects
AI objects and their object and request ids.
QMap< DWORD, swift::misc::aviation::CCallsign > m_pendingProbeRequests
pending elevation requests: requestId/aircraft callsign
static bool isRequestForSimObjTerrainProbe(DWORD requestId)
Request for probe (elevation)?
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.
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
DispatchProc m_dispatchProc
called function for dispatch, can be overriden by specialized P3D function
virtual void removeObserver(CSimConnectObject &simObject)
Remove observer if any.
virtual bool releaseAIControl(const CSimConnectObject &simObject, SIMCONNECT_DATA_REQUEST_ID requestId)
Release AI control.
swift::misc::aviation::CCallsign getCallsignForPendingProbeRequests(DWORD requestId, bool remove)
Callsign for pending request.
void setUsingFsxTerrainProbe(bool use)
FSX terrain probe.
virtual bool isConnected() const
Are we connected to the simulator?
static SIMCONNECT_DATA_LATLONALT coordinateToFsxLatLonAlt(const swift::misc::geo::ICoordinateGeodetic &coordinate)
Format conversion.
static void CALLBACK SimConnectProc(SIMCONNECT_RECV *pData, DWORD cbData, void *pContext)
SimConnect callback.
virtual bool connectTo()
Connect to simulator.
virtual void startImpl()
Plugin specific implementation to start listener.
P3D Simulator Implementation.
static void CALLBACK SimConnectProc(SIMCONNECT_RECV *pData, DWORD cbData, void *pContext)
SimConnect Callback.
CSimulatorP3D(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.
virtual HRESULT initEventsP3D()
Specific P3D events.
virtual bool connectTo()
Connect to simulator.
virtual void startImpl()
Plugin specific implementation to start listener.
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
const char * constData() const const
bool isEmpty() const const
QObject(QObject *parent)
QObject * parent() const const
bool isEmpty() const const
QByteArray toLatin1() const const
unsigned long DWORD
Fake Windows DWORD.
HRESULT s_ok()
Correctly casted values/checks.
bool isFailure(HRESULT result)
Correctly casted values/checks.
HRESULT s_false()
Correctly casted values/checks.