1 // FGAIMultiplayer - FGAIBase-derived class creates an AI multiplayer aircraft
3 // Based on FGAIAircraft
4 // Written by David Culp, started October 2003.
5 // Also by Gregor Richards, started December 2005.
7 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
8 // Copyright (C) 2005 Gregor Richards
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include "AIMultiplayer.hxx"
32 // #define SG_DEBUG SG_ALERT
34 FGAIMultiplayer::FGAIMultiplayer() : FGAIBase(otMultiplayer) {
37 mTimeOffsetSet = false;
38 mAllowExtrapolation = true;
39 mLagAdjustSystemSpeed = 10;
43 FGAIMultiplayer::~FGAIMultiplayer() {
46 bool FGAIMultiplayer::init() {
47 refuel_node = fgGetNode("systems/refuel/contact", true);
48 isTanker = false; // do this until this property is
49 // passed over the net
51 string str1 = mCallSign;
52 string str2 = "MOBIL";
54 unsigned int loc1= str1.find( str2, 0 );
55 if ( (loc1 != string::npos && str2 != "") /*|| mCallSign == "mpdummy" */) {
56 // cout << " string found " << str2 << " in " << str1 << endl;
58 // cout << "isTanker " << isTanker << " " << mCallSign <<endl;
60 return FGAIBase::init();
63 void FGAIMultiplayer::bind() {
66 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
67 props->setBoolValue("tanker",isTanker);
69 #define AIMPROProp(type, name) \
70 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
72 #define AIMPRWProp(type, name) \
73 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
74 &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
76 props->tie("callsign", AIMPROProp(const char *, CallSign));
78 props->tie("controls/allow-extrapolation",
79 AIMPRWProp(bool, AllowExtrapolation));
80 props->tie("controls/lag-adjust-system-speed",
81 AIMPRWProp(double, LagAdjustSystemSpeed));
88 void FGAIMultiplayer::unbind() {
91 props->untie("callsign");
92 props->untie("controls/allow-extrapolation");
93 props->untie("controls/lag-adjust-system-speed");
94 props->untie("refuel/contact");
97 void FGAIMultiplayer::update(double dt)
102 FGAIBase::update(dt);
104 // Check if we already got data
105 if (mMotionInfo.empty())
108 // The current simulation time we need to update for,
109 // note that the simulation time is updated before calling all the
110 // update methods. Thus it contains the time intervals *end* time
111 double curtime = globals->get_sim_time_sec();
113 // Get the last available time
114 MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
115 double curentPkgTime = it->second.time;
117 // Dynamically optimize the time offset between the feeder and the client
118 // Well, 'dynamically' means that the dynamic of that update must be very
119 // slow. You would otherwise notice huge jumps in the multiplayer models.
120 // The reason is that we want to avoid huge extrapolation times since
121 // extrapolation is highly error prone. For that we need something
122 // approaching the average latency of the packets. This first order lag
123 // component will provide this. We just take the error of the currently
124 // requested time to the most recent available packet. This is the
125 // target we want to reach in average.
126 double lag = it->second.lag;
127 if (!mTimeOffsetSet) {
128 mTimeOffsetSet = true;
129 mTimeOffset = curentPkgTime - curtime - lag;
131 double offset = curentPkgTime - curtime - lag;
132 if (!mAllowExtrapolation && offset + lag < mTimeOffset) {
133 mTimeOffset = offset;
134 SG_LOG(SG_GENERAL, SG_DEBUG, "Resetting time offset adjust system to "
135 "avoid extrapolation: time offset = " << mTimeOffset);
137 // the error of the offset, respectively the negative error to avoid
139 double err = offset - mTimeOffset;
140 // limit errors leading to shorter lag values somehow, that is late
141 // arriving packets will pessimize the overall lag much more than
142 // early packets will shorten the overall lag
145 // Ok, we have some very late packets and nothing newer increase the
146 // lag by the given speedadjust
147 sysSpeed = mLagAdjustSystemSpeed*err;
149 // We have a too pessimistic display delay shorten that a small bit
150 sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
153 // simple euler integration for that first order system including some
154 // overshooting guard to prevent to aggressive system speeds
155 // (stiff systems) to explode the systems state
156 double systemIncrement = dt*sysSpeed;
157 if (fabs(err) < fabs(systemIncrement))
158 systemIncrement = err;
159 mTimeOffset += systemIncrement;
161 SG_LOG(SG_GENERAL, SG_DEBUG, "Offset adjust system: time offset = "
162 << mTimeOffset << ", expected longitudinal position error due to "
163 " current adjustment of the offset: "
164 << fabs(norm(it->second.linearVel)*systemIncrement));
169 // Compute the time in the feeders time scale which fits the current time
171 double tInterp = curtime + mTimeOffset;
175 if (tInterp <= curentPkgTime) {
176 // Ok, we need a time prevous to the last available packet,
179 // Find the first packet before the target time
180 MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
181 if (nextIt == mMotionInfo.begin()) {
182 SG_LOG(SG_GENERAL, SG_DEBUG, "Taking oldest packet!");
183 // We have no packet before the target time, just use the first one
184 MotionInfo::iterator firstIt = mMotionInfo.begin();
185 ecPos = firstIt->second.position;
186 ecOrient = firstIt->second.orientation;
188 std::vector<FGFloatPropertyData>::const_iterator firstPropIt;
189 std::vector<FGFloatPropertyData>::const_iterator firstPropItEnd;
190 firstPropIt = firstIt->second.properties.begin();
191 firstPropItEnd = firstIt->second.properties.end();
192 while (firstPropIt != firstPropItEnd) {
193 float val = firstPropIt->value;
194 PropertyMap::iterator pIt = mPropertyMap.find(firstPropIt->id);
195 if (pIt != mPropertyMap.end())
196 pIt->second->setFloatValue(val);
201 // Ok, we have really found something where our target time is in between
202 // do interpolation here
203 MotionInfo::iterator prevIt = nextIt;
206 // Interpolation coefficient is between 0 and 1
207 double intervalStart = prevIt->second.time;
208 double intervalEnd = nextIt->second.time;
209 double intervalLen = intervalEnd - intervalStart;
210 double tau = (tInterp - intervalStart)/intervalLen;
212 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle interpolation: ["
213 << intervalStart << ", " << intervalEnd << "], intervalLen = "
214 << intervalLen << ", interpolation parameter = " << tau);
216 // Here we do just linear interpolation on the position
217 ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
218 ecOrient = interpolate((float)tau, prevIt->second.orientation,
219 nextIt->second.orientation);
221 if (prevIt->second.properties.size()
222 == nextIt->second.properties.size()) {
223 std::vector<FGFloatPropertyData>::const_iterator prevPropIt;
224 std::vector<FGFloatPropertyData>::const_iterator prevPropItEnd;
225 std::vector<FGFloatPropertyData>::const_iterator nextPropIt;
226 std::vector<FGFloatPropertyData>::const_iterator nextPropItEnd;
227 prevPropIt = prevIt->second.properties.begin();
228 prevPropItEnd = prevIt->second.properties.end();
229 nextPropIt = nextIt->second.properties.begin();
230 nextPropItEnd = nextIt->second.properties.end();
231 while (prevPropIt != prevPropItEnd) {
232 float val = (1-tau)*prevPropIt->value + tau*nextPropIt->value;
233 PropertyMap::iterator pIt = mPropertyMap.find(prevPropIt->id);
234 if (pIt != mPropertyMap.end())
235 pIt->second->setFloatValue(val);
241 // Now throw away too old data
242 if (prevIt != mMotionInfo.begin()) {
244 mMotionInfo.erase(mMotionInfo.begin(), prevIt);
248 // Ok, we need to predict the future, so, take the best data we can have
249 // and do some eom computation to guess that for now.
250 FGExternalMotionData motionInfo = it->second;
252 // The time to predict, limit to 5 seconds
253 double t = tInterp - motionInfo.time;
254 t = SGMisc<double>::min(t, 5);
256 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle extrapolation: "
257 "extrapolation time = " << t);
259 // Do a few explicit euler steps with the constant acceleration's
260 // This must be sufficient ...
261 ecPos = motionInfo.position;
262 ecOrient = motionInfo.orientation;
263 SGVec3f linearVel = motionInfo.linearVel;
264 SGVec3f angularVel = motionInfo.angularVel;
270 SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
272 ecOrient += h*ecOrient.derivative(angularVel);
274 linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
275 angularVel += h*motionInfo.angularAccel;
280 std::vector<FGFloatPropertyData>::const_iterator firstPropIt;
281 std::vector<FGFloatPropertyData>::const_iterator firstPropItEnd;
282 firstPropIt = it->second.properties.begin();
283 firstPropItEnd = it->second.properties.end();
284 while (firstPropIt != firstPropItEnd) {
285 float val = firstPropIt->value;
286 PropertyMap::iterator pIt = mPropertyMap.find(firstPropIt->id);
287 if (pIt != mPropertyMap.end())
288 pIt->second->setFloatValue(val);
293 // extract the position
295 pos.setlat(geod.getLatitudeDeg());
296 pos.setlon(geod.getLongitudeDeg());
297 pos.setelev(geod.getElevationM());
299 // The quaternion rotating from the earth centered frame to the
300 // horizontal local frame
301 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)geod.getLongitudeRad(),
302 (float)geod.getLatitudeRad());
303 // The orientation wrt the horizontal local frame
304 SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
305 float hDeg, pDeg, rDeg;
306 hlOr.getEulerDeg(hDeg, pDeg, rDeg);
311 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer position and orientation: "
312 << geod << ", " << hlOr);
314 //###########################//
315 // do calculations for radar //
316 //###########################//
317 double range_ft2 = UpdateRadar(manager);
319 //************************************//
321 //************************************//
325 if ( (range_ft2 < 250.0 * 250.0)
326 /*&& (y_shift > 0.0) && (elevation > 0.0)*/ ) {
327 refuel_node->setBoolValue(true);
330 refuel_node->setBoolValue(false);
341 FGAIMultiplayer::addMotionInfo(const FGExternalMotionData& motionInfo,
344 mLastTimestamp = stamp;
345 // Drop packets arriving out of order
346 if (!mMotionInfo.empty() && motionInfo.time < mMotionInfo.rbegin()->first)
348 mMotionInfo[motionInfo.time] = motionInfo;
352 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
354 SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
355 pNode->setDoubleValue(val);