console.cpp 77 KB

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