console.cpp 77 KB

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