console.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  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. #include "platform/platform.h"
  23. #include "platform/platformTLS.h"
  24. #include "platform/threads/thread.h"
  25. #include "console/console.h"
  26. #include "console/consoleInternal.h"
  27. #include "console/consoleObject.h"
  28. #include "console/consoleParser.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/ast.h"
  31. #include "core/tAlgorithm.h"
  32. #include "console/consoleTypes.h"
  33. #include "console/telnetDebugger.h"
  34. #include "console/simBase.h"
  35. #include "console/compiler.h"
  36. #include "console/stringStack.h"
  37. #include "console/ICallMethod.h"
  38. #include "console/engineAPI.h"
  39. #include <stdarg.h>
  40. #include "platform/threads/mutex.h"
  41. #include "core/util/journal/journal.h"
  42. #include "cinterface/cinterface.h"
  43. #include "console/consoleValueStack.h"
  44. extern StringStack STR;
  45. extern ConsoleValueStack<4096> gCallStack;
  46. char ConsoleValue::sConversionBuffer[ConversionBufferSize];
  47. void ConsoleValue::init()
  48. {
  49. dMemset(sConversionBuffer, '\0', ConversionBufferSize);
  50. }
  51. char* ConsoleValue::convertToBuffer() const
  52. {
  53. if (type == ConsoleValueType::cvFloat)
  54. dSprintf(sConversionBuffer, ConversionBufferSize, "%.9g", f);
  55. else
  56. dSprintf(sConversionBuffer, ConversionBufferSize, "%lld", i);
  57. return sConversionBuffer;
  58. }
  59. const char* ConsoleValue::getConsoleData() const
  60. {
  61. return Con::getData(type, ct->dataPtr, 0, ct->enumTable);
  62. }
  63. ConsoleDocFragment* ConsoleDocFragment::smFirst;
  64. ExprEvalState gEvalState;
  65. StmtNode *gStatementList;
  66. StmtNode *gAnonFunctionList;
  67. U32 gAnonFunctionID = 0;
  68. ConsoleConstructor *ConsoleConstructor::mFirst = NULL;
  69. bool gWarnUndefinedScriptVariables;
  70. static char scratchBuffer[4096];
  71. CON_DECLARE_PARSER(CMD);
  72. static const char * prependDollar ( const char * name )
  73. {
  74. if(name[0] != '$')
  75. {
  76. S32 len = dStrlen(name);
  77. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  78. scratchBuffer[0] = '$';
  79. dMemcpy(scratchBuffer + 1, name, len + 1);
  80. name = scratchBuffer;
  81. }
  82. return name;
  83. }
  84. static const char * prependPercent ( const char * name )
  85. {
  86. if(name[0] != '%')
  87. {
  88. S32 len = dStrlen(name);
  89. AssertFatal(len < sizeof(scratchBuffer)-2, "CONSOLE: name too long");
  90. scratchBuffer[0] = '%';
  91. dMemcpy(scratchBuffer + 1, name, len + 1);
  92. name = scratchBuffer;
  93. }
  94. return name;
  95. }
  96. //--------------------------------------
  97. void ConsoleConstructor::init( const char *cName, const char *fName, const char *usg, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  98. {
  99. mMina = minArgs;
  100. mMaxa = maxArgs;
  101. mFuncName = fName;
  102. mUsage = usg;
  103. mClassName = cName;
  104. mSC = 0; mFC = 0; mVC = 0; mBC = 0; mIC = 0;
  105. mCallback = mGroup = false;
  106. mNext = mFirst;
  107. mNS = false;
  108. mFirst = this;
  109. mToolOnly = isToolOnly;
  110. mHeader = header;
  111. }
  112. void ConsoleConstructor::setup()
  113. {
  114. for(ConsoleConstructor *walk = mFirst; walk; walk = walk->mNext)
  115. {
  116. #ifdef TORQUE_DEBUG
  117. walk->validate();
  118. #endif
  119. if( walk->mSC )
  120. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mSC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  121. else if( walk->mIC )
  122. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mIC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  123. else if( walk->mFC )
  124. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mFC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  125. else if( walk->mVC )
  126. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mVC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  127. else if( walk->mBC )
  128. Con::addCommand( walk->mClassName, walk->mFuncName, walk->mBC, walk->mUsage, walk->mMina, walk->mMaxa, walk->mToolOnly, walk->mHeader);
  129. else if( walk->mGroup )
  130. Con::markCommandGroup( walk->mClassName, walk->mFuncName, walk->mUsage);
  131. else if( walk->mClassName)
  132. Con::noteScriptCallback( walk->mClassName, walk->mFuncName, walk->mUsage, walk->mHeader);
  133. else if( walk->mNS )
  134. {
  135. Namespace* ns = Namespace::find( StringTable->insert( walk->mClassName) );
  136. if( ns )
  137. ns->mUsage = walk->mUsage;
  138. }
  139. else
  140. {
  141. AssertISV( false, "Found a ConsoleConstructor with an indeterminate type!" );
  142. }
  143. }
  144. }
  145. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, StringCallback sfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  146. {
  147. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  148. mSC = sfunc;
  149. }
  150. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, IntCallback ifunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  151. {
  152. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  153. mIC = ifunc;
  154. }
  155. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, FloatCallback ffunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  156. {
  157. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  158. mFC = ffunc;
  159. }
  160. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, VoidCallback vfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  161. {
  162. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  163. mVC = vfunc;
  164. }
  165. ConsoleConstructor::ConsoleConstructor(const char *className, const char *funcName, BoolCallback bfunc, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  166. {
  167. init( className, funcName, usage, minArgs, maxArgs, isToolOnly, header );
  168. mBC = bfunc;
  169. }
  170. ConsoleConstructor::ConsoleConstructor(const char* className, const char* groupName, const char* aUsage)
  171. {
  172. init(className, groupName, mUsage, -1, -2);
  173. mGroup = true;
  174. // Somewhere, the entry list is getting flipped, partially.
  175. // so we have to do tricks to deal with making sure usage
  176. // is properly populated.
  177. // This is probably redundant.
  178. static char * lastUsage = NULL;
  179. if(aUsage)
  180. lastUsage = (char *)aUsage;
  181. mUsage = lastUsage;
  182. }
  183. ConsoleConstructor::ConsoleConstructor(const char *className, const char *callbackName, const char *usage, ConsoleFunctionHeader* header )
  184. {
  185. init( className, callbackName, usage, -2, -3, false, header );
  186. mCallback = true;
  187. mNS = true;
  188. }
  189. void ConsoleConstructor::validate()
  190. {
  191. #ifdef TORQUE_DEBUG
  192. // Don't do the following check if we're not a method/func.
  193. if(mGroup)
  194. return;
  195. // In debug, walk the list and make sure this isn't a duplicate.
  196. for(ConsoleConstructor *walk = mFirst; walk; walk = walk->mNext)
  197. {
  198. // Skip mismatching func/method names.
  199. if(dStricmp(walk->mFuncName, mFuncName))
  200. continue;
  201. // Don't compare functions with methods or vice versa.
  202. if(bool(mClassName) != bool(walk->mClassName))
  203. continue;
  204. // Skip mismatching classnames, if they're present.
  205. if(mClassName && walk->mClassName && dStricmp(walk->mClassName, mClassName))
  206. continue;
  207. // If we encounter ourselves, stop searching; this prevents duplicate
  208. // firing of the assert, instead only firing for the latter encountered
  209. // entry.
  210. if(this == walk)
  211. break;
  212. // Match!
  213. if(mClassName)
  214. {
  215. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleMethod '%s::%s' collides with another of the same name.", mClassName, mFuncName));
  216. }
  217. else
  218. {
  219. AssertISV(false, avar("ConsoleConstructor::setup - ConsoleFunction '%s' collides with another of the same name.", mFuncName));
  220. }
  221. }
  222. #endif
  223. }
  224. // We comment out the implementation of the Con namespace when doxygenizing because
  225. // otherwise Doxygen decides to ignore our docs in console.h
  226. #ifndef DOXYGENIZING
  227. namespace Con
  228. {
  229. static Vector<ConsumerCallback> gConsumers(__FILE__, __LINE__);
  230. static Vector< String > sInstantGroupStack( __FILE__, __LINE__ );
  231. static DataChunker consoleLogChunker;
  232. static Vector<ConsoleLogEntry> consoleLog(__FILE__, __LINE__);
  233. static bool consoleLogLocked;
  234. static bool logBufferEnabled=true;
  235. static S32 printLevel = 10;
  236. static FileStream consoleLogFile;
  237. static const char *defLogFileName = "console.log";
  238. static S32 consoleLogMode = 0;
  239. static bool active = false;
  240. static bool newLogFile;
  241. static const char *logFileName;
  242. static const S32 MaxCompletionBufferSize = 4096;
  243. static char completionBuffer[MaxCompletionBufferSize];
  244. static char tabBuffer[MaxCompletionBufferSize] = {0};
  245. static SimObjectPtr<SimObject> tabObject;
  246. static U32 completionBaseStart;
  247. static U32 completionBaseLen;
  248. String gInstantGroup;
  249. Con::ConsoleInputEvent smConsoleInput;
  250. /// Current script file name and root, these are registered as
  251. /// console variables.
  252. /// @{
  253. ///
  254. StringTableEntry gCurrentFile;
  255. StringTableEntry gCurrentRoot;
  256. /// @}
  257. bool alwaysUseDebugOutput = true;
  258. bool useTimestamp = false;
  259. bool useRealTimestamp = false;
  260. ConsoleFunctionGroupBegin( Clipboard, "Miscellaneous functions to control the clipboard and clear the console.");
  261. DefineEngineFunction( cls, void, (), , "()"
  262. "@brief Clears the console output.\n\n"
  263. "@ingroup Console")
  264. {
  265. if(consoleLogLocked)
  266. return;
  267. consoleLogChunker.freeBlocks();
  268. consoleLog.setSize(0);
  269. };
  270. DefineEngineFunction( getClipboard, const char*, (), , "()"
  271. "@brief Get text from the clipboard.\n\n"
  272. "@internal")
  273. {
  274. return Platform::getClipboard();
  275. };
  276. DefineEngineFunction( setClipboard, bool, (const char* text), , "(string text)"
  277. "@brief Set the system clipboard.\n\n"
  278. "@internal")
  279. {
  280. return Platform::setClipboard(text);
  281. };
  282. ConsoleFunctionGroupEnd( Clipboard );
  283. void postConsoleInput( RawData data );
  284. void init()
  285. {
  286. AssertFatal(active == false, "Con::init should only be called once.");
  287. // Set up general init values.
  288. active = true;
  289. logFileName = NULL;
  290. newLogFile = true;
  291. gWarnUndefinedScriptVariables = false;
  292. // Initialize subsystems.
  293. Namespace::init();
  294. ConsoleConstructor::setup();
  295. // Set up the parser(s)
  296. CON_ADD_PARSER(CMD, TORQUE_SCRIPT_EXTENSION, true); // TorqueScript
  297. // Setup the console types.
  298. ConsoleBaseType::initialize();
  299. ConsoleValue::init();
  300. // And finally, the ACR...
  301. AbstractClassRep::initialize();
  302. // Variables
  303. setVariable("Con::prompt", "% ");
  304. addVariable("Con::logBufferEnabled", TypeBool, &logBufferEnabled, "If true, the log buffer will be enabled.\n"
  305. "@ingroup Console\n");
  306. addVariable("Con::printLevel", TypeS32, &printLevel,
  307. "@brief This is deprecated.\n\n"
  308. "It is no longer in use and does nothing.\n"
  309. "@ingroup Console\n");
  310. addVariable("Con::warnUndefinedVariables", TypeBool, &gWarnUndefinedScriptVariables, "If true, a warning will be displayed in the console whenever a undefined variable is used in script.\n"
  311. "@ingroup Console\n");
  312. addVariable( "instantGroup", TypeRealString, &gInstantGroup, "The group that objects will be added to when they are created.\n"
  313. "@ingroup Console\n");
  314. // Current script file name and root
  315. addVariable( "Con::File", TypeString, &gCurrentFile, "The currently executing script file.\n"
  316. "@ingroup FileSystem\n");
  317. addVariable( "Con::Root", TypeString, &gCurrentRoot, "The mod folder for the currently executing script file.\n"
  318. "@ingroup FileSystem\n" );
  319. // alwaysUseDebugOutput determines whether to send output to the platform's
  320. // "debug" system. see winConsole for an example.
  321. // in ship builds we don't expose this variable to script
  322. // and we set it to false by default (don't want to provide more information
  323. // to potential hackers). platform code should also ifdef out the code that
  324. // pays attention to this in ship builds (see winConsole.cpp)
  325. // note that enabling this can slow down your game
  326. // if you are running from the debugger and printing a lot of console messages.
  327. #ifndef TORQUE_SHIPPING
  328. addVariable("Con::alwaysUseDebugOutput", TypeBool, &alwaysUseDebugOutput,
  329. "@brief Determines whether to send output to the platform's \"debug\" system.\n\n"
  330. "@note This is disabled in shipping builds.\n"
  331. "@ingroup Console");
  332. #else
  333. alwaysUseDebugOutput = false;
  334. #endif
  335. // controls whether a timestamp is prepended to every console message
  336. addVariable("Con::useTimestamp", TypeBool, &useTimestamp, "If true a timestamp is prepended to every console message.\n"
  337. "@ingroup Console\n");
  338. // controls whether a real date and time is prepended to every console message
  339. addVariable("Con::useRealTimestamp", TypeBool, &useRealTimestamp, "If true a date and time will be prepended to every console message.\n"
  340. "@ingroup Console\n");
  341. // Plug us into the journaled console input signal.
  342. smConsoleInput.notify(postConsoleInput);
  343. }
  344. //--------------------------------------
  345. void shutdown()
  346. {
  347. AssertFatal(active == true, "Con::shutdown should only be called once.");
  348. active = false;
  349. smConsoleInput.remove(postConsoleInput);
  350. consoleLogFile.close();
  351. Namespace::shutdown();
  352. AbstractClassRep::shutdown();
  353. Compiler::freeConsoleParserList();
  354. }
  355. bool isActive()
  356. {
  357. return active;
  358. }
  359. bool isMainThread()
  360. {
  361. #ifdef TORQUE_MULTITHREAD
  362. return ThreadManager::isMainThread();
  363. #else
  364. // If we're single threaded we're always in the main thread.
  365. return true;
  366. #endif
  367. }
  368. //--------------------------------------
  369. void getLockLog(ConsoleLogEntry *&log, U32 &size)
  370. {
  371. consoleLogLocked = true;
  372. log = consoleLog.address();
  373. size = consoleLog.size();
  374. }
  375. void unlockLog()
  376. {
  377. consoleLogLocked = false;
  378. }
  379. U32 tabComplete(char* inputBuffer, U32 cursorPos, U32 maxResultLength, bool forwardTab)
  380. {
  381. // Check for null input.
  382. if (!inputBuffer[0])
  383. {
  384. return cursorPos;
  385. }
  386. // Cap the max result length.
  387. if (maxResultLength > MaxCompletionBufferSize)
  388. {
  389. maxResultLength = MaxCompletionBufferSize;
  390. }
  391. // See if this is the same partial text as last checked.
  392. if (String::compare(tabBuffer, inputBuffer))
  393. {
  394. // If not...
  395. // Save it for checking next time.
  396. dStrcpy(tabBuffer, inputBuffer, MaxCompletionBufferSize);
  397. // Scan backward from the cursor position to find the base to complete from.
  398. S32 p = cursorPos;
  399. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '.') && (inputBuffer[p - 1] != '('))
  400. {
  401. p--;
  402. }
  403. completionBaseStart = p;
  404. completionBaseLen = cursorPos - p;
  405. // Is this function being invoked on an object?
  406. if (inputBuffer[p - 1] == '.')
  407. {
  408. // If so...
  409. if (p <= 1)
  410. {
  411. // Bail if no object identifier.
  412. return cursorPos;
  413. }
  414. // Find the object identifier.
  415. S32 objLast = --p;
  416. while ((p > 0) && (inputBuffer[p - 1] != ' ') && (inputBuffer[p - 1] != '('))
  417. {
  418. p--;
  419. }
  420. if (objLast == p)
  421. {
  422. // Bail if no object identifier.
  423. return cursorPos;
  424. }
  425. // Look up the object identifier.
  426. dStrncpy(completionBuffer, inputBuffer + p, objLast - p);
  427. completionBuffer[objLast - p] = 0;
  428. tabObject = Sim::findObject(completionBuffer);
  429. if (tabObject == NULL)
  430. {
  431. // Bail if not found.
  432. return cursorPos;
  433. }
  434. }
  435. else
  436. {
  437. // Not invoked on an object; we'll use the global namespace.
  438. tabObject = 0;
  439. }
  440. }
  441. // Chop off the input text at the cursor position.
  442. inputBuffer[cursorPos] = 0;
  443. // Try to find a completion in the appropriate namespace.
  444. const char *newText;
  445. if (tabObject != 0)
  446. {
  447. newText = tabObject->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  448. }
  449. else
  450. {
  451. // In the global namespace, we can complete on global vars as well as functions.
  452. if (inputBuffer[completionBaseStart] == '$')
  453. {
  454. newText = gEvalState.globalVars.tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  455. }
  456. else
  457. {
  458. newText = Namespace::global()->tabComplete(inputBuffer + completionBaseStart, completionBaseLen, forwardTab);
  459. }
  460. }
  461. if (newText)
  462. {
  463. // If we got something, append it to the input text.
  464. S32 len = dStrlen(newText);
  465. if (len + completionBaseStart > maxResultLength)
  466. {
  467. len = maxResultLength - completionBaseStart;
  468. }
  469. dStrncpy(inputBuffer + completionBaseStart, newText, len);
  470. inputBuffer[completionBaseStart + len] = 0;
  471. // And set the cursor after it.
  472. cursorPos = completionBaseStart + len;
  473. }
  474. // Save the modified input buffer for checking next time.
  475. dStrcpy(tabBuffer, inputBuffer, MaxCompletionBufferSize);
  476. // Return the new (maybe) cursor position.
  477. return cursorPos;
  478. }
  479. //------------------------------------------------------------------------------
  480. static void log(const char *string)
  481. {
  482. // Bail if we ain't logging.
  483. if (!consoleLogMode)
  484. {
  485. return;
  486. }
  487. // In mode 1, we open, append, close on each log write.
  488. if ((consoleLogMode & 0x3) == 1)
  489. {
  490. consoleLogFile.open(defLogFileName, Torque::FS::File::ReadWrite);
  491. }
  492. // Write to the log if its status is hunky-dory.
  493. if ((consoleLogFile.getStatus() == Stream::Ok) || (consoleLogFile.getStatus() == Stream::EOS))
  494. {
  495. consoleLogFile.setPosition(consoleLogFile.getStreamSize());
  496. // If this is the first write...
  497. if (newLogFile)
  498. {
  499. // Make a header.
  500. Platform::LocalTime lt;
  501. Platform::getLocalTime(lt);
  502. char buffer[128];
  503. dSprintf(buffer, sizeof(buffer), "//-------------------------- %d/%d/%d -- %02d:%02d:%02d -----\r\n",
  504. lt.month + 1,
  505. lt.monthday,
  506. lt.year + 1900,
  507. lt.hour,
  508. lt.min,
  509. lt.sec);
  510. consoleLogFile.write(dStrlen(buffer), buffer);
  511. newLogFile = false;
  512. if (consoleLogMode & 0x4)
  513. {
  514. // Dump anything that has been printed to the console so far.
  515. consoleLogMode -= 0x4;
  516. U32 size, line;
  517. ConsoleLogEntry *log;
  518. getLockLog(log, size);
  519. for (line = 0; line < size; line++)
  520. {
  521. consoleLogFile.write(dStrlen(log[line].mString), log[line].mString);
  522. consoleLogFile.write(2, "\r\n");
  523. }
  524. unlockLog();
  525. }
  526. }
  527. // Now write what we came here to write.
  528. consoleLogFile.write(dStrlen(string), string);
  529. consoleLogFile.write(2, "\r\n");
  530. }
  531. if ((consoleLogMode & 0x3) == 1)
  532. {
  533. consoleLogFile.close();
  534. }
  535. }
  536. //------------------------------------------------------------------------------
  537. static void _printf(ConsoleLogEntry::Level level, ConsoleLogEntry::Type type, const char* fmt, va_list argptr)
  538. {
  539. if (!active)
  540. return;
  541. Con::active = false;
  542. char buffer[8192];
  543. U32 offset = 0;
  544. if( gEvalState.traceOn && gEvalState.getStackDepth() > 0 )
  545. {
  546. offset = gEvalState.getStackDepth() * 3;
  547. for(U32 i = 0; i < offset; i++)
  548. buffer[i] = ' ';
  549. }
  550. if (useRealTimestamp)
  551. {
  552. Platform::LocalTime lt;
  553. Platform::getLocalTime(lt);
  554. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[%d-%d-%d %02d:%02d:%02d]", lt.year + 1900, lt.month + 1, lt.monthday, lt.hour, lt.min, lt.sec);
  555. }
  556. if (useTimestamp)
  557. {
  558. static U32 startTime = Platform::getRealMilliseconds();
  559. U32 curTime = Platform::getRealMilliseconds() - startTime;
  560. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, "[+%4d.%03d]", U32(curTime * 0.001), curTime % 1000);
  561. }
  562. if (useTimestamp || useRealTimestamp) {
  563. offset += dSprintf(buffer + offset, sizeof(buffer) - offset, " ");
  564. }
  565. dVsprintf(buffer + offset, sizeof(buffer) - offset, fmt, argptr);
  566. for(S32 i = 0; i < gConsumers.size(); i++)
  567. gConsumers[i](level, buffer);
  568. if(logBufferEnabled || consoleLogMode)
  569. {
  570. char *pos = buffer;
  571. while(*pos)
  572. {
  573. if(*pos == '\t')
  574. *pos = '^';
  575. pos++;
  576. }
  577. pos = buffer;
  578. for(;;)
  579. {
  580. char *eofPos = dStrchr(pos, '\n');
  581. if(eofPos)
  582. *eofPos = 0;
  583. log(pos);
  584. if(logBufferEnabled && !consoleLogLocked)
  585. {
  586. ConsoleLogEntry entry;
  587. entry.mLevel = level;
  588. entry.mType = type;
  589. #ifndef TORQUE_SHIPPING // this is equivalent to a memory leak, turn it off in ship build
  590. dsize_t logStringLen = dStrlen(pos) + 1;
  591. entry.mString = (const char *)consoleLogChunker.alloc(logStringLen);
  592. dStrcpy(const_cast<char*>(entry.mString), pos, logStringLen);
  593. // This prevents infinite recursion if the console itself needs to
  594. // re-allocate memory to accommodate the new console log entry, and
  595. // LOG_PAGE_ALLOCS is defined. It is kind of a dirty hack, but the
  596. // uses for LOG_PAGE_ALLOCS are limited, and it is not worth writing
  597. // a lot of special case code to support this situation. -patw
  598. const bool save = Con::active;
  599. Con::active = false;
  600. consoleLog.push_back(entry);
  601. Con::active = save;
  602. #endif
  603. }
  604. if(!eofPos)
  605. break;
  606. pos = eofPos + 1;
  607. }
  608. }
  609. Con::active = true;
  610. }
  611. //------------------------------------------------------------------------------
  612. void printf(const char* fmt,...)
  613. {
  614. va_list argptr;
  615. va_start(argptr, fmt);
  616. _printf(ConsoleLogEntry::Normal, ConsoleLogEntry::General, fmt, argptr);
  617. va_end(argptr);
  618. }
  619. void warnf(ConsoleLogEntry::Type type, const char* fmt,...)
  620. {
  621. va_list argptr;
  622. va_start(argptr, fmt);
  623. _printf(ConsoleLogEntry::Warning, type, fmt, argptr);
  624. va_end(argptr);
  625. }
  626. void errorf(ConsoleLogEntry::Type type, const char* fmt,...)
  627. {
  628. va_list argptr;
  629. va_start(argptr, fmt);
  630. _printf(ConsoleLogEntry::Error, type, fmt, argptr);
  631. va_end(argptr);
  632. }
  633. void warnf(const char* fmt,...)
  634. {
  635. va_list argptr;
  636. va_start(argptr, fmt);
  637. _printf(ConsoleLogEntry::Warning, ConsoleLogEntry::General, fmt, argptr);
  638. va_end(argptr);
  639. }
  640. void errorf(const char* fmt,...)
  641. {
  642. va_list argptr;
  643. va_start(argptr, fmt);
  644. _printf(ConsoleLogEntry::Error, ConsoleLogEntry::General, fmt, argptr);
  645. va_end(argptr);
  646. }
  647. //---------------------------------------------------------------------------
  648. bool getVariableObjectField(const char *name, SimObject **object, const char **field)
  649. {
  650. // get the field info from the object..
  651. const char *dot = dStrchr(name, '.');
  652. if(name[0] != '$' && dot)
  653. {
  654. S32 len = dStrlen(name);
  655. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - name too long");
  656. dMemcpy(scratchBuffer, name, len+1);
  657. char * token = dStrtok(scratchBuffer, ".");
  658. SimObject * obj = Sim::findObject(token);
  659. if(!obj)
  660. return false;
  661. token = dStrtok(0, ".\0");
  662. if(!token)
  663. return false;
  664. while(token != NULL)
  665. {
  666. const char * val = obj->getDataField(StringTable->insert(token), 0);
  667. if(!val)
  668. return false;
  669. char *fieldToken = token;
  670. token = dStrtok(0, ".\0");
  671. if(token)
  672. {
  673. obj = Sim::findObject(token);
  674. if(!obj)
  675. return false;
  676. }
  677. else
  678. {
  679. *object = obj;
  680. *field = fieldToken;
  681. return true;
  682. }
  683. }
  684. }
  685. return false;
  686. }
  687. Dictionary::Entry *getLocalVariableEntry(const char *name)
  688. {
  689. name = prependPercent(name);
  690. return gEvalState.getCurrentFrame().lookup(StringTable->insert(name));
  691. }
  692. Dictionary::Entry *getVariableEntry(const char *name)
  693. {
  694. name = prependDollar(name);
  695. return gEvalState.globalVars.lookup(StringTable->insert(name));
  696. }
  697. Dictionary::Entry *addVariableEntry(const char *name)
  698. {
  699. name = prependDollar(name);
  700. return gEvalState.globalVars.add(StringTable->insert(name));
  701. }
  702. Dictionary::Entry *getAddVariableEntry(const char *name)
  703. {
  704. name = prependDollar(name);
  705. StringTableEntry stName = StringTable->insert(name);
  706. Dictionary::Entry *entry = gEvalState.globalVars.lookup(stName);
  707. if (!entry)
  708. entry = gEvalState.globalVars.add(stName);
  709. return entry;
  710. }
  711. Dictionary::Entry *getAddLocalVariableEntry(const char *name)
  712. {
  713. name = prependPercent(name);
  714. StringTableEntry stName = StringTable->insert(name);
  715. Dictionary::Entry *entry = gEvalState.getCurrentFrame().lookup(stName);
  716. if (!entry)
  717. entry = gEvalState.getCurrentFrame().add(stName);
  718. return entry;
  719. }
  720. void setVariable(const char *name, const char *value)
  721. {
  722. SimObject *obj = NULL;
  723. const char *objField = NULL;
  724. if (getVariableObjectField(name, &obj, &objField))
  725. {
  726. obj->setDataField(StringTable->insert(objField), 0, value);
  727. }
  728. else
  729. {
  730. name = prependDollar(name);
  731. gEvalState.globalVars.setVariable(StringTable->insert(name), value);
  732. }
  733. }
  734. void setLocalVariable(const char *name, const char *value)
  735. {
  736. name = prependPercent(name);
  737. gEvalState.getCurrentFrame().setVariable(StringTable->insert(name), value);
  738. }
  739. void setBoolVariable(const char *varName, bool value)
  740. {
  741. SimObject *obj = NULL;
  742. const char *objField = NULL;
  743. if (getVariableObjectField(varName, &obj, &objField))
  744. {
  745. obj->setDataField(StringTable->insert(objField), 0, value ? "1" : "0");
  746. }
  747. else
  748. {
  749. varName = prependDollar(varName);
  750. Dictionary::Entry *entry = getAddVariableEntry(varName);
  751. entry->setStringValue(value ? "1" : "0");
  752. }
  753. }
  754. void setIntVariable(const char *varName, S32 value)
  755. {
  756. SimObject *obj = NULL;
  757. const char *objField = NULL;
  758. if (getVariableObjectField(varName, &obj, &objField))
  759. {
  760. char varBuffer[32];
  761. dSprintf(varBuffer, sizeof(varBuffer), "%d", value);
  762. obj->setDataField(StringTable->insert(objField), 0, varBuffer);
  763. }
  764. else
  765. {
  766. varName = prependDollar(varName);
  767. Dictionary::Entry *entry = getAddVariableEntry(varName);
  768. entry->setIntValue(value);
  769. }
  770. }
  771. void setFloatVariable(const char *varName, F32 value)
  772. {
  773. SimObject *obj = NULL;
  774. const char *objField = NULL;
  775. if (getVariableObjectField(varName, &obj, &objField))
  776. {
  777. char varBuffer[32];
  778. dSprintf(varBuffer, sizeof(varBuffer), "%g", value);
  779. obj->setDataField(StringTable->insert(objField), 0, varBuffer);
  780. }
  781. else
  782. {
  783. varName = prependDollar(varName);
  784. Dictionary::Entry *entry = getAddVariableEntry(varName);
  785. entry->setFloatValue(value);
  786. }
  787. }
  788. //---------------------------------------------------------------------------
  789. void addConsumer(ConsumerCallback consumer)
  790. {
  791. gConsumers.push_back(consumer);
  792. }
  793. // dhc - found this empty -- trying what I think is a reasonable impl.
  794. void removeConsumer(ConsumerCallback consumer)
  795. {
  796. for(S32 i = 0; i < gConsumers.size(); i++)
  797. {
  798. if (gConsumers[i] == consumer)
  799. {
  800. // remove it from the list.
  801. gConsumers.erase(i);
  802. break;
  803. }
  804. }
  805. }
  806. void stripColorChars(char* line)
  807. {
  808. char* c = line;
  809. char cp = *c;
  810. while (cp)
  811. {
  812. if (cp < 18)
  813. {
  814. // Could be a color control character; let's take a closer look.
  815. if ((cp != 8) && (cp != 9) && (cp != 10) && (cp != 13))
  816. {
  817. // Yep... copy following chars forward over this.
  818. char* cprime = c;
  819. char cpp;
  820. do
  821. {
  822. cpp = *++cprime;
  823. *(cprime - 1) = cpp;
  824. }
  825. while (cpp);
  826. // Back up 1 so we'll check this position again post-copy.
  827. c--;
  828. }
  829. }
  830. cp = *++c;
  831. }
  832. }
  833. //
  834. const char *getObjectTokenField(const char *name)
  835. {
  836. const char *dot = dStrchr(name, '.');
  837. if(name[0] != '$' && dot)
  838. {
  839. S32 len = dStrlen(name);
  840. AssertFatal(len < sizeof(scratchBuffer)-1, "Sim::getVariable - object name too long");
  841. dMemcpy(scratchBuffer, name, len+1);
  842. char * token = dStrtok(scratchBuffer, ".");
  843. SimObject * obj = Sim::findObject(token);
  844. if(!obj)
  845. return("");
  846. token = dStrtok(0, ".\0");
  847. if(!token)
  848. return("");
  849. while(token != NULL)
  850. {
  851. const char * val = obj->getDataField(StringTable->insert(token), 0);
  852. if(!val)
  853. return("");
  854. token = dStrtok(0, ".\0");
  855. if(token)
  856. {
  857. obj = Sim::findObject(token);
  858. if(!obj)
  859. return("");
  860. }
  861. else
  862. return(val);
  863. }
  864. }
  865. return NULL;
  866. }
  867. const char *getVariable(const char *name, const char* def)
  868. {
  869. const char *objField = getObjectTokenField(name);
  870. if (objField)
  871. {
  872. return objField;
  873. }
  874. else
  875. {
  876. Dictionary::Entry *entry = getVariableEntry(name);
  877. return entry ? entry->getStringValue() : def;
  878. }
  879. }
  880. const char *getLocalVariable(const char *name)
  881. {
  882. name = prependPercent(name);
  883. return gEvalState.getCurrentFrame().getVariable(StringTable->insert(name));
  884. }
  885. bool getBoolVariable(const char *varName, bool def)
  886. {
  887. const char *objField = getObjectTokenField(varName);
  888. if (objField)
  889. {
  890. return *objField ? dAtob(objField) : def;
  891. }
  892. else
  893. {
  894. Dictionary::Entry *entry = getVariableEntry(varName);
  895. objField = entry ? entry->getStringValue() : "";
  896. return *objField ? dAtob(objField) : def;
  897. }
  898. }
  899. S32 getIntVariable(const char *varName, S32 def)
  900. {
  901. const char *objField = getObjectTokenField(varName);
  902. if (objField)
  903. {
  904. return *objField ? dAtoi(objField) : def;
  905. }
  906. else
  907. {
  908. Dictionary::Entry *entry = getVariableEntry(varName);
  909. return entry ? entry->getIntValue() : def;
  910. }
  911. }
  912. F32 getFloatVariable(const char *varName, F32 def)
  913. {
  914. const char *objField = getObjectTokenField(varName);
  915. if (objField)
  916. {
  917. return *objField ? dAtof(objField) : def;
  918. }
  919. else
  920. {
  921. Dictionary::Entry *entry = getVariableEntry(varName);
  922. return entry ? entry->getFloatValue() : def;
  923. }
  924. }
  925. //---------------------------------------------------------------------------
  926. void addVariable( const char *name,
  927. S32 type,
  928. void *dptr,
  929. const char* usage )
  930. {
  931. gEvalState.globalVars.addVariable( name, type, dptr, usage );
  932. }
  933. void addConstant( const char *name,
  934. S32 type,
  935. const void *dptr,
  936. const char* usage )
  937. {
  938. Dictionary::Entry* entry = gEvalState.globalVars.addVariable( name, type, const_cast< void* >( dptr ), usage );
  939. entry->mIsConstant = true;
  940. }
  941. bool removeVariable(const char *name)
  942. {
  943. name = StringTable->lookup(prependDollar(name));
  944. return name!=0 && gEvalState.globalVars.removeVariable(name);
  945. }
  946. void addVariableNotify( const char *name, const NotifyDelegate &callback )
  947. {
  948. gEvalState.globalVars.addVariableNotify( name, callback );
  949. }
  950. void removeVariableNotify( const char *name, const NotifyDelegate &callback )
  951. {
  952. gEvalState.globalVars.removeVariableNotify( name, callback );
  953. }
  954. //---------------------------------------------------------------------------
  955. void addCommand( const char *nsName, const char *name,StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  956. {
  957. Namespace *ns = lookupNamespace(nsName);
  958. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  959. }
  960. void addCommand( const char *nsName, const char *name,VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  961. {
  962. Namespace *ns = lookupNamespace(nsName);
  963. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  964. }
  965. void addCommand( const char *nsName, const char *name,IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  966. {
  967. Namespace *ns = lookupNamespace(nsName);
  968. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  969. }
  970. void addCommand( const char *nsName, const char *name,FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  971. {
  972. Namespace *ns = lookupNamespace(nsName);
  973. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  974. }
  975. void addCommand( const char *nsName, const char *name,BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  976. {
  977. Namespace *ns = lookupNamespace(nsName);
  978. ns->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  979. }
  980. void noteScriptCallback( const char *className, const char *funcName, const char *usage, ConsoleFunctionHeader* header )
  981. {
  982. Namespace *ns = lookupNamespace(className);
  983. ns->addScriptCallback( StringTable->insert(funcName), usage, header );
  984. }
  985. void markCommandGroup(const char * nsName, const char *name, const char* usage)
  986. {
  987. Namespace *ns = lookupNamespace(nsName);
  988. ns->markGroup(name,usage);
  989. }
  990. void beginCommandGroup(const char * nsName, const char *name, const char* usage)
  991. {
  992. markCommandGroup(nsName, name, usage);
  993. }
  994. void endCommandGroup(const char * nsName, const char *name)
  995. {
  996. markCommandGroup(nsName, name, NULL);
  997. }
  998. void addCommand( const char *name,StringCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  999. {
  1000. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1001. }
  1002. void addCommand( const char *name,VoidCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1003. {
  1004. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1005. }
  1006. void addCommand( const char *name,IntCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1007. {
  1008. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1009. }
  1010. void addCommand( const char *name,FloatCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1011. {
  1012. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1013. }
  1014. void addCommand( const char *name,BoolCallback cb,const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header )
  1015. {
  1016. Namespace::global()->addCommand( StringTable->insert(name), cb, usage, minArgs, maxArgs, isToolOnly, header );
  1017. }
  1018. bool executeFile(const char* fileName, bool noCalls, bool journalScript)
  1019. {
  1020. bool journal = false;
  1021. char scriptFilenameBuffer[1024];
  1022. U32 execDepth = 0;
  1023. U32 journalDepth = 1;
  1024. execDepth++;
  1025. if (journalDepth >= execDepth)
  1026. journalDepth = execDepth + 1;
  1027. else
  1028. journal = true;
  1029. bool ret = false;
  1030. if (journalScript && !journal)
  1031. {
  1032. journal = true;
  1033. journalDepth = execDepth;
  1034. }
  1035. // Determine the filename we actually want...
  1036. Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), fileName);
  1037. // since this function expects a script file reference, if it's a .dso
  1038. // lets terminate the string before the dso so it will act like a .tscript
  1039. if (dStrEndsWith(scriptFilenameBuffer, ".dso"))
  1040. {
  1041. scriptFilenameBuffer[dStrlen(scriptFilenameBuffer) - dStrlen(".dso")] = '\0';
  1042. }
  1043. // Figure out where to put DSOs
  1044. StringTableEntry dsoPath = Con::getDSOPath(scriptFilenameBuffer);
  1045. const char *ext = dStrrchr(scriptFilenameBuffer, '.');
  1046. if (!ext)
  1047. {
  1048. // Try appending the default script extension and see if that succeeds
  1049. if (executeFile(fileName + String("." TORQUE_SCRIPT_EXTENSION), noCalls, journalScript))
  1050. {
  1051. return true;
  1052. }
  1053. // We need an extension!
  1054. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file name %s.", scriptFilenameBuffer);
  1055. execDepth--;
  1056. return false;
  1057. }
  1058. // Check Editor Extensions
  1059. bool isEditorScript = false;
  1060. // If the script file extension is '.ed.tscript' then compile it to a different compiled extension
  1061. if (dStricmp(ext, "." TORQUE_SCRIPT_EXTENSION) == 0)
  1062. {
  1063. const char* ext2 = ext - 3;
  1064. if (dStricmp(ext2, ".ed." TORQUE_SCRIPT_EXTENSION) == 0)
  1065. isEditorScript = true;
  1066. }
  1067. else if (dStricmp(ext, ".gui") == 0)
  1068. {
  1069. const char* ext2 = ext - 3;
  1070. if (dStricmp(ext2, ".ed.gui") == 0)
  1071. isEditorScript = true;
  1072. }
  1073. StringTableEntry scriptFileName = StringTable->insert(scriptFilenameBuffer);
  1074. // Is this a file we should compile? (anything in the prefs path should not be compiled)
  1075. StringTableEntry prefsPath = Platform::getPrefsPath();
  1076. bool compiled = dStricmp(ext, ".mis") && !journal && !Con::getBoolVariable("Scripts::ignoreDSOs");
  1077. // [tom, 12/5/2006] stripBasePath() fucks up if the filename is not in the exe
  1078. // path, current directory or prefs path. Thus, getDSOFilename() will also screw
  1079. // up and so this allows the scripts to still load but without a DSO.
  1080. if (Platform::isFullPath(Platform::stripBasePath(scriptFilenameBuffer)))
  1081. compiled = false;
  1082. // [tom, 11/17/2006] It seems to make sense to not compile scripts that are in the
  1083. // prefs directory. However, getDSOPath() can handle this situation and will put
  1084. // the dso along with the script to avoid name clashes with tools/game dsos.
  1085. if ((dsoPath && *dsoPath == 0) || (prefsPath && prefsPath[0] && dStrnicmp(scriptFileName, prefsPath, dStrlen(prefsPath)) == 0))
  1086. compiled = false;
  1087. // If we're in a journaling mode, then we will read the script
  1088. // from the journal file.
  1089. if (journal && Journal::IsPlaying())
  1090. {
  1091. char fileNameBuf[256];
  1092. bool fileRead = false;
  1093. U32 fileSize;
  1094. Journal::ReadString(fileNameBuf);
  1095. Journal::Read(&fileRead);
  1096. if (!fileRead)
  1097. {
  1098. Con::errorf(ConsoleLogEntry::Script, "Journal script read (failed) for %s", fileNameBuf);
  1099. execDepth--;
  1100. return false;
  1101. }
  1102. Journal::Read(&fileSize);
  1103. char *script = new char[fileSize + 1];
  1104. Journal::Read(fileSize, script);
  1105. script[fileSize] = 0;
  1106. Con::printf("Executing (journal-read) %s.", scriptFileName);
  1107. CodeBlock *newCodeBlock = new CodeBlock();
  1108. newCodeBlock->compileExec(scriptFileName, script, noCalls, 0);
  1109. delete[] script;
  1110. execDepth--;
  1111. return true;
  1112. }
  1113. // Ok, we let's try to load and compile the script.
  1114. Torque::FS::FileNodeRef scriptFile = Torque::FS::GetFileNode(scriptFileName);
  1115. Torque::FS::FileNodeRef dsoFile;
  1116. // ResourceObject *rScr = gResourceManager->find(scriptFileName);
  1117. // ResourceObject *rCom = NULL;
  1118. char nameBuffer[512];
  1119. char* script = NULL;
  1120. U32 version;
  1121. Stream *compiledStream = NULL;
  1122. Torque::Time scriptModifiedTime, dsoModifiedTime;
  1123. // Check here for .edso
  1124. bool edso = false;
  1125. if (dStricmp(ext, ".edso") == 0 && scriptFile != NULL)
  1126. {
  1127. edso = true;
  1128. dsoFile = scriptFile;
  1129. scriptFile = NULL;
  1130. dsoModifiedTime = dsoFile->getModifiedTime();
  1131. dStrcpy(nameBuffer, scriptFileName, 512);
  1132. }
  1133. // If we're supposed to be compiling this file, check to see if there's a DSO
  1134. if (compiled && !edso)
  1135. {
  1136. const char *filenameOnly = dStrrchr(scriptFileName, '/');
  1137. if (filenameOnly)
  1138. ++filenameOnly;
  1139. else
  1140. filenameOnly = scriptFileName;
  1141. char pathAndFilename[1024];
  1142. Platform::makeFullPathName(filenameOnly, pathAndFilename, sizeof(pathAndFilename), dsoPath);
  1143. if (isEditorScript)
  1144. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".edso", NULL);
  1145. else
  1146. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".dso", NULL);
  1147. dsoFile = Torque::FS::GetFileNode(nameBuffer);
  1148. if (scriptFile != NULL)
  1149. scriptModifiedTime = scriptFile->getModifiedTime();
  1150. if (dsoFile != NULL)
  1151. dsoModifiedTime = dsoFile->getModifiedTime();
  1152. }
  1153. // Let's do a sanity check to complain about DSOs in the future.
  1154. //
  1155. // MM: This doesn't seem to be working correctly for now so let's just not issue
  1156. // the warning until someone knows how to resolve it.
  1157. //
  1158. //if(compiled && rCom && rScr && Platform::compareFileTimes(comModifyTime, scrModifyTime) < 0)
  1159. //{
  1160. //Con::warnf("exec: Warning! Found a DSO from the future! (%s)", nameBuffer);
  1161. //}
  1162. // If we had a DSO, let's check to see if we should be reading from it.
  1163. //MGT: fixed bug with dsos not getting recompiled correctly
  1164. //Note: Using Nathan Martin's version from the forums since its easier to read and understand
  1165. if (compiled && dsoFile != NULL && (scriptFile == NULL || (dsoModifiedTime >= scriptModifiedTime)))
  1166. { //MGT: end
  1167. compiledStream = FileStream::createAndOpen(nameBuffer, Torque::FS::File::Read);
  1168. if (compiledStream)
  1169. {
  1170. // Check the version!
  1171. compiledStream->read(&version);
  1172. if (version != Con::DSOVersion)
  1173. {
  1174. Con::warnf("exec: Found an old DSO (%s, ver %d < %d), ignoring.", nameBuffer, version, Con::DSOVersion);
  1175. delete compiledStream;
  1176. compiledStream = NULL;
  1177. }
  1178. }
  1179. }
  1180. // If we're journalling, let's write some info out.
  1181. if (journal && Journal::IsRecording())
  1182. Journal::WriteString(scriptFileName);
  1183. if (scriptFile != NULL && !compiledStream)
  1184. {
  1185. // If we have source but no compiled version, then we need to compile
  1186. // (and journal as we do so, if that's required).
  1187. void *data;
  1188. U32 dataSize = 0;
  1189. Torque::FS::ReadFile(scriptFileName, data, dataSize, true);
  1190. if (journal && Journal::IsRecording())
  1191. Journal::Write(bool(data != NULL));
  1192. if (data == NULL)
  1193. {
  1194. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file %s.", scriptFileName);
  1195. execDepth--;
  1196. return false;
  1197. }
  1198. else
  1199. {
  1200. if (!dataSize)
  1201. {
  1202. execDepth--;
  1203. return false;
  1204. }
  1205. script = (char *)data;
  1206. if (journal && Journal::IsRecording())
  1207. {
  1208. Journal::Write(dataSize);
  1209. Journal::Write(dataSize, data);
  1210. }
  1211. }
  1212. #ifndef TORQUE_NO_DSO_GENERATION
  1213. if (compiled)
  1214. {
  1215. // compile this baddie.
  1216. #ifdef TORQUE_DEBUG
  1217. Con::printf("Compiling %s...", scriptFileName);
  1218. #endif
  1219. CodeBlock *code = new CodeBlock();
  1220. code->compile(nameBuffer, scriptFileName, script);
  1221. delete code;
  1222. code = NULL;
  1223. compiledStream = FileStream::createAndOpen(nameBuffer, Torque::FS::File::Read);
  1224. if (compiledStream)
  1225. {
  1226. compiledStream->read(&version);
  1227. }
  1228. else
  1229. {
  1230. // We have to exit out here, as otherwise we get double error reports.
  1231. delete[] script;
  1232. execDepth--;
  1233. return false;
  1234. }
  1235. }
  1236. #endif
  1237. }
  1238. else
  1239. {
  1240. if (journal && Journal::IsRecording())
  1241. Journal::Write(bool(false));
  1242. }
  1243. if (compiledStream)
  1244. {
  1245. // Delete the script object first to limit memory used
  1246. // during recursive execs.
  1247. delete[] script;
  1248. script = 0;
  1249. // We're all compiled, so let's run it.
  1250. #ifdef TORQUE_DEBUG
  1251. Con::printf("Loading compiled script %s.", scriptFileName);
  1252. #endif
  1253. CodeBlock *code = new CodeBlock;
  1254. code->read(scriptFileName, *compiledStream);
  1255. delete compiledStream;
  1256. code->exec(0, scriptFileName, NULL, 0, NULL, noCalls, NULL, 0);
  1257. ret = true;
  1258. }
  1259. else
  1260. if (scriptFile)
  1261. {
  1262. // No compiled script, let's just try executing it
  1263. // directly... this is either a mission file, or maybe
  1264. // we're on a readonly volume.
  1265. #ifdef TORQUE_DEBUG
  1266. Con::printf("Executing %s.", scriptFileName);
  1267. #endif
  1268. CodeBlock *newCodeBlock = new CodeBlock();
  1269. StringTableEntry name = StringTable->insert(scriptFileName);
  1270. newCodeBlock->compileExec(name, script, noCalls, 0);
  1271. ret = true;
  1272. }
  1273. else
  1274. {
  1275. // Don't have anything.
  1276. Con::warnf(ConsoleLogEntry::Script, "Missing file: %s!", scriptFileName);
  1277. ret = false;
  1278. }
  1279. delete[] script;
  1280. execDepth--;
  1281. return ret;
  1282. }
  1283. ConsoleValue evaluate(const char* string, bool echo, const char *fileName)
  1284. {
  1285. ConsoleStackFrameSaver stackSaver;
  1286. stackSaver.save();
  1287. if (echo)
  1288. {
  1289. if (string[0] == '%')
  1290. Con::printf("%s", string);
  1291. else
  1292. Con::printf("%s%s", getVariable( "$Con::Prompt" ), string);
  1293. }
  1294. if(fileName)
  1295. fileName = StringTable->insert(fileName);
  1296. CodeBlock *newCodeBlock = new CodeBlock();
  1297. return std::move(newCodeBlock->compileExec(fileName, string, false, fileName ? -1 : 0));
  1298. }
  1299. //------------------------------------------------------------------------------
  1300. ConsoleValue evaluatef(const char* string, ...)
  1301. {
  1302. ConsoleStackFrameSaver stackSaver;
  1303. stackSaver.save();
  1304. char buffer[4096];
  1305. va_list args;
  1306. va_start(args, string);
  1307. dVsprintf(buffer, sizeof(buffer), string, args);
  1308. va_end(args);
  1309. CodeBlock *newCodeBlock = new CodeBlock();
  1310. return newCodeBlock->compileExec(NULL, buffer, false, 0);
  1311. }
  1312. //------------------------------------------------------------------------------
  1313. // Internal execute for global function which does not save the stack
  1314. ConsoleValue _internalExecute(S32 argc, ConsoleValue argv[])
  1315. {
  1316. StringTableEntry funcName = StringTable->insert(argv[0].getString());
  1317. const char** argv_str = static_cast<const char**>(malloc((argc - 1) * sizeof(char *)));
  1318. for (int i = 0; i < argc - 1; i++)
  1319. {
  1320. argv_str[i] = argv[i + 1].getString();
  1321. }
  1322. bool result;
  1323. const char* methodRes = CInterface::CallFunction(NULL, funcName, argv_str, argc - 1, &result);
  1324. free(argv_str);
  1325. if (result)
  1326. {
  1327. ConsoleValue ret;
  1328. ret.setString(methodRes);
  1329. return std::move(ret);
  1330. }
  1331. Namespace::Entry *ent;
  1332. ent = Namespace::global()->lookup(funcName);
  1333. if(!ent)
  1334. {
  1335. warnf(ConsoleLogEntry::Script, "%s: Unknown command.", funcName);
  1336. STR.clearFunctionOffset();
  1337. return std::move(ConsoleValue());
  1338. }
  1339. return std::move(ent->execute(argc, argv, &gEvalState));
  1340. }
  1341. ConsoleValue execute(S32 argc, ConsoleValue argv[])
  1342. {
  1343. #ifdef TORQUE_MULTITHREAD
  1344. if(isMainThread())
  1345. {
  1346. #endif
  1347. ConsoleStackFrameSaver stackSaver;
  1348. stackSaver.save();
  1349. return _internalExecute(argc, argv);
  1350. #ifdef TORQUE_MULTITHREAD
  1351. }
  1352. else
  1353. {
  1354. SimConsoleThreadExecCallback cb;
  1355. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, false, &cb);
  1356. Sim::postEvent(Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1357. return cb.waitForResult();
  1358. }
  1359. #endif
  1360. }
  1361. ConsoleValue execute(S32 argc, const char *argv[])
  1362. {
  1363. ConsoleStackFrameSaver stackSaver;
  1364. stackSaver.save();
  1365. StringArrayToConsoleValueWrapper args(argc, argv);
  1366. return std::move(execute(args.count(), args));
  1367. }
  1368. //------------------------------------------------------------------------------
  1369. // Internal execute for object method which does not save the stack
  1370. static ConsoleValue _internalExecute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1371. {
  1372. if(argc < 2)
  1373. {
  1374. STR.clearFunctionOffset();
  1375. return std::move(ConsoleValue());
  1376. }
  1377. // [neo, 10/05/2007 - #3010]
  1378. // Make sure we don't get recursive calls, respect the flag!
  1379. // Should we be calling handlesMethod() first?
  1380. if( !thisCallOnly )
  1381. {
  1382. ICallMethod *com = dynamic_cast<ICallMethod *>(object);
  1383. if(com)
  1384. {
  1385. gCallStack.pushFrame(0);
  1386. com->callMethodArgList(argc, argv, false);
  1387. gCallStack.popFrame();
  1388. }
  1389. }
  1390. StringTableEntry funcName = StringTable->insert(argv[0].getString());
  1391. const char** argv_str = static_cast<const char**>(malloc((argc - 2) * sizeof(char *)));
  1392. for (int i = 0; i < argc - 2; i++)
  1393. {
  1394. argv_str[i] = argv[i + 2].getString();
  1395. }
  1396. bool result;
  1397. const char* methodRes = CInterface::CallMethod(object, funcName, argv_str, argc - 2, &result);
  1398. free(argv_str);
  1399. if (result)
  1400. {
  1401. ConsoleValue val;
  1402. val.setString(methodRes);
  1403. return std::move(val);
  1404. }
  1405. if(object->getNamespace())
  1406. {
  1407. U32 ident = object->getId();
  1408. const char* oldIdent = argv[1].getString();
  1409. Namespace::Entry *ent = object->getNamespace()->lookup(funcName);
  1410. if(ent == NULL)
  1411. {
  1412. //warnf(ConsoleLogEntry::Script, "%s: undefined for object '%s' - id %d", funcName, object->getName(), object->getId());
  1413. STR.clearFunctionOffset();
  1414. return std::move(ConsoleValue());
  1415. }
  1416. // Twiddle %this argument
  1417. argv[1].setInt(ident);
  1418. SimObject *save = gEvalState.thisObject;
  1419. gEvalState.thisObject = object;
  1420. ConsoleValue ret = std::move(ent->execute(argc, argv, &gEvalState));
  1421. gEvalState.thisObject = save;
  1422. // Twiddle it back
  1423. argv[1].setString(oldIdent);
  1424. return std::move(ret);
  1425. }
  1426. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), funcName);
  1427. STR.clearFunctionOffset();
  1428. return std::move(ConsoleValue());
  1429. }
  1430. ConsoleValue execute(SimObject *object, S32 argc, ConsoleValue argv[], bool thisCallOnly)
  1431. {
  1432. if(argc < 2)
  1433. {
  1434. STR.clearFunctionOffset();
  1435. return std::move(ConsoleValue());
  1436. }
  1437. ConsoleStackFrameSaver stackSaver;
  1438. stackSaver.save();
  1439. if (object->getNamespace() || !thisCallOnly)
  1440. {
  1441. if (isMainThread())
  1442. {
  1443. return std::move(_internalExecute(object, argc, argv, thisCallOnly));
  1444. }
  1445. else
  1446. {
  1447. SimConsoleThreadExecCallback cb;
  1448. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(argc, argv, true, &cb);
  1449. Sim::postEvent(object, evt, Sim::getCurrentTime());
  1450. }
  1451. }
  1452. warnf(ConsoleLogEntry::Script, "Con::execute - %d has no namespace: %s", object->getId(), argv[0].getString());
  1453. STR.clearFunctionOffset();
  1454. return std::move(ConsoleValue());
  1455. }
  1456. ConsoleValue execute(SimObject *object, S32 argc, const char *argv[], bool thisCallOnly)
  1457. {
  1458. ConsoleStackFrameSaver stackSaver;
  1459. stackSaver.save();
  1460. StringArrayToConsoleValueWrapper args(argc, argv);
  1461. return std::move(execute(object, args.count(), args, thisCallOnly));
  1462. }
  1463. inline ConsoleValue _executef(SimObject *obj, S32 checkArgc, S32 argc, ConsoleValue *argv)
  1464. {
  1465. const U32 maxArg = 12;
  1466. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef(SimObject*)");
  1467. AssertFatal(argc <= maxArg - 1, "Too many args passed to Con::_executef(SimObject*). Please update the function to handle more.");
  1468. return std::move(execute(obj, argc, argv));
  1469. }
  1470. //------------------------------------------------------------------------------
  1471. inline ConsoleValue _executef(S32 checkArgc, S32 argc, ConsoleValue *argv)
  1472. {
  1473. const U32 maxArg = 10;
  1474. AssertFatal(checkArgc == argc, "Incorrect arg count passed to Con::executef()");
  1475. AssertFatal(argc <= maxArg, "Too many args passed to Con::_executef(). Please update the function to handle more.");
  1476. return std::move(execute(argc, argv));
  1477. }
  1478. //------------------------------------------------------------------------------
  1479. bool isFunction(const char *fn)
  1480. {
  1481. if (CInterface::isMethod(NULL, fn)) return true;
  1482. const char *string = StringTable->lookup(fn);
  1483. if(!string)
  1484. return false;
  1485. else
  1486. return Namespace::global()->lookup(string) != NULL;
  1487. }
  1488. //------------------------------------------------------------------------------
  1489. void setLogMode(S32 newMode)
  1490. {
  1491. if ((newMode & 0x3) != (consoleLogMode & 0x3)) {
  1492. if (newMode && !consoleLogMode) {
  1493. // Enabling logging when it was previously disabled.
  1494. newLogFile = true;
  1495. }
  1496. if ((consoleLogMode & 0x3) == 2) {
  1497. // Changing away from mode 2, must close logfile.
  1498. consoleLogFile.close();
  1499. }
  1500. else if ((newMode & 0x3) == 2) {
  1501. #ifdef _XBOX
  1502. // Xbox is not going to support logging to a file. Use the OutputDebugStr
  1503. // log consumer
  1504. Platform::debugBreak();
  1505. #endif
  1506. // Starting mode 2, must open logfile.
  1507. consoleLogFile.open(defLogFileName, Torque::FS::File::Write);
  1508. }
  1509. consoleLogMode = newMode;
  1510. }
  1511. }
  1512. Namespace *lookupNamespace(const char *ns)
  1513. {
  1514. if(!ns)
  1515. return Namespace::global();
  1516. return Namespace::find(StringTable->insert(ns));
  1517. }
  1518. bool linkNamespaces(const char *parent, const char *child)
  1519. {
  1520. Namespace *pns = lookupNamespace(parent);
  1521. Namespace *cns = lookupNamespace(child);
  1522. if(pns && cns)
  1523. return cns->classLinkTo(pns);
  1524. return false;
  1525. }
  1526. bool unlinkNamespaces(const char *parent, const char *child)
  1527. {
  1528. Namespace *pns = lookupNamespace(parent);
  1529. Namespace *cns = lookupNamespace(child);
  1530. if(pns == cns)
  1531. {
  1532. Con::warnf("Con::unlinkNamespaces - trying to unlink '%s' from itself, aborting.", parent);
  1533. return false;
  1534. }
  1535. if(pns && cns)
  1536. return cns->unlinkClass(pns);
  1537. return false;
  1538. }
  1539. bool classLinkNamespaces(Namespace *parent, Namespace *child)
  1540. {
  1541. if(parent && child)
  1542. return child->classLinkTo(parent);
  1543. return false;
  1544. }
  1545. void setData(S32 type, void *dptr, S32 index, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)
  1546. {
  1547. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1548. AssertFatal(cbt, "Con::setData - could not resolve type ID!");
  1549. cbt->setData((void *) (((const char *)dptr) + index * cbt->getTypeSize()),argc, argv, tbl, flag);
  1550. }
  1551. const char *getData(S32 type, void *dptr, S32 index, const EnumTable *tbl, BitSet32 flag)
  1552. {
  1553. ConsoleBaseType *cbt = ConsoleBaseType::getType(type);
  1554. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1555. return cbt->getData((void *) (((const char *)dptr) + index * cbt->getTypeSize()), tbl, flag);
  1556. }
  1557. const char *getFormattedData(S32 type, const char *data, const EnumTable *tbl, BitSet32 flag)
  1558. {
  1559. ConsoleBaseType *cbt = ConsoleBaseType::getType( type );
  1560. AssertFatal(cbt, "Con::getData - could not resolve type ID!");
  1561. // Datablock types are just a datablock
  1562. // name and don't ever need formatting.
  1563. if ( cbt->isDatablock() )
  1564. return data;
  1565. bool currWarn = gWarnUndefinedScriptVariables;
  1566. gWarnUndefinedScriptVariables = false;
  1567. const char* globalValue = Con::getVariable(data);
  1568. gWarnUndefinedScriptVariables = currWarn;
  1569. if (dStrlen(globalValue) > 0)
  1570. return globalValue;
  1571. void* variable = cbt->getNativeVariable();
  1572. if (variable)
  1573. {
  1574. Con::setData(type, variable, 0, 1, &data, tbl, flag);
  1575. const char* formattedVal = Con::getData(type, variable, 0, tbl, flag);
  1576. static const U32 bufSize = 2048;
  1577. char* returnBuffer = Con::getReturnBuffer(bufSize);
  1578. dSprintf(returnBuffer, bufSize, "%s\0", formattedVal );
  1579. cbt->deleteNativeVariable(variable);
  1580. return returnBuffer;
  1581. }
  1582. else
  1583. return data;
  1584. }
  1585. //------------------------------------------------------------------------------
  1586. bool isCurrentScriptToolScript()
  1587. {
  1588. // With a player build we ALWAYS return false
  1589. #ifndef TORQUE_TOOLS
  1590. return false;
  1591. #else
  1592. const StringTableEntry cbFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1593. if(cbFullPath == NULL)
  1594. return false;
  1595. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1596. return dStrnicmp(exePath, cbFullPath, dStrlen(exePath)) == 0;
  1597. #endif
  1598. }
  1599. //------------------------------------------------------------------------------
  1600. StringTableEntry getModNameFromPath(const char *path)
  1601. {
  1602. if(path == NULL || *path == 0)
  1603. return NULL;
  1604. char buf[1024];
  1605. buf[0] = 0;
  1606. if(path[0] == '/' || path[1] == ':')
  1607. {
  1608. // It's an absolute path
  1609. const StringTableEntry exePath = Platform::getMainDotCsDir();
  1610. U32 len = dStrlen(exePath);
  1611. if(dStrnicmp(exePath, path, len) == 0)
  1612. {
  1613. const char *ptr = path + len + 1;
  1614. const char *slash = dStrchr(ptr, '/');
  1615. if(slash)
  1616. {
  1617. dStrncpy(buf, ptr, slash - ptr);
  1618. buf[slash - ptr] = 0;
  1619. }
  1620. else
  1621. return NULL;
  1622. }
  1623. else
  1624. return NULL;
  1625. }
  1626. else
  1627. {
  1628. const char *slash = dStrchr(path, '/');
  1629. if(slash)
  1630. {
  1631. dStrncpy(buf, path, slash - path);
  1632. buf[slash - path] = 0;
  1633. }
  1634. else
  1635. return NULL;
  1636. }
  1637. return StringTable->insert(buf);
  1638. }
  1639. void postConsoleInput( RawData data )
  1640. {
  1641. // TODO(JTH): Mem leak
  1642. // Schedule this to happen at the next time event.
  1643. ConsoleValue* argv = new ConsoleValue[2];
  1644. argv[0].setString("eval");
  1645. argv[1].setString(reinterpret_cast<const char*>(data.data));
  1646. Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(2, argv, false));
  1647. }
  1648. //------------------------------------------------------------------------------
  1649. void pushInstantGroup( String name )
  1650. {
  1651. sInstantGroupStack.push_back( gInstantGroup );
  1652. gInstantGroup = name;
  1653. }
  1654. void popInstantGroup()
  1655. {
  1656. if( sInstantGroupStack.empty() )
  1657. gInstantGroup = String::EmptyString;
  1658. else
  1659. {
  1660. gInstantGroup = sInstantGroupStack.last();
  1661. sInstantGroupStack.pop_back();
  1662. }
  1663. }
  1664. typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
  1665. static typePathExpandoMap PathExpandos;
  1666. //-----------------------------------------------------------------------------
  1667. void addPathExpando(const char* pExpandoName, const char* pPath)
  1668. {
  1669. // Sanity!
  1670. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1671. AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
  1672. // Fetch expando name.
  1673. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1674. // Fetch the length of the path.
  1675. S32 pathLength = dStrlen(pPath);
  1676. char pathBuffer[1024];
  1677. // Sanity!
  1678. if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
  1679. {
  1680. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1681. return;
  1682. }
  1683. // Strip repeat slashes.
  1684. if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
  1685. {
  1686. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1687. return;
  1688. }
  1689. // Fetch new path length.
  1690. pathLength = dStrlen(pathBuffer);
  1691. // Sanity!
  1692. if (pathLength == 0)
  1693. {
  1694. Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
  1695. return;
  1696. }
  1697. // Remove any terminating slash.
  1698. if (pathBuffer[pathLength - 1] == '/')
  1699. pathBuffer[pathLength - 1] = 0;
  1700. // Fetch expanded path.
  1701. StringTableEntry expandedPath = StringTable->insert(pathBuffer);
  1702. // Info.
  1703. #if defined(TORQUE_DEBUG)
  1704. Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
  1705. #endif
  1706. // Find any existing path expando.
  1707. typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
  1708. // Does the expando exist?
  1709. if (expandoItr != PathExpandos.end())
  1710. {
  1711. // Yes, so modify the path.
  1712. expandoItr->value = expandedPath;
  1713. return;
  1714. }
  1715. // Insert expando.
  1716. PathExpandos.insert(expandoName, expandedPath);
  1717. }
  1718. //-----------------------------------------------------------------------------
  1719. StringTableEntry getPathExpando(const char* pExpandoName)
  1720. {
  1721. // Sanity!
  1722. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1723. // Fetch expando name.
  1724. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1725. // Find any existing path expando.
  1726. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1727. // Does the expando exist?
  1728. if (expandoItr != PathExpandos.end())
  1729. {
  1730. // Yes, so return it.
  1731. return expandoItr->value;
  1732. }
  1733. // Not found.
  1734. return NULL;
  1735. }
  1736. //-----------------------------------------------------------------------------
  1737. void removePathExpando(const char* pExpandoName)
  1738. {
  1739. // Sanity!
  1740. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1741. // Fetch expando name.
  1742. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1743. // Find any existing path expando.
  1744. typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
  1745. // Does the expando exist?
  1746. if (expandoItr == PathExpandos.end())
  1747. {
  1748. // No, so warn.
  1749. #if defined(TORQUE_DEBUG)
  1750. Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
  1751. #endif
  1752. return;
  1753. }
  1754. // Info.
  1755. #if defined(TORQUE_DEBUG)
  1756. Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
  1757. #endif
  1758. // Remove expando.
  1759. PathExpandos.erase(expandoItr);
  1760. }
  1761. //-----------------------------------------------------------------------------
  1762. bool isPathExpando(const char* pExpandoName)
  1763. {
  1764. // Sanity!
  1765. AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
  1766. // Fetch expando name.
  1767. StringTableEntry expandoName = StringTable->insert(pExpandoName);
  1768. return PathExpandos.contains(expandoName);
  1769. }
  1770. //-----------------------------------------------------------------------------
  1771. U32 getPathExpandoCount(void)
  1772. {
  1773. return PathExpandos.size();
  1774. }
  1775. //-----------------------------------------------------------------------------
  1776. StringTableEntry getPathExpandoKey(U32 expandoIndex)
  1777. {
  1778. // Finish if index is out of range.
  1779. if (expandoIndex >= PathExpandos.size())
  1780. return NULL;
  1781. // Find indexed iterator.
  1782. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1783. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1784. return expandoItr->key;
  1785. }
  1786. //-----------------------------------------------------------------------------
  1787. StringTableEntry getPathExpandoValue(U32 expandoIndex)
  1788. {
  1789. // Finish if index is out of range.
  1790. if (expandoIndex >= PathExpandos.size())
  1791. return NULL;
  1792. // Find indexed iterator.
  1793. typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
  1794. while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
  1795. return expandoItr->value;
  1796. }
  1797. //-----------------------------------------------------------------------------
  1798. bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
  1799. {
  1800. char pathBuffer[2048];
  1801. const char* pSrc = pSrcPath;
  1802. char* pSlash;
  1803. // Fetch leading character.
  1804. const char leadingToken = *pSrc;
  1805. // Fetch following token.
  1806. const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
  1807. // Expando.
  1808. if (leadingToken == '^')
  1809. {
  1810. // Initial prefix search.
  1811. const char* pPrefixSrc = pSrc + 1;
  1812. char* pPrefixDst = pathBuffer;
  1813. // Search for end of expando.
  1814. while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
  1815. {
  1816. // Copy prefix character.
  1817. *pPrefixDst++ = *pPrefixSrc++;
  1818. }
  1819. // Yes, so terminate the expando string.
  1820. *pPrefixDst = 0;
  1821. // Fetch the expando path.
  1822. StringTableEntry expandoPath = getPathExpando(pathBuffer);
  1823. // Does the expando exist?
  1824. if (expandoPath == NULL)
  1825. {
  1826. // No, so error.
  1827. Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
  1828. // Are we ensuring the trailing slash?
  1829. if (ensureTrailingSlash)
  1830. {
  1831. // Yes, so ensure it.
  1832. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1833. }
  1834. else
  1835. {
  1836. // No, so just use the source path.
  1837. dStrcpy(pDstPath, pSrcPath, size);
  1838. }
  1839. return false;
  1840. }
  1841. // Skip the expando and the following slash.
  1842. pSrc += dStrlen(pathBuffer) + 1;
  1843. // Format the output path.
  1844. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
  1845. // Are we ensuring the trailing slash?
  1846. if (ensureTrailingSlash)
  1847. {
  1848. // Yes, so ensure it.
  1849. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1850. }
  1851. // Strip repeat slashes.
  1852. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1853. return true;
  1854. }
  1855. // Script-Relative.
  1856. if (leadingToken == '.')
  1857. {
  1858. // Fetch the code-block file-path.
  1859. const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
  1860. // Do we have a code block full path?
  1861. if (codeblockFullPath == NULL)
  1862. {
  1863. // No, so error.
  1864. Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
  1865. // Are we ensuring the trailing slash?
  1866. if (ensureTrailingSlash)
  1867. {
  1868. // Yes, so ensure it.
  1869. Con::ensureTrailingSlash(pDstPath, pSrcPath, size);
  1870. }
  1871. else
  1872. {
  1873. // No, so just use the source path.
  1874. dStrcpy(pDstPath, pSrcPath, size);
  1875. }
  1876. return false;
  1877. }
  1878. // Yes, so use it as the prefix.
  1879. dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
  1880. // Find the final slash in the code-block.
  1881. pSlash = dStrrchr(pathBuffer, '/');
  1882. // Is this a parent directory token?
  1883. if (followingToken == '.')
  1884. {
  1885. // Yes, so terminate after the slash so we include it.
  1886. pSlash[1] = 0;
  1887. }
  1888. else
  1889. {
  1890. // No, it's a current directory token so terminate at the slash so we don't include it.
  1891. pSlash[0] = 0;
  1892. // Skip the current directory token.
  1893. pSrc++;
  1894. }
  1895. // Format the output path.
  1896. dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1897. dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
  1898. // Are we ensuring the trailing slash?
  1899. if (ensureTrailingSlash)
  1900. {
  1901. // Yes, so ensure it.
  1902. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1903. }
  1904. // Strip repeat slashes.
  1905. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1906. return true;
  1907. }
  1908. // All else.
  1909. //Using a special case here because the code below barfs on trying to build a full path for apk reading
  1910. #ifdef TORQUE_OS_ANDROID
  1911. if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
  1912. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1913. else
  1914. dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
  1915. #else
  1916. Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
  1917. #endif
  1918. // Are we ensuring the trailing slash?
  1919. if (ensureTrailingSlash)
  1920. {
  1921. // Yes, so ensure it.
  1922. Con::ensureTrailingSlash(pathBuffer, pathBuffer, size);
  1923. }
  1924. // Strip repeat slashes.
  1925. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1926. return true;
  1927. }
  1928. //-----------------------------------------------------------------------------
  1929. bool isBasePath(const char* SrcPath, const char* pBasePath)
  1930. {
  1931. char expandBuffer[1024], expandBaseBuffer[1024];
  1932. Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
  1933. Con::expandPath(expandBaseBuffer, sizeof(expandBaseBuffer), pBasePath);
  1934. return dStrnicmp(expandBaseBuffer, expandBuffer, dStrlen(expandBaseBuffer)) == 0;
  1935. }
  1936. //-----------------------------------------------------------------------------
  1937. void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
  1938. {
  1939. // Check path against expandos. If there are multiple matches, choose the
  1940. // expando that produces the shortest relative path.
  1941. char pathBuffer[2048];
  1942. // Fetch expando count.
  1943. const U32 expandoCount = getPathExpandoCount();
  1944. // Iterate expandos.
  1945. U32 expandoRelativePathLength = U32_MAX;
  1946. for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
  1947. {
  1948. // Fetch expando value (path).
  1949. StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
  1950. // Skip if not the base path.
  1951. if (!isBasePath(pSrcPath, expandoValue))
  1952. continue;
  1953. // Fetch path relative to expando path.
  1954. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
  1955. // If the relative path is simply a period
  1956. if (relativePath[0] == '.')
  1957. relativePath++;
  1958. if (dStrlen(relativePath) > expandoRelativePathLength)
  1959. {
  1960. // This expando covers less of the path than any previous one found.
  1961. // We will keep the previous one.
  1962. continue;
  1963. }
  1964. // Keep track of the relative path length
  1965. expandoRelativePathLength = dStrlen(relativePath);
  1966. // Fetch expando key (name).
  1967. StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
  1968. // Format against expando.
  1969. dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
  1970. }
  1971. // Check if we've found a suitable expando
  1972. if (expandoRelativePathLength != U32_MAX)
  1973. {
  1974. // Strip repeat slashes.
  1975. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1976. return;
  1977. }
  1978. // Fetch the working directory.
  1979. StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
  1980. // Fetch path relative to current directory.
  1981. StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
  1982. // If the relative path is simply a period
  1983. if (relativePath[0] == '.' && relativePath[1] != '.')
  1984. relativePath++;
  1985. // Format against expando.
  1986. dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
  1987. // Strip repeat slashes.
  1988. Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
  1989. }
  1990. void ensureTrailingSlash(char* pDstPath, const char* pSrcPath, S32 dstSize)
  1991. {
  1992. // Copy to target.
  1993. dStrcpy(pDstPath, pSrcPath, dstSize);
  1994. // Find trailing character index.
  1995. S32 trailIndex = dStrlen(pDstPath);
  1996. // Ignore if empty string.
  1997. if (trailIndex == 0)
  1998. return;
  1999. // Finish if the trailing slash already exists.
  2000. if (pDstPath[trailIndex - 1] == '/')
  2001. return;
  2002. // Add trailing slash.
  2003. pDstPath[trailIndex++] = '/';
  2004. pDstPath[trailIndex] = 0;
  2005. }
  2006. //-----------------------------------------------------------------------------
  2007. StringTableEntry getDSOPath(const char *scriptPath)
  2008. {
  2009. #ifndef TORQUE2D_TOOLS_FIXME
  2010. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  2011. const char *slash = dStrrchr(scriptPath, '/');
  2012. if (slash != NULL)
  2013. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  2014. slash = dStrrchr(scriptPath, ':');
  2015. if (slash != NULL)
  2016. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  2017. return "";
  2018. #else
  2019. char relPath[1024], dsoPath[1024];
  2020. bool isPrefs = false;
  2021. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  2022. StringTableEntry prefsPath = Platform::getPrefsPath();
  2023. if (dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  2024. {
  2025. relPath[0] = 0;
  2026. isPrefs = true;
  2027. }
  2028. else
  2029. {
  2030. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  2031. dStrcpy(relPath, strippedPath, 1024);
  2032. char *slash = dStrrchr(relPath, '/');
  2033. if (slash)
  2034. *slash = 0;
  2035. }
  2036. const char *overridePath;
  2037. if (!isPrefs)
  2038. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  2039. else
  2040. overridePath = prefsPath;
  2041. if (overridePath && *overridePath)
  2042. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  2043. else
  2044. {
  2045. char t[1024];
  2046. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  2047. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  2048. }
  2049. return StringTable->insert(dsoPath);
  2050. #endif
  2051. }
  2052. //-----------------------------------------------------------------------------
  2053. bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
  2054. {
  2055. // Note original destination.
  2056. char* pOriginalDst = pDstPath;
  2057. // Reset last source character.
  2058. char lastSrcChar = 0;
  2059. // Search source...
  2060. while (dstSize > 0)
  2061. {
  2062. // Fetch characters.
  2063. const char srcChar = *pSrcPath++;
  2064. // Do we have a repeat slash?
  2065. if (srcChar == '/' && lastSrcChar == '/')
  2066. {
  2067. // Yes, so skip it.
  2068. continue;
  2069. }
  2070. // No, so copy character.
  2071. *pDstPath++ = srcChar;
  2072. // Finish if end of source.
  2073. if (srcChar == 0)
  2074. return true;
  2075. // Reduce room left in destination.
  2076. dstSize--;
  2077. // Set last character.
  2078. lastSrcChar = srcChar;
  2079. }
  2080. // Terminate the destination string as we ran out of room.
  2081. *pOriginalDst = 0;
  2082. // Fail!
  2083. return false;
  2084. }
  2085. } // end of Console namespace
  2086. #endif
  2087. //=============================================================================
  2088. // API.
  2089. //=============================================================================
  2090. // MARK: ---- API ----
  2091. //-----------------------------------------------------------------------------
  2092. DefineEngineFunction( log, void, ( const char* message ),,
  2093. "@brief Logs a message to the console.\n\n"
  2094. "@param message The message text.\n"
  2095. "@note By default, messages will appear white in the console.\n"
  2096. "@ingroup Logging")
  2097. {
  2098. Con::printf( "%s", message );
  2099. }
  2100. //-----------------------------------------------------------------------------
  2101. DefineEngineFunction( logError, void, ( const char* message ),,
  2102. "@brief Logs an error message to the console.\n\n"
  2103. "@param message The message text.\n"
  2104. "@note By default, errors will appear red in the console.\n"
  2105. "@ingroup Logging")
  2106. {
  2107. Con::errorf( "%s", message );
  2108. }
  2109. //-----------------------------------------------------------------------------
  2110. DefineEngineFunction( logWarning, void, ( const char* message ),,
  2111. "@brief Logs a warning message to the console.\n\n"
  2112. "@param message The message text.\n\n"
  2113. "@note By default, warnings will appear turquoise in the console.\n"
  2114. "@ingroup Logging")
  2115. {
  2116. Con::warnf( "%s", message );
  2117. }
  2118. //------------------------------------------------------------------------------
  2119. ConsoleValueToStringArrayWrapper::ConsoleValueToStringArrayWrapper(int targc, ConsoleValue *targv)
  2120. {
  2121. argv = new const char*[targc];
  2122. argc = targc;
  2123. for (S32 i = 0; i < targc; i++)
  2124. {
  2125. argv[i] = dStrdup(targv[i].getString());
  2126. }
  2127. }
  2128. ConsoleValueToStringArrayWrapper::~ConsoleValueToStringArrayWrapper()
  2129. {
  2130. for (S32 i = 0; i< argc; i++)
  2131. {
  2132. dFree(argv[i]);
  2133. }
  2134. delete[] argv;
  2135. }
  2136. StringArrayToConsoleValueWrapper::StringArrayToConsoleValueWrapper(int targc, const char** targv)
  2137. {
  2138. argv = new ConsoleValue[targc];
  2139. argc = targc;
  2140. for (int i=0; i<targc; i++)
  2141. {
  2142. argv[i].setString(targv[i]);
  2143. }
  2144. }
  2145. StringArrayToConsoleValueWrapper::~StringArrayToConsoleValueWrapper()
  2146. {
  2147. delete[] argv;
  2148. }
  2149. //------------------------------------------------------------------------------
  2150. ConsoleValue _BaseEngineConsoleCallbackHelper::_exec()
  2151. {
  2152. if( mThis )
  2153. {
  2154. // Cannot invoke callback until object has been registered
  2155. if (mThis->isProperlyAdded())
  2156. {
  2157. ConsoleValue returnValue = Con::_internalExecute( mThis, mArgc, mArgv, false );
  2158. mArgc = mInitialArgc; // reset
  2159. return std::move(returnValue);
  2160. }
  2161. STR.clearFunctionOffset();
  2162. mArgc = mInitialArgc; // reset
  2163. return std::move(ConsoleValue());
  2164. }
  2165. ConsoleValue returnValue = std::move(Con::_internalExecute( mArgc, mArgv ));
  2166. mArgc = mInitialArgc; // reset args
  2167. return std::move(returnValue);
  2168. }
  2169. ConsoleValue _BaseEngineConsoleCallbackHelper::_execLater(SimConsoleThreadExecEvent *evt)
  2170. {
  2171. mArgc = mInitialArgc; // reset args
  2172. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  2173. return std::move(evt->getCB().waitForResult());
  2174. }
  2175. //------------------------------------------------------------------------------
  2176. void ConsoleStackFrameSaver::save()
  2177. {
  2178. gCallStack.pushFrame(0);
  2179. mSaved = true;
  2180. }
  2181. void ConsoleStackFrameSaver::restore()
  2182. {
  2183. if (mSaved)
  2184. {
  2185. gCallStack.popFrame();
  2186. }
  2187. }