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