console.cpp 78 KB

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