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