gameBase.h 17 KB

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