console.cpp 79 KB

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