console.h 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  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 _CONSOLE_H_
  23. #define _CONSOLE_H_
  24. #ifndef _PLATFORM_H_
  25. #include "platform/platform.h"
  26. #endif
  27. #ifndef _BITSET_H_
  28. #include "core/bitSet.h"
  29. #endif
  30. #ifndef _REFBASE_H_
  31. #include "core/util/refBase.h"
  32. #endif
  33. #include <stdarg.h>
  34. #include "core/util/str.h"
  35. #include "core/util/journal/journaledSignal.h"
  36. #include "core/stringTable.h"
  37. class SimObject;
  38. class Namespace;
  39. struct ConsoleFunctionHeader;
  40. class EngineEnumTable;
  41. typedef EngineEnumTable EnumTable;
  42. typedef U32 StringStackPtr;
  43. template< typename T > S32 TYPEID();
  44. /// @defgroup console_system Console System
  45. /// The Console system is the basis for logging, SimObject, and TorqueScript itself.
  46. ///
  47. /// @{
  48. /// Indicates that warnings about undefined script variables should be displayed.
  49. ///
  50. /// @note This is set and controlled by script.
  51. extern bool gWarnUndefinedScriptVariables;
  52. enum StringTableConstants
  53. {
  54. StringTagPrefixByte = 0x01 ///< Magic value prefixed to tagged strings.
  55. };
  56. /// Represents an entry in the log.
  57. struct ConsoleLogEntry
  58. {
  59. /// This field indicates the severity of the log entry.
  60. ///
  61. /// Log entries are filtered and displayed differently based on
  62. /// their severity. Errors are highlighted red, while normal entries
  63. /// are displayed as normal text. Often times, the engine will be
  64. /// configured to hide all log entries except warnings or errors,
  65. /// or to perform a special notification when it encounters an error.
  66. enum Level
  67. {
  68. Normal = 0,
  69. Warning,
  70. Error,
  71. NUM_CLASS
  72. } mLevel;
  73. /// Used to associate a log entry with a module.
  74. ///
  75. /// Log entries can come from different sources; for instance,
  76. /// the scripting engine, or the network code. This allows the
  77. /// logging system to be aware of where different log entries
  78. /// originated from.
  79. enum Type
  80. {
  81. General = 0,
  82. Assert,
  83. Script,
  84. GUI,
  85. Network,
  86. GGConnect,
  87. NUM_TYPE
  88. } mType;
  89. /// Indicates the actual log entry.
  90. ///
  91. /// This contains a description of the event being logged.
  92. /// For instance, "unable to access file", or "player connected
  93. /// successfully", or nearly anything else you might imagine.
  94. ///
  95. /// Typically, the description should contain a concise, descriptive
  96. /// string describing whatever is being logged. Whenever possible,
  97. /// include useful details like the name of the file being accessed,
  98. /// or the id of the player or GuiControl, so that if a log needs
  99. /// to be used to locate a bug, it can be done as painlessly as
  100. /// possible.
  101. const char *mString;
  102. };
  103. typedef const char *StringTableEntry;
  104. extern char *typeValueEmpty;
  105. enum ConsoleValueType
  106. {
  107. cvInteger = -4,
  108. cvFloat = -3,
  109. cvString = -2,
  110. cvSTEntry = -1,
  111. cvConsoleValueType = 0
  112. };
  113. struct ConsoleValueConsoleType
  114. {
  115. void* dataPtr;
  116. EnumTable* enumTable;
  117. };
  118. class ConsoleValue
  119. {
  120. union
  121. {
  122. F64 f;
  123. S64 i;
  124. char* s;
  125. void* data;
  126. ConsoleValueConsoleType* ct;
  127. };
  128. S32 type;
  129. enum Constants
  130. {
  131. ConversionBufferSize = 32
  132. };
  133. static char sConversionBuffer[ConversionBufferSize];
  134. char* convertToBuffer() const;
  135. TORQUE_FORCEINLINE bool hasAllocatedData() const
  136. {
  137. return (type == ConsoleValueType::cvString || isConsoleType()) && data != NULL;
  138. }
  139. const char* getConsoleData() const;
  140. TORQUE_FORCEINLINE void cleanupData()
  141. {
  142. if (hasAllocatedData())
  143. {
  144. dFree(data);
  145. data = NULL;
  146. }
  147. }
  148. TORQUE_FORCEINLINE void _move(ConsoleValue&& ref) noexcept
  149. {
  150. type = ref.type;
  151. switch (ref.type)
  152. {
  153. case cvInteger:
  154. i = ref.i;
  155. break;
  156. case cvFloat:
  157. f = ref.f;
  158. break;
  159. case cvSTEntry:
  160. TORQUE_CASE_FALLTHROUGH;
  161. case cvString:
  162. s = ref.s;
  163. break;
  164. default:
  165. data = ref.data;
  166. break;
  167. }
  168. ref.data = NULL;
  169. ref.setEmptyString();
  170. }
  171. public:
  172. ConsoleValue()
  173. {
  174. type = ConsoleValueType::cvSTEntry;
  175. s = const_cast<char*>(StringTable->EmptyString());
  176. }
  177. ConsoleValue(ConsoleValue&& ref) noexcept
  178. {
  179. _move(std::move(ref));
  180. }
  181. TORQUE_FORCEINLINE ConsoleValue& operator=(ConsoleValue&& ref) noexcept
  182. {
  183. _move(std::move(ref));
  184. return *this;
  185. }
  186. ConsoleValue(const ConsoleValue&) = delete;
  187. ConsoleValue& operator=(const ConsoleValue&) = delete;
  188. TORQUE_FORCEINLINE ~ConsoleValue()
  189. {
  190. cleanupData();
  191. }
  192. TORQUE_FORCEINLINE void reset()
  193. {
  194. setEmptyString();
  195. }
  196. TORQUE_FORCEINLINE F64 getFloat() const
  197. {
  198. if (type == ConsoleValueType::cvFloat)
  199. return f;
  200. if (type == ConsoleValueType::cvInteger)
  201. return i;
  202. if (isStringType())
  203. return dAtof(s);
  204. return dAtof(getConsoleData());
  205. }
  206. TORQUE_FORCEINLINE S64 getInt() const
  207. {
  208. if (type == ConsoleValueType::cvInteger)
  209. return i;
  210. if (type == ConsoleValueType::cvFloat)
  211. return f;
  212. if (isStringType())
  213. return dAtoi(s);
  214. return dAtoi(getConsoleData());
  215. }
  216. TORQUE_FORCEINLINE const char* getString() const
  217. {
  218. if (isStringType())
  219. return s;
  220. if (isNumberType())
  221. return convertToBuffer();
  222. return getConsoleData();
  223. }
  224. TORQUE_FORCEINLINE operator const char* () const
  225. {
  226. return getString();
  227. }
  228. TORQUE_FORCEINLINE bool getBool() const
  229. {
  230. if (type == ConsoleValueType::cvInteger)
  231. return (bool)i;
  232. if (type == ConsoleValueType::cvFloat)
  233. return (bool)f;
  234. if (isStringType())
  235. return dAtob(s);
  236. return dAtob(getConsoleData());
  237. }
  238. TORQUE_FORCEINLINE void setFloat(const F64 val)
  239. {
  240. cleanupData();
  241. type = ConsoleValueType::cvFloat;
  242. f = val;
  243. }
  244. TORQUE_FORCEINLINE void setInt(const S64 val)
  245. {
  246. cleanupData();
  247. type = ConsoleValueType::cvInteger;
  248. i = val;
  249. }
  250. TORQUE_FORCEINLINE void setString(const char* val)
  251. {
  252. setString(val, val != NULL ? dStrlen(val) : 0);
  253. }
  254. TORQUE_FORCEINLINE void setString(const char* val, S32 len)
  255. {
  256. if (len == 0)
  257. {
  258. setEmptyString();
  259. return;
  260. }
  261. cleanupData();
  262. type = ConsoleValueType::cvString;
  263. s = (char*)dMalloc(static_cast<dsize_t>(len) + 1);
  264. s[len] = '\0';
  265. dStrcpy(s, val, static_cast<dsize_t>(len) + 1);
  266. }
  267. TORQUE_FORCEINLINE void setStringRef(const char* ref, S32 len)
  268. {
  269. cleanupData();
  270. type = ConsoleValueType::cvString;
  271. s = const_cast<char*>(ref);
  272. }
  273. TORQUE_FORCEINLINE void setBool(const bool val)
  274. {
  275. cleanupData();
  276. type = ConsoleValueType::cvInteger;
  277. i = (int)val;
  278. }
  279. TORQUE_FORCEINLINE void setStringTableEntry(StringTableEntry val)
  280. {
  281. cleanupData();
  282. type = ConsoleValueType::cvSTEntry;
  283. s = const_cast<char*>(val);
  284. }
  285. TORQUE_FORCEINLINE void setEmptyString()
  286. {
  287. setStringTableEntry(StringTable->EmptyString());
  288. }
  289. TORQUE_FORCEINLINE void setConsoleData(S32 consoleType, void* dataPtr, const EnumTable* enumTable)
  290. {
  291. cleanupData();
  292. type = ConsoleValueType::cvSTEntry;
  293. ct = new ConsoleValueConsoleType{ dataPtr, const_cast<EnumTable*>(enumTable) };
  294. }
  295. TORQUE_FORCEINLINE S32 getType() const
  296. {
  297. return type;
  298. }
  299. TORQUE_FORCEINLINE bool isStringType() const
  300. {
  301. return type == ConsoleValueType::cvString || type == ConsoleValueType::cvSTEntry;
  302. }
  303. TORQUE_FORCEINLINE bool isNumberType() const
  304. {
  305. return type == ConsoleValueType::cvFloat || type == ConsoleValueType::cvInteger;
  306. }
  307. TORQUE_FORCEINLINE bool isConsoleType() const
  308. {
  309. return type >= ConsoleValueType::cvConsoleValueType;
  310. }
  311. TORQUE_FORCEINLINE void setFastFloat(F64 flt)
  312. {
  313. type = ConsoleValueType::cvFloat;
  314. f = flt;
  315. }
  316. TORQUE_FORCEINLINE F64 getFastFloat() const
  317. {
  318. return f;
  319. }
  320. TORQUE_FORCEINLINE void setFastInt(S64 flt)
  321. {
  322. type = ConsoleValueType::cvInteger;
  323. i = flt;
  324. }
  325. TORQUE_FORCEINLINE S64 getFastInt() const
  326. {
  327. return i;
  328. }
  329. static void init();
  330. };
  331. // Transparently converts ConsoleValue[] to const char**
  332. class ConsoleValueToStringArrayWrapper
  333. {
  334. public:
  335. const char **argv;
  336. S32 argc;
  337. ConsoleValueToStringArrayWrapper(int targc, ConsoleValue* targv);
  338. ~ConsoleValueToStringArrayWrapper();
  339. const char* operator[](S32 idx) { return argv[idx]; }
  340. operator const char**() { return argv; }
  341. S32 count() { return argc; }
  342. };
  343. // Transparently converts const char** to ConsoleValue
  344. class StringArrayToConsoleValueWrapper
  345. {
  346. public:
  347. ConsoleValue *argv;
  348. S32 argc;
  349. StringArrayToConsoleValueWrapper(int targc, const char **targv);
  350. ~StringArrayToConsoleValueWrapper();
  351. ConsoleValue& operator[](int idx) { return argv[idx]; }
  352. operator ConsoleValue*() { return argv; }
  353. S32 count() { return argc; }
  354. };
  355. /// @defgroup console_callbacks Scripting Engine Callbacks
  356. ///
  357. /// The scripting engine makes heavy use of callbacks to represent
  358. /// function exposed to the scripting language. StringCallback,
  359. /// IntCallback, FloatCallback, VoidCallback, and BoolCallback all
  360. /// represent exposed script functions returning different types.
  361. ///
  362. /// ConsumerCallback is used with the function Con::addConsumer; functions
  363. /// registered with Con::addConsumer are called whenever something is outputted
  364. /// to the console. For instance, the TelnetConsole registers itself with the
  365. /// console so it can echo the console over the network.
  366. ///
  367. /// @note Callbacks to the scripting language - for instance, onExit(), which is
  368. /// a script function called when the engine is shutting down - are handled
  369. /// using Con::executef() and kin.
  370. /// @{
  371. ///
  372. typedef const char * (*StringCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  373. typedef S32(*IntCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  374. typedef F32(*FloatCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  375. typedef void(*VoidCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]); // We have it return a value so things don't break..
  376. typedef bool(*BoolCallback)(SimObject *obj, S32 argc, ConsoleValue argv[]);
  377. typedef void(*ConsumerCallback)(U32 level, const char *consoleLine);
  378. /// @}
  379. /// @defgroup console_types Scripting Engine Type Functions
  380. ///
  381. /// @see Con::registerType
  382. /// @{
  383. typedef const char* (*GetDataFunction)(void *dptr, EnumTable *tbl, BitSet32 flag);
  384. typedef void(*SetDataFunction)(void *dptr, S32 argc, const char **argv, EnumTable *tbl, BitSet32 flag);
  385. /// @}
  386. /// This namespace contains the core of the console functionality.
  387. ///
  388. /// @section con_intro Introduction
  389. ///
  390. /// The console is a key part of Torque's architecture. It allows direct run-time control
  391. /// of many aspects of the engine.
  392. ///
  393. /// @nosubgrouping
  394. namespace Con
  395. {
  396. /// Various configuration constants.
  397. enum Constants
  398. {
  399. /// This is the version number associated with DSO files.
  400. ///
  401. /// If you make any changes to the way the scripting language works
  402. /// (such as DSO format changes, adding/removing op-codes) that would
  403. /// break compatibility, then you should increment this.
  404. ///
  405. /// If you make a really major change, increment it to the next multiple
  406. /// of ten.
  407. ///
  408. /// 12/29/04 - BJG - 33->34 Removed some opcodes, part of namespace upgrade.
  409. /// 12/30/04 - BJG - 34->35 Reordered some things, further general shuffling.
  410. /// 11/03/05 - BJG - 35->36 Integrated new debugger code.
  411. /// 09/08/06 - THB - 36->37 New opcode for internal names
  412. /// 09/15/06 - THB - 37->38 Added unit conversions
  413. /// 11/23/06 - THB - 38->39 Added recursive internal name operator
  414. /// 02/15/07 - THB - 39->40 Bumping to 40 for TGB since the console has been
  415. /// majorly hacked without the version number being bumped
  416. /// 02/16/07 - THB - 40->41 newmsg operator
  417. /// 06/15/07 - THB - 41->42 script types
  418. /// 07/31/07 - THB - 42->43 Patch from Andreas Kirsch: Added opcode to support nested new declarations.
  419. /// 09/12/07 - CAF - 43->44 remove newmsg operator
  420. /// 09/27/07 - RDB - 44->45 Patch from Andreas Kirsch: Added opcode to support correct void return
  421. /// 01/13/09 - TMS - 45->46 Added script assert
  422. /// 09/07/14 - jamesu - 46->47 64bit support
  423. /// 10/14/14 - jamesu - 47->48 Added opcodes to reduce reliance on strings in function calls
  424. /// 10/07/17 - JTH - 48->49 Added opcode for function pointers and revamp of interpreter
  425. /// from switch to function calls.
  426. /// 09/04/21 - JTH - 49->50 Rewrite of interpreter
  427. DSOVersion = 50,
  428. MaxLineLength = 512, ///< Maximum length of a line of console input.
  429. MaxDataTypes = 256 ///< Maximum number of registered data types.
  430. };
  431. /// @name Control Functions
  432. ///
  433. /// The console must be initialized and shutdown appropriately during the
  434. /// lifetime of the app. These functions are used to manage this behavior.
  435. ///
  436. /// @note Torque deals with this aspect of console management, so you don't need
  437. /// to call these functions in normal usage of the engine.
  438. /// @{
  439. /// Initializes the console.
  440. ///
  441. /// This performs the following steps:
  442. /// - Calls Namespace::init() to initialize the scripting namespace hierarchy.
  443. /// - Calls ConsoleConstructor::setup() to initialize globally defined console
  444. /// methods and functions.
  445. /// - Registers some basic global script variables.
  446. /// - Calls AbstractClassRep::init() to initialize Torque's class database.
  447. /// - Registers some basic global script functions that couldn't usefully
  448. /// be defined anywhere else.
  449. void init();
  450. /// Shuts down the console.
  451. ///
  452. /// This performs the following steps:
  453. /// - Closes the console log file.
  454. /// - Calls Namespace::shutdown() to shut down the scripting namespace hierarchy.
  455. void shutdown();
  456. /// Is the console active at this time?
  457. bool isActive();
  458. /// @}
  459. /// @name Console Consumers
  460. ///
  461. /// The console distributes its output through Torque by using
  462. /// consumers. Every time a new line is printed to the console,
  463. /// all the ConsumerCallbacks registered using addConsumer are
  464. /// called, in order.
  465. ///
  466. /// @note The GuiConsole control, which provides the on-screen
  467. /// in-game console, uses a different technique to render
  468. /// the console. It calls getLockLog() to lock the Vector
  469. /// of on-screen console entries, then it renders them as
  470. /// needed. While the Vector is locked, the console will
  471. /// not change the Vector. When the GuiConsole control is
  472. /// done with the console entries, it calls unlockLog()
  473. /// to tell the console that it is again safe to modify
  474. /// the Vector.
  475. ///
  476. /// @see TelnetConsole
  477. /// @see TelnetDebugger
  478. /// @see WinConsole
  479. /// @see MacCarbConsole
  480. /// @see StdConsole
  481. /// @see ConsoleLogger
  482. ///
  483. /// @{
  484. ///
  485. void addConsumer(ConsumerCallback cb);
  486. void removeConsumer(ConsumerCallback cb);
  487. typedef JournaledSignal<void(RawData)> ConsoleInputEvent;
  488. /// Called from the native consoles to provide lines of console input
  489. /// to process. This will schedule it for execution ASAP.
  490. extern ConsoleInputEvent smConsoleInput;
  491. /// @}
  492. /// @name Miscellaneous
  493. /// @{
  494. /// Remove color marking information from a string.
  495. ///
  496. /// @note It does this in-place, so be careful! It may
  497. /// potentially blast data if you're not careful.
  498. /// When in doubt, make a copy of the string first.
  499. void stripColorChars(char* line);
  500. /// Convert from a relative script path to an absolute script path.
  501. ///
  502. /// This is used in (among other places) the exec() script function, which
  503. /// takes a parameter indicating a script file and executes it. Script paths
  504. /// can be one of:
  505. /// - <b>Absolute:</b> <i>fps/foo/bar.tscript</i> Paths of this sort are passed
  506. /// through.
  507. /// - <b>Mod-relative:</b> <i>~/foo/bar.tscript</i> Paths of this sort have their
  508. /// replaced with the name of the current mod.
  509. /// - <b>File-relative:</b> <i>./baz/blip.tscript</i> Paths of this sort are
  510. /// calculated relative to the path of the current scripting file.
  511. ///
  512. /// @note This function determines paths relative to the currently executing
  513. /// CodeBlock. Calling it outside of script execution will result in
  514. /// it directly copying src to filename, since it won't know to what the
  515. /// path is relative!
  516. ///
  517. /// @param filename Pointer to string buffer to fill with absolute path.
  518. /// @param size Size of buffer pointed to by filename.
  519. /// @param src Original, possibly relative script path.
  520. bool expandScriptFilename(char *filename, U32 size, const char *src);
  521. bool expandGameScriptFilename(char *filename, U32 size, const char *src);
  522. bool expandToolScriptFilename(char *filename, U32 size, const char *src);
  523. bool collapseScriptFilename(char *filename, U32 size, const char *src);
  524. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL, const bool ensureTrailingSlash = false);
  525. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL);
  526. bool isBasePath(const char* SrcPath, const char* pBasePath);
  527. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize);
  528. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize);
  529. StringTableEntry getDSOPath(const char *scriptPath);
  530. void addPathExpando(const char* pExpandoName, const char* pPath);
  531. void removePathExpando(const char* pExpandoName);
  532. bool isPathExpando(const char* pExpandoName);
  533. StringTableEntry getPathExpando(const char* pExpandoName);
  534. U32 getPathExpandoCount(void);
  535. StringTableEntry getPathExpandoKey(U32 expandoIndex);
  536. StringTableEntry getPathExpandoValue(U32 expandoIndex);
  537. bool isCurrentScriptToolScript();
  538. StringTableEntry getModNameFromPath(const char *path);
  539. /// Returns true if fn is a global scripting function.
  540. ///
  541. /// This looks in the global namespace. It also checks to see if fn
  542. /// is in the StringTable; if not, it returns false.
  543. bool isFunction(const char *fn);
  544. /// This is the basis for tab completion in the console.
  545. ///
  546. /// @note This is an internally used function. You probably don't
  547. /// care much about how this works.
  548. ///
  549. /// This function does some basic parsing to try to ascertain the namespace in which
  550. /// we are attempting to do tab completion, then bumps control off to the appropriate
  551. /// tabComplete function, either in SimObject or Namespace.
  552. ///
  553. /// @param inputBuffer Pointer to buffer containing starting data, or last result.
  554. /// @param cursorPos Location of cursor in this buffer. This is used to indicate
  555. /// what part of the string should be kept and what part should
  556. /// be advanced to the next match if any.
  557. /// @param maxResultLength Maximum amount of result data to put into inputBuffer. This
  558. /// is capped by MaxCompletionBufferSize.
  559. /// @param forwardTab Should we go forward to next match or backwards to previous
  560. /// match? True indicates forward.
  561. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab);
  562. /// @}
  563. /// @name Variable Management
  564. /// @{
  565. /// The delegate signature for the variable assignment notifications.
  566. ///
  567. /// @see addVariableNotify, removeVariableNotify
  568. typedef Delegate<void()> NotifyDelegate;
  569. /// Add a console variable that references the value of a variable in C++ code.
  570. ///
  571. /// If a value is assigned to the console variable the C++ variable is updated,
  572. /// and vice-versa.
  573. ///
  574. /// @param name Global console variable name to create.
  575. /// @param type The type of the C++ variable; see the ConsoleDynamicTypes enum for a complete list.
  576. /// @param pointer Pointer to the variable.
  577. /// @param usage Documentation string.
  578. ///
  579. /// @see ConsoleDynamicTypes
  580. void addVariable(const char *name,
  581. S32 type,
  582. void *pointer,
  583. const char* usage = NULL);
  584. /// Add a console constant that references the value of a constant in C++ code.
  585. ///
  586. /// @param name Global console constant name to create.
  587. /// @param type The type of the C++ constant; see the ConsoleDynamicTypes enum for a complete list.
  588. /// @param pointer Pointer to the constant.
  589. /// @param usage Documentation string.
  590. ///
  591. /// @see ConsoleDynamicTypes
  592. void addConstant(const char *name,
  593. S32 type,
  594. const void *pointer,
  595. const char* usage = NULL);
  596. /// Remove a console variable.
  597. ///
  598. /// @param name Global console variable name to remove
  599. /// @return true if variable existed before removal.
  600. bool removeVariable(const char *name);
  601. /// Add a callback for notification when a variable
  602. /// is assigned a new value.
  603. ///
  604. /// @param name An existing global console variable name.
  605. /// @param callback The notification delegate function.
  606. ///
  607. void addVariableNotify(const char *name, const NotifyDelegate &callback);
  608. /// Remove an existing variable assignment notification callback.
  609. ///
  610. /// @param name An existing global console variable name.
  611. /// @param callback The notification delegate function.
  612. ///
  613. void removeVariableNotify(const char *name, const NotifyDelegate &callback);
  614. /// Assign a string value to a locally scoped console variable
  615. ///
  616. /// @note The context of the variable is determined by gEvalState; that is,
  617. /// by the currently executing code.
  618. ///
  619. /// @param name Local console variable name to set
  620. /// @param value String value to assign to name
  621. void setLocalVariable(const char *name, const char *value);
  622. /// Retrieve the string value to a locally scoped console variable
  623. ///
  624. /// @note The context of the variable is determined by gEvalState; that is,
  625. /// by the currently executing code.
  626. ///
  627. /// @param name Local console variable name to get
  628. const char* getLocalVariable(const char* name);
  629. /// @}
  630. /// @name Global Variable Accessors
  631. /// @{
  632. /// Assign a string value to a global console variable
  633. /// @param name Global console variable name to set
  634. /// @param value String value to assign to this variable.
  635. void setVariable(const char *name, const char *value);
  636. /// Retrieve the string value of a global console variable
  637. /// @param name Global Console variable name to query
  638. /// @return The string value of the variable or "" if the variable does not exist.
  639. const char* getVariable(const char* name, const char* def = "");
  640. /// Retrieve the string value of an object field
  641. /// @param name "object.field" string to query
  642. /// @return The string value of the variable or NULL if no object is specified
  643. const char* getObjectField(const char* name);
  644. /// Same as setVariable(), but for bools.
  645. void setBoolVariable(const char* name, bool var);
  646. /// Same as getVariable(), but for bools.
  647. ///
  648. /// @param name Name of the variable.
  649. /// @param def Default value to supply if no matching variable is found.
  650. bool getBoolVariable(const char* name, bool def = false);
  651. /// Same as setVariable(), but for ints.
  652. void setIntVariable(const char* name, S32 var);
  653. /// Same as getVariable(), but for ints.
  654. ///
  655. /// @param name Name of the variable.
  656. /// @param def Default value to supply if no matching variable is found.
  657. S32 getIntVariable(const char* name, S32 def = 0);
  658. /// Same as setVariable(), but for floats.
  659. void setFloatVariable(const char* name, F32 var);
  660. /// Same as getVariable(), but for floats.
  661. ///
  662. /// @param name Name of the variable.
  663. /// @param def Default value to supply if no matching variable is found.
  664. F32 getFloatVariable(const char* name, F32 def = .0f);
  665. /// @}
  666. /// @name Global Function Registration
  667. /// @{
  668. /// Register a C++ function with the console making it a global function callable from the scripting engine.
  669. ///
  670. /// @param name Name of the new function.
  671. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  672. /// @param usage Documentation for this function. @ref console_autodoc
  673. /// @param minArgs Minimum number of arguments this function accepts
  674. /// @param maxArgs Maximum number of arguments this function accepts
  675. /// @param toolOnly Wether this is a TORQUE_TOOLS only function.
  676. /// @param header The extended function header.
  677. void addCommand(const char* name, StringCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  678. void addCommand(const char* name, IntCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  679. void addCommand(const char* name, FloatCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  680. void addCommand(const char* name, VoidCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  681. void addCommand(const char* name, BoolCallback cb, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  682. /// @}
  683. /// @name Namespace Function Registration
  684. /// @{
  685. /// Register a C++ function with the console making it callable
  686. /// as a method of the given namespace from the scripting engine.
  687. ///
  688. /// @param nameSpace Name of the namespace to associate the new function with; this is usually the name of a class.
  689. /// @param name Name of the new function.
  690. /// @param cb Pointer to the function implementing the scripting call; a console callback function returning a specific type value.
  691. /// @param usage Documentation for this function. @ref console_autodoc
  692. /// @param minArgs Minimum number of arguments this function accepts
  693. /// @param maxArgs Maximum number of arguments this function accepts
  694. /// @param toolOnly Wether this is a TORQUE_TOOLS only function.
  695. /// @param header The extended function header.
  696. void addCommand(const char *nameSpace, const char *name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  697. void addCommand(const char *nameSpace, const char *name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  698. void addCommand(const char *nameSpace, const char *name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  699. void addCommand(const char *nameSpace, const char *name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  700. void addCommand(const char *nameSpace, const char *name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL); ///< @copydoc addCommand( const char*, const char *, StringCallback, const char *, S32, S32, bool, ConsoleFunctionHeader* )
  701. /// @}
  702. /// @name Special Purpose Registration
  703. ///
  704. /// These are special-purpose functions that exist to allow commands to be grouped, so
  705. /// that when we generate console docs, they can be more meaningfully presented.
  706. ///
  707. /// @ref console_autodoc "Click here for more information about console docs and grouping."
  708. ///
  709. /// @{
  710. void markCommandGroup(const char * nsName, const char *name, const char* usage = NULL);
  711. void beginCommandGroup(const char * nsName, const char *name, const char* usage);
  712. void endCommandGroup(const char * nsName, const char *name);
  713. void noteScriptCallback(const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header = NULL);
  714. /// @}
  715. /// @name Console Output
  716. ///
  717. /// These functions process the formatted string and pass it to all the ConsumerCallbacks that are
  718. /// currently registered. The console log file and the console window callbacks are installed by default.
  719. ///
  720. /// @see addConsumer()
  721. /// @see removeConsumer()
  722. /// @{
  723. /// @param _format A stdlib printf style formatted out put string
  724. /// @param ... Variables to be written
  725. void printf(const char *_format, ...);
  726. /// @note The console window colors warning text as LIGHT GRAY.
  727. /// @param _format A stdlib printf style formatted out put string
  728. /// @param ... Variables to be written
  729. void warnf(const char *_format, ...);
  730. /// @note The console window colors warning text as RED.
  731. /// @param _format A stdlib printf style formatted out put string
  732. /// @param ... Variables to be written
  733. void errorf(const char *_format, ...);
  734. /// @note The console window colors warning text as LIGHT GRAY.
  735. /// @param type Allows you to associate the warning message with an internal module.
  736. /// @param _format A stdlib printf style formatted out put string
  737. /// @param ... Variables to be written
  738. /// @see Con::warnf()
  739. void warnf(ConsoleLogEntry::Type type, const char *_format, ...);
  740. /// @note The console window colors warning text as RED.
  741. /// @param type Allows you to associate the warning message with an internal module.
  742. /// @param _format A stdlib printf style formatted out put string
  743. /// @param ... Variables to be written
  744. /// @see Con::errorf()
  745. void errorf(ConsoleLogEntry::Type type, const char *_format, ...);
  746. //some additions from t2d
  747. /// Prints a separator to the console.
  748. inline void printSeparator(void) { printf("--------------------------------------------------------------------------------"); }
  749. /// Prints a separator to the console.
  750. inline void printBlankLine(void) { printf(""); }
  751. /// @}
  752. /// Returns true when called from the main thread, false otherwise
  753. bool isMainThread();
  754. /// @name Console Execution
  755. ///
  756. /// These are functions relating to the execution of script code.
  757. ///
  758. /// @{
  759. /// Call a script function from C/C++ code.
  760. ///
  761. /// @param argc Number of elements in the argv parameter
  762. /// @param argv A character string array containing the name of the function
  763. /// to call followed by the arguments to that function.
  764. /// @code
  765. /// // Call a Torque script function called mAbs, having one parameter.
  766. /// char* argv[] = {"abs", "-9"};
  767. /// char* result = execute(2, argv);
  768. /// @endcode
  769. /// NOTE: this function restores the console stack on return.
  770. ConsoleValue execute(S32 argc, const char* argv[]);
  771. ConsoleValue execute(S32 argc, ConsoleValue argv[]);
  772. /// Call a Torque Script member function of a SimObject from C/C++ code.
  773. /// @param object Object on which to execute the method call.
  774. /// @param argc Number of elements in the argv parameter (must be >2, see argv)
  775. /// @param argv A character string array containing the name of the member function
  776. /// to call followed by an empty parameter (gets filled with object ID)
  777. /// followed by arguments to that function.
  778. /// @code
  779. /// // Call the method setMode() on an object, passing it one parameter.
  780. ///
  781. /// char* argv[] = {"setMode", "", "2"};
  782. /// char* result = execute(mysimobject, 3, argv);
  783. /// @endcode
  784. /// NOTE: this function restores the console stack on return.
  785. ConsoleValue execute(SimObject *object, S32 argc, const char* argv[], bool thisCallOnly = false);
  786. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly = false);
  787. /// Executes a script file and compiles it for use in script.
  788. ///
  789. /// @param string File name that is the script to be executed and compiled.
  790. /// @param fileName Path to the file to execute
  791. /// @param noCalls Deprecated
  792. /// @param journalScript Deprecated
  793. ///
  794. /// @return True if the script was successfully executed, false if not.
  795. bool executeFile(const char* fileName, bool noCalls, bool journalScript);
  796. /// Evaluate an arbitrary chunk of code.
  797. ///
  798. /// @param string Buffer containing code to execute.
  799. /// @param echo Should we echo the string to the console?
  800. /// @param fileName Indicate what file this code is coming from; used in error reporting and such.
  801. /// NOTE: This function restores the console stack on return.
  802. ConsoleValue evaluate(const char* string, bool echo = false, const char *fileName = NULL);
  803. /// Evaluate an arbitrary line of script.
  804. ///
  805. /// This wraps dVsprintf(), so you can substitute parameters into the code being executed.
  806. /// NOTE: This function restores the console stack on return.
  807. ConsoleValue evaluatef(const char* string, ...);
  808. /// @}
  809. /// @name Console Function Implementation Helpers
  810. ///
  811. /// The functions Con::getIntArg, Con::getFloatArg and Con::getArgBuffer(size) are used to
  812. /// allocate on the console stack string variables that will be passed into the next console
  813. // function called. This allows the console to avoid copying some data.
  814. ///
  815. /// getReturnBuffer lets you allocate stack space to return data in.
  816. /// @{
  817. ///
  818. char* getReturnBuffer(U32 bufferSize);
  819. char* getReturnBuffer(const char *stringToCopy);
  820. char* getReturnBuffer(const String& str);
  821. char* getReturnBuffer(const StringBuilder& str);
  822. char* getArgBuffer(U32 bufferSize);
  823. char* getFloatArg(F64 arg);
  824. char* getIntArg(S32 arg);
  825. char* getBoolArg(bool arg);
  826. char* getStringArg(const char* arg);
  827. char* getStringArg(const String& arg);
  828. /// @}
  829. /// @name Namespaces
  830. /// @{
  831. Namespace *lookupNamespace(const char *nsName);
  832. bool linkNamespaces(const char *parentName, const char *childName);
  833. bool unlinkNamespaces(const char *parentName, const char *childName);
  834. /// @note This should only be called from consoleObject.h
  835. bool classLinkNamespaces(Namespace *parent, Namespace *child);
  836. const char *getNamespaceList(Namespace *ns);
  837. /// @}
  838. /// @name Logging
  839. /// @{
  840. void getLockLog(ConsoleLogEntry * &log, U32 &size);
  841. void unlockLog(void);
  842. void setLogMode(S32 mode);
  843. /// @}
  844. /// @name Instant Group
  845. /// @{
  846. void pushInstantGroup(String name = String());
  847. void popInstantGroup();
  848. /// @}
  849. /// @name Dynamic Type System
  850. /// @{
  851. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  852. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  853. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl = NULL, BitSet32 flag = 0);
  854. /// @}
  855. };
  856. struct _EngineConsoleCallbackHelper;
  857. template<typename P1> struct _EngineConsoleExecCallbackHelper;
  858. namespace Con
  859. {
  860. /// @name Console Execution - executef
  861. /// {
  862. ///
  863. /// Implements a script function thunk which automatically converts parameters to relevant console types.
  864. /// Can be used as follows:
  865. /// - Con::executef("functionName", ...);
  866. /// - Con::executef(mySimObject, "functionName", ...);
  867. ///
  868. /// NOTE: if you get a rather cryptic template error coming through here, most likely you are trying to
  869. /// convert a parameter which EngineMarshallType does not have a specialization for.
  870. /// Another problem can occur if you do not include "console/simBase.h" and "console/engineAPI.h"
  871. /// since _EngineConsoleExecCallbackHelper and SimConsoleThreadExecCallback are required.
  872. ///
  873. /// @see _EngineConsoleExecCallbackHelper
  874. ///
  875. template<typename R, typename ...ArgTs>
  876. ConsoleValue executef(R r, ArgTs ...argTs)
  877. {
  878. _EngineConsoleExecCallbackHelper<R> callback(r);
  879. return std::move(callback.template call<ConsoleValue>(argTs...));
  880. }
  881. /// }
  882. };
  883. extern void expandEscape(char *dest, const char *src);
  884. extern bool collapseEscape(char *buf);
  885. extern U32 HashPointer(StringTableEntry ptr);
  886. /// Extended information about a console function.
  887. struct ConsoleFunctionHeader
  888. {
  889. /// Return type string.
  890. const char* mReturnString;
  891. /// List of arguments taken by the function. Used for documentation.
  892. const char* mArgString;
  893. /// List of default argument values. Used for documentation.
  894. const char* mDefaultArgString;
  895. /// Whether this is a static method in a class.
  896. bool mIsStatic;
  897. ConsoleFunctionHeader(
  898. const char* returnString,
  899. const char* argString,
  900. const char* defaultArgString,
  901. bool isStatic = false)
  902. : mReturnString(returnString),
  903. mArgString(argString),
  904. mDefaultArgString(defaultArgString),
  905. mIsStatic(isStatic) {}
  906. };
  907. /// This is the backend for the ConsoleMethod()/ConsoleFunction() macros.
  908. ///
  909. /// See the group ConsoleConstructor Innards for specifics on how this works.
  910. ///
  911. /// @see @ref console_autodoc
  912. /// @nosubgrouping
  913. class ConsoleConstructor
  914. {
  915. public:
  916. /// @name Entry Type Fields
  917. ///
  918. /// One of these is set based on the type of entry we want
  919. /// inserted in the console.
  920. ///
  921. /// @ref console_autodoc
  922. /// @{
  923. StringCallback mSC; ///< A function/method that returns a string.
  924. IntCallback mIC; ///< A function/method that returns an int.
  925. FloatCallback mFC; ///< A function/method that returns a float.
  926. VoidCallback mVC; ///< A function/method that returns nothing.
  927. BoolCallback mBC; ///< A function/method that returns a bool.
  928. bool mGroup; ///< Indicates that this is a group marker.
  929. bool mNS; ///< Indicates that this is a namespace marker.
  930. /// @deprecated Unused.
  931. bool mCallback; ///< Is this a callback into script?
  932. /// @}
  933. /// Minimum number of arguments expected by the function.
  934. S32 mMina;
  935. /// Maximum number of arguments accepted by the funtion. Zero for varargs.
  936. S32 mMaxa;
  937. /// Name of the function/method.
  938. const char* mFuncName;
  939. /// Name of the class namespace to which to add the method.
  940. const char* mClassName;
  941. /// Usage string for documentation.
  942. const char* mUsage;
  943. /// Whether this is a TORQUE_TOOLS only function.
  944. bool mToolOnly;
  945. /// The extended function header.
  946. ConsoleFunctionHeader* mHeader;
  947. /// @name ConsoleConstructor Innards
  948. ///
  949. /// The ConsoleConstructor class is used as the backend for the ConsoleFunction() and
  950. /// ConsoleMethod() macros. The way it works takes advantage of several properties of
  951. /// C++.
  952. ///
  953. /// The ConsoleFunction()/ConsoleMethod() macros wrap the declaration of a ConsoleConstructor.
  954. ///
  955. /// @code
  956. /// // The definition of a ConsoleFunction using the macro
  957. /// ConsoleFunction(ExpandFilename, const char*, 2, 2, "(string filename)")
  958. /// {
  959. /// argc;
  960. /// char* ret = Con::getReturnBuffer( 1024 );
  961. /// Con::expandScriptFilename(ret, 1024, argv[1]);
  962. /// return ret;
  963. /// }
  964. ///
  965. /// // Resulting code
  966. /// static const char* cExpandFilename(SimObject *, S32, const char **argv);
  967. /// static ConsoleConstructor
  968. /// gExpandFilenameobj(NULL,"ExpandFilename", cExpandFilename,
  969. /// "(string filename)", 2, 2);
  970. /// static const char* cExpandFilename(SimObject *, S32 argc, const char **argv)
  971. /// {
  972. /// argc;
  973. /// char* ret = Con::getReturnBuffer( 1024 );
  974. /// Con::expandScriptFilename(ret, 1024, argv[1]);
  975. /// return ret;
  976. /// }
  977. ///
  978. /// // A similar thing happens when you do a ConsoleMethod.
  979. /// @endcode
  980. ///
  981. /// As you can see, several global items are defined when you use the ConsoleFunction method.
  982. /// The macro constructs the name of these items from the parameters you passed it. Your
  983. /// implementation of the console function is is placed in a function with a name based on
  984. /// the actual name of the console funnction. In addition, a ConsoleConstructor is declared.
  985. ///
  986. /// Because it is defined as a global, the constructor for the ConsoleConstructor is called
  987. /// before execution of main() is started. The constructor is called once for each global
  988. /// ConsoleConstructor variable, in the order in which they were defined (this property only holds true
  989. /// within file scope).
  990. ///
  991. /// We have ConsoleConstructor create a linked list at constructor time, by storing a static
  992. /// pointer to the head of the list, and keeping a pointer to the next item in each instance
  993. /// of ConsoleConstructor. init() is a helper function in this process, automatically filling
  994. /// in commonly used fields and updating first and next as needed. In this way, a list of
  995. /// items to add to the console is assemble in memory, ready for use, before we start
  996. /// execution of the program proper.
  997. ///
  998. /// In Con::init(), ConsoleConstructor::setup() is called to process this prepared list. Each
  999. /// item in the list is iterated over, and the appropriate Con namespace functions (usually
  1000. /// Con::addCommand) are invoked to register the ConsoleFunctions and ConsoleMethods in
  1001. /// the appropriate namespaces.
  1002. ///
  1003. /// @see Namespace
  1004. /// @see Con
  1005. /// @{
  1006. ///
  1007. ConsoleConstructor *mNext;
  1008. static ConsoleConstructor *mFirst;
  1009. void init(const char* cName, const char* fName, const char *usg, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1010. static void setup();
  1011. /// Validate there are no duplicate entries for this item.
  1012. void validate();
  1013. /// @}
  1014. /// @name Basic Console Constructors
  1015. /// @{
  1016. ConsoleConstructor(const char* className, const char* funcName, StringCallback sfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1017. ConsoleConstructor(const char* className, const char* funcName, IntCallback ifunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1018. ConsoleConstructor(const char* className, const char* funcName, FloatCallback ffunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1019. ConsoleConstructor(const char* className, const char* funcName, VoidCallback vfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1020. ConsoleConstructor(const char* className, const char* funcName, BoolCallback bfunc, const char* usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  1021. /// @}
  1022. /// @name Magic Console Constructors
  1023. ///
  1024. /// These perform various pieces of "magic" related to consoleDoc functionality.
  1025. /// @ref console_autodoc
  1026. /// @{
  1027. /// Indicates a group marker. (A doxygen illusion)
  1028. ///
  1029. /// @see Con::markCommandGroup
  1030. /// @ref console_autodoc
  1031. ConsoleConstructor(const char *className, const char *groupName, const char* usage);
  1032. /// Indicates a callback declared with the DECLARE_SCRIPT_CALLBACK macro and friends.
  1033. ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header);
  1034. /// @}
  1035. };
  1036. /// An arbitrary fragment of auto-doc text for the script reference.
  1037. struct ConsoleDocFragment
  1038. {
  1039. /// The class in which to put the fragment. If NULL, the fragment
  1040. /// will be placed globally.
  1041. const char* mClass;
  1042. /// The definition to output for this fragment. NULL for fragments
  1043. /// not associated with a definition.
  1044. const char* mDefinition;
  1045. /// The documentation text.
  1046. const char* mText;
  1047. /// Next fragment in the global link chain.
  1048. ConsoleDocFragment* mNext;
  1049. /// First fragment in the global link chain.
  1050. static ConsoleDocFragment* smFirst;
  1051. ConsoleDocFragment(const char* text, const char* inClass = NULL, const char* definition = NULL)
  1052. : mClass(inClass),
  1053. mDefinition(definition),
  1054. mText(text),
  1055. mNext(smFirst)
  1056. {
  1057. smFirst = this;
  1058. }
  1059. };
  1060. /// Utility class to save and restore the current console stack frame
  1061. ///
  1062. class ConsoleStackFrameSaver
  1063. {
  1064. public:
  1065. bool mSaved;
  1066. ConsoleStackFrameSaver() : mSaved(false)
  1067. {
  1068. }
  1069. ~ConsoleStackFrameSaver()
  1070. {
  1071. restore();
  1072. }
  1073. void save();
  1074. void restore();
  1075. };
  1076. /// @name Global Console Definition Macros
  1077. ///
  1078. /// @note If TORQUE_DEBUG is defined, then we gather documentation information, and
  1079. /// do some extra sanity checks.
  1080. ///
  1081. /// @see ConsoleConstructor
  1082. /// @ref console_autodoc
  1083. /// @{
  1084. /// Define a C++ method that calls back to script on an object.
  1085. ///
  1086. /// @see consoleCallback.h
  1087. #define DECLARE_CALLBACK( returnType, name, args ) \
  1088. virtual returnType name ## _callback args
  1089. // O hackery of hackeries
  1090. #define conmethod_return_const return (const
  1091. #define conmethod_return_S32 return (S32
  1092. #define conmethod_return_F32 return (F32
  1093. #define conmethod_nullify(val)
  1094. #define conmethod_return_void conmethod_nullify(void
  1095. #define conmethod_return_bool return (bool
  1096. #if !defined(TORQUE_SHIPPING)
  1097. // Console function macros
  1098. # define ConsoleFunctionGroupBegin(groupName, usage) \
  1099. static ConsoleConstructor cfg_ConsoleFunctionGroup_##groupName##_GroupBegin(NULL,#groupName,usage)
  1100. # define ConsoleToolFunction(name,returnType,minArgs,maxArgs,usage1) \
  1101. returnType ctf_##name(SimObject *, S32, ConsoleValue *argv); \
  1102. ConsoleConstructor cc_##name##_obj(NULL,#name,ctf_##name,usage1,minArgs,maxArgs, true); \
  1103. returnType ctf_##name(SimObject *, S32 argc, ConsoleValue *argv)
  1104. # define ConsoleFunctionGroupEnd(groupName) \
  1105. static ConsoleConstructor cfg_##groupName##_GroupEnd(NULL,#groupName,NULL)
  1106. // Console method macros
  1107. # define ConsoleNamespace(className, usage) \
  1108. ConsoleConstructor cc_##className##_Namespace(#className, usage)
  1109. # define ConsoleMethodGroupBegin(className, groupName, usage) \
  1110. static ConsoleConstructor cc_##className##_##groupName##_GroupBegin(#className,#groupName,usage)
  1111. # define ConsoleMethodGroupEnd(className, groupName) \
  1112. static ConsoleConstructor cc_##className##_##groupName##_GroupEnd(#className,#groupName,NULL)
  1113. /// Add a fragment of auto-doc text to the console API reference.
  1114. /// @note There can only be one ConsoleDoc per source file.
  1115. # define ConsoleDoc( text ) \
  1116. namespace { \
  1117. ConsoleDocFragment _sDocFragment( text ); \
  1118. }
  1119. #else
  1120. // These do nothing if we don't want doc information.
  1121. # define ConsoleFunctionGroupBegin(groupName, usage)
  1122. # define ConsoleFunctionGroupEnd(groupName)
  1123. # define ConsoleNamespace(className, usage)
  1124. # define ConsoleMethodGroupBegin(className, groupName, usage)
  1125. # define ConsoleMethodGroupEnd(className, groupName)
  1126. // These are identical to what's above, we just want to null out the usage strings.
  1127. # define ConsoleFunction(name,returnType,minArgs,maxArgs,usage1) \
  1128. static returnType c##name(SimObject *, S32, ConsoleValue*); \
  1129. static ConsoleConstructor g##name##obj(NULL,#name,c##name,"",minArgs,maxArgs);\
  1130. static returnType c##name(SimObject *, S32 argc, ConsoleValue *argv)
  1131. # define ConsoleToolFunction(name,returnType,minArgs,maxArgs,usage1) \
  1132. static returnType c##name(SimObject *, S32, ConsoleValue*); \
  1133. static ConsoleConstructor g##name##obj(NULL,#name,c##name,"",minArgs,maxArgs, true);\
  1134. static returnType c##name(SimObject *, S32 argc, ConsoleValue *argv)
  1135. # define ConsoleMethod(className,name,returnType,minArgs,maxArgs,usage1) \
  1136. static inline returnType c##className##name(className *, S32, ConsoleValue *argv); \
  1137. static returnType c##className##name##caster(SimObject *object, S32 argc, ConsoleValue *argv) { \
  1138. conmethod_return_##returnType ) c##className##name(static_cast<className*>(object),argc,argv); \
  1139. }; \
  1140. static ConsoleConstructor \
  1141. className##name##obj(#className,#name,c##className##name##caster,"",minArgs,maxArgs); \
  1142. static inline returnType c##className##name(className *object, S32 argc, ConsoleValue *argv)
  1143. #define ConsoleDoc( text )
  1144. #endif
  1145. /// @}
  1146. /// @}
  1147. #endif // _CONSOLE_H_