console.cpp 78 KB

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