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"
33 // #define SG_DEBUG SG_ALERT
35 FGAIMultiplayer::FGAIMultiplayer() :
36 FGAIBase(otMultiplayer, false)
40 mTimeOffsetSet = false;
41 mAllowExtrapolation = true;
42 mLagAdjustSystemSpeed = 10;
48 FGAIMultiplayer::~FGAIMultiplayer() {
51 bool FGAIMultiplayer::init(bool search_in_AI_path) {
52 props->setStringValue("sim/model/path", model_path.c_str());
53 //refuel_node = fgGetNode("systems/refuel/contact", true);
54 isTanker = false; // do this until this property is
55 // passed over the net
57 string str1 = _getCallsign();
58 string str2 = "MOBIL";
60 string::size_type loc1= str1.find( str2, 0 );
61 if ( (loc1 != string::npos && str2 != "") ){
62 // cout << " string found " << str2 << " in " << str1 << endl;
64 // cout << "isTanker " << isTanker << " " << mCallSign <<endl;
68 bool result = FGAIBase::init(search_in_AI_path);
69 // propagate installation state (used by MP pilot list)
70 props->setBoolValue("model-installed", _installed);
74 void FGAIMultiplayer::bind() {
77 tie("refuel/contact", SGRawValuePointer<bool>(&contact));
78 tie("tanker", SGRawValuePointer<bool>(&isTanker));
80 tie("controls/invisible",
81 SGRawValuePointer<bool>(&invisible));
83 #define AIMPROProp(type, name) \
84 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
86 #define AIMPRWProp(type, name) \
87 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
88 &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
90 //tie("callsign", AIMPROProp(const char *, CallSign));
92 tie("controls/allow-extrapolation",
93 AIMPRWProp(bool, AllowExtrapolation));
94 tie("controls/lag-adjust-system-speed",
95 AIMPRWProp(double, LagAdjustSystemSpeed));
102 void FGAIMultiplayer::update(double dt)
104 using namespace simgear;
109 FGAIBase::update(dt);
111 // Check if we already got data
112 if (mMotionInfo.empty())
115 // The current simulation time we need to update for,
116 // note that the simulation time is updated before calling all the
117 // update methods. Thus it contains the time intervals *end* time
118 double curtime = globals->get_sim_time_sec();
120 // Get the last available time
121 MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
122 double curentPkgTime = it->second.time;
124 // Dynamically optimize the time offset between the feeder and the client
125 // Well, 'dynamically' means that the dynamic of that update must be very
126 // slow. You would otherwise notice huge jumps in the multiplayer models.
127 // The reason is that we want to avoid huge extrapolation times since
128 // extrapolation is highly error prone. For that we need something
129 // approaching the average latency of the packets. This first order lag
130 // component will provide this. We just take the error of the currently
131 // requested time to the most recent available packet. This is the
132 // target we want to reach in average.
133 double lag = it->second.lag;
134 if (!mTimeOffsetSet) {
135 mTimeOffsetSet = true;
136 mTimeOffset = curentPkgTime - curtime - lag;
138 double offset = curentPkgTime - curtime - lag;
139 if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
140 || (offset - 10 > mTimeOffset)) {
141 mTimeOffset = offset;
142 SG_LOG(SG_AI, SG_DEBUG, "Resetting time offset adjust system to "
143 "avoid extrapolation: time offset = " << mTimeOffset);
145 // the error of the offset, respectively the negative error to avoid
147 double err = offset - mTimeOffset;
148 // limit errors leading to shorter lag values somehow, that is late
149 // arriving packets will pessimize the overall lag much more than
150 // early packets will shorten the overall lag
153 // Ok, we have some very late packets and nothing newer increase the
154 // lag by the given speedadjust
155 sysSpeed = mLagAdjustSystemSpeed*err;
157 // We have a too pessimistic display delay shorten that a small bit
158 sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
161 // simple euler integration for that first order system including some
162 // overshooting guard to prevent to aggressive system speeds
163 // (stiff systems) to explode the systems state
164 double systemIncrement = dt*sysSpeed;
165 if (fabs(err) < fabs(systemIncrement))
166 systemIncrement = err;
167 mTimeOffset += systemIncrement;
169 SG_LOG(SG_AI, SG_DEBUG, "Offset adjust system: time offset = "
170 << mTimeOffset << ", expected longitudinal position error due to "
171 " current adjustment of the offset: "
172 << fabs(norm(it->second.linearVel)*systemIncrement));
177 // Compute the time in the feeders time scale which fits the current time
179 double tInterp = curtime + mTimeOffset;
184 if (tInterp <= curentPkgTime) {
185 // Ok, we need a time prevous to the last available packet,
188 // Find the first packet before the target time
189 MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
190 if (nextIt == mMotionInfo.begin()) {
191 SG_LOG(SG_AI, SG_DEBUG, "Taking oldest packet!");
192 // We have no packet before the target time, just use the first one
193 MotionInfo::iterator firstIt = mMotionInfo.begin();
194 ecPos = firstIt->second.position;
195 ecOrient = firstIt->second.orientation;
196 speed = norm(firstIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
198 std::vector<FGPropertyData*>::const_iterator firstPropIt;
199 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
200 firstPropIt = firstIt->second.properties.begin();
201 firstPropItEnd = firstIt->second.properties.end();
202 while (firstPropIt != firstPropItEnd) {
203 //cout << " Setting property..." << (*firstPropIt)->id;
204 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
205 if (pIt != mPropertyMap.end())
207 //cout << "Found " << pIt->second->getPath() << ":";
208 switch ((*firstPropIt)->type) {
212 pIt->second->setIntValue((*firstPropIt)->int_value);
213 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
217 pIt->second->setFloatValue((*firstPropIt)->float_value);
218 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
221 case props::UNSPECIFIED:
222 pIt->second->setStringValue((*firstPropIt)->string_value);
223 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
226 // FIXME - currently defaults to float values
227 pIt->second->setFloatValue((*firstPropIt)->float_value);
228 //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
234 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
240 // Ok, we have really found something where our target time is in between
241 // do interpolation here
242 MotionInfo::iterator prevIt = nextIt;
245 // Interpolation coefficient is between 0 and 1
246 double intervalStart = prevIt->second.time;
247 double intervalEnd = nextIt->second.time;
248 double intervalLen = intervalEnd - intervalStart;
249 double tau = (tInterp - intervalStart)/intervalLen;
251 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle interpolation: ["
252 << intervalStart << ", " << intervalEnd << "], intervalLen = "
253 << intervalLen << ", interpolation parameter = " << tau);
255 // Here we do just linear interpolation on the position
256 ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
257 ecOrient = interpolate((float)tau, prevIt->second.orientation,
258 nextIt->second.orientation);
259 speed = norm((1-tau)*prevIt->second.linearVel
260 + tau*nextIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
262 if (prevIt->second.properties.size()
263 == nextIt->second.properties.size()) {
264 std::vector<FGPropertyData*>::const_iterator prevPropIt;
265 std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
266 std::vector<FGPropertyData*>::const_iterator nextPropIt;
267 std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
268 prevPropIt = prevIt->second.properties.begin();
269 prevPropItEnd = prevIt->second.properties.end();
270 nextPropIt = nextIt->second.properties.begin();
271 nextPropItEnd = nextIt->second.properties.end();
272 while (prevPropIt != prevPropItEnd) {
273 PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
274 //cout << " Setting property..." << (*prevPropIt)->id;
276 if (pIt != mPropertyMap.end())
278 //cout << "Found " << pIt->second->getPath() << ":";
282 switch ((*prevPropIt)->type) {
286 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
287 tau*((double) (*nextPropIt)->int_value));
288 pIt->second->setIntValue(ival);
289 //cout << "Int: " << ival << "\n";
293 val = (1-tau)*(*prevPropIt)->float_value +
294 tau*(*nextPropIt)->float_value;
295 //cout << "Flo: " << val << "\n";
296 pIt->second->setFloatValue(val);
299 case props::UNSPECIFIED:
300 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
301 pIt->second->setStringValue((*nextPropIt)->string_value);
304 // FIXME - currently defaults to float values
305 val = (1-tau)*(*prevPropIt)->float_value +
306 tau*(*nextPropIt)->float_value;
307 //cout << "Unk: " << val << "\n";
308 pIt->second->setFloatValue(val);
314 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
322 // Now throw away too old data
323 if (prevIt != mMotionInfo.begin())
326 mMotionInfo.erase(mMotionInfo.begin(), prevIt);
330 // Ok, we need to predict the future, so, take the best data we can have
331 // and do some eom computation to guess that for now.
332 FGExternalMotionData& motionInfo = it->second;
334 // The time to predict, limit to 5 seconds
335 double t = tInterp - motionInfo.time;
336 t = SGMisc<double>::min(t, 5);
338 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle extrapolation: "
339 "extrapolation time = " << t);
341 // Do a few explicit euler steps with the constant acceleration's
342 // This must be sufficient ...
343 ecPos = motionInfo.position;
344 ecOrient = motionInfo.orientation;
345 SGVec3f linearVel = motionInfo.linearVel;
346 SGVec3f angularVel = motionInfo.angularVel;
352 SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
354 ecOrient += h*ecOrient.derivative(angularVel);
356 linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
357 angularVel += h*motionInfo.angularAccel;
362 std::vector<FGPropertyData*>::const_iterator firstPropIt;
363 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
364 speed = norm(linearVel) * SG_METER_TO_NM * 3600.0;
365 firstPropIt = it->second.properties.begin();
366 firstPropItEnd = it->second.properties.end();
367 while (firstPropIt != firstPropItEnd) {
368 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
369 //cout << " Setting property..." << (*firstPropIt)->id;
371 if (pIt != mPropertyMap.end())
373 switch ((*firstPropIt)->type) {
377 pIt->second->setIntValue((*firstPropIt)->int_value);
378 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
382 pIt->second->setFloatValue((*firstPropIt)->float_value);
383 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
386 case props::UNSPECIFIED:
387 pIt->second->setStringValue((*firstPropIt)->string_value);
388 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
391 // FIXME - currently defaults to float values
392 pIt->second->setFloatValue((*firstPropIt)->float_value);
393 //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
399 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
406 // extract the position
407 pos = SGGeod::fromCart(ecPos);
408 double recent_alt_ft = altitude_ft;
409 altitude_ft = pos.getElevationFt();
411 // expose a valid vertical speed
412 if (lastUpdateTime != 0)
414 double dT = curtime - lastUpdateTime;
418 // simple smoothing over 1 second
419 vs = (1.0-Weighting)*vs + Weighting * (altitude_ft - recent_alt_ft) / dT * 60;
421 lastUpdateTime = curtime;
423 // The quaternion rotating from the earth centered frame to the
424 // horizontal local frame
425 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
426 (float)pos.getLatitudeRad());
427 // The orientation wrt the horizontal local frame
428 SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
429 float hDeg, pDeg, rDeg;
430 hlOr.getEulerDeg(hDeg, pDeg, rDeg);
435 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer position and orientation: "
436 << ecPos << ", " << hlOr);
438 //###########################//
439 // do calculations for radar //
440 //###########################//
441 double range_ft2 = UpdateRadar(manager);
443 //************************************//
445 //************************************//
449 //cout << "IS tanker ";
450 if ( (range_ft2 < 250.0 * 250.0) &&
453 // refuel_node->setBoolValue(true);
454 //cout << "in contact" << endl;
457 // refuel_node->setBoolValue(false);
458 //cout << "not in contact" << endl;
462 //cout << "NOT tanker " << endl;
470 FGAIMultiplayer::addMotionInfo(FGExternalMotionData& motionInfo,
473 mLastTimestamp = stamp;
475 if (!mMotionInfo.empty()) {
476 double diff = motionInfo.time - mMotionInfo.rbegin()->first;
478 // packet is very old -- MP has probably reset (incl. his timebase)
482 // drop packets arriving out of order
486 mMotionInfo[motionInfo.time] = motionInfo;
487 // We just copied the property (pointer) list - they are ours now. Clear the
488 // properties list in given/returned object, so former owner won't deallocate them.
489 motionInfo.properties.clear();
493 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
495 SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
496 pNode->setDoubleValue(val);