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