simSet.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 _SIMSET_H_
  23. #define _SIMSET_H_
  24. #ifndef _SIMOBJECT_H_
  25. #include "console/simObject.h"
  26. #endif
  27. #ifndef _SIMOBJECTLIST_H_
  28. #include "console/simObjectList.h"
  29. #endif
  30. #ifndef _SIMDICTIONARY_H_
  31. #include "console/simDictionary.h"
  32. #endif
  33. #ifndef _TSIGNAL_H_
  34. #include "core/util/tSignal.h"
  35. #endif
  36. #include "persistence/taml/tamlChildren.h"
  37. //---------------------------------------------------------------------------
  38. /// A set of SimObjects.
  39. ///
  40. /// It is often necessary to keep track of an arbitrary set of SimObjects.
  41. /// For instance, Torque's networking code needs to not only keep track of
  42. /// the set of objects which need to be ghosted, but also the set of objects
  43. /// which must <i>always</i> be ghosted. It does this by working with two
  44. /// sets. The first of these is the RootGroup (which is actually a SimGroup)
  45. /// and the second is the GhostAlwaysSet, which contains objects which must
  46. /// always be ghosted to the client.
  47. ///
  48. /// Some general notes on SimSets:
  49. /// - Membership is not exclusive. A SimObject may be a member of multiple
  50. /// SimSets.
  51. /// - A SimSet does not destroy subobjects when it is destroyed.
  52. /// - A SimSet may hold an arbitrary number of objects.
  53. ///
  54. /// Using SimSets, the code to work with these two sets becomes
  55. /// relatively straightforward:
  56. ///
  57. /// @code
  58. /// // (Example from netObject.cc)
  59. /// // To iterate over all the objects in the Sim:
  60. /// for (SimSetIterator obj(Sim::getRootGroup()); *obj; ++obj)
  61. /// {
  62. /// NetObject* nobj = dynamic_cast<NetObject*>(*obj);
  63. ///
  64. /// if (nobj)
  65. /// {
  66. /// // ... do things ...
  67. /// }
  68. /// }
  69. ///
  70. /// // (Example from netGhost.cc)
  71. /// // To iterate over the ghostAlways set.
  72. /// SimSet* ghostAlwaysSet = Sim::getGhostAlwaysSet();
  73. /// SimSet::iterator i;
  74. ///
  75. /// U32 sz = ghostAlwaysSet->size();
  76. /// S32 j;
  77. ///
  78. /// for(i = ghostAlwaysSet->begin(); i != ghostAlwaysSet->end(); i++)
  79. /// {
  80. /// NetObject *obj = (NetObject *)(*i);
  81. ///
  82. /// /// ... do things with obj...
  83. /// }
  84. /// @endcode
  85. ///
  86. class SimSet : public SimObject, public TamlChildren
  87. {
  88. public:
  89. typedef SimObject Parent;
  90. enum SetModification
  91. {
  92. SetCleared,
  93. SetObjectAdded,
  94. SetObjectRemoved
  95. };
  96. /// Signal for letting observers know when objects are added to or removed from
  97. /// the set.
  98. ///
  99. /// @param modification In what way the set has been modified.
  100. /// @param set The set that has been modified.
  101. /// @param object If #modification is #SetObjectAdded or #SetObjectRemoved, this is
  102. /// the object that has been added or removed. Otherwise NULL.
  103. typedef Signal< void( SetModification modification, SimSet* set, SimObject* object ) > SetModificationSignal;
  104. protected:
  105. SimObjectList objectList;
  106. void *mMutex;
  107. /// Signal that is triggered when objects are added or removed from the set.
  108. SetModificationSignal mSetModificationSignal;
  109. /// @name Callbacks
  110. /// @{
  111. DECLARE_CALLBACK( void, onObjectAdded, ( SimObject* object ) );
  112. DECLARE_CALLBACK( void, onObjectRemoved, ( SimObject* object ) );
  113. /// @}
  114. public:
  115. SimSet();
  116. ~SimSet();
  117. /// Return the signal that is triggered when an object is added to or removed
  118. /// from the set.
  119. const SetModificationSignal& getSetModificationSignal() const { return mSetModificationSignal; }
  120. SetModificationSignal& getSetModificationSignal() { return mSetModificationSignal; }
  121. /// @name STL Interface
  122. /// @{
  123. ///
  124. typedef SimObjectList::iterator iterator;
  125. typedef SimObjectList::value_type value;
  126. SimObject* front() { return objectList.front(); }
  127. SimObject* first() { return objectList.first(); }
  128. SimObject* last() { return objectList.last(); }
  129. bool empty() const { return objectList.empty(); }
  130. S32 size() const { return objectList.size(); }
  131. iterator begin() { return objectList.begin(); }
  132. iterator end() { return objectList.end(); }
  133. value operator[] (S32 index) { return objectList[U32(index)]; }
  134. inline iterator find( iterator first, iterator last, SimObject *obj)
  135. { return ::find(first, last, obj); }
  136. inline iterator find(SimObject *obj)
  137. { return ::find(begin(), end(), obj); }
  138. /// Reorder the position of "obj" to either be the last object in the list or, if
  139. /// "target" is given, to come before "target" in the list of children.
  140. virtual bool reOrder( SimObject *obj, SimObject *target=0 );
  141. /// Return the object at the given index.
  142. SimObject* at(S32 index) const { return objectList.at(index); }
  143. /// Remove all objects from this set.
  144. virtual void clear();
  145. /// @}
  146. /// @name Set Management
  147. /// @{
  148. /// Add the given object to the set.
  149. /// @param object Object to add to the set.
  150. virtual void addObject( SimObject* object );
  151. /// Remove the given object from the set.
  152. /// @param object Object to remove from the set.
  153. virtual void removeObject( SimObject* object );
  154. /// Add the given object to the end of the object list of this set.
  155. /// @param object Object to add to the set.
  156. virtual void pushObject( SimObject* object );
  157. /// Return true if this set accepts the given object as a child.
  158. /// This method should be overridden for set classes that restrict membership.
  159. virtual bool acceptsAsChild( SimObject* object ) const { return true; }
  160. /// Deletes all the objects in the set.
  161. void deleteAllObjects();
  162. /// Remove an object from the end of the list.
  163. virtual void popObject();
  164. void bringObjectToFront(SimObject* obj) { reOrder(obj, front()); }
  165. void pushObjectToBack(SimObject* obj) { reOrder(obj, NULL); }
  166. /// Performs a sort of the objects in the set using a script
  167. /// callback function to do the comparison.
  168. ///
  169. /// An example script sort callback:
  170. ///
  171. /// @code
  172. /// function sortByName( %object1, %object2 )
  173. /// {
  174. /// return strcmp( %object1.getName(), %object2.getName() );
  175. /// }
  176. /// @endcode
  177. ///
  178. /// Note: You should never modify the SimSet itself while in
  179. /// the sort callback function as it can cause a deadlock.
  180. ///
  181. void scriptSort( const String &scriptCallbackFn );
  182. /// @}
  183. void callOnChildren( const String &method, S32 argc, ConsoleValueRef argv[], bool executeOnChildGroups = true );
  184. /// Return the number of objects in this set as well as all sets that are contained
  185. /// in this set and its children.
  186. ///
  187. /// @note The child sets themselves count towards the total too.
  188. U32 sizeRecursive();
  189. virtual SimObject* findObjectByInternalName(StringTableEntry internalName, bool searchChildren = false);
  190. SimObject* findObjectByLineNumber(const char* fileName, S32 declarationLine, bool searchChildren = false);
  191. /// Find the given object in this set. Returns NULL if the object
  192. /// is not part of this set.
  193. SimObject* findObject( SimObject* object );
  194. /// Add all child objects ( including children of children ) to the foundObjects
  195. /// Vector which are of type T.
  196. template< class T >
  197. void findObjectByType( Vector<T*> &foundObjects );
  198. /// Add all child objects ( including children of children ) to the foundObjects
  199. /// Vector which are of type T and for which DecideAddObjectCallback return true;
  200. template< class T >
  201. void findObjectByCallback( bool ( *fn )( T* ), Vector<T*>& foundObjects );
  202. SimObject* getRandom();
  203. inline void lock()
  204. {
  205. #ifdef TORQUE_MULTITHREAD
  206. Mutex::lockMutex(mMutex);
  207. #endif
  208. }
  209. void unlock()
  210. {
  211. #ifdef TORQUE_MULTITHREAD
  212. Mutex::unlockMutex(mMutex);
  213. #endif
  214. }
  215. #ifdef TORQUE_DEBUG_GUARD
  216. inline void _setVectorAssoc( const char *file, const U32 line )
  217. {
  218. objectList.setFileAssociation( file, line );
  219. }
  220. #endif
  221. // SimObject.
  222. DECLARE_CONOBJECT( SimSet );
  223. virtual void onRemove();
  224. virtual void onDeleteNotify(SimObject *object);
  225. virtual SimObject* findObject( const char* name );
  226. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  227. virtual bool writeObject(Stream *stream);
  228. virtual bool readObject(Stream *stream);
  229. virtual SimSet* clone();
  230. // TamlChildren
  231. virtual U32 getTamlChildCount(void) const
  232. {
  233. return (U32)size();
  234. }
  235. virtual SimObject* getTamlChild(const U32 childIndex) const
  236. {
  237. // Sanity!
  238. AssertFatal(childIndex < (U32)size(), "SimSet::getTamlChild() - Child index is out of range.");
  239. // For when the assert is not used.
  240. if (childIndex >= (U32)size())
  241. return NULL;
  242. return at(childIndex);
  243. }
  244. virtual void addTamlChild(SimObject* pSimObject)
  245. {
  246. // Sanity!
  247. AssertFatal(pSimObject != NULL, "SimSet::addTamlChild() - Cannot add a NULL child object.");
  248. addObject(pSimObject);
  249. }
  250. };
  251. #ifdef TORQUE_DEBUG_GUARD
  252. # define SIMSET_SET_ASSOCIATION( x ) x._setVectorAssoc( __FILE__, __LINE__ )
  253. #else
  254. # define SIMSET_SET_ASSOCIATION( x )
  255. #endif
  256. template< class T >
  257. void SimSet::findObjectByType( Vector<T*> &foundObjects )
  258. {
  259. T *curObj;
  260. SimSet *curSet;
  261. lock();
  262. // Loop through our child objects.
  263. SimObjectList::iterator itr = objectList.begin();
  264. for ( ; itr != objectList.end(); itr++ )
  265. {
  266. curObj = dynamic_cast<T*>( *itr );
  267. curSet = dynamic_cast<SimSet*>( *itr );
  268. // If child object is a set, call recursively into it.
  269. if ( curSet )
  270. curSet->findObjectByType( foundObjects );
  271. // Add this child object if appropriate.
  272. if ( curObj )
  273. foundObjects.push_back( curObj );
  274. }
  275. // Add this object if appropriate.
  276. curObj = dynamic_cast<T*>(this);
  277. if ( curObj )
  278. foundObjects.push_back( curObj );
  279. unlock();
  280. }
  281. template< class T >
  282. void SimSet::findObjectByCallback( bool ( *fn )( T* ), Vector<T*> &foundObjects )
  283. {
  284. T *curObj;
  285. SimSet *curSet;
  286. lock();
  287. // Loop through our child objects.
  288. SimObjectList::iterator itr = objectList.begin();
  289. for ( ; itr != objectList.end(); itr++ )
  290. {
  291. curObj = dynamic_cast<T*>( *itr );
  292. curSet = dynamic_cast<SimSet*>( *itr );
  293. // If child object is a set, call recursively into it.
  294. if ( curSet )
  295. curSet->findObjectByCallback( fn, foundObjects );
  296. // Add this child object if appropriate.
  297. if ( curObj && ( fn == NULL || fn( curObj ) ) )
  298. foundObjects.push_back( curObj );
  299. }
  300. // Add this object if appropriate.
  301. curObj = dynamic_cast<T*>(this);
  302. if ( curObj && ( fn == NULL || fn( curObj ) ) )
  303. foundObjects.push_back( curObj );
  304. unlock();
  305. }
  306. /// An iterator that recursively and exhaustively traverses the contents
  307. /// of a SimSet.
  308. ///
  309. /// @see SimSet
  310. class SimSetIterator
  311. {
  312. protected:
  313. struct Entry {
  314. SimSet* set;
  315. SimSet::iterator itr;
  316. };
  317. class Stack: public Vector<Entry> {
  318. public:
  319. void push_back(SimSet*);
  320. };
  321. Stack stack;
  322. public:
  323. SimSetIterator(SimSet*);
  324. SimObject* operator++();
  325. SimObject* operator*() {
  326. return stack.empty()? 0: *stack.last().itr;
  327. }
  328. };
  329. //---------------------------------------------------------------------------
  330. /// A group of SimObjects.
  331. ///
  332. /// A SimGroup is a stricter form of SimSet. SimObjects may only be a member
  333. /// of a single SimGroup at a time.
  334. ///
  335. /// The SimGroup will automatically enforce the single-group-membership rule.
  336. ///
  337. /// @code
  338. /// // From engine/sim/simPath.cc - getting a pointer to a SimGroup
  339. /// SimGroup* pMissionGroup = dynamic_cast<SimGroup*>(Sim::findObject("MissionGroup"));
  340. ///
  341. /// // From game/trigger.cc:46 - iterating over a SimObject's group.
  342. /// SimObject* trigger = ...;
  343. /// SimGroup* pGroup = trigger->getGroup();
  344. /// for (SimGroup::iterator itr = pGroup->begin(); itr != pGroup->end(); itr++)
  345. /// {
  346. /// // do something with *itr
  347. /// }
  348. /// @endcode
  349. class SimGroup: public SimSet
  350. {
  351. public:
  352. typedef SimSet Parent;
  353. friend class SimManager;
  354. friend class SimObject;
  355. private:
  356. SimNameDictionary mNameDictionary;
  357. void _addObject( SimObject* object, bool forcePushBack = false );
  358. void _removeObjectNoLock( SimObject* );
  359. public:
  360. ~SimGroup();
  361. void addObject( SimObject* object, SimObjectId id);
  362. void addObject( SimObject* object, const char* name );
  363. // SimSet.
  364. virtual void addObject( SimObject* object );
  365. virtual void removeObject( SimObject* object );
  366. virtual void pushObject( SimObject* object );
  367. virtual void popObject();
  368. virtual void clear();
  369. virtual SimGroup* clone();
  370. virtual SimGroup* deepClone();
  371. virtual SimObject* findObject(const char* name);
  372. virtual void onRemove();
  373. virtual bool processArguments( S32 argc, ConsoleValueRef *argv );
  374. DECLARE_CONOBJECT( SimGroup );
  375. };
  376. inline void SimGroup::addObject(SimObject* obj, SimObjectId id)
  377. {
  378. obj->mId = id;
  379. dSprintf( obj->mIdString, sizeof( obj->mIdString ), "%u", obj->mId );
  380. addObject( obj );
  381. }
  382. inline void SimGroup::addObject(SimObject *obj, const char *name)
  383. {
  384. addObject( obj );
  385. obj->assignName(name);
  386. }
  387. /// An iterator that recursively and exhaustively traverses all objects
  388. /// in an SimGroup object tree.
  389. class SimGroupIterator: public SimSetIterator
  390. {
  391. public:
  392. SimGroupIterator(SimGroup* grp): SimSetIterator(grp) {}
  393. SimObject* operator++();
  394. };
  395. #endif // _SIMSET_H_