consoleObject.h 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 _CONSOLEOBJECT_H_
  23. #define _CONSOLEOBJECT_H_
  24. #ifndef _TVECTOR_H_
  25. #include "core/util/tVector.h"
  26. #endif
  27. #ifndef _STRINGTABLE_H_
  28. #include "core/stringTable.h"
  29. #endif
  30. #ifndef _STRINGFUNCTIONS_H_
  31. #include "core/strings/stringFunctions.h"
  32. #endif
  33. #ifndef _BITSET_H_
  34. #include "core/bitSet.h"
  35. #endif
  36. #ifndef _DYNAMIC_CONSOLETYPES_H_
  37. #include "console/dynamicTypes.h"
  38. #endif
  39. #ifndef _ENGINEOBJECT_H_
  40. #include "console/engineObject.h"
  41. #endif
  42. #ifndef _ENGINEFUNCTIONS_H_
  43. #include "console/engineFunctions.h"
  44. #endif
  45. #ifndef _SIMOBJECTREF_H_
  46. #include "console/simObjectRef.h"
  47. #endif
  48. /// @file
  49. /// Legacy console object system.
  50. /// @ingroup console_system Console System
  51. /// @{
  52. class Namespace;
  53. class ConsoleObject;
  54. enum NetClassTypes
  55. {
  56. NetClassTypeObject = 0,
  57. NetClassTypeDataBlock,
  58. NetClassTypeEvent,
  59. NetClassTypesCount,
  60. };
  61. enum NetClassGroups
  62. {
  63. NetClassGroupGame = 0,
  64. NetClassGroupCommunity,
  65. NetClassGroup3,
  66. NetClassGroup4,
  67. NetClassGroupsCount,
  68. };
  69. enum NetClassMasks
  70. {
  71. NetClassGroupGameMask = BIT(NetClassGroupGame),
  72. NetClassGroupCommunityMask = BIT(NetClassGroupCommunity),
  73. };
  74. enum NetDirection
  75. {
  76. NetEventDirAny,
  77. NetEventDirServerToClient,
  78. NetEventDirClientToServer,
  79. };
  80. class SimObject;
  81. class TypeValidator;
  82. class ConsoleClassObject;
  83. DECLARE_SCOPE( ConsoleAPI );
  84. //=============================================================================
  85. // AbstractClassRep.
  86. //=============================================================================
  87. /// Core functionality for class manipulation.
  88. ///
  89. /// @section AbstractClassRep_intro Introduction (or, Why AbstractClassRep?)
  90. ///
  91. /// Many of Torque's subsystems, especially network, console, and sim,
  92. /// require the ability to programatically instantiate classes. For instance,
  93. /// when objects are ghosted, the networking layer needs to be able to create
  94. /// an instance of the object on the client. When the console scripting
  95. /// language runtime encounters the "new" keyword, it has to be able to fill
  96. /// that request.
  97. ///
  98. /// Since standard C++ doesn't provide a function to create a new instance of
  99. /// an arbitrary class at runtime, one must be created. This is what
  100. /// AbstractClassRep and ConcreteClassRep are all about. They allow the registration
  101. /// and instantiation of arbitrary classes at runtime.
  102. ///
  103. /// In addition, ACR keeps track of the fields (registered via addField() and co.) of
  104. /// a class, allowing programmatic access of class fields.
  105. ///
  106. /// @see ConsoleObject
  107. ///
  108. /// @note In general, you will only access the functionality implemented in this class via
  109. /// ConsoleObject::create(). Most of the time, you will only ever need to use this part
  110. /// part of the engine indirectly - ie, you will use the networking system or the console,
  111. /// or ConsoleObject, and they will indirectly use this code. <b>The following discussion
  112. /// is really only relevant for advanced engine users.</b>
  113. ///
  114. /// @section AbstractClassRep_netstuff NetClasses and Class IDs
  115. ///
  116. /// Torque supports a notion of group, type, and direction for objects passed over
  117. /// the network. Class IDs are assigned sequentially per-group, per-type, so that, for instance,
  118. /// the IDs assigned to Datablocks are seperate from the IDs assigned to NetObjects or NetEvents.
  119. /// This can translate into significant bandwidth savings (especially since the size of the fields
  120. /// for transmitting these bits are determined at run-time based on the number of IDs given out.
  121. ///
  122. /// @section AbstractClassRep_details AbstractClassRep Internals
  123. ///
  124. /// Much like ConsoleConstructor, ACR does some preparatory work at runtime before execution
  125. /// is passed to main(). In actual fact, this preparatory work is done by the ConcreteClassRep
  126. /// template. Let's examine this more closely.
  127. ///
  128. /// If we examine ConsoleObject, we see that two macros must be used in the definition of a
  129. /// properly integrated objects. From the ConsoleObject example:
  130. ///
  131. /// @code
  132. /// // This is from inside the class definition...
  133. /// DECLARE_CONOBJECT(TorqueObject);
  134. ///
  135. /// // And this is from outside the class definition...
  136. /// IMPLEMENT_CONOBJECT(TorqueObject);
  137. /// @endcode
  138. ///
  139. /// What do these things actually do?
  140. ///
  141. /// Not all that much, in fact. They expand to code something like this:
  142. ///
  143. /// @code
  144. /// // This is from inside the class definition...
  145. /// static ConcreteClassRep<TorqueObject> dynClassRep;
  146. /// static AbstractClassRep* getParentStaticClassRep();
  147. /// static AbstractClassRep* getStaticClassRep();
  148. /// virtual AbstractClassRep* getClassRep() const;
  149. /// @endcode
  150. ///
  151. /// @code
  152. /// // And this is from outside the class definition...
  153. /// AbstractClassRep* TorqueObject::getClassRep() const { return &TorqueObject::dynClassRep; }
  154. /// AbstractClassRep* TorqueObject::getStaticClassRep() { return &dynClassRep; }
  155. /// AbstractClassRep* TorqueObject::getParentStaticClassRep() { return Parent::getStaticClassRep(); }
  156. /// ConcreteClassRep<TorqueObject> TorqueObject::dynClassRep("TorqueObject", 0, -1, 0);
  157. /// @endcode
  158. ///
  159. /// As you can see, getClassRep(), getStaticClassRep(), and getParentStaticClassRep() are just
  160. /// accessors to allow access to various ConcreteClassRep instances. This is where the Parent
  161. /// typedef comes into play as well - it lets getParentStaticClassRep() get the right
  162. /// class rep.
  163. ///
  164. /// In addition, dynClassRep is declared as a member of TorqueObject, and defined later
  165. /// on. Much like ConsoleConstructor, ConcreteClassReps add themselves to a global linked
  166. /// list in their constructor.
  167. ///
  168. /// Then, when AbstractClassRep::initialize() is called, from Con::init(), we iterate through
  169. /// the list and perform the following tasks:
  170. /// - Sets up a Namespace for each class.
  171. /// - Call the init() method on each ConcreteClassRep. This method:
  172. /// - Links namespaces between parent and child classes, using Con::classLinkNamespaces.
  173. /// - Calls initPersistFields() and consoleInit().
  174. /// - As a result of calling initPersistFields, the field list for the class is populated.
  175. /// - Assigns network IDs for classes based on their NetGroup membership. Determines
  176. /// bit allocations for network ID fields.
  177. ///
  178. /// @nosubgrouping
  179. class AbstractClassRep : public ConsoleBaseType
  180. {
  181. friend class ConsoleObject;
  182. public:
  183. typedef ConsoleBaseType Parent;
  184. /// @name 'Tructors
  185. /// @{
  186. ///
  187. /// @param conIdPtr Pointer to the static S32 console ID.
  188. /// @param conTypeName Console type name.
  189. AbstractClassRep( S32* conIdPtr, const char* typeName )
  190. : Parent( sizeof( void* ), conIdPtr, typeName )
  191. {
  192. VECTOR_SET_ASSOCIATION( mFieldList );
  193. parentClass = NULL;
  194. mIsRenderEnabled = true;
  195. mIsSelectionEnabled = true;
  196. }
  197. /// @}
  198. /// @name Representation Interface
  199. /// @{
  200. //TODO: move over to EngineTypeNetInfo
  201. S32 mClassGroupMask; ///< Mask indicating in which NetGroups this object belongs.
  202. S32 mClassType; ///< Stores the NetClass of this class.
  203. S32 mNetEventDir; ///< Stores the NetDirection of this class.
  204. S32 mClassId[ NetClassGroupsCount ]; ///< Stores the IDs assigned to this class for each group.
  205. S32 mClassSizeof; ///< Size of instances in bytes.
  206. //TODO: move over to EngineTypeNetInfo
  207. #ifdef TORQUE_NET_STATS
  208. struct NetStatInstance
  209. {
  210. U32 numEvents;
  211. U32 total;
  212. S32 min;
  213. S32 max;
  214. void reset()
  215. {
  216. numEvents = 0;
  217. total = 0;
  218. min = S32_MAX;
  219. max = S32_MIN;
  220. }
  221. void update(U32 amount)
  222. {
  223. numEvents++;
  224. total += amount;
  225. min = getMin((S32)amount, min);
  226. max = getMax((S32)amount, max);
  227. }
  228. NetStatInstance()
  229. {
  230. reset();
  231. }
  232. };
  233. NetStatInstance mNetStatPack;
  234. NetStatInstance mNetStatUnpack;
  235. NetStatInstance mNetStatWrite;
  236. NetStatInstance mNetStatRead;
  237. U32 mDirtyMaskFrequency[32];
  238. U32 mDirtyMaskTotal[32];
  239. void resetNetStats()
  240. {
  241. mNetStatPack.reset();
  242. mNetStatUnpack.reset();
  243. mNetStatWrite.reset();
  244. mNetStatRead.reset();
  245. for(S32 i=0; i<32; i++)
  246. {
  247. mDirtyMaskFrequency[i] = 0;
  248. mDirtyMaskTotal[i] = 0;
  249. }
  250. }
  251. void updateNetStatPack(U32 dirtyMask, U32 length)
  252. {
  253. mNetStatPack.update(length);
  254. for(S32 i=0; i<32; i++)
  255. if(BIT(i) & dirtyMask)
  256. {
  257. mDirtyMaskFrequency[i]++;
  258. mDirtyMaskTotal[i] += length;
  259. }
  260. }
  261. void updateNetStatUnpack(U32 length)
  262. {
  263. mNetStatUnpack.update(length);
  264. }
  265. void updateNetStatWriteData(U32 length)
  266. {
  267. mNetStatWrite.update(length);
  268. }
  269. void updateNetStatReadData(U32 length)
  270. {
  271. mNetStatRead.update(length);
  272. }
  273. #endif
  274. S32 getClassId (U32 netClassGroup) const { return mClassId[ netClassGroup ]; }
  275. static U32 getClassCRC (U32 netClassGroup) { return classCRC[ netClassGroup ]; }
  276. AbstractClassRep* getCommonParent( const AbstractClassRep *otherClass ) const;
  277. /// Return the name of this class.
  278. StringTableEntry getClassName() const { return mClassName; }
  279. /// Return the namespace that contains the methods of this class.
  280. Namespace* getNameSpace() const { return mNamespace; }
  281. /// Return the AbstractClassRep of the class that this class is derived from.
  282. AbstractClassRep* getParentClass() const { return parentClass; }
  283. /// Return the size of instances of this class in bytes.
  284. S32 getSizeof() const { return mClassSizeof; }
  285. /// Return the next class in the global class list link chain.
  286. AbstractClassRep* getNextClass() const { return nextClass; }
  287. /// Return the head of the global class list.
  288. static AbstractClassRep* getClassList() { return classLinkList; }
  289. /// Helper class to see if we are a given class, or a subclass thereof by
  290. /// comparing AbstractClassRep pointers.
  291. bool isSubclassOf( const AbstractClassRep* klass ) const
  292. {
  293. const AbstractClassRep *walk = this;
  294. // Walk up parents, checking for equivalence.
  295. while ( walk )
  296. {
  297. if ( walk == klass )
  298. return true;
  299. walk = walk->parentClass;
  300. };
  301. return false;
  302. }
  303. /// Helper class to see if we are a given class, or a subclass thereof by
  304. /// comparing the class name strings.
  305. bool isSubclassOf( const char *klass ) const
  306. {
  307. klass = StringTable->insert( klass );
  308. // Walk up parents, checking for equivalence.
  309. const AbstractClassRep *walk = this;
  310. while ( walk )
  311. {
  312. if ( walk->mClassName == klass )
  313. return true;
  314. walk = walk->parentClass;
  315. };
  316. return false;
  317. }
  318. /// @deprecated Use isSubclassOf.
  319. bool isClass( const AbstractClassRep* acr ) const
  320. {
  321. return isSubclassOf( acr );
  322. }
  323. virtual ConsoleObject* create () const = 0;
  324. protected:
  325. virtual void init();
  326. const char * mClassName;
  327. AbstractClassRep * nextClass;
  328. AbstractClassRep * parentClass;
  329. Namespace * mNamespace;
  330. /// @}
  331. public:
  332. bool mIsRenderEnabled;
  333. bool mIsSelectionEnabled;
  334. bool isRenderEnabled() const { return mIsRenderEnabled; }
  335. bool isSelectionEnabled() const { return mIsSelectionEnabled; }
  336. /// @name Categories
  337. /// @{
  338. protected:
  339. const char* mCategory;
  340. const char* mDescription;
  341. public:
  342. /// Return the space separated category path for the class.
  343. const char* getCategory() const { return mCategory; }
  344. /// Return a short description string suitable for displaying in tooltips.
  345. const char* getDescription() const { return mDescription; }
  346. /// @}
  347. /// @name Fields
  348. /// @{
  349. public:
  350. /// This is a function pointer typedef to support get/set callbacks for fields
  351. typedef bool (*SetDataNotify)( void *obj, const char *array, const char *data );
  352. typedef const char *(*GetDataNotify)( void *obj, const char *data );
  353. /// These are special field type values used to mark
  354. /// groups and arrays in the field list.
  355. /// @see Field::type
  356. /// @see addArray, endArray
  357. /// @see addGroup, endGroup
  358. /// @see addGroup, endGroup
  359. /// @see addDeprecatedField
  360. enum ACRFieldTypes
  361. {
  362. /// The first custom field type... all fields
  363. /// types greater or equal to this one are not
  364. /// console data types.
  365. ARCFirstCustomField = 0xFFFFFFFB,
  366. /// Marks the start of a fixed size array of fields.
  367. /// @see addArray
  368. StartArrayFieldType = 0xFFFFFFFB,
  369. /// Marks the end of a fixed size array of fields.
  370. /// @see endArray
  371. EndArrayFieldType = 0xFFFFFFFC,
  372. /// Marks the beginning of a group of fields.
  373. /// @see addGroup
  374. StartGroupFieldType = 0xFFFFFFFD,
  375. /// Marks the beginning of a group of fields.
  376. /// @see endGroup
  377. EndGroupFieldType = 0xFFFFFFFE,
  378. /// Marks a field that is depreciated and no
  379. /// longer stores a value.
  380. /// @see addDeprecatedField
  381. DeprecatedFieldType = 0xFFFFFFFF
  382. };
  383. enum FieldFlags
  384. {
  385. FIELD_HideInInspectors = BIT( 0 ), ///< Do not show the field in inspectors.
  386. };
  387. struct Field
  388. {
  389. Field()
  390. : pFieldname( NULL ),
  391. pGroupname( NULL ),
  392. pFieldDocs( NULL ),
  393. groupExpand( false ),
  394. type( 0 ),
  395. offset( 0 ),
  396. elementCount( 0 ),
  397. table( NULL ),
  398. validator( NULL ),
  399. setDataFn( NULL ),
  400. getDataFn( NULL )
  401. {
  402. }
  403. StringTableEntry pFieldname; ///< Name of the field.
  404. const char* pGroupname; ///< Optionally filled field containing the group name.
  405. ///
  406. /// This is filled when type is StartField or EndField
  407. const char* pFieldDocs; ///< Documentation about this field; see consoleDoc.cc.
  408. bool groupExpand; ///< Flag to track expanded/not state of this group in the editor.
  409. U32 type; ///< A data type ID or one of the special custom fields. @see ACRFieldTypes
  410. U32 offset; ///< Memory offset from beginning of class for this field.
  411. S32 elementCount; ///< Number of elements, if this is an array.
  412. const EnumTable * table; ///< If this is an enum, this points to the table defining it.
  413. BitSet32 flag; ///< Stores various flags
  414. TypeValidator *validator; ///< Validator, if any.
  415. SetDataNotify setDataFn; ///< Set data notify Fn
  416. GetDataNotify getDataFn; ///< Get data notify Fn
  417. };
  418. typedef Vector<Field> FieldList;
  419. FieldList mFieldList;
  420. bool mDynamicGroupExpand;
  421. const Field* findField( StringTableEntry fieldName ) const;
  422. /// @}
  423. /// @name Console Type Interface
  424. /// @{
  425. virtual void* getNativeVariable() { return new ( AbstractClassRep* ); } // Any pointer-sized allocation will do.
  426. virtual void deleteNativeVariable( void* var ) { delete reinterpret_cast< AbstractClassRep** >( var ); }
  427. /// @}
  428. /// @name Abstract Class Database
  429. /// @{
  430. protected:
  431. static AbstractClassRep ** classTable[NetClassGroupsCount][NetClassTypesCount];
  432. static AbstractClassRep * classLinkList;
  433. static U32 classCRC[NetClassGroupsCount];
  434. static bool initialized;
  435. static ConsoleObject* create(const char* in_pClassName);
  436. static ConsoleObject* create(const U32 groupId, const U32 typeId, const U32 in_classId);
  437. public:
  438. static U32 NetClassCount [NetClassGroupsCount][NetClassTypesCount];
  439. static U32 NetClassBitSize[NetClassGroupsCount][NetClassTypesCount];
  440. static void registerClassRep(AbstractClassRep*);
  441. static AbstractClassRep* findClassRep(const char* in_pClassName);
  442. static AbstractClassRep* findClassRep( U32 groupId, U32 typeId, U32 classId );
  443. static void removeClassRep(AbstractClassRep*); // This should not be used lightly
  444. static void initialize(); // Called from Con::init once on startup
  445. static void shutdown();
  446. /// @}
  447. };
  448. extern AbstractClassRep::FieldList sg_tempFieldList;
  449. //=============================================================================
  450. // ConcreteClassRep.
  451. //=============================================================================
  452. /// Helper class for AbstractClassRep.
  453. ///
  454. /// @see AbtractClassRep
  455. /// @see ConsoleObject
  456. template< class T >
  457. class ConcreteClassRep : public AbstractClassRep
  458. {
  459. public:
  460. static EnginePropertyTable _smPropertyTable;
  461. static EnginePropertyTable& smPropertyTable;
  462. ConcreteClassRep( const char* name,
  463. const char* conTypeName,
  464. S32* conTypeIdPtr,
  465. S32 netClassGroupMask,
  466. S32 netClassType,
  467. S32 netEventDir,
  468. AbstractClassRep* parent,
  469. const char* ( *parentDesc )() )
  470. : AbstractClassRep( conTypeIdPtr, conTypeName )
  471. {
  472. mClassName = StringTable->insert( name );
  473. mCategory = T::__category();
  474. mTypeInfo = _MAPTYPE< T >();
  475. if( mTypeInfo )
  476. const_cast< EngineTypeInfo* >( mTypeInfo )->mPropertyTable = &smPropertyTable;
  477. if( &T::__description != parentDesc )
  478. mDescription = T::__description();
  479. // Clean up mClassId
  480. for(U32 i = 0; i < NetClassGroupsCount; i++)
  481. mClassId[i] = -1;
  482. // Set properties for this ACR
  483. mClassType = netClassType;
  484. mClassGroupMask = netClassGroupMask;
  485. mNetEventDir = netEventDir;
  486. parentClass = parent;
  487. mClassSizeof = sizeof(T);
  488. // Finally, register ourselves.
  489. registerClassRep(this);
  490. };
  491. /// Perform class specific initialization tasks.
  492. ///
  493. /// Link namespaces, call initPersistFields() and consoleInit().
  494. void init()
  495. {
  496. // Get handle to our parent class, if any, and ourselves (we are our parent's child).
  497. AbstractClassRep *parent = T::getParentStaticClassRep();
  498. AbstractClassRep *child = T::getStaticClassRep();
  499. // If we got reps, then link those namespaces! (To get proper inheritance.)
  500. if(parent && child)
  501. Con::classLinkNamespaces(parent->getNameSpace(), child->getNameSpace());
  502. // Finally, do any class specific initialization...
  503. T::initPersistFields();
  504. T::consoleInit();
  505. // Let the base finish up.
  506. AbstractClassRep::init();
  507. }
  508. /// Wrap constructor.
  509. ConsoleObject* create() const { return new T; }
  510. /// @name Console Type Interface
  511. /// @{
  512. virtual void setData( void* dptr, S32 argc, const char** argv, const EnumTable* tbl, BitSet32 flag )
  513. {
  514. if( argc == 1 )
  515. {
  516. T** obj = ( T** ) dptr;
  517. *obj = dynamic_cast< T* >( T::__findObject( argv[ 0 ] ) );
  518. }
  519. else
  520. Con::errorf( "Cannot set multiple args to a single ConsoleObject*.");
  521. }
  522. virtual const char* getData( void* dptr, const EnumTable* tbl, BitSet32 flag )
  523. {
  524. T** obj = ( T** ) dptr;
  525. return Con::getReturnBuffer( T::__getObjectId( *obj ) );
  526. }
  527. virtual const char* getTypeClassName() { return mClassName; }
  528. virtual const bool isDatablock() { return T::__smIsDatablock; };
  529. /// @}
  530. };
  531. template< typename T > EnginePropertyTable ConcreteClassRep< T >::_smPropertyTable( 0, NULL );
  532. template< typename T > EnginePropertyTable& ConcreteClassRep< T >::smPropertyTable = ConcreteClassRep< T >::_smPropertyTable;
  533. //------------------------------------------------------------------------------
  534. // Forward declaration of this function so it can be used in the class
  535. const char *defaultProtectedGetFn( void *obj, const char *data );
  536. //=============================================================================
  537. // ConsoleObject.
  538. //=============================================================================
  539. /// Interface class to the console.
  540. ///
  541. /// @section ConsoleObject_basics The Basics
  542. ///
  543. /// Any object which you want to work with the console system should derive from this,
  544. /// and access functionality through the static interface.
  545. ///
  546. /// This class is always used with the DECLARE_CONOBJECT and IMPLEMENT_* macros.
  547. ///
  548. /// @code
  549. /// // A very basic example object. It will do nothing!
  550. /// class TorqueObject : public ConsoleObject {
  551. /// // Must provide a Parent typedef so the console system knows what we inherit from.
  552. /// typedef ConsoleObject Parent;
  553. ///
  554. /// // This does a lot of menial declaration for you.
  555. /// DECLARE_CONOBJECT(TorqueObject);
  556. ///
  557. /// // This is for us to register our fields in.
  558. /// static void initPersistFields();
  559. ///
  560. /// // A sample field.
  561. /// S8 mSample;
  562. /// }
  563. /// @endcode
  564. ///
  565. /// @code
  566. /// // And the accordant implementation...
  567. /// IMPLEMENT_CONOBJECT(TorqueObject);
  568. ///
  569. /// void TorqueObject::initPersistFields()
  570. /// {
  571. /// // If you want to inherit any fields from the parent (you do), do this:
  572. /// Parent::initPersistFields();
  573. ///
  574. /// // Pass the field, the type, the offset, and a usage string.
  575. /// addField("sample", TypeS8, Offset(mSample, TorqueObject), "A test field.");
  576. /// }
  577. /// @endcode
  578. ///
  579. /// That's all you need to do to get a class registered with the console system. At this point,
  580. /// you can instantiate it via script, tie methods to it using ConsoleMethod, register fields,
  581. /// and so forth. You can also register any global variables related to the class by creating
  582. /// a consoleInit() method.
  583. ///
  584. /// You will need to use different IMPLEMENT_ macros in different cases; for instance, if you
  585. /// are making a NetObject (for ghosting), a DataBlock, or a NetEvent.
  586. ///
  587. /// @see AbstractClassRep for gory implementation details.
  588. /// @nosubgrouping
  589. class ConsoleObject : public EngineObject
  590. {
  591. DECLARE_ABSTRACT_CLASS( ConsoleObject, EngineObject );
  592. protected:
  593. /// @deprecated This is disallowed.
  594. ConsoleObject(const ConsoleObject&);
  595. public:
  596. ConsoleObject() {}
  597. /// Get a reference to a field by name.
  598. const AbstractClassRep::Field *findField(StringTableEntry fieldName) const;
  599. /// Gets the ClassRep.
  600. virtual AbstractClassRep* getClassRep() const;
  601. /// Set the value of a field.
  602. bool setField(const char *fieldName, const char *value);
  603. public:
  604. /// @name Object Creation
  605. /// @{
  606. static ConsoleObject* create(const char* in_pClassName);
  607. static ConsoleObject* create(const U32 groupId, const U32 typeId, const U32 in_classId);
  608. /// @}
  609. public:
  610. /// Get the classname from a class tag.
  611. static const char* lookupClassName(const U32 in_classTag);
  612. /// @name Fields
  613. /// @{
  614. /// Mark the beginning of a group of fields.
  615. ///
  616. /// This is used in the consoleDoc system.
  617. /// @see console_autodoc
  618. static void addGroup(const char* in_pGroupname, const char* in_pGroupDocs = NULL);
  619. /// Mark the end of a group of fields.
  620. ///
  621. /// This is used in the consoleDoc system.
  622. /// @see console_autodoc
  623. static void endGroup(const char* in_pGroupname);
  624. /// Marks the start of a fixed size array of fields.
  625. /// @see console_autodoc
  626. static void addArray( const char *arrayName, S32 count );
  627. /// Marks the end of an array of fields.
  628. /// @see console_autodoc
  629. static void endArray( const char *arrayName );
  630. /// Register a complex field.
  631. ///
  632. /// @param in_pFieldname Name of the field.
  633. /// @param in_fieldType Type of the field. @see ConsoleDynamicTypes
  634. /// @param in_fieldOffset Offset to the field from the start of the class; calculated using the Offset() macro.
  635. /// @param in_elementCount Number of elements in this field. Arrays of elements are assumed to be contiguous in memory.
  636. /// @param in_pFieldDocs Usage string for this field. @see console_autodoc
  637. static void addField(const char* in_pFieldname,
  638. const U32 in_fieldType,
  639. const dsize_t in_fieldOffset,
  640. const U32 in_elementCount = 1,
  641. const char* in_pFieldDocs = NULL,
  642. U32 flags = 0 );
  643. /// Register a simple field.
  644. ///
  645. /// @param in_pFieldname Name of the field.
  646. /// @param in_fieldType Type of the field. @see ConsoleDynamicTypes
  647. /// @param in_fieldOffset Offset to the field from the start of the class; calculated using the Offset() macro.
  648. /// @param in_pFieldDocs Usage string for this field. @see console_autodoc
  649. static void addField(const char* in_pFieldname,
  650. const U32 in_fieldType,
  651. const dsize_t in_fieldOffset,
  652. const char* in_pFieldDocs,
  653. U32 flags = 0 );
  654. /// Register a validated field.
  655. ///
  656. /// A validated field is just like a normal field except that you can't
  657. /// have it be an array, and that you give it a pointer to a TypeValidator
  658. /// subclass, which is then used to validate any value placed in it. Invalid
  659. /// values are ignored and an error is printed to the console.
  660. ///
  661. /// @see addField
  662. /// @see typeValidators.h
  663. static void addFieldV(const char* in_pFieldname,
  664. const U32 in_fieldType,
  665. const dsize_t in_fieldOffset,
  666. TypeValidator *v,
  667. const char * in_pFieldDocs = NULL);
  668. /// Register a complex protected field.
  669. ///
  670. /// @param in_pFieldname Name of the field.
  671. /// @param in_fieldType Type of the field. @see ConsoleDynamicTypes
  672. /// @param in_fieldOffset Offset to the field from the start of the class; calculated using the Offset() macro.
  673. /// @param in_setDataFn When this field gets set, it will call the callback provided. @see console_protected
  674. /// @param in_getDataFn When this field is accessed for it's data, it will return the value of this function
  675. /// @param in_elementCount Number of elements in this field. Arrays of elements are assumed to be contiguous in memory.
  676. /// @param in_pFieldDocs Usage string for this field. @see console_autodoc
  677. static void addProtectedField(const char* in_pFieldname,
  678. const U32 in_fieldType,
  679. const dsize_t in_fieldOffset,
  680. AbstractClassRep::SetDataNotify in_setDataFn,
  681. AbstractClassRep::GetDataNotify in_getDataFn,
  682. const U32 in_elementCount,
  683. const char* in_pFieldDocs = NULL,
  684. U32 flags = 0 );
  685. /// Register a simple protected field.
  686. ///
  687. /// @param in_pFieldname Name of the field.
  688. /// @param in_fieldType Type of the field. @see ConsoleDynamicTypes
  689. /// @param in_fieldOffset Offset to the field from the start of the class; calculated using the Offset() macro.
  690. /// @param in_setDataFn When this field gets set, it will call the callback provided. @see console_protected
  691. /// @param in_getDataFn When this field is accessed for it's data, it will return the value of this function
  692. /// @param in_pFieldDocs Usage string for this field. @see console_autodoc
  693. static void addProtectedField(const char* in_pFieldname,
  694. const U32 in_fieldType,
  695. const dsize_t in_fieldOffset,
  696. AbstractClassRep::SetDataNotify in_setDataFn,
  697. AbstractClassRep::GetDataNotify in_getDataFn = &defaultProtectedGetFn,
  698. const char* in_pFieldDocs = NULL,
  699. U32 flags = 0 );
  700. /// Add a deprecated field.
  701. ///
  702. /// A deprecated field will always be undefined, even if you assign a value to it. This
  703. /// is useful when you need to make sure that a field is not being used anymore.
  704. static void addDeprecatedField(const char *fieldName);
  705. /// Remove a field.
  706. ///
  707. /// Sometimes, you just have to remove a field!
  708. /// @returns True on success.
  709. static bool removeField(const char* in_pFieldname);
  710. /// @}
  711. /// @name Logging
  712. /// @{
  713. /// Overload this in subclasses to change the message formatting.
  714. /// @param fmt A printf style format string.
  715. /// @param args A va_list containing the args passed ot a log function.
  716. /// @note It is suggested that you use String::VToString.
  717. virtual String _getLogMessage(const char* fmt, void* args) const;
  718. /// @}
  719. public:
  720. /// @name Logging
  721. /// These functions will try to print out a message along the lines
  722. /// of "ObjectClass - ObjectName(ObjectId) - formatted message"
  723. /// @{
  724. /// Logs with Con::printf.
  725. void logMessage(const char* fmt, ...) const;
  726. /// Logs with Con::warnf.
  727. void logWarning(const char* fmt, ...) const;
  728. /// Logs with Con::errorf.
  729. void logError(const char* fmt, ...) const;
  730. /// @}
  731. /// Register dynamic fields in a subclass of ConsoleObject.
  732. ///
  733. /// @see addField(), addFieldV(), addDeprecatedField(), addGroup(), endGroup()
  734. static void initPersistFields();
  735. /// Register global constant variables and do other one-time initialization tasks in
  736. /// a subclass of ConsoleObject.
  737. ///
  738. /// @deprecated You should use ConsoleMethod and ConsoleFunction, not this, to
  739. /// register methods or commands.
  740. /// @see console
  741. static void consoleInit();
  742. /// @name Field List
  743. /// @{
  744. /// Get a list of all the fields. This information cannot be modified.
  745. const AbstractClassRep::FieldList& getFieldList() const;
  746. /// Get a list of all the fields, set up so we can modify them.
  747. ///
  748. /// @note This is a bad trick to pull if you aren't very careful,
  749. /// since you can blast field data!
  750. AbstractClassRep::FieldList& getModifiableFieldList();
  751. /// Get a handle to a boolean telling us if we expanded the dynamic group.
  752. ///
  753. /// @see GuiInspector::Inspect()
  754. bool& getDynamicGroupExpand();
  755. /// @}
  756. /// @name ConsoleObject Implementation
  757. ///
  758. /// These functions are implemented in every subclass of
  759. /// ConsoleObject by an IMPLEMENT_CONOBJECT or IMPLEMENT_CO_* macro.
  760. /// @{
  761. /// Get the abstract class information for this class.
  762. static AbstractClassRep *getStaticClassRep() { return NULL; }
  763. /// Get the abstract class information for this class's superclass.
  764. static AbstractClassRep *getParentStaticClassRep() { return NULL; }
  765. /// Get our network-layer class id.
  766. ///
  767. /// @param netClassGroup The net class for which we want our ID.
  768. /// @see
  769. S32 getClassId(U32 netClassGroup) const;
  770. /// Get our compiler and platform independent class name.
  771. ///
  772. /// @note This name can be used to instantiate another instance using create()
  773. StringTableEntry getClassName() const;
  774. /// @}
  775. static const char* __category() { return ""; }
  776. static const char* __description() { return ""; }
  777. /// Subclasses of ConsoleObjects that are datablocks should redefine this static member variable
  778. /// and set it to true.
  779. static const bool __smIsDatablock = false;
  780. /// @name Object IDs and lookup.
  781. /// For a subclass hierarchy based on ConsoleObject to become functional for use as a console object type,
  782. /// the hierarchy must implement a naming scheme and indexing function for looking up objects by name.
  783. /// @{
  784. static ConsoleObject* __findObject( const char* ) { return NULL; }
  785. static const char* __getObjectId( ConsoleObject* ) { return ""; }
  786. };
  787. #define addNamedField(fieldName,type,className) addField(#fieldName, type, Offset(fieldName,className))
  788. #define addNamedFieldV(fieldName,type,className, validator) addFieldV(#fieldName, type, Offset(fieldName,className), validator)
  789. //------------------------------------------------------------------------------
  790. //-------------------------------------- Inlines
  791. //
  792. inline S32 ConsoleObject::getClassId(U32 netClassGroup) const
  793. {
  794. AssertFatal(getClassRep() != NULL,"Cannot get tag from non-declared dynamic class!");
  795. return getClassRep()->getClassId(netClassGroup);
  796. }
  797. inline StringTableEntry ConsoleObject::getClassName() const
  798. {
  799. AssertFatal(getClassRep() != NULL,
  800. "Cannot get tag from non-declared dynamic class");
  801. return getClassRep()->getClassName();
  802. }
  803. inline const AbstractClassRep::Field * ConsoleObject::findField(StringTableEntry name) const
  804. {
  805. AssertFatal(getClassRep() != NULL,
  806. avar("Cannot get field '%s' from non-declared dynamic class.", name));
  807. return getClassRep()->findField(name);
  808. }
  809. inline bool ConsoleObject::setField(const char *fieldName, const char *value)
  810. {
  811. //sanity check
  812. if ((! fieldName) || (! fieldName[0]) || (! value))
  813. return false;
  814. if (! getClassRep())
  815. return false;
  816. const AbstractClassRep::Field *myField = getClassRep()->findField(StringTable->insert(fieldName));
  817. if (! myField)
  818. return false;
  819. Con::setData(
  820. myField->type,
  821. (void *) (((const char *)(this)) + myField->offset),
  822. 0,
  823. 1,
  824. &value,
  825. myField->table,
  826. myField->flag);
  827. return true;
  828. }
  829. inline ConsoleObject* ConsoleObject::create(const char* in_pClassName)
  830. {
  831. return AbstractClassRep::create(in_pClassName);
  832. }
  833. inline ConsoleObject* ConsoleObject::create(const U32 groupId, const U32 typeId, const U32 in_classId)
  834. {
  835. return AbstractClassRep::create(groupId, typeId, in_classId);
  836. }
  837. inline const AbstractClassRep::FieldList& ConsoleObject::getFieldList() const
  838. {
  839. return getClassRep()->mFieldList;
  840. }
  841. inline AbstractClassRep::FieldList& ConsoleObject::getModifiableFieldList()
  842. {
  843. return getClassRep()->mFieldList;
  844. }
  845. inline bool& ConsoleObject::getDynamicGroupExpand()
  846. {
  847. return getClassRep()->mDynamicGroupExpand;
  848. }
  849. /// @name ConsoleObject Macros
  850. /// @{
  851. #define DECLARE_CONOBJECT( className ) \
  852. DECLARE_CLASS( className, Parent ); \
  853. static S32 _smTypeId; \
  854. static ConcreteClassRep< className > dynClassRep; \
  855. static AbstractClassRep* getParentStaticClassRep(); \
  856. static AbstractClassRep* getStaticClassRep(); \
  857. static SimObjectRefConsoleBaseType< className > ptrRefType; \
  858. virtual AbstractClassRep* getClassRep() const
  859. #define DECLARE_CATEGORY( string ) \
  860. static const char* __category() { return string; }
  861. #define DECLARE_DESCRIPTION( string ) \
  862. static const char* __description() { return string; }
  863. #define IMPLEMENT_CONOBJECT( className ) \
  864. IMPLEMENT_CLASS( className, NULL ) \
  865. END_IMPLEMENT_CLASS; \
  866. S32 className::_smTypeId; \
  867. SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
  868. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  869. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  870. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  871. ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, 0, -1, 0, className::getParentStaticClassRep(), &Parent::__description )
  872. #define IMPLEMENT_CO_NETOBJECT_V1( className ) \
  873. IMPLEMENT_CLASS( className, NULL ) \
  874. END_IMPLEMENT_CLASS; \
  875. S32 className::_smTypeId; \
  876. SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
  877. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  878. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  879. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  880. ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeObject, 0, className::getParentStaticClassRep(), &Parent::__description )
  881. #define IMPLEMENT_CO_DATABLOCK_V1( className ) \
  882. IMPLEMENT_CLASS( className, NULL ) \
  883. END_IMPLEMENT_CLASS; \
  884. S32 className::_smTypeId; \
  885. SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
  886. AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
  887. AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
  888. AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
  889. ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeDataBlock, 0, className::getParentStaticClassRep(), &Parent::__description )
  890. // Support for adding properties to classes CONOBJECT style.
  891. #define PROPERTY_TABLE( className ) \
  892. namespace { namespace _ ## className { \
  893. extern EnginePropertyTable _propTable; \
  894. } } \
  895. template<> EnginePropertyTable& \
  896. ConcreteClassRep< className >::smPropertyTable = _ ## className::_propTable; \
  897. namespace { namespace _ ## className { \
  898. EnginePropertyTable::Property _props[] = {
  899. #define END_PROPERTY_TABLE \
  900. { NULL } \
  901. }; \
  902. EnginePropertyTable _propTable( sizeof( _props ) / sizeof( _props[ 0 ] ) - 1, _props ); \
  903. } }
  904. /// Add an auto-doc for a class.
  905. #define ConsoleDocClass( className, docString ) \
  906. CLASSDOC( className, docString )
  907. /// @}
  908. //------------------------------------------------------------------------------
  909. // Protected field default get/set functions
  910. //
  911. // The reason for these functions is that it will save one branch per console
  912. // data request and script functions will still execute at the same speed as
  913. // before the modifications to allow protected static fields. These will just
  914. // inline and the code should be roughly the same size, and just as fast as
  915. // before the modifications. -pw
  916. inline bool defaultProtectedSetFn( void *object, const char *index, const char *data )
  917. {
  918. return true;
  919. }
  920. inline bool defaultProtectedSetNotEmptyFn( void *object, const char *index, const char *data )
  921. {
  922. return data && data[0];
  923. }
  924. inline const char *defaultProtectedGetFn( void *obj, const char *data )
  925. {
  926. return data;
  927. }
  928. inline const char *emptyStringProtectedGetFn( void *obj, const char *data )
  929. {
  930. return "";
  931. }
  932. /// @}
  933. #endif //_CONSOLEOBJECT_H_