]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Add command multiplayer to control the multiplay_mgr
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.cxx
4 //
5 // Written by Duncan McCreanor, started February 2003.
6 // duncan.mccreanor@airservicesaustralia.com
7 //
8 // Copyright (C) 2003  Airservices Australia
9 // Copyright (C) 2005  Oliver Schroeder
10 // Copyright (C) 2006  Mathias Froehlich
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27 //  
28 //////////////////////////////////////////////////////////////////////
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #include <iostream>
35 #include <algorithm>
36 #include <cstring>
37 #include <errno.h>
38
39 #include <simgear/misc/stdint.hxx>
40 #include <simgear/timing/timestamp.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/structure/commands.hxx>
44
45 #include <AIModel/AIManager.hxx>
46 #include <AIModel/AIMultiplayer.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Network/RemoteXMLRequest.hxx>
49 #include <Network/HTTPClient.hxx>
50 #include "multiplaymgr.hxx"
51 #include "mpmessages.hxx"
52 #include <FDM/flightProperties.hxx>
53
54 using namespace std;
55
56 #define MAX_PACKET_SIZE 1200
57 #define MAX_TEXT_SIZE 128
58
59 struct IdPropertyList {
60   unsigned id;
61   const char* name;
62   simgear::props::Type type;
63 };
64  
65 static const IdPropertyList* findProperty(unsigned id);
66   
67 // A static map of protocol property id values to property paths,
68 // This should be extendable dynamically for every specific aircraft ...
69 // For now only that static list
70 static const IdPropertyList sIdPropertyList[] = {
71   {100, "surface-positions/left-aileron-pos-norm",  simgear::props::FLOAT},
72   {101, "surface-positions/right-aileron-pos-norm", simgear::props::FLOAT},
73   {102, "surface-positions/elevator-pos-norm",      simgear::props::FLOAT},
74   {103, "surface-positions/rudder-pos-norm",        simgear::props::FLOAT},
75   {104, "surface-positions/flap-pos-norm",          simgear::props::FLOAT},
76   {105, "surface-positions/speedbrake-pos-norm",    simgear::props::FLOAT},
77   {106, "gear/tailhook/position-norm",              simgear::props::FLOAT},
78   {107, "gear/launchbar/position-norm",             simgear::props::FLOAT},
79   {108, "gear/launchbar/state",                     simgear::props::STRING},
80   {109, "gear/launchbar/holdback-position-norm",    simgear::props::FLOAT},
81   {110, "canopy/position-norm",                     simgear::props::FLOAT},
82   {111, "surface-positions/wing-pos-norm",          simgear::props::FLOAT},
83   {112, "surface-positions/wing-fold-pos-norm",     simgear::props::FLOAT},
84
85   {200, "gear/gear[0]/compression-norm",           simgear::props::FLOAT},
86   {201, "gear/gear[0]/position-norm",              simgear::props::FLOAT},
87   {210, "gear/gear[1]/compression-norm",           simgear::props::FLOAT},
88   {211, "gear/gear[1]/position-norm",              simgear::props::FLOAT},
89   {220, "gear/gear[2]/compression-norm",           simgear::props::FLOAT},
90   {221, "gear/gear[2]/position-norm",              simgear::props::FLOAT},
91   {230, "gear/gear[3]/compression-norm",           simgear::props::FLOAT},
92   {231, "gear/gear[3]/position-norm",              simgear::props::FLOAT},
93   {240, "gear/gear[4]/compression-norm",           simgear::props::FLOAT},
94   {241, "gear/gear[4]/position-norm",              simgear::props::FLOAT},
95
96   {300, "engines/engine[0]/n1",  simgear::props::FLOAT},
97   {301, "engines/engine[0]/n2",  simgear::props::FLOAT},
98   {302, "engines/engine[0]/rpm", simgear::props::FLOAT},
99   {310, "engines/engine[1]/n1",  simgear::props::FLOAT},
100   {311, "engines/engine[1]/n2",  simgear::props::FLOAT},
101   {312, "engines/engine[1]/rpm", simgear::props::FLOAT},
102   {320, "engines/engine[2]/n1",  simgear::props::FLOAT},
103   {321, "engines/engine[2]/n2",  simgear::props::FLOAT},
104   {322, "engines/engine[2]/rpm", simgear::props::FLOAT},
105   {330, "engines/engine[3]/n1",  simgear::props::FLOAT},
106   {331, "engines/engine[3]/n2",  simgear::props::FLOAT},
107   {332, "engines/engine[3]/rpm", simgear::props::FLOAT},
108   {340, "engines/engine[4]/n1",  simgear::props::FLOAT},
109   {341, "engines/engine[4]/n2",  simgear::props::FLOAT},
110   {342, "engines/engine[4]/rpm", simgear::props::FLOAT},
111   {350, "engines/engine[5]/n1",  simgear::props::FLOAT},
112   {351, "engines/engine[5]/n2",  simgear::props::FLOAT},
113   {352, "engines/engine[5]/rpm", simgear::props::FLOAT},
114   {360, "engines/engine[6]/n1",  simgear::props::FLOAT},
115   {361, "engines/engine[6]/n2",  simgear::props::FLOAT},
116   {362, "engines/engine[6]/rpm", simgear::props::FLOAT},
117   {370, "engines/engine[7]/n1",  simgear::props::FLOAT},
118   {371, "engines/engine[7]/n2",  simgear::props::FLOAT},
119   {372, "engines/engine[7]/rpm", simgear::props::FLOAT},
120   {380, "engines/engine[8]/n1",  simgear::props::FLOAT},
121   {381, "engines/engine[8]/n2",  simgear::props::FLOAT},
122   {382, "engines/engine[8]/rpm", simgear::props::FLOAT},
123   {390, "engines/engine[9]/n1",  simgear::props::FLOAT},
124   {391, "engines/engine[9]/n2",  simgear::props::FLOAT},
125   {392, "engines/engine[9]/rpm", simgear::props::FLOAT},
126
127   {800, "rotors/main/rpm", simgear::props::FLOAT},
128   {801, "rotors/tail/rpm", simgear::props::FLOAT},
129   {810, "rotors/main/blade[0]/position-deg",  simgear::props::FLOAT},
130   {811, "rotors/main/blade[1]/position-deg",  simgear::props::FLOAT},
131   {812, "rotors/main/blade[2]/position-deg",  simgear::props::FLOAT},
132   {813, "rotors/main/blade[3]/position-deg",  simgear::props::FLOAT},
133   {820, "rotors/main/blade[0]/flap-deg",  simgear::props::FLOAT},
134   {821, "rotors/main/blade[1]/flap-deg",  simgear::props::FLOAT},
135   {822, "rotors/main/blade[2]/flap-deg",  simgear::props::FLOAT},
136   {823, "rotors/main/blade[3]/flap-deg",  simgear::props::FLOAT},
137   {830, "rotors/tail/blade[0]/position-deg",  simgear::props::FLOAT},
138   {831, "rotors/tail/blade[1]/position-deg",  simgear::props::FLOAT},
139
140   {900, "sim/hitches/aerotow/tow/length",                       simgear::props::FLOAT},
141   {901, "sim/hitches/aerotow/tow/elastic-constant",             simgear::props::FLOAT},
142   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            simgear::props::FLOAT},
143   {903, "sim/hitches/aerotow/tow/dist",                         simgear::props::FLOAT},
144   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   simgear::props::BOOL},
145   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   simgear::props::STRING},
146   {906, "sim/hitches/aerotow/tow/brake-force",                  simgear::props::FLOAT},
147   {907, "sim/hitches/aerotow/tow/end-force-x",                  simgear::props::FLOAT},
148   {908, "sim/hitches/aerotow/tow/end-force-y",                  simgear::props::FLOAT},
149   {909, "sim/hitches/aerotow/tow/end-force-z",                  simgear::props::FLOAT},
150   {930, "sim/hitches/aerotow/is-slave",                         simgear::props::BOOL},
151   {931, "sim/hitches/aerotow/speed-in-tow-direction",           simgear::props::FLOAT},
152   {932, "sim/hitches/aerotow/open",                             simgear::props::BOOL},
153   {933, "sim/hitches/aerotow/local-pos-x",                      simgear::props::FLOAT},
154   {934, "sim/hitches/aerotow/local-pos-y",                      simgear::props::FLOAT},
155   {935, "sim/hitches/aerotow/local-pos-z",                      simgear::props::FLOAT},
156
157   {1001, "controls/flight/slats",  simgear::props::FLOAT},
158   {1002, "controls/flight/speedbrake",  simgear::props::FLOAT},
159   {1003, "controls/flight/spoilers",  simgear::props::FLOAT},
160   {1004, "controls/gear/gear-down",  simgear::props::FLOAT},
161   {1005, "controls/lighting/nav-lights",  simgear::props::FLOAT},
162   {1006, "controls/armament/station[0]/jettison-all",  simgear::props::BOOL},
163
164   {1100, "sim/model/variant", simgear::props::INT},
165   {1101, "sim/model/livery/file", simgear::props::STRING},
166
167   {1200, "environment/wildfire/data", simgear::props::STRING},
168   {1201, "environment/contrail", simgear::props::INT},
169
170   {1300, "tanker", simgear::props::INT},
171
172   {1400, "scenery/events", simgear::props::STRING},
173
174   {1500, "instrumentation/transponder/transmitted-id", simgear::props::INT},
175   {1501, "instrumentation/transponder/altitude", simgear::props::INT},
176   {1502, "instrumentation/transponder/ident", simgear::props::BOOL},
177   {1503, "instrumentation/transponder/inputs/mode", simgear::props::INT},
178
179   {10001, "sim/multiplay/transmission-freq-hz",  simgear::props::STRING},
180   {10002, "sim/multiplay/chat",  simgear::props::STRING},
181
182   {10100, "sim/multiplay/generic/string[0]", simgear::props::STRING},
183   {10101, "sim/multiplay/generic/string[1]", simgear::props::STRING},
184   {10102, "sim/multiplay/generic/string[2]", simgear::props::STRING},
185   {10103, "sim/multiplay/generic/string[3]", simgear::props::STRING},
186   {10104, "sim/multiplay/generic/string[4]", simgear::props::STRING},
187   {10105, "sim/multiplay/generic/string[5]", simgear::props::STRING},
188   {10106, "sim/multiplay/generic/string[6]", simgear::props::STRING},
189   {10107, "sim/multiplay/generic/string[7]", simgear::props::STRING},
190   {10108, "sim/multiplay/generic/string[8]", simgear::props::STRING},
191   {10109, "sim/multiplay/generic/string[9]", simgear::props::STRING},
192   {10110, "sim/multiplay/generic/string[10]", simgear::props::STRING},
193   {10111, "sim/multiplay/generic/string[11]", simgear::props::STRING},
194   {10112, "sim/multiplay/generic/string[12]", simgear::props::STRING},
195   {10113, "sim/multiplay/generic/string[13]", simgear::props::STRING},
196   {10114, "sim/multiplay/generic/string[14]", simgear::props::STRING},
197   {10115, "sim/multiplay/generic/string[15]", simgear::props::STRING},
198   {10116, "sim/multiplay/generic/string[16]", simgear::props::STRING},
199   {10117, "sim/multiplay/generic/string[17]", simgear::props::STRING},
200   {10118, "sim/multiplay/generic/string[18]", simgear::props::STRING},
201   {10119, "sim/multiplay/generic/string[19]", simgear::props::STRING},
202
203   {10200, "sim/multiplay/generic/float[0]", simgear::props::FLOAT},
204   {10201, "sim/multiplay/generic/float[1]", simgear::props::FLOAT},
205   {10202, "sim/multiplay/generic/float[2]", simgear::props::FLOAT},
206   {10203, "sim/multiplay/generic/float[3]", simgear::props::FLOAT},
207   {10204, "sim/multiplay/generic/float[4]", simgear::props::FLOAT},
208   {10205, "sim/multiplay/generic/float[5]", simgear::props::FLOAT},
209   {10206, "sim/multiplay/generic/float[6]", simgear::props::FLOAT},
210   {10207, "sim/multiplay/generic/float[7]", simgear::props::FLOAT},
211   {10208, "sim/multiplay/generic/float[8]", simgear::props::FLOAT},
212   {10209, "sim/multiplay/generic/float[9]", simgear::props::FLOAT},
213   {10210, "sim/multiplay/generic/float[10]", simgear::props::FLOAT},
214   {10211, "sim/multiplay/generic/float[11]", simgear::props::FLOAT},
215   {10212, "sim/multiplay/generic/float[12]", simgear::props::FLOAT},
216   {10213, "sim/multiplay/generic/float[13]", simgear::props::FLOAT},
217   {10214, "sim/multiplay/generic/float[14]", simgear::props::FLOAT},
218   {10215, "sim/multiplay/generic/float[15]", simgear::props::FLOAT},
219   {10216, "sim/multiplay/generic/float[16]", simgear::props::FLOAT},
220   {10217, "sim/multiplay/generic/float[17]", simgear::props::FLOAT},
221   {10218, "sim/multiplay/generic/float[18]", simgear::props::FLOAT},
222   {10219, "sim/multiplay/generic/float[19]", simgear::props::FLOAT},
223
224   {10300, "sim/multiplay/generic/int[0]", simgear::props::INT},
225   {10301, "sim/multiplay/generic/int[1]", simgear::props::INT},
226   {10302, "sim/multiplay/generic/int[2]", simgear::props::INT},
227   {10303, "sim/multiplay/generic/int[3]", simgear::props::INT},
228   {10304, "sim/multiplay/generic/int[4]", simgear::props::INT},
229   {10305, "sim/multiplay/generic/int[5]", simgear::props::INT},
230   {10306, "sim/multiplay/generic/int[6]", simgear::props::INT},
231   {10307, "sim/multiplay/generic/int[7]", simgear::props::INT},
232   {10308, "sim/multiplay/generic/int[8]", simgear::props::INT},
233   {10309, "sim/multiplay/generic/int[9]", simgear::props::INT},
234   {10310, "sim/multiplay/generic/int[10]", simgear::props::INT},
235   {10311, "sim/multiplay/generic/int[11]", simgear::props::INT},
236   {10312, "sim/multiplay/generic/int[12]", simgear::props::INT},
237   {10313, "sim/multiplay/generic/int[13]", simgear::props::INT},
238   {10314, "sim/multiplay/generic/int[14]", simgear::props::INT},
239   {10315, "sim/multiplay/generic/int[15]", simgear::props::INT},
240   {10316, "sim/multiplay/generic/int[16]", simgear::props::INT},
241   {10317, "sim/multiplay/generic/int[17]", simgear::props::INT},
242   {10318, "sim/multiplay/generic/int[18]", simgear::props::INT},
243   {10319, "sim/multiplay/generic/int[19]", simgear::props::INT}
244 };
245
246 const unsigned int numProperties = (sizeof(sIdPropertyList)
247                                  / sizeof(sIdPropertyList[0]));
248
249 // Look up a property ID using binary search.
250 namespace
251 {
252   struct ComparePropertyId
253   {
254     bool operator()(const IdPropertyList& lhs,
255                     const IdPropertyList& rhs)
256     {
257       return lhs.id < rhs.id;
258     }
259     bool operator()(const IdPropertyList& lhs,
260                     unsigned id)
261     {
262       return lhs.id < id;
263     }
264     bool operator()(unsigned id,
265                     const IdPropertyList& rhs)
266     {
267       return id < rhs.id;
268     }
269   };    
270 }
271
272 const IdPropertyList* findProperty(unsigned id)
273 {
274   std::pair<const IdPropertyList*, const IdPropertyList*> result
275     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
276                        ComparePropertyId());
277   if (result.first == result.second) {
278     return 0;
279   } else {
280     return result.first;
281   }
282 }
283
284 namespace
285 {
286   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
287   {
288     using namespace simgear;
289     const xdr_data_t* xdr = data;
290     while (xdr < end) {
291       unsigned id = XDR_decode_uint32(*xdr);
292       const IdPropertyList* plist = findProperty(id);
293     
294       if (plist) {
295         xdr++;
296         // How we decode the remainder of the property depends on the type
297         switch (plist->type) {
298         case props::INT:
299         case props::BOOL:
300         case props::LONG:
301           xdr++;
302           break;
303         case props::FLOAT:
304         case props::DOUBLE:
305           {
306             float val = XDR_decode_float(*xdr);
307             if (SGMisc<float>::isNaN(val))
308               return false;
309             xdr++;
310             break;
311           }
312         case props::STRING:
313         case props::UNSPECIFIED:
314           {
315             // String is complicated. It consists of
316             // The length of the string
317             // The string itself
318             // Padding to the nearest 4-bytes.
319             // XXX Yes, each byte is padded out to a word! Too late
320             // to change...
321             uint32_t length = XDR_decode_uint32(*xdr);
322             xdr++;
323             // Old versions truncated the string but left the length
324             // unadjusted.
325             if (length > MAX_TEXT_SIZE)
326               length = MAX_TEXT_SIZE;
327             xdr += length;
328             // Now handle the padding
329             while ((length % 4) != 0)
330               {
331                 xdr++;
332                 length++;
333                 //cout << "0";
334               }
335           }
336           break;
337         default:
338           // cerr << "Unknown Prop type " << id << " " << type << "\n";
339           xdr++;
340           break;
341         }            
342       }
343       else {
344         // give up; this is a malformed property list.
345         return false;
346       }
347     }
348     return true;
349   }
350 }
351
352 class MPPropertyListener : public SGPropertyChangeListener
353 {
354 public:
355   MPPropertyListener(FGMultiplayMgr* mp) :
356     _multiplay(mp)
357   {
358   }
359
360   virtual void childAdded(SGPropertyNode*, SGPropertyNode*)
361   {
362     _multiplay->setPropertiesChanged();
363   }
364
365 private:
366   FGMultiplayMgr* _multiplay;
367 };
368
369 //////////////////////////////////////////////////////////////////////
370 //
371 //  handle command "multiplayer"
372 //  command: connect|disconnect|refreshserverlist
373 //
374 //  connect args:
375 //  server: servername to connect (mandatory)
376 //  txport: outgoing port number (default: 5000)
377 //  rxport: incoming port number (default: 5000)
378 //
379 //  disconnect args:
380 //  none
381 //
382 //  refreshserverlist args:
383 //  none
384 //
385 //////////////////////////////////////////////////////////////////////
386 static bool do_multiplayer (const SGPropertyNode * arg)
387 {
388     FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
389
390     const string &command = arg->getStringValue("command", "");
391     SG_LOG(SG_NETWORK, SG_WARN, "do_multiplayer: " << command );
392     if( command == "connect" ) {
393         string servername = arg->getStringValue("servername", "");
394         if( servername.empty() ) {
395           SG_LOG(SG_NETWORK, SG_WARN, "do_multiplayer.connect: no server name given, command ignored." );
396           return false;
397         }
398         int port = arg->getIntValue("rxport", -1 );
399         if( port > 0 && port <= 0xffff ) {
400             fgSetInt( "/sim/multiplay/rxport", port );
401         }
402
403         port = arg->getIntValue("txport", -1 );
404         if( port > 0 && port <= 0xffff ) {
405             fgSetInt( "/sim/multiplay/txport", port );
406         }
407
408         servername = servername.substr( 0, servername.find_first_of(' '));
409         fgSetString("/sim/multiplay/txhost", servername );
410         self->reinit();
411         return true;
412
413     } else if( command == "disconnect" ) {
414         fgSetString("/sim/multiplay/txhost", "");
415         self->reinit();
416         return true;
417
418     } else if( command == "refreshserverlist" ) {
419         string url(fgGetString("/sim/multiplay/serverlist-url",
420                                "http://liveries.flightgear.org/mpstatus/mpservers.xml" ));
421
422         if (url.empty()) {
423             SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
424             return false;
425         }
426
427         FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
428         if (!http) {
429             SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: HTTP client not running");
430             return false;
431         }
432
433         SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true );
434         SGPropertyNode *completeNode = fgGetNode("/sim/multiplay/got-servers", true);
435         SGPropertyNode *failureNode = fgGetNode("/sim/multiplay/get-servers-failure", true);
436         RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
437         req->setCompletionProp( completeNode );
438         req->setFailedProp( failureNode );
439         completeNode->setBoolValue(false);
440         failureNode->setBoolValue(false);
441         http->makeRequest(req);
442         return true;
443
444     } else {
445         SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr do_multiplayer: command" << command << " unknown. ignored.");
446     }
447     return true;
448 }
449
450 //////////////////////////////////////////////////////////////////////
451 //
452 //  MultiplayMgr constructor
453 //
454 //////////////////////////////////////////////////////////////////////
455 FGMultiplayMgr::FGMultiplayMgr() 
456 {
457   mInitialised   = false;
458   mHaveServer    = false;
459   mListener = NULL;
460   globals->get_commands()->addCommand("multiplayer", do_multiplayer);
461 } // FGMultiplayMgr::FGMultiplayMgr()
462 //////////////////////////////////////////////////////////////////////
463
464 //////////////////////////////////////////////////////////////////////
465 //
466 //  MultiplayMgr destructor
467 //
468 //////////////////////////////////////////////////////////////////////
469 FGMultiplayMgr::~FGMultiplayMgr() 
470 {
471    globals->get_commands()->removeCommand("multiplayer");
472 } // FGMultiplayMgr::~FGMultiplayMgr()
473 //////////////////////////////////////////////////////////////////////
474
475 //////////////////////////////////////////////////////////////////////
476 //
477 //  Initialise object
478 //
479 //////////////////////////////////////////////////////////////////////
480 void
481 FGMultiplayMgr::init (void) 
482 {
483   //////////////////////////////////////////////////
484   //  Initialise object if not already done
485   //////////////////////////////////////////////////
486   if (mInitialised) {
487     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
488     return;
489   }
490
491   SGPropertyNode* propOnline = fgGetNode("/sim/multiplay/online", true);
492   propOnline->setBoolValue(false);
493   propOnline->setAttribute(SGPropertyNode::PRESERVE, true);
494
495   //////////////////////////////////////////////////
496   //  Set members from property values
497   //////////////////////////////////////////////////
498   short rxPort = fgGetInt("/sim/multiplay/rxport");
499   string rxAddress = fgGetString("/sim/multiplay/rxhost");
500   short txPort = fgGetInt("/sim/multiplay/txport", 5000);
501   string txAddress = fgGetString("/sim/multiplay/txhost");
502   
503   int hz = fgGetInt("/sim/multiplay/tx-rate-hz", 10);
504   if (hz < 1) {
505     hz = 10;
506   }
507   
508   mDt = 1.0 / hz;
509   mTimeUntilSend = 0.0;
510   
511   mCallsign = fgGetString("/sim/multiplay/callsign");
512   fgGetNode("/sim/multiplay/callsign", true)->setAttribute(SGPropertyNode::PRESERVE, true);
513     
514   if ((!txAddress.empty()) && (txAddress!="0")) {
515     mServer.set(txAddress.c_str(), txPort);
516     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
517       mHaveServer = false;
518       SG_LOG(SG_NETWORK, SG_ALERT,
519         "Cannot enable multiplayer mode: resolving MP server address '"
520         << txAddress << "' failed.");
521       return;
522     } else {
523       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
524       mHaveServer = true;
525     }
526     if (rxPort <= 0)
527       rxPort = txPort;
528   } else {
529     SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - multiplayer mode disabled (no MP server specificed).");
530     return;
531   }
532
533   if (rxPort <= 0) {
534     SG_LOG(SG_NETWORK, SG_ALERT,
535       "Cannot enable multiplayer mode: No receiver port specified.");
536     return;
537   }
538   if (mCallsign.empty())
539     mCallsign = "JohnDoe"; // FIXME: use getpwuid
540   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
541   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
542   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
543   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
544   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
545   
546   mSocket.reset(new simgear::Socket());
547   if (!mSocket->open(false)) {
548     SG_LOG( SG_NETWORK, SG_ALERT,
549             "Cannot enable multiplayer mode: creating data socket failed." );
550     return;
551   }
552   mSocket->setBlocking(false);
553   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
554     SG_LOG( SG_NETWORK, SG_ALERT,
555             "Cannot enable multiplayer mode: binding receive socket failed. "
556             << strerror(errno) << "(errno " << errno << ")");
557     return;
558   }
559   
560   mPropertiesChanged = true;
561   mListener = new MPPropertyListener(this);
562   globals->get_props()->addChangeListener(mListener, false);
563   
564   fgSetBool("/sim/multiplay/online", true);
565   mInitialised = true;
566
567   SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer mode active!");
568
569   if (!fgGetBool("/sim/ai/enabled"))
570   {
571       // multiplayer depends on AI module
572       fgSetBool("/sim/ai/enabled", true);
573   }
574 } // FGMultiplayMgr::init()
575 //////////////////////////////////////////////////////////////////////
576
577 //////////////////////////////////////////////////////////////////////
578 //
579 //  Closes and deletes the local player object. Closes
580 //  and deletes the tx socket. Resets the object state to unitialised.
581 //
582 //////////////////////////////////////////////////////////////////////
583 void
584 FGMultiplayMgr::shutdown (void) 
585 {
586   fgSetBool("/sim/multiplay/online", false);
587   
588   if (mSocket.get()) {
589     mSocket->close();
590     mSocket.reset(); 
591   }
592   
593   MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
594     end = mMultiPlayerMap.end();
595   for (; it != end; ++it) {
596     it->second->setDie(true);
597   }
598   mMultiPlayerMap.clear();
599   
600   if (mListener) {
601     globals->get_props()->removeChangeListener(mListener);
602     delete mListener;
603     mListener = NULL;
604   }
605   
606   mInitialised = false;
607 } // FGMultiplayMgr::Close(void)
608 //////////////////////////////////////////////////////////////////////
609
610 void
611 FGMultiplayMgr::reinit()
612 {
613   shutdown();
614   init();
615 }
616
617 //////////////////////////////////////////////////////////////////////
618 //
619 //  Description: Sends the position data for the local position.
620 //
621 //////////////////////////////////////////////////////////////////////
622
623 /**
624  * The buffer that holds a multi-player message, suitably aligned.
625  */
626 union FGMultiplayMgr::MsgBuf
627 {
628     MsgBuf()
629     {
630         memset(&Msg, 0, sizeof(Msg));
631     }
632
633     T_MsgHdr* msgHdr()
634     {
635         return &Header;
636     }
637
638     const T_MsgHdr* msgHdr() const
639     {
640         return reinterpret_cast<const T_MsgHdr*>(&Header);
641     }
642
643     T_PositionMsg* posMsg()
644     {
645         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
646     }
647
648     const T_PositionMsg* posMsg() const
649     {
650         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
651     }
652
653     xdr_data_t* properties()
654     {
655         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
656                                              + sizeof(T_PositionMsg));
657     }
658
659     const xdr_data_t* properties() const
660     {
661         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
662                                                    + sizeof(T_PositionMsg));
663     }
664     /**
665      * The end of the properties buffer.
666      */
667     xdr_data_t* propsEnd()
668     {
669         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
670     };
671
672     const xdr_data_t* propsEnd() const
673     {
674         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
675     };
676     /**
677      * The end of properties actually in the buffer. This assumes that
678      * the message header is valid.
679      */
680     xdr_data_t* propsRecvdEnd()
681     {
682         return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
683     }
684
685     const xdr_data_t* propsRecvdEnd() const
686     {
687         return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
688     }
689     
690     xdr_data2_t double_val;
691     char Msg[MAX_PACKET_SIZE];
692     T_MsgHdr Header;
693 };
694
695 bool
696 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
697 {
698     // check for corrupted data (NaNs)
699     bool isCorrupted = false;
700     isCorrupted |= ((SGMisc<double>::isNaN(motionInfo.time           )) ||
701                     (SGMisc<double>::isNaN(motionInfo.lag            )) ||
702                     (osg::isNaN(motionInfo.orientation(3) )));
703     for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
704     {
705         isCorrupted |= ((osg::isNaN(motionInfo.position(i)      ))||
706                         (osg::isNaN(motionInfo.orientation(i)   ))||
707                         (osg::isNaN(motionInfo.linearVel(i))    )||
708                         (osg::isNaN(motionInfo.angularVel(i))   )||
709                         (osg::isNaN(motionInfo.linearAccel(i))  )||
710                         (osg::isNaN(motionInfo.angularAccel(i)) ));
711     }
712     return !isCorrupted;
713 }
714
715 void
716 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
717 {
718   if ((! mInitialised) || (! mHaveServer))
719         return;
720
721   if (! mHaveServer) {
722       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
723       return;
724   }
725
726   if (!isSane(motionInfo))
727   {
728       // Current local data is invalid (NaN), so stop MP transmission.
729       // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
730       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
731               << "Local data is invalid (NaN). Data not transmitted.");
732       return;
733   }
734
735   static MsgBuf msgBuf;
736   static unsigned msgLen = 0;
737   T_PositionMsg* PosMsg = msgBuf.posMsg();
738
739   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
740   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
741   if (fgGetBool("/sim/freeze/replay-state", true)&&
742       fgGetBool("/sim/multiplay/freeze-on-replay",true))
743   {
744       // do not send position updates during replay
745       for (unsigned i = 0 ; i < 3; ++i)
746       {
747           // no movement during replay
748           PosMsg->linearVel[i] = XDR_encode_float (0.0);
749           PosMsg->angularVel[i] = XDR_encode_float (0.0);
750           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
751           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
752       }
753       // all other data remains unchanged (resend last state) 
754   }
755   else
756   {
757       PosMsg->time = XDR_encode_double (motionInfo.time);
758       PosMsg->lag = XDR_encode_double (motionInfo.lag);
759       for (unsigned i = 0 ; i < 3; ++i)
760         PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
761       SGVec3f angleAxis;
762       motionInfo.orientation.getAngleAxis(angleAxis);
763       for (unsigned i = 0 ; i < 3; ++i)
764         PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
765       for (unsigned i = 0 ; i < 3; ++i)
766         PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
767       for (unsigned i = 0 ; i < 3; ++i)
768         PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
769       for (unsigned i = 0 ; i < 3; ++i)
770         PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
771       for (unsigned i = 0 ; i < 3; ++i)
772         PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
773
774       xdr_data_t* ptr = msgBuf.properties();
775       std::vector<FGPropertyData*>::const_iterator it;
776       it = motionInfo.properties.begin();
777       //cout << "OUTPUT PROPERTIES\n";
778       xdr_data_t* msgEnd = msgBuf.propsEnd();
779       while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
780         
781         // First element is the ID. Write it out when we know we have room for
782         // the whole property.
783         xdr_data_t id =  XDR_encode_uint32((*it)->id);
784         // The actual data representation depends on the type
785         switch ((*it)->type) {
786           case simgear::props::INT:
787           case simgear::props::BOOL:
788           case simgear::props::LONG:
789             *ptr++ = id;
790             *ptr++ = XDR_encode_uint32((*it)->int_value);
791             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
792             break;
793           case simgear::props::FLOAT:
794           case simgear::props::DOUBLE:
795             *ptr++ = id;
796             *ptr++ = XDR_encode_float((*it)->float_value);
797             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
798             break;
799           case simgear::props::STRING:
800           case simgear::props::UNSPECIFIED:
801             {
802               // String is complicated. It consists of
803               // The length of the string
804               // The string itself
805               // Padding to the nearest 4-bytes.        
806               const char* lcharptr = (*it)->string_value;
807               
808               if (lcharptr != 0)
809               {
810                 // Add the length         
811                 ////cout << "String length: " << strlen(lcharptr) << "\n";
812                 uint32_t len = strlen(lcharptr);
813                 if (len > MAX_TEXT_SIZE)
814                   len = MAX_TEXT_SIZE;
815                 // XXX This should not be using 4 bytes per character!
816                 // If there's not enough room for this property, drop it
817                 // on the floor.
818                 if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
819                     goto escape;
820                 //cout << "String length unint32: " << len << "\n";
821                 *ptr++ = id;
822                 *ptr++ = XDR_encode_uint32(len);
823                 if (len != 0)
824                 {
825                   // Now the text itself
826                   // XXX This should not be using 4 bytes per character!
827                   int lcount = 0;
828                   while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
829                   {
830                     *ptr++ = XDR_encode_int8(*lcharptr);
831                     lcharptr++;
832                     lcount++;          
833                   }
834     
835                   //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
836     
837                   // Now pad if required
838                   while ((lcount % 4) != 0)
839                   {
840                     *ptr++ = XDR_encode_int8(0);
841                     lcount++;          
842                     //cout << "0";
843                   }
844                   
845                   //cout << "\n";
846                 }
847               }
848               else
849               {
850                 // Nothing to encode
851                 *ptr++ = id;
852                 *ptr++ = XDR_encode_uint32(0);
853                 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
854               }
855             }
856             break;
857             
858           default:
859             //cout << " Unknown Type: " << (*it)->type << "\n";
860             *ptr++ = id;
861             *ptr++ = XDR_encode_float((*it)->float_value);;
862             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
863             break;
864         }
865             
866         ++it;
867       }
868   escape:
869       msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
870       FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
871   }
872   if (msgLen>0)
873       mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
874   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
875 } // FGMultiplayMgr::SendMyPosition()
876
877 //////////////////////////////////////////////////////////////////////
878
879 //////////////////////////////////////////////////////////////////////
880 //
881 //  Name: SendTextMessage
882 //  Description: Sends a message to the player. The message must
883 //  contain a valid and correctly filled out header and optional
884 //  message body.
885 //
886 //////////////////////////////////////////////////////////////////////
887 void
888 FGMultiplayMgr::SendTextMessage(const string &MsgText)
889 {
890   if (!mInitialised || !mHaveServer)
891     return;
892
893   T_MsgHdr MsgHdr;
894   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
895   //////////////////////////////////////////////////
896   // Divide the text string into blocks that fit
897   // in the message and send the blocks.
898   //////////////////////////////////////////////////
899   unsigned iNextBlockPosition = 0;
900   T_ChatMsg ChatMsg;
901   
902   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
903   while (iNextBlockPosition < MsgText.length()) {
904     strncpy (ChatMsg.Text, 
905              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
906              MAX_CHAT_MSG_LEN);
907     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
908     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
909     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
910     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
911     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
912
913   }
914   
915   
916 } // FGMultiplayMgr::SendTextMessage ()
917 //////////////////////////////////////////////////////////////////////
918
919 //////////////////////////////////////////////////////////////////////
920 //
921 //  Name: ProcessData
922 //  Description: Processes data waiting at the receive socket. The
923 //  processing ends when there is no more data at the socket.
924 //  
925 //////////////////////////////////////////////////////////////////////
926 void
927 FGMultiplayMgr::update(double dt) 
928 {
929   if (!mInitialised)
930     return;
931
932   /// Just for expiry
933   long stamp = SGTimeStamp::now().getSeconds();
934
935   //////////////////////////////////////////////////
936   //  Send if required
937   //////////////////////////////////////////////////
938   mTimeUntilSend -= dt;
939   if (mTimeUntilSend <= 0.0) {
940     Send();
941   }
942
943   //////////////////////////////////////////////////
944   //  Read the receive socket and process any data
945   //////////////////////////////////////////////////
946   ssize_t bytes;
947   do {
948     MsgBuf msgBuf;
949     //////////////////////////////////////////////////
950     //  Although the recv call asks for 
951     //  MAX_PACKET_SIZE of data, the number of bytes
952     //  returned will only be that of the next
953     //  packet waiting to be processed.
954     //////////////////////////////////////////////////
955     simgear::IPAddress SenderAddress;
956     int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
957                               &SenderAddress);
958     //////////////////////////////////////////////////
959     //  no Data received
960     //////////////////////////////////////////////////
961     if (RecvStatus == 0)
962         break;
963
964     // socket error reported?
965     // errno isn't thread-safe - so only check its value when
966     // socket return status < 0 really indicates a failure.
967     if ((RecvStatus < 0)&&
968         ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
969     {
970         // ignore "normal" errors
971         break;
972     }
973
974     if (RecvStatus<0)
975     {
976         SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
977                << strerror(errno) << "(errno " << errno << ")");
978         break;
979     }
980
981     // status is positive: bytes received
982     bytes = (ssize_t) RecvStatus;
983     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
984       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
985               << "received message with insufficient data" );
986       break;
987     }
988     //////////////////////////////////////////////////
989     //  Read header
990     //////////////////////////////////////////////////
991     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
992     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
993     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
994     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
995     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
996     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
997     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
998     if (MsgHdr->Magic != MSG_MAGIC) {
999       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1000               << "message has invalid magic number!" );
1001       break;
1002     }
1003     if (MsgHdr->Version != PROTO_VER) {
1004       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1005               << "message has invalid protocol number!" );
1006       break;
1007     }
1008     if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
1009       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1010              << "message from " << MsgHdr->Callsign << " has invalid length!");
1011       break;
1012     }
1013     //////////////////////////////////////////////////
1014     //  Process messages
1015     //////////////////////////////////////////////////
1016     switch (MsgHdr->MsgId) {
1017     case CHAT_MSG_ID:
1018       ProcessChatMsg(msgBuf, SenderAddress);
1019       break;
1020     case POS_DATA_ID:
1021       ProcessPosMsg(msgBuf, SenderAddress, stamp);
1022       break;
1023     case UNUSABLE_POS_DATA_ID:
1024     case OLD_OLD_POS_DATA_ID:
1025     case OLD_PROP_MSG_ID:
1026     case OLD_POS_DATA_ID:
1027       break;
1028     default:
1029       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1030               << "Unknown message Id received: " << MsgHdr->MsgId );
1031       break;
1032     }
1033   } while (bytes > 0);
1034
1035   // check for expiry
1036   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
1037   while (it != mMultiPlayerMap.end()) {
1038     if (it->second->getLastTimestamp() + 10 < stamp) {
1039       std::string name = it->first;
1040       it->second->setDie(true);
1041       mMultiPlayerMap.erase(it);
1042       it = mMultiPlayerMap.upper_bound(name);
1043     } else
1044       ++it;
1045   }
1046 } // FGMultiplayMgr::ProcessData(void)
1047 //////////////////////////////////////////////////////////////////////
1048
1049 void
1050 FGMultiplayMgr::Send()
1051 {
1052   using namespace simgear;
1053   
1054   findProperties();
1055     
1056   // smooth the send rate, by adjusting based on the 'remainder' time, which
1057   // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
1058   // however.
1059     if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
1060       mTimeUntilSend = mDt + mTimeUntilSend;
1061     } else {
1062       mTimeUntilSend = mDt;
1063     }
1064
1065     double sim_time = globals->get_sim_time_sec();
1066 //    static double lastTime = 0.0;
1067     
1068    // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
1069 //    lastTime = sim_time;
1070     
1071     FlightProperties ifce;
1072
1073     // put together a motion info struct, you will get that later
1074     // from FGInterface directly ...
1075     FGExternalMotionData motionInfo;
1076
1077     // The current simulation time we need to update for,
1078     // note that the simulation time is updated before calling all the
1079     // update methods. Thus it contains the time intervals *end* time.
1080     // The FDM is already run, so the states belong to that time.
1081     motionInfo.time = sim_time;
1082     motionInfo.lag = mDt;
1083
1084     // These are for now converted from lat/lon/alt and euler angles.
1085     // But this should change in FGInterface ...
1086     double lon = ifce.get_Longitude();
1087     double lat = ifce.get_Latitude();
1088     // first the aprioriate structure for the geodetic one
1089     SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
1090     // Convert to cartesion coordinate
1091     motionInfo.position = SGVec3d::fromGeod(geod);
1092     
1093     // The quaternion rotating from the earth centered frame to the
1094     // horizontal local frame
1095     SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
1096     // The orientation wrt the horizontal local frame
1097     float heading = ifce.get_Psi();
1098     float pitch = ifce.get_Theta();
1099     float roll = ifce.get_Phi();
1100     SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
1101     // The orientation of the vehicle wrt the earth centered frame
1102     motionInfo.orientation = qEc2Hl*hlOr;
1103
1104     if (!globals->get_subsystem("flight")->is_suspended()) {
1105       // velocities
1106       motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1107                                                       ifce.get_vBody(),
1108                                                       ifce.get_wBody());
1109       motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1110                                       ifce.get_Q_body(),
1111                                       ifce.get_R_body());
1112       
1113       // accels, set that to zero for now.
1114       // Angular accelerations are missing from the interface anyway,
1115       // linear accelerations are screwed up at least for JSBSim.
1116 //  motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1117 //                                                    ifce.get_V_dot_body(),
1118 //                                                    ifce.get_W_dot_body());
1119       motionInfo.linearAccel = SGVec3f::zeros();
1120       motionInfo.angularAccel = SGVec3f::zeros();
1121     } else {
1122       // if the interface is suspendend, prevent the client from
1123       // wild extrapolations
1124       motionInfo.linearVel = SGVec3f::zeros();
1125       motionInfo.angularVel = SGVec3f::zeros();
1126       motionInfo.linearAccel = SGVec3f::zeros();
1127       motionInfo.angularAccel = SGVec3f::zeros();
1128     }
1129
1130     // now send the properties
1131     PropertyMap::iterator it;
1132     for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1133       FGPropertyData* pData = new FGPropertyData;
1134       pData->id = it->first;
1135       pData->type = it->second->getType();
1136       
1137       switch (pData->type) {
1138         case props::INT:
1139         case props::LONG:
1140         case props::BOOL:
1141           pData->int_value = it->second->getIntValue();
1142           break;
1143         case props::FLOAT:
1144         case props::DOUBLE:
1145           pData->float_value = it->second->getFloatValue();
1146           break;
1147         case props::STRING:
1148         case props::UNSPECIFIED:
1149           {
1150             // FIXME: We assume unspecified are strings for the moment.
1151
1152             const char* cstr = it->second->getStringValue();
1153             int len = strlen(cstr);
1154             
1155             if (len > 0)
1156             {            
1157               pData->string_value = new char[len + 1];
1158               strcpy(pData->string_value, cstr);
1159             }
1160             else
1161             {
1162               // Size 0 - ignore
1163               pData->string_value = 0;            
1164             }
1165
1166             //cout << " Sending property " << pData->id << " " << pData->type << " " <<  pData->string_value << "\n";
1167             break;        
1168           }
1169         default:
1170           // FIXME Currently default to a float. 
1171           //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1172           pData->float_value = it->second->getFloatValue();
1173           break;
1174       }
1175       
1176       motionInfo.properties.push_back(pData);
1177     }
1178
1179     SendMyPosition(motionInfo);
1180 }
1181
1182
1183 //////////////////////////////////////////////////////////////////////
1184 //
1185 //  handle a position message
1186 //
1187 //////////////////////////////////////////////////////////////////////
1188 void
1189 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1190                               const simgear::IPAddress& SenderAddress, long stamp)
1191 {
1192   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1193   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1194     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1195             << "Position message received with insufficient data" );
1196     return;
1197   }
1198   const T_PositionMsg* PosMsg = Msg.posMsg();
1199   FGExternalMotionData motionInfo;
1200   motionInfo.time = XDR_decode_double(PosMsg->time);
1201   motionInfo.lag = XDR_decode_double(PosMsg->lag);
1202   for (unsigned i = 0; i < 3; ++i)
1203     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1204   SGVec3f angleAxis;
1205   for (unsigned i = 0; i < 3; ++i)
1206     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1207   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1208   for (unsigned i = 0; i < 3; ++i)
1209     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1210   for (unsigned i = 0; i < 3; ++i)
1211     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1212   for (unsigned i = 0; i < 3; ++i)
1213     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1214   for (unsigned i = 0; i < 3; ++i)
1215     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1216
1217   // sanity check: do not allow injection of corrupted data (NaNs)
1218   if (!isSane(motionInfo))
1219   {
1220       // drop this message, keep old position until receiving valid data
1221       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1222               << "Position message with invalid data (NaN) received from "
1223               << MsgHdr->Callsign);
1224       return;
1225   }
1226
1227   //cout << "INPUT MESSAGE\n";
1228
1229   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1230   // on 32 bit architectures and 200 bytes on 64 bit, and this
1231   // structure is put directly on the wire. By looking at the padding,
1232   // we can sort through the mess, mostly:
1233   // If padding is 0 (which is not a valid property type), then the
1234   // message was produced by a new client or an old 64 bit client that
1235   // happened to have 0 on the stack;
1236   // Else if the property list starting with the padding word is
1237   // well-formed, then the client is probably an old 32 bit client and
1238   // we'll go with that;
1239   // Else it is an old 64-bit client and properties start after the
1240   // padding.
1241   // There is a chance that we could be fooled by garbage in the
1242   // padding looking like a valid property, so verifyProperties() is
1243   // strict about the validity of the property values.
1244   const xdr_data_t* xdr = Msg.properties();
1245   if (PosMsg->pad != 0) {
1246     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1247       xdr = &PosMsg->pad;
1248     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1249       goto noprops;
1250   }
1251   while (xdr < Msg.propsRecvdEnd()) {
1252     // simgear::props::Type type = simgear::props::UNSPECIFIED;
1253     
1254     // First element is always the ID
1255     unsigned id = XDR_decode_uint32(*xdr);
1256     //cout << pData->id << " ";
1257     xdr++;
1258     
1259     // Check the ID actually exists and get the type
1260     const IdPropertyList* plist = findProperty(id);
1261     
1262     if (plist)
1263     {
1264       FGPropertyData* pData = new FGPropertyData;
1265       pData->id = id;
1266       pData->type = plist->type;
1267       // How we decode the remainder of the property depends on the type
1268       switch (pData->type) {
1269         case simgear::props::INT:
1270         case simgear::props::BOOL:
1271         case simgear::props::LONG:
1272           pData->int_value = XDR_decode_uint32(*xdr);
1273           xdr++;
1274           //cout << pData->int_value << "\n";
1275           break;
1276         case simgear::props::FLOAT:
1277         case simgear::props::DOUBLE:
1278           pData->float_value = XDR_decode_float(*xdr);
1279           xdr++;
1280           //cout << pData->float_value << "\n";
1281           break;
1282         case simgear::props::STRING:
1283         case simgear::props::UNSPECIFIED:
1284           {
1285             // String is complicated. It consists of
1286             // The length of the string
1287             // The string itself
1288             // Padding to the nearest 4-bytes.    
1289             uint32_t length = XDR_decode_uint32(*xdr);
1290             xdr++;
1291             //cout << length << " ";
1292             // Old versions truncated the string but left the length unadjusted.
1293             if (length > MAX_TEXT_SIZE)
1294               length = MAX_TEXT_SIZE;
1295             pData->string_value = new char[length + 1];
1296             //cout << " String: ";
1297             for (unsigned i = 0; i < length; i++)
1298               {
1299                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1300                 xdr++;
1301                 //cout << pData->string_value[i];
1302               }
1303
1304             pData->string_value[length] = '\0';
1305
1306             // Now handle the padding
1307             while ((length % 4) != 0)
1308               {
1309                 xdr++;
1310                 length++;
1311                 //cout << "0";
1312               }
1313             //cout << "\n";
1314           }
1315           break;
1316
1317         default:
1318           pData->float_value = XDR_decode_float(*xdr);
1319           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1320           xdr++;
1321           break;
1322       }
1323
1324       motionInfo.properties.push_back(pData);
1325     }
1326     else
1327     {
1328       // We failed to find the property. We'll try the next packet immediately.
1329       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1330              "message from " << MsgHdr->Callsign << " has unknown property id "
1331              << id); 
1332     }
1333   }
1334  noprops:
1335   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1336   if (!mp)
1337     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1338   mp->addMotionInfo(motionInfo, stamp);
1339 } // FGMultiplayMgr::ProcessPosMsg()
1340 //////////////////////////////////////////////////////////////////////
1341
1342 //////////////////////////////////////////////////////////////////////
1343 //
1344 //  handle a chat message
1345 //  FIXME: display chat message within flightgear
1346 //
1347 //////////////////////////////////////////////////////////////////////
1348 void
1349 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1350                                const simgear::IPAddress& SenderAddress)
1351 {
1352   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1353   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1354     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1355             << "Chat message received with insufficient data" );
1356     return;
1357   }
1358   
1359   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1360   const T_ChatMsg* ChatMsg
1361       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1362   strncpy(chatStr, ChatMsg->Text,
1363           MsgHdr->MsgLen - sizeof(T_MsgHdr));
1364   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1365   
1366   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1367            << " " << chatStr);
1368
1369   delete [] chatStr;
1370 } // FGMultiplayMgr::ProcessChatMsg ()
1371 //////////////////////////////////////////////////////////////////////
1372
1373 void
1374 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1375 {
1376   uint32_t len;
1377   switch (MsgId) {
1378   case CHAT_MSG_ID:
1379     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1380     break;
1381   case POS_DATA_ID:
1382     len = _len;
1383     break;
1384   default:
1385     len = sizeof(T_MsgHdr);
1386     break;
1387   }
1388   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1389   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1390   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1391   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1392   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1393   MsgHdr->ReplyPort       = 0; // now
1394   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1395   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1396 }
1397
1398 FGAIMultiplayer*
1399 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1400                                const std::string& modelName)
1401 {
1402   if (0 < mMultiPlayerMap.count(callsign))
1403     return mMultiPlayerMap[callsign].get();
1404
1405   FGAIMultiplayer* mp = new FGAIMultiplayer;
1406   mp->setPath(modelName.c_str());
1407   mp->setCallSign(callsign);
1408   mMultiPlayerMap[callsign] = mp;
1409
1410   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai-model");
1411   if (aiMgr) {
1412     aiMgr->attach(mp);
1413
1414     /// FIXME: that must follow the attach ATM ...
1415     for (unsigned i = 0; i < numProperties; ++i)
1416       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1417   }
1418
1419   return mp;
1420 }
1421
1422 FGAIMultiplayer*
1423 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1424 {
1425   if (0 < mMultiPlayerMap.count(callsign))
1426     return mMultiPlayerMap[callsign].get();
1427   else
1428     return 0;
1429 }
1430
1431 void
1432 FGMultiplayMgr::findProperties()
1433 {
1434   if (!mPropertiesChanged) {
1435     return;
1436   }
1437   
1438   mPropertiesChanged = false;
1439   
1440   for (unsigned i = 0; i < numProperties; ++i) {
1441       const char* name = sIdPropertyList[i].name;
1442       SGPropertyNode* pNode = globals->get_props()->getNode(name);
1443       if (!pNode) {
1444         continue;
1445       }
1446       
1447       int id = sIdPropertyList[i].id;
1448       if (mPropertyMap.find(id) != mPropertyMap.end()) {
1449         continue; // already activated
1450       }
1451       
1452       mPropertyMap[id] = pNode;
1453       SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());
1454     }
1455 }