console.cpp 77 KB

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