]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Use SG_LOG(&strerror) instead of "perror".
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.cxx
4 //
5 // Written by Duncan McCreanor, started February 2003.
6 // duncan.mccreanor@airservicesaustralia.com
7 //
8 // Copyright (C) 2003  Airservices Australia
9 // Copyright (C) 2005  Oliver Schroeder
10 // Copyright (C) 2006  Mathias Froehlich
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27 //  
28 //////////////////////////////////////////////////////////////////////
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #include <iostream>
35 #include <algorithm>
36 #include <cstring>
37 #include <osg/Math>             // isNaN
38
39 #include <simgear/misc/stdint.hxx>
40 #include <simgear/timing/timestamp.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43
44 #include <AIModel/AIManager.hxx>
45 #include <AIModel/AIMultiplayer.hxx>
46 #include <Main/fg_props.hxx>
47 #include "multiplaymgr.hxx"
48 #include "mpmessages.hxx"
49 #include <FDM/flightProperties.hxx>
50
51 using namespace std;
52
53 #define MAX_PACKET_SIZE 1200
54 #define MAX_TEXT_SIZE 128
55
56 // These constants are provided so that the ident 
57 // command can list file versions
58 const char sMULTIPLAYMGR_BID[] = "$Id$";
59 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
60
61 struct IdPropertyList {
62   unsigned id;
63   const char* name;
64   simgear::props::Type type;
65 };
66  
67 static const IdPropertyList* findProperty(unsigned id);
68   
69 // A static map of protocol property id values to property paths,
70 // This should be extendable dynamically for every specific aircraft ...
71 // For now only that static list
72 static const IdPropertyList sIdPropertyList[] = {
73   {100, "surface-positions/left-aileron-pos-norm",  simgear::props::FLOAT},
74   {101, "surface-positions/right-aileron-pos-norm", simgear::props::FLOAT},
75   {102, "surface-positions/elevator-pos-norm",      simgear::props::FLOAT},
76   {103, "surface-positions/rudder-pos-norm",        simgear::props::FLOAT},
77   {104, "surface-positions/flap-pos-norm",          simgear::props::FLOAT},
78   {105, "surface-positions/speedbrake-pos-norm",    simgear::props::FLOAT},
79   {106, "gear/tailhook/position-norm",              simgear::props::FLOAT},
80   {107, "gear/launchbar/position-norm",             simgear::props::FLOAT},
81   {108, "gear/launchbar/state",                     simgear::props::STRING},
82   {109, "gear/launchbar/holdback-position-norm",    simgear::props::FLOAT},
83   {110, "canopy/position-norm",                     simgear::props::FLOAT},
84   {111, "surface-positions/wing-pos-norm",          simgear::props::FLOAT},
85   {112, "surface-positions/wing-fold-pos-norm",     simgear::props::FLOAT},
86
87   {200, "gear/gear[0]/compression-norm",           simgear::props::FLOAT},
88   {201, "gear/gear[0]/position-norm",              simgear::props::FLOAT},
89   {210, "gear/gear[1]/compression-norm",           simgear::props::FLOAT},
90   {211, "gear/gear[1]/position-norm",              simgear::props::FLOAT},
91   {220, "gear/gear[2]/compression-norm",           simgear::props::FLOAT},
92   {221, "gear/gear[2]/position-norm",              simgear::props::FLOAT},
93   {230, "gear/gear[3]/compression-norm",           simgear::props::FLOAT},
94   {231, "gear/gear[3]/position-norm",              simgear::props::FLOAT},
95   {240, "gear/gear[4]/compression-norm",           simgear::props::FLOAT},
96   {241, "gear/gear[4]/position-norm",              simgear::props::FLOAT},
97
98   {300, "engines/engine[0]/n1",  simgear::props::FLOAT},
99   {301, "engines/engine[0]/n2",  simgear::props::FLOAT},
100   {302, "engines/engine[0]/rpm", simgear::props::FLOAT},
101   {310, "engines/engine[1]/n1",  simgear::props::FLOAT},
102   {311, "engines/engine[1]/n2",  simgear::props::FLOAT},
103   {312, "engines/engine[1]/rpm", simgear::props::FLOAT},
104   {320, "engines/engine[2]/n1",  simgear::props::FLOAT},
105   {321, "engines/engine[2]/n2",  simgear::props::FLOAT},
106   {322, "engines/engine[2]/rpm", simgear::props::FLOAT},
107   {330, "engines/engine[3]/n1",  simgear::props::FLOAT},
108   {331, "engines/engine[3]/n2",  simgear::props::FLOAT},
109   {332, "engines/engine[3]/rpm", simgear::props::FLOAT},
110   {340, "engines/engine[4]/n1",  simgear::props::FLOAT},
111   {341, "engines/engine[4]/n2",  simgear::props::FLOAT},
112   {342, "engines/engine[4]/rpm", simgear::props::FLOAT},
113   {350, "engines/engine[5]/n1",  simgear::props::FLOAT},
114   {351, "engines/engine[5]/n2",  simgear::props::FLOAT},
115   {352, "engines/engine[5]/rpm", simgear::props::FLOAT},
116   {360, "engines/engine[6]/n1",  simgear::props::FLOAT},
117   {361, "engines/engine[6]/n2",  simgear::props::FLOAT},
118   {362, "engines/engine[6]/rpm", simgear::props::FLOAT},
119   {370, "engines/engine[7]/n1",  simgear::props::FLOAT},
120   {371, "engines/engine[7]/n2",  simgear::props::FLOAT},
121   {372, "engines/engine[7]/rpm", simgear::props::FLOAT},
122   {380, "engines/engine[8]/n1",  simgear::props::FLOAT},
123   {381, "engines/engine[8]/n2",  simgear::props::FLOAT},
124   {382, "engines/engine[8]/rpm", simgear::props::FLOAT},
125   {390, "engines/engine[9]/n1",  simgear::props::FLOAT},
126   {391, "engines/engine[9]/n2",  simgear::props::FLOAT},
127   {392, "engines/engine[9]/rpm", simgear::props::FLOAT},
128
129   {800, "rotors/main/rpm", simgear::props::FLOAT},
130   {801, "rotors/tail/rpm", simgear::props::FLOAT},
131   {810, "rotors/main/blade[0]/position-deg",  simgear::props::FLOAT},
132   {811, "rotors/main/blade[1]/position-deg",  simgear::props::FLOAT},
133   {812, "rotors/main/blade[2]/position-deg",  simgear::props::FLOAT},
134   {813, "rotors/main/blade[3]/position-deg",  simgear::props::FLOAT},
135   {820, "rotors/main/blade[0]/flap-deg",  simgear::props::FLOAT},
136   {821, "rotors/main/blade[1]/flap-deg",  simgear::props::FLOAT},
137   {822, "rotors/main/blade[2]/flap-deg",  simgear::props::FLOAT},
138   {823, "rotors/main/blade[3]/flap-deg",  simgear::props::FLOAT},
139   {830, "rotors/tail/blade[0]/position-deg",  simgear::props::FLOAT},
140   {831, "rotors/tail/blade[1]/position-deg",  simgear::props::FLOAT},
141
142   {900, "sim/hitches/aerotow/tow/length",                       simgear::props::FLOAT},
143   {901, "sim/hitches/aerotow/tow/elastic-constant",             simgear::props::FLOAT},
144   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            simgear::props::FLOAT},
145   {903, "sim/hitches/aerotow/tow/dist",                         simgear::props::FLOAT},
146   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   simgear::props::BOOL},
147   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   simgear::props::STRING},
148   {906, "sim/hitches/aerotow/tow/brake-force",                  simgear::props::FLOAT},
149   {907, "sim/hitches/aerotow/tow/end-force-x",                  simgear::props::FLOAT},
150   {908, "sim/hitches/aerotow/tow/end-force-y",                  simgear::props::FLOAT},
151   {909, "sim/hitches/aerotow/tow/end-force-z",                  simgear::props::FLOAT},
152   {930, "sim/hitches/aerotow/is-slave",                         simgear::props::BOOL},
153   {931, "sim/hitches/aerotow/speed-in-tow-direction",           simgear::props::FLOAT},
154   {932, "sim/hitches/aerotow/open",                             simgear::props::BOOL},
155   {933, "sim/hitches/aerotow/local-pos-x",                      simgear::props::FLOAT},
156   {934, "sim/hitches/aerotow/local-pos-y",                      simgear::props::FLOAT},
157   {935, "sim/hitches/aerotow/local-pos-z",                      simgear::props::FLOAT},
158
159   {1001, "controls/flight/slats",  simgear::props::FLOAT},
160   {1002, "controls/flight/speedbrake",  simgear::props::FLOAT},
161   {1003, "controls/flight/spoilers",  simgear::props::FLOAT},
162   {1004, "controls/gear/gear-down",  simgear::props::FLOAT},
163   {1005, "controls/lighting/nav-lights",  simgear::props::FLOAT},
164   {1006, "controls/armament/station[0]/jettison-all",  simgear::props::BOOL},
165
166   {1100, "sim/model/variant", simgear::props::INT},
167   {1101, "sim/model/livery/file", simgear::props::STRING},
168
169   {1200, "environment/wildfire/data", simgear::props::STRING},
170   {1201, "environment/contrail", simgear::props::INT},
171
172   {1300, "tanker", simgear::props::INT},
173
174   {10001, "sim/multiplay/transmission-freq-hz",  simgear::props::STRING},
175   {10002, "sim/multiplay/chat",  simgear::props::STRING},
176
177   {10100, "sim/multiplay/generic/string[0]", simgear::props::STRING},
178   {10101, "sim/multiplay/generic/string[1]", simgear::props::STRING},
179   {10102, "sim/multiplay/generic/string[2]", simgear::props::STRING},
180   {10103, "sim/multiplay/generic/string[3]", simgear::props::STRING},
181   {10104, "sim/multiplay/generic/string[4]", simgear::props::STRING},
182   {10105, "sim/multiplay/generic/string[5]", simgear::props::STRING},
183   {10106, "sim/multiplay/generic/string[6]", simgear::props::STRING},
184   {10107, "sim/multiplay/generic/string[7]", simgear::props::STRING},
185   {10108, "sim/multiplay/generic/string[8]", simgear::props::STRING},
186   {10109, "sim/multiplay/generic/string[9]", simgear::props::STRING},
187   {10110, "sim/multiplay/generic/string[10]", simgear::props::STRING},
188   {10111, "sim/multiplay/generic/string[11]", simgear::props::STRING},
189   {10112, "sim/multiplay/generic/string[12]", simgear::props::STRING},
190   {10113, "sim/multiplay/generic/string[13]", simgear::props::STRING},
191   {10114, "sim/multiplay/generic/string[14]", simgear::props::STRING},
192   {10115, "sim/multiplay/generic/string[15]", simgear::props::STRING},
193   {10116, "sim/multiplay/generic/string[16]", simgear::props::STRING},
194   {10117, "sim/multiplay/generic/string[17]", simgear::props::STRING},
195   {10118, "sim/multiplay/generic/string[18]", simgear::props::STRING},
196   {10119, "sim/multiplay/generic/string[19]", simgear::props::STRING},
197
198   {10200, "sim/multiplay/generic/float[0]", simgear::props::FLOAT},
199   {10201, "sim/multiplay/generic/float[1]", simgear::props::FLOAT},
200   {10202, "sim/multiplay/generic/float[2]", simgear::props::FLOAT},
201   {10203, "sim/multiplay/generic/float[3]", simgear::props::FLOAT},
202   {10204, "sim/multiplay/generic/float[4]", simgear::props::FLOAT},
203   {10205, "sim/multiplay/generic/float[5]", simgear::props::FLOAT},
204   {10206, "sim/multiplay/generic/float[6]", simgear::props::FLOAT},
205   {10207, "sim/multiplay/generic/float[7]", simgear::props::FLOAT},
206   {10208, "sim/multiplay/generic/float[8]", simgear::props::FLOAT},
207   {10209, "sim/multiplay/generic/float[9]", simgear::props::FLOAT},
208   {10210, "sim/multiplay/generic/float[10]", simgear::props::FLOAT},
209   {10211, "sim/multiplay/generic/float[11]", simgear::props::FLOAT},
210   {10212, "sim/multiplay/generic/float[12]", simgear::props::FLOAT},
211   {10213, "sim/multiplay/generic/float[13]", simgear::props::FLOAT},
212   {10214, "sim/multiplay/generic/float[14]", simgear::props::FLOAT},
213   {10215, "sim/multiplay/generic/float[15]", simgear::props::FLOAT},
214   {10216, "sim/multiplay/generic/float[16]", simgear::props::FLOAT},
215   {10217, "sim/multiplay/generic/float[17]", simgear::props::FLOAT},
216   {10218, "sim/multiplay/generic/float[18]", simgear::props::FLOAT},
217   {10219, "sim/multiplay/generic/float[19]", simgear::props::FLOAT},
218
219   {10300, "sim/multiplay/generic/int[0]", simgear::props::INT},
220   {10301, "sim/multiplay/generic/int[1]", simgear::props::INT},
221   {10302, "sim/multiplay/generic/int[2]", simgear::props::INT},
222   {10303, "sim/multiplay/generic/int[3]", simgear::props::INT},
223   {10304, "sim/multiplay/generic/int[4]", simgear::props::INT},
224   {10305, "sim/multiplay/generic/int[5]", simgear::props::INT},
225   {10306, "sim/multiplay/generic/int[6]", simgear::props::INT},
226   {10307, "sim/multiplay/generic/int[7]", simgear::props::INT},
227   {10308, "sim/multiplay/generic/int[8]", simgear::props::INT},
228   {10309, "sim/multiplay/generic/int[9]", simgear::props::INT},
229   {10310, "sim/multiplay/generic/int[10]", simgear::props::INT},
230   {10311, "sim/multiplay/generic/int[11]", simgear::props::INT},
231   {10312, "sim/multiplay/generic/int[12]", simgear::props::INT},
232   {10313, "sim/multiplay/generic/int[13]", simgear::props::INT},
233   {10314, "sim/multiplay/generic/int[14]", simgear::props::INT},
234   {10315, "sim/multiplay/generic/int[15]", simgear::props::INT},
235   {10316, "sim/multiplay/generic/int[16]", simgear::props::INT},
236   {10317, "sim/multiplay/generic/int[17]", simgear::props::INT},
237   {10318, "sim/multiplay/generic/int[18]", simgear::props::INT},
238   {10319, "sim/multiplay/generic/int[19]", simgear::props::INT}
239 };
240
241 const unsigned int numProperties = (sizeof(sIdPropertyList)
242                                  / sizeof(sIdPropertyList[0]));
243
244 // Look up a property ID using binary search.
245 namespace
246 {
247   struct ComparePropertyId
248   {
249     bool operator()(const IdPropertyList& lhs,
250                     const IdPropertyList& rhs)
251     {
252       return lhs.id < rhs.id;
253     }
254     bool operator()(const IdPropertyList& lhs,
255                     unsigned id)
256     {
257       return lhs.id < id;
258     }
259     bool operator()(unsigned id,
260                     const IdPropertyList& rhs)
261     {
262       return id < rhs.id;
263     }
264   };    
265 }
266
267 const IdPropertyList* findProperty(unsigned id)
268 {
269   std::pair<const IdPropertyList*, const IdPropertyList*> result
270     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
271                        ComparePropertyId());
272   if (result.first == result.second) {
273     return 0;
274   } else {
275     return result.first;
276   }
277 }
278
279 namespace
280 {
281   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
282   {
283     using namespace simgear;
284     const xdr_data_t* xdr = data;
285     while (xdr < end) {
286       unsigned id = XDR_decode_uint32(*xdr);
287       const IdPropertyList* plist = findProperty(id);
288     
289       if (plist) {
290         xdr++;
291         // How we decode the remainder of the property depends on the type
292         switch (plist->type) {
293         case props::INT:
294         case props::BOOL:
295         case props::LONG:
296           xdr++;
297           break;
298         case props::FLOAT:
299         case props::DOUBLE:
300           {
301             float val = XDR_decode_float(*xdr);
302             if (osg::isNaN(val))
303               return false;
304             xdr++;
305             break;
306           }
307         case props::STRING:
308         case props::UNSPECIFIED:
309           {
310             // String is complicated. It consists of
311             // The length of the string
312             // The string itself
313             // Padding to the nearest 4-bytes.
314             // XXX Yes, each byte is padded out to a word! Too late
315             // to change...
316             uint32_t length = XDR_decode_uint32(*xdr);
317             xdr++;
318             // Old versions truncated the string but left the length
319             // unadjusted.
320             if (length > MAX_TEXT_SIZE)
321               length = MAX_TEXT_SIZE;
322             xdr += length;
323             // Now handle the padding
324             while ((length % 4) != 0)
325               {
326                 xdr++;
327                 length++;
328                 //cout << "0";
329               }
330           }
331           break;
332         default:
333           // cerr << "Unknown Prop type " << id << " " << type << "\n";
334           xdr++;
335           break;
336         }            
337       }
338       else {
339         // give up; this is a malformed property list.
340         return false;
341       }
342     }
343     return true;
344   }
345 }
346
347 class MPPropertyListener : public SGPropertyChangeListener
348 {
349 public:
350   MPPropertyListener(FGMultiplayMgr* mp) :
351     _multiplay(mp)
352   {
353   }
354
355   virtual void childAdded(SGPropertyNode*, SGPropertyNode*)
356   {
357     _multiplay->setPropertiesChanged();
358   }
359
360 private:
361   FGMultiplayMgr* _multiplay;
362 };
363
364 //////////////////////////////////////////////////////////////////////
365 //
366 //  MultiplayMgr constructor
367 //
368 //////////////////////////////////////////////////////////////////////
369 FGMultiplayMgr::FGMultiplayMgr() 
370 {
371   mInitialised   = false;
372   mHaveServer    = false;
373   mListener = NULL;
374 } // FGMultiplayMgr::FGMultiplayMgr()
375 //////////////////////////////////////////////////////////////////////
376
377 //////////////////////////////////////////////////////////////////////
378 //
379 //  MultiplayMgr destructor
380 //
381 //////////////////////////////////////////////////////////////////////
382 FGMultiplayMgr::~FGMultiplayMgr() 
383 {
384   
385 } // FGMultiplayMgr::~FGMultiplayMgr()
386 //////////////////////////////////////////////////////////////////////
387
388 //////////////////////////////////////////////////////////////////////
389 //
390 //  Initialise object
391 //
392 //////////////////////////////////////////////////////////////////////
393 void
394 FGMultiplayMgr::init (void) 
395 {
396   //////////////////////////////////////////////////
397   //  Initialise object if not already done
398   //////////////////////////////////////////////////
399   if (mInitialised) {
400     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
401     return;
402   }
403   
404   fgSetBool("/sim/multiplay/online", false);
405   
406   //////////////////////////////////////////////////
407   //  Set members from property values
408   //////////////////////////////////////////////////
409   short rxPort = fgGetInt("/sim/multiplay/rxport");
410   string rxAddress = fgGetString("/sim/multiplay/rxhost");
411   short txPort = fgGetInt("/sim/multiplay/txport", 5000);
412   string txAddress = fgGetString("/sim/multiplay/txhost");
413   
414   int hz = fgGetInt("/sim/multiplay/tx-rate-hz", 10);
415   if (hz < 1) {
416     hz = 10;
417   }
418   
419   mDt = 1.0 / hz;
420   mTimeUntilSend = 0.0;
421   
422   mCallsign = fgGetString("/sim/multiplay/callsign");
423   if ((!txAddress.empty()) && (txAddress!="0")) {
424     mServer.set(txAddress.c_str(), txPort);
425     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
426       mHaveServer = false;
427       SG_LOG(SG_NETWORK, SG_ALERT,
428         "FGMultiplayMgr - Could not resolve '"
429         << txAddress << "'. Multiplayer mode disabled.");
430       return;
431     } else {
432         SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
433       mHaveServer = true;
434     }
435     if (rxPort <= 0)
436       rxPort = txPort;
437   }
438   if (rxPort <= 0) {
439     SG_LOG(SG_NETWORK, SG_ALERT,
440       "FGMultiplayMgr - No receiver port. Multiplayer mode disabled.");
441     return;
442   }
443   if (mCallsign.empty())
444     mCallsign = "JohnDoe"; // FIXME: use getpwuid
445   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
446   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
447   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
448   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
449   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
450   
451   mSocket.reset(new simgear::Socket());
452   if (!mSocket->open(false)) {
453     SG_LOG( SG_NETWORK, SG_WARN,
454             "FGMultiplayMgr - Failed to create data socket." );
455     return;
456   }
457   mSocket->setBlocking(false);
458   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
459     SG_LOG( SG_NETWORK, SG_ALERT,
460             "FGMultiplayMgr - Failed to bind receive socket. Multiplayer mode disabled. "
461             << strerror(errno) << "(errno " << errno << ")");
462     return;
463   }
464   
465   mPropertiesChanged = true;
466   mListener = new MPPropertyListener(this);
467   globals->get_props()->addChangeListener(mListener, false);
468   
469   fgSetBool("/sim/multiplay/online", true);
470   mInitialised = true;
471 } // FGMultiplayMgr::init()
472 //////////////////////////////////////////////////////////////////////
473
474 //////////////////////////////////////////////////////////////////////
475 //
476 //  Closes and deletes the local player object. Closes
477 //  and deletes the tx socket. Resets the object state to unitialised.
478 //
479 //////////////////////////////////////////////////////////////////////
480 void
481 FGMultiplayMgr::shutdown (void) 
482 {
483   fgSetBool("/sim/multiplay/online", false);
484   
485   if (mSocket.get()) {
486     mSocket->close();
487     mSocket.reset(); 
488   }
489   
490   MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
491     end = mMultiPlayerMap.end();
492   for (; it != end; ++it) {
493     it->second->setDie(true);
494   }
495   mMultiPlayerMap.clear();
496   
497   if (mListener) {
498     globals->get_props()->removeChangeListener(mListener);
499     delete mListener;
500     mListener = NULL;
501   }
502   
503   mInitialised = false;
504 } // FGMultiplayMgr::Close(void)
505 //////////////////////////////////////////////////////////////////////
506
507 void
508 FGMultiplayMgr::reinit()
509 {
510   shutdown();
511   init();
512 }
513
514 //////////////////////////////////////////////////////////////////////
515 //
516 //  Description: Sends the position data for the local position.
517 //
518 //////////////////////////////////////////////////////////////////////
519
520 /**
521  * The buffer that holds a multi-player message, suitably aligned.
522  */
523 union FGMultiplayMgr::MsgBuf
524 {
525     MsgBuf()
526     {
527         memset(&Msg, 0, sizeof(Msg));
528     }
529
530     T_MsgHdr* msgHdr()
531     {
532         return &Header;
533     }
534
535     const T_MsgHdr* msgHdr() const
536     {
537         return reinterpret_cast<const T_MsgHdr*>(&Header);
538     }
539
540     T_PositionMsg* posMsg()
541     {
542         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
543     }
544
545     const T_PositionMsg* posMsg() const
546     {
547         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
548     }
549
550     xdr_data_t* properties()
551     {
552         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
553                                              + sizeof(T_PositionMsg));
554     }
555
556     const xdr_data_t* properties() const
557     {
558         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
559                                                    + sizeof(T_PositionMsg));
560     }
561     /**
562      * The end of the properties buffer.
563      */
564     xdr_data_t* propsEnd()
565     {
566         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
567     };
568
569     const xdr_data_t* propsEnd() const
570     {
571         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
572     };
573     /**
574      * The end of properties actually in the buffer. This assumes that
575      * the message header is valid.
576      */
577     xdr_data_t* propsRecvdEnd()
578     {
579         return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
580     }
581
582     const xdr_data_t* propsRecvdEnd() const
583     {
584         return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
585     }
586     
587     xdr_data2_t double_val;
588     char Msg[MAX_PACKET_SIZE];
589     T_MsgHdr Header;
590 };
591
592 bool
593 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
594 {
595     // check for corrupted data (NaNs)
596     bool isCorrupted = false;
597     isCorrupted |= ((osg::isNaN(motionInfo.time           )) ||
598                     (osg::isNaN(motionInfo.lag            )) ||
599                     (osg::isNaN(motionInfo.orientation(3) )));
600     for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
601     {
602         isCorrupted |= ((osg::isNaN(motionInfo.position(i)      ))||
603                         (osg::isNaN(motionInfo.orientation(i)   ))||
604                         (osg::isNaN(motionInfo.linearVel(i))    )||
605                         (osg::isNaN(motionInfo.angularVel(i))   )||
606                         (osg::isNaN(motionInfo.linearAccel(i))  )||
607                         (osg::isNaN(motionInfo.angularAccel(i)) ));
608     }
609     return !isCorrupted;
610 }
611
612 void
613 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
614 {
615   if ((! mInitialised) || (! mHaveServer))
616         return;
617
618   if (! mHaveServer) {
619       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
620       return;
621   }
622
623   if (!isSane(motionInfo))
624   {
625       // Current local data is invalid (NaN), so stop MP transmission.
626       // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
627       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
628               << "Local data is invalid (NaN). Data not transmitted.");
629       return;
630   }
631
632   static MsgBuf msgBuf;
633   static unsigned msgLen = 0;
634   T_PositionMsg* PosMsg = msgBuf.posMsg();
635
636   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
637   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
638   if (fgGetBool("/sim/freeze/replay-state", true))
639   {
640       // do not send position updates during replay
641       for (unsigned i = 0 ; i < 3; ++i)
642       {
643           // no movement during replay
644           PosMsg->linearVel[i] = XDR_encode_float (0.0);
645           PosMsg->angularVel[i] = XDR_encode_float (0.0);
646           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
647           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
648       }
649       // all other data remains unchanged (resend last state) 
650   }
651   else
652   {
653       PosMsg->time = XDR_encode_double (motionInfo.time);
654       PosMsg->lag = XDR_encode_double (motionInfo.lag);
655       for (unsigned i = 0 ; i < 3; ++i)
656         PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
657       SGVec3f angleAxis;
658       motionInfo.orientation.getAngleAxis(angleAxis);
659       for (unsigned i = 0 ; i < 3; ++i)
660         PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
661       for (unsigned i = 0 ; i < 3; ++i)
662         PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
663       for (unsigned i = 0 ; i < 3; ++i)
664         PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
665       for (unsigned i = 0 ; i < 3; ++i)
666         PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
667       for (unsigned i = 0 ; i < 3; ++i)
668         PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
669
670       xdr_data_t* ptr = msgBuf.properties();
671       std::vector<FGPropertyData*>::const_iterator it;
672       it = motionInfo.properties.begin();
673       //cout << "OUTPUT PROPERTIES\n";
674       xdr_data_t* msgEnd = msgBuf.propsEnd();
675       while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
676         
677         // First element is the ID. Write it out when we know we have room for
678         // the whole property.
679         xdr_data_t id =  XDR_encode_uint32((*it)->id);
680         // The actual data representation depends on the type
681         switch ((*it)->type) {
682           case simgear::props::INT:
683           case simgear::props::BOOL:
684           case simgear::props::LONG:
685             *ptr++ = id;
686             *ptr++ = XDR_encode_uint32((*it)->int_value);
687             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
688             break;
689           case simgear::props::FLOAT:
690           case simgear::props::DOUBLE:
691             *ptr++ = id;
692             *ptr++ = XDR_encode_float((*it)->float_value);
693             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
694             break;
695           case simgear::props::STRING:
696           case simgear::props::UNSPECIFIED:
697             {
698               // String is complicated. It consists of
699               // The length of the string
700               // The string itself
701               // Padding to the nearest 4-bytes.        
702               const char* lcharptr = (*it)->string_value;
703               
704               if (lcharptr != 0)
705               {
706                 // Add the length         
707                 ////cout << "String length: " << strlen(lcharptr) << "\n";
708                 uint32_t len = strlen(lcharptr);
709                 if (len > MAX_TEXT_SIZE)
710                   len = MAX_TEXT_SIZE;
711                 // XXX This should not be using 4 bytes per character!
712                 // If there's not enough room for this property, drop it
713                 // on the floor.
714                 if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
715                     goto escape;
716                 //cout << "String length unint32: " << len << "\n";
717                 *ptr++ = id;
718                 *ptr++ = XDR_encode_uint32(len);
719                 if (len != 0)
720                 {
721                   // Now the text itself
722                   // XXX This should not be using 4 bytes per character!
723                   int lcount = 0;
724                   while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
725                   {
726                     *ptr++ = XDR_encode_int8(*lcharptr);
727                     lcharptr++;
728                     lcount++;          
729                   }
730     
731                   //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
732     
733                   // Now pad if required
734                   while ((lcount % 4) != 0)
735                   {
736                     *ptr++ = XDR_encode_int8(0);
737                     lcount++;          
738                     //cout << "0";
739                   }
740                   
741                   //cout << "\n";
742                 }
743               }
744               else
745               {
746                 // Nothing to encode
747                 *ptr++ = id;
748                 *ptr++ = XDR_encode_uint32(0);
749                 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
750               }
751             }
752             break;
753             
754           default:
755             //cout << " Unknown Type: " << (*it)->type << "\n";
756             *ptr++ = id;
757             *ptr++ = XDR_encode_float((*it)->float_value);;
758             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
759             break;
760         }
761             
762         ++it;
763       }
764   escape:
765       msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
766       FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
767   }
768   if (msgLen>0)
769       mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
770   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
771 } // FGMultiplayMgr::SendMyPosition()
772
773 //////////////////////////////////////////////////////////////////////
774
775 //////////////////////////////////////////////////////////////////////
776 //
777 //  Name: SendTextMessage
778 //  Description: Sends a message to the player. The message must
779 //  contain a valid and correctly filled out header and optional
780 //  message body.
781 //
782 //////////////////////////////////////////////////////////////////////
783 void
784 FGMultiplayMgr::SendTextMessage(const string &MsgText)
785 {
786   if (!mInitialised || !mHaveServer)
787     return;
788
789   T_MsgHdr MsgHdr;
790   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
791   //////////////////////////////////////////////////
792   // Divide the text string into blocks that fit
793   // in the message and send the blocks.
794   //////////////////////////////////////////////////
795   unsigned iNextBlockPosition = 0;
796   T_ChatMsg ChatMsg;
797   
798   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
799   while (iNextBlockPosition < MsgText.length()) {
800     strncpy (ChatMsg.Text, 
801              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
802              MAX_CHAT_MSG_LEN);
803     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
804     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
805     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
806     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
807     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
808
809   }
810   
811   
812 } // FGMultiplayMgr::SendTextMessage ()
813 //////////////////////////////////////////////////////////////////////
814
815 //////////////////////////////////////////////////////////////////////
816 //
817 //  Name: ProcessData
818 //  Description: Processes data waiting at the receive socket. The
819 //  processing ends when there is no more data at the socket.
820 //  
821 //////////////////////////////////////////////////////////////////////
822 void
823 FGMultiplayMgr::update(double dt) 
824 {
825   if (!mInitialised)
826     return;
827
828   /// Just for expiry
829   long stamp = SGTimeStamp::now().getSeconds();
830
831   //////////////////////////////////////////////////
832   //  Send if required
833   //////////////////////////////////////////////////
834   mTimeUntilSend -= dt;
835   if (mTimeUntilSend <= 0.0) {
836     Send();
837   }
838
839   //////////////////////////////////////////////////
840   //  Read the receive socket and process any data
841   //////////////////////////////////////////////////
842   ssize_t bytes;
843   do {
844     MsgBuf msgBuf;
845     //////////////////////////////////////////////////
846     //  Although the recv call asks for 
847     //  MAX_PACKET_SIZE of data, the number of bytes
848     //  returned will only be that of the next
849     //  packet waiting to be processed.
850     //////////////////////////////////////////////////
851     simgear::IPAddress SenderAddress;
852     int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
853                               &SenderAddress);
854     //////////////////////////////////////////////////
855     //  no Data received
856     //////////////////////////////////////////////////
857     if (RecvStatus == 0)
858         break;
859
860     // socket error reported?
861     // errno isn't thread-safe - so only check its value when
862     // socket return status < 0 really indicates a failure.
863     if ((RecvStatus < 0)&&
864         ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
865     {
866         // ignore "normal" errors
867         break;
868     }
869
870     if (RecvStatus<0)
871     {
872         SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
873                << strerror(errno) << "(errno " << errno << ")");
874         break;
875     }
876
877     // status is positive: bytes received
878     bytes = (ssize_t) RecvStatus;
879     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
880       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
881               << "received message with insufficient data" );
882       break;
883     }
884     //////////////////////////////////////////////////
885     //  Read header
886     //////////////////////////////////////////////////
887     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
888     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
889     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
890     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
891     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
892     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
893     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
894     if (MsgHdr->Magic != MSG_MAGIC) {
895       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
896               << "message has invalid magic number!" );
897       break;
898     }
899     if (MsgHdr->Version != PROTO_VER) {
900       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
901               << "message has invalid protocol number!" );
902       break;
903     }
904     if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
905       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
906              << "message from " << MsgHdr->Callsign << " has invalid length!");
907       break;
908     }
909     //////////////////////////////////////////////////
910     //  Process messages
911     //////////////////////////////////////////////////
912     switch (MsgHdr->MsgId) {
913     case CHAT_MSG_ID:
914       ProcessChatMsg(msgBuf, SenderAddress);
915       break;
916     case POS_DATA_ID:
917       ProcessPosMsg(msgBuf, SenderAddress, stamp);
918       break;
919     case UNUSABLE_POS_DATA_ID:
920     case OLD_OLD_POS_DATA_ID:
921     case OLD_PROP_MSG_ID:
922     case OLD_POS_DATA_ID:
923       break;
924     default:
925       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
926               << "Unknown message Id received: " << MsgHdr->MsgId );
927       break;
928     }
929   } while (bytes > 0);
930
931   // check for expiry
932   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
933   while (it != mMultiPlayerMap.end()) {
934     if (it->second->getLastTimestamp() + 10 < stamp) {
935       std::string name = it->first;
936       it->second->setDie(true);
937       mMultiPlayerMap.erase(it);
938       it = mMultiPlayerMap.upper_bound(name);
939     } else
940       ++it;
941   }
942 } // FGMultiplayMgr::ProcessData(void)
943 //////////////////////////////////////////////////////////////////////
944
945 void
946 FGMultiplayMgr::Send()
947 {
948   using namespace simgear;
949   
950   findProperties();
951     
952   // smooth the send rate, by adjusting based on the 'remainder' time, which
953   // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
954   // however.
955     if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
956       mTimeUntilSend = mDt + mTimeUntilSend;
957     } else {
958       mTimeUntilSend = mDt;
959     }
960
961     double sim_time = globals->get_sim_time_sec();
962     static double lastTime = 0.0;
963     
964    // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
965     lastTime = sim_time;
966     
967     FlightProperties ifce;
968
969     // put together a motion info struct, you will get that later
970     // from FGInterface directly ...
971     FGExternalMotionData motionInfo;
972
973     // The current simulation time we need to update for,
974     // note that the simulation time is updated before calling all the
975     // update methods. Thus it contains the time intervals *end* time.
976     // The FDM is already run, so the states belong to that time.
977     motionInfo.time = sim_time;
978     motionInfo.lag = mDt;
979
980     // These are for now converted from lat/lon/alt and euler angles.
981     // But this should change in FGInterface ...
982     double lon = ifce.get_Longitude();
983     double lat = ifce.get_Latitude();
984     // first the aprioriate structure for the geodetic one
985     SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
986     // Convert to cartesion coordinate
987     motionInfo.position = SGVec3d::fromGeod(geod);
988     
989     // The quaternion rotating from the earth centered frame to the
990     // horizontal local frame
991     SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
992     // The orientation wrt the horizontal local frame
993     float heading = ifce.get_Psi();
994     float pitch = ifce.get_Theta();
995     float roll = ifce.get_Phi();
996     SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
997     // The orientation of the vehicle wrt the earth centered frame
998     motionInfo.orientation = qEc2Hl*hlOr;
999
1000     if (!globals->get_subsystem("flight")->is_suspended()) {
1001       // velocities
1002       motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1003                                                       ifce.get_vBody(),
1004                                                       ifce.get_wBody());
1005       motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1006                                       ifce.get_Q_body(),
1007                                       ifce.get_R_body());
1008       
1009       // accels, set that to zero for now.
1010       // Angular accelerations are missing from the interface anyway,
1011       // linear accelerations are screwed up at least for JSBSim.
1012 //  motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1013 //                                                    ifce.get_V_dot_body(),
1014 //                                                    ifce.get_W_dot_body());
1015       motionInfo.linearAccel = SGVec3f::zeros();
1016       motionInfo.angularAccel = SGVec3f::zeros();
1017     } else {
1018       // if the interface is suspendend, prevent the client from
1019       // wild extrapolations
1020       motionInfo.linearVel = SGVec3f::zeros();
1021       motionInfo.angularVel = SGVec3f::zeros();
1022       motionInfo.linearAccel = SGVec3f::zeros();
1023       motionInfo.angularAccel = SGVec3f::zeros();
1024     }
1025
1026     // now send the properties
1027     PropertyMap::iterator it;
1028     for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1029       FGPropertyData* pData = new FGPropertyData;
1030       pData->id = it->first;
1031       pData->type = it->second->getType();
1032       
1033       switch (pData->type) {
1034         case props::INT:
1035         case props::LONG:
1036         case props::BOOL:
1037           pData->int_value = it->second->getIntValue();
1038           break;
1039         case props::FLOAT:
1040         case props::DOUBLE:
1041           pData->float_value = it->second->getFloatValue();
1042           break;
1043         case props::STRING:
1044         case props::UNSPECIFIED:
1045           {
1046             // FIXME: We assume unspecified are strings for the moment.
1047
1048             const char* cstr = it->second->getStringValue();
1049             int len = strlen(cstr);
1050             
1051             if (len > 0)
1052             {            
1053               pData->string_value = new char[len + 1];
1054               strcpy(pData->string_value, cstr);
1055             }
1056             else
1057             {
1058               // Size 0 - ignore
1059               pData->string_value = 0;            
1060             }
1061
1062             //cout << " Sending property " << pData->id << " " << pData->type << " " <<  pData->string_value << "\n";
1063             break;        
1064           }
1065         default:
1066           // FIXME Currently default to a float. 
1067           //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1068           pData->float_value = it->second->getFloatValue();
1069           break;
1070       }
1071       
1072       motionInfo.properties.push_back(pData);
1073     }
1074
1075     SendMyPosition(motionInfo);
1076 }
1077
1078
1079 //////////////////////////////////////////////////////////////////////
1080 //
1081 //  handle a position message
1082 //
1083 //////////////////////////////////////////////////////////////////////
1084 void
1085 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1086                               const simgear::IPAddress& SenderAddress, long stamp)
1087 {
1088   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1089   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1090     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1091             << "Position message received with insufficient data" );
1092     return;
1093   }
1094   const T_PositionMsg* PosMsg = Msg.posMsg();
1095   FGExternalMotionData motionInfo;
1096   motionInfo.time = XDR_decode_double(PosMsg->time);
1097   motionInfo.lag = XDR_decode_double(PosMsg->lag);
1098   for (unsigned i = 0; i < 3; ++i)
1099     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1100   SGVec3f angleAxis;
1101   for (unsigned i = 0; i < 3; ++i)
1102     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1103   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1104   for (unsigned i = 0; i < 3; ++i)
1105     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1106   for (unsigned i = 0; i < 3; ++i)
1107     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1108   for (unsigned i = 0; i < 3; ++i)
1109     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1110   for (unsigned i = 0; i < 3; ++i)
1111     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1112
1113   // sanity check: do not allow injection of corrupted data (NaNs)
1114   if (!isSane(motionInfo))
1115   {
1116       // drop this message, keep old position until receiving valid data
1117       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1118               << "Position message with invalid data (NaN) received from "
1119               << MsgHdr->Callsign);
1120       return;
1121   }
1122
1123   //cout << "INPUT MESSAGE\n";
1124
1125   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1126   // on 32 bit architectures and 200 bytes on 64 bit, and this
1127   // structure is put directly on the wire. By looking at the padding,
1128   // we can sort through the mess, mostly:
1129   // If padding is 0 (which is not a valid property type), then the
1130   // message was produced by a new client or an old 64 bit client that
1131   // happened to have 0 on the stack;
1132   // Else if the property list starting with the padding word is
1133   // well-formed, then the client is probably an old 32 bit client and
1134   // we'll go with that;
1135   // Else it is an old 64-bit client and properties start after the
1136   // padding.
1137   // There is a chance that we could be fooled by garbage in the
1138   // padding looking like a valid property, so verifyProperties() is
1139   // strict about the validity of the property values.
1140   const xdr_data_t* xdr = Msg.properties();
1141   if (PosMsg->pad != 0) {
1142     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1143       xdr = &PosMsg->pad;
1144     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1145       goto noprops;
1146   }
1147   while (xdr < Msg.propsRecvdEnd()) {
1148     // simgear::props::Type type = simgear::props::UNSPECIFIED;
1149     
1150     // First element is always the ID
1151     unsigned id = XDR_decode_uint32(*xdr);
1152     //cout << pData->id << " ";
1153     xdr++;
1154     
1155     // Check the ID actually exists and get the type
1156     const IdPropertyList* plist = findProperty(id);
1157     
1158     if (plist)
1159     {
1160       FGPropertyData* pData = new FGPropertyData;
1161       pData->id = id;
1162       pData->type = plist->type;
1163       // How we decode the remainder of the property depends on the type
1164       switch (pData->type) {
1165         case simgear::props::INT:
1166         case simgear::props::BOOL:
1167         case simgear::props::LONG:
1168           pData->int_value = XDR_decode_uint32(*xdr);
1169           xdr++;
1170           //cout << pData->int_value << "\n";
1171           break;
1172         case simgear::props::FLOAT:
1173         case simgear::props::DOUBLE:
1174           pData->float_value = XDR_decode_float(*xdr);
1175           xdr++;
1176           //cout << pData->float_value << "\n";
1177           break;
1178         case simgear::props::STRING:
1179         case simgear::props::UNSPECIFIED:
1180           {
1181             // String is complicated. It consists of
1182             // The length of the string
1183             // The string itself
1184             // Padding to the nearest 4-bytes.    
1185             uint32_t length = XDR_decode_uint32(*xdr);
1186             xdr++;
1187             //cout << length << " ";
1188             // Old versions truncated the string but left the length unadjusted.
1189             if (length > MAX_TEXT_SIZE)
1190               length = MAX_TEXT_SIZE;
1191             pData->string_value = new char[length + 1];
1192             //cout << " String: ";
1193             for (unsigned i = 0; i < length; i++)
1194               {
1195                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1196                 xdr++;
1197                 //cout << pData->string_value[i];
1198               }
1199
1200             pData->string_value[length] = '\0';
1201
1202             // Now handle the padding
1203             while ((length % 4) != 0)
1204               {
1205                 xdr++;
1206                 length++;
1207                 //cout << "0";
1208               }
1209             //cout << "\n";
1210           }
1211           break;
1212
1213         default:
1214           pData->float_value = XDR_decode_float(*xdr);
1215           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1216           xdr++;
1217           break;
1218       }
1219
1220       motionInfo.properties.push_back(pData);
1221     }
1222     else
1223     {
1224       // We failed to find the property. We'll try the next packet immediately.
1225       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1226              "message from " << MsgHdr->Callsign << " has unknown property id "
1227              << id); 
1228     }
1229   }
1230  noprops:
1231   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1232   if (!mp)
1233     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1234   mp->addMotionInfo(motionInfo, stamp);
1235 } // FGMultiplayMgr::ProcessPosMsg()
1236 //////////////////////////////////////////////////////////////////////
1237
1238 //////////////////////////////////////////////////////////////////////
1239 //
1240 //  handle a chat message
1241 //  FIXME: display chat message within flightgear
1242 //
1243 //////////////////////////////////////////////////////////////////////
1244 void
1245 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1246                                const simgear::IPAddress& SenderAddress)
1247 {
1248   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1249   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1250     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1251             << "Chat message received with insufficient data" );
1252     return;
1253   }
1254   
1255   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1256   const T_ChatMsg* ChatMsg
1257       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1258   strncpy(chatStr, ChatMsg->Text,
1259           MsgHdr->MsgLen - sizeof(T_MsgHdr));
1260   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1261   
1262   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1263            << " " << chatStr);
1264
1265   delete [] chatStr;
1266 } // FGMultiplayMgr::ProcessChatMsg ()
1267 //////////////////////////////////////////////////////////////////////
1268
1269 void
1270 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1271 {
1272   uint32_t len;
1273   switch (MsgId) {
1274   case CHAT_MSG_ID:
1275     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1276     break;
1277   case POS_DATA_ID:
1278     len = _len;
1279     break;
1280   default:
1281     len = sizeof(T_MsgHdr);
1282     break;
1283   }
1284   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1285   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1286   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1287   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1288   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1289   MsgHdr->ReplyPort       = 0; // now
1290   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1291   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1292 }
1293
1294 FGAIMultiplayer*
1295 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1296                                const std::string& modelName)
1297 {
1298   if (0 < mMultiPlayerMap.count(callsign))
1299     return mMultiPlayerMap[callsign].get();
1300
1301   FGAIMultiplayer* mp = new FGAIMultiplayer;
1302   mp->setPath(modelName.c_str());
1303   mp->setCallSign(callsign);
1304   mMultiPlayerMap[callsign] = mp;
1305
1306   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
1307   if (aiMgr) {
1308     aiMgr->attach(mp);
1309
1310     /// FIXME: that must follow the attach ATM ...
1311     for (unsigned i = 0; i < numProperties; ++i)
1312       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1313   }
1314
1315   return mp;
1316 }
1317
1318 FGAIMultiplayer*
1319 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1320 {
1321   if (0 < mMultiPlayerMap.count(callsign))
1322     return mMultiPlayerMap[callsign].get();
1323   else
1324     return 0;
1325 }
1326
1327 void
1328 FGMultiplayMgr::findProperties()
1329 {
1330   if (!mPropertiesChanged) {
1331     return;
1332   }
1333   
1334   mPropertiesChanged = false;
1335   
1336   for (unsigned i = 0; i < numProperties; ++i) {
1337       const char* name = sIdPropertyList[i].name;
1338       SGPropertyNode* pNode = globals->get_props()->getNode(name);
1339       if (!pNode) {
1340         continue;
1341       }
1342       
1343       int id = sIdPropertyList[i].id;
1344       if (mPropertyMap.find(id) != mPropertyMap.end()) {
1345         continue; // already activated
1346       }
1347       
1348       mPropertyMap[id] = pNode;
1349       SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());
1350     }
1351 }