]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[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-connect"
372 //  args:
373 //  server: servername to connect (mandatory)
374 //  txport: outgoing port number (default: 5000)
375 //  rxport: incoming port number (default: 5000)
376 //////////////////////////////////////////////////////////////////////
377 static bool do_multiplayer_connect(const SGPropertyNode * arg) {
378         FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
379         if (!self) {
380                 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
381                 return false;
382         }
383
384         string servername = arg->getStringValue("servername", "");
385         if (servername.empty()) {
386                 SG_LOG(SG_NETWORK, SG_WARN,
387                                 "do_multiplayer.connect: no server name given, command ignored.");
388                 return false;
389         }
390         int port = arg->getIntValue("rxport", -1);
391         if (port > 0 && port <= 0xffff) {
392                 fgSetInt("/sim/multiplay/rxport", port);
393         }
394
395         port = arg->getIntValue("txport", -1);
396         if (port > 0 && port <= 0xffff) {
397                 fgSetInt("/sim/multiplay/txport", port);
398         }
399
400         servername = servername.substr(0, servername.find_first_of(' '));
401         fgSetString("/sim/multiplay/txhost", servername);
402         self->reinit();
403         return true;
404 }
405
406 //////////////////////////////////////////////////////////////////////
407 //
408 //  handle command "multiplayer-disconnect"
409 //  disconnect args:
410 //  none
411 //////////////////////////////////////////////////////////////////////
412 static bool do_multiplayer_disconnect(const SGPropertyNode * arg) {
413         FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
414         if (!self) {
415                 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
416                 return false;
417         }
418
419         fgSetString("/sim/multiplay/txhost", "");
420         self->reinit();
421         return true;
422 }
423
424 //////////////////////////////////////////////////////////////////////
425 //
426 //  handle command "multiplayer-refreshserverlist"
427 //  refreshserverlist args:
428 //  none
429 //
430 //////////////////////////////////////////////////////////////////////
431 static bool do_multiplayer_refreshserverlist(const SGPropertyNode * arg) {
432         FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
433         if (!self) {
434                 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
435                 return false;
436         }
437
438     FGHTTPClient* http = globals->get_subsystem<FGHTTPClient>();
439         if (!http) {
440                 SG_LOG(SG_IO, SG_ALERT,
441                                 "do_multiplayer.refreshserverlist: HTTP client not running");
442                 return false;
443         }
444
445         string url(
446                         fgGetString("/sim/multiplay/serverlist-url",
447                                         "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
448
449         if (url.empty()) {
450                 SG_LOG(SG_IO, SG_ALERT,
451                                 "do_multiplayer.refreshserverlist: no URL given");
452                 return false;
453         }
454
455         SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
456         SGPropertyNode *completeNode = fgGetNode("/sim/multiplay/got-servers", true);
457         SGPropertyNode *failureNode = fgGetNode("/sim/multiplay/get-servers-failure", true);
458         RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
459         req->setCompletionProp(completeNode);
460         req->setFailedProp(failureNode);
461         completeNode->setBoolValue(false);
462         failureNode->setBoolValue(false);
463         http->makeRequest(req);
464         return true;
465 }
466
467 //////////////////////////////////////////////////////////////////////
468 //
469 //  MultiplayMgr constructor
470 //
471 //////////////////////////////////////////////////////////////////////
472 FGMultiplayMgr::FGMultiplayMgr() 
473 {
474   mInitialised   = false;
475   mHaveServer    = false;
476   mListener = NULL;
477   globals->get_commands()->addCommand("multiplayer-connect", do_multiplayer_connect);
478   globals->get_commands()->addCommand("multiplayer-disconnect", do_multiplayer_disconnect);
479   globals->get_commands()->addCommand("multiplayer-refreshserverlist", do_multiplayer_refreshserverlist);
480 } // FGMultiplayMgr::FGMultiplayMgr()
481 //////////////////////////////////////////////////////////////////////
482
483 //////////////////////////////////////////////////////////////////////
484 //
485 //  MultiplayMgr destructor
486 //
487 //////////////////////////////////////////////////////////////////////
488 FGMultiplayMgr::~FGMultiplayMgr() 
489 {
490    globals->get_commands()->removeCommand("multiplayer-connect");
491    globals->get_commands()->removeCommand("multiplayer-disconnect");
492    globals->get_commands()->removeCommand("multiplayer-refreshserverlist");
493 } // FGMultiplayMgr::~FGMultiplayMgr()
494 //////////////////////////////////////////////////////////////////////
495
496 //////////////////////////////////////////////////////////////////////
497 //
498 //  Initialise object
499 //
500 //////////////////////////////////////////////////////////////////////
501 void
502 FGMultiplayMgr::init (void) 
503 {
504   //////////////////////////////////////////////////
505   //  Initialise object if not already done
506   //////////////////////////////////////////////////
507   if (mInitialised) {
508     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
509     return;
510   }
511
512   SGPropertyNode* propOnline = fgGetNode("/sim/multiplay/online", true);
513   propOnline->setBoolValue(false);
514   propOnline->setAttribute(SGPropertyNode::PRESERVE, true);
515
516   //////////////////////////////////////////////////
517   //  Set members from property values
518   //////////////////////////////////////////////////
519   short rxPort = fgGetInt("/sim/multiplay/rxport");
520   string rxAddress = fgGetString("/sim/multiplay/rxhost");
521   short txPort = fgGetInt("/sim/multiplay/txport", 5000);
522   string txAddress = fgGetString("/sim/multiplay/txhost");
523   
524   int hz = fgGetInt("/sim/multiplay/tx-rate-hz", 10);
525   if (hz < 1) {
526     hz = 10;
527   }
528   
529   mDt = 1.0 / hz;
530   mTimeUntilSend = 0.0;
531   
532   mCallsign = fgGetString("/sim/multiplay/callsign");
533   fgGetNode("/sim/multiplay/callsign", true)->setAttribute(SGPropertyNode::PRESERVE, true);
534     
535   if ((!txAddress.empty()) && (txAddress!="0")) {
536     mServer.set(txAddress.c_str(), txPort);
537     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
538       mHaveServer = false;
539       SG_LOG(SG_NETWORK, SG_ALERT,
540         "Cannot enable multiplayer mode: resolving MP server address '"
541         << txAddress << "' failed.");
542       return;
543     } else {
544       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
545       mHaveServer = true;
546     }
547     if (rxPort <= 0)
548       rxPort = txPort;
549   } else {
550     SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - multiplayer mode disabled (no MP server specificed).");
551     return;
552   }
553
554   if (rxPort <= 0) {
555     SG_LOG(SG_NETWORK, SG_ALERT,
556       "Cannot enable multiplayer mode: No receiver port specified.");
557     return;
558   }
559   if (mCallsign.empty())
560     mCallsign = "JohnDoe"; // FIXME: use getpwuid
561   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
562   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
563   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
564   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
565   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
566   
567   mSocket.reset(new simgear::Socket());
568   if (!mSocket->open(false)) {
569     SG_LOG( SG_NETWORK, SG_ALERT,
570             "Cannot enable multiplayer mode: creating data socket failed." );
571     return;
572   }
573   mSocket->setBlocking(false);
574   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
575     SG_LOG( SG_NETWORK, SG_ALERT,
576             "Cannot enable multiplayer mode: binding receive socket failed. "
577             << strerror(errno) << "(errno " << errno << ")");
578     return;
579   }
580   
581   mPropertiesChanged = true;
582   mListener = new MPPropertyListener(this);
583   globals->get_props()->addChangeListener(mListener, false);
584   
585   fgSetBool("/sim/multiplay/online", true);
586   mInitialised = true;
587
588   SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer mode active!");
589
590   if (!fgGetBool("/sim/ai/enabled"))
591   {
592       // multiplayer depends on AI module
593       fgSetBool("/sim/ai/enabled", true);
594   }
595 } // FGMultiplayMgr::init()
596 //////////////////////////////////////////////////////////////////////
597
598 //////////////////////////////////////////////////////////////////////
599 //
600 //  Closes and deletes the local player object. Closes
601 //  and deletes the tx socket. Resets the object state to unitialised.
602 //
603 //////////////////////////////////////////////////////////////////////
604 void
605 FGMultiplayMgr::shutdown (void) 
606 {
607   fgSetBool("/sim/multiplay/online", false);
608   
609   if (mSocket.get()) {
610     mSocket->close();
611     mSocket.reset(); 
612   }
613   
614   MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
615     end = mMultiPlayerMap.end();
616   for (; it != end; ++it) {
617     it->second->setDie(true);
618   }
619   mMultiPlayerMap.clear();
620   
621   if (mListener) {
622     globals->get_props()->removeChangeListener(mListener);
623     delete mListener;
624     mListener = NULL;
625   }
626   
627   mInitialised = false;
628 } // FGMultiplayMgr::Close(void)
629 //////////////////////////////////////////////////////////////////////
630
631 void
632 FGMultiplayMgr::reinit()
633 {
634   shutdown();
635   init();
636 }
637
638 //////////////////////////////////////////////////////////////////////
639 //
640 //  Description: Sends the position data for the local position.
641 //
642 //////////////////////////////////////////////////////////////////////
643
644 /**
645  * The buffer that holds a multi-player message, suitably aligned.
646  */
647 union FGMultiplayMgr::MsgBuf
648 {
649     MsgBuf()
650     {
651         memset(&Msg, 0, sizeof(Msg));
652     }
653
654     T_MsgHdr* msgHdr()
655     {
656         return &Header;
657     }
658
659     const T_MsgHdr* msgHdr() const
660     {
661         return reinterpret_cast<const T_MsgHdr*>(&Header);
662     }
663
664     T_PositionMsg* posMsg()
665     {
666         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
667     }
668
669     const T_PositionMsg* posMsg() const
670     {
671         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
672     }
673
674     xdr_data_t* properties()
675     {
676         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
677                                              + sizeof(T_PositionMsg));
678     }
679
680     const xdr_data_t* properties() const
681     {
682         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
683                                                    + sizeof(T_PositionMsg));
684     }
685     /**
686      * The end of the properties buffer.
687      */
688     xdr_data_t* propsEnd()
689     {
690         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
691     };
692
693     const xdr_data_t* propsEnd() const
694     {
695         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
696     };
697     /**
698      * The end of properties actually in the buffer. This assumes that
699      * the message header is valid.
700      */
701     xdr_data_t* propsRecvdEnd()
702     {
703         return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
704     }
705
706     const xdr_data_t* propsRecvdEnd() const
707     {
708         return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
709     }
710     
711     xdr_data2_t double_val;
712     char Msg[MAX_PACKET_SIZE];
713     T_MsgHdr Header;
714 };
715
716 bool
717 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
718 {
719     // check for corrupted data (NaNs)
720     bool isCorrupted = false;
721     isCorrupted |= ((SGMisc<double>::isNaN(motionInfo.time           )) ||
722                     (SGMisc<double>::isNaN(motionInfo.lag            )) ||
723                     (osg::isNaN(motionInfo.orientation(3) )));
724     for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
725     {
726         isCorrupted |= ((osg::isNaN(motionInfo.position(i)      ))||
727                         (osg::isNaN(motionInfo.orientation(i)   ))||
728                         (osg::isNaN(motionInfo.linearVel(i))    )||
729                         (osg::isNaN(motionInfo.angularVel(i))   )||
730                         (osg::isNaN(motionInfo.linearAccel(i))  )||
731                         (osg::isNaN(motionInfo.angularAccel(i)) ));
732     }
733     return !isCorrupted;
734 }
735
736 void
737 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
738 {
739   if ((! mInitialised) || (! mHaveServer))
740         return;
741
742   if (! mHaveServer) {
743       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
744       return;
745   }
746
747   if (!isSane(motionInfo))
748   {
749       // Current local data is invalid (NaN), so stop MP transmission.
750       // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
751       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
752               << "Local data is invalid (NaN). Data not transmitted.");
753       return;
754   }
755
756   static MsgBuf msgBuf;
757   static unsigned msgLen = 0;
758   T_PositionMsg* PosMsg = msgBuf.posMsg();
759
760   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
761   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
762   if (fgGetBool("/sim/freeze/replay-state", true)&&
763       fgGetBool("/sim/multiplay/freeze-on-replay",true))
764   {
765       // do not send position updates during replay
766       for (unsigned i = 0 ; i < 3; ++i)
767       {
768           // no movement during replay
769           PosMsg->linearVel[i] = XDR_encode_float (0.0);
770           PosMsg->angularVel[i] = XDR_encode_float (0.0);
771           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
772           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
773       }
774       // all other data remains unchanged (resend last state) 
775   }
776   else
777   {
778       PosMsg->time = XDR_encode_double (motionInfo.time);
779       PosMsg->lag = XDR_encode_double (motionInfo.lag);
780       for (unsigned i = 0 ; i < 3; ++i)
781         PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
782       SGVec3f angleAxis;
783       motionInfo.orientation.getAngleAxis(angleAxis);
784       for (unsigned i = 0 ; i < 3; ++i)
785         PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
786       if (fgGetBool("/sim/crashed",true))
787       {
788         for (unsigned i = 0 ; i < 3; ++i)
789         {
790           // no speed or acceleration sent when crashed, for better mp patch
791           PosMsg->linearVel[i] = XDR_encode_float (0.0);
792           PosMsg->angularVel[i] = XDR_encode_float (0.0);
793           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
794           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
795         }
796       }
797       else
798       {
799         //including speed up time in velocity and acceleration
800         double timeAccel = fgGetDouble("/sim/speed-up");
801         for (unsigned i = 0 ; i < 3; ++i)
802           PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i) * timeAccel);
803         for (unsigned i = 0 ; i < 3; ++i)
804           PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i) * timeAccel);
805         for (unsigned i = 0 ; i < 3; ++i)
806           PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i) * timeAccel * timeAccel);
807         for (unsigned i = 0 ; i < 3; ++i)
808           PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i) * timeAccel * timeAccel);
809       }
810       xdr_data_t* ptr = msgBuf.properties();
811       std::vector<FGPropertyData*>::const_iterator it;
812       it = motionInfo.properties.begin();
813       //cout << "OUTPUT PROPERTIES\n";
814       xdr_data_t* msgEnd = msgBuf.propsEnd();
815       while (it != motionInfo.properties.end()) {
816
817         if (ptr + 2 >= msgEnd)
818         {
819             SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer packet truncated prop id: " << (*it)->id);
820             break;
821         }
822
823         // First element is the ID. Write it out when we know we have room for
824         // the whole property.
825         xdr_data_t id =  XDR_encode_uint32((*it)->id);
826         // The actual data representation depends on the type
827         switch ((*it)->type) {
828           case simgear::props::INT:
829           case simgear::props::BOOL:
830           case simgear::props::LONG:
831             *ptr++ = id;
832             *ptr++ = XDR_encode_uint32((*it)->int_value);
833             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
834             break;
835           case simgear::props::FLOAT:
836           case simgear::props::DOUBLE:
837             *ptr++ = id;
838             *ptr++ = XDR_encode_float((*it)->float_value);
839             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
840             break;
841           case simgear::props::STRING:
842           case simgear::props::UNSPECIFIED:
843             {
844               // String is complicated. It consists of
845               // The length of the string
846               // The string itself
847               // Padding to the nearest 4-bytes.        
848               const char* lcharptr = (*it)->string_value;
849               
850               if (lcharptr != 0)
851               {
852                 // Add the length         
853                 ////cout << "String length: " << strlen(lcharptr) << "\n";
854                 uint32_t len = strlen(lcharptr);
855                 if (len >= MAX_TEXT_SIZE)
856                 {
857                   len = MAX_TEXT_SIZE - 1;
858                   SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer property truncated at MAX_TEXT_SIZE in string " << (*it)->id);
859                 }
860
861                 // XXX This should not be using 4 bytes per character!
862                 // If there's not enough room for this property, drop it
863                 // on the floor.
864                 if (ptr + 2 + ((len + 3) & ~3) >= msgEnd)
865                 {
866                     SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer property not sent (no room) string " << (*it)->id);
867                     goto escape;
868                 }
869                 //cout << "String length unint32: " << len << "\n";
870                 *ptr++ = id;
871                 *ptr++ = XDR_encode_uint32(len);
872                 if (len != 0)
873                 {
874                   // Now the text itself
875                   // XXX This should not be using 4 bytes per character!
876                   int lcount = 0;
877                   while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
878                   {
879                     if (ptr + 2 >= msgEnd)
880                     {
881                       SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer packet truncated in string " << (*it)->id << " lcount " << lcount);
882                       break;
883                     }
884                     *ptr++ = XDR_encode_int8(*lcharptr);
885                     lcharptr++;
886                     lcount++;          
887                   }
888                   //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
889     
890                   // Now pad if required
891                   while ((lcount % 4) != 0)
892                   {
893                     if (ptr + 2 >= msgEnd)
894                     {
895                       SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer packet truncated in string " << (*it)->id << " lcount " << lcount);
896                       break;
897                     }
898                     *ptr++ = XDR_encode_int8(0);
899                     lcount++;          
900                     //cout << "0";
901                   }
902
903                   //cout << "\n";
904                 }
905               }
906               else
907               {
908                 // Nothing to encode
909                 *ptr++ = id;
910                 *ptr++ = XDR_encode_uint32(0);
911                 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
912               }
913             }
914             break;
915             
916           default:
917             //cout << " Unknown Type: " << (*it)->type << "\n";
918             *ptr++ = id;
919             *ptr++ = XDR_encode_float((*it)->float_value);;
920             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
921             break;
922         }
923             
924         ++it;
925       }
926   escape:
927       msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
928       FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
929   }
930   if (msgLen>0)
931       mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
932   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
933 } // FGMultiplayMgr::SendMyPosition()
934
935 //////////////////////////////////////////////////////////////////////
936
937 //////////////////////////////////////////////////////////////////////
938 //
939 //  Name: SendTextMessage
940 //  Description: Sends a message to the player. The message must
941 //  contain a valid and correctly filled out header and optional
942 //  message body.
943 //
944 //////////////////////////////////////////////////////////////////////
945 void
946 FGMultiplayMgr::SendTextMessage(const string &MsgText)
947 {
948   if (!mInitialised || !mHaveServer)
949     return;
950
951   T_MsgHdr MsgHdr;
952   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
953   //////////////////////////////////////////////////
954   // Divide the text string into blocks that fit
955   // in the message and send the blocks.
956   //////////////////////////////////////////////////
957   unsigned iNextBlockPosition = 0;
958   T_ChatMsg ChatMsg;
959   
960   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
961   while (iNextBlockPosition < MsgText.length()) {
962     strncpy (ChatMsg.Text, 
963              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
964              MAX_CHAT_MSG_LEN);
965     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
966     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
967     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
968     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
969     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
970
971   }
972   
973   
974 } // FGMultiplayMgr::SendTextMessage ()
975 //////////////////////////////////////////////////////////////////////
976
977 //////////////////////////////////////////////////////////////////////
978 //
979 //  Name: ProcessData
980 //  Description: Processes data waiting at the receive socket. The
981 //  processing ends when there is no more data at the socket.
982 //  
983 //////////////////////////////////////////////////////////////////////
984 void
985 FGMultiplayMgr::update(double dt) 
986 {
987   if (!mInitialised)
988     return;
989
990   /// Just for expiry
991   long stamp = SGTimeStamp::now().getSeconds();
992
993   //////////////////////////////////////////////////
994   //  Send if required
995   //////////////////////////////////////////////////
996   mTimeUntilSend -= dt;
997   if (mTimeUntilSend <= 0.0) {
998     Send();
999   }
1000
1001   //////////////////////////////////////////////////
1002   //  Read the receive socket and process any data
1003   //////////////////////////////////////////////////
1004   ssize_t bytes;
1005   do {
1006     MsgBuf msgBuf;
1007     //////////////////////////////////////////////////
1008     //  Although the recv call asks for 
1009     //  MAX_PACKET_SIZE of data, the number of bytes
1010     //  returned will only be that of the next
1011     //  packet waiting to be processed.
1012     //////////////////////////////////////////////////
1013     simgear::IPAddress SenderAddress;
1014     int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
1015                               &SenderAddress);
1016     //////////////////////////////////////////////////
1017     //  no Data received
1018     //////////////////////////////////////////////////
1019     if (RecvStatus == 0)
1020         break;
1021
1022     // socket error reported?
1023     // errno isn't thread-safe - so only check its value when
1024     // socket return status < 0 really indicates a failure.
1025     if ((RecvStatus < 0)&&
1026         ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
1027     {
1028         // ignore "normal" errors
1029         break;
1030     }
1031
1032     if (RecvStatus<0)
1033     {
1034         SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
1035                << strerror(errno) << "(errno " << errno << ")");
1036         break;
1037     }
1038
1039     // status is positive: bytes received
1040     bytes = (ssize_t) RecvStatus;
1041     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
1042       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1043               << "received message with insufficient data" );
1044       break;
1045     }
1046     //////////////////////////////////////////////////
1047     //  Read header
1048     //////////////////////////////////////////////////
1049     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
1050     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
1051     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
1052     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
1053     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
1054     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
1055     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
1056     if (MsgHdr->Magic != MSG_MAGIC) {
1057       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1058               << "message has invalid magic number!" );
1059       break;
1060     }
1061     if (MsgHdr->Version != PROTO_VER) {
1062       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1063               << "message has invalid protocol number!" );
1064       break;
1065     }
1066     if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
1067       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1068              << "message from " << MsgHdr->Callsign << " has invalid length!");
1069       break;
1070     }
1071     //////////////////////////////////////////////////
1072     //  Process messages
1073     //////////////////////////////////////////////////
1074     switch (MsgHdr->MsgId) {
1075     case CHAT_MSG_ID:
1076       ProcessChatMsg(msgBuf, SenderAddress);
1077       break;
1078     case POS_DATA_ID:
1079       ProcessPosMsg(msgBuf, SenderAddress, stamp);
1080       break;
1081     case UNUSABLE_POS_DATA_ID:
1082     case OLD_OLD_POS_DATA_ID:
1083     case OLD_PROP_MSG_ID:
1084     case OLD_POS_DATA_ID:
1085       break;
1086     default:
1087       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1088               << "Unknown message Id received: " << MsgHdr->MsgId );
1089       break;
1090     }
1091   } while (bytes > 0);
1092
1093   // check for expiry
1094   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
1095   while (it != mMultiPlayerMap.end()) {
1096     if (it->second->getLastTimestamp() + 10 < stamp) {
1097       std::string name = it->first;
1098       it->second->setDie(true);
1099       mMultiPlayerMap.erase(it);
1100       it = mMultiPlayerMap.upper_bound(name);
1101     } else
1102       ++it;
1103   }
1104 } // FGMultiplayMgr::ProcessData(void)
1105 //////////////////////////////////////////////////////////////////////
1106
1107 void
1108 FGMultiplayMgr::Send()
1109 {
1110   using namespace simgear;
1111   
1112   findProperties();
1113     
1114   // smooth the send rate, by adjusting based on the 'remainder' time, which
1115   // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
1116   // however.
1117     if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
1118       mTimeUntilSend = mDt + mTimeUntilSend;
1119     } else {
1120       mTimeUntilSend = mDt;
1121     }
1122
1123     double sim_time = globals->get_sim_time_sec();
1124 //    static double lastTime = 0.0;
1125     
1126    // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
1127 //    lastTime = sim_time;
1128     
1129     FlightProperties ifce;
1130
1131     // put together a motion info struct, you will get that later
1132     // from FGInterface directly ...
1133     FGExternalMotionData motionInfo;
1134
1135     // The current simulation time we need to update for,
1136     // note that the simulation time is updated before calling all the
1137     // update methods. Thus it contains the time intervals *end* time.
1138     // The FDM is already run, so the states belong to that time.
1139     motionInfo.time = sim_time;
1140     motionInfo.lag = mDt;
1141
1142     // These are for now converted from lat/lon/alt and euler angles.
1143     // But this should change in FGInterface ...
1144     double lon = ifce.get_Longitude();
1145     double lat = ifce.get_Latitude();
1146     // first the aprioriate structure for the geodetic one
1147     SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
1148     // Convert to cartesion coordinate
1149     motionInfo.position = SGVec3d::fromGeod(geod);
1150     
1151     // The quaternion rotating from the earth centered frame to the
1152     // horizontal local frame
1153     SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
1154     // The orientation wrt the horizontal local frame
1155     float heading = ifce.get_Psi();
1156     float pitch = ifce.get_Theta();
1157     float roll = ifce.get_Phi();
1158     SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
1159     // The orientation of the vehicle wrt the earth centered frame
1160     motionInfo.orientation = qEc2Hl*hlOr;
1161
1162     if (!globals->get_subsystem("flight")->is_suspended()) {
1163       // velocities
1164       motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1165                                                       ifce.get_vBody(),
1166                                                       ifce.get_wBody());
1167       motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1168                                       ifce.get_Q_body(),
1169                                       ifce.get_R_body());
1170       
1171       // accels, set that to zero for now.
1172       // Angular accelerations are missing from the interface anyway,
1173       // linear accelerations are screwed up at least for JSBSim.
1174 //  motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1175 //                                                    ifce.get_V_dot_body(),
1176 //                                                    ifce.get_W_dot_body());
1177       motionInfo.linearAccel = SGVec3f::zeros();
1178       motionInfo.angularAccel = SGVec3f::zeros();
1179     } else {
1180       // if the interface is suspendend, prevent the client from
1181       // wild extrapolations
1182       motionInfo.linearVel = SGVec3f::zeros();
1183       motionInfo.angularVel = SGVec3f::zeros();
1184       motionInfo.linearAccel = SGVec3f::zeros();
1185       motionInfo.angularAccel = SGVec3f::zeros();
1186     }
1187
1188     // now send the properties
1189     PropertyMap::iterator it;
1190     for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1191       FGPropertyData* pData = new FGPropertyData;
1192       pData->id = it->first;
1193       pData->type = findProperty(pData->id)->type;
1194       
1195       switch (pData->type) {
1196         case props::INT:
1197         case props::LONG:
1198         case props::BOOL:
1199           pData->int_value = it->second->getIntValue();
1200           break;
1201         case props::FLOAT:
1202         case props::DOUBLE:
1203           pData->float_value = it->second->getFloatValue();
1204           break;
1205         case props::STRING:
1206         case props::UNSPECIFIED:
1207           {
1208             // FIXME: We assume unspecified are strings for the moment.
1209
1210             const char* cstr = it->second->getStringValue();
1211             int len = strlen(cstr);
1212             
1213             if (len > 0)
1214             {            
1215               pData->string_value = new char[len + 1];
1216               strcpy(pData->string_value, cstr);
1217             }
1218             else
1219             {
1220               // Size 0 - ignore
1221               pData->string_value = 0;            
1222             }
1223
1224             //cout << " Sending property " << pData->id << " " << pData->type << " " <<  pData->string_value << "\n";
1225             break;        
1226           }
1227         default:
1228           // FIXME Currently default to a float. 
1229           //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1230           pData->float_value = it->second->getFloatValue();
1231           break;
1232       }
1233       
1234       motionInfo.properties.push_back(pData);
1235     }
1236
1237     SendMyPosition(motionInfo);
1238 }
1239
1240
1241 //////////////////////////////////////////////////////////////////////
1242 //
1243 //  handle a position message
1244 //
1245 //////////////////////////////////////////////////////////////////////
1246 void
1247 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1248                               const simgear::IPAddress& SenderAddress, long stamp)
1249 {
1250   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1251   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1252     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1253             << "Position message received with insufficient data" );
1254     return;
1255   }
1256   const T_PositionMsg* PosMsg = Msg.posMsg();
1257   FGExternalMotionData motionInfo;
1258   motionInfo.time = XDR_decode_double(PosMsg->time);
1259   motionInfo.lag = XDR_decode_double(PosMsg->lag);
1260   for (unsigned i = 0; i < 3; ++i)
1261     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1262   SGVec3f angleAxis;
1263   for (unsigned i = 0; i < 3; ++i)
1264     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1265   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1266   for (unsigned i = 0; i < 3; ++i)
1267     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1268   for (unsigned i = 0; i < 3; ++i)
1269     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1270   for (unsigned i = 0; i < 3; ++i)
1271     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1272   for (unsigned i = 0; i < 3; ++i)
1273     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1274
1275   // sanity check: do not allow injection of corrupted data (NaNs)
1276   if (!isSane(motionInfo))
1277   {
1278       // drop this message, keep old position until receiving valid data
1279       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1280               << "Position message with invalid data (NaN) received from "
1281               << MsgHdr->Callsign);
1282       return;
1283   }
1284
1285   //cout << "INPUT MESSAGE\n";
1286
1287   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1288   // on 32 bit architectures and 200 bytes on 64 bit, and this
1289   // structure is put directly on the wire. By looking at the padding,
1290   // we can sort through the mess, mostly:
1291   // If padding is 0 (which is not a valid property type), then the
1292   // message was produced by a new client or an old 64 bit client that
1293   // happened to have 0 on the stack;
1294   // Else if the property list starting with the padding word is
1295   // well-formed, then the client is probably an old 32 bit client and
1296   // we'll go with that;
1297   // Else it is an old 64-bit client and properties start after the
1298   // padding.
1299   // There is a chance that we could be fooled by garbage in the
1300   // padding looking like a valid property, so verifyProperties() is
1301   // strict about the validity of the property values.
1302   const xdr_data_t* xdr = Msg.properties();
1303   if (PosMsg->pad != 0) {
1304     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1305       xdr = &PosMsg->pad;
1306     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1307       goto noprops;
1308   }
1309   while (xdr < Msg.propsRecvdEnd()) {
1310     // simgear::props::Type type = simgear::props::UNSPECIFIED;
1311     
1312     // First element is always the ID
1313     unsigned id = XDR_decode_uint32(*xdr);
1314     //cout << pData->id << " ";
1315     xdr++;
1316     
1317     // Check the ID actually exists and get the type
1318     const IdPropertyList* plist = findProperty(id);
1319     
1320     if (plist)
1321     {
1322       FGPropertyData* pData = new FGPropertyData;
1323       pData->id = id;
1324       pData->type = plist->type;
1325       // How we decode the remainder of the property depends on the type
1326       switch (pData->type) {
1327         case simgear::props::INT:
1328         case simgear::props::BOOL:
1329         case simgear::props::LONG:
1330           pData->int_value = XDR_decode_uint32(*xdr);
1331           xdr++;
1332           //cout << pData->int_value << "\n";
1333           break;
1334         case simgear::props::FLOAT:
1335         case simgear::props::DOUBLE:
1336           pData->float_value = XDR_decode_float(*xdr);
1337           xdr++;
1338           //cout << pData->float_value << "\n";
1339           break;
1340         case simgear::props::STRING:
1341         case simgear::props::UNSPECIFIED:
1342           {
1343             // String is complicated. It consists of
1344             // The length of the string
1345             // The string itself
1346             // Padding to the nearest 4-bytes.    
1347             uint32_t length = XDR_decode_uint32(*xdr);
1348             xdr++;
1349             //cout << length << " ";
1350             // Old versions truncated the string but left the length unadjusted.
1351             if (length > MAX_TEXT_SIZE)
1352               length = MAX_TEXT_SIZE;
1353             pData->string_value = new char[length + 1];
1354             //cout << " String: ";
1355             for (unsigned i = 0; i < length; i++)
1356               {
1357                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1358                 xdr++;
1359                 //cout << pData->string_value[i];
1360               }
1361
1362             pData->string_value[length] = '\0';
1363
1364             // Now handle the padding
1365             while ((length % 4) != 0)
1366               {
1367                 xdr++;
1368                 length++;
1369                 //cout << "0";
1370               }
1371             //cout << "\n";
1372           }
1373           break;
1374
1375         default:
1376           pData->float_value = XDR_decode_float(*xdr);
1377           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1378           xdr++;
1379           break;
1380       }
1381
1382       motionInfo.properties.push_back(pData);
1383     }
1384     else
1385     {
1386       // We failed to find the property. We'll try the next packet immediately.
1387       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1388              "message from " << MsgHdr->Callsign << " has unknown property id "
1389              << id); 
1390     }
1391   }
1392  noprops:
1393   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1394   if (!mp)
1395     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1396   mp->addMotionInfo(motionInfo, stamp);
1397 } // FGMultiplayMgr::ProcessPosMsg()
1398 //////////////////////////////////////////////////////////////////////
1399
1400 //////////////////////////////////////////////////////////////////////
1401 //
1402 //  handle a chat message
1403 //  FIXME: display chat message within flightgear
1404 //
1405 //////////////////////////////////////////////////////////////////////
1406 void
1407 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1408                                const simgear::IPAddress& SenderAddress)
1409 {
1410   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1411   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1412     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1413             << "Chat message received with insufficient data" );
1414     return;
1415   }
1416   
1417   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1418   const T_ChatMsg* ChatMsg
1419       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1420   strncpy(chatStr, ChatMsg->Text,
1421           MsgHdr->MsgLen - sizeof(T_MsgHdr));
1422   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1423   
1424   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1425            << " " << chatStr);
1426
1427   delete [] chatStr;
1428 } // FGMultiplayMgr::ProcessChatMsg ()
1429 //////////////////////////////////////////////////////////////////////
1430
1431 void
1432 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1433 {
1434   uint32_t len;
1435   switch (MsgId) {
1436   case CHAT_MSG_ID:
1437     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1438     break;
1439   case POS_DATA_ID:
1440     len = _len;
1441     break;
1442   default:
1443     len = sizeof(T_MsgHdr);
1444     break;
1445   }
1446   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1447   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1448   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1449   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1450   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1451   MsgHdr->ReplyPort       = 0; // now
1452   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1453   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1454 }
1455
1456 FGAIMultiplayer*
1457 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1458                                const std::string& modelName)
1459 {
1460   if (0 < mMultiPlayerMap.count(callsign))
1461     return mMultiPlayerMap[callsign].get();
1462
1463   FGAIMultiplayer* mp = new FGAIMultiplayer;
1464   mp->setPath(modelName.c_str());
1465   mp->setCallSign(callsign);
1466   mMultiPlayerMap[callsign] = mp;
1467
1468   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai-model");
1469   if (aiMgr) {
1470     aiMgr->attach(mp);
1471
1472     /// FIXME: that must follow the attach ATM ...
1473     for (unsigned i = 0; i < numProperties; ++i)
1474       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1475   }
1476
1477   return mp;
1478 }
1479
1480 FGAIMultiplayer*
1481 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1482 {
1483   if (0 < mMultiPlayerMap.count(callsign))
1484     return mMultiPlayerMap[callsign].get();
1485   else
1486     return 0;
1487 }
1488
1489 void
1490 FGMultiplayMgr::findProperties()
1491 {
1492   if (!mPropertiesChanged) {
1493     return;
1494   }
1495   
1496   mPropertiesChanged = false;
1497   
1498   for (unsigned i = 0; i < numProperties; ++i) {
1499       const char* name = sIdPropertyList[i].name;
1500       SGPropertyNode* pNode = globals->get_props()->getNode(name);
1501       if (!pNode) {
1502         continue;
1503       }
1504       
1505       int id = sIdPropertyList[i].id;
1506       if (mPropertyMap.find(id) != mPropertyMap.end()) {
1507         continue; // already activated
1508       }
1509       
1510       mPropertyMap[id] = pNode;
1511       SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());
1512     }
1513 }