netConnection.h 45 KB

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