console.h 53 KB

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