simSet.h 14 KB

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