console.cpp 80 KB

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