netConnection.h 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _NETCONNECTION_H_
  23. #define _NETCONNECTION_H_
  24. #ifndef _MPOINT3_H_
  25. #include "math/mPoint3.h"
  26. #endif
  27. #ifndef _NETOBJECT_H_
  28. #include "sim/netObject.h"
  29. #endif
  30. #ifndef _NETSTRINGTABLE_H_
  31. #include "sim/netStringTable.h"
  32. #endif
  33. #ifndef _EVENT_H_
  34. #include "platform/event.h"
  35. #endif
  36. #ifndef _DNET_H_
  37. #include "core/dnet.h"
  38. #endif
  39. #ifndef _H_CONNECTIONSTRINGTABLE
  40. #include "sim/connectionStringTable.h"
  41. #endif
  42. class NetConnection;
  43. class NetObject;
  44. class BitStream;
  45. class ResizeBitStream;
  46. class Stream;
  47. class Point3F;
  48. struct GhostInfo;
  49. struct SubPacketRef; // defined in NetConnection subclass
  50. //#define DEBUG_NET
  51. #ifdef TORQUE_DEBUG_NET
  52. #define DEBUG_LOG(x) if(mLogging){Con::printf x;}
  53. #else
  54. #define DEBUG_LOG(x)
  55. #endif
  56. DECLARE_SCOPE( NetAPI );
  57. //----------------------------------------------------------------------------
  58. class NetEvent;
  59. struct NetEventNote
  60. {
  61. NetEvent *mEvent;
  62. S32 mSeqCount;
  63. NetEventNote *mNextEvent;
  64. };
  65. /// An event to be sent over the network.
  66. ///
  67. /// @note Torque implements two methods of network data passing; this is one of them.
  68. /// See NetConnection for details of the other, which is referred to as ghosting.
  69. ///
  70. /// Torque's network layer lets you pass events to/from the server. There are three
  71. /// types of events:
  72. /// - <b>Unguaranteed events</b> are events which are sent once. If they don't
  73. /// make it through the link, they are not resent. This is good for quick,
  74. /// frequent status updates which are of transient interest, like position
  75. /// updates or voice communication.
  76. /// - <b>Guaranteed events</b> are events which are guaranteed to be
  77. /// delivered. If they don't make it through the link, they are sent as
  78. /// needed. This is good for important, one-time information,
  79. /// like which team a user wants to play on, or the current weather.
  80. /// - <b>GuaranteedOrdered events</b> are events which are guaranteed not
  81. /// only to be delivered, but to be delivered in order. This is good for
  82. /// information which is not only important, but also order-critical, like
  83. /// chat messages.
  84. ///
  85. /// There are 6 methods that you need to implement if you want to make a
  86. /// basic NetEvent subclass, and 2 macros you need to call.
  87. ///
  88. /// @code
  89. /// // A simple NetEvent to transmit a string over the network.
  90. /// // This is based on the code in netTest.cc
  91. /// class SimpleMessageEvent : public NetEvent
  92. /// {
  93. /// typedef NetEvent Parent;
  94. /// char *msg;
  95. /// public:
  96. /// SimpleMessageEvent(const char *message = NULL);
  97. /// ~SimpleMessageEvent();
  98. ///
  99. /// virtual void pack (NetConnection *conn, BitStream *bstream);
  100. /// virtual void write (NetConnection *conn, BitStream *bstream);
  101. /// virtual void unpack (NetConnection *conn, BitStream *bstream);
  102. /// virtual void process(NetConnection *conn);
  103. ///
  104. /// DECLARE_CONOBJECT(SimpleMessageEvent);
  105. /// };
  106. ///
  107. /// IMPLEMENT_CO_NETEVENT_V1(SimpleMessageEvent);
  108. /// @endcode
  109. ///
  110. /// Notice the two macros which we call. The first, DECLARE_CONOBJECT() is there
  111. /// because we're a ConsoleObject. The second, IMPLEMENT_CO_NETEVENT_V1(), is there
  112. /// to register this event type with Torque's networking layer, so that it can be
  113. /// properly transmitted over the wire. There are three macros which you might use:
  114. /// - <b>IMPLEMENT_CO_NETEVENT_V1</b>, which indicates an event which may be sent
  115. /// in either direction, from the client to the server, or from the server to the
  116. /// client.
  117. /// - <b>IMPLEMENT_CO_CLIENTEVENT_V1</b>, which indicates an event which may only
  118. /// be sent to the client.
  119. /// - <b>IMPLEMENT_CO_SERVEREVENT_V1</b>, which indicates an event which may only
  120. /// be sent to the server.
  121. ///
  122. /// Choosing the right macro is a good way to make your game more resistant to hacking; for instance,
  123. /// PathManager events are marked as CLIENTEVENTs, because they would cause the server to crash if
  124. /// a client sent them.
  125. ///
  126. /// @note Torque allows you to call NetConnection::setLastError() on the NetConnection passed to
  127. /// your NetEvent. You can cause the connection to abort if invalid data is received, specifying
  128. /// a reason to the user.
  129. ///
  130. /// Now, the 6 methods which we have above; the constructor and destructor need only do
  131. /// whatever book-keeping is needed for your specific implementation. In our case, we
  132. /// just need to allocate/deallocate the space for our string:
  133. ///
  134. /// @code
  135. /// SimpleMessageEvent::SimpleMessageEvent(const char *message = NULL)
  136. /// {
  137. /// // If we wanted to make this not be a GuaranteedOrdered event, we'd
  138. /// // put a line like this in the constructor:
  139. /// // mGuaranteeType = Guaranteed;
  140. /// // (or whatever type you wanted.)
  141. /// if(message)
  142. /// msg = dStrdup(message);
  143. /// else
  144. /// msg = NULL;
  145. /// }
  146. ///
  147. /// SimpleMessageEvent::~SimpleMessageEvent()
  148. /// {
  149. /// dFree(msg);
  150. /// }
  151. /// @endcode
  152. ///
  153. /// Simple as that! Now, onto pack(), write(), unpack(), process().
  154. ///
  155. /// <b>pack()</b> is responsible for packing the event over the wire:
  156. ///
  157. /// @code
  158. /// void SimpleMessageEvent::pack(NetConnection* conn, BitStream *bstream)
  159. /// {
  160. /// bstream->writeString(msg);
  161. /// }
  162. /// @endcode
  163. ///
  164. /// <b>unpack()</b> is responsible for unpacking the event on the other end:
  165. ///
  166. /// @code
  167. /// // The networking layer takes care of instantiating a new
  168. /// // SimpleMessageEvent, which saves us a bit of effort.
  169. /// void SimpleMessageEvent::unpack(NetConnection *conn, BitStream *bstream)
  170. /// {
  171. /// char buf[256];
  172. /// bstream->readString(buf);
  173. /// msg = dStrdup(buf);
  174. /// }
  175. /// @endcode
  176. ///
  177. /// <b>process()</b> is called when the network layer is finished with things.
  178. /// A typical case is that a GuaranteedOrdered event is unpacked and stored, but
  179. /// not processed until the events preceding it in the sequence have also been
  180. /// dealt with.
  181. ///
  182. /// @code
  183. /// // This just prints the event in the console. You might
  184. /// // want to do something more clever here -- BJG
  185. /// void SimpleMessageEvent::process(NetConnection *conn)
  186. /// {
  187. /// Con::printf("RMSG %d %s", mSourceId, msg);
  188. /// }
  189. /// @endcode
  190. ///
  191. /// <b>write()</b> is called if a demo recording is started, and the event has not yet been
  192. /// processed, but it has been unpacked. It should be identical in its output to the bitstream
  193. /// compared to pack(), but since it is called after unpack() some lookups may not need to be
  194. /// performed. In normal demo recording, whole network packets are recorded, meaning that most
  195. /// of the time write() will not be called.
  196. ///
  197. /// In our case, it's entirely identical to pack():
  198. ///
  199. /// @code
  200. /// virtual void write(NetConnection*, BitStream *bstream)
  201. /// {
  202. /// bstream->writeString(msg);
  203. /// }
  204. /// @endcode
  205. ///
  206. /// The NetEvent is sent over the wire in a straightforward way (assuming you have a
  207. /// handle to a NetConnection):
  208. ///
  209. /// @code
  210. /// NetConnection *conn; // We assume you have filled this in.
  211. ///
  212. /// con->postNetEvent(new SimpleMessageEvent("This is a test!"));
  213. /// @endcode
  214. ///
  215. /// @see GhostAlwaysObjectEvent for an example of dissimilar write()/pack() methods.
  216. ///
  217. /// Finally, for more advanced applications, notifySent() is called whenever the event is
  218. /// sent over the wire, in NetConnection::eventWritePacket(). notifyDelivered() is called
  219. /// when the packet is finally received or (in the case of Unguaranteed packets) dropped.
  220. ///
  221. /// @note IMPLEMENT_CO_NETEVENT_V1 and co. have sibling macros which allow you to specify a
  222. /// groupMask; see ConsoleObject for a further discussion of this.
  223. class NetEvent : public ConsoleObject
  224. {
  225. public:
  226. DECLARE_ABSTRACT_CLASS( NetEvent, ConsoleObject );
  227. DECLARE_INSCOPE( NetAPI );
  228. /// @name Implementation Details
  229. ///
  230. /// These are internal fields which you won't need to manipulate, except for mGuaranteeType.
  231. /// @{
  232. ///
  233. typedef ConsoleObject Parent;
  234. enum {
  235. GuaranteedOrdered = 0,
  236. Guaranteed = 1,
  237. Unguaranteed = 2
  238. } mGuaranteeType;
  239. NetConnectionId mSourceId;
  240. void incRef()
  241. {
  242. incRefCount();
  243. }
  244. void decRef()
  245. {
  246. decRefCount();
  247. }
  248. #ifdef TORQUE_DEBUG_NET
  249. virtual const char *getDebugName();
  250. #endif
  251. /// @}
  252. /// @name Things To Subclass
  253. /// @{
  254. ///
  255. NetEvent() { mGuaranteeType = GuaranteedOrdered; }
  256. virtual ~NetEvent();
  257. virtual void write(NetConnection *ps, BitStream *bstream) = 0;
  258. virtual void pack(NetConnection *ps, BitStream *bstream) = 0;
  259. virtual void unpack(NetConnection *ps, BitStream *bstream) = 0;
  260. virtual void process(NetConnection *ps) = 0;
  261. virtual void notifySent(NetConnection *ps);
  262. virtual void notifyDelivered(NetConnection *ps, bool madeit);
  263. /// @}
  264. };
  265. #define IMPLEMENT_CO_NETEVENT_V1(className) \
  266. IMPLEMENT_CLASS( className, NULL ) \
  267. END_IMPLEMENT_CLASS; \
  268. S32 className::_smTypeId; \
  269. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  270. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  271. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  272. ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeEvent, NetEventDirAny, className::getParentStaticClassRep(), &Parent::__description)
  273. #define IMPLEMENT_CO_CLIENTEVENT_V1(className) \
  274. IMPLEMENT_CLASS( className, NULL ) \
  275. END_IMPLEMENT_CLASS; \
  276. S32 className::_smTypeId; \
  277. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  278. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  279. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  280. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId,NetClassGroupGameMask, NetClassTypeEvent, NetEventDirServerToClient, className::getParentStaticClassRep(), &Parent::__description)
  281. #define IMPLEMENT_CO_SERVEREVENT_V1(className) \
  282. IMPLEMENT_CLASS( className, NULL ) \
  283. END_IMPLEMENT_CLASS; \
  284. S32 className::_smTypeId; \
  285. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  286. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  287. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  288. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeEvent, NetEventDirClientToServer, className::getParentStaticClassRep(), &Parent::__description)
  289. #define IMPLEMENT_CO_NETEVENT(className,groupMask) \
  290. IMPLEMENT_CLASS( className, NULL ) \
  291. END_IMPLEMENT_CLASS; \
  292. S32 className::_smTypeId; \
  293. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  294. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  295. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  296. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, groupMask, NetClassTypeEvent, NetEventDirAny, className::getParentStaticClassRep(), &Parent::__description)
  297. #define IMPLEMENT_CO_CLIENTEVENT(className,groupMask) \
  298. IMPLEMENT_CLASS( className, NULL ) \
  299. END_IMPLEMENT_CLASS; \
  300. S32 className::_smTypeId; \
  301. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  302. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  303. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  304. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, groupMask, NetClassTypeEvent, NetEventDirServerToClient, className::getParentStaticClassRep(), &Parent::__description)
  305. #define IMPLEMENT_CO_SERVEREVENT(className,groupMask) \
  306. IMPLEMENT_CLASS( className, className, __scope, NULL ) \
  307. END_IMPLEMENT_CLASS; \
  308. S32 className::_smTypeId; \
  309. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  310. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  311. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  312. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, groupMask, NetClassTypeEvent, NetEventDirClientToServer, className::getParentStaticClassRep(), &Parent::__description)
  313. //----------------------------------------------------------------------------
  314. /// Torque network connection.
  315. ///
  316. /// @section NetConnection_intro Introduction
  317. ///
  318. /// NetConnection is the glue that binds a networked Torque game together. It combines
  319. /// the low-level notify protocol implemented in ConnectionProtocol with a SimGroup to
  320. /// provide a powerful basis for implementing a multiplayer game protocol.
  321. ///
  322. /// On top of this basis it implements several distinct subsystems:
  323. /// - <b>Event manager</b>, which is responsible for transmitting NetEvents over the wire.
  324. /// It deals with ensuring that the various types of NetEvents are delivered appropriately,
  325. /// and with notifying the event of its delivery status.
  326. /// - <b>Move manager</b>, which is responsible for transferring a Move to the server 32
  327. /// times a second (on the client) and applying it to the control object (on the server).
  328. /// - <b>Ghost manager</b>, which is responsible for doing scoping calculations (on the server
  329. /// side) and transmitting most-recent ghost information to the client.
  330. /// - <b>File transfer</b>; it is often the case that clients will lack important files when
  331. /// connecting to a server which is running a mod or new map. This subsystem allows the
  332. /// server to transfer such files to the client.
  333. /// - <b>Networked String Table</b>; string data can easily soak up network bandwidth, so for
  334. /// efficiency, we implement a networked string table. We can then notify the connection
  335. /// of strings we will reference often, such as player names, and transmit only a tag,
  336. /// instead of the whole string.
  337. /// - <b>Demo Recording</b> is also implemented in NetConnection. A demo in Torque is a log
  338. /// of the network traffic between client and server; when a NetConnection records a demo,
  339. /// it simply logs this data to a file. When it plays a demo back, it replays the logged
  340. /// data.
  341. /// - The <b>Connection Database</b> is used to keep track of all the NetConnections; it can
  342. /// be iterated over (for instance, to send an event to all active connections), or queried
  343. /// by address.
  344. ///
  345. /// @section NetConnection_events On Events
  346. ///
  347. /// The Event Manager is exposed to the outside world via postNetEvent(), which accepts NetEvents.
  348. ///
  349. /// @see NetEvent for a more thorough explanation of how to use events.
  350. ///
  351. /// @section NetConnection_ghosting On Ghosting and Scoping
  352. ///
  353. /// Ghosting is the most complex, and most powerful, part of Torque's networking capabilities. It
  354. /// allows the information sent to clients to be very precisely matched to what they need, so that
  355. /// no excess bandwidth is wasted. The control object's onCameraScopeQuery() is called, to determine
  356. /// scoping information for the client; then objects which are in scope are then transmitted to the
  357. /// client, prioritized by the results of their getPriority() method.
  358. ///
  359. /// There is a cap on the maximum number of ghosts; ghost IDs are currently sent via a 12-bit field,
  360. /// ergo, there is a cap of 4096 objects ghosted per client. This can be easily raised; see the
  361. /// GhostConstants enum.
  362. ///
  363. /// Each object ghosted is assigned a ghost ID; the client is _only_ aware of the ghost ID. This acts
  364. /// to enhance game security, as it becomes difficult to map objects from one connection to another, or
  365. /// to reliably identify objects from ID alone. IDs are also reassigned based on need, making it hard
  366. /// to track objects that have fallen out of scope (as any object which the player shouldn't see would).
  367. ///
  368. /// resolveGhost() is used on the client side, and resolveObjectFromGhostIndex() on the server side, to
  369. /// turn ghost IDs into object references.
  370. ///
  371. /// The NetConnection is a SimGroup. On the client side, it contains all the objects which have been
  372. /// ghosted to that client. On the server side, it is empty; it can be used (typically in script) to
  373. /// hold objects related to the connection. For instance, you might place an observation camera in the
  374. /// NetConnnection. In both cases, when the connection is destroyed, so are the contained objects.
  375. ///
  376. /// @see NetObject, which is the superclass for ghostable objects, and ShapeBase, which is the base
  377. /// for player and vehicle classes.
  378. ///
  379. /// @nosubgrouping
  380. class NetConnection : public SimGroup, public ConnectionProtocol
  381. {
  382. friend class NetInterface;
  383. typedef SimGroup Parent;
  384. public:
  385. /// Structure to track ghost references in packets.
  386. ///
  387. /// Every packet we send out with an update from a ghost causes one of these to be
  388. /// allocated. mask is used to track what states were sent; that way if a packet is
  389. /// dropped, we can easily manipulate the stored states and figure out what if any data
  390. /// we need to resend.
  391. ///
  392. struct GhostRef
  393. {
  394. U32 mask; ///< States we transmitted.
  395. U32 ghostInfoFlags; ///< Flags from GhostInfo::Flags
  396. GhostInfo *ghost; ///< Reference to the GhostInfo we're from.
  397. GhostRef *nextRef; ///< Next GhostRef in this packet.
  398. GhostRef *nextUpdateChain; ///< Next update we sent for this ghost.
  399. };
  400. enum Constants
  401. {
  402. HashTableSize = 127,
  403. };
  404. void sendDisconnectPacket(const char *reason);
  405. virtual bool canRemoteCreate();
  406. virtual void onTimedOut();
  407. virtual void onConnectTimedOut();
  408. virtual void onDisconnect(const char *reason);
  409. virtual void onConnectionRejected(const char *reason);
  410. virtual void onConnectionEstablished(bool isInitiator);
  411. virtual void handleStartupError(const char *errorString);
  412. virtual void writeConnectRequest(BitStream *stream);
  413. virtual bool readConnectRequest(BitStream *stream, const char **errorString);
  414. virtual void writeConnectAccept(BitStream *stream);
  415. virtual bool readConnectAccept(BitStream *stream, const char **errorString);
  416. void connect(const NetAddress *address);
  417. //----------------------------------------------------------------
  418. /// @name Global Connection List
  419. /// @{
  420. private:
  421. ///
  422. NetConnection *mNextConnection; ///< Next item in list.
  423. NetConnection *mPrevConnection; ///< Previous item in list.
  424. static NetConnection *mConnectionList; ///< Head of list.
  425. public:
  426. static NetConnection *getConnectionList() { return mConnectionList; }
  427. NetConnection *getNext() { return mNextConnection; }
  428. /// @}
  429. //----------------------------------------------------------------
  430. enum NetConnectionFlags
  431. {
  432. ConnectionToServer = BIT(0),
  433. ConnectionToClient = BIT(1),
  434. LocalClientConnection = BIT(2),
  435. NetworkConnection = BIT(3),
  436. };
  437. private:
  438. BitSet32 mTypeFlags;
  439. U32 mNetClassGroup; ///< The NetClassGroup of this connection.
  440. /// @name Statistics
  441. /// @{
  442. /// Last time a packet was sent in milliseconds.
  443. /// @see Platform::getVirtualMilliseconds()
  444. U32 mLastUpdateTime;
  445. F32 mRoundTripTime;
  446. F32 mPacketLoss;
  447. U32 mSimulatedPing;
  448. F32 mSimulatedPacketLoss;
  449. /// @}
  450. /// @name State
  451. /// @{
  452. U32 mProtocolVersion;
  453. U32 mSendDelayCredit;
  454. U32 mConnectSequence;
  455. U32 mAddressDigest[4];
  456. bool mEstablished;
  457. bool mMissionPathsSent;
  458. struct NetRate
  459. {
  460. U32 updateDelay;
  461. S32 packetSize;
  462. bool changed;
  463. };
  464. NetRate mCurRate;
  465. NetRate mMaxRate;
  466. /// If we're doing a "short circuited" connection, this stores
  467. /// a pointer to the other side.
  468. SimObjectPtr<NetConnection> mRemoteConnection;
  469. NetAddress mNetAddress;
  470. /// @}
  471. /// @name Timeout Management
  472. /// @{
  473. U32 mPingSendCount;
  474. U32 mPingRetryCount;
  475. U32 mLastPingSendTime;
  476. /// @}
  477. /// @name Connection Table
  478. ///
  479. /// We store our connections on a hash table so we can
  480. /// quickly find them.
  481. /// @{
  482. NetConnection *mNextTableHash;
  483. static NetConnection *mHashTable[HashTableSize];
  484. /// @}
  485. protected:
  486. static SimObjectPtr<NetConnection> mServerConnection;
  487. static SimObjectPtr<NetConnection> mLocalClientConnection;
  488. static bool mFilesWereDownloaded;
  489. U32 mConnectSendCount;
  490. U32 mConnectLastSendTime;
  491. SimObjectPtr<NetConnection> getRemoteConnection() { return mRemoteConnection; }
  492. public:
  493. static NetConnection *getConnectionToServer() { return mServerConnection; }
  494. static NetConnection *getLocalClientConnection() { return mLocalClientConnection; }
  495. static void setLocalClientConnection(NetConnection *conn) { mLocalClientConnection = conn; }
  496. U32 getNetClassGroup() { return mNetClassGroup; }
  497. static bool filesWereDownloaded() { return mFilesWereDownloaded; }
  498. static String &getErrorBuffer() { return mErrorBuffer; }
  499. #ifdef TORQUE_DEBUG_NET
  500. bool mLogging;
  501. void setLogging(bool logging) { mLogging = logging; }
  502. #endif
  503. void setSimulatedNetParams(F32 packetLoss, U32 ping)
  504. { mSimulatedPacketLoss = packetLoss; mSimulatedPing = ping; }
  505. bool isConnectionToServer() { return mTypeFlags.test(ConnectionToServer); }
  506. bool isLocalConnection() { return !mRemoteConnection.isNull() ; }
  507. bool isNetworkConnection() { return mTypeFlags.test(NetworkConnection); }
  508. void setIsConnectionToServer() { mTypeFlags.set(ConnectionToServer); }
  509. void setIsLocalClientConnection() { mTypeFlags.set(LocalClientConnection); }
  510. void setNetworkConnection(bool net) { mTypeFlags.set(BitSet32(NetworkConnection), net); }
  511. virtual void setEstablished();
  512. /// Call this if the "connection" is local to this app. This short-circuits the protocol layer.
  513. void setRemoteConnectionObject(NetConnection *connection) { mRemoteConnection = connection; };
  514. void setSequence(U32 connectSequence);
  515. void setAddressDigest(U32 digest[4]);
  516. void getAddressDigest(U32 digest[4]);
  517. U32 getSequence();
  518. void setProtocolVersion(U32 protocolVersion) { mProtocolVersion = protocolVersion; }
  519. U32 getProtocolVersion() { return mProtocolVersion; }
  520. F32 getRoundTripTime() { return mRoundTripTime; }
  521. F32 getPacketLoss() { return( mPacketLoss ); }
  522. static String mErrorBuffer;
  523. static void setLastError(const char *fmt,...);
  524. void checkMaxRate();
  525. void handlePacket(BitStream *stream);
  526. void processRawPacket(BitStream *stream);
  527. void handleNotify(bool recvd);
  528. void handleConnectionEstablished();
  529. void keepAlive();
  530. const NetAddress *getNetAddress();
  531. void setNetAddress(const NetAddress *address);
  532. Net::Error sendPacket(BitStream *stream);
  533. private:
  534. void netAddressTableInsert();
  535. void netAddressTableRemove();
  536. public:
  537. /// Find a NetConnection, if any, with the specified address.
  538. static NetConnection *lookup(const NetAddress *remoteAddress);
  539. bool checkTimeout(U32 time); ///< returns true if the connection timed out
  540. void checkPacketSend(bool force);
  541. bool missionPathsSent() const { return mMissionPathsSent; }
  542. void setMissionPathsSent(const bool s) { mMissionPathsSent = s; }
  543. static void consoleInit();
  544. void onRemove();
  545. NetConnection();
  546. ~NetConnection();
  547. public:
  548. enum NetConnectionState
  549. {
  550. NotConnected,
  551. AwaitingChallengeResponse, ///< We've sent a challenge request, awaiting the response.
  552. AwaitingConnectRequest, ///< We've received a challenge request and sent a challenge response.
  553. AwaitingConnectResponse, ///< We've received a challenge response and sent a connect request.
  554. Connected, ///< We've accepted a connect request, or we've received a connect response accept.
  555. };
  556. U32 mConnectionSendCount; ///< number of connection messages we've sent.
  557. U32 mConnectionState; ///< State of the connection, from NetConnectionState.
  558. void setConnectionState(U32 state) { mConnectionState = state; }
  559. U32 getConnectionState() { return mConnectionState; }
  560. void setGhostFrom(bool ghostFrom); ///< Sets whether ghosts transmit from this side of the connection.
  561. void setGhostTo(bool ghostTo); ///< Sets whether ghosts are allowed from the other side of the connection.
  562. void setSendingEvents(bool sending); ///< Sets whether this side actually sends the events that are posted to it.
  563. void setTranslatesStrings(bool xl); ///< Sets whether this connection is capable of translating strings.
  564. void setNetClassGroup(U32 group); ///< Sets the group of NetClasses this connection traffics in.
  565. bool isEstablished() { return mEstablished; } ///< Is the connection established?
  566. DECLARE_CONOBJECT(NetConnection);
  567. DECLARE_INSCOPE( NetAPI );
  568. /// Structure to track packets and what we sent over them.
  569. ///
  570. /// We need to know what is sent in each packet, so that if a packet is
  571. /// dropped, we know what to resend. This is the structure we use to track
  572. /// this data.
  573. struct PacketNotify
  574. {
  575. bool rateChanged; ///< Did the rate change on this packet?
  576. bool maxRateChanged; ///< Did the max rate change on this packet?
  577. U32 sendTime; ///< Timestampe, when we sent this packet.
  578. NetEventNote *eventList; ///< Linked list of events sent over this packet.
  579. GhostRef *ghostList; ///< Linked list of ghost updates we sent in this packet.
  580. SubPacketRef *subList; ///< Defined by subclass - used as desired.
  581. PacketNotify *nextPacket; ///< Next packet sent.
  582. PacketNotify();
  583. };
  584. virtual PacketNotify *allocNotify();
  585. PacketNotify *mNotifyQueueHead; ///< Head of packet notify list.
  586. PacketNotify *mNotifyQueueTail; ///< Tail of packet notify list.
  587. protected:
  588. virtual void readPacket(BitStream *bstream);
  589. virtual void writePacket(BitStream *bstream, PacketNotify *note);
  590. virtual void packetReceived(PacketNotify *note);
  591. virtual void packetDropped(PacketNotify *note);
  592. virtual void connectionError(const char *errorString);
  593. //----------------------------------------------------------------
  594. /// @name Event Manager
  595. /// @{
  596. private:
  597. NetEventNote *mSendEventQueueHead;
  598. NetEventNote *mSendEventQueueTail;
  599. NetEventNote *mUnorderedSendEventQueueHead;
  600. NetEventNote *mUnorderedSendEventQueueTail;
  601. NetEventNote *mWaitSeqEvents;
  602. NetEventNote *mNotifyEventList;
  603. static FreeListChunker<NetEventNote> mEventNoteChunker;
  604. bool mSendingEvents;
  605. S32 mNextSendEventSeq;
  606. S32 mNextRecvEventSeq;
  607. S32 mLastAckedEventSeq;
  608. enum NetEventConstants {
  609. InvalidSendEventSeq = -1,
  610. FirstValidSendEventSeq = 0
  611. };
  612. void eventOnRemove();
  613. void eventPacketDropped(PacketNotify *notify);
  614. void eventPacketReceived(PacketNotify *notify);
  615. void eventWritePacket(BitStream *bstream, PacketNotify *notify);
  616. void eventReadPacket(BitStream *bstream);
  617. void eventWriteStartBlock(ResizeBitStream *stream);
  618. void eventReadStartBlock(BitStream *stream);
  619. public:
  620. /// Post an event to this connection.
  621. bool postNetEvent(NetEvent *event);
  622. /// @}
  623. //----------------------------------------------------------------
  624. /// @name Networked string table
  625. /// @{
  626. private:
  627. bool mTranslateStrings;
  628. ConnectionStringTable *mStringTable;
  629. public:
  630. void mapString(U32 netId, NetStringHandle &string)
  631. { mStringTable->mapString(netId, string); }
  632. U32 checkString(NetStringHandle &string, bool *isOnOtherSide = NULL)
  633. { if(mStringTable) return mStringTable->checkString(string, isOnOtherSide); else return 0; }
  634. U32 getNetSendId(NetStringHandle &string)
  635. { if(mStringTable) return mStringTable->getNetSendId(string); else return 0;}
  636. void confirmStringReceived(NetStringHandle &string, U32 index)
  637. { if(!isRemoved()) mStringTable->confirmStringReceived(string, index); }
  638. NetStringHandle translateRemoteStringId(U32 id) { return mStringTable->lookupString(id); }
  639. void validateSendString(const char *str);
  640. void packString(BitStream *stream, const char *str);
  641. void unpackString(BitStream *stream, char readBuffer[1024]);
  642. void packNetStringHandleU(BitStream *stream, NetStringHandle &h);
  643. NetStringHandle unpackNetStringHandleU(BitStream *stream);
  644. /// @}
  645. //----------------------------------------------------------------
  646. /// @name Ghost manager
  647. /// @{
  648. protected:
  649. enum GhostStates
  650. {
  651. GhostAlwaysDone,
  652. ReadyForNormalGhosts,
  653. EndGhosting,
  654. GhostAlwaysStarting,
  655. SendNextDownloadRequest,
  656. FileDownloadSizeMessage,
  657. NumConnectionMessages,
  658. };
  659. GhostInfo **mGhostArray; ///< Linked list of ghostInfos ghosted by this side of the connection
  660. U32 mGhostZeroUpdateIndex; ///< Index in mGhostArray of first ghost with 0 update mask.
  661. U32 mGhostFreeIndex; ///< Index in mGhostArray of first free ghost.
  662. U32 mGhostsActive; ///- Track actve ghosts on client side
  663. bool mGhosting; ///< Am I currently ghosting objects?
  664. bool mScoping; ///< am I currently scoping objects?
  665. U32 mGhostingSequence; ///< Sequence number describing this ghosting session.
  666. NetObject **mLocalGhosts; ///< Local ghost for remote object.
  667. ///
  668. /// mLocalGhosts pointer is NULL if mGhostTo is false
  669. GhostInfo *mGhostRefs; ///< Allocated array of ghostInfos. Null if ghostFrom is false.
  670. GhostInfo **mGhostLookupTable; ///< Table indexed by object id to GhostInfo. Null if ghostFrom is false.
  671. /// The object around which we are scoping this connection.
  672. ///
  673. /// This is usually the player object, or a related object, like a vehicle
  674. /// that the player is driving.
  675. SimObjectPtr<NetObject> mScopeObject;
  676. void clearGhostInfo();
  677. bool validateGhostArray();
  678. void ghostPacketDropped(PacketNotify *notify);
  679. void ghostPacketReceived(PacketNotify *notify);
  680. void ghostWritePacket(BitStream *bstream, PacketNotify *notify);
  681. void ghostReadPacket(BitStream *bstream);
  682. void freeGhostInfo(GhostInfo *);
  683. void ghostWriteStartBlock(ResizeBitStream *stream);
  684. void ghostReadStartBlock(BitStream *stream);
  685. virtual void ghostWriteExtra(NetObject *,BitStream *) {}
  686. virtual void ghostReadExtra(NetObject *,BitStream *, bool newGhost) {}
  687. virtual void ghostPreRead(NetObject *, bool newGhost) {}
  688. /// Called when 'EndGhosting' message is received from server.
  689. virtual void onEndGhosting() {}
  690. public:
  691. /// Some configuration values.
  692. enum GhostConstants
  693. {
  694. GhostIdBitSize = 12,
  695. MaxGhostCount = 1 << GhostIdBitSize, //4096,
  696. GhostLookupTableSize = 1 << GhostIdBitSize, //4096
  697. GhostIndexBitSize = 4 // number of bits GhostIdBitSize-3 fits into
  698. };
  699. U32 getGhostsActive() { return mGhostsActive;};
  700. /// Are we ghosting to someone?
  701. bool isGhostingTo() { return mLocalGhosts != NULL; };
  702. /// Are we ghosting from someone?
  703. bool isGhostingFrom() { return mGhostArray != NULL; };
  704. /// Called by onRemove, to shut down the ghost subsystem.
  705. void ghostOnRemove();
  706. /// Called when we're done with normal scoping.
  707. ///
  708. /// This gives subclasses a chance to shove things into scope, such as
  709. /// the results of a sensor network calculation, that would otherwise
  710. /// be awkward to add.
  711. virtual void doneScopingScene() { /* null */ }
  712. /// Set the object around which we are currently scoping network traffic.
  713. void setScopeObject(NetObject *object);
  714. /// Get the object around which we are currently scoping network traffic.
  715. NetObject *getScopeObject();
  716. /// Add an object to scope.
  717. void objectInScope(NetObject *object);
  718. /// Add an object to scope, marking that it should always be scoped to this connection.
  719. void objectLocalScopeAlways(NetObject *object);
  720. /// Mark an object that is being ghosted as not always needing to be scoped.
  721. ///
  722. /// This undoes objectLocalScopeAlways(), but doesn't immediately flush it from scope.
  723. ///
  724. /// Instead, the standard scoping mechanisms will clear it from scope when it is appropos
  725. /// to do so.
  726. void objectLocalClearAlways(NetObject *object);
  727. /// Get a NetObject* from a ghost ID (on client side).
  728. NetObject *resolveGhost(S32 id);
  729. /// Get a NetObject* from a ghost index (on the server side).
  730. NetObject *resolveObjectFromGhostIndex(S32 id);
  731. /// Get the ghost index corresponding to a given NetObject. This is only
  732. /// meaningful on the server side.
  733. S32 getGhostIndex(NetObject *object);
  734. /// Move a GhostInfo into the nonzero portion of the list (so that we know to update it).
  735. void ghostPushNonZero(GhostInfo *gi);
  736. /// Move a GhostInfo into the zero portion of the list (so that we know not to update it).
  737. void ghostPushToZero(GhostInfo *gi);
  738. /// Move a GhostInfo from the zero portion of the list to the free portion.
  739. void ghostPushZeroToFree(GhostInfo *gi);
  740. /// Move a GhostInfo from the free portion of the list to the zero portion.
  741. inline void ghostPushFreeToZero(GhostInfo *info);
  742. /// Stop all ghosting activity and inform the other side about this.
  743. ///
  744. /// Turns off ghosting.
  745. void resetGhosting();
  746. /// Activate ghosting, once it's enabled.
  747. void activateGhosting();
  748. /// Are we ghosting?
  749. bool isGhosting() { return mGhosting; }
  750. /// Begin to stop ghosting an object.
  751. void detachObject(GhostInfo *info);
  752. /// Mark an object to be always ghosted. Index is the ghost index of the object.
  753. void setGhostAlwaysObject(NetObject *object, U32 index);
  754. /// Send ghost connection handshake message.
  755. ///
  756. /// As part of the ghost connection process, extensive hand-shaking must be performed.
  757. ///
  758. /// This is done by passing ConnectionMessageEvents; this is a helper function
  759. /// to more effectively perform this task. Messages are dealt with by
  760. /// handleConnectionMessage().
  761. ///
  762. /// @param message One of GhostStates
  763. /// @param sequence A sequence number, if any.
  764. /// @param ghostCount A count of ghosts relating to this message.
  765. void sendConnectionMessage(U32 message, U32 sequence = 0, U32 ghostCount = 0);
  766. /// Handle message from sendConnectionMessage().
  767. ///
  768. /// This is called to handle messages sent via sendConnectionMessage.
  769. ///
  770. /// @param message One of GhostStates
  771. /// @param sequence A sequence number, if any.
  772. /// @param ghostCount A count of ghosts relating to this message.
  773. virtual void handleConnectionMessage(U32 message, U32 sequence, U32 ghostCount);
  774. /// Sends a signal to any object that needs to wait till everything has been ghosted
  775. /// before performing an operation.
  776. static Signal<void()> smGhostAlwaysDone;
  777. /// @}
  778. public:
  779. //----------------------------------------------------------------
  780. /// @name File transfer
  781. /// @{
  782. protected:
  783. /// List of files missing for this connection.
  784. ///
  785. /// The currently downloading file is always first in the list (ie, [0]).
  786. Vector<char *> mMissingFileList;
  787. /// Stream for currently uploading file (if any).
  788. Stream *mCurrentDownloadingFile;
  789. /// Storage for currently downloading file.
  790. void *mCurrentFileBuffer;
  791. /// Size of currently downloading file in bytes.
  792. U32 mCurrentFileBufferSize;
  793. /// Our position in the currently downloading file in bytes.
  794. U32 mCurrentFileBufferOffset;
  795. /// Number of files we have downloaded.
  796. U32 mNumDownloadedFiles;
  797. /// Error storage for file transfers.
  798. String mLastFileErrorBuffer;
  799. /// Structure to track ghost-always objects and their ghost indices.
  800. struct GhostSave {
  801. NetObject *ghost;
  802. U32 index;
  803. };
  804. /// List of objects to ghost-always.
  805. Vector<GhostSave> mGhostAlwaysSaveList;
  806. public:
  807. /// Start sending the specified file over the link.
  808. bool startSendingFile(const char *fileName);
  809. /// Called when we receive a FileChunkEvent.
  810. void chunkReceived(U8 *chunkData, U32 chunkLen);
  811. /// Get the next file...
  812. void sendNextFileDownloadRequest();
  813. /// Post the next FileChunkEvent.
  814. void sendFileChunk();
  815. /// Called when we finish downloading file data.
  816. virtual void fileDownloadSegmentComplete();
  817. /// This is part of the file transfer logic; basically, we call this
  818. /// every time we finish downloading new files. It attempts to load
  819. /// the GhostAlways objects; if they fail, it marks an error and we
  820. /// have chance to retry.
  821. void loadNextGhostAlwaysObject(bool hadNewFiles);
  822. /// @}
  823. //----------------------------------------------------------------
  824. /// @name Demo Recording
  825. /// @{
  826. private:
  827. Stream *mDemoWriteStream;
  828. Stream *mDemoReadStream;
  829. U32 mDemoNextBlockType;
  830. U32 mDemoNextBlockSize;
  831. U32 mDemoWriteStartTime;
  832. U32 mDemoReadStartTime;
  833. U32 mDemoLastWriteTime;
  834. U32 mDemoRealStartTime;
  835. public:
  836. enum DemoBlockTypes {
  837. BlockTypePacket,
  838. BlockTypeSendPacket,
  839. NetConnectionBlockTypeCount
  840. };
  841. enum DemoConstants {
  842. MaxNumBlockTypes = 16,
  843. MaxBlockSize = 0x1000,
  844. };
  845. bool isRecording()
  846. { return mDemoWriteStream != NULL; }
  847. bool isPlayingBack()
  848. { return mDemoReadStream != NULL; }
  849. U32 getNextBlockType() { return mDemoNextBlockType; }
  850. void recordBlock(U32 type, U32 size, void *data);
  851. virtual void handleRecordedBlock(U32 type, U32 size, void *data);
  852. bool processNextBlock();
  853. bool startDemoRecord(const char *fileName);
  854. bool replayDemoRecord(const char *fileName);
  855. void startDemoRead();
  856. void stopRecording();
  857. void stopDemoPlayback();
  858. virtual void writeDemoStartBlock(ResizeBitStream *stream);
  859. virtual bool readDemoStartBlock(BitStream *stream);
  860. virtual void demoPlaybackComplete();
  861. /// @}
  862. };
  863. //----------------------------------------------------------------------------
  864. /// Information about a ghosted object.
  865. ///
  866. /// @note If the size of this structure changes, the
  867. /// NetConnection::getGhostIndex function MUST be changed
  868. /// to reflect the new size.
  869. struct GhostInfo
  870. {
  871. public: // required for MSVC
  872. NetObject *obj; ///< The object being ghosted.
  873. U32 updateMask; ///< Flags indicating what state data needs to be transferred.
  874. U32 updateSkipCount; ///< How many updates have we skipped this guy?
  875. U32 flags; ///< Flags from GhostInfo::Flags
  876. F32 priority; ///< A float value indicating the priority of this object for
  877. /// updates.
  878. /// @name References
  879. ///
  880. /// The GhostInfo structure is used in several linked lists; these members are
  881. /// the implementation for this.
  882. /// @{
  883. NetConnection::GhostRef *updateChain; ///< List of references in NetConnections to us.
  884. GhostInfo *nextObjectRef; ///< Next ghosted object.
  885. GhostInfo *prevObjectRef; ///< Previous ghosted object.
  886. NetConnection *connection; ///< Connection that we're ghosting over.
  887. GhostInfo *nextLookupInfo; ///< GhostInfo references are stored in a hash; this is the bucket
  888. /// implementation.
  889. /// @}
  890. U32 index;
  891. U32 arrayIndex;
  892. /// Flags relating to the state of the object.
  893. enum Flags
  894. {
  895. Valid = BIT(0),
  896. InScope = BIT(1),
  897. ScopeAlways = BIT(2),
  898. NotYetGhosted = BIT(3),
  899. Ghosting = BIT(4),
  900. KillGhost = BIT(5),
  901. KillingGhost = BIT(6),
  902. ScopedEvent = BIT(7),
  903. ScopeLocalAlways = BIT(8),
  904. };
  905. };
  906. inline void NetConnection::ghostPushNonZero(GhostInfo *info)
  907. {
  908. AssertFatal(info->arrayIndex >= mGhostZeroUpdateIndex && info->arrayIndex < mGhostFreeIndex, "Out of range arrayIndex.");
  909. AssertFatal(mGhostArray[info->arrayIndex] == info, "Invalid array object.");
  910. if(info->arrayIndex != mGhostZeroUpdateIndex)
  911. {
  912. mGhostArray[mGhostZeroUpdateIndex]->arrayIndex = info->arrayIndex;
  913. mGhostArray[info->arrayIndex] = mGhostArray[mGhostZeroUpdateIndex];
  914. mGhostArray[mGhostZeroUpdateIndex] = info;
  915. info->arrayIndex = mGhostZeroUpdateIndex;
  916. }
  917. mGhostZeroUpdateIndex++;
  918. //AssertFatal(validateGhostArray(), "Invalid ghost array!");
  919. }
  920. inline void NetConnection::ghostPushToZero(GhostInfo *info)
  921. {
  922. AssertFatal(info->arrayIndex < mGhostZeroUpdateIndex, "Out of range arrayIndex.");
  923. AssertFatal(mGhostArray[info->arrayIndex] == info, "Invalid array object.");
  924. mGhostZeroUpdateIndex--;
  925. if(info->arrayIndex != mGhostZeroUpdateIndex)
  926. {
  927. mGhostArray[mGhostZeroUpdateIndex]->arrayIndex = info->arrayIndex;
  928. mGhostArray[info->arrayIndex] = mGhostArray[mGhostZeroUpdateIndex];
  929. mGhostArray[mGhostZeroUpdateIndex] = info;
  930. info->arrayIndex = mGhostZeroUpdateIndex;
  931. }
  932. //AssertFatal(validateGhostArray(), "Invalid ghost array!");
  933. }
  934. inline void NetConnection::ghostPushZeroToFree(GhostInfo *info)
  935. {
  936. AssertFatal(info->arrayIndex >= mGhostZeroUpdateIndex && info->arrayIndex < mGhostFreeIndex, "Out of range arrayIndex.");
  937. AssertFatal(mGhostArray[info->arrayIndex] == info, "Invalid array object.");
  938. mGhostFreeIndex--;
  939. if(info->arrayIndex != mGhostFreeIndex)
  940. {
  941. mGhostArray[mGhostFreeIndex]->arrayIndex = info->arrayIndex;
  942. mGhostArray[info->arrayIndex] = mGhostArray[mGhostFreeIndex];
  943. mGhostArray[mGhostFreeIndex] = info;
  944. info->arrayIndex = mGhostFreeIndex;
  945. }
  946. //AssertFatal(validateGhostArray(), "Invalid ghost array!");
  947. }
  948. inline void NetConnection::ghostPushFreeToZero(GhostInfo *info)
  949. {
  950. AssertFatal(info->arrayIndex >= mGhostFreeIndex, "Out of range arrayIndex.");
  951. AssertFatal(mGhostArray[info->arrayIndex] == info, "Invalid array object.");
  952. if(info->arrayIndex != mGhostFreeIndex)
  953. {
  954. mGhostArray[mGhostFreeIndex]->arrayIndex = info->arrayIndex;
  955. mGhostArray[info->arrayIndex] = mGhostArray[mGhostFreeIndex];
  956. mGhostArray[mGhostFreeIndex] = info;
  957. info->arrayIndex = mGhostFreeIndex;
  958. }
  959. mGhostFreeIndex++;
  960. //AssertFatal(validateGhostArray(), "Invalid ghost array!");
  961. }
  962. #endif