console.cpp 80 KB

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