console.cpp 80 KB

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