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