simObject.h 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 _SIMOBJECT_H_
  23. #define _SIMOBJECT_H_
  24. #ifndef _SIM_H_
  25. #include "console/sim.h"
  26. #endif
  27. #ifndef _CONSOLEOBJECT_H_
  28. #include "console/consoleObject.h"
  29. #endif
  30. #ifndef _BITSET_H_
  31. #include "core/bitSet.h"
  32. #endif
  33. #ifndef _TAML_CALLBACKS_H_
  34. #include "persistence/taml/tamlCallbacks.h"
  35. #endif
  36. class Stream;
  37. class LightManager;
  38. class SimFieldDictionary;
  39. class SimPersistID;
  40. /// Base class for objects involved in the simulation.
  41. ///
  42. /// @section simobject_intro Introduction
  43. ///
  44. /// SimObject is a base class for most of the classes you'll encounter
  45. /// working in Torque. It provides fundamental services allowing "smart"
  46. /// object referencing, creation, destruction, organization, and location.
  47. /// Along with SimEvent, it gives you a flexible event-scheduling system,
  48. /// as well as laying the foundation for the in-game editors, GUI system,
  49. /// and other vital subsystems.
  50. ///
  51. /// @section simobject_subclassing Subclassing
  52. ///
  53. /// You will spend a lot of your time in Torque subclassing, or working
  54. /// with subclasses of, SimObject. SimObject is designed to be easy to
  55. /// subclass.
  56. ///
  57. /// You should not need to override anything in a subclass except:
  58. /// - The constructor/destructor.
  59. /// - processArguments()
  60. /// - onAdd()/onRemove()
  61. /// - onGroupAdd()/onGroupRemove()
  62. /// - onNameChange()
  63. /// - onStaticModified()
  64. /// - onDeleteNotify()
  65. /// - onEditorEnable()/onEditorDisable()
  66. /// - inspectPreApply()/inspectPostApply()
  67. /// - things from ConsoleObject (see ConsoleObject docs for specifics)
  68. ///
  69. /// Of course, if you know what you're doing, go nuts! But in most cases, you
  70. /// shouldn't need to touch things not on that list.
  71. ///
  72. /// When you subclass, you should define a typedef in the class, called Parent,
  73. /// that references the class you're inheriting from.
  74. ///
  75. /// @code
  76. /// class mySubClass : public SimObject {
  77. /// typedef SimObject Parent;
  78. /// ...
  79. /// @endcode
  80. ///
  81. /// Then, when you override a method, put in:
  82. ///
  83. /// @code
  84. /// bool mySubClass::onAdd()
  85. /// {
  86. /// if(!Parent::onAdd())
  87. /// return false;
  88. ///
  89. /// // ... do other things ...
  90. /// }
  91. /// @endcode
  92. ///
  93. /// Of course, you want to replace onAdd with the appropriate method call.
  94. ///
  95. /// @section simobject_lifecycle A SimObject's Life Cycle
  96. ///
  97. /// SimObjects do not live apart. One of the primary benefits of using a
  98. /// SimObject is that you can uniquely identify it and easily find it (using
  99. /// its ID). Torque does this by keeping a global hierarchy of SimGroups -
  100. /// a tree - containing every registered SimObject. You can then query
  101. /// for a given object using Sim::findObject() (or SimSet::findObject() if
  102. /// you want to search only a specific set).
  103. ///
  104. /// @code
  105. /// // Three examples of registering an object.
  106. ///
  107. /// // Method 1:
  108. /// AIClient *aiPlayer = new AIClient();
  109. /// aiPlayer->registerObject();
  110. ///
  111. /// // Method 2:
  112. /// ActionMap* globalMap = new ActionMap;
  113. /// globalMap->registerObject("GlobalActionMap");
  114. ///
  115. /// // Method 3:
  116. /// bool reg = mObj->registerObject(id);
  117. /// @endcode
  118. ///
  119. /// Registering a SimObject performs these tasks:
  120. /// - Marks the object as not cleared and not removed.
  121. /// - Assigns the object a unique SimObjectID if it does not have one already.
  122. /// - Adds the object to the global name and ID dictionaries so it can be found
  123. /// again.
  124. /// - Calls the object's onAdd() method. <b>Note:</b> SimObject::onAdd() performs
  125. /// some important initialization steps. See @ref simobject_subclassing "here
  126. /// for details" on how to properly subclass SimObject.
  127. /// - If onAdd() fails (returns false), it calls unregisterObject().
  128. /// - Checks to make sure that the SimObject was properly initialized (and asserts
  129. /// if not).
  130. ///
  131. /// Calling registerObject() and passing an ID or a name will cause the object to be
  132. /// assigned that name and/or ID before it is registered.
  133. ///
  134. /// Congratulations, you have now registered your object! What now?
  135. ///
  136. /// Well, hopefully, the SimObject will have a long, useful life. But eventually,
  137. /// it must die.
  138. ///
  139. /// There are a two ways a SimObject can die.
  140. /// - First, the game can be shut down. This causes the root SimGroup
  141. /// to be unregistered and deleted. When a SimGroup is unregistered,
  142. /// it unregisters all of its member SimObjects; this results in everything
  143. /// that has been registered with Sim being unregistered, as everything
  144. /// registered with Sim is in the root group.
  145. /// - Second, you can manually kill it off, either by calling unregisterObject()
  146. /// or by calling deleteObject().
  147. ///
  148. /// When you unregister a SimObject, the following tasks are performed:
  149. /// - The object is flagged as removed.
  150. /// - Notifications are cleaned up.
  151. /// - If the object is in a group, then it removes itself from the group.
  152. /// - Delete notifications are sent out.
  153. /// - Finally, the object removes itself from the Sim globals, and tells
  154. /// Sim to get rid of any pending events for it.
  155. ///
  156. /// If you call deleteObject(), all of the above tasks are performed, in addition
  157. /// to some sanity checking to make sure the object was previously added properly,
  158. /// and isn't in the process of being deleted. After the object is unregistered, it
  159. /// deallocates itself.
  160. ///
  161. /// @section simobject_editor Torque Editors
  162. ///
  163. /// SimObjects are one of the building blocks for the in-game editors. They
  164. /// provide a basic interface for the editor to be able to list the fields
  165. /// of the object, update them safely and reliably, and inform the object
  166. /// things have changed.
  167. ///
  168. /// This interface is implemented in the following areas:
  169. /// - onNameChange() is called when the object is renamed.
  170. /// - onStaticModified() is called whenever a static field is modified.
  171. /// - inspectPreApply() is called before the object's fields are updated,
  172. /// when changes are being applied.
  173. /// - inspectPostApply() is called after the object's fields are updated.
  174. /// - onEditorEnable() is called whenever an editor is enabled (for instance,
  175. /// when you hit F11 to bring up the world editor).
  176. /// - onEditorDisable() is called whenever the editor is disabled (for instance,
  177. /// when you hit F11 again to close the world editor).
  178. ///
  179. /// (Note: you can check the variable gEditingMission to see if the mission editor
  180. /// is running; if so, you may want to render special indicators. For instance, the
  181. /// fxFoliageReplicator renders inner and outer radii when the mission editor is
  182. /// runnning.)
  183. ///
  184. /// @section simobject_console The Console
  185. ///
  186. /// SimObject extends ConsoleObject by allowing you to
  187. /// to set arbitrary dynamic fields on the object, as well as
  188. /// statically defined fields. This is done through two methods,
  189. /// setDataField and getDataField, which deal with the complexities of
  190. /// allowing access to two different types of object fields.
  191. ///
  192. /// Static fields take priority over dynamic fields. This is to be
  193. /// expected, as the role of dynamic fields is to allow data to be
  194. /// stored in addition to the predefined fields.
  195. ///
  196. /// The fields in a SimObject are like properties (or fields) in a class.
  197. ///
  198. /// Some fields may be arrays, which is what the array parameter is for; if it's non-null,
  199. /// then it is parsed with dAtoI and used as an index into the array. If you access something
  200. /// as an array which isn't, then you get an empty string.
  201. ///
  202. /// <b>You don't need to read any further than this.</b> Right now,
  203. /// set/getDataField are called a total of 6 times through the entire
  204. /// Torque codebase. Therefore, you probably don't need to be familiar
  205. /// with the details of accessing them. You may want to look at Con::setData
  206. /// instead. Most of the time you will probably be accessing fields directly,
  207. /// or using the scripting language, which in either case means you don't
  208. /// need to do anything special.
  209. ///
  210. /// The functions to get/set these fields are very straightforward:
  211. ///
  212. /// @code
  213. /// setDataField(StringTable->insert("locked", false), NULL, b ? "true" : "false" );
  214. /// curObject->setDataField(curField, curFieldArray, STR.getStringValue());
  215. /// setDataField(slotName, array, value);
  216. /// @endcode
  217. ///
  218. /// <i>For advanced users:</i> There are two flags which control the behavior
  219. /// of these functions. The first is ModStaticFields, which controls whether
  220. /// or not the DataField functions look through the static fields (defined
  221. /// with addField; see ConsoleObject for details) of the class. The second
  222. /// is ModDynamicFields, which controls dynamically defined fields. They are
  223. /// set automatically by the console constructor code.
  224. ///
  225. /// @nosubgrouping
  226. class SimObject: public ConsoleObject, public TamlCallbacks
  227. {
  228. public:
  229. typedef ConsoleObject Parent;
  230. friend class SimManager;
  231. friend class SimGroup;
  232. friend class SimNameDictionary;
  233. friend class SimManagerNameDictionary;
  234. friend class SimIdDictionary;
  235. /// @name Notification
  236. /// @{
  237. struct Notify
  238. {
  239. enum Type
  240. {
  241. ClearNotify, ///< Notified when the object is cleared.
  242. DeleteNotify, ///< Notified when the object is deleted.
  243. ObjectRef, ///< Cleverness to allow tracking of references.
  244. Invalid ///< Mark this notification as unused (used in freeNotify).
  245. } type;
  246. void *ptr; ///< Data (typically referencing or interested object).
  247. Notify *next; ///< Next notification in the linked list.
  248. };
  249. /// @}
  250. /// Flags passed to SimObject::write
  251. enum WriteFlags
  252. {
  253. SelectedOnly = BIT( 0 ), ///< Indicates that only objects marked as selected should be outputted. Used in SimSet.
  254. NoName = BIT( 1 ), ///< Indicates that the object name should not be saved.
  255. IgnoreCanSave = BIT( 2 ), ///< Write out even if CannotSave=true.
  256. };
  257. private:
  258. /// Flags for use in mFlags
  259. enum
  260. {
  261. Deleted = BIT( 0 ), ///< This object is marked for deletion.
  262. Removed = BIT( 1 ), ///< This object has been unregistered from the object system.
  263. Added = BIT( 3 ), ///< This object has been registered with the object system.
  264. Selected = BIT( 4 ), ///< This object has been marked as selected. (in editor)
  265. Expanded = BIT( 5 ), ///< This object has been marked as expanded. (in editor)
  266. ModStaticFields = BIT( 6 ), ///< The object allows you to read/modify static fields
  267. ModDynamicFields = BIT( 7 ), ///< The object allows you to read/modify dynamic fields
  268. AutoDelete = BIT( 8 ), ///< Delete this object when the last ObjectRef is gone.
  269. CannotSave = BIT( 9 ), ///< Object should not be saved.
  270. EditorOnly = BIT( 10 ), ///< This object is for use by the editor only.
  271. NoNameChange = BIT( 11 ), ///< Whether changing the name of this object is allowed.
  272. Hidden = BIT( 12 ), ///< Object is hidden in editors.
  273. Locked = BIT( 13 ), ///< Object is locked in editors.
  274. };
  275. // dictionary information stored on the object
  276. StringTableEntry objectName;
  277. StringTableEntry mOriginalName;
  278. SimObject* nextNameObject;
  279. SimObject* nextManagerNameObject;
  280. SimObject* nextIdObject;
  281. /// SimGroup we're contained in, if any.
  282. SimGroup* mGroup;
  283. /// Flags internal to the object management system.
  284. BitSet32 mFlags;
  285. StringTableEntry mProgenitorFile;
  286. /// Object we are copying fields from.
  287. SimObject* mCopySource;
  288. /// Table of dynamic fields assigned to this object.
  289. SimFieldDictionary *mFieldDictionary;
  290. /// Buffer to store textual representation of this object's numeric ID in.
  291. char mIdString[ 11 ];
  292. /// @name Serialization
  293. /// @{
  294. /// Path to file this SimObject was loaded from.
  295. StringTableEntry mFilename;
  296. /// The line number that the object was declared on if it was loaded from a file.
  297. S32 mDeclarationLine;
  298. /// @}
  299. /// @name Notification
  300. /// @{
  301. /// List of notifications added to this object.
  302. Notify* mNotifyList;
  303. static SimObject::Notify *mNotifyFreeList;
  304. static SimObject::Notify *allocNotify(); ///< Get a free Notify structure.
  305. static void freeNotify(SimObject::Notify*); ///< Mark a Notify structure as free.
  306. /// @}
  307. static bool _setCanSave( void* object, const char* index, const char* data );
  308. static const char* _getCanSave( void* object, const char* data );
  309. static const char* _getHidden( void* object, const char* data )
  310. { if( static_cast< SimObject* >( object )->isHidden() ) return "1"; return "0"; }
  311. static const char* _getLocked( void* object, const char* data )
  312. { if( static_cast< SimObject* >( object )->isLocked() ) return "1"; return "0"; }
  313. static bool _setHidden( void* object, const char* index, const char* data )
  314. { static_cast< SimObject* >( object )->setHidden( dAtob( data ) ); return false; }
  315. static bool _setLocked( void* object, const char* index, const char* data )
  316. { static_cast< SimObject* >( object )->setLocked( dAtob( data ) ); return false; }
  317. // Namespace protected set methods
  318. static bool setClass( void *object, const char *index, const char *data )
  319. { static_cast<SimObject*>(object)->setClassNamespace(data); return false; };
  320. static bool setSuperClass(void *object, const char *index, const char *data)
  321. { static_cast<SimObject*>(object)->setSuperClassNamespace(data); return false; };
  322. static bool writeObjectName(void* obj, StringTableEntry pFieldName)
  323. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->objectName != NULL && simObject->objectName != StringTable->EmptyString(); }
  324. static bool writeCanSaveDynamicFields(void* obj, StringTableEntry pFieldName)
  325. { return static_cast<SimObject*>(obj)->mCanSaveFieldDictionary == false; }
  326. static bool writeInternalName(void* obj, StringTableEntry pFieldName)
  327. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mInternalName != NULL && simObject->mInternalName != StringTable->EmptyString(); }
  328. static bool setParentGroup(void* obj, const char* data);
  329. static bool writeParentGroup(void* obj, StringTableEntry pFieldName)
  330. { return static_cast<SimObject*>(obj)->mGroup != NULL; }
  331. static bool writeSuperclass(void* obj, StringTableEntry pFieldName)
  332. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mSuperClassName != NULL && simObject->mSuperClassName != StringTable->EmptyString(); }
  333. static bool writeClass(void* obj, StringTableEntry pFieldName)
  334. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  335. static bool writeClassName(void* obj, StringTableEntry pFieldName)
  336. { SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
  337. // Group hierarchy protected set method
  338. static bool setProtectedParent(void *object, const char *index, const char *data);
  339. // Object name protected set method
  340. static bool setProtectedName(void *object, const char *index, const char *data);
  341. public:
  342. inline void setProgenitorFile(const char* pFile) { mProgenitorFile = StringTable->insert(pFile); }
  343. inline StringTableEntry getProgenitorFile(void) const { return mProgenitorFile; }
  344. protected:
  345. /// Taml callbacks.
  346. virtual void onTamlPreWrite(void) {}
  347. virtual void onTamlPostWrite(void) {}
  348. virtual void onTamlPreRead(void) {}
  349. virtual void onTamlPostRead(const TamlCustomNodes& customNodes) {}
  350. virtual void onTamlAddParent(SimObject* pParentObject) {}
  351. virtual void onTamlCustomWrite(TamlCustomNodes& customNodes) {}
  352. virtual void onTamlCustomRead(const TamlCustomNodes& customNodes);
  353. /// Id number for this object.
  354. SimObjectId mId;
  355. /// Internal name assigned to the object. Not set by default.
  356. StringTableEntry mInternalName;
  357. static bool smForceId; ///< Force a registered object to use the given Id. Cleared upon use.
  358. static SimObjectId smForcedId; ///< The Id to force upon the object. Poor object.
  359. /// @name Serialization
  360. /// @{
  361. /// Whether dynamic fields should be saved out in serialization. Defaults to true.
  362. bool mCanSaveFieldDictionary;
  363. /// @}
  364. /// @name Persistent IDs
  365. /// @{
  366. /// Persistent ID assigned to this object. Allows to unambiguously refer to this
  367. /// object in serializations regardless of stream object ordering.
  368. SimPersistID* mPersistentId;
  369. static bool _setPersistentID( void* object, const char* index, const char* data );
  370. /// @}
  371. /// @name Namespace management
  372. /// @{
  373. /// The namespace in which method lookup for this object begins.
  374. Namespace* mNameSpace;
  375. /// Name of namespace to use as class namespace.
  376. StringTableEntry mClassName;
  377. /// Name of namespace to use as class super namespace.
  378. StringTableEntry mSuperClassName;
  379. /// Perform namespace linking on this object.
  380. void linkNamespaces();
  381. /// Undo namespace linking on this object.
  382. void unlinkNamespaces();
  383. /// @}
  384. /// Called when the object is selected in the editor.
  385. virtual void _onSelected() {}
  386. /// Called when the object is unselected in the editor.
  387. virtual void _onUnselected() {}
  388. /// We can provide more detail, like object name and id.
  389. virtual String _getLogMessage(const char* fmt, va_list args) const;
  390. DEFINE_CREATE_METHOD
  391. {
  392. T* object = new T;
  393. object->incRefCount();
  394. object->registerObject();
  395. return object;
  396. }
  397. // EngineObject.
  398. virtual void _destroySelf();
  399. public:
  400. /// @name Cloning
  401. /// @{
  402. /// Return a shallow copy of this object.
  403. virtual SimObject* clone();
  404. /// Return a deep copy of this object.
  405. virtual SimObject* deepClone();
  406. /// @}
  407. /// @name Accessors
  408. /// @{
  409. /// Get the value of a field on the object.
  410. ///
  411. /// See @ref simobject_console "here" for a detailed discussion of what this
  412. /// function does.
  413. ///
  414. /// @param slotName Field to access.
  415. /// @param array String containing index into array
  416. /// (if field is an array); if NULL, it is ignored.
  417. const char *getDataField(StringTableEntry slotName, const char *array);
  418. /// Set the value of a field on the object.
  419. ///
  420. /// See @ref simobject_console "here" for a detailed discussion of what this
  421. /// function does.
  422. ///
  423. /// @param slotName Field to access.
  424. /// @param array String containing index into array; if NULL, it is ignored.
  425. /// @param value Value to store.
  426. void setDataField(StringTableEntry slotName, const char *array, const char *value);
  427. const char *getPrefixedDataField(StringTableEntry fieldName, const char *array);
  428. void setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value);
  429. const char *getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType = -1);
  430. void setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType = -1);
  431. StringTableEntry getDataFieldPrefix(StringTableEntry fieldName);
  432. /// Get the type of a field on the object.
  433. ///
  434. /// @param slotName Field to access.
  435. /// @param array String containing index into array
  436. /// (if field is an array); if NULL, it is ignored.
  437. U32 getDataFieldType(StringTableEntry slotName, const char *array);
  438. /// Set the type of a *dynamic* field on the object.
  439. ///
  440. /// @param typeName/Id Console base type name/id to assign to a dynamic field.
  441. /// @param slotName Field to access.
  442. /// @param array String containing index into array
  443. /// (if field is an array); if NULL, it is ignored.
  444. void setDataFieldType(const U32 fieldTypeId, StringTableEntry slotName, const char *array);
  445. void setDataFieldType(const char *typeName, StringTableEntry slotName, const char *array);
  446. /// Get reference to the dictionary containing dynamic fields.
  447. ///
  448. /// See @ref simobject_console "here" for a detailed discussion of what this
  449. /// function does.
  450. ///
  451. /// This dictionary can be iterated over using a SimFieldDictionaryIterator.
  452. SimFieldDictionary * getFieldDictionary() {return(mFieldDictionary);}
  453. // Component Information
  454. inline virtual StringTableEntry getComponentName() { return StringTable->insert( getClassName() ); };
  455. /// These functions support internal naming that is not namespace
  456. /// bound for locating child controls in a generic way.
  457. ///
  458. /// Set the internal name of this control (Not linked to a namespace)
  459. void setInternalName(const char* newname);
  460. /// Get the internal name of this control
  461. StringTableEntry getInternalName() const { return mInternalName; }
  462. /// Set the original name of this control
  463. void setOriginalName(const char* originalName);
  464. /// Get the original name of this control
  465. StringTableEntry getOriginalName() const { return mOriginalName; }
  466. /// These functions allow you to set and access the filename
  467. /// where this object was created.
  468. ///
  469. /// Set the filename
  470. void setFilename(const char* file);
  471. /// Get the filename
  472. StringTableEntry getFilename() const { return mFilename; }
  473. /// These functions are used to track the line number (1-based)
  474. /// on which the object was created if it was loaded from script
  475. ///
  476. /// Set the declaration line number
  477. void setDeclarationLine(U32 lineNumber);
  478. /// Get the declaration line number
  479. S32 getDeclarationLine() const { return mDeclarationLine; }
  480. /// Save object as a TorqueScript File.
  481. virtual bool save( const char* pcFilePath, bool bOnlySelected = false, const char *preappend = NULL );
  482. /// Check if a method exists in the objects current namespace.
  483. virtual bool isMethod( const char* methodName );
  484. /// Return true if the field is defined on the object
  485. virtual bool isField( const char* fieldName, bool includeStatic = true, bool includeDynamic = true );
  486. /// @}
  487. /// @name Initialization
  488. /// @{
  489. ///
  490. SimObject();
  491. virtual ~SimObject();
  492. virtual bool processArguments(S32 argc, ConsoleValueRef *argv); ///< Process constructor options. (ie, new SimObject(1,2,3))
  493. /// @}
  494. /// @name Events
  495. /// @{
  496. /// Called when the object is added to the sim.
  497. virtual bool onAdd();
  498. /// Called when the object is removed from the sim.
  499. virtual void onRemove();
  500. /// Called when the object is added to a SimGroup.
  501. virtual void onGroupAdd();
  502. /// Called when the object is removed from a SimGroup.
  503. virtual void onGroupRemove();
  504. /// Called when the object's name is changed.
  505. virtual void onNameChange(const char *name);
  506. ///
  507. /// Specifically, these are called by setDataField
  508. /// when a static or dynamic field is modified, see
  509. /// @ref simobject_console "the console details".
  510. virtual void onStaticModified(const char* slotName, const char*newValue = NULL); ///< Called when a static field is modified.
  511. virtual void onDynamicModified(const char* slotName, const char*newValue = NULL); ///< Called when a dynamic field is modified.
  512. /// Called before any property of the object is changed in the world editor.
  513. ///
  514. /// The calling order here is:
  515. /// - inspectPreApply()
  516. /// - ...
  517. /// - calls to setDataField()
  518. /// - ...
  519. /// - inspectPostApply()
  520. virtual void inspectPreApply();
  521. /// Called after any property of the object is changed in the world editor.
  522. ///
  523. /// @see inspectPreApply
  524. virtual void inspectPostApply();
  525. /// Called when a SimObject is deleted.
  526. ///
  527. /// When you are on the notification list for another object
  528. /// and it is deleted, this method is called.
  529. virtual void onDeleteNotify(SimObject *object);
  530. /// Called when the editor is activated.
  531. virtual void onEditorEnable(){};
  532. /// Called when the editor is deactivated.
  533. virtual void onEditorDisable(){};
  534. /// @}
  535. /// Find a named sub-object of this object.
  536. ///
  537. /// This is subclassed in the SimGroup and SimSet classes.
  538. ///
  539. /// For a single object, it just returns NULL, as normal objects cannot have children.
  540. virtual SimObject *findObject(const char *name);
  541. /// @name Notification
  542. /// @{
  543. Notify *removeNotify(void *ptr, Notify::Type); ///< Remove a notification from the list.
  544. void deleteNotify(SimObject* obj); ///< Notify an object when we are deleted.
  545. void clearNotify(SimObject* obj); ///< Notify an object when we are cleared.
  546. void clearAllNotifications(); ///< Remove all notifications for this object.
  547. void processDeleteNotifies(); ///< Send out deletion notifications.
  548. /// Register a reference to this object.
  549. ///
  550. /// You pass a pointer to your reference to this object.
  551. ///
  552. /// When the object is deleted, it will null your
  553. /// pointer, ensuring you don't access old memory.
  554. ///
  555. /// @param obj Pointer to your reference to the object.
  556. void registerReference(SimObject **obj);
  557. /// Unregister a reference to this object.
  558. ///
  559. /// Remove a reference from the list, so that it won't
  560. /// get nulled inappropriately.
  561. ///
  562. /// Call this when you're done with your reference to
  563. /// the object, especially if you're going to free the
  564. /// memory. Otherwise, you may erroneously get something
  565. /// overwritten.
  566. ///
  567. /// @see registerReference
  568. void unregisterReference(SimObject **obj);
  569. /// @}
  570. /// @name Registration
  571. ///
  572. /// SimObjects must be registered with the object system.
  573. /// @{
  574. /// Register an object with the object system.
  575. ///
  576. /// This must be called if you want to keep the object around.
  577. /// In the rare case that you will delete the object immediately, or
  578. /// don't want to be able to use Sim::findObject to locate it, then
  579. /// you don't need to register it.
  580. ///
  581. /// registerObject adds the object to the global ID and name dictionaries,
  582. /// after first assigning it a new ID number. It calls onAdd(). If onAdd fails,
  583. /// it unregisters the object and returns false.
  584. ///
  585. /// If a subclass's onAdd doesn't eventually call SimObject::onAdd(), it will
  586. /// cause an assertion.
  587. bool registerObject();
  588. /// Register the object, forcing the id.
  589. ///
  590. /// @see registerObject()
  591. /// @param id ID to assign to the object.
  592. bool registerObject(U32 id);
  593. /// Register the object, assigning the name.
  594. ///
  595. /// @see registerObject()
  596. /// @param name Name to assign to the object.
  597. bool registerObject(const char *name);
  598. /// Register the object, assigning a name and ID.
  599. ///
  600. /// @see registerObject()
  601. /// @param name Name to assign to the object.
  602. /// @param id ID to assign to the object.
  603. bool registerObject(const char *name, U32 id);
  604. /// Unregister the object from Sim.
  605. ///
  606. /// This performs several operations:
  607. /// - Sets the removed flag.
  608. /// - Call onRemove()
  609. /// - Clear out notifications.
  610. /// - Remove the object from...
  611. /// - its group, if any. (via getGroup)
  612. /// - Sim::gNameDictionary
  613. /// - Sim::gIDDictionary
  614. /// - Finally, cancel any pending events for this object (as it can't receive them now).
  615. void unregisterObject();
  616. /// Unregister, mark as deleted, and free the object.
  617. void deleteObject();
  618. /// Performs a safe delayed delete of the object using a sim event.
  619. void safeDeleteObject();
  620. /// @}
  621. /// @name Accessors
  622. /// @{
  623. /// Return the unique numeric object ID.
  624. SimObjectId getId() const { return mId; }
  625. /// Return the object ID as a string.
  626. const char* getIdString() const { return mIdString; }
  627. /// Return the name of this object.
  628. StringTableEntry getName() const { return objectName; }
  629. /// Return the SimGroup that this object is contained in. Never NULL except for
  630. /// RootGroup and unregistered objects.
  631. SimGroup* getGroup() const { return mGroup; }
  632. /// Assign the given name to this object.
  633. void assignName( const char* name );
  634. void setId(SimObjectId id);
  635. static void setForcedId(SimObjectId id) { smForceId = true; smForcedId = id; } ///< Force an Id on the next registered object.
  636. bool isChildOfGroup(SimGroup* pGroup);
  637. bool isProperlyAdded() const { return mFlags.test(Added); }
  638. bool isDeleted() const { return mFlags.test(Deleted); }
  639. bool isRemoved() const { return mFlags.test(Deleted | Removed); }
  640. virtual bool isLocked() const { return mFlags.test( Locked ); }
  641. virtual void setLocked( bool b );
  642. virtual bool isHidden() const { return mFlags.test( Hidden ); }
  643. virtual void setHidden(bool b);
  644. /// @}
  645. /// @name Sets
  646. ///
  647. /// The object must be properly registered before you can add/remove it to/from a set.
  648. ///
  649. /// All these functions accept either a name or ID to identify the set you wish
  650. /// to operate on. Then they call addObject or removeObject on the set, which
  651. /// sets up appropriate notifications.
  652. ///
  653. /// An object may be in multiple sets at a time.
  654. /// @{
  655. bool addToSet(SimObjectId);
  656. bool addToSet(const char *);
  657. bool removeFromSet(SimObjectId);
  658. bool removeFromSet(const char *);
  659. /// @}
  660. /// @name Serialization
  661. /// @{
  662. /// Determine whether or not a field should be written.
  663. ///
  664. /// @param fiedname The name of the field being written.
  665. /// @param value The value of the field.
  666. virtual bool writeField(StringTableEntry fieldname, const char* value);
  667. /// Output the TorqueScript to recreate this object.
  668. ///
  669. /// This calls writeFields internally.
  670. /// @param stream Stream to output to.
  671. /// @param tabStop Indentation level for this object.
  672. /// @param flags If SelectedOnly is passed here, then
  673. /// only objects marked as selected (using setSelected)
  674. /// will output themselves.
  675. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  676. /// Write the fields of this object in TorqueScript.
  677. ///
  678. /// @param stream Stream for output.
  679. /// @param tabStop Indentation level for the fields.
  680. virtual void writeFields(Stream &stream, U32 tabStop);
  681. virtual bool writeObject(Stream *stream);
  682. virtual bool readObject(Stream *stream);
  683. /// Set whether fields created at runtime should be saved. Default is true.
  684. void setCanSaveDynamicFields( bool bCanSave ) { mCanSaveFieldDictionary = bCanSave; }
  685. /// Get whether fields created at runtime should be saved. Default is true.
  686. bool getCanSaveDynamicFields( ) { return mCanSaveFieldDictionary;}
  687. /// Return the object that this object is copying fields from.
  688. SimObject* getCopySource() const { return mCopySource; }
  689. /// Set the object that this object should be copying fields from.
  690. void setCopySource( SimObject* object );
  691. /// Copy fields from another object onto this one.
  692. ///
  693. /// Objects must be of same type. Everything from obj
  694. /// will overwrite what's in this object; extra fields
  695. /// in this object will remain. This includes dynamic
  696. /// fields.
  697. ///
  698. /// @param obj Object to copy from.
  699. void assignFieldsFrom(SimObject *obj);
  700. /// Copy dynamic fields from another object onto this one.
  701. ///
  702. /// Everything from obj will overwrite what's in this
  703. /// object.
  704. ///
  705. /// @param obj Object to copy from.
  706. void assignDynamicFieldsFrom(SimObject *obj);
  707. /// @}
  708. /// Return the object's namespace.
  709. Namespace* getNamespace() { return mNameSpace; }
  710. /// Get next matching item in namespace.
  711. ///
  712. /// This wraps a call to Namespace::tabComplete; it gets the
  713. /// next thing in the namespace, given a starting value
  714. /// and a base length of the string. See
  715. /// Namespace::tabComplete for details.
  716. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  717. /// @name Accessors
  718. /// @{
  719. bool isSelected() const { return mFlags.test(Selected); }
  720. bool isExpanded() const { return mFlags.test(Expanded); }
  721. bool isEditorOnly() const { return mFlags.test( EditorOnly ); }
  722. bool isNameChangeAllowed() const { return !mFlags.test( NoNameChange ); }
  723. bool isAutoDeleted() const { return mFlags.test( AutoDelete ); }
  724. void setSelected(bool sel);
  725. void setExpanded(bool exp) { if(exp) mFlags.set(Expanded); else mFlags.clear(Expanded); }
  726. void setModDynamicFields(bool dyn) { if(dyn) mFlags.set(ModDynamicFields); else mFlags.clear(ModDynamicFields); }
  727. void setModStaticFields(bool sta) { if(sta) mFlags.set(ModStaticFields); else mFlags.clear(ModStaticFields); }
  728. bool canModDynamicFields() { return mFlags.test(ModDynamicFields); }
  729. bool canModStaticFields() { return mFlags.test(ModStaticFields); }
  730. void setAutoDelete( bool val ) { if( val ) mFlags.set( AutoDelete ); else mFlags.clear( AutoDelete ); }
  731. void setEditorOnly( bool val ) { if( val ) mFlags.set( EditorOnly ); else mFlags.clear( EditorOnly ); }
  732. void setNameChangeAllowed( bool val ) { if( val ) mFlags.clear( NoNameChange ); else mFlags.set( NoNameChange ); }
  733. /// Returns boolean specifying if the object can be serialized.
  734. bool getCanSave() const { return !mFlags.test( CannotSave ); }
  735. /// Set serialization flag.
  736. virtual void setCanSave( bool val ) { if( !val ) mFlags.set( CannotSave ); else mFlags.clear( CannotSave ); }
  737. /// Returns true if this object is selected or any group it is a member of is.
  738. bool isSelectedRecursive() const;
  739. /// @}
  740. /// @name Namespace management
  741. /// @{
  742. /// Return name of class namespace set on this object.
  743. StringTableEntry getClassNamespace() const { return mClassName; };
  744. /// Return name of superclass namespace set on this object.
  745. StringTableEntry getSuperClassNamespace() const { return mSuperClassName; };
  746. ///
  747. void setClassNamespace( const char* classNamespace );
  748. ///
  749. void setSuperClassNamespace( const char* superClassNamespace );
  750. /// @}
  751. /// @name Persistent IDs
  752. /// @{
  753. /// Return the persistent ID assigned to this object or NULL.
  754. SimPersistID* getPersistentId() const { return mPersistentId; }
  755. /// Return the persistent ID assigned to this object or assign one to it if it has none.
  756. SimPersistID* getOrCreatePersistentId();
  757. /// @}
  758. /// @name Debugging
  759. /// @{
  760. /// Return a textual description of the object.
  761. virtual String describeSelf() const;
  762. /// Dump the contents of this object to the console. Use the Torque Script dump() and dumpF() functions to
  763. /// call this.
  764. void dumpToConsole( bool includeFunctions=true );
  765. ///added this so that you can print the entire class hierarchy, including script objects,
  766. //from the console or C++.
  767. /// Print the AbstractClassRep hierarchy of this object to the console.
  768. virtual void dumpClassHierarchy();
  769. /// Print the SimGroup hierarchy of this object to the console.
  770. virtual void dumpGroupHierarchy();
  771. /// @}
  772. static void initPersistFields();
  773. /// Copy SimObject to another SimObject (Originally designed for T2D).
  774. virtual void copyTo(SimObject* object);
  775. // Component Console Overrides
  776. virtual bool handlesConsoleMethod(const char * fname, S32 * routingId) { return false; }
  777. virtual void getConsoleMethodData(const char * fname, S32 routingId, S32 * type, S32 * minArgs, S32 * maxArgs, void ** callback, const char ** usage) {}
  778. DECLARE_CONOBJECT( SimObject );
  779. static SimObject* __findObject( const char* id ) { return Sim::findObject( id ); }
  780. static const char* __getObjectId( ConsoleObject* object )
  781. {
  782. SimObject* simObject = static_cast< SimObject* >( object );
  783. if( !simObject )
  784. return "";
  785. else if( simObject->getName() )
  786. return simObject->getName();
  787. return simObject->getIdString();
  788. }
  789. // EngineObject.
  790. virtual void destroySelf();
  791. };
  792. /// Smart SimObject pointer.
  793. ///
  794. /// This class keeps track of the book-keeping necessary
  795. /// to keep a registered reference to a SimObject or subclass
  796. /// thereof.
  797. ///
  798. /// Normally, if you want the SimObject to be aware that you
  799. /// have a reference to it, you must call SimObject::registerReference()
  800. /// when you create the reference, and SimObject::unregisterReference() when
  801. /// you're done. If you change the reference, you must also register/unregister
  802. /// it. This is a big headache, so this class exists to automatically
  803. /// keep track of things for you.
  804. ///
  805. /// @code
  806. /// // Assign an object to the
  807. /// SimObjectPtr<GameBase> mOrbitObject = Sim::findObject("anObject");
  808. ///
  809. /// // Use it as a GameBase*.
  810. /// mOrbitObject->getWorldBox().getCenter(&mPosition);
  811. ///
  812. /// // And reassign it - it will automatically update the references.
  813. /// mOrbitObject = Sim::findObject("anotherObject");
  814. /// @endcode
  815. template< typename T >
  816. class SimObjectPtr : public WeakRefPtr< T >
  817. {
  818. public:
  819. typedef WeakRefPtr< T > Parent;
  820. SimObjectPtr() {}
  821. SimObjectPtr(T *ptr) { this->mReference = NULL; set(ptr); }
  822. SimObjectPtr( const SimObjectPtr& ref ) { this->mReference = NULL; set(ref.mReference); }
  823. T* getObject() const { return Parent::getPointer(); }
  824. ~SimObjectPtr() { set((WeakRefBase::WeakReference*)NULL); }
  825. SimObjectPtr<T>& operator=(const SimObjectPtr ref)
  826. {
  827. set(ref.mReference);
  828. return *this;
  829. }
  830. SimObjectPtr<T>& operator=(T *ptr)
  831. {
  832. set(ptr);
  833. return *this;
  834. }
  835. protected:
  836. void set(WeakRefBase::WeakReference * ref)
  837. {
  838. if( ref == this->mReference )
  839. return;
  840. if( this->mReference )
  841. {
  842. // Auto-delete
  843. T* obj = this->getPointer();
  844. if ( this->mReference->getRefCount() == 2 && obj && obj->isAutoDeleted() )
  845. obj->deleteObject();
  846. this->mReference->decRefCount();
  847. }
  848. this->mReference = NULL;
  849. if( ref )
  850. {
  851. this->mReference = ref;
  852. this->mReference->incRefCount();
  853. }
  854. }
  855. void set(T * obj)
  856. {
  857. set(obj ? obj->getWeakReference() : (WeakRefBase::WeakReference *)NULL);
  858. }
  859. };
  860. #endif // _SIMOBJECT_H_