gameBase.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 _GAMEBASE_H_
  23. #define _GAMEBASE_H_
  24. #ifndef _SCENEOBJECT_H_
  25. #include "scene/sceneObject.h"
  26. #endif
  27. #ifndef _PROCESSLIST_H_
  28. #include "T3D/gameBase/processList.h"
  29. #endif
  30. #ifndef _TICKCACHE_H_
  31. #include "T3D/gameBase/tickCache.h"
  32. #endif
  33. #ifndef _DYNAMIC_CONSOLETYPES_H_
  34. #include "console/dynamicTypes.h"
  35. #endif
  36. class NetConnection;
  37. class ProcessList;
  38. class GameBase;
  39. struct Move;
  40. //----------------------------------------------------------------------------
  41. //----------------------------------------------------------------------------
  42. /// Scriptable, demo-able datablock.
  43. ///
  44. /// This variant of SimDataBlock performs these additional tasks:
  45. /// - Linking datablock's namepsaces to the namespace of their C++ class, so
  46. /// that datablocks can expose script functionality.
  47. /// - Linking datablocks to a user defined scripting namespace, by setting the
  48. /// 'class' field at datablock definition time.
  49. /// - Adds a category field; this is used by the world creator in the editor to
  50. /// classify creatable shapes. Creatable shapes are placed under the Shapes
  51. /// node in the treeview for this; additional levels are created, named after
  52. /// the category fields.
  53. /// - Adds support for demo stream recording. This support takes the form
  54. /// of the member variable packed. When a demo is being recorded by a client,
  55. /// data is unpacked, then packed again to the data stream, then, in the case
  56. /// of datablocks, preload() is called to process the data. It is occasionally
  57. /// the case that certain references in the datablock stream cannot be resolved
  58. /// until preload is called, in which case a raw ID field is stored in the variable
  59. /// which will eventually be used to store a pointer to the object. However, if
  60. /// packData() is called before we resolve this ID, trying to call getID() on the
  61. /// objecct ID would be a fatal error. Therefore, in these cases, we test packed;
  62. /// if it is true, then we know we have to write the raw data, instead of trying
  63. /// to resolve an ID.
  64. ///
  65. /// @see SimDataBlock for further details about datablocks.
  66. /// @see http://hosted.tribalwar.com/t2faq/datablocks.shtml for an excellent
  67. /// explanation of the basics of datablocks from a scripting perspective.
  68. /// @nosubgrouping
  69. struct GameBaseData : public SimDataBlock
  70. {
  71. private:
  72. typedef SimDataBlock Parent;
  73. public:
  74. bool packed;
  75. StringTableEntry category;
  76. // Signal triggered when this datablock is modified.
  77. // GameBase objects referencing this datablock notify with this signal.
  78. Signal<void(void)> mReloadSignal;
  79. // Triggers the reload signal.
  80. void inspectPostApply();
  81. bool onAdd();
  82. // The derived class should provide the following:
  83. DECLARE_CONOBJECT(GameBaseData);
  84. GameBaseData();
  85. static void initPersistFields();
  86. bool preload(bool server, String &errorStr);
  87. void unpackData(BitStream* stream);
  88. /// @name Callbacks
  89. /// @{
  90. DECLARE_CALLBACK( void, onAdd, ( GameBase* obj ) );
  91. DECLARE_CALLBACK( void, onRemove, ( GameBase* obj ) );
  92. DECLARE_CALLBACK( void, onNewDataBlock, ( GameBase* obj ) );
  93. DECLARE_CALLBACK( void, onMount, ( GameBase* obj, SceneObject* mountObj, S32 node ) );
  94. DECLARE_CALLBACK( void, onUnmount, ( GameBase* obj, SceneObject* mountObj, S32 node ) );
  95. /// @}
  96. };
  97. //----------------------------------------------------------------------------
  98. // A few utility methods for sending datablocks over the net
  99. //----------------------------------------------------------------------------
  100. bool UNPACK_DB_ID(BitStream *, U32 & id);
  101. bool PACK_DB_ID(BitStream *, U32 id);
  102. bool PRELOAD_DB(U32 & id, SimDataBlock **, bool server, const char * clientMissing = NULL, const char * serverMissing = NULL);
  103. //----------------------------------------------------------------------------
  104. class GameConnection;
  105. class WaterObject;
  106. class MoveList;
  107. // For truly it is written: "The wise man extends GameBase for his purposes,
  108. // while the fool has the ability to eject shell casings from the belly of his
  109. // dragon." -- KillerBunny
  110. /// Base class for game objects which use datablocks, networking, are editable,
  111. /// and need to process ticks.
  112. ///
  113. /// @section GameBase_process GameBase and ProcessList
  114. ///
  115. /// GameBase adds two kinds of time-based updates. Torque works off of a concept
  116. /// of ticks. Ticks are slices of time 32 milliseconds in length. There are three
  117. /// methods which are used to update GameBase objects that are registered with
  118. /// the ProcessLists:
  119. /// - processTick(Move*) is called on each object once for every tick, regardless
  120. /// of the "real" framerate.
  121. /// - interpolateTick(float) is called on client objects when they need to interpolate
  122. /// to match the next tick.
  123. /// - advanceTime(float) is called on client objects so they can do time-based behaviour,
  124. /// like updating animations.
  125. ///
  126. /// Torque maintains a server and a client processing list; in a local game, both
  127. /// are populated, while in multiplayer situations, either one or the other is
  128. /// populated.
  129. ///
  130. /// You can control whether an object is considered for ticking by means of the
  131. /// setProcessTick() method.
  132. ///
  133. /// @section GameBase_datablock GameBase and Datablocks
  134. ///
  135. /// GameBase adds support for datablocks. Datablocks are secondary classes which store
  136. /// static data for types of game elements. For instance, this means that all "light human
  137. /// male armor" type Players share the same datablock. Datablocks typically store not only
  138. /// raw data, but perform precalculations, like finding nodes in the game model, or
  139. /// validating movement parameters.
  140. ///
  141. /// There are three parts to the datablock interface implemented in GameBase:
  142. /// - <b>getDataBlock()</b>, which gets a pointer to the current datablock. This is
  143. /// mostly for external use; for in-class use, it's better to directly access the
  144. /// mDataBlock member.
  145. /// - <b>setDataBlock()</b>, which sets mDataBlock to point to a new datablock; it
  146. /// uses the next part of the interface to inform subclasses of this.
  147. /// - <b>onNewDataBlock()</b> is called whenever a new datablock is assigned to a GameBase.
  148. ///
  149. /// Datablocks are also usable through the scripting language.
  150. ///
  151. /// @see SimDataBlock for more details.
  152. ///
  153. /// @section GameBase_networking GameBase and Networking
  154. ///
  155. /// writePacketData() and readPacketData() are called to transfer information needed for client
  156. /// side prediction. They are usually used when updating a client of its control object state.
  157. ///
  158. /// Subclasses of GameBase usually transmit positional and basic status data in the packUpdate()
  159. /// functions, while giving velocity, momentum, and similar state information in the writePacketData().
  160. ///
  161. /// writePacketData()/readPacketData() are called <i>in addition</i> to packUpdate/unpackUpdate().
  162. ///
  163. /// @nosubgrouping
  164. class GameBase : public SceneObject
  165. {
  166. typedef SceneObject Parent;
  167. /// @name Datablock
  168. /// @{
  169. GameBaseData* mDataBlock;
  170. /// @}
  171. TickCache mTickCache;
  172. // Control interface
  173. GameConnection* mControllingClient;
  174. public:
  175. static bool gShowBoundingBox; ///< Should we render bounding boxes?
  176. protected:
  177. F32 mCameraFov;
  178. /// The WaterObject we are currently within.
  179. WaterObject *mCurrentWaterObject;
  180. static bool setDataBlockProperty( void *object, const char *index, const char *data );
  181. #ifdef TORQUE_DEBUG_NET_MOVES
  182. U32 mLastMoveId;
  183. U32 mTicksSinceLastMove;
  184. bool mIsAiControlled;
  185. #endif
  186. public:
  187. GameBase();
  188. ~GameBase();
  189. enum GameBaseMasks {
  190. DataBlockMask = Parent::NextFreeMask << 0,
  191. ExtendedInfoMask = Parent::NextFreeMask << 1,
  192. NextFreeMask = Parent::NextFreeMask << 2
  193. };
  194. // net flags added by game base
  195. enum
  196. {
  197. NetOrdered = BIT(Parent::MaxNetFlagBit+1), /// Process in same order on client and server.
  198. NetNearbyAdded = BIT(Parent::MaxNetFlagBit+2), /// Is set during client catchup when neighbors have been checked.
  199. GhostUpdated = BIT(Parent::MaxNetFlagBit+3), /// Is set whenever ghost updated (and reset) on the client, for hifi objects.
  200. TickLast = BIT(Parent::MaxNetFlagBit+4), /// Tick this object after all others.
  201. NewGhost = BIT(Parent::MaxNetFlagBit+5), /// This ghost was just added during the last update.
  202. HiFiPassive = BIT(Parent::MaxNetFlagBit+6), /// Do not interact with other hifi passive objects.
  203. MaxNetFlagBit = Parent::MaxNetFlagBit+6
  204. };
  205. /// @name Inherited Functionality.
  206. /// @{
  207. bool onAdd();
  208. void onRemove();
  209. void inspectPostApply();
  210. static void initPersistFields();
  211. static void consoleInit();
  212. /// @}
  213. ///@name Datablock
  214. ///@{
  215. /// Assigns this object a datablock and loads attributes with onNewDataBlock.
  216. ///
  217. /// @see onNewDataBlock
  218. /// @param dptr Datablock
  219. bool setDataBlock( GameBaseData *dptr );
  220. /// Returns the datablock for this object.
  221. GameBaseData* getDataBlock() { return mDataBlock; }
  222. /// Called when a new datablock is set. This allows subclasses to
  223. /// appropriately handle new datablocks.
  224. ///
  225. /// @see setDataBlock()
  226. /// @param dptr New datablock
  227. /// @param reload Is this a new datablock or are we reloading one
  228. /// we already had.
  229. virtual bool onNewDataBlock( GameBaseData *dptr, bool reload );
  230. ///@}
  231. /// @name Script
  232. /// The scriptOnXX methods are invoked by the leaf classes
  233. /// @{
  234. /// Executes the 'onAdd' script function for this object.
  235. /// @note This must be called after everything is ready
  236. void scriptOnAdd();
  237. /// Executes the 'onNewDataBlock' script function for this object.
  238. ///
  239. /// @note This must be called after everything is loaded.
  240. void scriptOnNewDataBlock();
  241. /// Executes the 'onRemove' script function for this object.
  242. /// @note This must be called while the object is still valid
  243. void scriptOnRemove();
  244. /// @}
  245. // ProcessObject override
  246. void processTick( const Move *move );
  247. /// @name GameBase NetFlags & Hifi-Net Interface
  248. /// @{
  249. /// Set or clear the GhostUpdated bit in our NetFlags.
  250. /// @see GhostUpdated
  251. void setGhostUpdated( bool b ) { if (b) mNetFlags.set(GhostUpdated); else mNetFlags.clear(GhostUpdated); }
  252. /// Returns true if the GhostUpdated bit in our NetFlags is set.
  253. /// @see GhostUpdated
  254. bool isGhostUpdated() const { return mNetFlags.test(GhostUpdated); }
  255. /// Set or clear the NewGhost bit in our NetFlags.
  256. /// @see NewGhost
  257. void setNewGhost( bool n ) { if (n) mNetFlags.set(NewGhost); else mNetFlags.clear(NewGhost); }
  258. /// Returns true if the NewGhost bit in out NetFlags is set.
  259. /// @see NewGhost
  260. bool isNewGhost() const { return mNetFlags.test(NewGhost); }
  261. /// Set or clear the NetNearbyAdded bit in our NetFlags.
  262. /// @see NetNearbyAdded
  263. void setNetNearbyAdded( bool b ) { if (b) mNetFlags.set(NetNearbyAdded); else mNetFlags.clear(NetNearbyAdded); }
  264. /// Returns true if the NetNearby bit in our NetFlags is set.
  265. /// @see NetNearbyAdded
  266. bool isNetNearbyAdded() const { return mNetFlags.test(NetNearbyAdded); }
  267. /// Returns true if the HiFiPassive bit in our NetFlags is set.
  268. /// @see HiFiPassive
  269. bool isHifiPassive() const { return mNetFlags.test(HiFiPassive); }
  270. /// Returns true if the TickLast bit in our NetFlags is set.
  271. /// @see TickLast
  272. bool isTickLast() const { return mNetFlags.test(TickLast); }
  273. /// Returns true if the NetOrdered bit in our NetFlags is set.
  274. /// @see NetOrdered
  275. bool isNetOrdered() const { return mNetFlags.test(NetOrdered); }
  276. /// Called during client catchup under the hifi-net model.
  277. virtual void computeNetSmooth( F32 backDelta ) {}
  278. /// Returns TickCache used under the hifi-net model.
  279. TickCache& getTickCache() { return mTickCache; }
  280. /// @}
  281. /// @name Network
  282. /// @see NetObject, NetConnection
  283. /// @{
  284. F32 getUpdatePriority( CameraScopeQuery *focusObject, U32 updateMask, S32 updateSkips );
  285. U32 packUpdate ( NetConnection *conn, U32 mask, BitStream *stream );
  286. void unpackUpdate( NetConnection *conn, BitStream *stream );
  287. /// Write state information necessary to perform client side prediction of an object.
  288. ///
  289. /// This information is sent only to the controlling object. For example, if you are a client
  290. /// controlling a Player, the server uses writePacketData() instead of packUpdate() to
  291. /// generate the data you receive.
  292. ///
  293. /// @param conn Connection for which we're generating this data.
  294. /// @param stream Bitstream for output.
  295. virtual void writePacketData( GameConnection *conn, BitStream *stream );
  296. /// Read data written with writePacketData() and update the object state.
  297. ///
  298. /// @param conn Connection for which we're generating this data.
  299. /// @param stream Bitstream to read.
  300. virtual void readPacketData( GameConnection *conn, BitStream *stream );
  301. /// Gets the checksum for packet data.
  302. ///
  303. /// Basically writes a packet, does a CRC check on it, and returns
  304. /// that CRC.
  305. ///
  306. /// @see writePacketData
  307. /// @param conn Game connection
  308. virtual U32 getPacketDataChecksum( GameConnection *conn );
  309. ///@}
  310. /// @name Mounted objects ( overrides )
  311. /// @{
  312. public:
  313. virtual void onMount( SceneObject *obj, S32 node );
  314. virtual void onUnmount( SceneObject *obj,S32 node );
  315. /// @}
  316. /// @name User control
  317. /// @{
  318. /// Returns the client controlling this object
  319. GameConnection *getControllingClient() { return mControllingClient; }
  320. const GameConnection *getControllingClient() const { return mControllingClient; }
  321. /// Returns the MoveList of the client controlling this object.
  322. /// If there is no client it returns NULL;
  323. MoveList* getMoveList();
  324. /// Sets the client controlling this object
  325. /// @param client Client that is now controlling this object
  326. virtual void setControllingClient( GameConnection *client );
  327. virtual GameBase * getControllingObject() { return NULL; }
  328. virtual GameBase * getControlObject() { return NULL; }
  329. virtual void setControlObject( GameBase * ) { }
  330. /// @}
  331. virtual F32 getDefaultCameraFov() { return 90.f; }
  332. virtual F32 getCameraFov() { return 90.f; }
  333. virtual void setCameraFov( F32 fov ) { }
  334. virtual bool isValidCameraFov( F32 fov ) { return true; }
  335. virtual bool useObjsEyePoint() const { return false; }
  336. virtual bool onlyFirstPerson() const { return false; }
  337. virtual F32 getDamageFlash() const { return 0.0f; }
  338. virtual F32 getWhiteOut() const { return 0.0f; }
  339. // Not implemented here, but should return the Camera to world transformation matrix
  340. virtual void getCameraTransform (F32 *pos, MatrixF *mat ) { *mat = MatrixF::Identity; }
  341. /// Returns the water object we are colliding with, it is up to derived
  342. /// classes to actually set this object.
  343. virtual WaterObject* getCurrentWaterObject() { return mCurrentWaterObject; }
  344. #ifdef TORQUE_DEBUG_NET_MOVES
  345. bool isAIControlled() const { return mIsAiControlled; }
  346. #endif
  347. DECLARE_CONOBJECT (GameBase );
  348. /// @name Callbacks
  349. /// @{
  350. DECLARE_CALLBACK( void, setControl, ( bool controlled ) );
  351. /// @}
  352. private:
  353. /// This is called by the reload signal in our datablock when it is
  354. /// modified in the editor.
  355. ///
  356. /// This method is private and is not virtual. To handle a datablock-modified
  357. /// even in a child-class specific way you should override onNewDatablock
  358. /// and handle the reload( true ) case.
  359. ///
  360. /// Warning: For local-client, editor situations only.
  361. ///
  362. /// Warning: Do not attempt to call .remove or .notify on mDataBlock->mReloadSignal
  363. /// within this callback.
  364. ///
  365. void _onDatablockModified();
  366. };
  367. #endif // _GAMEBASE_H_