console.cpp 77 KB

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