console.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 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 _CONSOLE_H_
  23. #define _CONSOLE_H_
  24. #ifndef _PLATFORM_H_
  25. #include "platform/platform.h"
  26. #endif
  27. #ifndef _BITSET_H_
  28. #include "collection/bitSet.h"
  29. #endif
  30. #include <stdarg.h>
  31. class SimObject;
  32. struct EnumTable;
  33. class Namespace;
  34. /// Indicates that warnings about undefined script variables should be displayed.
  35. ///
  36. /// @note This is set and controlled by script.
  37. extern bool gWarnUndefinedScriptVariables;
  38. enum StringTableConstants
  39. {
  40. StringTagPrefixByte = 0x01 ///< Magic value prefixed to tagged strings.
  41. };
  42. /// Represents an entry in the log.
  43. struct ConsoleLogEntry
  44. {
  45. /// This field indicates the severity of the log entry.
  46. ///
  47. /// Log entries are filtered and displayed differently based on
  48. /// their severity. Errors are highlighted red, while normal entries
  49. /// are displayed as normal text. Often times, the engine will be
  50. /// configured to hide all log entries except warnings or errors,
  51. /// or to perform a special notification when it encounters an error.
  52. enum Level
  53. {
  54. Normal = 0,
  55. Warning,
  56. Error,
  57. NUM_CLASS
  58. } mLevel;
  59. /// Used to associate a log entry with a module.
  60. ///
  61. /// Log entries can come from different sources; for instance,
  62. /// the scripting engine, or the network code. This allows the
  63. /// logging system to be aware of where different log entries
  64. /// originated from.
  65. enum Type
  66. {
  67. General = 0,
  68. Assert,
  69. Script,
  70. GUI,
  71. Network,
  72. NUM_TYPE
  73. } mType;
  74. /// Indicates the actual log entry.
  75. ///
  76. /// This contains a description of the event being logged.
  77. /// For instance, "unable to access file", or "player connected
  78. /// successfully", or nearly anything else you might imagine.
  79. ///
  80. /// Typically, the description should contain a concise, descriptive
  81. /// string describing whatever is being logged. Whenever possible,
  82. /// include useful details like the name of the file being accessed,
  83. /// or the id of the player or GuiControl, so that if a log needs
  84. /// to be used to locate a bug, it can be done as painlessly as
  85. /// possible.
  86. const char *mString;
  87. };
  88. /// Scripting engine representation of an enum.
  89. ///
  90. /// This data structure is used by the scripting engine
  91. /// to expose enumerations to the scripting language. It
  92. /// acts to relate named constants to integer values, just
  93. /// like an enum in C++.
  94. struct EnumTable
  95. {
  96. /// Number of enumerated items in the table.
  97. S32 size;
  98. /// This represents a specific item in the enumeration.
  99. struct Enums
  100. {
  101. S32 index; ///< Index label maps to.
  102. const char *label;///< Label for this index.
  103. };
  104. Enums *table;
  105. /// Constructor.
  106. ///
  107. /// This sets up the EnumTable with predefined data.
  108. ///
  109. /// @param sSize Size of the table.
  110. /// @param sTable Pointer to table of Enums.
  111. ///
  112. /// @see gLiquidTypeTable
  113. /// @see gAlignTable
  114. EnumTable(S32 sSize, Enums *sTable)
  115. { size = sSize; table = sTable; }
  116. };
  117. typedef const char *StringTableEntry;
  118. /// @defgroup console_callbacks Scripting Engine Callbacks
  119. ///
  120. /// The scripting engine makes heavy use of callbacks to represent
  121. /// function exposed to the scripting language. StringCallback,
  122. /// IntCallback, FloatCallback, VoidCallback, and BoolCallback all
  123. /// represent exposed script functions returning different types.
  124. ///
  125. /// ConsumerCallback is used with the function Con::addConsumer; functions
  126. /// registered with Con::addConsumer are called whenever something is outputted
  127. /// to the console. For instance, the TelnetConsole registers itself with the
  128. /// console so it can echo the console over the network.
  129. ///
  130. /// @note Callbacks to the scripting language - for instance, onExit(), which is
  131. /// a script function called when the engine is shutting down - are handled
  132. /// using Con::executef() and kin.
  133. /// @{
  134. ///
  135. typedef const char * (*StringCallback)(SimObject *obj, S32 argc, const char *argv[]);
  136. typedef S32 (*IntCallback)(SimObject *obj, S32 argc, const char *argv[]);
  137. typedef F32 (*FloatCallback)(SimObject *obj, S32 argc, const char *argv[]);
  138. typedef void (*VoidCallback)(SimObject *obj, S32 argc, const char *argv[]); // We have it return a value so things don't break..
  139. typedef bool (*BoolCallback)(SimObject *obj, S32 argc, const char *argv[]);
  140. typedef void (*ConsumerCallback)(ConsoleLogEntry::Level level, const char *consoleLine);
  141. /// @}
  142. /// @defgroup console_types Scripting Engine Type Functions
  143. ///
  144. /// @see Con::registerType
  145. /// @{
  146. typedef const char* (*GetDataFunction)(void *dptr, EnumTable *tbl, BitSet32 flag);
  147. typedef void (*SetDataFunction)(void *dptr, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag);
  148. /// @}
  149. /// This namespace contains the core of the console functionality.
  150. ///
  151. /// @section con_intro Introduction
  152. ///
  153. /// The console is a key part of Torque's architecture. It allows direct run-time control
  154. /// of many aspects of the engine.
  155. ///
  156. /// @nosubgrouping
  157. namespace Con
  158. {
  159. /// Various configuration constants.
  160. enum Constants
  161. {
  162. /// This is the version number associated with DSO files.
  163. ///
  164. /// If you make any changes to the way the scripting language works
  165. /// (such as DSO format changes, adding/removing op-codes) that would
  166. /// break compatibility, then you should increment this.
  167. ///
  168. /// If you make a really major change, increment it to the next multiple
  169. /// of ten.
  170. ///
  171. /// 12/29/04 - BJG - 33->34 Removed some opcodes, part of namespace upgrade.
  172. /// 12/30/04 - BJG - 34->35 Reordered some things, further general shuffling.
  173. /// 11/03/05 - BJG - 35->36 Integrated new debugger code.
  174. // 09/08/06 - THB - 36->37 New opcode for internal names
  175. // 09/15/06 - THB - 37->38 Added unit conversions
  176. // 11/23/06 - THB - 38->39 Added recursive internal name operator
  177. // 02/15/07 - THB - 39->40 Bumping to 40 for TGB since the console has been majorly hacked without the version number being bumped
  178. // 02/16/07 - THB - 40->41 newmsg operator
  179. // 02/16/07 - PAUP - 41->42 DSOs are read with a pointer before every string(ASTnodes changed). Namespace and HashTable revamped
  180. // 05/17/10 - Luma - 42-43 Adding proper sceneObject physics flags, fixes in general
  181. DSOVersion = 43,
  182. MaxLineLength = 512, ///< Maximum length of a line of console input.
  183. MaxDataTypes = 256 ///< Maximum number of registered data types.
  184. };
  185. /// @name Control Functions
  186. ///
  187. /// The console must be initialized and shutdown appropriately during the
  188. /// lifetime of the app. These functions are used to manage this behavior.
  189. ///
  190. /// @note Torque deals with this aspect of console management, so you don't need
  191. /// to call these functions in normal usage of the engine.
  192. /// @{
  193. /// Initializes the console.
  194. ///
  195. /// This performs the following steps:
  196. /// - Calls Namespace::init() to initialize the scripting namespace hierarchy.
  197. /// - Calls ConsoleConstructor::setup() to initialize globally defined console
  198. /// methods and functions.
  199. /// - Registers some basic global script variables.
  200. /// - Calls AbstractClassRep::init() to initialize Torque's class database.
  201. /// - Registers some basic global script functions that couldn't usefully
  202. /// be defined anywhere else.
  203. void init();
  204. /// Shuts down the console.
  205. ///
  206. /// This performs the following steps:
  207. /// - Closes the console log file.
  208. /// - Calls Namespace::shutdown() to shut down the scripting namespace hierarchy.
  209. void shutdown();
  210. /// Is the console active at this time?
  211. bool isActive();
  212. /// @}
  213. /// @name Console Consumers
  214. ///
  215. /// The console distributes its output through Torque by using
  216. /// consumers. Every time a new line is printed to the console,
  217. /// all the ConsumerCallbacks registered using addConsumer are
  218. /// called, in order.
  219. ///
  220. /// @note The GuiConsole control, which provides the on-screen
  221. /// in-game console, uses a different technique to render
  222. /// the console. It calls getLockLog() to lock the Vector
  223. /// of on-screen console entries, then it renders them as
  224. /// needed. While the Vector is locked, the console will
  225. /// not change the Vector. When the GuiConsole control is
  226. /// done with the console entries, it calls unlockLog()
  227. /// to tell the console that it is again safe to modify
  228. /// the Vector.
  229. ///
  230. /// @see TelnetConsole
  231. /// @see TelnetDebugger
  232. /// @see WinConsole
  233. /// @see MacCarbConsole
  234. /// @see iPhoneConsole
  235. /// @see StdConsole
  236. /// @see ConsoleLogger
  237. ///
  238. /// @{
  239. void addConsumer(ConsumerCallback cb);
  240. void removeConsumer(ConsumerCallback cb);
  241. /// @}
  242. /// @name Miscellaneous
  243. /// @{
  244. /// Remove color marking information from a string.
  245. ///
  246. /// @note It does this in-place, so be careful! It may
  247. /// potentially blast data if you're not careful.
  248. /// When in doubt, make a copy of the string first.
  249. void stripColorChars(char* line);
  250. /// Convert from a relative path to an absolute path.
  251. ///
  252. /// This is used in (among other places) the exec() script function, which
  253. /// takes a parameter indicating a script file and executes it. Script paths
  254. /// can be one of:
  255. /// - <b>Absolute:</b> <i>fps/foo/bar.cs</i> Paths of this sort are passed
  256. /// through.
  257. /// - <b>Mod-relative:</b> <i>~/foo/bar.cs</i> Paths of this sort have their
  258. /// replaced with the name of the current mod.
  259. /// - <b>File-relative:</b> <i>./baz/blip.cs</i> Paths of this sort are
  260. /// calculated relative to the path of the current scripting file.
  261. /// - <b>Expando:</b> <i>^Project/image/happy.png</I> Paths of this sort are
  262. /// relative to the path defined by the expando, in this case the "Project"
  263. /// expando.
  264. ///
  265. /// @param pDstPath Pointer to string buffer to fill with absolute path.
  266. /// @param size Size of buffer pointed to by pDstPath.
  267. /// @param pSrcPath Original, possibly relative path.
  268. bool expandPath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL, const bool ensureTrailingSlash = false );
  269. void collapsePath( char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL );
  270. bool isBasePath( const char* SrcPath, const char* pBasePath );
  271. void ensureTrailingSlash( char* pDstPath, const char* pSrcPath );
  272. bool stripRepeatSlashes( char* pDstPath, const char* pSrcPath, S32 dstSize );
  273. void addPathExpando( const char* pExpandoName, const char* pPath );
  274. void removePathExpando( const char* pExpandoName );
  275. bool isPathExpando( const char* pExpandoName );
  276. StringTableEntry getPathExpando( const char* pExpandoName );
  277. U32 getPathExpandoCount( void );
  278. StringTableEntry getPathExpandoKey( U32 expandoIndex );
  279. StringTableEntry getPathExpandoValue( U32 expandoIndex );
  280. StringTableEntry getModNameFromPath(const char *path);
  281. /// Returns true if fn is a global scripting function.
  282. ///
  283. /// This looks in the global namespace. It also checks to see if fn
  284. /// is in the StringTable; if not, it returns false.
  285. bool isFunction(const char *fn);
  286. /// This is the basis for tab completion in the console.
  287. ///
  288. /// @note This is an internally used function. You probably don't
  289. /// care much about how this works.
  290. ///
  291. /// This function does some basic parsing to try to ascertain the namespace in which
  292. /// we are attempting to do tab completion, then bumps control off to the appropriate
  293. /// tabComplete function, either in SimObject or Namespace.
  294. ///
  295. /// @param inputBuffer Pointer to buffer containing starting data, or last result.
  296. /// @param cursorPos Location of cursor in this buffer. This is used to indicate
  297. /// what part of the string should be kept and what part should
  298. /// be advanced to the next match if any.
  299. /// @param maxResultLength Maximum amount of result data to put into inputBuffer. This
  300. /// is capped by MaxCompletionBufferSize.
  301. /// @param forwardTab Should we go forward to next match or backwards to previous
  302. /// match? True indicates forward.
  303. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab);
  304. /// @}
  305. /// @name Variable Management
  306. /// @{
  307. /// Add a console variable that references the value of a variable in C++ code.
  308. ///
  309. /// If a value is assigned to the console variable the C++ variable is updated,
  310. /// and vice-versa.
  311. ///
  312. /// @param name Global console variable name to create
  313. /// @param type The type of the C++ variable; see the ConsoleDynamicTypes enum for a complete list.
  314. /// @param pointer Pointer to the variable.
  315. /// @see ConsoleDynamicTypes
  316. bool addVariable(const char *name, S32 type, void *pointer);
  317. /// Remove a console variable.
  318. ///
  319. /// @param name Global console variable name to remove
  320. /// @return true if variable existed before removal.
  321. bool removeVariable(const char *name);
  322. /// Assign a string value to a locally scoped console variable
  323. ///
  324. /// @note The context of the variable is determined by gEvalState; that is,
  325. /// by the currently executing code.
  326. ///
  327. /// @param name Local console variable name to set
  328. /// @param value String value to assign to name
  329. void setLocalVariable(const char *name, const char *value);
  330. /// Retrieve the string value to a locally scoped console variable
  331. ///
  332. /// @note The context of the variable is determined by gEvalState; that is,
  333. /// by the currently executing code.
  334. ///
  335. /// @param name Local console variable name to get
  336. const char* getLocalVariable(const char* name);
  337. /// @}
  338. /// @name Global Variable Accessors
  339. /// @{
  340. /// Assign a string value to a global console variable
  341. /// @param name Global console variable name to set
  342. /// @param value String value to assign to this variable.
  343. void setVariable(const char *name, const char *value);
  344. /// Retrieve the string value of a global console variable
  345. /// @param name Global Console variable name to query
  346. /// @return The string value of the variable or "" if the variable does not exist.
  347. const char* getVariable(const char* name);
  348. /// Same as setVariable(), but for bools.
  349. void setBoolVariable (const char* name,bool var);
  350. /// Same as getVariable(), but for bools.
  351. ///
  352. /// @param name Name of the variable.
  353. /// @param def Default value to supply if no matching variable is found.
  354. bool getBoolVariable (const char* name,bool def = false);
  355. /// Same as setVariable(), but for ints.
  356. void setIntVariable (const char* name,S32 var);
  357. /// Same as getVariable(), but for ints.
  358. ///
  359. /// @param name Name of the variable.
  360. /// @param def Default value to supply if no matching variable is found.
  361. S32 getIntVariable (const char* name,S32 def = 0);
  362. /// Same as setVariable(), but for floats.
  363. void setFloatVariable(const char* name,F32 var);
  364. /// Same as getVariable(), but for floats.
  365. ///
  366. /// @param name Name of the variable.
  367. /// @param def Default value to supply if no matching variable is found.
  368. F32 getFloatVariable(const char* name,F32 def = .0f);
  369. /// @}
  370. /// @name Global Function Registration
  371. /// @{
  372. /// Register a C++ function with the console making it a global function callable from the scripting engine.
  373. ///
  374. /// @param name Name of the new function.
  375. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  376. /// @param usage Documentation for this function. @ref console_autodoc
  377. /// @param minArgs Minimum number of arguments this function accepts
  378. /// @param maxArgs Maximum number of arguments this function accepts
  379. void addCommand(const char *name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs);
  380. void addCommand(const char *name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArg); ///< @copydoc addCommand(const char *, StringCallback, const char *, S32, S32)
  381. void addCommand(const char *name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char *, StringCallback, const char *, S32, S32)
  382. void addCommand(const char *name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char *, StringCallback, const char *, S32, S32)
  383. void addCommand(const char *name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char *, StringCallback, const char *, S32, S32)
  384. /// @}
  385. /// @name Namespace Function Registration
  386. /// @{
  387. /// Register a C++ function with the console making it callable
  388. /// as a method of the given namespace from the scripting engine.
  389. ///
  390. /// @param nameSpace Name of the namespace to associate the new function with; this is usually the name of a class.
  391. /// @param name Name of the new function.
  392. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  393. /// @param usage Documentation for this function. @ref console_autodoc
  394. /// @param minArgs Minimum number of arguments this function accepts
  395. /// @param maxArgs Maximum number of arguments this function accepts
  396. void addCommand(const char *nameSpace, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs);
  397. void addCommand(const char *nameSpace, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char*, const char *, StringCallback, const char *, S32, S32)
  398. void addCommand(const char *nameSpace, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char*, const char *, StringCallback, const char *, S32, S32)
  399. void addCommand(const char *nameSpace, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char*, const char *, StringCallback, const char *, S32, S32)
  400. void addCommand(const char *nameSpace, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs); ///< @copydoc addCommand(const char*, const char *, StringCallback, const char *, S32, S32)
  401. /// @}
  402. /// @name Special Purpose Registration
  403. ///
  404. /// These are special-purpose functions that exist to allow commands to be grouped, so
  405. /// that when we generate console docs, they can be more meaningfully presented.
  406. ///
  407. /// @ref console_autodoc "Click here for more information about console docs and grouping."
  408. ///
  409. /// @{
  410. void markCommandGroup (const char * nsName, const char *name, const char* usage=NULL);
  411. void beginCommandGroup(const char * nsName, const char *name, const char* usage);
  412. void endCommandGroup (const char * nsName, const char *name);
  413. /// @deprecated
  414. void addOverload (const char * nsName, const char *name, const char *altUsage);
  415. /// @}
  416. /// @name Console Output
  417. ///
  418. /// These functions process the formatted string and pass it to all the ConsumerCallbacks that are
  419. /// currently registered. The console log file and the console window callbacks are installed by default.
  420. ///
  421. /// @see addConsumer()
  422. /// @see removeConsumer()
  423. /// @{
  424. /// @param _format A stdlib printf style formatted out put string
  425. /// @param ... Variables to be written
  426. void printf(const char *_format, ...);
  427. /// @note The console window colors warning text as LIGHT GRAY.
  428. /// @param _format A stdlib printf style formatted out put string
  429. /// @param ... Variables to be written
  430. void warnf(const char *_format, ...);
  431. /// @note The console window colors warning text as RED.
  432. /// @param _format A stdlib printf style formatted out put string
  433. /// @param ... Variables to be written
  434. void errorf(const char *_format, ...);
  435. /// @note The console window colors warning text as LIGHT GRAY.
  436. /// @param type Allows you to associate the warning message with an internal module.
  437. /// @param _format A stdlib printf style formatted out put string
  438. /// @param ... Variables to be written
  439. /// @see Con::warnf()
  440. void warnf(ConsoleLogEntry::Type type, const char *_format, ...);
  441. /// @note The console window colors warning text as RED.
  442. /// @param type Allows you to associate the warning message with an internal module.
  443. /// @param _format A stdlib printf style formatted out put string
  444. /// @param ... Variables to be written
  445. /// @see Con::errorf()
  446. void errorf(ConsoleLogEntry::Type type, const char *_format, ...);
  447. /// Prints a separator to the console.
  448. inline void printSeparator( void ) { printf("--------------------------------------------------------------------------------"); }
  449. /// Prints a separator to the console.
  450. inline void printBlankLine( void ) { printf(""); }
  451. /// @}
  452. /// Returns true when called from the main thread, false otherwise
  453. bool isMainThread();
  454. /// @name Console Execution
  455. ///
  456. /// These are functions relating to the execution of script code.
  457. ///
  458. /// @{
  459. /// Call a script function from C/C++ code.
  460. ///
  461. /// @param argc Number of elements in the argv parameter
  462. /// @param argv A character string array containing the name of the function
  463. /// to call followed by the arguments to that function.
  464. /// @code
  465. /// // Call a Torque script function called mAbs, having one parameter.
  466. /// char* argv[] = {"abs", "-9"};
  467. /// char* result = execute(2, argv);
  468. /// @endcode
  469. const char *execute(S32 argc, const char* argv[]);
  470. /// @see execute(S32 argc, const char* argv[])
  471. const char *executef(S32 argc, ...);
  472. /// Call a Torque Script member function of a SimObject from C/C++ code.
  473. /// @param object Object on which to execute the method call.
  474. /// @param argc Number of elements in the argv parameter (must be >2, see argv)
  475. /// @param argv A character string array containing the name of the member function
  476. /// to call followed by an empty parameter (gets filled with object ID)
  477. /// followed by arguments to that function.
  478. /// @code
  479. /// // Call the method setMode() on an object, passing it one parameter.
  480. ///
  481. /// char* argv[] = {"setMode", "", "2"};
  482. /// char* result = execute(mysimobject, 3, argv);
  483. /// @endcode
  484. // [neo, 5/10/2007 - #3010]
  485. // Added flag thisCallOnly to bypass dynamic method calls
  486. const char *execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly = false);
  487. /// @see execute(SimObject *, S32 argc, const char *argv[])
  488. const char *executef(SimObject *, S32 argc, ...);
  489. /// Evaluate an arbitrary chunk of code.
  490. ///
  491. /// @param string Buffer containing code to execute.
  492. /// @param echo Should we echo the string to the console?
  493. /// @param fileName Indicate what file this code is coming from; used in error reporting and such.
  494. const char *evaluate(const char* string, bool echo = false, const char *fileName = NULL);
  495. /// Evaluate an arbitrary line of script.
  496. ///
  497. /// This wraps dVsprintf(), so you can substitute parameters into the code being executed.
  498. const char *evaluatef(const char* string, ...);
  499. /// @}
  500. /// @name Console Function Implementation Helpers
  501. ///
  502. /// The functions Con::getIntArg, Con::getFloatArg and Con::getArgBuffer(size) are used to
  503. /// allocate on the console stack string variables that will be passed into the next console
  504. // function called. This allows the console to avoid copying some data.
  505. ///
  506. /// getReturnBuffer lets you allocate stack space to return data in.
  507. /// @{
  508. ///
  509. char *getReturnBuffer(U32 bufferSize);
  510. char *getReturnBuffer(const char *stringToCopy);
  511. char *getArgBuffer(U32 bufferSize);
  512. char *getFloatArg(F64 arg);
  513. char *getIntArg (S32 arg);
  514. char* getBoolArg(bool arg);
  515. /// @}
  516. /// @name Namespaces
  517. /// @{
  518. Namespace *lookupNamespace(const char *nsName);
  519. bool linkNamespaces(const char *parentName, const char *childName);
  520. bool unlinkNamespaces(const char *parentName, const char *childName);
  521. /// @note This should only be called from consoleObject.h
  522. bool classLinkNamespaces(Namespace *parent, Namespace *child);
  523. /// @}
  524. /// @name Logging
  525. /// @{
  526. void getLockLog(ConsoleLogEntry * &log, U32 &size);
  527. void unlockLog(void);
  528. void setLogMode(S32 mode);
  529. /// @}
  530. /// @name Dynamic Type System
  531. /// @{
  532. ///
  533. /* void registerType( const char *typeName, S32 type, S32 size, GetDataFunction gdf, SetDataFunction sdf, bool isDatablockType = false );
  534. void registerType( const char* typeName, S32 type, S32 size, bool isDatablockType = false );
  535. void registerTypeGet( S32 type, GetDataFunction gdf );
  536. void registerTypeSet( S32 type, SetDataFunction sdf );
  537. const char *getTypeName(S32 type);
  538. bool isDatablockType( S32 type ); */
  539. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, EnumTable *tbl = NULL, BitSet32 flag = 0);
  540. const char *getData(S32 type, void *dptr, S32 index, EnumTable *tbl = NULL, BitSet32 flag = 0);
  541. /// @}
  542. };
  543. extern void expandEscape(char *dest, const char *src);
  544. extern bool collapseEscape(char *buf);
  545. extern S32 HashPointer(StringTableEntry ptr);
  546. /// This is the backend for the ConsoleMethod()/ConsoleFunction() macros.
  547. ///
  548. /// See the group ConsoleConstructor Innards for specifics on how this works.
  549. ///
  550. /// @see @ref console_autodoc
  551. /// @nosubgrouping
  552. class ConsoleConstructor
  553. {
  554. public:
  555. /// @name Entry Type Fields
  556. ///
  557. /// One of these is set based on the type of entry we want
  558. /// inserted in the console.
  559. ///
  560. /// @ref console_autodoc
  561. /// @{
  562. StringCallback sc; ///< A function/method that returns a string.
  563. IntCallback ic; ///< A function/method that returns an int.
  564. FloatCallback fc; ///< A function/method that returns a float.
  565. VoidCallback vc; ///< A function/method that returns nothing.
  566. BoolCallback bc; ///< A function/method that returns a bool.
  567. bool group; ///< Indicates that this is a group marker.
  568. bool overload; ///< Indicates that this is an overload marker.
  569. bool ns; ///< Indicates that this is a namespace marker.
  570. /// @deprecated Unused.
  571. /// @}
  572. /// Minimum/maximum number of arguments for the function.
  573. S32 mina, maxa;
  574. const char *usage; ///< Usage string.
  575. const char *funcName; ///< Function name.
  576. const char *className; ///< Class name.
  577. /// @name ConsoleConstructer Innards
  578. ///
  579. /// The ConsoleConstructor class is used as the backend for the ConsoleFunction() and
  580. /// ConsoleMethod() macros. The way it works takes advantage of several properties of
  581. /// C++.
  582. ///
  583. /// The ConsoleFunction()/ConsoleMethod() macros wrap the declaration of a ConsoleConstructor.
  584. ///
  585. /// @code
  586. /// // The definition of a ConsoleFunction using the macro
  587. /// ConsoleFunction(ExpandPath, const char*, 2, 2, "(string filePath)")
  588. /// {
  589. /// argc;
  590. /// char* ret = Con::getReturnBuffer( 1024 );
  591. /// Con::expandPath(ret, 1024, argv[1]);
  592. /// return ret;
  593. /// }
  594. ///
  595. /// // Resulting code
  596. /// static const char* cExpandPath(SimObject *, S32, const char **argv);
  597. /// static ConsoleConstructor
  598. /// gExpandPathobj(NULL,"ExpandPath", cExpandPath,
  599. /// "(string filePath)", 2, 2);
  600. /// static const char* cExpandPath(SimObject *, S32 argc, const char **argv)
  601. /// {
  602. /// argc;
  603. /// char* ret = Con::getReturnBuffer( 1024 );
  604. /// Con::expandPath(ret, 1024, argv[1]);
  605. /// return ret;
  606. /// }
  607. ///
  608. /// // A similar thing happens when you do a ConsoleMethod.
  609. /// @endcode
  610. ///
  611. /// As you can see, several global items are defined when you use the ConsoleFunction method.
  612. /// The macro constructs the name of these items from the parameters you passed it. Your
  613. /// implementation of the console function is is placed in a function with a name based on
  614. /// the actual name of the console funnction. In addition, a ConsoleConstructor is declared.
  615. ///
  616. /// Because it is defined as a global, the constructor for the ConsoleConstructor is called
  617. /// before execution of main() is started. The constructor is called once for each global
  618. /// ConsoleConstructor variable, in the order in which they were defined (this property only holds true
  619. /// within file scope).
  620. ///
  621. /// We have ConsoleConstructor create a linked list at constructor time, by storing a static
  622. /// pointer to the head of the list, and keeping a pointer to the next item in each instance
  623. /// of ConsoleConstructor. init() is a helper function in this process, automatically filling
  624. /// in commonly used fields and updating first and next as needed. In this way, a list of
  625. /// items to add to the console is assemble in memory, ready for use, before we start
  626. /// execution of the program proper.
  627. ///
  628. /// In Con::init(), ConsoleConstructor::setup() is called to process this prepared list. Each
  629. /// item in the list is iterated over, and the appropriate Con namespace functions (usually
  630. /// Con::addCommand) are invoked to register the ConsoleFunctions and ConsoleMethods in
  631. /// the appropriate namespaces.
  632. ///
  633. /// @see Namespace
  634. /// @see Con
  635. /// @{
  636. ConsoleConstructor *next;
  637. static ConsoleConstructor *first;
  638. void init(const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs);
  639. static void setup();
  640. /// @}
  641. /// @name Basic Console Constructors
  642. /// @{
  643. ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char* usage, S32 minArgs, S32 maxArgs);
  644. ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char* usage, S32 minArgs, S32 maxArgs);
  645. ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char* usage, S32 minArgs, S32 maxArgs);
  646. ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char* usage, S32 minArgs, S32 maxArgs);
  647. ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char* usage, S32 minArgs, S32 maxArgs);
  648. /// @}
  649. /// @name Magic Console Constructors
  650. ///
  651. /// These perform various pieces of "magic" related to consoleDoc functionality.
  652. /// @ref console_autodoc
  653. /// @{
  654. /// Indicates a group marker. (A doxygen illusion)
  655. ///
  656. /// @see Con::markCommandGroup
  657. /// @ref console_autodoc
  658. ConsoleConstructor(const char *className, const char *groupName, const char* usage);
  659. /// Indicates a namespace usage string.
  660. ConsoleConstructor(const char *className, const char *usage);
  661. /// @}
  662. };
  663. /// @name Global Console Definition Macros
  664. ///
  665. /// @note If TORQUE_DEBUG is defined, then we gather documentation information, and
  666. /// do some extra sanity checks.
  667. ///
  668. /// @see ConsoleConstructor
  669. /// @ref console_autodoc
  670. /// @{
  671. // O hackery of hackeries
  672. #define conmethod_return_const return (const
  673. #define conmethod_return_S32 return (S32
  674. #define conmethod_return_F32 return (F32
  675. #define conmethod_nullify(val)
  676. #define conmethod_return_void conmethod_nullify(void
  677. #define conmethod_return_bool return (bool
  678. #if !defined(TORQUE_SHIPPING)
  679. // Console function macros
  680. # define ConsoleFunctionGroupBegin(groupName, usage) \
  681. static ConsoleConstructor gConsoleFunctionGroup##groupName##__GroupBegin(NULL,#groupName,usage);
  682. # define ConsoleFunction(name,returnType,minArgs,maxArgs,usage1) \
  683. static returnType c##name(SimObject *, S32, const char **argv); \
  684. static ConsoleConstructor g##name##obj(NULL,#name,c##name,usage1,minArgs,maxArgs); \
  685. static returnType c##name(SimObject *, S32 argc, const char **argv)
  686. # define ConsoleFunctionGroupEnd(groupName) \
  687. static ConsoleConstructor gConsoleFunctionGroup##groupName##__GroupEnd(NULL,#groupName,NULL);
  688. // Console method macros
  689. # define ConsoleNamespace(className, usage) \
  690. static ConsoleConstructor className##__Namespace(#className, usage);
  691. # define ConsoleMethodGroupBegin(className, groupName, usage) \
  692. static ConsoleConstructor className##groupName##__GroupBegin(#className,#groupName,usage);
  693. # define ConsoleMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  694. static inline returnType c##className##name(className *, S32, const char **argv); \
  695. static returnType c##className##name##caster(SimObject *object, S32 argc, const char **argv) { \
  696. AssertFatal( dynamic_cast<className*>( object ), "Object passed to " #name " is not a " #className "!" ); \
  697. conmethod_return_##returnType ) c##className##name(static_cast<className*>(object),argc,argv); \
  698. }; \
  699. static ConsoleConstructor className##name##obj(#className,#name,c##className##name##caster,usage1,minArgs,maxArgs); \
  700. static inline returnType c##className##name(className *object, S32 argc, const char **argv)
  701. # define ConsoleStaticMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  702. static inline returnType c##className##name(S32, const char **); \
  703. static returnType c##className##name##caster(SimObject *object, S32 argc, const char **argv) { \
  704. conmethod_return_##returnType ) c##className##name(argc,argv); \
  705. }; \
  706. static ConsoleConstructor \
  707. className##name##obj(#className,#name,c##className##name##caster,usage1,minArgs,maxArgs); \
  708. static inline returnType c##className##name(S32 argc, const char **argv)
  709. # define ConsoleMethodGroupEnd(className, groupName) \
  710. static ConsoleConstructor className##groupName##__GroupEnd(#className,#groupName,NULL);
  711. #else
  712. // These do nothing if we don't want doc information.
  713. # define ConsoleFunctionGroupBegin(groupName, usage)
  714. # define ConsoleFunctionGroupEnd(groupName)
  715. # define ConsoleNamespace(className, usage)
  716. # define ConsoleMethodGroupBegin(className, groupName, usage)
  717. # define ConsoleMethodGroupEnd(className, groupName)
  718. // These are identical to what's above, we just want to null out the usage strings.
  719. # define ConsoleFunction(name,returnType,minArgs,maxArgs,usage1) \
  720. static returnType c##name(SimObject *, S32, const char **); \
  721. static ConsoleConstructor g##name##obj(NULL,#name,c##name,"",minArgs,maxArgs);\
  722. static returnType c##name(SimObject *, S32 argc, const char **argv)
  723. # define ConsoleMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  724. static inline returnType c##className##name(className *, S32, const char **argv); \
  725. static returnType c##className##name##caster(SimObject *object, S32 argc, const char **argv) { \
  726. conmethod_return_##returnType ) c##className##name(static_cast<className*>(object),argc,argv); \
  727. }; \
  728. static ConsoleConstructor \
  729. className##name##obj(#className,#name,c##className##name##caster,"",minArgs,maxArgs); \
  730. static inline returnType c##className##name(className *object, S32 argc, const char **argv)
  731. # define ConsoleStaticMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  732. static inline returnType c##className##name(S32, const char **); \
  733. static returnType c##className##name##caster(SimObject *object, S32 argc, const char **argv) { \
  734. conmethod_return_##returnType ) c##className##name(argc,argv); \
  735. }; \
  736. static ConsoleConstructor \
  737. className##name##obj(#className,#name,c##className##name##caster,"",minArgs,maxArgs); \
  738. static inline returnType c##className##name(S32 argc, const char **argv)
  739. #endif
  740. /// @}
  741. #endif