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