simObject.h 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. /// Called when the adding of the object to the sim is complete, all sub-objects have been processed as well
  507. // This is a special-case function that only really gets used with Entities/BehaviorObjects.
  508. virtual void onPostAdd() {}
  509. ///
  510. /// Specifically, these are called by setDataField
  511. /// when a static or dynamic field is modified, see
  512. /// @ref simobject_console "the console details".
  513. virtual void onStaticModified(const char* slotName, const char*newValue = NULL); ///< Called when a static field is modified.
  514. virtual void onDynamicModified(const char* slotName, const char*newValue = NULL); ///< Called when a dynamic field is modified.
  515. /// Called before any property of the object is changed in the world editor.
  516. ///
  517. /// The calling order here is:
  518. /// - inspectPreApply()
  519. /// - ...
  520. /// - calls to setDataField()
  521. /// - ...
  522. /// - inspectPostApply()
  523. virtual void inspectPreApply();
  524. /// Called after any property of the object is changed in the world editor.
  525. ///
  526. /// @see inspectPreApply
  527. virtual void inspectPostApply();
  528. /// Called when a SimObject is deleted.
  529. ///
  530. /// When you are on the notification list for another object
  531. /// and it is deleted, this method is called.
  532. virtual void onDeleteNotify(SimObject *object);
  533. /// Called when the editor is activated.
  534. virtual void onEditorEnable(){};
  535. /// Called when the editor is deactivated.
  536. virtual void onEditorDisable(){};
  537. /// @}
  538. /// Find a named sub-object of this object.
  539. ///
  540. /// This is subclassed in the SimGroup and SimSet classes.
  541. ///
  542. /// For a single object, it just returns NULL, as normal objects cannot have children.
  543. virtual SimObject *findObject(const char *name);
  544. /// @name Notification
  545. /// @{
  546. Notify *removeNotify(void *ptr, Notify::Type); ///< Remove a notification from the list.
  547. void deleteNotify(SimObject* obj); ///< Notify an object when we are deleted.
  548. void clearNotify(SimObject* obj); ///< Notify an object when we are cleared.
  549. void clearAllNotifications(); ///< Remove all notifications for this object.
  550. void processDeleteNotifies(); ///< Send out deletion notifications.
  551. /// Register a reference to this object.
  552. ///
  553. /// You pass a pointer to your reference to this object.
  554. ///
  555. /// When the object is deleted, it will null your
  556. /// pointer, ensuring you don't access old memory.
  557. ///
  558. /// @param obj Pointer to your reference to the object.
  559. void registerReference(SimObject **obj);
  560. /// Unregister a reference to this object.
  561. ///
  562. /// Remove a reference from the list, so that it won't
  563. /// get nulled inappropriately.
  564. ///
  565. /// Call this when you're done with your reference to
  566. /// the object, especially if you're going to free the
  567. /// memory. Otherwise, you may erroneously get something
  568. /// overwritten.
  569. ///
  570. /// @see registerReference
  571. void unregisterReference(SimObject **obj);
  572. /// @}
  573. /// @name Registration
  574. ///
  575. /// SimObjects must be registered with the object system.
  576. /// @{
  577. /// Register an object with the object system.
  578. ///
  579. /// This must be called if you want to keep the object around.
  580. /// In the rare case that you will delete the object immediately, or
  581. /// don't want to be able to use Sim::findObject to locate it, then
  582. /// you don't need to register it.
  583. ///
  584. /// registerObject adds the object to the global ID and name dictionaries,
  585. /// after first assigning it a new ID number. It calls onAdd(). If onAdd fails,
  586. /// it unregisters the object and returns false.
  587. ///
  588. /// If a subclass's onAdd doesn't eventually call SimObject::onAdd(), it will
  589. /// cause an assertion.
  590. bool registerObject();
  591. /// Register the object, forcing the id.
  592. ///
  593. /// @see registerObject()
  594. /// @param id ID to assign to the object.
  595. bool registerObject(U32 id);
  596. /// Register the object, assigning the name.
  597. ///
  598. /// @see registerObject()
  599. /// @param name Name to assign to the object.
  600. bool registerObject(const char *name);
  601. /// Register the object, assigning a name and ID.
  602. ///
  603. /// @see registerObject()
  604. /// @param name Name to assign to the object.
  605. /// @param id ID to assign to the object.
  606. bool registerObject(const char *name, U32 id);
  607. /// Unregister the object from Sim.
  608. ///
  609. /// This performs several operations:
  610. /// - Sets the removed flag.
  611. /// - Call onRemove()
  612. /// - Clear out notifications.
  613. /// - Remove the object from...
  614. /// - its group, if any. (via getGroup)
  615. /// - Sim::gNameDictionary
  616. /// - Sim::gIDDictionary
  617. /// - Finally, cancel any pending events for this object (as it can't receive them now).
  618. void unregisterObject();
  619. /// Unregister, mark as deleted, and free the object.
  620. void deleteObject();
  621. /// Performs a safe delayed delete of the object using a sim event.
  622. void safeDeleteObject();
  623. /// @}
  624. /// @name Accessors
  625. /// @{
  626. /// Return the unique numeric object ID.
  627. SimObjectId getId() const { return mId; }
  628. /// Return the object ID as a string.
  629. const char* getIdString() const { return mIdString; }
  630. /// Return the name of this object.
  631. StringTableEntry getName() const { return objectName; }
  632. /// Return the SimGroup that this object is contained in. Never NULL except for
  633. /// RootGroup and unregistered objects.
  634. SimGroup* getGroup() const { return mGroup; }
  635. /// Assign the given name to this object.
  636. void assignName( const char* name );
  637. void setId(SimObjectId id);
  638. static void setForcedId(SimObjectId id) { smForceId = true; smForcedId = id; } ///< Force an Id on the next registered object.
  639. bool isChildOfGroup(SimGroup* pGroup);
  640. bool isProperlyAdded() const { return mFlags.test(Added); }
  641. bool isDeleted() const { return mFlags.test(Deleted); }
  642. bool isRemoved() const { return mFlags.test(Deleted | Removed); }
  643. virtual bool isLocked() const { return mFlags.test( Locked ); }
  644. virtual void setLocked( bool b );
  645. virtual bool isHidden() const { return mFlags.test( Hidden ); }
  646. virtual void setHidden(bool b);
  647. /// @}
  648. /// @name Sets
  649. ///
  650. /// The object must be properly registered before you can add/remove it to/from a set.
  651. ///
  652. /// All these functions accept either a name or ID to identify the set you wish
  653. /// to operate on. Then they call addObject or removeObject on the set, which
  654. /// sets up appropriate notifications.
  655. ///
  656. /// An object may be in multiple sets at a time.
  657. /// @{
  658. bool addToSet(SimObjectId);
  659. bool addToSet(const char *);
  660. bool removeFromSet(SimObjectId);
  661. bool removeFromSet(const char *);
  662. /// @}
  663. /// @name Serialization
  664. /// @{
  665. /// Determine whether or not a field should be written.
  666. ///
  667. /// @param fiedname The name of the field being written.
  668. /// @param value The value of the field.
  669. virtual bool writeField(StringTableEntry fieldname, const char* value);
  670. /// Output the TorqueScript to recreate this object.
  671. ///
  672. /// This calls writeFields internally.
  673. /// @param stream Stream to output to.
  674. /// @param tabStop Indentation level for this object.
  675. /// @param flags If SelectedOnly is passed here, then
  676. /// only objects marked as selected (using setSelected)
  677. /// will output themselves.
  678. virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
  679. /// Write the fields of this object in TorqueScript.
  680. ///
  681. /// @param stream Stream for output.
  682. /// @param tabStop Indentation level for the fields.
  683. virtual void writeFields(Stream &stream, U32 tabStop);
  684. virtual bool writeObject(Stream *stream);
  685. virtual bool readObject(Stream *stream);
  686. /// Set whether fields created at runtime should be saved. Default is true.
  687. void setCanSaveDynamicFields( bool bCanSave ) { mCanSaveFieldDictionary = bCanSave; }
  688. /// Get whether fields created at runtime should be saved. Default is true.
  689. bool getCanSaveDynamicFields( ) { return mCanSaveFieldDictionary;}
  690. /// Return the object that this object is copying fields from.
  691. SimObject* getCopySource() const { return mCopySource; }
  692. /// Set the object that this object should be copying fields from.
  693. void setCopySource( SimObject* object );
  694. /// Copy fields from another object onto this one.
  695. ///
  696. /// Objects must be of same type. Everything from obj
  697. /// will overwrite what's in this object; extra fields
  698. /// in this object will remain. This includes dynamic
  699. /// fields.
  700. ///
  701. /// @param obj Object to copy from.
  702. void assignFieldsFrom(SimObject *obj);
  703. /// Copy dynamic fields from another object onto this one.
  704. ///
  705. /// Everything from obj will overwrite what's in this
  706. /// object.
  707. ///
  708. /// @param obj Object to copy from.
  709. void assignDynamicFieldsFrom(SimObject *obj);
  710. /// @}
  711. /// Return the object's namespace.
  712. Namespace* getNamespace() { return mNameSpace; }
  713. /// Get next matching item in namespace.
  714. ///
  715. /// This wraps a call to Namespace::tabComplete; it gets the
  716. /// next thing in the namespace, given a starting value
  717. /// and a base length of the string. See
  718. /// Namespace::tabComplete for details.
  719. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  720. /// @name Accessors
  721. /// @{
  722. bool isSelected() const { return mFlags.test(Selected); }
  723. bool isExpanded() const { return mFlags.test(Expanded); }
  724. bool isEditorOnly() const { return mFlags.test( EditorOnly ); }
  725. bool isNameChangeAllowed() const { return !mFlags.test( NoNameChange ); }
  726. bool isAutoDeleted() const { return mFlags.test( AutoDelete ); }
  727. void setSelected(bool sel);
  728. void setExpanded(bool exp) { if(exp) mFlags.set(Expanded); else mFlags.clear(Expanded); }
  729. void setModDynamicFields(bool dyn) { if(dyn) mFlags.set(ModDynamicFields); else mFlags.clear(ModDynamicFields); }
  730. void setModStaticFields(bool sta) { if(sta) mFlags.set(ModStaticFields); else mFlags.clear(ModStaticFields); }
  731. bool canModDynamicFields() { return mFlags.test(ModDynamicFields); }
  732. bool canModStaticFields() { return mFlags.test(ModStaticFields); }
  733. void setAutoDelete( bool val ) { if( val ) mFlags.set( AutoDelete ); else mFlags.clear( AutoDelete ); }
  734. void setEditorOnly( bool val ) { if( val ) mFlags.set( EditorOnly ); else mFlags.clear( EditorOnly ); }
  735. void setNameChangeAllowed( bool val ) { if( val ) mFlags.clear( NoNameChange ); else mFlags.set( NoNameChange ); }
  736. /// Returns boolean specifying if the object can be serialized.
  737. bool getCanSave() const { return !mFlags.test( CannotSave ); }
  738. /// Set serialization flag.
  739. virtual void setCanSave( bool val ) { if( !val ) mFlags.set( CannotSave ); else mFlags.clear( CannotSave ); }
  740. /// Returns true if this object is selected or any group it is a member of is.
  741. bool isSelectedRecursive() const;
  742. /// @}
  743. /// @name Namespace management
  744. /// @{
  745. /// Return name of class namespace set on this object.
  746. StringTableEntry getClassNamespace() const { return mClassName; };
  747. /// Return name of superclass namespace set on this object.
  748. StringTableEntry getSuperClassNamespace() const { return mSuperClassName; };
  749. ///
  750. void setClassNamespace( const char* classNamespace );
  751. ///
  752. void setSuperClassNamespace( const char* superClassNamespace );
  753. /// @}
  754. /// @name Persistent IDs
  755. /// @{
  756. /// Return the persistent ID assigned to this object or NULL.
  757. SimPersistID* getPersistentId() const { return mPersistentId; }
  758. /// Return the persistent ID assigned to this object or assign one to it if it has none.
  759. SimPersistID* getOrCreatePersistentId();
  760. /// @}
  761. /// @name Debugging
  762. /// @{
  763. /// Return a textual description of the object.
  764. virtual String describeSelf() const;
  765. /// Dump the contents of this object to the console. Use the Torque Script dump() and dumpF() functions to
  766. /// call this.
  767. void dumpToConsole( bool includeFunctions=true );
  768. ///added this so that you can print the entire class hierarchy, including script objects,
  769. //from the console or C++.
  770. /// Print the AbstractClassRep hierarchy of this object to the console.
  771. virtual void dumpClassHierarchy();
  772. /// Print the SimGroup hierarchy of this object to the console.
  773. virtual void dumpGroupHierarchy();
  774. /// @}
  775. static void initPersistFields();
  776. /// Copy SimObject to another SimObject (Originally designed for T2D).
  777. virtual void copyTo(SimObject* object);
  778. // Component Console Overrides
  779. virtual bool handlesConsoleMethod(const char * fname, S32 * routingId) { return false; }
  780. virtual void getConsoleMethodData(const char * fname, S32 routingId, S32 * type, S32 * minArgs, S32 * maxArgs, void ** callback, const char ** usage) {}
  781. DECLARE_CONOBJECT( SimObject );
  782. static SimObject* __findObject( const char* id ) { return Sim::findObject( id ); }
  783. static const char* __getObjectId( ConsoleObject* object )
  784. {
  785. SimObject* simObject = static_cast< SimObject* >( object );
  786. if( !simObject )
  787. return "";
  788. else if( simObject->getName() )
  789. return simObject->getName();
  790. return simObject->getIdString();
  791. }
  792. // EngineObject.
  793. virtual void destroySelf();
  794. };
  795. /// Smart SimObject pointer.
  796. ///
  797. /// This class keeps track of the book-keeping necessary
  798. /// to keep a registered reference to a SimObject or subclass
  799. /// thereof.
  800. ///
  801. /// Normally, if you want the SimObject to be aware that you
  802. /// have a reference to it, you must call SimObject::registerReference()
  803. /// when you create the reference, and SimObject::unregisterReference() when
  804. /// you're done. If you change the reference, you must also register/unregister
  805. /// it. This is a big headache, so this class exists to automatically
  806. /// keep track of things for you.
  807. ///
  808. /// @code
  809. /// // Assign an object to the
  810. /// SimObjectPtr<GameBase> mOrbitObject = Sim::findObject("anObject");
  811. ///
  812. /// // Use it as a GameBase*.
  813. /// mOrbitObject->getWorldBox().getCenter(&mPosition);
  814. ///
  815. /// // And reassign it - it will automatically update the references.
  816. /// mOrbitObject = Sim::findObject("anotherObject");
  817. /// @endcode
  818. template< typename T >
  819. class SimObjectPtr : public WeakRefPtr< T >
  820. {
  821. public:
  822. typedef WeakRefPtr< T > Parent;
  823. SimObjectPtr() {}
  824. SimObjectPtr(T *ptr) { this->mReference = NULL; set(ptr); }
  825. SimObjectPtr( const SimObjectPtr& ref ) { this->mReference = NULL; set(ref.mReference); }
  826. T* getObject() const { return Parent::getPointer(); }
  827. ~SimObjectPtr() { set((WeakRefBase::WeakReference*)NULL); }
  828. SimObjectPtr<T>& operator=(const SimObjectPtr ref)
  829. {
  830. set(ref.mReference);
  831. return *this;
  832. }
  833. SimObjectPtr<T>& operator=(T *ptr)
  834. {
  835. set(ptr);
  836. return *this;
  837. }
  838. protected:
  839. void set(WeakRefBase::WeakReference * ref)
  840. {
  841. if( ref == this->mReference )
  842. return;
  843. if( this->mReference )
  844. {
  845. // Auto-delete
  846. T* obj = this->getPointer();
  847. if ( this->mReference->getRefCount() == 2 && obj && obj->isAutoDeleted() )
  848. obj->deleteObject();
  849. this->mReference->decRefCount();
  850. }
  851. this->mReference = NULL;
  852. if( ref )
  853. {
  854. this->mReference = ref;
  855. this->mReference->incRefCount();
  856. }
  857. }
  858. void set(T * obj)
  859. {
  860. set(obj ? obj->getWeakReference() : (WeakRefBase::WeakReference *)NULL);
  861. }
  862. };
  863. #endif // _SIMOBJECT_H_