netConnection.h 45 KB

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