console.cpp 77 KB

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