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