]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Check for valid multiplayer packet.
[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 <plib/netSocket.h>
35
36 #include <simgear/misc/stdint.hxx>
37 #include <simgear/timing/timestamp.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/props/props.hxx>
40
41 #include <AIModel/AIManager.hxx>
42 #include <Main/fg_props.hxx>
43 #include "multiplaymgr.hxx"
44 #include "mpmessages.hxx"
45
46 #define MAX_PACKET_SIZE 1200
47 #define MAX_TEXT_SIZE 128
48
49 // These constants are provided so that the ident 
50 // command can list file versions
51 const char sMULTIPLAYMGR_BID[] = "$Id$";
52 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
53
54 // A static map of protocol property id values to property paths,
55 // This should be extendable dynamically for every specific aircraft ...
56 // For now only that static list
57 FGMultiplayMgr::IdPropertyList
58 FGMultiplayMgr::sIdPropertyList[] = {
59   {100, "surface-positions/left-aileron-pos-norm",  SGPropertyNode::FLOAT},
60   {101, "surface-positions/right-aileron-pos-norm", SGPropertyNode::FLOAT},
61   {102, "surface-positions/elevator-pos-norm",      SGPropertyNode::FLOAT},
62   {103, "surface-positions/rudder-pos-norm",        SGPropertyNode::FLOAT},
63   {104, "surface-positions/flap-pos-norm",          SGPropertyNode::FLOAT},
64   {105, "surface-positions/speedbrake-pos-norm",    SGPropertyNode::FLOAT},
65   {106, "gear/tailhook/position-norm",              SGPropertyNode::FLOAT},
66   {107, "gear/launchbar/position-norm",             SGPropertyNode::FLOAT},
67   {108, "gear/launchbar/state",                     SGPropertyNode::STRING},
68   {109, "gear/launchbar/holdback-position-norm",    SGPropertyNode::FLOAT},
69   {110, "canopy/position-norm",                     SGPropertyNode::FLOAT},
70
71   {200, "gear/gear[0]/compression-norm",           SGPropertyNode::FLOAT},
72   {201, "gear/gear[0]/position-norm",              SGPropertyNode::FLOAT},
73   {210, "gear/gear[1]/compression-norm",           SGPropertyNode::FLOAT},
74   {211, "gear/gear[1]/position-norm",              SGPropertyNode::FLOAT},
75   {220, "gear/gear[2]/compression-norm",           SGPropertyNode::FLOAT},
76   {221, "gear/gear[2]/position-norm",              SGPropertyNode::FLOAT},
77   {230, "gear/gear[3]/compression-norm",           SGPropertyNode::FLOAT},
78   {231, "gear/gear[3]/position-norm",              SGPropertyNode::FLOAT},
79   {240, "gear/gear[4]/compression-norm",           SGPropertyNode::FLOAT},
80   {241, "gear/gear[4]/position-norm",              SGPropertyNode::FLOAT},
81
82   {300, "engines/engine[0]/n1",  SGPropertyNode::FLOAT},
83   {301, "engines/engine[0]/n2",  SGPropertyNode::FLOAT},
84   {302, "engines/engine[0]/rpm", SGPropertyNode::FLOAT},
85   {310, "engines/engine[1]/n1",  SGPropertyNode::FLOAT},
86   {311, "engines/engine[1]/n2",  SGPropertyNode::FLOAT},
87   {312, "engines/engine[1]/rpm", SGPropertyNode::FLOAT},
88   {320, "engines/engine[2]/n1",  SGPropertyNode::FLOAT},
89   {321, "engines/engine[2]/n2",  SGPropertyNode::FLOAT},
90   {322, "engines/engine[2]/rpm", SGPropertyNode::FLOAT},
91   {330, "engines/engine[3]/n1",  SGPropertyNode::FLOAT},
92   {331, "engines/engine[3]/n2",  SGPropertyNode::FLOAT},
93   {332, "engines/engine[3]/rpm", SGPropertyNode::FLOAT},
94   {340, "engines/engine[4]/n1",  SGPropertyNode::FLOAT},
95   {341, "engines/engine[4]/n2",  SGPropertyNode::FLOAT},
96   {342, "engines/engine[4]/rpm", SGPropertyNode::FLOAT},
97   {350, "engines/engine[5]/n1",  SGPropertyNode::FLOAT},
98   {351, "engines/engine[5]/n2",  SGPropertyNode::FLOAT},
99   {352, "engines/engine[5]/rpm", SGPropertyNode::FLOAT},
100   {360, "engines/engine[6]/n1",  SGPropertyNode::FLOAT},
101   {361, "engines/engine[6]/n2",  SGPropertyNode::FLOAT},
102   {362, "engines/engine[6]/rpm", SGPropertyNode::FLOAT},
103   {370, "engines/engine[7]/n1",  SGPropertyNode::FLOAT},
104   {371, "engines/engine[7]/n2",  SGPropertyNode::FLOAT},
105   {372, "engines/engine[7]/rpm", SGPropertyNode::FLOAT},
106   {380, "engines/engine[8]/n1",  SGPropertyNode::FLOAT},
107   {381, "engines/engine[8]/n2",  SGPropertyNode::FLOAT},
108   {382, "engines/engine[8]/rpm", SGPropertyNode::FLOAT},
109   {390, "engines/engine[9]/n1",  SGPropertyNode::FLOAT},
110   {391, "engines/engine[9]/n2",  SGPropertyNode::FLOAT},
111   {392, "engines/engine[9]/rpm", SGPropertyNode::FLOAT},
112
113   {800, "rotors/main/rpm", SGPropertyNode::FLOAT},
114   {801, "rotors/tail/rpm", SGPropertyNode::FLOAT},
115   {810, "rotors/main/blade[0]/position-deg",  SGPropertyNode::FLOAT},
116   {811, "rotors/main/blade[1]/position-deg",  SGPropertyNode::FLOAT},
117   {812, "rotors/main/blade[2]/position-deg",  SGPropertyNode::FLOAT},
118   {813, "rotors/main/blade[3]/position-deg",  SGPropertyNode::FLOAT},
119   {820, "rotors/main/blade[0]/flap-deg",  SGPropertyNode::FLOAT},
120   {821, "rotors/main/blade[1]/flap-deg",  SGPropertyNode::FLOAT},
121   {822, "rotors/main/blade[2]/flap-deg",  SGPropertyNode::FLOAT},
122   {823, "rotors/main/blade[3]/flap-deg",  SGPropertyNode::FLOAT},
123   {830, "rotors/tail/blade[0]/position-deg",  SGPropertyNode::FLOAT},
124   {831, "rotors/tail/blade[1]/position-deg",  SGPropertyNode::FLOAT},
125
126   {900, "sim/hitches/aerotow/tow/length",                       SGPropertyNode::FLOAT},
127   {901, "sim/hitches/aerotow/tow/elastic-constant",             SGPropertyNode::FLOAT},
128   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            SGPropertyNode::FLOAT},
129   {903, "sim/hitches/aerotow/tow/dist",                         SGPropertyNode::FLOAT},
130   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   SGPropertyNode::BOOL},
131   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   SGPropertyNode::STRING},
132   {906, "sim/hitches/aerotow/tow/brake-force",                  SGPropertyNode::FLOAT},
133   {907, "sim/hitches/aerotow/tow/end-force-x",                  SGPropertyNode::FLOAT},
134   {908, "sim/hitches/aerotow/tow/end-force-y",                  SGPropertyNode::FLOAT},
135   {909, "sim/hitches/aerotow/tow/end-force-z",                  SGPropertyNode::FLOAT},
136   {930, "sim/hitches/aerotow/is-slave",                         SGPropertyNode::BOOL},
137   {931, "sim/hitches/aerotow/speed-in-tow-direction",           SGPropertyNode::FLOAT},
138   {932, "sim/hitches/aerotow/open",                             SGPropertyNode::BOOL},
139   {933, "sim/hitches/aerotow/local-pos-x",                      SGPropertyNode::FLOAT},
140   {934, "sim/hitches/aerotow/local-pos-y",                      SGPropertyNode::FLOAT},
141   {935, "sim/hitches/aerotow/local-pos-z",                      SGPropertyNode::FLOAT},
142
143   {1001, "controls/flight/slats",  SGPropertyNode::FLOAT},
144   {1002, "controls/flight/speedbrake",  SGPropertyNode::FLOAT},
145   {1003, "controls/flight/spoilers",  SGPropertyNode::FLOAT},
146   {1004, "controls/gear/gear-down",  SGPropertyNode::FLOAT},
147   {1005, "controls/lighting/nav-lights",  SGPropertyNode::FLOAT},
148   {1006, "controls/armament/station[0]/jettison-all",  SGPropertyNode::BOOL},
149
150   {1100, "sim/model/variant", SGPropertyNode::INT},
151
152   {10001, "sim/multiplay/transmission-freq-hz",  SGPropertyNode::STRING},
153   {10002, "sim/multiplay/chat",  SGPropertyNode::STRING},
154
155   /// termination
156   {0, 0, SGPropertyNode::UNSPECIFIED}
157 };
158
159 //////////////////////////////////////////////////////////////////////
160 //
161 //  MultiplayMgr constructor
162 //
163 //////////////////////////////////////////////////////////////////////
164 FGMultiplayMgr::FGMultiplayMgr() 
165 {
166   mSocket        = 0;
167   mInitialised   = false;
168   mHaveServer    = false;
169 } // FGMultiplayMgr::FGMultiplayMgr()
170 //////////////////////////////////////////////////////////////////////
171
172 //////////////////////////////////////////////////////////////////////
173 //
174 //  MultiplayMgr destructor
175 //
176 //////////////////////////////////////////////////////////////////////
177 FGMultiplayMgr::~FGMultiplayMgr() 
178 {
179   Close();
180 } // FGMultiplayMgr::~FGMultiplayMgr()
181 //////////////////////////////////////////////////////////////////////
182
183 //////////////////////////////////////////////////////////////////////
184 //
185 //  Initialise object
186 //
187 //////////////////////////////////////////////////////////////////////
188 bool
189 FGMultiplayMgr::init (void) 
190 {
191   //////////////////////////////////////////////////
192   //  Initialise object if not already done
193   //////////////////////////////////////////////////
194   if (mInitialised) {
195     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
196     return false;
197   }
198   //////////////////////////////////////////////////
199   //  Set members from property values
200   //////////////////////////////////////////////////
201   short rxPort = fgGetInt("/sim/multiplay/rxport");
202   if (rxPort <= 0)
203     rxPort = 5000;
204   mCallsign = fgGetString("/sim/multiplay/callsign");
205   if (mCallsign.empty())
206     // FIXME: use getpwuid
207     mCallsign = "JohnDoe"; 
208   string rxAddress = fgGetString("/sim/multiplay/rxhost");
209   if (rxAddress.empty())
210     rxAddress = "127.0.0.1";
211   short txPort = fgGetInt("/sim/multiplay/txport");
212   string txAddress = fgGetString("/sim/multiplay/txhost");
213   if (txPort > 0 && !txAddress.empty()) {
214     mHaveServer = true;
215     mServer.set(txAddress.c_str(), txPort);
216   }
217   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
218   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
219   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
220   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
221   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
222   Close(); // Should Init be called twice, close Socket first
223            // A memory leak was reported here by valgrind
224   mSocket = new netSocket();
225   if (!mSocket->open(false)) {
226     SG_LOG( SG_NETWORK, SG_ALERT,
227             "FGMultiplayMgr::init - Failed to create data socket" );
228     return false;
229   }
230   mSocket->setBlocking(false);
231   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
232     perror("bind");
233     SG_LOG( SG_NETWORK, SG_ALERT,
234             "FGMultiplayMgr::Open - Failed to bind receive socket" );
235     return false;
236   }
237   mInitialised = true;
238   return true;
239 } // FGMultiplayMgr::init()
240 //////////////////////////////////////////////////////////////////////
241
242 //////////////////////////////////////////////////////////////////////
243 //
244 //  Closes and deletes the local player object. Closes
245 //  and deletes the tx socket. Resets the object state to unitialised.
246 //
247 //////////////////////////////////////////////////////////////////////
248 void
249 FGMultiplayMgr::Close (void) 
250 {
251   mMultiPlayerMap.clear();
252
253   if (mSocket) {
254     mSocket->close();
255     delete mSocket;
256     mSocket = 0;
257   }
258   mInitialised = false;
259 } // FGMultiplayMgr::Close(void)
260 //////////////////////////////////////////////////////////////////////
261
262 //////////////////////////////////////////////////////////////////////
263 //
264 //  Description: Sends the position data for the local position.
265 //
266 //////////////////////////////////////////////////////////////////////
267 void
268 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
269 {
270   if ((! mInitialised) || (! mHaveServer)) {
271     if (! mInitialised)
272       SG_LOG( SG_NETWORK, SG_ALERT,
273               "FGMultiplayMgr::SendMyPosition - not initialised" );
274     if (! mHaveServer)
275       SG_LOG( SG_NETWORK, SG_ALERT,
276               "FGMultiplayMgr::SendMyPosition - no server" );
277     return;
278   }
279
280   T_PositionMsg PosMsg;
281   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
282   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
283   
284   PosMsg.time = XDR_encode_double (motionInfo.time);
285   PosMsg.lag = XDR_encode_double (motionInfo.lag);
286   for (unsigned i = 0 ; i < 3; ++i)
287     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
288   SGVec3f angleAxis;
289   motionInfo.orientation.getAngleAxis(angleAxis);
290   for (unsigned i = 0 ; i < 3; ++i)
291     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
292   for (unsigned i = 0 ; i < 3; ++i)
293     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
294   for (unsigned i = 0 ; i < 3; ++i)
295     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
296   for (unsigned i = 0 ; i < 3; ++i)
297     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
298   for (unsigned i = 0 ; i < 3; ++i)
299     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
300
301   char Msg[MAX_PACKET_SIZE];
302   memcpy(Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
303   
304   char* ptr = Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg);
305   std::vector<FGPropertyData*>::const_iterator it;
306   it = motionInfo.properties.begin();
307   //cout << "OUTPUT PROPERTIES\n";
308   while (it != motionInfo.properties.end()
309          && ptr + 2 * sizeof(xdr_data_t) < (Msg + MAX_PACKET_SIZE)) {
310              
311     // First elements is the ID
312     xdr_data_t xdr = XDR_encode_uint32((*it)->id);
313     memcpy(ptr, &xdr, sizeof(xdr_data_t));
314     ptr += sizeof(xdr_data_t);
315     
316     // The actual data representation depends on the type
317     switch ((*it)->type) {
318       case SGPropertyNode::INT:        
319       case SGPropertyNode::BOOL:        
320       case SGPropertyNode::LONG:        
321         xdr = XDR_encode_uint32((*it)->int_value);
322         memcpy(ptr, &xdr, sizeof(xdr_data_t));
323         ptr += sizeof(xdr_data_t);
324         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
325         break;
326       case SGPropertyNode::FLOAT:
327       case SGPropertyNode::DOUBLE:
328         xdr = XDR_encode_float((*it)->float_value);;
329         memcpy(ptr, &xdr, sizeof(xdr_data_t));
330         ptr += sizeof(xdr_data_t);
331         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
332         break;
333       case SGPropertyNode::STRING:
334       case SGPropertyNode::UNSPECIFIED:
335         {
336           // String is complicated. It consists of
337           // The length of the string
338           // The string itself
339           // Padding to the nearest 4-bytes.        
340           const char* lcharptr = (*it)->string_value;
341           
342           if (lcharptr != 0)
343           {
344             // Add the length         
345             ////cout << "String length: " << strlen(lcharptr) << "\n";
346             uint32_t len = strlen(lcharptr);
347             // XXX This should not be using 4 bytes per character!
348             if (ptr + (1 + len + (4 - len % 4)) * sizeof (xdr_data_t)
349                 >= (Msg + MAX_PACKET_SIZE))
350                 goto escape;
351             //cout << "String length unint32: " << len << "\n";
352             xdr = XDR_encode_uint32(len);
353             memcpy(ptr, &xdr, sizeof(xdr_data_t));
354             ptr += sizeof(xdr_data_t);
355             
356             if (len != 0)
357             {
358
359               // Now the text itself
360               // XXX This should not be using 4 bytes per character!
361               int lcount = 0;
362               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
363               {
364                 xdr = XDR_encode_int8(*lcharptr);
365                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
366                 ptr += sizeof(xdr_data_t);
367                 lcharptr++;
368                 lcount++;          
369               }
370
371               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
372
373               // Now pad if required
374               while ((lcount % 4) != 0)
375               {
376                 xdr = XDR_encode_int8(0);
377                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
378                 ptr += sizeof(xdr_data_t);
379                 lcount++;          
380                 //cout << "0";
381               }
382               
383               //cout << "\n";
384             }
385           }
386           else
387           {
388             // Nothing to encode
389             xdr = XDR_encode_uint32(0);
390             memcpy(ptr, &xdr, sizeof(xdr_data_t));
391             ptr += sizeof(xdr_data_t);
392             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
393           }
394            
395         }
396         break;
397         
398       default:
399         //cout << " Unknown Type: " << (*it)->type << "\n";
400         xdr = XDR_encode_float((*it)->float_value);;
401         memcpy(ptr, &xdr, sizeof(xdr_data_t));
402         ptr += sizeof(xdr_data_t);
403         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
404         break;
405     }
406         
407     ++it;
408   }
409 escape:
410   
411   T_MsgHdr MsgHdr;
412   FillMsgHdr(&MsgHdr, POS_DATA_ID, ptr - Msg);
413   memcpy(Msg, &MsgHdr, sizeof(T_MsgHdr));
414
415   mSocket->sendto(Msg, ptr - Msg, 0, &mServer);
416   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
417 } // FGMultiplayMgr::SendMyPosition()
418 //////////////////////////////////////////////////////////////////////
419
420 //////////////////////////////////////////////////////////////////////
421 //
422 //  Name: SendTextMessage
423 //  Description: Sends a message to the player. The message must
424 //  contain a valid and correctly filled out header and optional
425 //  message body.
426 //
427 //////////////////////////////////////////////////////////////////////
428 void
429 FGMultiplayMgr::SendTextMessage(const string &MsgText)
430 {
431   if (!mInitialised || !mHaveServer)
432     return;
433
434   T_MsgHdr MsgHdr;
435   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
436   //////////////////////////////////////////////////
437   // Divide the text string into blocks that fit
438   // in the message and send the blocks.
439   //////////////////////////////////////////////////
440   unsigned iNextBlockPosition = 0;
441   T_ChatMsg ChatMsg;
442   
443   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
444   while (iNextBlockPosition < MsgText.length()) {
445     strncpy (ChatMsg.Text, 
446              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
447              MAX_CHAT_MSG_LEN);
448     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
449     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
450     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
451     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
452     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
453
454   }
455   
456   
457 } // FGMultiplayMgr::SendTextMessage ()
458 //////////////////////////////////////////////////////////////////////
459
460 //////////////////////////////////////////////////////////////////////
461 //
462 //  Name: ProcessData
463 //  Description: Processes data waiting at the receive socket. The
464 //  processing ends when there is no more data at the socket.
465 //  
466 //////////////////////////////////////////////////////////////////////
467 void
468 FGMultiplayMgr::Update(void) 
469 {
470   if (!mInitialised)
471     return;
472
473   /// Just for expiry
474   SGTimeStamp timestamper;
475   timestamper.stamp();
476   long stamp = timestamper.get_seconds();
477
478   //////////////////////////////////////////////////
479   //  Read the receive socket and process any data
480   //////////////////////////////////////////////////
481   int bytes;
482   do {
483     char Msg[MAX_PACKET_SIZE];
484     //////////////////////////////////////////////////
485     //  Although the recv call asks for 
486     //  MAX_PACKET_SIZE of data, the number of bytes
487     //  returned will only be that of the next
488     //  packet waiting to be processed.
489     //////////////////////////////////////////////////
490     netAddress SenderAddress;
491     bytes = mSocket->recvfrom(Msg, sizeof(Msg), 0, &SenderAddress);
492     //////////////////////////////////////////////////
493     //  no Data received
494     //////////////////////////////////////////////////
495     if (bytes <= 0) {
496       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
497         perror("FGMultiplayMgr::MP_ProcessData");
498       break;
499     }
500     if (bytes <= sizeof(T_MsgHdr)) {
501       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
502               << "received message with insufficient data" );
503       break;
504     }
505     //////////////////////////////////////////////////
506     //  Read header
507     //////////////////////////////////////////////////
508     T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
509     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
510     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
511     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
512     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
513     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
514     if (MsgHdr->Magic != MSG_MAGIC) {
515       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
516               << "message has invalid magic number!" );
517       break;
518     }
519     if (MsgHdr->Version != PROTO_VER) {
520       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
521               << "message has invalid protocoll number!" );
522       break;
523     }
524     if (MsgHdr->MsgLen != bytes) {
525       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
526               << "message has invalid length!" );
527       break;
528     }
529     //////////////////////////////////////////////////
530     //  Process messages
531     //////////////////////////////////////////////////
532     switch (MsgHdr->MsgId) {
533     case CHAT_MSG_ID:
534       ProcessChatMsg(Msg, SenderAddress);
535       break;
536     case POS_DATA_ID:
537       ProcessPosMsg(Msg, SenderAddress, bytes, stamp);
538       break;
539     case UNUSABLE_POS_DATA_ID:
540     case OLD_OLD_POS_DATA_ID:
541     case OLD_PROP_MSG_ID:
542     case OLD_POS_DATA_ID:
543       break;
544     default:
545       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
546               << "Unknown message Id received: " << MsgHdr->MsgId );
547       break;
548     }
549   } while (bytes > 0);
550
551   // check for expiry
552   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
553   while (it != mMultiPlayerMap.end()) {
554     if (it->second->getLastTimestamp() + 10 < stamp) {
555       std::string name = it->first;
556       it->second->setDie(true);
557       mMultiPlayerMap.erase(it);
558       it = mMultiPlayerMap.upper_bound(name);
559     } else
560       ++it;
561   }
562 } // FGMultiplayMgr::ProcessData(void)
563 //////////////////////////////////////////////////////////////////////
564
565 //////////////////////////////////////////////////////////////////////
566 //
567 //  handle a position message
568 //
569 //////////////////////////////////////////////////////////////////////
570 void
571 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
572                               unsigned len, long stamp)
573 {
574   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
575   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
576     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
577             << "Position message received with insufficient data" );
578     return;
579   }
580   T_PositionMsg* PosMsg = (T_PositionMsg *)(Msg + sizeof(T_MsgHdr));
581   FGExternalMotionData motionInfo;
582   motionInfo.time = XDR_decode_double(PosMsg->time);
583   motionInfo.lag = XDR_decode_double(PosMsg->lag);
584   for (unsigned i = 0; i < 3; ++i)
585     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
586   SGVec3f angleAxis;
587   for (unsigned i = 0; i < 3; ++i)
588     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
589   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
590   for (unsigned i = 0; i < 3; ++i)
591     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
592   for (unsigned i = 0; i < 3; ++i)
593     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
594   for (unsigned i = 0; i < 3; ++i)
595     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
596   for (unsigned i = 0; i < 3; ++i)
597     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
598
599
600   //cout << "INPUT MESSAGE\n";
601   xdr_data_t* xdr = (xdr_data_t*) 
602                    (Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
603   while ((char*)xdr < Msg + len) {
604     FGPropertyData* pData = new FGPropertyData;
605     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
606     
607     // First element is always the ID
608     pData->id = XDR_decode_uint32(*xdr);
609     //cout << pData->id << " ";
610     xdr++;
611     
612     // Check the ID actually exists and get the type
613     unsigned i = 0;
614     bool found = false;
615     while (FGMultiplayMgr::sIdPropertyList[i].name) 
616     {
617       if (sIdPropertyList[i].id == pData->id)
618       {
619         found = true;
620         pData->type = sIdPropertyList[i].type;
621       } 
622       
623       i++;
624     }
625     
626     if (found == true)
627     {
628       // How we decode the remainder of the property depends on the type
629       switch (pData->type) {
630         case SGPropertyNode::INT:        
631         case SGPropertyNode::BOOL:
632         case SGPropertyNode::LONG:        
633           pData->int_value = XDR_decode_uint32(*xdr);
634           xdr++;
635           //cout << pData->int_value << "\n";
636           break;
637         case SGPropertyNode::FLOAT:
638         case SGPropertyNode::DOUBLE:
639           pData->float_value = XDR_decode_float(*xdr);
640           xdr++;
641           //cout << pData->float_value << "\n";
642           break;
643         case SGPropertyNode::STRING:
644         case SGPropertyNode::UNSPECIFIED:
645           {
646             // String is complicated. It consists of
647             // The length of the string
648             // The string itself
649             // Padding to the nearest 4-bytes.    
650             uint32_t length = XDR_decode_uint32(*xdr);
651             xdr++;
652             //cout << length << " ";
653
654             if ((length > 0) && (length < MAX_TEXT_SIZE))
655             {
656               pData->string_value = new char[length + 1];
657               //cout << " String: ";
658
659               for (int i = 0; i < length; i++)
660               {
661                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
662                 xdr++;
663                 //cout << pData->string_value[i];
664               }
665
666               pData->string_value[length] = '\0';
667
668               // Now handle the padding
669               while ((length % 4) != 0)
670               {
671                 xdr++;
672                 length++;
673                 //cout << "0";
674               }
675             }
676             else
677             {
678               pData->string_value = new char[1];
679               pData->string_value[0] = '\0';
680             }
681
682             //cout << "\n";
683           }
684           break;
685
686         default:
687           pData->float_value = XDR_decode_float(*xdr);
688           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
689           xdr++;
690           break;
691       }            
692
693       motionInfo.properties.push_back(pData);
694     }
695     else
696     {
697       // We failed to find the property. We'll try the next packet immediately.
698       //cout << " Unknown\n";
699     }
700   }
701   
702   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
703   if (!mp)
704     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
705   mp->addMotionInfo(motionInfo, stamp);
706 } // FGMultiplayMgr::ProcessPosMsg()
707 //////////////////////////////////////////////////////////////////////
708
709 //////////////////////////////////////////////////////////////////////
710 //
711 //  handle a chat message
712 //  FIXME: display chat message withi flightgear
713 //
714 //////////////////////////////////////////////////////////////////////
715 void
716 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
717 {
718   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
719   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
720     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
721             << "Chat message received with insufficient data" );
722     return;
723   }
724   
725   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
726   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
727           MsgHdr->MsgLen - sizeof(T_MsgHdr));
728   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
729   
730   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
731   SG_LOG ( SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
732            << " " << MsgBuf << endl);
733
734   delete [] MsgBuf;
735 } // FGMultiplayMgr::ProcessChatMsg ()
736 //////////////////////////////////////////////////////////////////////
737
738 void
739 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
740 {
741   uint32_t len;
742   switch (MsgId) {
743   case CHAT_MSG_ID:
744     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
745     break;
746   case POS_DATA_ID:
747     len = _len;
748     break;
749   default:
750     len = sizeof(T_MsgHdr);
751     break;
752   }
753   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
754   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
755   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
756   MsgHdr->MsgLen          = XDR_encode_uint32(len);
757   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
758   MsgHdr->ReplyPort       = 0; // now
759   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
760   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
761 }
762
763 FGAIMultiplayer*
764 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
765                                const std::string& modelName)
766 {
767   if (0 < mMultiPlayerMap.count(callsign))
768     return mMultiPlayerMap[callsign];
769
770   FGAIMultiplayer* mp = new FGAIMultiplayer;
771   mp->setPath(modelName.c_str());
772   mp->setCallSign(callsign);
773   mMultiPlayerMap[callsign] = mp;
774
775   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
776   if (aiMgr) {
777     aiMgr->attach(mp);
778
779     /// FIXME: that must follow the attach ATM ...
780     unsigned i = 0;
781     while (sIdPropertyList[i].name) {
782       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
783       ++i;
784     }
785   }
786
787   return mp;
788 }
789
790 FGAIMultiplayer*
791 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
792 {
793   if (0 < mMultiPlayerMap.count(callsign))
794     return mMultiPlayerMap[callsign];
795   else
796     return 0;
797 }