console.cpp 79 KB

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