]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIMultiplayer.cxx
d9b44305a1468c9061771bc34354d2a3b600ebd7
[flightgear.git] / src / AIModel / AIMultiplayer.cxx
1 // FGAIMultiplayer - FGAIBase-derived class creates an AI multiplayer aircraft
2 //
3 // Based on FGAIAircraft
4 // Written by David Culp, started October 2003.
5 // Also by Gregor Richards, started December 2005.
6 //
7 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.net
8 // Copyright (C) 2005  Gregor Richards
9 //
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.
14 //
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.
19 //
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.
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <string>
29
30 #include "AIMultiplayer.hxx"
31
32 // #define SG_DEBUG SG_ALERT
33
34 FGAIMultiplayer::FGAIMultiplayer() : FGAIBase(otMultiplayer) {
35    no_roll = false;
36
37    mTimeOffsetSet = false;
38    mAllowExtrapolation = true;
39    mLagAdjustSystemSpeed = 10;
40 }
41
42
43 FGAIMultiplayer::~FGAIMultiplayer() {
44 }
45
46 bool FGAIMultiplayer::init(bool search_in_AI_path) {
47     props->setStringValue("sim/model/path", model_path.c_str());
48     //refuel_node = fgGetNode("systems/refuel/contact", true);
49     isTanker = false; // do this until this property is
50                       // passed over the net
51
52     string str1 = _getCallsign();
53     string str2 = "MOBIL";
54
55     string::size_type loc1= str1.find( str2, 0 );
56     if ( (loc1 != string::npos && str2 != "") ){
57         //         cout << " string found "     << str2 << " in " << str1 << endl;
58         isTanker = true;
59         //         cout << "isTanker " << isTanker << " " << mCallSign <<endl;
60     }
61    return FGAIBase::init(search_in_AI_path);
62 }
63
64 void FGAIMultiplayer::bind() {
65     FGAIBase::bind();
66
67     props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
68     props->setBoolValue("tanker",isTanker);
69
70 #define AIMPROProp(type, name) \
71 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
72
73 #define AIMPRWProp(type, name) \
74 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
75       &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
76
77     //props->tie("callsign", AIMPROProp(const char *, CallSign));
78
79     props->tie("controls/allow-extrapolation",
80                AIMPRWProp(bool, AllowExtrapolation));
81     props->tie("controls/lag-adjust-system-speed",
82                AIMPRWProp(double, LagAdjustSystemSpeed));
83
84
85 #undef AIMPROProp
86 #undef AIMPRWProp
87 }
88
89 void FGAIMultiplayer::unbind() {
90     FGAIBase::unbind();
91
92     //props->untie("callsign");
93     props->untie("controls/allow-extrapolation");
94     props->untie("controls/lag-adjust-system-speed");
95     props->untie("refuel/contact");
96 }
97
98 void FGAIMultiplayer::update(double dt)
99 {
100   using namespace simgear;
101
102   if (dt <= 0)
103     return;
104
105   FGAIBase::update(dt);
106
107   // Check if we already got data
108   if (mMotionInfo.empty())
109     return;
110
111   // The current simulation time we need to update for,
112   // note that the simulation time is updated before calling all the
113   // update methods. Thus it contains the time intervals *end* time
114   double curtime = globals->get_sim_time_sec();
115
116   // Get the last available time
117   MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
118   double curentPkgTime = it->second.time;
119
120   // Dynamically optimize the time offset between the feeder and the client
121   // Well, 'dynamically' means that the dynamic of that update must be very
122   // slow. You would otherwise notice huge jumps in the multiplayer models.
123   // The reason is that we want to avoid huge extrapolation times since
124   // extrapolation is highly error prone. For that we need something
125   // approaching the average latency of the packets. This first order lag
126   // component will provide this. We just take the error of the currently
127   // requested time to the most recent available packet. This is the
128   // target we want to reach in average.
129   double lag = it->second.lag;
130   if (!mTimeOffsetSet) {
131     mTimeOffsetSet = true;
132     mTimeOffset = curentPkgTime - curtime - lag;
133   } else {
134     double offset = curentPkgTime - curtime - lag;
135     if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
136         || (offset - 10 > mTimeOffset)) {
137       mTimeOffset = offset;
138       SG_LOG(SG_GENERAL, SG_DEBUG, "Resetting time offset adjust system to "
139              "avoid extrapolation: time offset = " << mTimeOffset);
140     } else {
141       // the error of the offset, respectively the negative error to avoid
142       // a minus later ...
143       double err = offset - mTimeOffset;
144       // limit errors leading to shorter lag values somehow, that is late
145       // arriving packets will pessimize the overall lag much more than
146       // early packets will shorten the overall lag
147       double sysSpeed;
148       if (err < 0) {
149         // Ok, we have some very late packets and nothing newer increase the
150         // lag by the given speedadjust
151         sysSpeed = mLagAdjustSystemSpeed*err;
152       } else {
153         // We have a too pessimistic display delay shorten that a small bit
154         sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
155       }
156
157       // simple euler integration for that first order system including some
158       // overshooting guard to prevent to aggressive system speeds
159       // (stiff systems) to explode the systems state
160       double systemIncrement = dt*sysSpeed;
161       if (fabs(err) < fabs(systemIncrement))
162         systemIncrement = err;
163       mTimeOffset += systemIncrement;
164       
165       SG_LOG(SG_GENERAL, SG_DEBUG, "Offset adjust system: time offset = "
166              << mTimeOffset << ", expected longitudinal position error due to "
167              " current adjustment of the offset: "
168              << fabs(norm(it->second.linearVel)*systemIncrement));
169     }
170   }
171
172
173   // Compute the time in the feeders time scale which fits the current time
174   // we need to 
175   double tInterp = curtime + mTimeOffset;
176
177   SGVec3d ecPos;
178   SGQuatf ecOrient;
179
180   if (tInterp <= curentPkgTime) {
181     // Ok, we need a time prevous to the last available packet,
182     // that is good ...
183
184     // Find the first packet before the target time
185     MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
186     if (nextIt == mMotionInfo.begin()) {
187       SG_LOG(SG_GENERAL, SG_DEBUG, "Taking oldest packet!");
188       // We have no packet before the target time, just use the first one
189       MotionInfo::iterator firstIt = mMotionInfo.begin();
190       ecPos = firstIt->second.position;
191       ecOrient = firstIt->second.orientation;
192       speed = norm(firstIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
193
194       std::vector<FGPropertyData*>::const_iterator firstPropIt;
195       std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
196       firstPropIt = firstIt->second.properties.begin();
197       firstPropItEnd = firstIt->second.properties.end();
198       while (firstPropIt != firstPropItEnd) {
199         //cout << " Setting property..." << (*firstPropIt)->id;
200         PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
201         if (pIt != mPropertyMap.end())
202         {
203           //cout << "Found " << pIt->second->getPath() << ":";
204           switch ((*firstPropIt)->type) {
205             case props::INT:
206             case props::BOOL:
207             case props::LONG:
208               pIt->second->setIntValue((*firstPropIt)->int_value);
209               //cout << "Int: " << (*firstPropIt)->int_value << "\n";
210               break;
211             case props::FLOAT:
212             case props::DOUBLE:
213               pIt->second->setFloatValue((*firstPropIt)->float_value);
214               //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
215               break;
216             case props::STRING:
217             case props::UNSPECIFIED:
218               pIt->second->setStringValue((*firstPropIt)->string_value);
219               //cout << "Str: " << (*firstPropIt)->string_value << "\n";    
220               break;
221             default:
222               // FIXME - currently defaults to float values
223               pIt->second->setFloatValue((*firstPropIt)->float_value);
224               //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
225               break;
226           }            
227         }
228         else
229         {
230           SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
231         }
232         ++firstPropIt;
233       }
234
235     } else {
236       // Ok, we have really found something where our target time is in between
237       // do interpolation here
238       MotionInfo::iterator prevIt = nextIt;
239       --prevIt;
240
241       // Interpolation coefficient is between 0 and 1
242       double intervalStart = prevIt->second.time;
243       double intervalEnd = nextIt->second.time;
244       double intervalLen = intervalEnd - intervalStart;
245       double tau = (tInterp - intervalStart)/intervalLen;
246
247       SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle interpolation: ["
248              << intervalStart << ", " << intervalEnd << "], intervalLen = "
249              << intervalLen << ", interpolation parameter = " << tau);
250
251       // Here we do just linear interpolation on the position
252       ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
253       ecOrient = interpolate((float)tau, prevIt->second.orientation,
254                              nextIt->second.orientation);
255       speed = norm((1-tau)*prevIt->second.linearVel
256                    + tau*nextIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
257
258       if (prevIt->second.properties.size()
259           == nextIt->second.properties.size()) {
260         std::vector<FGPropertyData*>::const_iterator prevPropIt;
261         std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
262         std::vector<FGPropertyData*>::const_iterator nextPropIt;
263         std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
264         prevPropIt = prevIt->second.properties.begin();
265         prevPropItEnd = prevIt->second.properties.end();
266         nextPropIt = nextIt->second.properties.begin();
267         nextPropItEnd = nextIt->second.properties.end();
268         while (prevPropIt != prevPropItEnd) {
269           PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
270           //cout << " Setting property..." << (*prevPropIt)->id;
271           
272           if (pIt != mPropertyMap.end())
273           {
274             //cout << "Found " << pIt->second->getPath() << ":";
275           
276             int ival;
277             float val;
278             switch ((*prevPropIt)->type) {
279               case props::INT:
280               case props::BOOL:
281               case props::LONG:
282                 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
283                   tau*((double) (*nextPropIt)->int_value));
284                 pIt->second->setIntValue(ival);
285                 //cout << "Int: " << ival << "\n";
286                 break;
287               case props::FLOAT:
288               case props::DOUBLE:
289                 val = (1-tau)*(*prevPropIt)->float_value +
290                   tau*(*nextPropIt)->float_value;
291                 //cout << "Flo: " << val << "\n";
292                 pIt->second->setFloatValue(val);
293                 break;
294               case props::STRING:
295               case props::UNSPECIFIED:
296                 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
297                 pIt->second->setStringValue((*nextPropIt)->string_value);
298                 break;
299               default:
300                 // FIXME - currently defaults to float values
301                 val = (1-tau)*(*prevPropIt)->float_value +
302                   tau*(*nextPropIt)->float_value;
303                 //cout << "Unk: " << val << "\n";
304                 pIt->second->setFloatValue(val);
305                 break;
306             }            
307           }
308           else
309           {
310             SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
311           }
312           
313           ++prevPropIt;
314           ++nextPropIt;
315         }
316       }
317
318       // Now throw away too old data
319       if (prevIt != mMotionInfo.begin()) 
320       {
321         --prevIt;
322         
323         MotionInfo::iterator delIt;
324         delIt = mMotionInfo.begin();
325         
326         while (delIt != prevIt) 
327         {
328           std::vector<FGPropertyData*>::const_iterator propIt;
329           std::vector<FGPropertyData*>::const_iterator propItEnd;
330           propIt = delIt->second.properties.begin();
331           propItEnd = delIt->second.properties.end();
332
333           //cout << "Deleting data\n";
334           
335           while (propIt != propItEnd)
336           {
337             delete *propIt;
338             propIt++;
339           }
340           
341           delIt++;
342         }
343         
344         mMotionInfo.erase(mMotionInfo.begin(), prevIt);
345       }
346     }
347   } else {
348     // Ok, we need to predict the future, so, take the best data we can have
349     // and do some eom computation to guess that for now.
350     FGExternalMotionData motionInfo = it->second;
351
352     // The time to predict, limit to 5 seconds
353     double t = tInterp - motionInfo.time;
354     t = SGMisc<double>::min(t, 5);
355
356     SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle extrapolation: "
357            "extrapolation time = " << t);
358
359     // Do a few explicit euler steps with the constant acceleration's
360     // This must be sufficient ...
361     ecPos = motionInfo.position;
362     ecOrient = motionInfo.orientation;
363     SGVec3f linearVel = motionInfo.linearVel;
364     SGVec3f angularVel = motionInfo.angularVel;
365     while (0 < t) {
366       double h = 1e-1;
367       if (t < h)
368         h = t;
369
370       SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
371       ecPos += h*ecVel;
372       ecOrient += h*ecOrient.derivative(angularVel);
373
374       linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
375       angularVel += h*motionInfo.angularAccel;
376       
377       t -= h;
378     }
379
380     std::vector<FGPropertyData*>::const_iterator firstPropIt;
381     std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
382     speed = norm(linearVel) * SG_METER_TO_NM * 3600.0;
383     firstPropIt = it->second.properties.begin();
384     firstPropItEnd = it->second.properties.end();
385     while (firstPropIt != firstPropItEnd) {
386       PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
387       //cout << " Setting property..." << (*firstPropIt)->id;
388       
389       if (pIt != mPropertyMap.end())
390       {
391         switch ((*firstPropIt)->type) {
392           case props::INT:
393           case props::BOOL:
394           case props::LONG:
395             pIt->second->setIntValue((*firstPropIt)->int_value);
396             //cout << "Int: " << (*firstPropIt)->int_value << "\n";
397             break;
398           case props::FLOAT:
399           case props::DOUBLE:
400             pIt->second->setFloatValue((*firstPropIt)->float_value);
401             //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
402             break;
403           case props::STRING:
404           case props::UNSPECIFIED:
405             pIt->second->setStringValue((*firstPropIt)->string_value);
406             //cout << "Str: " << (*firstPropIt)->string_value << "\n";
407             break;
408           default:
409             // FIXME - currently defaults to float values
410             pIt->second->setFloatValue((*firstPropIt)->float_value);
411             //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
412             break;
413         }            
414       }
415       else
416       {
417         SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
418       }
419       
420       ++firstPropIt;
421     }
422   }
423   
424   // extract the position
425   pos = SGGeod::fromCart(ecPos);
426   altitude_ft = pos.getElevationFt();
427
428   // The quaternion rotating from the earth centered frame to the
429   // horizontal local frame
430   SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
431                                           (float)pos.getLatitudeRad());
432   // The orientation wrt the horizontal local frame
433   SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
434   float hDeg, pDeg, rDeg;
435   hlOr.getEulerDeg(hDeg, pDeg, rDeg);
436   hdg = hDeg;
437   roll = rDeg;
438   pitch = pDeg;
439
440   SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer position and orientation: "
441          << ecPos << ", " << hlOr);
442
443   //###########################//
444   // do calculations for radar //
445   //###########################//
446     double range_ft2 = UpdateRadar(manager);
447
448     //************************************//
449     // Tanker code                        //
450     //************************************//
451
452
453     if ( isTanker) {
454         if ( (range_ft2 < 250.0 * 250.0) &&
455             (y_shift > 0.0)    &&
456             (elevation > 0.0) ){
457                 // refuel_node->setBoolValue(true);
458             contact = true;
459         } else {
460             // refuel_node->setBoolValue(false);
461             contact = false;
462         }
463     } else {
464         contact = false;
465     }
466
467   Transform();
468 }
469
470 void
471 FGAIMultiplayer::addMotionInfo(const FGExternalMotionData& motionInfo,
472                                long stamp)
473 {
474   mLastTimestamp = stamp;
475
476   if (!mMotionInfo.empty()) {
477     double diff = motionInfo.time - mMotionInfo.rbegin()->first;
478
479     // packet is very old -- MP has probably reset (incl. his timebase)
480     if (diff < -10.0)
481       mMotionInfo.clear();
482
483     // drop packets arriving out of order
484     else if (diff < 0.0)
485       return;
486   }
487   mMotionInfo[motionInfo.time] = motionInfo;
488 }
489
490 void
491 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
492 {
493   SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
494   pNode->setDoubleValue(val);
495 }