]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Sync. w. JSBSim CVS
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.hpp
4 //
5 // Written by Duncan McCreanor, started February 2003.
6 // duncan.mccreanor@airservicesaustralia.com
7 //
8 // Copyright (C) 2003  Airservices Australia
9 // Copyright (C) 2005  Oliver Schroeder
10 // Copyright (C) 2006  Mathias Froehlich
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27 //  
28 //////////////////////////////////////////////////////////////////////
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #include <iostream>
35 #include <algorithm>
36 #include <cstring>
37 #include <osg/Math>             // isNaN
38 #include <plib/netSocket.h>
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 <Main/fg_props.hxx>
47 #include "multiplaymgr.hxx"
48 #include "mpmessages.hxx"
49
50 using namespace std;
51
52 #define MAX_PACKET_SIZE 1200
53 #define MAX_TEXT_SIZE 128
54
55 // These constants are provided so that the ident 
56 // command can list file versions
57 const char sMULTIPLAYMGR_BID[] = "$Id$";
58 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
59
60 // A static map of protocol property id values to property paths,
61 // This should be extendable dynamically for every specific aircraft ...
62 // For now only that static list
63 FGMultiplayMgr::IdPropertyList
64 const FGMultiplayMgr::sIdPropertyList[] = {
65   {100, "surface-positions/left-aileron-pos-norm",  SGPropertyNode::FLOAT},
66   {101, "surface-positions/right-aileron-pos-norm", SGPropertyNode::FLOAT},
67   {102, "surface-positions/elevator-pos-norm",      SGPropertyNode::FLOAT},
68   {103, "surface-positions/rudder-pos-norm",        SGPropertyNode::FLOAT},
69   {104, "surface-positions/flap-pos-norm",          SGPropertyNode::FLOAT},
70   {105, "surface-positions/speedbrake-pos-norm",    SGPropertyNode::FLOAT},
71   {106, "gear/tailhook/position-norm",              SGPropertyNode::FLOAT},
72   {107, "gear/launchbar/position-norm",             SGPropertyNode::FLOAT},
73   {108, "gear/launchbar/state",                     SGPropertyNode::STRING},
74   {109, "gear/launchbar/holdback-position-norm",    SGPropertyNode::FLOAT},
75   {110, "canopy/position-norm",                     SGPropertyNode::FLOAT},
76   {111, "surface-positions/wing-pos-norm",          SGPropertyNode::FLOAT},
77   {112, "surface-positions/wing-fold-pos-norm",     SGPropertyNode::FLOAT},
78
79   {200, "gear/gear[0]/compression-norm",           SGPropertyNode::FLOAT},
80   {201, "gear/gear[0]/position-norm",              SGPropertyNode::FLOAT},
81   {210, "gear/gear[1]/compression-norm",           SGPropertyNode::FLOAT},
82   {211, "gear/gear[1]/position-norm",              SGPropertyNode::FLOAT},
83   {220, "gear/gear[2]/compression-norm",           SGPropertyNode::FLOAT},
84   {221, "gear/gear[2]/position-norm",              SGPropertyNode::FLOAT},
85   {230, "gear/gear[3]/compression-norm",           SGPropertyNode::FLOAT},
86   {231, "gear/gear[3]/position-norm",              SGPropertyNode::FLOAT},
87   {240, "gear/gear[4]/compression-norm",           SGPropertyNode::FLOAT},
88   {241, "gear/gear[4]/position-norm",              SGPropertyNode::FLOAT},
89
90   {300, "engines/engine[0]/n1",  SGPropertyNode::FLOAT},
91   {301, "engines/engine[0]/n2",  SGPropertyNode::FLOAT},
92   {302, "engines/engine[0]/rpm", SGPropertyNode::FLOAT},
93   {310, "engines/engine[1]/n1",  SGPropertyNode::FLOAT},
94   {311, "engines/engine[1]/n2",  SGPropertyNode::FLOAT},
95   {312, "engines/engine[1]/rpm", SGPropertyNode::FLOAT},
96   {320, "engines/engine[2]/n1",  SGPropertyNode::FLOAT},
97   {321, "engines/engine[2]/n2",  SGPropertyNode::FLOAT},
98   {322, "engines/engine[2]/rpm", SGPropertyNode::FLOAT},
99   {330, "engines/engine[3]/n1",  SGPropertyNode::FLOAT},
100   {331, "engines/engine[3]/n2",  SGPropertyNode::FLOAT},
101   {332, "engines/engine[3]/rpm", SGPropertyNode::FLOAT},
102   {340, "engines/engine[4]/n1",  SGPropertyNode::FLOAT},
103   {341, "engines/engine[4]/n2",  SGPropertyNode::FLOAT},
104   {342, "engines/engine[4]/rpm", SGPropertyNode::FLOAT},
105   {350, "engines/engine[5]/n1",  SGPropertyNode::FLOAT},
106   {351, "engines/engine[5]/n2",  SGPropertyNode::FLOAT},
107   {352, "engines/engine[5]/rpm", SGPropertyNode::FLOAT},
108   {360, "engines/engine[6]/n1",  SGPropertyNode::FLOAT},
109   {361, "engines/engine[6]/n2",  SGPropertyNode::FLOAT},
110   {362, "engines/engine[6]/rpm", SGPropertyNode::FLOAT},
111   {370, "engines/engine[7]/n1",  SGPropertyNode::FLOAT},
112   {371, "engines/engine[7]/n2",  SGPropertyNode::FLOAT},
113   {372, "engines/engine[7]/rpm", SGPropertyNode::FLOAT},
114   {380, "engines/engine[8]/n1",  SGPropertyNode::FLOAT},
115   {381, "engines/engine[8]/n2",  SGPropertyNode::FLOAT},
116   {382, "engines/engine[8]/rpm", SGPropertyNode::FLOAT},
117   {390, "engines/engine[9]/n1",  SGPropertyNode::FLOAT},
118   {391, "engines/engine[9]/n2",  SGPropertyNode::FLOAT},
119   {392, "engines/engine[9]/rpm", SGPropertyNode::FLOAT},
120
121   {800, "rotors/main/rpm", SGPropertyNode::FLOAT},
122   {801, "rotors/tail/rpm", SGPropertyNode::FLOAT},
123   {810, "rotors/main/blade[0]/position-deg",  SGPropertyNode::FLOAT},
124   {811, "rotors/main/blade[1]/position-deg",  SGPropertyNode::FLOAT},
125   {812, "rotors/main/blade[2]/position-deg",  SGPropertyNode::FLOAT},
126   {813, "rotors/main/blade[3]/position-deg",  SGPropertyNode::FLOAT},
127   {820, "rotors/main/blade[0]/flap-deg",  SGPropertyNode::FLOAT},
128   {821, "rotors/main/blade[1]/flap-deg",  SGPropertyNode::FLOAT},
129   {822, "rotors/main/blade[2]/flap-deg",  SGPropertyNode::FLOAT},
130   {823, "rotors/main/blade[3]/flap-deg",  SGPropertyNode::FLOAT},
131   {830, "rotors/tail/blade[0]/position-deg",  SGPropertyNode::FLOAT},
132   {831, "rotors/tail/blade[1]/position-deg",  SGPropertyNode::FLOAT},
133
134   {900, "sim/hitches/aerotow/tow/length",                       SGPropertyNode::FLOAT},
135   {901, "sim/hitches/aerotow/tow/elastic-constant",             SGPropertyNode::FLOAT},
136   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            SGPropertyNode::FLOAT},
137   {903, "sim/hitches/aerotow/tow/dist",                         SGPropertyNode::FLOAT},
138   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   SGPropertyNode::BOOL},
139   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   SGPropertyNode::STRING},
140   {906, "sim/hitches/aerotow/tow/brake-force",                  SGPropertyNode::FLOAT},
141   {907, "sim/hitches/aerotow/tow/end-force-x",                  SGPropertyNode::FLOAT},
142   {908, "sim/hitches/aerotow/tow/end-force-y",                  SGPropertyNode::FLOAT},
143   {909, "sim/hitches/aerotow/tow/end-force-z",                  SGPropertyNode::FLOAT},
144   {930, "sim/hitches/aerotow/is-slave",                         SGPropertyNode::BOOL},
145   {931, "sim/hitches/aerotow/speed-in-tow-direction",           SGPropertyNode::FLOAT},
146   {932, "sim/hitches/aerotow/open",                             SGPropertyNode::BOOL},
147   {933, "sim/hitches/aerotow/local-pos-x",                      SGPropertyNode::FLOAT},
148   {934, "sim/hitches/aerotow/local-pos-y",                      SGPropertyNode::FLOAT},
149   {935, "sim/hitches/aerotow/local-pos-z",                      SGPropertyNode::FLOAT},
150
151   {1001, "controls/flight/slats",  SGPropertyNode::FLOAT},
152   {1002, "controls/flight/speedbrake",  SGPropertyNode::FLOAT},
153   {1003, "controls/flight/spoilers",  SGPropertyNode::FLOAT},
154   {1004, "controls/gear/gear-down",  SGPropertyNode::FLOAT},
155   {1005, "controls/lighting/nav-lights",  SGPropertyNode::FLOAT},
156   {1006, "controls/armament/station[0]/jettison-all",  SGPropertyNode::BOOL},
157
158   {1100, "sim/model/variant", SGPropertyNode::INT},
159   {1101, "sim/model/livery/file", SGPropertyNode::STRING},
160
161   {1200, "environment/wildfire/data", SGPropertyNode::STRING},
162
163   {10001, "sim/multiplay/transmission-freq-hz",  SGPropertyNode::STRING},
164   {10002, "sim/multiplay/chat",  SGPropertyNode::STRING},
165
166   {10100, "sim/multiplay/generic/string[0]", SGPropertyNode::STRING},
167   {10101, "sim/multiplay/generic/string[1]", SGPropertyNode::STRING},
168   {10102, "sim/multiplay/generic/string[2]", SGPropertyNode::STRING},
169   {10103, "sim/multiplay/generic/string[3]", SGPropertyNode::STRING},
170   {10104, "sim/multiplay/generic/string[4]", SGPropertyNode::STRING},
171   {10105, "sim/multiplay/generic/string[5]", SGPropertyNode::STRING},
172   {10106, "sim/multiplay/generic/string[6]", SGPropertyNode::STRING},
173   {10107, "sim/multiplay/generic/string[7]", SGPropertyNode::STRING},
174   {10108, "sim/multiplay/generic/string[8]", SGPropertyNode::STRING},
175   {10109, "sim/multiplay/generic/string[9]", SGPropertyNode::STRING},
176   {10110, "sim/multiplay/generic/string[10]", SGPropertyNode::STRING},
177   {10111, "sim/multiplay/generic/string[11]", SGPropertyNode::STRING},
178   {10112, "sim/multiplay/generic/string[12]", SGPropertyNode::STRING},
179   {10113, "sim/multiplay/generic/string[13]", SGPropertyNode::STRING},
180   {10114, "sim/multiplay/generic/string[14]", SGPropertyNode::STRING},
181   {10115, "sim/multiplay/generic/string[15]", SGPropertyNode::STRING},
182   {10116, "sim/multiplay/generic/string[16]", SGPropertyNode::STRING},
183   {10117, "sim/multiplay/generic/string[17]", SGPropertyNode::STRING},
184   {10118, "sim/multiplay/generic/string[18]", SGPropertyNode::STRING},
185   {10119, "sim/multiplay/generic/string[19]", SGPropertyNode::STRING},
186
187   {10200, "sim/multiplay/generic/float[0]", SGPropertyNode::FLOAT},
188   {10201, "sim/multiplay/generic/float[1]", SGPropertyNode::FLOAT},
189   {10202, "sim/multiplay/generic/float[2]", SGPropertyNode::FLOAT},
190   {10203, "sim/multiplay/generic/float[3]", SGPropertyNode::FLOAT},
191   {10204, "sim/multiplay/generic/float[4]", SGPropertyNode::FLOAT},
192   {10205, "sim/multiplay/generic/float[5]", SGPropertyNode::FLOAT},
193   {10206, "sim/multiplay/generic/float[6]", SGPropertyNode::FLOAT},
194   {10207, "sim/multiplay/generic/float[7]", SGPropertyNode::FLOAT},
195   {10208, "sim/multiplay/generic/float[8]", SGPropertyNode::FLOAT},
196   {10209, "sim/multiplay/generic/float[9]", SGPropertyNode::FLOAT},
197   {10210, "sim/multiplay/generic/float[10]", SGPropertyNode::FLOAT},
198   {10211, "sim/multiplay/generic/float[11]", SGPropertyNode::FLOAT},
199   {10212, "sim/multiplay/generic/float[12]", SGPropertyNode::FLOAT},
200   {10213, "sim/multiplay/generic/float[13]", SGPropertyNode::FLOAT},
201   {10214, "sim/multiplay/generic/float[14]", SGPropertyNode::FLOAT},
202   {10215, "sim/multiplay/generic/float[15]", SGPropertyNode::FLOAT},
203   {10216, "sim/multiplay/generic/float[16]", SGPropertyNode::FLOAT},
204   {10217, "sim/multiplay/generic/float[17]", SGPropertyNode::FLOAT},
205   {10218, "sim/multiplay/generic/float[18]", SGPropertyNode::FLOAT},
206   {10219, "sim/multiplay/generic/float[19]", SGPropertyNode::FLOAT},
207
208   {10300, "sim/multiplay/generic/int[0]", SGPropertyNode::INT},
209   {10301, "sim/multiplay/generic/int[1]", SGPropertyNode::INT},
210   {10302, "sim/multiplay/generic/int[2]", SGPropertyNode::INT},
211   {10303, "sim/multiplay/generic/int[3]", SGPropertyNode::INT},
212   {10304, "sim/multiplay/generic/int[4]", SGPropertyNode::INT},
213   {10305, "sim/multiplay/generic/int[5]", SGPropertyNode::INT},
214   {10306, "sim/multiplay/generic/int[6]", SGPropertyNode::INT},
215   {10307, "sim/multiplay/generic/int[7]", SGPropertyNode::INT},
216   {10308, "sim/multiplay/generic/int[8]", SGPropertyNode::INT},
217   {10309, "sim/multiplay/generic/int[9]", SGPropertyNode::INT},
218   {10310, "sim/multiplay/generic/int[10]", SGPropertyNode::INT},
219   {10311, "sim/multiplay/generic/int[11]", SGPropertyNode::INT},
220   {10312, "sim/multiplay/generic/int[12]", SGPropertyNode::INT},
221   {10313, "sim/multiplay/generic/int[13]", SGPropertyNode::INT},
222   {10314, "sim/multiplay/generic/int[14]", SGPropertyNode::INT},
223   {10315, "sim/multiplay/generic/int[15]", SGPropertyNode::INT},
224   {10316, "sim/multiplay/generic/int[16]", SGPropertyNode::INT},
225   {10317, "sim/multiplay/generic/int[17]", SGPropertyNode::INT},
226   {10318, "sim/multiplay/generic/int[18]", SGPropertyNode::INT},
227   {10319, "sim/multiplay/generic/int[19]", SGPropertyNode::INT},
228 };
229
230 const unsigned
231 FGMultiplayMgr::numProperties = (sizeof(FGMultiplayMgr::sIdPropertyList)
232                                  / sizeof(FGMultiplayMgr::sIdPropertyList[0]));
233
234 // Look up a property ID using binary search.
235 namespace
236 {
237   struct ComparePropertyId
238   {
239     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
240                     const FGMultiplayMgr::IdPropertyList& rhs)
241     {
242       return lhs.id < rhs.id;
243     }
244     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
245                     unsigned id)
246     {
247       return lhs.id < id;
248     }
249     bool operator()(unsigned id,
250                     const FGMultiplayMgr::IdPropertyList& rhs)
251     {
252       return id < rhs.id;
253     }
254   };
255     
256 }
257 const FGMultiplayMgr::IdPropertyList* FGMultiplayMgr::findProperty(unsigned id)
258 {
259   std::pair<const IdPropertyList*, const IdPropertyList*> result
260     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
261                        ComparePropertyId());
262   if (result.first == result.second) {
263     return 0;
264   } else {
265     return result.first;
266   }
267 }
268
269 namespace
270 {
271   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
272   {
273     const xdr_data_t* xdr = data;
274     while (xdr < end) {
275       unsigned id = XDR_decode_uint32(*xdr);
276       const FGMultiplayMgr::IdPropertyList* plist
277         = FGMultiplayMgr::findProperty(id);
278     
279       if (plist) {
280         xdr++;
281         // How we decode the remainder of the property depends on the type
282         switch (plist->type) {
283         case SGPropertyNode::INT:        
284         case SGPropertyNode::BOOL:
285         case SGPropertyNode::LONG:
286           xdr++;
287           break;
288         case SGPropertyNode::FLOAT:
289         case SGPropertyNode::DOUBLE:
290           {
291             float val = XDR_decode_float(*xdr);
292             if (osg::isNaN(val))
293               return false;
294             xdr++;
295             break;
296           }
297         case SGPropertyNode::STRING:
298         case SGPropertyNode::UNSPECIFIED:
299           {
300             // String is complicated. It consists of
301             // The length of the string
302             // The string itself
303             // Padding to the nearest 4-bytes.
304             // XXX Yes, each byte is padded out to a word! Too late
305             // to change...
306             uint32_t length = XDR_decode_uint32(*xdr);
307             xdr++;
308             // Old versions truncated the string but left the length
309             // unadjusted.
310             if (length > MAX_TEXT_SIZE)
311               length = MAX_TEXT_SIZE;
312             xdr += length;
313             // Now handle the padding
314             while ((length % 4) != 0)
315               {
316                 xdr++;
317                 length++;
318                 //cout << "0";
319               }
320           }
321           break;
322         default:
323           // cerr << "Unknown Prop type " << id << " " << type << "\n";
324           xdr++;
325           break;
326         }            
327       }
328       else {
329         // give up; this is a malformed property list.
330         return false;
331       }
332     }
333     return true;
334   }
335 }
336 //////////////////////////////////////////////////////////////////////
337 //
338 //  MultiplayMgr constructor
339 //
340 //////////////////////////////////////////////////////////////////////
341 FGMultiplayMgr::FGMultiplayMgr() 
342 {
343   mSocket        = 0;
344   mInitialised   = false;
345   mHaveServer    = false;
346 } // FGMultiplayMgr::FGMultiplayMgr()
347 //////////////////////////////////////////////////////////////////////
348
349 //////////////////////////////////////////////////////////////////////
350 //
351 //  MultiplayMgr destructor
352 //
353 //////////////////////////////////////////////////////////////////////
354 FGMultiplayMgr::~FGMultiplayMgr() 
355 {
356   Close();
357 } // FGMultiplayMgr::~FGMultiplayMgr()
358 //////////////////////////////////////////////////////////////////////
359
360 //////////////////////////////////////////////////////////////////////
361 //
362 //  Initialise object
363 //
364 //////////////////////////////////////////////////////////////////////
365 bool
366 FGMultiplayMgr::init (void) 
367 {
368   //////////////////////////////////////////////////
369   //  Initialise object if not already done
370   //////////////////////////////////////////////////
371   if (mInitialised) {
372     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
373     return false;
374   }
375   //////////////////////////////////////////////////
376   //  Set members from property values
377   //////////////////////////////////////////////////
378   short rxPort = fgGetInt("/sim/multiplay/rxport");
379   string rxAddress = fgGetString("/sim/multiplay/rxhost");
380   short txPort = fgGetInt("/sim/multiplay/txport");
381   string txAddress = fgGetString("/sim/multiplay/txhost");
382   mCallsign = fgGetString("/sim/multiplay/callsign");
383   if (txPort > 0 && !txAddress.empty()) {
384     mServer.set(txAddress.c_str(), txPort);
385     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
386       mHaveServer = false;
387       SG_LOG(SG_NETWORK, SG_ALERT,
388         "FGMultiplayMgr - could not resolve '"
389         << txAddress << "', Multiplayermode disabled");
390     } else {
391       mHaveServer = true;
392     }
393     if (rxPort <= 0)
394       rxPort = txPort;
395   }
396   if (rxPort <= 0) {
397     SG_LOG(SG_NETWORK, SG_ALERT,
398       "FGMultiplayMgr - No receiver port, Multiplayermode disabled");
399     return (false);
400   }
401   if (mCallsign.empty())
402     mCallsign = "JohnDoe"; // FIXME: use getpwuid
403   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
404   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
405   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
406   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
407   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
408   Close(); // Should Init be called twice, close Socket first
409            // A memory leak was reported here by valgrind
410   mSocket = new netSocket();
411   if (!mSocket->open(false)) {
412     SG_LOG( SG_NETWORK, SG_ALERT,
413             "FGMultiplayMgr::init - Failed to create data socket" );
414     return false;
415   }
416   mSocket->setBlocking(false);
417   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
418     perror("bind");
419     SG_LOG( SG_NETWORK, SG_ALERT,
420             "FGMultiplayMgr::Open - Failed to bind receive socket" );
421     return false;
422   }
423   mInitialised = true;
424   return true;
425 } // FGMultiplayMgr::init()
426 //////////////////////////////////////////////////////////////////////
427
428 //////////////////////////////////////////////////////////////////////
429 //
430 //  Closes and deletes the local player object. Closes
431 //  and deletes the tx socket. Resets the object state to unitialised.
432 //
433 //////////////////////////////////////////////////////////////////////
434 void
435 FGMultiplayMgr::Close (void) 
436 {
437   mMultiPlayerMap.clear();
438
439   if (mSocket) {
440     mSocket->close();
441     delete mSocket;
442     mSocket = 0;
443   }
444   mInitialised = false;
445 } // FGMultiplayMgr::Close(void)
446 //////////////////////////////////////////////////////////////////////
447
448 //////////////////////////////////////////////////////////////////////
449 //
450 //  Description: Sends the position data for the local position.
451 //
452 //////////////////////////////////////////////////////////////////////
453
454 /**
455  * The buffer that holds a multi-player message, suitably aligned.
456  */
457 union FGMultiplayMgr::MsgBuf
458 {
459     MsgBuf()
460     {
461         memset(&Msg, 0, sizeof(Msg));
462     }
463
464     T_MsgHdr* msgHdr()
465     {
466         return reinterpret_cast<T_MsgHdr*>(Msg);
467     }
468
469     const T_MsgHdr* msgHdr() const
470     {
471         return reinterpret_cast<const T_MsgHdr*>(Msg);
472     }
473
474     T_PositionMsg* posMsg()
475     {
476         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
477     }
478
479     const T_PositionMsg* posMsg() const
480     {
481         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
482     }
483
484     xdr_data_t* properties()
485     {
486         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
487                                              + sizeof(T_PositionMsg));
488     }
489
490     const xdr_data_t* properties() const
491     {
492         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
493                                                    + sizeof(T_PositionMsg));
494     }
495     /**
496      * The end of the properties buffer.
497      */
498     xdr_data_t* propsEnd()
499     {
500         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
501     };
502
503     const xdr_data_t* propsEnd() const
504     {
505         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
506     };
507     /**
508      * The end of properties actually in the buffer. This assumes that
509      * the message header is valid.
510      */
511     xdr_data_t* propsRecvdEnd()
512     {
513         return reinterpret_cast<xdr_data_t*>(Msg + msgHdr()->MsgLen);
514     }
515
516     const xdr_data_t* propsRecvdEnd() const
517     {
518         return reinterpret_cast<const xdr_data_t*>(Msg + msgHdr()->MsgLen);
519     }
520     
521     xdr_data2_t double_val;
522     char Msg[MAX_PACKET_SIZE];
523 };
524
525 void
526 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
527 {
528   if ((! mInitialised) || (! mHaveServer))
529         return;
530   if (! mHaveServer) {
531     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - no server");
532     return;
533   }
534
535   MsgBuf msgBuf;
536   T_PositionMsg* PosMsg = msgBuf.posMsg();
537
538   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
539   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
540   
541   PosMsg->time = XDR_encode_double (motionInfo.time);
542   PosMsg->lag = XDR_encode_double (motionInfo.lag);
543   for (unsigned i = 0 ; i < 3; ++i)
544     PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
545   SGVec3f angleAxis;
546   motionInfo.orientation.getAngleAxis(angleAxis);
547   for (unsigned i = 0 ; i < 3; ++i)
548     PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
549   for (unsigned i = 0 ; i < 3; ++i)
550     PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
551   for (unsigned i = 0 ; i < 3; ++i)
552     PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
553   for (unsigned i = 0 ; i < 3; ++i)
554     PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
555   for (unsigned i = 0 ; i < 3; ++i)
556     PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
557   
558   xdr_data_t* ptr = msgBuf.properties();
559   std::vector<FGPropertyData*>::const_iterator it;
560   it = motionInfo.properties.begin();
561   //cout << "OUTPUT PROPERTIES\n";
562   xdr_data_t* msgEnd = msgBuf.propsEnd();
563   while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
564     
565     // First element is the ID. Write it out when we know we have room for
566     // the whole property.
567     xdr_data_t id =  XDR_encode_uint32((*it)->id);
568     // The actual data representation depends on the type
569     switch ((*it)->type) {
570       case SGPropertyNode::INT:        
571       case SGPropertyNode::BOOL:        
572       case SGPropertyNode::LONG:
573         *ptr++ = id;
574         *ptr++ = XDR_encode_uint32((*it)->int_value);
575         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
576         break;
577       case SGPropertyNode::FLOAT:
578       case SGPropertyNode::DOUBLE:
579         *ptr++ = id;
580         *ptr++ = XDR_encode_float((*it)->float_value);
581         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
582         break;
583       case SGPropertyNode::STRING:
584       case SGPropertyNode::UNSPECIFIED:
585         {
586           // String is complicated. It consists of
587           // The length of the string
588           // The string itself
589           // Padding to the nearest 4-bytes.        
590           const char* lcharptr = (*it)->string_value;
591           
592           if (lcharptr != 0)
593           {
594             // Add the length         
595             ////cout << "String length: " << strlen(lcharptr) << "\n";
596             uint32_t len = strlen(lcharptr);
597             if (len > MAX_TEXT_SIZE)
598               len = MAX_TEXT_SIZE;
599             // XXX This should not be using 4 bytes per character!
600             // If there's not enough room for this property, drop it
601             // on the floor.
602             if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
603                 goto escape;
604             //cout << "String length unint32: " << len << "\n";
605             *ptr++ = id;
606             *ptr++ = XDR_encode_uint32(len);
607             if (len != 0)
608             {
609               // Now the text itself
610               // XXX This should not be using 4 bytes per character!
611               int lcount = 0;
612               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
613               {
614                 *ptr++ = XDR_encode_int8(*lcharptr);
615                 lcharptr++;
616                 lcount++;          
617               }
618
619               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
620
621               // Now pad if required
622               while ((lcount % 4) != 0)
623               {
624                 *ptr++ = XDR_encode_int8(0);
625                 lcount++;          
626                 //cout << "0";
627               }
628               
629               //cout << "\n";
630             }
631           }
632           else
633           {
634             // Nothing to encode
635             *ptr++ = id;
636             *ptr++ = XDR_encode_uint32(0);
637             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
638           }
639         }
640         break;
641         
642       default:
643         //cout << " Unknown Type: " << (*it)->type << "\n";
644         *ptr++ = id;
645         *ptr++ = XDR_encode_float((*it)->float_value);;
646         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
647         break;
648     }
649         
650     ++it;
651   }
652 escape:
653   unsigned msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
654   FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
655   mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
656   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
657 } // FGMultiplayMgr::SendMyPosition()
658
659 //////////////////////////////////////////////////////////////////////
660
661 //////////////////////////////////////////////////////////////////////
662 //
663 //  Name: SendTextMessage
664 //  Description: Sends a message to the player. The message must
665 //  contain a valid and correctly filled out header and optional
666 //  message body.
667 //
668 //////////////////////////////////////////////////////////////////////
669 void
670 FGMultiplayMgr::SendTextMessage(const string &MsgText)
671 {
672   if (!mInitialised || !mHaveServer)
673     return;
674
675   T_MsgHdr MsgHdr;
676   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
677   //////////////////////////////////////////////////
678   // Divide the text string into blocks that fit
679   // in the message and send the blocks.
680   //////////////////////////////////////////////////
681   unsigned iNextBlockPosition = 0;
682   T_ChatMsg ChatMsg;
683   
684   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
685   while (iNextBlockPosition < MsgText.length()) {
686     strncpy (ChatMsg.Text, 
687              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
688              MAX_CHAT_MSG_LEN);
689     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
690     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
691     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
692     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
693     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
694
695   }
696   
697   
698 } // FGMultiplayMgr::SendTextMessage ()
699 //////////////////////////////////////////////////////////////////////
700
701 //////////////////////////////////////////////////////////////////////
702 //
703 //  Name: ProcessData
704 //  Description: Processes data waiting at the receive socket. The
705 //  processing ends when there is no more data at the socket.
706 //  
707 //////////////////////////////////////////////////////////////////////
708 void
709 FGMultiplayMgr::Update(void) 
710 {
711   if (!mInitialised)
712     return;
713
714   /// Just for expiry
715   long stamp = SGTimeStamp::now().getSeconds();
716
717   //////////////////////////////////////////////////
718   //  Read the receive socket and process any data
719   //////////////////////////////////////////////////
720   int bytes;
721   do {
722     MsgBuf msgBuf;
723     //////////////////////////////////////////////////
724     //  Although the recv call asks for 
725     //  MAX_PACKET_SIZE of data, the number of bytes
726     //  returned will only be that of the next
727     //  packet waiting to be processed.
728     //////////////////////////////////////////////////
729     netAddress SenderAddress;
730     bytes = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
731                               &SenderAddress);
732     //////////////////////////////////////////////////
733     //  no Data received
734     //////////////////////////////////////////////////
735     if (bytes <= 0) {
736       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
737         perror("FGMultiplayMgr::MP_ProcessData");
738       break;
739     }
740     if (bytes <= sizeof(T_MsgHdr)) {
741       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
742               << "received message with insufficient data" );
743       break;
744     }
745     //////////////////////////////////////////////////
746     //  Read header
747     //////////////////////////////////////////////////
748     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
749     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
750     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
751     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
752     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
753     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
754     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
755     if (MsgHdr->Magic != MSG_MAGIC) {
756       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
757               << "message has invalid magic number!" );
758       break;
759     }
760     if (MsgHdr->Version != PROTO_VER) {
761       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
762               << "message has invalid protocoll number!" );
763       break;
764     }
765     if (MsgHdr->MsgLen != bytes) {
766       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
767              << "message from " << MsgHdr->Callsign << " has invalid length!");
768       break;
769     }
770     //////////////////////////////////////////////////
771     //  Process messages
772     //////////////////////////////////////////////////
773     switch (MsgHdr->MsgId) {
774     case CHAT_MSG_ID:
775       ProcessChatMsg(msgBuf, SenderAddress);
776       break;
777     case POS_DATA_ID:
778       ProcessPosMsg(msgBuf, SenderAddress, stamp);
779       break;
780     case UNUSABLE_POS_DATA_ID:
781     case OLD_OLD_POS_DATA_ID:
782     case OLD_PROP_MSG_ID:
783     case OLD_POS_DATA_ID:
784       break;
785     default:
786       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
787               << "Unknown message Id received: " << MsgHdr->MsgId );
788       break;
789     }
790   } while (bytes > 0);
791
792   // check for expiry
793   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
794   while (it != mMultiPlayerMap.end()) {
795     if (it->second->getLastTimestamp() + 10 < stamp) {
796       std::string name = it->first;
797       it->second->setDie(true);
798       mMultiPlayerMap.erase(it);
799       it = mMultiPlayerMap.upper_bound(name);
800     } else
801       ++it;
802   }
803 } // FGMultiplayMgr::ProcessData(void)
804 //////////////////////////////////////////////////////////////////////
805
806 //////////////////////////////////////////////////////////////////////
807 //
808 //  handle a position message
809 //
810 //////////////////////////////////////////////////////////////////////
811 void
812 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
813                               const netAddress& SenderAddress, long stamp)
814 {
815   const T_MsgHdr* MsgHdr = Msg.msgHdr();
816   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
817     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
818             << "Position message received with insufficient data" );
819     return;
820   }
821   const T_PositionMsg* PosMsg = Msg.posMsg();
822   FGExternalMotionData motionInfo;
823   motionInfo.time = XDR_decode_double(PosMsg->time);
824   motionInfo.lag = XDR_decode_double(PosMsg->lag);
825   for (unsigned i = 0; i < 3; ++i)
826     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
827   SGVec3f angleAxis;
828   for (unsigned i = 0; i < 3; ++i)
829     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
830   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
831   for (unsigned i = 0; i < 3; ++i)
832     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
833   for (unsigned i = 0; i < 3; ++i)
834     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
835   for (unsigned i = 0; i < 3; ++i)
836     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
837   for (unsigned i = 0; i < 3; ++i)
838     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
839
840
841   //cout << "INPUT MESSAGE\n";
842
843   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
844   // on 32 bit architectures and 200 bytes on 64 bit, and this
845   // structure is put directly on the wire. By looking at the padding,
846   // we can sort through the mess, mostly:
847   // If padding is 0 (which is not a valid property type), then the
848   // message was produced by a new client or an old 64 bit client that
849   // happened to have 0 on the stack;
850   // Else if the property list starting with the padding word is
851   // well-formed, then the client is probably an old 32 bit client and
852   // we'll go with that;
853   // Else it is an old 64-bit client and properties start after the
854   // padding.
855   // There is a chance that we could be fooled by garbage in the
856   // padding looking like a valid property, so verifyProperties() is
857   // strict about the validity of the property values.
858   const xdr_data_t* xdr = Msg.properties();
859   if (PosMsg->pad != 0) {
860     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
861       xdr = &PosMsg->pad;
862     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
863       goto noprops;
864   }
865   while (xdr < Msg.propsRecvdEnd()) {
866     FGPropertyData* pData = new FGPropertyData;
867     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
868     
869     // First element is always the ID
870     pData->id = XDR_decode_uint32(*xdr);
871     //cout << pData->id << " ";
872     xdr++;
873     
874     // Check the ID actually exists and get the type
875     const IdPropertyList* plist = findProperty(pData->id);
876     
877     if (plist)
878     {
879       pData->type = plist->type;
880       // How we decode the remainder of the property depends on the type
881       switch (pData->type) {
882         case SGPropertyNode::INT:        
883         case SGPropertyNode::BOOL:
884         case SGPropertyNode::LONG:        
885           pData->int_value = XDR_decode_uint32(*xdr);
886           xdr++;
887           //cout << pData->int_value << "\n";
888           break;
889         case SGPropertyNode::FLOAT:
890         case SGPropertyNode::DOUBLE:
891           pData->float_value = XDR_decode_float(*xdr);
892           xdr++;
893           //cout << pData->float_value << "\n";
894           break;
895         case SGPropertyNode::STRING:
896         case SGPropertyNode::UNSPECIFIED:
897           {
898             // String is complicated. It consists of
899             // The length of the string
900             // The string itself
901             // Padding to the nearest 4-bytes.    
902             uint32_t length = XDR_decode_uint32(*xdr);
903             xdr++;
904             //cout << length << " ";
905             // Old versions truncated the string but left the length unadjusted.
906             if (length > MAX_TEXT_SIZE)
907               length = MAX_TEXT_SIZE;
908             pData->string_value = new char[length + 1];
909             //cout << " String: ";
910             for (int i = 0; i < length; i++)
911               {
912                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
913                 xdr++;
914                 //cout << pData->string_value[i];
915               }
916
917             pData->string_value[length] = '\0';
918
919             // Now handle the padding
920             while ((length % 4) != 0)
921               {
922                 xdr++;
923                 length++;
924                 //cout << "0";
925               }
926             //cout << "\n";
927           }
928           break;
929
930         default:
931           pData->float_value = XDR_decode_float(*xdr);
932           SG_LOG(SG_NETWORK, SG_ALERT, "Unknown Prop type " << pData->id << " " << pData->type);
933           xdr++;
934           break;
935       }            
936
937       motionInfo.properties.push_back(pData);
938     }
939     else
940     {
941       // We failed to find the property. We'll try the next packet immediately.
942       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr::ProcessPosMsg - "
943              "message from " << MsgHdr->Callsign << " has unknown property id "
944              << pData->id); 
945     }
946   }
947  noprops:
948   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
949   if (!mp)
950     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
951   mp->addMotionInfo(motionInfo, stamp);
952 } // FGMultiplayMgr::ProcessPosMsg()
953 //////////////////////////////////////////////////////////////////////
954
955 //////////////////////////////////////////////////////////////////////
956 //
957 //  handle a chat message
958 //  FIXME: display chat message withi flightgear
959 //
960 //////////////////////////////////////////////////////////////////////
961 void
962 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
963                                const netAddress& SenderAddress)
964 {
965   const T_MsgHdr* MsgHdr = Msg.msgHdr();
966   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
967     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
968             << "Chat message received with insufficient data" );
969     return;
970   }
971   
972   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
973   strncpy(chatStr,
974           (reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr)))
975           ->Text,
976           MsgHdr->MsgLen - sizeof(T_MsgHdr));
977   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
978   
979   const T_ChatMsg* ChatMsg
980       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
981   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
982            << " " << chatStr);
983
984   delete [] chatStr;
985 } // FGMultiplayMgr::ProcessChatMsg ()
986 //////////////////////////////////////////////////////////////////////
987
988 void
989 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
990 {
991   uint32_t len;
992   switch (MsgId) {
993   case CHAT_MSG_ID:
994     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
995     break;
996   case POS_DATA_ID:
997     len = _len;
998     break;
999   default:
1000     len = sizeof(T_MsgHdr);
1001     break;
1002   }
1003   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1004   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1005   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1006   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1007   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1008   MsgHdr->ReplyPort       = 0; // now
1009   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1010   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1011 }
1012
1013 FGAIMultiplayer*
1014 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1015                                const std::string& modelName)
1016 {
1017   if (0 < mMultiPlayerMap.count(callsign))
1018     return mMultiPlayerMap[callsign].get();
1019
1020   FGAIMultiplayer* mp = new FGAIMultiplayer;
1021   mp->setPath(modelName.c_str());
1022   mp->setCallSign(callsign);
1023   mMultiPlayerMap[callsign] = mp;
1024
1025   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
1026   if (aiMgr) {
1027     aiMgr->attach(mp);
1028
1029     /// FIXME: that must follow the attach ATM ...
1030     for (unsigned i = 0; i < numProperties; ++i)
1031       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1032   }
1033
1034   return mp;
1035 }
1036
1037 FGAIMultiplayer*
1038 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1039 {
1040   if (0 < mMultiPlayerMap.count(callsign))
1041     return mMultiPlayerMap[callsign].get();
1042   else
1043     return 0;
1044 }