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