]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Make sure 'make dist' keeps working.
[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     if (rxPort <= 0)
251       rxPort = txPort;
252   }
253   if (rxPort <= 0) {
254     SG_LOG(SG_NETWORK, SG_ALERT,
255       "FGMultiplayMgr - No receiver port, Multiplayermode disabled");
256     return (false);
257   }
258   if (mCallsign.empty())
259     mCallsign = "JohnDoe"; // FIXME: use getpwuid
260   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
261   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
262   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
263   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
264   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
265   Close(); // Should Init be called twice, close Socket first
266            // A memory leak was reported here by valgrind
267   mSocket = new netSocket();
268   if (!mSocket->open(false)) {
269     SG_LOG( SG_NETWORK, SG_ALERT,
270             "FGMultiplayMgr::init - Failed to create data socket" );
271     return false;
272   }
273   mSocket->setBlocking(false);
274   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
275     perror("bind");
276     SG_LOG( SG_NETWORK, SG_ALERT,
277             "FGMultiplayMgr::Open - Failed to bind receive socket" );
278     return false;
279   }
280   mInitialised = true;
281   return true;
282 } // FGMultiplayMgr::init()
283 //////////////////////////////////////////////////////////////////////
284
285 //////////////////////////////////////////////////////////////////////
286 //
287 //  Closes and deletes the local player object. Closes
288 //  and deletes the tx socket. Resets the object state to unitialised.
289 //
290 //////////////////////////////////////////////////////////////////////
291 void
292 FGMultiplayMgr::Close (void) 
293 {
294   mMultiPlayerMap.clear();
295
296   if (mSocket) {
297     mSocket->close();
298     delete mSocket;
299     mSocket = 0;
300   }
301   mInitialised = false;
302 } // FGMultiplayMgr::Close(void)
303 //////////////////////////////////////////////////////////////////////
304
305 //////////////////////////////////////////////////////////////////////
306 //
307 //  Description: Sends the position data for the local position.
308 //
309 //////////////////////////////////////////////////////////////////////
310 void
311 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
312 {
313   if ((! mInitialised) || (! mHaveServer))
314         return;
315   if (! mHaveServer) {
316     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - no server");
317     return;
318   }
319
320   T_PositionMsg PosMsg;
321   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
322   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
323   
324   PosMsg.time = XDR_encode_double (motionInfo.time);
325   PosMsg.lag = XDR_encode_double (motionInfo.lag);
326   for (unsigned i = 0 ; i < 3; ++i)
327     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
328   SGVec3f angleAxis;
329   motionInfo.orientation.getAngleAxis(angleAxis);
330   for (unsigned i = 0 ; i < 3; ++i)
331     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
332   for (unsigned i = 0 ; i < 3; ++i)
333     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
334   for (unsigned i = 0 ; i < 3; ++i)
335     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
336   for (unsigned i = 0 ; i < 3; ++i)
337     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
338   for (unsigned i = 0 ; i < 3; ++i)
339     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
340
341   char Msg[MAX_PACKET_SIZE];
342   memcpy(Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
343   
344   char* ptr = Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg);
345   std::vector<FGPropertyData*>::const_iterator it;
346   it = motionInfo.properties.begin();
347   //cout << "OUTPUT PROPERTIES\n";
348   while (it != motionInfo.properties.end()
349          && ptr + 2 * sizeof(xdr_data_t) < (Msg + MAX_PACKET_SIZE)) {
350              
351     // First elements is the ID
352     xdr_data_t xdr = XDR_encode_uint32((*it)->id);
353     memcpy(ptr, &xdr, sizeof(xdr_data_t));
354     ptr += sizeof(xdr_data_t);
355     
356     // The actual data representation depends on the type
357     switch ((*it)->type) {
358       case SGPropertyNode::INT:        
359       case SGPropertyNode::BOOL:        
360       case SGPropertyNode::LONG:        
361         xdr = XDR_encode_uint32((*it)->int_value);
362         memcpy(ptr, &xdr, sizeof(xdr_data_t));
363         ptr += sizeof(xdr_data_t);
364         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
365         break;
366       case SGPropertyNode::FLOAT:
367       case SGPropertyNode::DOUBLE:
368         xdr = XDR_encode_float((*it)->float_value);;
369         memcpy(ptr, &xdr, sizeof(xdr_data_t));
370         ptr += sizeof(xdr_data_t);
371         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
372         break;
373       case SGPropertyNode::STRING:
374       case SGPropertyNode::UNSPECIFIED:
375         {
376           // String is complicated. It consists of
377           // The length of the string
378           // The string itself
379           // Padding to the nearest 4-bytes.        
380           const char* lcharptr = (*it)->string_value;
381           
382           if (lcharptr != 0)
383           {
384             // Add the length         
385             ////cout << "String length: " << strlen(lcharptr) << "\n";
386             uint32_t len = strlen(lcharptr);
387             // XXX This should not be using 4 bytes per character!
388             if (ptr + (1 + len + (4 - len % 4)) * sizeof (xdr_data_t)
389                 >= (Msg + MAX_PACKET_SIZE))
390                 goto escape;
391             //cout << "String length unint32: " << len << "\n";
392             xdr = XDR_encode_uint32(len);
393             memcpy(ptr, &xdr, sizeof(xdr_data_t));
394             ptr += sizeof(xdr_data_t);
395             
396             if (len != 0)
397             {
398
399               // Now the text itself
400               // XXX This should not be using 4 bytes per character!
401               int lcount = 0;
402               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
403               {
404                 xdr = XDR_encode_int8(*lcharptr);
405                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
406                 ptr += sizeof(xdr_data_t);
407                 lcharptr++;
408                 lcount++;          
409               }
410
411               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
412
413               // Now pad if required
414               while ((lcount % 4) != 0)
415               {
416                 xdr = XDR_encode_int8(0);
417                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
418                 ptr += sizeof(xdr_data_t);
419                 lcount++;          
420                 //cout << "0";
421               }
422               
423               //cout << "\n";
424             }
425           }
426           else
427           {
428             // Nothing to encode
429             xdr = XDR_encode_uint32(0);
430             memcpy(ptr, &xdr, sizeof(xdr_data_t));
431             ptr += sizeof(xdr_data_t);
432             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
433           }
434            
435         }
436         break;
437         
438       default:
439         //cout << " Unknown Type: " << (*it)->type << "\n";
440         xdr = XDR_encode_float((*it)->float_value);;
441         memcpy(ptr, &xdr, sizeof(xdr_data_t));
442         ptr += sizeof(xdr_data_t);
443         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
444         break;
445     }
446         
447     ++it;
448   }
449 escape:
450   
451   T_MsgHdr MsgHdr;
452   FillMsgHdr(&MsgHdr, POS_DATA_ID, ptr - Msg);
453   memcpy(Msg, &MsgHdr, sizeof(T_MsgHdr));
454
455   mSocket->sendto(Msg, ptr - Msg, 0, &mServer);
456   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
457 } // FGMultiplayMgr::SendMyPosition()
458 //////////////////////////////////////////////////////////////////////
459
460 //////////////////////////////////////////////////////////////////////
461 //
462 //  Name: SendTextMessage
463 //  Description: Sends a message to the player. The message must
464 //  contain a valid and correctly filled out header and optional
465 //  message body.
466 //
467 //////////////////////////////////////////////////////////////////////
468 void
469 FGMultiplayMgr::SendTextMessage(const string &MsgText)
470 {
471   if (!mInitialised || !mHaveServer)
472     return;
473
474   T_MsgHdr MsgHdr;
475   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
476   //////////////////////////////////////////////////
477   // Divide the text string into blocks that fit
478   // in the message and send the blocks.
479   //////////////////////////////////////////////////
480   unsigned iNextBlockPosition = 0;
481   T_ChatMsg ChatMsg;
482   
483   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
484   while (iNextBlockPosition < MsgText.length()) {
485     strncpy (ChatMsg.Text, 
486              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
487              MAX_CHAT_MSG_LEN);
488     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
489     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
490     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
491     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
492     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
493
494   }
495   
496   
497 } // FGMultiplayMgr::SendTextMessage ()
498 //////////////////////////////////////////////////////////////////////
499
500 //////////////////////////////////////////////////////////////////////
501 //
502 //  Name: ProcessData
503 //  Description: Processes data waiting at the receive socket. The
504 //  processing ends when there is no more data at the socket.
505 //  
506 //////////////////////////////////////////////////////////////////////
507 void
508 FGMultiplayMgr::Update(void) 
509 {
510   if (!mInitialised)
511     return;
512
513   /// Just for expiry
514   SGTimeStamp timestamper;
515   timestamper.stamp();
516   long stamp = timestamper.get_seconds();
517
518   //////////////////////////////////////////////////
519   //  Read the receive socket and process any data
520   //////////////////////////////////////////////////
521   int bytes;
522   do {
523     char Msg[MAX_PACKET_SIZE];
524     //////////////////////////////////////////////////
525     //  Although the recv call asks for 
526     //  MAX_PACKET_SIZE of data, the number of bytes
527     //  returned will only be that of the next
528     //  packet waiting to be processed.
529     //////////////////////////////////////////////////
530     netAddress SenderAddress;
531     bytes = mSocket->recvfrom(Msg, sizeof(Msg), 0, &SenderAddress);
532     //////////////////////////////////////////////////
533     //  no Data received
534     //////////////////////////////////////////////////
535     if (bytes <= 0) {
536       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
537         perror("FGMultiplayMgr::MP_ProcessData");
538       break;
539     }
540     if (bytes <= sizeof(T_MsgHdr)) {
541       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
542               << "received message with insufficient data" );
543       break;
544     }
545     //////////////////////////////////////////////////
546     //  Read header
547     //////////////////////////////////////////////////
548     T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
549     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
550     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
551     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
552     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
553     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
554     if (MsgHdr->Magic != MSG_MAGIC) {
555       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
556               << "message has invalid magic number!" );
557       break;
558     }
559     if (MsgHdr->Version != PROTO_VER) {
560       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
561               << "message has invalid protocoll number!" );
562       break;
563     }
564     if (MsgHdr->MsgLen != bytes) {
565       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
566               << "message has invalid length!" );
567       break;
568     }
569     //////////////////////////////////////////////////
570     //  Process messages
571     //////////////////////////////////////////////////
572     switch (MsgHdr->MsgId) {
573     case CHAT_MSG_ID:
574       ProcessChatMsg(Msg, SenderAddress);
575       break;
576     case POS_DATA_ID:
577       ProcessPosMsg(Msg, SenderAddress, bytes, stamp);
578       break;
579     case UNUSABLE_POS_DATA_ID:
580     case OLD_OLD_POS_DATA_ID:
581     case OLD_PROP_MSG_ID:
582     case OLD_POS_DATA_ID:
583       break;
584     default:
585       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
586               << "Unknown message Id received: " << MsgHdr->MsgId );
587       break;
588     }
589   } while (bytes > 0);
590
591   // check for expiry
592   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
593   while (it != mMultiPlayerMap.end()) {
594     if (it->second->getLastTimestamp() + 10 < stamp) {
595       std::string name = it->first;
596       it->second->setDie(true);
597       mMultiPlayerMap.erase(it);
598       it = mMultiPlayerMap.upper_bound(name);
599     } else
600       ++it;
601   }
602 } // FGMultiplayMgr::ProcessData(void)
603 //////////////////////////////////////////////////////////////////////
604
605 //////////////////////////////////////////////////////////////////////
606 //
607 //  handle a position message
608 //
609 //////////////////////////////////////////////////////////////////////
610 void
611 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
612                               unsigned len, long stamp)
613 {
614   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
615   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
616     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
617             << "Position message received with insufficient data" );
618     return;
619   }
620   T_PositionMsg* PosMsg = (T_PositionMsg *)(Msg + sizeof(T_MsgHdr));
621   FGExternalMotionData motionInfo;
622   motionInfo.time = XDR_decode_double(PosMsg->time);
623   motionInfo.lag = XDR_decode_double(PosMsg->lag);
624   for (unsigned i = 0; i < 3; ++i)
625     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
626   SGVec3f angleAxis;
627   for (unsigned i = 0; i < 3; ++i)
628     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
629   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
630   for (unsigned i = 0; i < 3; ++i)
631     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
632   for (unsigned i = 0; i < 3; ++i)
633     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
634   for (unsigned i = 0; i < 3; ++i)
635     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
636   for (unsigned i = 0; i < 3; ++i)
637     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
638
639
640   //cout << "INPUT MESSAGE\n";
641   xdr_data_t* xdr = (xdr_data_t*) 
642                    (Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
643   while ((char*)xdr < Msg + len) {
644     FGPropertyData* pData = new FGPropertyData;
645     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
646     
647     // First element is always the ID
648     pData->id = XDR_decode_uint32(*xdr);
649     //cout << pData->id << " ";
650     xdr++;
651     
652     // Check the ID actually exists and get the type
653     unsigned i = 0;
654     bool found = false;
655     while (FGMultiplayMgr::sIdPropertyList[i].name) 
656     {
657       if (sIdPropertyList[i].id == pData->id)
658       {
659         found = true;
660         pData->type = sIdPropertyList[i].type;
661       } 
662       
663       i++;
664     }
665     
666     if (found == true)
667     {
668       // How we decode the remainder of the property depends on the type
669       switch (pData->type) {
670         case SGPropertyNode::INT:        
671         case SGPropertyNode::BOOL:
672         case SGPropertyNode::LONG:        
673           pData->int_value = XDR_decode_uint32(*xdr);
674           xdr++;
675           //cout << pData->int_value << "\n";
676           break;
677         case SGPropertyNode::FLOAT:
678         case SGPropertyNode::DOUBLE:
679           pData->float_value = XDR_decode_float(*xdr);
680           xdr++;
681           //cout << pData->float_value << "\n";
682           break;
683         case SGPropertyNode::STRING:
684         case SGPropertyNode::UNSPECIFIED:
685           {
686             // String is complicated. It consists of
687             // The length of the string
688             // The string itself
689             // Padding to the nearest 4-bytes.    
690             uint32_t length = XDR_decode_uint32(*xdr);
691             xdr++;
692             //cout << length << " ";
693
694             if ((length > 0) && (length < MAX_TEXT_SIZE))
695             {
696               pData->string_value = new char[length + 1];
697               //cout << " String: ";
698
699               for (int i = 0; i < length; i++)
700               {
701                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
702                 xdr++;
703                 //cout << pData->string_value[i];
704               }
705
706               pData->string_value[length] = '\0';
707
708               // Now handle the padding
709               while ((length % 4) != 0)
710               {
711                 xdr++;
712                 length++;
713                 //cout << "0";
714               }
715             }
716             else
717             {
718               pData->string_value = new char[1];
719               pData->string_value[0] = '\0';
720             }
721
722             //cout << "\n";
723           }
724           break;
725
726         default:
727           pData->float_value = XDR_decode_float(*xdr);
728           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
729           xdr++;
730           break;
731       }            
732
733       motionInfo.properties.push_back(pData);
734     }
735     else
736     {
737       // We failed to find the property. We'll try the next packet immediately.
738       //cout << " Unknown\n";
739     }
740   }
741   
742   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
743   if (!mp)
744     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
745   mp->addMotionInfo(motionInfo, stamp);
746 } // FGMultiplayMgr::ProcessPosMsg()
747 //////////////////////////////////////////////////////////////////////
748
749 //////////////////////////////////////////////////////////////////////
750 //
751 //  handle a chat message
752 //  FIXME: display chat message withi flightgear
753 //
754 //////////////////////////////////////////////////////////////////////
755 void
756 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
757 {
758   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
759   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
760     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
761             << "Chat message received with insufficient data" );
762     return;
763   }
764   
765   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
766   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
767           MsgHdr->MsgLen - sizeof(T_MsgHdr));
768   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
769   
770   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
771   SG_LOG (SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
772            << " " << MsgBuf);
773
774   delete [] MsgBuf;
775 } // FGMultiplayMgr::ProcessChatMsg ()
776 //////////////////////////////////////////////////////////////////////
777
778 void
779 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
780 {
781   uint32_t len;
782   switch (MsgId) {
783   case CHAT_MSG_ID:
784     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
785     break;
786   case POS_DATA_ID:
787     len = _len;
788     break;
789   default:
790     len = sizeof(T_MsgHdr);
791     break;
792   }
793   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
794   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
795   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
796   MsgHdr->MsgLen          = XDR_encode_uint32(len);
797   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
798   MsgHdr->ReplyPort       = 0; // now
799   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
800   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
801 }
802
803 FGAIMultiplayer*
804 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
805                                const std::string& modelName)
806 {
807   if (0 < mMultiPlayerMap.count(callsign))
808     return mMultiPlayerMap[callsign].get();
809
810   FGAIMultiplayer* mp = new FGAIMultiplayer;
811   mp->setPath(modelName.c_str());
812   mp->setCallSign(callsign);
813   mMultiPlayerMap[callsign] = mp;
814
815   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
816   if (aiMgr) {
817     aiMgr->attach(mp);
818
819     /// FIXME: that must follow the attach ATM ...
820     unsigned i = 0;
821     while (sIdPropertyList[i].name) {
822       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
823       ++i;
824     }
825   }
826
827   return mp;
828 }
829
830 FGAIMultiplayer*
831 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
832 {
833   if (0 < mMultiPlayerMap.count(callsign))
834     return mMultiPlayerMap[callsign].get();
835   else
836     return 0;
837 }