consoleFunctions.cpp 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  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 "console/console.h"
  24. #include "console/consoleInternal.h"
  25. #include "console/engineAPI.h"
  26. #include "console/ast.h"
  27. #ifndef _CONSOLFUNCTIONS_H_
  28. #include "console/consoleFunctions.h"
  29. #endif
  30. #include "core/strings/findMatch.h"
  31. #include "core/strings/stringUnit.h"
  32. #include "core/strings/unicode.h"
  33. #include "core/stream/fileStream.h"
  34. #include "console/compiler.h"
  35. #include "platform/platformInput.h"
  36. #include "core/util/journal/journal.h"
  37. #include "core/util/uuid.h"
  38. #ifdef TORQUE_DEMO_PURCHASE
  39. #include "gui/core/guiCanvas.h"
  40. #endif
  41. // This is a temporary hack to get tools using the library to
  42. // link in this module which contains no other references.
  43. bool LinkConsoleFunctions = false;
  44. // Buffer for expanding script filenames.
  45. static char scriptFilenameBuffer[1024];
  46. bool isInt(const char* str)
  47. {
  48. int len = dStrlen(str);
  49. if(len <= 0)
  50. return false;
  51. // Ingore whitespace
  52. int start = 0;
  53. for(int i = start; i < len; i++)
  54. if(str[i] != ' ')
  55. {
  56. start = i;
  57. break;
  58. }
  59. for(int i = start; i < len; i++)
  60. switch(str[i])
  61. {
  62. case '+': case '-':
  63. if(i != 0)
  64. return false;
  65. break;
  66. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0':
  67. break;
  68. case ' ': // ignore whitespace
  69. for(int j = i+1; j < len; j++)
  70. if(str[j] != ' ')
  71. return false;
  72. return true;
  73. break;
  74. default:
  75. return false;
  76. }
  77. return true;
  78. }
  79. bool isFloat(const char* str, bool sciOk = false)
  80. {
  81. int len = dStrlen(str);
  82. if(len <= 0)
  83. return false;
  84. // Ingore whitespace
  85. int start = 0;
  86. for(int i = start; i < len; i++)
  87. if(str[i] != ' ')
  88. {
  89. start = i;
  90. break;
  91. }
  92. bool seenDot = false;
  93. int eLoc = -1;
  94. for(int i = 0; i < len; i++)
  95. switch(str[i])
  96. {
  97. case '+': case '-':
  98. if(sciOk)
  99. {
  100. //Haven't found e or scientific notation symbol
  101. if(eLoc == -1)
  102. {
  103. //only allowed in beginning
  104. if(i != 0)
  105. return false;
  106. }
  107. else
  108. {
  109. //if not right after the e
  110. if(i != (eLoc + 1))
  111. return false;
  112. }
  113. }
  114. else
  115. {
  116. //only allowed in beginning
  117. if(i != 0)
  118. return false;
  119. }
  120. break;
  121. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0':
  122. break;
  123. case 'e': case 'E':
  124. if(!sciOk)
  125. return false;
  126. else
  127. {
  128. //already saw it so can't have 2
  129. if(eLoc != -1)
  130. return false;
  131. eLoc = i;
  132. }
  133. break;
  134. case '.':
  135. if(seenDot | (sciOk && eLoc != -1))
  136. return false;
  137. seenDot = true;
  138. break;
  139. case ' ': // ignore whitespace
  140. for(int j = i+1; j < len; j++)
  141. if(str[j] != ' ')
  142. return false;
  143. return true;
  144. break;
  145. default:
  146. return false;
  147. }
  148. return true;
  149. }
  150. bool isValidIP(const char* ip)
  151. {
  152. unsigned b1, b2, b3, b4;
  153. unsigned char c;
  154. int rc = dSscanf(ip, "%3u.%3u.%3u.%3u%c", &b1, &b2, &b3, &b4, &c);
  155. if (rc != 4 && rc != 5) return false;
  156. if ((b1 | b2 | b3 | b4) > 255) return false;
  157. if (dStrspn(ip, "0123456789.") < dStrlen(ip)) return false;
  158. return true;
  159. }
  160. bool isValidPort(U16 port)
  161. {
  162. return (port >= 0 && port <=65535);
  163. }
  164. //=============================================================================
  165. // String Functions.
  166. //=============================================================================
  167. // MARK: ---- String Functions ----
  168. //-----------------------------------------------------------------------------
  169. DefineConsoleFunction( strasc, int, ( const char* chr ),,
  170. "Return the integer character code value corresponding to the first character in the given string.\n"
  171. "@param chr a (one-character) string.\n"
  172. "@return the UTF32 code value for the first character in the given string.\n"
  173. "@ingroup Strings" )
  174. {
  175. return oneUTF8toUTF32( chr );
  176. }
  177. //-----------------------------------------------------------------------------
  178. DefineConsoleFunction( strformat, const char*, ( const char* format, const char* value ),,
  179. "Format the given value as a string using printf-style formatting.\n"
  180. "@param format A printf-style format string.\n"
  181. "@param value The value argument matching the given format string.\n\n"
  182. "@tsexample\n"
  183. "// Convert the given integer value to a string in a hex notation.\n"
  184. "%hex = strformat( \"%x\", %value );\n"
  185. "@endtsexample\n"
  186. "@ingroup Strings\n"
  187. "@see http://en.wikipedia.org/wiki/Printf" )
  188. {
  189. static const U32 bufSize = 64;
  190. char* pBuffer = Con::getReturnBuffer(bufSize);
  191. const char *pch = format;
  192. pBuffer[0] = '\0';
  193. while (*pch != '\0' && *pch !='%')
  194. pch++;
  195. while (*pch != '\0' && !dIsalpha(*pch))
  196. pch++;
  197. if (*pch == '\0')
  198. {
  199. Con::errorf("strFormat: Invalid format string!\n");
  200. return pBuffer;
  201. }
  202. switch(*pch)
  203. {
  204. case 'c':
  205. case 'C':
  206. case 'd':
  207. case 'i':
  208. case 'o':
  209. case 'u':
  210. case 'x':
  211. case 'X':
  212. dSprintf( pBuffer, bufSize, format, dAtoi( value ) );
  213. break;
  214. case 'e':
  215. case 'E':
  216. case 'f':
  217. case 'g':
  218. case 'G':
  219. dSprintf( pBuffer, bufSize, format, dAtof( value ) );
  220. break;
  221. default:
  222. Con::errorf("strFormat: Invalid format string!\n");
  223. break;
  224. }
  225. return pBuffer;
  226. }
  227. //-----------------------------------------------------------------------------
  228. DefineConsoleFunction( strcmp, S32, ( const char* str1, const char* str2 ),,
  229. "Compares two strings using case-<b>sensitive</b> comparison.\n"
  230. "@param str1 The first string.\n"
  231. "@param str2 The second string.\n"
  232. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  233. "value than the character at the same position in str2, and a value >1 otherwise.\n\n"
  234. "@tsexample\n"
  235. "if( strcmp( %var, \"foobar\" ) == 0 )\n"
  236. " echo( \"%var is equal to 'foobar'\" );\n"
  237. "@endtsexample\n"
  238. "@see stricmp\n"
  239. "@see strnatcmp\n"
  240. "@ingroup Strings" )
  241. {
  242. return dStrcmp( str1, str2 );
  243. }
  244. //-----------------------------------------------------------------------------
  245. DefineConsoleFunction( stricmp, S32, ( const char* str1, const char* str2 ),,
  246. "Compares two strings using case-<b>insensitive</b> comparison.\n"
  247. "@param str1 The first string.\n"
  248. "@param str2 The second string.\n"
  249. "@return 0 if both strings are equal, a value <0 if the first character different in str1 has a smaller character code "
  250. "value than the character at the same position in str2, and a value >0 otherwise.\n\n"
  251. "@tsexample\n"
  252. "if( stricmp( \"FOObar\", \"foobar\" ) == 0 )\n"
  253. " echo( \"this is always true\" );\n"
  254. "@endtsexample\n"
  255. "@see strcmp\n"
  256. "@see strinatcmp\n"
  257. "@ingroup Strings" )
  258. {
  259. return dStricmp( str1, str2 );
  260. }
  261. //-----------------------------------------------------------------------------
  262. DefineConsoleFunction( strnatcmp, S32, ( const char* str1, const char* str2 ),,
  263. "Compares two strings using \"natural order\" case-<b>sensitive</b> comparison.\n"
  264. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  265. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  266. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  267. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  268. "@param str1 The first string.\n"
  269. "@param str2 The second string.\n\n"
  270. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  271. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  272. "@tsexample\n"
  273. "// Bubble sort 10 elements of %array using natural order\n"
  274. "do\n"
  275. "{\n"
  276. " %swapped = false;\n"
  277. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  278. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  279. " {\n"
  280. " %temp = %array[ %i ];\n"
  281. " %array[ %i ] = %array[ %i + 1 ];\n"
  282. " %array[ %i + 1 ] = %temp;\n"
  283. " %swapped = true;\n"
  284. " }\n"
  285. "}\n"
  286. "while( %swapped );\n"
  287. "@endtsexample\n"
  288. "@see strcmp\n"
  289. "@see strinatcmp\n"
  290. "@ingroup Strings" )
  291. {
  292. return dStrnatcmp( str1, str2 );
  293. }
  294. //-----------------------------------------------------------------------------
  295. DefineConsoleFunction( strinatcmp, S32, ( const char* str1, const char* str2 ),,
  296. "Compares two strings using \"natural order\" case-<b>insensitive</b> comparison.\n"
  297. "Natural order means that rather than solely comparing single character code values, strings are ordered in a "
  298. "natural way. For example, the string \"hello10\" is considered greater than the string \"hello2\" even though "
  299. "the first numeric character in \"hello10\" actually has a smaller character value than the corresponding character "
  300. "in \"hello2\". However, since 10 is greater than 2, strnatcmp will put \"hello10\" after \"hello2\".\n"
  301. "@param str1 The first string.\n"
  302. "@param str2 The second string.\n"
  303. "@return 0 if the strings are equal, a value >0 if @a str1 comes after @a str2 in a natural order, and a value "
  304. "<0 if @a str1 comes before @a str2 in a natural order.\n\n"
  305. "@tsexample\n\n"
  306. "// Bubble sort 10 elements of %array using natural order\n"
  307. "do\n"
  308. "{\n"
  309. " %swapped = false;\n"
  310. " for( %i = 0; %i < 10 - 1; %i ++ )\n"
  311. " if( strnatcmp( %array[ %i ], %array[ %i + 1 ] ) > 0 )\n"
  312. " {\n"
  313. " %temp = %array[ %i ];\n"
  314. " %array[ %i ] = %array[ %i + 1 ];\n"
  315. " %array[ %i + 1 ] = %temp;\n"
  316. " %swapped = true;\n"
  317. " }\n"
  318. "}\n"
  319. "while( %swapped );\n"
  320. "@endtsexample\n"
  321. "@see stricmp\n"
  322. "@see strnatcmp\n"
  323. "@ingroup Strings" )
  324. {
  325. return dStrnatcasecmp( str1, str2 );
  326. }
  327. //-----------------------------------------------------------------------------
  328. DefineConsoleFunction( strlen, S32, ( const char* str ),,
  329. "Get the length of the given string in bytes.\n"
  330. "@note This does <b>not</b> return a true character count for strings with multi-byte characters!\n"
  331. "@param str A string.\n"
  332. "@return The length of the given string in bytes.\n"
  333. "@ingroup Strings" )
  334. {
  335. return dStrlen( str );
  336. }
  337. //-----------------------------------------------------------------------------
  338. DefineConsoleFunction( strstr, S32, ( const char* string, const char* substring ),,
  339. "Find the start of @a substring in the given @a string searching from left to right.\n"
  340. "@param string The string to search.\n"
  341. "@param substring The string to search for.\n"
  342. "@return The index into @a string at which the first occurrence of @a substring was found or -1 if @a substring could not be found.\n\n"
  343. "@tsexample\n"
  344. "strstr( \"abcd\", \"c\" ) // Returns 2.\n"
  345. "@endtsexample\n"
  346. "@ingroup Strings" )
  347. {
  348. const char* retpos = dStrstr( string, substring );
  349. if( !retpos )
  350. return -1;
  351. return retpos - string;
  352. }
  353. //-----------------------------------------------------------------------------
  354. DefineConsoleFunction( strpos, S32, ( const char* haystack, const char* needle, S32 offset ), ( 0 ),
  355. "Find the start of @a needle in @a haystack searching from left to right beginning at the given offset.\n"
  356. "@param haystack The string to search.\n"
  357. "@param needle The string to search for.\n"
  358. "@return The index at which the first occurrence of @a needle was found in @a haystack or -1 if no match was found.\n\n"
  359. "@tsexample\n"
  360. "strpos( \"b ab\", \"b\", 1 ) // Returns 3.\n"
  361. "@endtsexample\n"
  362. "@ingroup Strings" )
  363. {
  364. S32 start = offset;
  365. U32 sublen = dStrlen( needle );
  366. U32 strlen = dStrlen( haystack );
  367. if(start < 0)
  368. return -1;
  369. if(sublen + start > strlen)
  370. return -1;
  371. for(; start + sublen <= strlen; start++)
  372. if(!dStrncmp(haystack + start, needle, sublen))
  373. return start;
  374. return -1;
  375. }
  376. //-----------------------------------------------------------------------------
  377. DefineConsoleFunction( ltrim, const char*, ( const char* str ),,
  378. "Remove leading whitespace from the string.\n"
  379. "@param str A string.\n"
  380. "@return A string that is the same as @a str but with any leading (i.e. leftmost) whitespace removed.\n\n"
  381. "@tsexample\n"
  382. "ltrim( \" string \" ); // Returns \"string \".\n"
  383. "@endtsexample\n"
  384. "@see rtrim\n"
  385. "@see trim\n"
  386. "@ingroup Strings" )
  387. {
  388. const char *ret = str;
  389. while(*ret == ' ' || *ret == '\n' || *ret == '\t')
  390. ret++;
  391. return ret;
  392. }
  393. //-----------------------------------------------------------------------------
  394. DefineConsoleFunction( rtrim, const char*, ( const char* str ),,
  395. "Remove trailing whitespace from the string.\n"
  396. "@param str A string.\n"
  397. "@return A string that is the same as @a str but with any trailing (i.e. rightmost) whitespace removed.\n\n"
  398. "@tsexample\n"
  399. "rtrim( \" string \" ); // Returns \" string\".\n"
  400. "@endtsexample\n"
  401. "@see ltrim\n"
  402. "@see trim\n"
  403. "@ingroup Strings" )
  404. {
  405. S32 firstWhitespace = 0;
  406. S32 pos = 0;
  407. while(str[pos])
  408. {
  409. if(str[pos] != ' ' && str[pos] != '\n' && str[pos] != '\t')
  410. firstWhitespace = pos + 1;
  411. pos++;
  412. }
  413. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  414. dStrncpy(ret, str, firstWhitespace);
  415. ret[firstWhitespace] = 0;
  416. return ret;
  417. }
  418. //-----------------------------------------------------------------------------
  419. DefineConsoleFunction( trim, const char*, ( const char* str ),,
  420. "Remove leading and trailing whitespace from the string.\n"
  421. "@param str A string.\n"
  422. "@return A string that is the same as @a str but with any leading (i.e. leftmost) and trailing (i.e. rightmost) whitespace removed.\n\n"
  423. "@tsexample\n"
  424. "trim( \" string \" ); // Returns \"string\".\n"
  425. "@endtsexample\n"
  426. "@ingroup Strings" )
  427. {
  428. const char *ptr = str;
  429. while(*ptr == ' ' || *ptr == '\n' || *ptr == '\t')
  430. ptr++;
  431. S32 firstWhitespace = 0;
  432. S32 pos = 0;
  433. while(ptr[pos])
  434. {
  435. if(ptr[pos] != ' ' && ptr[pos] != '\n' && ptr[pos] != '\t')
  436. firstWhitespace = pos + 1;
  437. pos++;
  438. }
  439. char *ret = Con::getReturnBuffer(firstWhitespace + 1);
  440. dStrncpy(ret, ptr, firstWhitespace);
  441. ret[firstWhitespace] = 0;
  442. return ret;
  443. }
  444. //-----------------------------------------------------------------------------
  445. DefineConsoleFunction( stripChars, const char*, ( const char* str, const char* chars ),,
  446. "Remove all occurrences of characters contained in @a chars from @a str.\n"
  447. "@param str The string to filter characters out from.\n"
  448. "@param chars A string of characters to filter out from @a str.\n"
  449. "@return A version of @a str with all occurrences of characters contained in @a chars filtered out.\n\n"
  450. "@tsexample\n"
  451. "stripChars( \"teststring\", \"se\" ); // Returns \"tttring\"."
  452. "@endtsexample\n"
  453. "@ingroup Strings" )
  454. {
  455. char* ret = Con::getReturnBuffer( dStrlen( str ) + 1 );
  456. dStrcpy( ret, str );
  457. U32 pos = dStrcspn( ret, chars );
  458. while ( pos < dStrlen( ret ) )
  459. {
  460. dStrcpy( ret + pos, ret + pos + 1 );
  461. pos = dStrcspn( ret, chars );
  462. }
  463. return( ret );
  464. }
  465. //-----------------------------------------------------------------------------
  466. DefineConsoleFunction( strlwr, const char*, ( const char* str ),,
  467. "Return an all lower-case version of the given string.\n"
  468. "@param str A string.\n"
  469. "@return A version of @a str with all characters converted to lower-case.\n\n"
  470. "@tsexample\n"
  471. "strlwr( \"TesT1\" ) // Returns \"test1\"\n"
  472. "@endtsexample\n"
  473. "@see strupr\n"
  474. "@ingroup Strings" )
  475. {
  476. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  477. dStrcpy(ret, str);
  478. return dStrlwr(ret);
  479. }
  480. //-----------------------------------------------------------------------------
  481. DefineConsoleFunction( strupr, const char*, ( const char* str ),,
  482. "Return an all upper-case version of the given string.\n"
  483. "@param str A string.\n"
  484. "@return A version of @a str with all characters converted to upper-case.\n\n"
  485. "@tsexample\n"
  486. "strupr( \"TesT1\" ) // Returns \"TEST1\"\n"
  487. "@endtsexample\n"
  488. "@see strlwr\n"
  489. "@ingroup Strings" )
  490. {
  491. char *ret = Con::getReturnBuffer(dStrlen(str) + 1);
  492. dStrcpy(ret, str);
  493. return dStrupr(ret);
  494. }
  495. //-----------------------------------------------------------------------------
  496. DefineConsoleFunction( strchr, const char*, ( const char* str, const char* chr ),,
  497. "Find the first occurrence of the given character in @a str.\n"
  498. "@param str The string to search.\n"
  499. "@param chr The character to search for. Only the first character from the string is taken.\n"
  500. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  501. "@see strrchr\n"
  502. "@ingroup Strings" )
  503. {
  504. const char *ret = dStrchr( str, chr[ 0 ] );
  505. return ret ? ret : "";
  506. }
  507. //-----------------------------------------------------------------------------
  508. DefineConsoleFunction( strrchr, const char*, ( const char* str, const char* chr ),,
  509. "Find the last occurrence of the given character in @a str."
  510. "@param str The string to search.\n"
  511. "@param chr The character to search for. Only the first character from the string is taken.\n"
  512. "@return The remainder of the input string starting with the given character or the empty string if the character could not be found.\n\n"
  513. "@see strchr\n"
  514. "@ingroup Strings" )
  515. {
  516. const char *ret = dStrrchr( str, chr[ 0 ] );
  517. return ret ? ret : "";
  518. }
  519. //-----------------------------------------------------------------------------
  520. DefineConsoleFunction( strreplace, const char*, ( const char* source, const char* from, const char* to ),,
  521. "Replace all occurrences of @a from in @a source with @a to.\n"
  522. "@param source The string in which to replace the occurrences of @a from.\n"
  523. "@param from The string to replace in @a source.\n"
  524. "@param to The string with which to replace occurrences of @from.\n"
  525. "@return A string with all occurrences of @a from in @a source replaced by @a to.\n\n"
  526. "@tsexample\n"
  527. "strreplace( \"aabbccbb\", \"bb\", \"ee\" ) // Returns \"aaeeccee\".\n"
  528. "@endtsexample\n"
  529. "@ingroup Strings" )
  530. {
  531. S32 fromLen = dStrlen( from );
  532. if(!fromLen)
  533. return source;
  534. S32 toLen = dStrlen( to );
  535. S32 count = 0;
  536. const char *scan = source;
  537. while(scan)
  538. {
  539. scan = dStrstr(scan, from);
  540. if(scan)
  541. {
  542. scan += fromLen;
  543. count++;
  544. }
  545. }
  546. char *ret = Con::getReturnBuffer(dStrlen(source) + 1 + (toLen - fromLen) * count);
  547. U32 scanp = 0;
  548. U32 dstp = 0;
  549. for(;;)
  550. {
  551. const char *scan = dStrstr(source + scanp, from);
  552. if(!scan)
  553. {
  554. dStrcpy(ret + dstp, source + scanp);
  555. break;
  556. }
  557. U32 len = scan - (source + scanp);
  558. dStrncpy(ret + dstp, source + scanp, len);
  559. dstp += len;
  560. dStrcpy(ret + dstp, to);
  561. dstp += toLen;
  562. scanp += len + fromLen;
  563. }
  564. return ret;
  565. }
  566. //-----------------------------------------------------------------------------
  567. DefineConsoleFunction( strrepeat, const char*, ( const char* str, S32 numTimes, const char* delimiter ), ( "" ),
  568. "Return a string that repeats @a str @a numTimes number of times delimiting each occurrence with @a delimiter.\n"
  569. "@param str The string to repeat multiple times.\n"
  570. "@param numTimes The number of times to repeat @a str in the result string.\n"
  571. "@param delimiter The string to put between each repetition of @a str.\n"
  572. "@return A string containing @a str repeated @a numTimes times.\n\n"
  573. "@tsexample\n"
  574. "strrepeat( \"a\", 5, \"b\" ) // Returns \"ababababa\".\n"
  575. "@endtsexample\n"
  576. "@ingroup Strings" )
  577. {
  578. StringBuilder result;
  579. bool isFirst = false;
  580. for( U32 i = 0; i < numTimes; ++ i )
  581. {
  582. if( !isFirst )
  583. result.append( delimiter );
  584. result.append( str );
  585. isFirst = false;
  586. }
  587. return Con::getReturnBuffer( result );
  588. }
  589. //-----------------------------------------------------------------------------
  590. DefineConsoleFunction( getSubStr, const char*, ( const char* str, S32 start, S32 numChars ), ( -1 ),
  591. "@brief Return a substring of @a str starting at @a start and continuing either through to the end of @a str "
  592. "(if @a numChars is -1) or for @a numChars characters (except if this would exceed the actual source "
  593. "string length).\n"
  594. "@param str The string from which to extract a substring.\n"
  595. "@param start The offset at which to start copying out characters.\n"
  596. "@param numChars Optional argument to specify the number of characters to copy. If this is -1, all characters up the end "
  597. "of the input string are copied.\n"
  598. "@return A string that contains the given portion of the input string.\n\n"
  599. "@tsexample\n"
  600. "getSubStr( \"foobar\", 1, 2 ) // Returns \"oo\".\n"
  601. "@endtsexample\n\n"
  602. "@ingroup Strings" )
  603. {
  604. S32 baseLen = dStrlen( str );
  605. if( numChars == -1 )
  606. numChars = baseLen - start;
  607. if (start < 0 || numChars < 0) {
  608. Con::errorf(ConsoleLogEntry::Script, "getSubStr(...): error, starting position and desired length must be >= 0: (%d, %d)", start, numChars);
  609. return "";
  610. }
  611. if (baseLen < start)
  612. return "";
  613. U32 actualLen = numChars;
  614. if (start + numChars > baseLen)
  615. actualLen = baseLen - start;
  616. char *ret = Con::getReturnBuffer(actualLen + 1);
  617. dStrncpy(ret, str + start, actualLen);
  618. ret[actualLen] = '\0';
  619. return ret;
  620. }
  621. //-----------------------------------------------------------------------------
  622. DefineConsoleFunction( strIsMatchExpr, bool, ( const char* pattern, const char* str, bool caseSensitive ), ( false ),
  623. "Match a pattern against a string.\n"
  624. "@param pattern The wildcard pattern to match against. The pattern can include characters, '*' to match "
  625. "any number of characters and '?' to match a single character.\n"
  626. "@param str The string which should be matched against @a pattern.\n"
  627. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  628. "this string. If false, differences in casing are ignored.\n"
  629. "@return True if @a str matches the given @a pattern.\n\n"
  630. "@tsexample\n"
  631. "strIsMatchExpr( \"f?o*R\", \"foobar\" ) // Returns true.\n"
  632. "@endtsexample\n"
  633. "@see strIsMatchMultipleExpr\n"
  634. "@ingroup Strings" )
  635. {
  636. return FindMatch::isMatch( pattern, str, caseSensitive );
  637. }
  638. //-----------------------------------------------------------------------------
  639. DefineConsoleFunction( strIsMatchMultipleExpr, bool, ( const char* patterns, const char* str, bool caseSensitive ), ( false ),
  640. "Match a multiple patterns against a single string.\n"
  641. "@param patterns A tab-separated list of patterns. Each pattern can include charaters, '*' to match "
  642. "any number of characters and '?' to match a single character. Each of the patterns is tried in turn.\n"
  643. "@param str The string which should be matched against @a patterns.\n"
  644. "@param caseSensitive If true, characters in the pattern are matched in case-sensitive fashion against "
  645. "this string. If false, differences in casing are ignored.\n"
  646. "@return True if @a str matches any of the given @a patterns.\n\n"
  647. "@tsexample\n"
  648. "strIsMatchMultipleExpr( \"*.cs *.gui *.mis\", \"mymission.mis\" ) // Returns true.\n"
  649. "@endtsexample\n"
  650. "@see strIsMatchExpr\n"
  651. "@ingroup Strings" )
  652. {
  653. return FindMatch::isMatchMultipleExprs( patterns, str, caseSensitive );
  654. }
  655. //-----------------------------------------------------------------------------
  656. DefineConsoleFunction( getTrailingNumber, S32, ( const char* str ),,
  657. "Get the numeric suffix of the given input string.\n"
  658. "@param str The string from which to read out the numeric suffix.\n"
  659. "@return The numeric value of the number suffix of @a str or -1 if @a str has no such suffix.\n\n"
  660. "@tsexample\n"
  661. "getTrailingNumber( \"test123\" ) // Returns '123'.\n"
  662. "@endtsexample\n\n"
  663. "@see stripTrailingNumber\n"
  664. "@ingroup Strings" )
  665. {
  666. S32 suffix = -1;
  667. String outStr( String::GetTrailingNumber( str, suffix ) );
  668. return suffix;
  669. }
  670. //-----------------------------------------------------------------------------
  671. DefineConsoleFunction( stripTrailingNumber, String, ( const char* str ),,
  672. "Strip a numeric suffix from the given string.\n"
  673. "@param str The string from which to strip its numeric suffix.\n"
  674. "@return The string @a str without its number suffix or the original string @a str if it has no such suffix.\n\n"
  675. "@tsexample\n"
  676. "stripTrailingNumber( \"test123\" ) // Returns \"test\".\n"
  677. "@endtsexample\n\n"
  678. "@see getTrailingNumber\n"
  679. "@ingroup Strings" )
  680. {
  681. S32 suffix;
  682. return String::GetTrailingNumber( str, suffix );
  683. }
  684. //----------------------------------------------------------------
  685. DefineConsoleFunction( isspace, bool, ( const char* str, S32 index ),,
  686. "Test whether the character at the given position is a whitespace character.\n"
  687. "Characters such as tab, space, or newline are considered whitespace.\n"
  688. "@param str The string to test.\n"
  689. "@param index The index of a character in @a str.\n"
  690. "@return True if the character at the given index in @a str is a whitespace character; false otherwise.\n\n"
  691. "@see isalnum\n"
  692. "@ingroup Strings" )
  693. {
  694. if( index >= 0 && index < dStrlen( str ) )
  695. return dIsspace( str[ index ] );
  696. else
  697. return false;
  698. }
  699. //----------------------------------------------------------------
  700. DefineConsoleFunction( isalnum, bool, ( const char* str, S32 index ),,
  701. "Test whether the character at the given position is an alpha-numeric character.\n"
  702. "Alpha-numeric characters are characters that are either alphabetic (a-z, A-Z) or numbers (0-9).\n"
  703. "@param str The string to test.\n"
  704. "@param index The index of a character in @a str.\n"
  705. "@return True if the character at the given index in @a str is an alpha-numeric character; false otherwise.\n\n"
  706. "@see isspace\n"
  707. "@ingroup Strings" )
  708. {
  709. if( index >= 0 && index < dStrlen( str ) )
  710. return dIsalnum( str[ index ] );
  711. else
  712. return false;
  713. }
  714. //----------------------------------------------------------------
  715. DefineConsoleFunction( startsWith, bool, ( const char* str, const char* prefix, bool caseSensitive ), ( false ),
  716. "Test whether the given string begins with the given prefix.\n"
  717. "@param str The string to test.\n"
  718. "@param prefix The potential prefix of @a str.\n"
  719. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  720. "not be taken into account.\n"
  721. "@return True if the first characters in @a str match the complete contents of @a prefix; false otherwise.\n\n"
  722. "@tsexample\n"
  723. "startsWith( \"TEST123\", \"test\" ) // Returns true.\n"
  724. "@endtsexample\n"
  725. "@see endsWith\n"
  726. "@ingroup Strings" )
  727. {
  728. // if the target string is empty, return true (all strings start with the empty string)
  729. S32 srcLen = dStrlen( str );
  730. S32 targetLen = dStrlen( prefix );
  731. if( targetLen == 0 )
  732. return true;
  733. // else if the src string is empty, return false (empty src does not start with non-empty target)
  734. else if( srcLen == 0 )
  735. return false;
  736. if( caseSensitive )
  737. return ( dStrncmp( str, prefix, targetLen ) == 0 );
  738. // both src and target are non empty, create temp buffers for lowercase operation
  739. char* srcBuf = new char[ srcLen + 1 ];
  740. char* targetBuf = new char[ targetLen + 1 ];
  741. // copy src and target into buffers
  742. dStrcpy( srcBuf, str );
  743. dStrcpy( targetBuf, prefix );
  744. // reassign src/target pointers to lowercase versions
  745. str = dStrlwr( srcBuf );
  746. prefix = dStrlwr( targetBuf );
  747. // do the comparison
  748. bool startsWith = dStrncmp( str, prefix, targetLen ) == 0;
  749. // delete temp buffers
  750. delete [] srcBuf;
  751. delete [] targetBuf;
  752. return startsWith;
  753. }
  754. //----------------------------------------------------------------
  755. DefineConsoleFunction( endsWith, bool, ( const char* str, const char* suffix, bool caseSensitive ), ( false ),
  756. "@brief Test whether the given string ends with the given suffix.\n\n"
  757. "@param str The string to test.\n"
  758. "@param suffix The potential suffix of @a str.\n"
  759. "@param caseSensitive If true, the comparison will be case-sensitive; if false, differences in casing will "
  760. "not be taken into account.\n"
  761. "@return True if the last characters in @a str match the complete contents of @a suffix; false otherwise.\n\n"
  762. "@tsexample\n"
  763. "startsWith( \"TEST123\", \"123\" ) // Returns true.\n"
  764. "@endtsexample\n\n"
  765. "@see startsWith\n"
  766. "@ingroup Strings" )
  767. {
  768. // if the target string is empty, return true (all strings end with the empty string)
  769. S32 srcLen = dStrlen( str );
  770. S32 targetLen = dStrlen( suffix );
  771. if (targetLen == 0)
  772. return true;
  773. // else if the src string is empty, return false (empty src does not end with non-empty target)
  774. else if (srcLen == 0)
  775. return false;
  776. else if( targetLen > srcLen )
  777. return false;
  778. if( caseSensitive )
  779. return ( dStrcmp( &str[ srcLen - targetLen ], suffix ) == 0 );
  780. // both src and target are non empty, create temp buffers for lowercase operation
  781. char* srcBuf = new char[ srcLen + 1 ];
  782. char* targetBuf = new char[ targetLen + 1 ];
  783. // copy src and target into buffers
  784. dStrcpy( srcBuf, str );
  785. dStrcpy( targetBuf, suffix );
  786. // reassign src/target pointers to lowercase versions
  787. str = dStrlwr( srcBuf );
  788. suffix = dStrlwr( targetBuf );
  789. // set the src pointer to the appropriate place to check the end of the string
  790. str += srcLen - targetLen;
  791. // do the comparison
  792. bool endsWith = dStrcmp( str, suffix ) == 0;
  793. // delete temp buffers
  794. delete [] srcBuf;
  795. delete [] targetBuf;
  796. return endsWith;
  797. }
  798. //----------------------------------------------------------------
  799. DefineConsoleFunction( strchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  800. "Find the first occurrence of the given character in the given string.\n"
  801. "@param str The string to search.\n"
  802. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  803. "@param start The index into @a str at which to start searching for the given character.\n"
  804. "@return The index of the first occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  805. "@tsexample\n"
  806. "strchrpos( \"test\", \"s\" ) // Returns 2.\n"
  807. "@endtsexample\n"
  808. "@ingroup Strings" )
  809. {
  810. if( start != 0 && start >= dStrlen( str ) )
  811. return -1;
  812. const char* ret = dStrchr( &str[ start ], chr[ 0 ] );
  813. return ret ? ret - str : -1;
  814. }
  815. //----------------------------------------------------------------
  816. DefineConsoleFunction( strrchrpos, S32, ( const char* str, const char* chr, S32 start ), ( 0 ),
  817. "Find the last occurrence of the given character in the given string.\n"
  818. "@param str The string to search.\n"
  819. "@param chr The character to look for. Only the first character of this string will be searched for.\n"
  820. "@param start The index into @a str at which to start searching for the given character.\n"
  821. "@return The index of the last occurrence of @a chr in @a str or -1 if @a str does not contain the given character.\n\n"
  822. "@tsexample\n"
  823. "strrchrpos( \"test\", \"t\" ) // Returns 3.\n"
  824. "@endtsexample\n"
  825. "@ingroup Strings" )
  826. {
  827. if( start != 0 && start >= dStrlen( str ) )
  828. return -1;
  829. const char* ret = dStrrchr( str, chr[ 0 ] );
  830. if( !ret )
  831. return -1;
  832. S32 index = ret - str;
  833. if( index < start )
  834. return -1;
  835. return index;
  836. }
  837. //----------------------------------------------------------------
  838. // Warning: isInt and isFloat are very 'strict' and might need to be adjusted to allow other values. //seanmc
  839. DefineConsoleFunction( isInt, bool, ( const char* str),,
  840. "Returns true if the string is an integer.\n"
  841. "@param str The string to test.\n"
  842. "@return true if @a str is an integer and false if not\n\n"
  843. "@tsexample\n"
  844. "isInt( \"13\" ) // Returns true.\n"
  845. "@endtsexample\n"
  846. "@ingroup Strings" )
  847. {
  848. return isInt(str);
  849. }
  850. //----------------------------------------------------------------
  851. DefineConsoleFunction( isFloat, bool, ( const char* str, bool sciOk), (false),
  852. "Returns true if the string is a float.\n"
  853. "@param str The string to test.\n"
  854. "@param sciOk Test for correct scientific notation and accept it (ex. 1.2e+14)"
  855. "@return true if @a str is a float and false if not\n\n"
  856. "@tsexample\n"
  857. "isFloat( \"13.5\" ) // Returns true.\n"
  858. "@endtsexample\n"
  859. "@ingroup Strings" )
  860. {
  861. return isFloat(str, sciOk);
  862. }
  863. //----------------------------------------------------------------
  864. DefineConsoleFunction( isValidPort, bool, ( const char* str),,
  865. "Returns true if the string is a valid port number.\n"
  866. "@param str The string to test.\n"
  867. "@return true if @a str is a port and false if not\n\n"
  868. "@tsexample\n"
  869. "isValidPort( \"8080\" ) // Returns true.\n"
  870. "@endtsexample\n"
  871. "@ingroup Strings" )
  872. {
  873. if(isInt(str))
  874. {
  875. U16 port = dAtous(str);
  876. return isValidPort(port);
  877. }
  878. else
  879. return false;
  880. }
  881. //----------------------------------------------------------------
  882. DefineConsoleFunction( isValidIP, bool, ( const char* str),,
  883. "Returns true if the string is a valid ip address, excepts localhost.\n"
  884. "@param str The string to test.\n"
  885. "@return true if @a str is a valid ip address and false if not\n\n"
  886. "@tsexample\n"
  887. "isValidIP( \"localhost\" ) // Returns true.\n"
  888. "@endtsexample\n"
  889. "@ingroup Strings" )
  890. {
  891. if(dStrcmp(str, "localhost") == 0)
  892. {
  893. return true;
  894. }
  895. else
  896. return isValidIP(str);
  897. }
  898. //=============================================================================
  899. // Field Manipulators.
  900. //=============================================================================
  901. // MARK: ---- Field Manipulators ----
  902. //-----------------------------------------------------------------------------
  903. DefineConsoleFunction( getWord, const char*, ( const char* text, S32 index ),,
  904. "Extract the word at the given @a index in the whitespace-separated list in @a text.\n"
  905. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  906. "@param text A whitespace-separated list of words.\n"
  907. "@param index The zero-based index of the word to extract.\n"
  908. "@return The word at the given index or \"\" if the index is out of range.\n\n"
  909. "@tsexample\n"
  910. "getWord( \"a b c\", 1 ) // Returns \"b\"\n"
  911. "@endtsexample\n\n"
  912. "@see getWords\n"
  913. "@see getWordCount\n"
  914. "@see getField\n"
  915. "@see getRecord\n"
  916. "@ingroup FieldManip" )
  917. {
  918. return Con::getReturnBuffer( StringUnit::getUnit( text, index, " \t\n") );
  919. }
  920. //-----------------------------------------------------------------------------
  921. DefineConsoleFunction( getWords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  922. "Extract a range of words from the given @a startIndex onwards thru @a endIndex.\n"
  923. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  924. "@param text A whitespace-separated list of words.\n"
  925. "@param startIndex The zero-based index of the first word to extract from @a text.\n"
  926. "@param endIndex The zero-based index of the last word to extract from @a text. If this is -1, all words beginning "
  927. "with @a startIndex are extracted from @a text.\n"
  928. "@return A string containing the specified range of words from @a text or \"\" if @a startIndex "
  929. "is out of range or greater than @a endIndex.\n\n"
  930. "@tsexample\n"
  931. "getWords( \"a b c d\", 1, 2, ) // Returns \"b c\"\n"
  932. "@endtsexample\n\n"
  933. "@see getWord\n"
  934. "@see getWordCount\n"
  935. "@see getFields\n"
  936. "@see getRecords\n"
  937. "@ingroup FieldManip" )
  938. {
  939. if( endIndex < 0 )
  940. endIndex = 1000000;
  941. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, " \t\n" ) );
  942. }
  943. //-----------------------------------------------------------------------------
  944. DefineConsoleFunction( setWord, const char*, ( const char* text, S32 index, const char* replacement ),,
  945. "Replace the word in @a text at the given @a index with @a replacement.\n"
  946. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  947. "@param text A whitespace-separated list of words.\n"
  948. "@param index The zero-based index of the word to replace.\n"
  949. "@param replacement The string with which to replace the word.\n"
  950. "@return A new string with the word at the given @a index replaced by @a replacement or the original "
  951. "string if @a index is out of range.\n\n"
  952. "@tsexample\n"
  953. "setWord( \"a b c d\", 2, \"f\" ) // Returns \"a b f d\"\n"
  954. "@endtsexample\n\n"
  955. "@see getWord\n"
  956. "@see setField\n"
  957. "@see setRecord\n"
  958. "@ingroup FieldManip" )
  959. {
  960. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, " \t\n") );
  961. }
  962. //-----------------------------------------------------------------------------
  963. DefineConsoleFunction( removeWord, const char*, ( const char* text, S32 index ),,
  964. "Remove the word in @a text at the given @a index.\n"
  965. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  966. "@param text A whitespace-separated list of words.\n"
  967. "@param index The zero-based index of the word in @a text.\n"
  968. "@return A new string with the word at the given index removed or the original string if @a index is "
  969. "out of range.\n\n"
  970. "@tsexample\n"
  971. "removeWord( \"a b c d\", 2 ) // Returns \"a b d\"\n"
  972. "@endtsexample\n\n"
  973. "@see removeField\n"
  974. "@see removeRecord\n"
  975. "@ingroup FieldManip" )
  976. {
  977. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, " \t\n" ) );
  978. }
  979. //-----------------------------------------------------------------------------
  980. DefineConsoleFunction( getWordCount, S32, ( const char* text ),,
  981. "Return the number of whitespace-separated words in @a text.\n"
  982. "Words in @a text must be separated by newlines, spaces, and/or tabs.\n"
  983. "@param text A whitespace-separated list of words.\n"
  984. "@return The number of whitespace-separated words in @a text.\n\n"
  985. "@tsexample\n"
  986. "getWordCount( \"a b c d e\" ) // Returns 5\n"
  987. "@endtsexample\n\n"
  988. "@see getFieldCount\n"
  989. "@see getRecordCount\n"
  990. "@ingroup FieldManip" )
  991. {
  992. return StringUnit::getUnitCount( text, " \t\n" );
  993. }
  994. //-----------------------------------------------------------------------------
  995. DefineConsoleFunction( getField, const char*, ( const char* text, S32 index ),,
  996. "Extract the field at the given @a index in the newline and/or tab separated list in @a text.\n"
  997. "Fields in @a text must be separated by newlines and/or tabs.\n"
  998. "@param text A list of fields separated by newlines and/or tabs.\n"
  999. "@param index The zero-based index of the field to extract.\n"
  1000. "@return The field at the given index or \"\" if the index is out of range.\n\n"
  1001. "@tsexample\n"
  1002. "getField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\"\n"
  1003. "@endtsexample\n\n"
  1004. "@see getFields\n"
  1005. "@see getFieldCount\n"
  1006. "@see getWord\n"
  1007. "@see getRecord\n"
  1008. "@ingroup FieldManip" )
  1009. {
  1010. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\t\n" ) );
  1011. }
  1012. //-----------------------------------------------------------------------------
  1013. DefineConsoleFunction( getFields, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  1014. "Extract a range of fields from the given @a startIndex onwards thru @a endIndex.\n"
  1015. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1016. "@param text A list of fields separated by newlines and/or tabs.\n"
  1017. "@param startIndex The zero-based index of the first field to extract from @a text.\n"
  1018. "@param endIndex The zero-based index of the last field to extract from @a text. If this is -1, all fields beginning "
  1019. "with @a startIndex are extracted from @a text.\n"
  1020. "@return A string containing the specified range of fields from @a text or \"\" if @a startIndex "
  1021. "is out of range or greater than @a endIndex.\n\n"
  1022. "@tsexample\n"
  1023. "getFields( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"c d\" TAB \"e f\"\n"
  1024. "@endtsexample\n\n"
  1025. "@see getField\n"
  1026. "@see getFieldCount\n"
  1027. "@see getWords\n"
  1028. "@see getRecords\n"
  1029. "@ingroup FieldManip" )
  1030. {
  1031. if( endIndex < 0 )
  1032. endIndex = 1000000;
  1033. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\t\n" ) );
  1034. }
  1035. //-----------------------------------------------------------------------------
  1036. DefineConsoleFunction( setField, const char*, ( const char* text, S32 index, const char* replacement ),,
  1037. "Replace the field in @a text at the given @a index with @a replacement.\n"
  1038. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1039. "@param text A list of fields separated by newlines and/or tabs.\n"
  1040. "@param index The zero-based index of the field to replace.\n"
  1041. "@param replacement The string with which to replace the field.\n"
  1042. "@return A new string with the field at the given @a index replaced by @a replacement or the original "
  1043. "string if @a index is out of range.\n\n"
  1044. "@tsexample\n"
  1045. "setField( \"a b\" TAB \"c d\" TAB \"e f\", 1, \"g h\" ) // Returns \"a b\" TAB \"g h\" TAB \"e f\"\n"
  1046. "@endtsexample\n\n"
  1047. "@see getField\n"
  1048. "@see setWord\n"
  1049. "@see setRecord\n"
  1050. "@ingroup FieldManip" )
  1051. {
  1052. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\t\n" ) );
  1053. }
  1054. //-----------------------------------------------------------------------------
  1055. DefineConsoleFunction( removeField, const char*, ( const char* text, S32 index ),,
  1056. "Remove the field in @a text at the given @a index.\n"
  1057. "Fields in @a text must be separated by newlines and/or tabs.\n"
  1058. "@param text A list of fields separated by newlines and/or tabs.\n"
  1059. "@param index The zero-based index of the field in @a text.\n"
  1060. "@return A new string with the field at the given index removed or the original string if @a index is "
  1061. "out of range.\n\n"
  1062. "@tsexample\n"
  1063. "removeField( \"a b\" TAB \"c d\" TAB \"e f\", 1 ) // Returns \"a b\" TAB \"e f\"\n"
  1064. "@endtsexample\n\n"
  1065. "@see removeWord\n"
  1066. "@see removeRecord\n"
  1067. "@ingroup FieldManip" )
  1068. {
  1069. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\t\n" ) );
  1070. }
  1071. //-----------------------------------------------------------------------------
  1072. DefineConsoleFunction( getFieldCount, S32, ( const char* text ),,
  1073. "Return the number of newline and/or tab separated fields in @a text.\n"
  1074. "@param text A list of fields separated by newlines and/or tabs.\n"
  1075. "@return The number of newline and/or tab sepearated elements in @a text.\n\n"
  1076. "@tsexample\n"
  1077. "getFieldCount( \"a b\" TAB \"c d\" TAB \"e f\" ) // Returns 3\n"
  1078. "@endtsexample\n\n"
  1079. "@see getWordCount\n"
  1080. "@see getRecordCount\n"
  1081. "@ingroup FieldManip" )
  1082. {
  1083. return StringUnit::getUnitCount( text, "\t\n" );
  1084. }
  1085. //-----------------------------------------------------------------------------
  1086. DefineConsoleFunction( getRecord, const char*, ( const char* text, S32 index ),,
  1087. "Extract the record at the given @a index in the newline-separated list in @a text.\n"
  1088. "Records in @a text must be separated by newlines.\n"
  1089. "@param text A list of records separated by newlines.\n"
  1090. "@param index The zero-based index of the record to extract.\n"
  1091. "@return The record at the given index or \"\" if @a index is out of range.\n\n"
  1092. "@tsexample\n"
  1093. "getRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\"\n"
  1094. "@endtsexample\n\n"
  1095. "@see getRecords\n"
  1096. "@see getRecordCount\n"
  1097. "@see getWord\n"
  1098. "@see getField\n"
  1099. "@ingroup FieldManip" )
  1100. {
  1101. return Con::getReturnBuffer( StringUnit::getUnit( text, index, "\n" ) );
  1102. }
  1103. //-----------------------------------------------------------------------------
  1104. DefineConsoleFunction( getRecords, const char*, ( const char* text, S32 startIndex, S32 endIndex ), ( -1 ),
  1105. "Extract a range of records from the given @a startIndex onwards thru @a endIndex.\n"
  1106. "Records in @a text must be separated by newlines.\n"
  1107. "@param text A list of records separated by newlines.\n"
  1108. "@param startIndex The zero-based index of the first record to extract from @a text.\n"
  1109. "@param endIndex The zero-based index of the last record to extract from @a text. If this is -1, all records beginning "
  1110. "with @a startIndex are extracted from @a text.\n"
  1111. "@return A string containing the specified range of records from @a text or \"\" if @a startIndex "
  1112. "is out of range or greater than @a endIndex.\n\n"
  1113. "@tsexample\n"
  1114. "getRecords( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"c d\" NL \"e f\"\n"
  1115. "@endtsexample\n\n"
  1116. "@see getRecord\n"
  1117. "@see getRecordCount\n"
  1118. "@see getWords\n"
  1119. "@see getFields\n"
  1120. "@ingroup FieldManip" )
  1121. {
  1122. if( endIndex < 0 )
  1123. endIndex = 1000000;
  1124. return Con::getReturnBuffer( StringUnit::getUnits( text, startIndex, endIndex, "\n" ) );
  1125. }
  1126. //-----------------------------------------------------------------------------
  1127. DefineConsoleFunction( setRecord, const char*, ( const char* text, S32 index, const char* replacement ),,
  1128. "Replace the record in @a text at the given @a index with @a replacement.\n"
  1129. "Records in @a text must be separated by newlines.\n"
  1130. "@param text A list of records separated by newlines.\n"
  1131. "@param index The zero-based index of the record to replace.\n"
  1132. "@param replacement The string with which to replace the record.\n"
  1133. "@return A new string with the record at the given @a index replaced by @a replacement or the original "
  1134. "string if @a index is out of range.\n\n"
  1135. "@tsexample\n"
  1136. "setRecord( \"a b\" NL \"c d\" NL \"e f\", 1, \"g h\" ) // Returns \"a b\" NL \"g h\" NL \"e f\"\n"
  1137. "@endtsexample\n\n"
  1138. "@see getRecord\n"
  1139. "@see setWord\n"
  1140. "@see setField\n"
  1141. "@ingroup FieldManip" )
  1142. {
  1143. return Con::getReturnBuffer( StringUnit::setUnit( text, index, replacement, "\n" ) );
  1144. }
  1145. //-----------------------------------------------------------------------------
  1146. DefineConsoleFunction( removeRecord, const char*, ( const char* text, S32 index ),,
  1147. "Remove the record in @a text at the given @a index.\n"
  1148. "Records in @a text must be separated by newlines.\n"
  1149. "@param text A list of records separated by newlines.\n"
  1150. "@param index The zero-based index of the record in @a text.\n"
  1151. "@return A new string with the record at the given @a index removed or the original string if @a index is "
  1152. "out of range.\n\n"
  1153. "@tsexample\n"
  1154. "removeRecord( \"a b\" NL \"c d\" NL \"e f\", 1 ) // Returns \"a b\" NL \"e f\"\n"
  1155. "@endtsexample\n\n"
  1156. "@see removeWord\n"
  1157. "@see removeField\n"
  1158. "@ingroup FieldManip" )
  1159. {
  1160. return Con::getReturnBuffer( StringUnit::removeUnit( text, index, "\n" ) );
  1161. }
  1162. //-----------------------------------------------------------------------------
  1163. DefineConsoleFunction( getRecordCount, S32, ( const char* text ),,
  1164. "Return the number of newline-separated records in @a text.\n"
  1165. "@param text A list of records separated by newlines.\n"
  1166. "@return The number of newline-sepearated elements in @a text.\n\n"
  1167. "@tsexample\n"
  1168. "getRecordCount( \"a b\" NL \"c d\" NL \"e f\" ) // Returns 3\n"
  1169. "@endtsexample\n\n"
  1170. "@see getWordCount\n"
  1171. "@see getFieldCount\n"
  1172. "@ingroup FieldManip" )
  1173. {
  1174. return StringUnit::getUnitCount( text, "\n" );
  1175. }
  1176. //-----------------------------------------------------------------------------
  1177. DefineConsoleFunction( firstWord, const char*, ( const char* text ),,
  1178. "Return the first word in @a text.\n"
  1179. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  1180. "@return The word at index 0 in @a text or \"\" if @a text is empty.\n\n"
  1181. "@note This is equal to \n"
  1182. "@tsexample_nopar\n"
  1183. "getWord( text, 0 )\n"
  1184. "@endtsexample\n\n"
  1185. "@see getWord\n"
  1186. "@ingroup FieldManip" )
  1187. {
  1188. return Con::getReturnBuffer( StringUnit::getUnit( text, 0, " \t\n" ) );
  1189. }
  1190. //-----------------------------------------------------------------------------
  1191. DefineConsoleFunction( restWords, const char*, ( const char* text ),,
  1192. "Return all but the first word in @a text.\n"
  1193. "@param text A list of words separated by newlines, spaces, and/or tabs.\n"
  1194. "@return @a text with the first word removed.\n\n"
  1195. "@note This is equal to \n"
  1196. "@tsexample_nopar\n"
  1197. "getWords( text, 1 )\n"
  1198. "@endtsexample\n\n"
  1199. "@see getWords\n"
  1200. "@ingroup FieldManip" )
  1201. {
  1202. const char* ptr = text;
  1203. while( *ptr && *ptr != ' ' && *ptr != '\t' && *ptr != '\n' )
  1204. ptr ++;
  1205. // Skip separator.
  1206. if( *ptr )
  1207. ptr ++;
  1208. return Con::getReturnBuffer( ptr );
  1209. }
  1210. //-----------------------------------------------------------------------------
  1211. static bool isInSet(char c, const char *set)
  1212. {
  1213. if (set)
  1214. while (*set)
  1215. if (c == *set++)
  1216. return true;
  1217. return false;
  1218. }
  1219. DefineConsoleFunction( nextToken, const char*, ( const char* str1, const char* token, const char* delim), , "( string str, string token, string delimiters ) "
  1220. "Tokenize a string using a set of delimiting characters.\n"
  1221. "This function first skips all leading charaters in @a str that are contained in @a delimiters. "
  1222. "From that position, it then scans for the next character in @a str that is contained in @a delimiters and stores all characters "
  1223. "from the starting position up to the first delimiter in a variable in the current scope called @a token. Finally, it "
  1224. "skips all characters in @a delimiters after the token and then returns the remaining string contents in @a str.\n\n"
  1225. "To scan out all tokens in a string, call this function repeatedly by passing the result it returns each time as the new @a str "
  1226. "until the function returns \"\".\n\n"
  1227. "@param str A string.\n"
  1228. "@param token The name of the variable in which to store the current token. This variable is set in the "
  1229. "scope in which nextToken is called.\n"
  1230. "@param delimiters A string of characters. Each character is considered a delimiter.\n"
  1231. "@return The remainder of @a str after the token has been parsed out or \"\" if no more tokens were found in @a str.\n\n"
  1232. "@tsexample\n"
  1233. "// Prints:\n"
  1234. "// a\n"
  1235. "// b\n"
  1236. "// c\n"
  1237. "%str = \"a b c\";\n"
  1238. "while ( %str !$= \"\" )\n"
  1239. "{\n"
  1240. " // First time, stores \"a\" in the variable %token and sets %str to \"b c\".\n"
  1241. " %str = nextToken( %str, \"token\", \" \" );\n"
  1242. " echo( %token );\n"
  1243. "}\n"
  1244. "@endtsexample\n\n"
  1245. "@ingroup Strings" )
  1246. {
  1247. char buffer[4096];
  1248. dStrncpy(buffer, str1, 4096);
  1249. char *str = buffer;
  1250. if( str[0] )
  1251. {
  1252. // skip over any characters that are a member of delim
  1253. // no need for special '\0' check since it can never be in delim
  1254. while (isInSet(*str, delim))
  1255. str++;
  1256. // skip over any characters that are NOT a member of delim
  1257. const char *tmp = str;
  1258. while (*str && !isInSet(*str, delim))
  1259. str++;
  1260. // terminate the token
  1261. if (*str)
  1262. *str++ = 0;
  1263. // set local variable if inside a function
  1264. if (gEvalState.getStackDepth() > 0 &&
  1265. gEvalState.getCurrentFrame().scopeName)
  1266. Con::setLocalVariable(token,tmp);
  1267. else
  1268. Con::setVariable(token,tmp);
  1269. // advance str past the 'delim space'
  1270. while (isInSet(*str, delim))
  1271. str++;
  1272. }
  1273. U32 returnLen = dStrlen(str)+1;
  1274. char *ret = Con::getReturnBuffer(returnLen);
  1275. dStrncpy(ret, str, returnLen);
  1276. return ret;
  1277. }
  1278. //=============================================================================
  1279. // Tagged Strings.
  1280. //=============================================================================
  1281. // MARK: ---- Tagged Strings ----
  1282. //-----------------------------------------------------------------------------
  1283. DefineEngineFunction( detag, const char*, ( const char* str ),,
  1284. "@brief Returns the string from a tag string.\n\n"
  1285. "Should only be used within the context of a function that receives a tagged "
  1286. "string, and is not meant to be used outside of this context. Use getTaggedString() "
  1287. "to convert a tagged string ID back into a regular string at any time.\n\n"
  1288. "@tsexample\n"
  1289. "// From scripts/client/message.cs\n"
  1290. "function clientCmdChatMessage(%sender, %voice, %pitch, %msgString, %a1, %a2, %a3, %a4, %a5, %a6, %a7, %a8, %a9, %a10)\n"
  1291. "{\n"
  1292. " onChatMessage(detag(%msgString), %voice, %pitch);\n"
  1293. "}\n"
  1294. "@endtsexample\n\n"
  1295. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1296. "@see getTag()\n"
  1297. "@see getTaggedString()\n"
  1298. "@ingroup Networking")
  1299. {
  1300. if( str[ 0 ] == StringTagPrefixByte )
  1301. {
  1302. const char* word = dStrchr( str, ' ' );
  1303. if( word == NULL )
  1304. return "";
  1305. char* ret = Con::getReturnBuffer( dStrlen( word + 1 ) + 1 );
  1306. dStrcpy( ret, word + 1 );
  1307. return ret;
  1308. }
  1309. else
  1310. return str;
  1311. }
  1312. DefineConsoleFunction( getTag, const char*, ( const char* textTagString ), , "( string textTagString ) "
  1313. "@brief Extracts the tag from a tagged string\n\n"
  1314. "Should only be used within the context of a function that receives a tagged "
  1315. "string, and is not meant to be used outside of this context.\n\n"
  1316. "@param textTagString The tagged string to extract.\n"
  1317. "@returns The tag ID of the string.\n"
  1318. "@see \\ref syntaxDataTypes under Tagged %Strings\n"
  1319. "@see detag()\n"
  1320. "@ingroup Networking")
  1321. {
  1322. if(textTagString[0] == StringTagPrefixByte)
  1323. {
  1324. const char * space = dStrchr(textTagString, ' ');
  1325. U64 len;
  1326. if(space)
  1327. len = space - textTagString;
  1328. else
  1329. len = dStrlen(textTagString) + 1;
  1330. char * ret = Con::getReturnBuffer(len);
  1331. dStrncpy(ret, textTagString + 1, len - 1);
  1332. ret[len - 1] = 0;
  1333. return(ret);
  1334. }
  1335. else
  1336. return(textTagString);
  1337. }
  1338. //=============================================================================
  1339. // Output.
  1340. //=============================================================================
  1341. // MARK: ---- Output ----
  1342. //-----------------------------------------------------------------------------
  1343. ConsoleFunction( echo, void, 2, 0, "( string message... ) "
  1344. "@brief Logs a message to the console.\n\n"
  1345. "Concatenates all given arguments to a single string and prints the string to the console. "
  1346. "A newline is added automatically after the text.\n\n"
  1347. "@param message Any number of string arguments.\n\n"
  1348. "@ingroup Logging" )
  1349. {
  1350. U32 len = 0;
  1351. S32 i;
  1352. for(i = 1; i < argc; i++)
  1353. len += dStrlen(argv[i]);
  1354. char *ret = Con::getReturnBuffer(len + 1);
  1355. ret[0] = 0;
  1356. for(i = 1; i < argc; i++)
  1357. dStrcat(ret, argv[i]);
  1358. Con::printf("%s", ret);
  1359. ret[0] = 0;
  1360. }
  1361. //-----------------------------------------------------------------------------
  1362. ConsoleFunction( warn, void, 2, 0, "( string message... ) "
  1363. "@brief Logs a warning message to the console.\n\n"
  1364. "Concatenates all given arguments to a single string and prints the string to the console as a warning "
  1365. "message (in the in-game console, these will show up using a turquoise font by default). "
  1366. "A newline is added automatically after the text.\n\n"
  1367. "@param message Any number of string arguments.\n\n"
  1368. "@ingroup Logging" )
  1369. {
  1370. U32 len = 0;
  1371. S32 i;
  1372. for(i = 1; i < argc; i++)
  1373. len += dStrlen(argv[i]);
  1374. char *ret = Con::getReturnBuffer(len + 1);
  1375. ret[0] = 0;
  1376. for(i = 1; i < argc; i++)
  1377. dStrcat(ret, argv[i]);
  1378. Con::warnf(ConsoleLogEntry::General, "%s", ret);
  1379. ret[0] = 0;
  1380. }
  1381. //-----------------------------------------------------------------------------
  1382. ConsoleFunction( error, void, 2, 0, "( string message... ) "
  1383. "@brief Logs an error message to the console.\n\n"
  1384. "Concatenates all given arguments to a single string and prints the string to the console as an error "
  1385. "message (in the in-game console, these will show up using a red font by default). "
  1386. "A newline is added automatically after the text.\n\n"
  1387. "@param message Any number of string arguments.\n\n"
  1388. "@ingroup Logging" )
  1389. {
  1390. U32 len = 0;
  1391. S32 i;
  1392. for(i = 1; i < argc; i++)
  1393. len += dStrlen(argv[i]);
  1394. char *ret = Con::getReturnBuffer(len + 1);
  1395. ret[0] = 0;
  1396. for(i = 1; i < argc; i++)
  1397. dStrcat(ret, argv[i]);
  1398. Con::errorf(ConsoleLogEntry::General, "%s", ret);
  1399. ret[0] = 0;
  1400. }
  1401. //-----------------------------------------------------------------------------
  1402. DefineEngineFunction( debugv, void, ( const char* variableName ),,
  1403. "@brief Logs the value of the given variable to the console.\n\n"
  1404. "Prints a string of the form \"<variableName> = <variable value>\" to the console.\n\n"
  1405. "@param variableName Name of the local or global variable to print.\n\n"
  1406. "@tsexample\n"
  1407. "%var = 1;\n"
  1408. "debugv( \"%var\" ); // Prints \"%var = 1\"\n"
  1409. "@endtsexample\n\n"
  1410. "@ingroup Debugging" )
  1411. {
  1412. if( variableName[ 0 ] == '%' )
  1413. Con::errorf( "%s = %s", variableName, Con::getLocalVariable( variableName ) );
  1414. else
  1415. Con::errorf( "%s = %s", variableName, Con::getVariable( variableName ) );
  1416. }
  1417. //-----------------------------------------------------------------------------
  1418. DefineConsoleFunction( expandEscape, const char*, ( const char* text ),,
  1419. "@brief Replace all characters in @a text that need to be escaped for the string to be a valid string literal with their "
  1420. "respective escape sequences.\n\n"
  1421. "All characters in @a text that cannot appear in a string literal will be replaced by an escape sequence (\\\\n, \\\\t, etc).\n\n"
  1422. "The primary use of this function is for converting strings suitable for being passed as string literals "
  1423. "to the TorqueScript compiler.\n\n"
  1424. "@param text A string\n"
  1425. "@return A duplicate of the text parameter with all unescaped characters that cannot appear in string literals replaced by their respective "
  1426. "escape sequences.\n\n"
  1427. "@tsxample\n"
  1428. "expandEscape( \"str\" NL \"ing\" ) // Returns \"str\\ning\".\n"
  1429. "@endtsxample\n\n"
  1430. "@see collapseEscape\n"
  1431. "@ingroup Strings")
  1432. {
  1433. char* ret = Con::getReturnBuffer(dStrlen( text ) * 2 + 1 ); // worst case situation
  1434. expandEscape( ret, text );
  1435. return ret;
  1436. }
  1437. //-----------------------------------------------------------------------------
  1438. DefineConsoleFunction( collapseEscape, const char*, ( const char* text ),,
  1439. "Replace all escape sequences in @a text with their respective character codes.\n\n"
  1440. "This function replaces all escape sequences (\\\\n, \\\\t, etc) in the given string "
  1441. "with the respective characters they represent.\n\n"
  1442. "The primary use of this function is for converting strings from their literal form into "
  1443. "their compiled/translated form, as is normally done by the TorqueScript compiler.\n\n"
  1444. "@param text A string.\n"
  1445. "@return A duplicate of @a text with all escape sequences replaced by their respective character codes.\n\n"
  1446. "@tsexample\n"
  1447. "// Print:\n"
  1448. "//\n"
  1449. "// str\n"
  1450. "// ing\n"
  1451. "//\n"
  1452. "// to the console. Note how the backslash in the string must be escaped here\n"
  1453. "// in order to prevent the TorqueScript compiler from collapsing the escape\n"
  1454. "// sequence in the resulting string.\n"
  1455. "echo( collapseEscape( \"str\\ning\" ) );\n"
  1456. "@endtsexample\n\n"
  1457. "@see expandEscape\n\n"
  1458. "@ingroup Strings" )
  1459. {
  1460. char* ret = Con::getReturnBuffer( text );
  1461. collapseEscape( ret );
  1462. return ret;
  1463. }
  1464. //-----------------------------------------------------------------------------
  1465. DefineEngineFunction( setLogMode, void, ( S32 mode ),,
  1466. "@brief Determines how log files are written.\n\n"
  1467. "Sets the operational mode of the console logging system.\n\n"
  1468. "@param mode Parameter specifying the logging mode. This can be:\n"
  1469. "- 1: Open and close the console log file for each seperate string of output. This will ensure that all "
  1470. "parts get written out to disk and that no parts remain in intermediate buffers even if the process crashes.\n"
  1471. "- 2: Keep the log file open and write to it continuously. This will make the system operate faster but "
  1472. "if the process crashes, parts of the output may not have been written to disk yet and will be missing from "
  1473. "the log.\n\n"
  1474. "Additionally, when changing the log mode and thus opening a new log file, either of the two mode values may be "
  1475. "combined by binary OR with 0x4 to cause the logging system to flush all console log messages that had already been "
  1476. "issued to the console system into the newly created log file.\n\n"
  1477. "@note Xbox 360 does not support logging to a file. Use Platform::OutputDebugStr in C++ instead."
  1478. "@ingroup Logging" )
  1479. {
  1480. Con::setLogMode( mode );
  1481. }
  1482. //=============================================================================
  1483. // Misc.
  1484. //=============================================================================
  1485. // MARK: ---- Misc ----
  1486. //-----------------------------------------------------------------------------
  1487. DefineConsoleFunction( quit, void, ( ),,
  1488. "Shut down the engine and exit its process.\n"
  1489. "This function cleanly uninitializes the engine and then exits back to the system with a process "
  1490. "exit status indicating a clean exit.\n\n"
  1491. "@see quitWithErrorMessage\n\n"
  1492. "@ingroup Platform" )
  1493. {
  1494. Platform::postQuitMessage(0);
  1495. }
  1496. //-----------------------------------------------------------------------------
  1497. DefineConsoleFunction( realQuit, void, (), , "")
  1498. {
  1499. Platform::postQuitMessage(0);
  1500. }
  1501. //-----------------------------------------------------------------------------
  1502. DefineConsoleFunction( quitWithErrorMessage, void, ( const char* message, S32 status ), (0),
  1503. "Display an error message box showing the given @a message and then shut down the engine and exit its process.\n"
  1504. "This function cleanly uninitialized the engine and then exits back to the system with a process "
  1505. "exit status indicating an error.\n\n"
  1506. "@param message The message to log to the console and show in an error message box.\n"
  1507. "@param status The status code to return to the OS.\n\n"
  1508. "@see quit\n\n"
  1509. "@ingroup Platform" )
  1510. {
  1511. Con::errorf( message );
  1512. Platform::AlertOK( "Error", message );
  1513. // [rene 03/30/10] This was previously using forceShutdown which is a bad thing
  1514. // as the script code should not be allowed to pretty much hard-crash the engine
  1515. // and prevent proper shutdown. Changed this to use postQuitMessage.
  1516. Platform::postQuitMessage( status );
  1517. }
  1518. //-----------------------------------------------------------------------------
  1519. DefineConsoleFunction( quitWithStatus, void, ( S32 status ), (0),
  1520. "Shut down the engine and exit its process.\n"
  1521. "This function cleanly uninitializes the engine and then exits back to the system with a given "
  1522. "return status code.\n\n"
  1523. "@param status The status code to return to the OS.\n\n"
  1524. "@see quitWithErrorMessage\n\n"
  1525. "@ingroup Platform" )
  1526. {
  1527. Platform::postQuitMessage(status);
  1528. }
  1529. //-----------------------------------------------------------------------------
  1530. DefineEngineFunction( gotoWebPage, void, ( const char* address ),,
  1531. "Open the given URL or file in the user's web browser.\n\n"
  1532. "@param address The address to open. If this is not prefixed by a protocol specifier (\"...://\"), then "
  1533. "the function checks whether the address refers to a file or directory and if so, prepends \"file://\" "
  1534. "to @a adress; if the file check fails, \"http://\" is prepended to @a address.\n\n"
  1535. "@tsexample\n"
  1536. "gotoWebPage( \"http://www.garagegames.com\" );\n"
  1537. "@endtsexample\n\n"
  1538. "@ingroup Platform" )
  1539. {
  1540. // If there's a protocol prefix in the address, just invoke
  1541. // the browser on the given address.
  1542. char* protocolSep = dStrstr( address,"://");
  1543. if( protocolSep != NULL )
  1544. {
  1545. Platform::openWebBrowser( address );
  1546. return;
  1547. }
  1548. // If we don't see a protocol seperator, then we know that some bullethead
  1549. // sent us a bad url. We'll first check to see if a file inside the sandbox
  1550. // with that name exists, then we'll just glom "http://" onto the front of
  1551. // the bogus url, and hope for the best.
  1552. String addr;
  1553. if( Platform::isFile( address ) || Platform::isDirectory( address ) )
  1554. {
  1555. #ifdef TORQUE2D_TOOLS_FIXME
  1556. addr = String::ToString( "file://%s", address );
  1557. #else
  1558. addr = String::ToString( "file://%s/%s", Platform::getCurrentDirectory(), address );
  1559. #endif
  1560. }
  1561. else
  1562. addr = String::ToString( "http://%s", address );
  1563. Platform::openWebBrowser( addr );
  1564. return;
  1565. }
  1566. //-----------------------------------------------------------------------------
  1567. DefineEngineFunction( displaySplashWindow, bool, (const char* path), ("art/gui/splash.bmp"),
  1568. "Display a startup splash window suitable for showing while the engine still starts up.\n\n"
  1569. "@note This is currently only implemented on Windows.\n\n"
  1570. "@return True if the splash window could be successfully initialized.\n\n"
  1571. "@ingroup Platform" )
  1572. {
  1573. return Platform::displaySplashWindow(path);
  1574. }
  1575. DefineEngineFunction( closeSplashWindow, void, (),,
  1576. "Close our startup splash window.\n\n"
  1577. "@note This is currently only implemented on Windows.\n\n"
  1578. "@ingroup Platform" )
  1579. {
  1580. Platform::closeSplashWindow();
  1581. }
  1582. //-----------------------------------------------------------------------------
  1583. DefineEngineFunction( getWebDeployment, bool, (),,
  1584. "Test whether Torque is running in web-deployment mode.\n"
  1585. "In this mode, Torque will usually run within a browser and certain restrictions apply (e.g. Torque will not "
  1586. "be able to enter fullscreen exclusive mode).\n"
  1587. "@return True if Torque is running in web-deployment mode.\n"
  1588. "@ingroup Platform" )
  1589. {
  1590. return Platform::getWebDeployment();
  1591. }
  1592. //-----------------------------------------------------------------------------
  1593. DefineEngineFunction( countBits, S32, ( S32 v ),,
  1594. "Count the number of bits that are set in the given 32 bit integer.\n"
  1595. "@param v An integer value.\n\n"
  1596. "@return The number of bits that are set in @a v.\n\n"
  1597. "@ingroup Utilities" )
  1598. {
  1599. S32 c = 0;
  1600. // from
  1601. // http://graphics.stanford.edu/~seander/bithacks.html
  1602. // for at most 32-bit values in v:
  1603. c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1604. c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) %
  1605. 0x1f;
  1606. c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
  1607. #ifndef TORQUE_SHIPPING
  1608. // since the above isn't very obvious, for debugging compute the count in a more
  1609. // traditional way and assert if it is different
  1610. {
  1611. S32 c2 = 0;
  1612. S32 v2 = v;
  1613. for (c2 = 0; v2; v2 >>= 1)
  1614. {
  1615. c2 += v2 & 1;
  1616. }
  1617. if (c2 != c)
  1618. Con::errorf("countBits: Uh oh bit count mismatch");
  1619. AssertFatal(c2 == c, "countBits: uh oh, bit count mismatch");
  1620. }
  1621. #endif
  1622. return c;
  1623. }
  1624. //-----------------------------------------------------------------------------
  1625. DefineEngineFunction( generateUUID, Torque::UUID, (),,
  1626. "Generate a new universally unique identifier (UUID).\n\n"
  1627. "@return A newly generated UUID.\n\n"
  1628. "@ingroup Utilities" )
  1629. {
  1630. Torque::UUID uuid;
  1631. uuid.generate();
  1632. return uuid;
  1633. }
  1634. //=============================================================================
  1635. // Meta Scripting.
  1636. //=============================================================================
  1637. // MARK: ---- Meta Scripting ----
  1638. //-----------------------------------------------------------------------------
  1639. ConsoleFunction( call, const char *, 2, 0, "( string functionName, string args... ) "
  1640. "Apply the given arguments to the specified global function and return the result of the call.\n\n"
  1641. "@param functionName The name of the function to call. This function must be in the global namespace, i.e. "
  1642. "you cannot call a function in a namespace through #call. Use eval() for that.\n"
  1643. "@return The result of the function call.\n\n"
  1644. "@tsexample\n"
  1645. "function myFunction( %arg )\n"
  1646. "{\n"
  1647. " return ( %arg SPC \"World!\" );\n"
  1648. "}\n"
  1649. "\n"
  1650. "echo( call( \"myFunction\", \"Hello\" ) ); // Prints \"Hello World!\" to the console.\n"
  1651. "@endtsexample\n\n"
  1652. "@ingroup Scripting" )
  1653. {
  1654. return Con::execute( argc - 1, argv + 1 );
  1655. }
  1656. //-----------------------------------------------------------------------------
  1657. static U32 execDepth = 0;
  1658. static U32 journalDepth = 1;
  1659. static StringTableEntry getDSOPath(const char *scriptPath)
  1660. {
  1661. #ifndef TORQUE2D_TOOLS_FIXME
  1662. // [tom, 11/17/2006] Force old behavior for the player. May not want to do this.
  1663. const char *slash = dStrrchr(scriptPath, '/');
  1664. if(slash != NULL)
  1665. return StringTable->insertn(scriptPath, slash - scriptPath, true);
  1666. slash = dStrrchr(scriptPath, ':');
  1667. if(slash != NULL)
  1668. return StringTable->insertn(scriptPath, (slash - scriptPath) + 1, true);
  1669. return "";
  1670. #else
  1671. char relPath[1024], dsoPath[1024];
  1672. bool isPrefs = false;
  1673. // [tom, 11/17/2006] Prefs are handled slightly differently to avoid dso name clashes
  1674. StringTableEntry prefsPath = Platform::getPrefsPath();
  1675. if(dStrnicmp(scriptPath, prefsPath, dStrlen(prefsPath)) == 0)
  1676. {
  1677. relPath[0] = 0;
  1678. isPrefs = true;
  1679. }
  1680. else
  1681. {
  1682. StringTableEntry strippedPath = Platform::stripBasePath(scriptPath);
  1683. dStrcpy(relPath, strippedPath);
  1684. char *slash = dStrrchr(relPath, '/');
  1685. if(slash)
  1686. *slash = 0;
  1687. }
  1688. const char *overridePath;
  1689. if(! isPrefs)
  1690. overridePath = Con::getVariable("$Scripts::OverrideDSOPath");
  1691. else
  1692. overridePath = prefsPath;
  1693. if(overridePath && *overridePath)
  1694. Platform::makeFullPathName(relPath, dsoPath, sizeof(dsoPath), overridePath);
  1695. else
  1696. {
  1697. char t[1024];
  1698. dSprintf(t, sizeof(t), "compiledScripts/%s", relPath);
  1699. Platform::makeFullPathName(t, dsoPath, sizeof(dsoPath), Platform::getPrefsPath());
  1700. }
  1701. return StringTable->insert(dsoPath);
  1702. #endif
  1703. }
  1704. DefineConsoleFunction( getDSOPath, const char*, ( const char* scriptFileName ),,
  1705. "Get the absolute path to the file in which the compiled code for the given script file will be stored.\n"
  1706. "@param scriptFileName %Path to the .cs script file.\n"
  1707. "@return The absolute path to the .dso file for the given script file.\n\n"
  1708. "@note The compiler will store newly compiled DSOs in the prefs path but pre-existing DSOs will be loaded "
  1709. "from the current paths.\n\n"
  1710. "@see compile\n"
  1711. "@see getPrefsPath\n"
  1712. "@ingroup Scripting" )
  1713. {
  1714. Con::expandScriptFilename( scriptFilenameBuffer, sizeof(scriptFilenameBuffer), scriptFileName );
  1715. const char* filename = getDSOPath(scriptFilenameBuffer);
  1716. if(filename == NULL || *filename == 0)
  1717. return "";
  1718. return filename;
  1719. }
  1720. //-----------------------------------------------------------------------------
  1721. DefineEngineFunction( compile, bool, ( const char* fileName, bool overrideNoDSO ), ( false ),
  1722. "Compile a file to bytecode.\n\n"
  1723. "This function will read the TorqueScript code in the specified file, compile it to internal bytecode, and, "
  1724. "if DSO generation is enabled or @a overrideNoDDSO is true, will store the compiled code in a .dso file "
  1725. "in the current DSO path mirrorring the path of @a fileName.\n\n"
  1726. "@param fileName Path to the file to compile to bytecode.\n"
  1727. "@param overrideNoDSO If true, force generation of DSOs even if the engine is compiled to not "
  1728. "generate write compiled code to DSO files.\n\n"
  1729. "@return True if the file was successfully compiled, false if not.\n\n"
  1730. "@note The definitions contained in the given file will not be made available and no code will actually "
  1731. "be executed. Use exec() for that.\n\n"
  1732. "@see getDSOPath\n"
  1733. "@see exec\n"
  1734. "@ingroup Scripting" )
  1735. {
  1736. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1737. // Figure out where to put DSOs
  1738. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1739. if(dsoPath && *dsoPath == 0)
  1740. return false;
  1741. // If the script file extention is '.ed.cs' then compile it to a different compiled extention
  1742. bool isEditorScript = false;
  1743. const char *ext = dStrrchr( scriptFilenameBuffer, '.' );
  1744. if( ext && ( dStricmp( ext, ".cs" ) == 0 ) )
  1745. {
  1746. const char* ext2 = ext - 3;
  1747. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1748. isEditorScript = true;
  1749. }
  1750. else if( ext && ( dStricmp( ext, ".gui" ) == 0 ) )
  1751. {
  1752. const char* ext2 = ext - 3;
  1753. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1754. isEditorScript = true;
  1755. }
  1756. const char *filenameOnly = dStrrchr(scriptFilenameBuffer, '/');
  1757. if(filenameOnly)
  1758. ++filenameOnly;
  1759. else
  1760. filenameOnly = scriptFilenameBuffer;
  1761. char nameBuffer[512];
  1762. if( isEditorScript )
  1763. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".edso", NULL);
  1764. else
  1765. dStrcpyl(nameBuffer, sizeof(nameBuffer), dsoPath, "/", filenameOnly, ".dso", NULL);
  1766. void *data = NULL;
  1767. U32 dataSize = 0;
  1768. Torque::FS::ReadFile(scriptFilenameBuffer, data, dataSize, true);
  1769. if(data == NULL)
  1770. {
  1771. Con::errorf(ConsoleLogEntry::Script, "compile: invalid script file %s.", scriptFilenameBuffer);
  1772. return false;
  1773. }
  1774. const char *script = static_cast<const char *>(data);
  1775. #ifdef TORQUE_DEBUG
  1776. Con::printf("Compiling %s...", scriptFilenameBuffer);
  1777. #endif
  1778. CodeBlock *code = new CodeBlock();
  1779. code->compile(nameBuffer, scriptFilenameBuffer, script, overrideNoDSO);
  1780. delete code;
  1781. delete[] script;
  1782. return true;
  1783. }
  1784. //-----------------------------------------------------------------------------
  1785. DefineEngineFunction( exec, bool, ( const char* fileName, bool noCalls, bool journalScript ), ( false, false ),
  1786. "Execute the given script file.\n"
  1787. "@param fileName Path to the file to execute\n"
  1788. "@param noCalls Deprecated\n"
  1789. "@param journalScript Deprecated\n"
  1790. "@return True if the script was successfully executed, false if not.\n\n"
  1791. "@tsexample\n"
  1792. "// Execute the init.cs script file found in the same directory as the current script file.\n"
  1793. "exec( \"./init.cs\" );\n"
  1794. "@endtsexample\n\n"
  1795. "@see compile\n"
  1796. "@see eval\n"
  1797. "@ingroup Scripting" )
  1798. {
  1799. bool journal = false;
  1800. execDepth++;
  1801. if(journalDepth >= execDepth)
  1802. journalDepth = execDepth + 1;
  1803. else
  1804. journal = true;
  1805. bool ret = false;
  1806. if( journalScript && !journal )
  1807. {
  1808. journal = true;
  1809. journalDepth = execDepth;
  1810. }
  1811. // Determine the filename we actually want...
  1812. Con::expandScriptFilename( scriptFilenameBuffer, sizeof( scriptFilenameBuffer ), fileName );
  1813. // since this function expects a script file reference, if it's a .dso
  1814. // lets terminate the string before the dso so it will act like a .cs
  1815. if(dStrEndsWith(scriptFilenameBuffer, ".dso"))
  1816. {
  1817. scriptFilenameBuffer[dStrlen(scriptFilenameBuffer) - dStrlen(".dso")] = '\0';
  1818. }
  1819. // Figure out where to put DSOs
  1820. StringTableEntry dsoPath = getDSOPath(scriptFilenameBuffer);
  1821. const char *ext = dStrrchr(scriptFilenameBuffer, '.');
  1822. if(!ext)
  1823. {
  1824. // We need an extension!
  1825. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file name %s.", scriptFilenameBuffer);
  1826. execDepth--;
  1827. return false;
  1828. }
  1829. // Check Editor Extensions
  1830. bool isEditorScript = false;
  1831. // If the script file extension is '.ed.cs' then compile it to a different compiled extension
  1832. if( dStricmp( ext, ".cs" ) == 0 )
  1833. {
  1834. const char* ext2 = ext - 3;
  1835. if( dStricmp( ext2, ".ed.cs" ) == 0 )
  1836. isEditorScript = true;
  1837. }
  1838. else if( dStricmp( ext, ".gui" ) == 0 )
  1839. {
  1840. const char* ext2 = ext - 3;
  1841. if( dStricmp( ext2, ".ed.gui" ) == 0 )
  1842. isEditorScript = true;
  1843. }
  1844. StringTableEntry scriptFileName = StringTable->insert(scriptFilenameBuffer);
  1845. #ifndef TORQUE_OS_XENON
  1846. // Is this a file we should compile? (anything in the prefs path should not be compiled)
  1847. StringTableEntry prefsPath = Platform::getPrefsPath();
  1848. bool compiled = dStricmp(ext, ".mis") && !journal && !Con::getBoolVariable("Scripts::ignoreDSOs");
  1849. // [tom, 12/5/2006] stripBasePath() fucks up if the filename is not in the exe
  1850. // path, current directory or prefs path. Thus, getDSOFilename() will also screw
  1851. // up and so this allows the scripts to still load but without a DSO.
  1852. if(Platform::isFullPath(Platform::stripBasePath(scriptFilenameBuffer)))
  1853. compiled = false;
  1854. // [tom, 11/17/2006] It seems to make sense to not compile scripts that are in the
  1855. // prefs directory. However, getDSOPath() can handle this situation and will put
  1856. // the dso along with the script to avoid name clashes with tools/game dsos.
  1857. if( (dsoPath && *dsoPath == 0) || (prefsPath && prefsPath[ 0 ] && dStrnicmp(scriptFileName, prefsPath, dStrlen(prefsPath)) == 0) )
  1858. compiled = false;
  1859. #else
  1860. bool compiled = false; // Don't try to compile things on the 360, ignore DSO's when debugging
  1861. // because PC prefs will screw up stuff like SFX.
  1862. #endif
  1863. // If we're in a journaling mode, then we will read the script
  1864. // from the journal file.
  1865. if(journal && Journal::IsPlaying())
  1866. {
  1867. char fileNameBuf[256];
  1868. bool fileRead = false;
  1869. U32 fileSize;
  1870. Journal::ReadString(fileNameBuf);
  1871. Journal::Read(&fileRead);
  1872. if(!fileRead)
  1873. {
  1874. Con::errorf(ConsoleLogEntry::Script, "Journal script read (failed) for %s", fileNameBuf);
  1875. execDepth--;
  1876. return false;
  1877. }
  1878. Journal::Read(&fileSize);
  1879. char *script = new char[fileSize + 1];
  1880. Journal::Read(fileSize, script);
  1881. script[fileSize] = 0;
  1882. Con::printf("Executing (journal-read) %s.", scriptFileName);
  1883. CodeBlock *newCodeBlock = new CodeBlock();
  1884. newCodeBlock->compileExec(scriptFileName, script, noCalls, 0);
  1885. delete [] script;
  1886. execDepth--;
  1887. return true;
  1888. }
  1889. // Ok, we let's try to load and compile the script.
  1890. Torque::FS::FileNodeRef scriptFile = Torque::FS::GetFileNode(scriptFileName);
  1891. Torque::FS::FileNodeRef dsoFile;
  1892. // ResourceObject *rScr = gResourceManager->find(scriptFileName);
  1893. // ResourceObject *rCom = NULL;
  1894. char nameBuffer[512];
  1895. char* script = NULL;
  1896. U32 version;
  1897. Stream *compiledStream = NULL;
  1898. Torque::Time scriptModifiedTime, dsoModifiedTime;
  1899. // Check here for .edso
  1900. bool edso = false;
  1901. if( dStricmp( ext, ".edso" ) == 0 && scriptFile != NULL )
  1902. {
  1903. edso = true;
  1904. dsoFile = scriptFile;
  1905. scriptFile = NULL;
  1906. dsoModifiedTime = dsoFile->getModifiedTime();
  1907. dStrcpy( nameBuffer, scriptFileName );
  1908. }
  1909. // If we're supposed to be compiling this file, check to see if there's a DSO
  1910. if(compiled && !edso)
  1911. {
  1912. const char *filenameOnly = dStrrchr(scriptFileName, '/');
  1913. if(filenameOnly)
  1914. ++filenameOnly;
  1915. else
  1916. filenameOnly = scriptFileName;
  1917. char pathAndFilename[1024];
  1918. Platform::makeFullPathName(filenameOnly, pathAndFilename, sizeof(pathAndFilename), dsoPath);
  1919. if( isEditorScript )
  1920. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".edso", NULL);
  1921. else
  1922. dStrcpyl(nameBuffer, sizeof(nameBuffer), pathAndFilename, ".dso", NULL);
  1923. dsoFile = Torque::FS::GetFileNode(nameBuffer);
  1924. if(scriptFile != NULL)
  1925. scriptModifiedTime = scriptFile->getModifiedTime();
  1926. if(dsoFile != NULL)
  1927. dsoModifiedTime = dsoFile->getModifiedTime();
  1928. }
  1929. // Let's do a sanity check to complain about DSOs in the future.
  1930. //
  1931. // MM: This doesn't seem to be working correctly for now so let's just not issue
  1932. // the warning until someone knows how to resolve it.
  1933. //
  1934. //if(compiled && rCom && rScr && Platform::compareFileTimes(comModifyTime, scrModifyTime) < 0)
  1935. //{
  1936. //Con::warnf("exec: Warning! Found a DSO from the future! (%s)", nameBuffer);
  1937. //}
  1938. // If we had a DSO, let's check to see if we should be reading from it.
  1939. //MGT: fixed bug with dsos not getting recompiled correctly
  1940. //Note: Using Nathan Martin's version from the forums since its easier to read and understand
  1941. if(compiled && dsoFile != NULL && (scriptFile == NULL|| (dsoModifiedTime >= scriptModifiedTime)))
  1942. { //MGT: end
  1943. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  1944. if (compiledStream)
  1945. {
  1946. // Check the version!
  1947. compiledStream->read(&version);
  1948. if(version != Con::DSOVersion)
  1949. {
  1950. Con::warnf("exec: Found an old DSO (%s, ver %d < %d), ignoring.", nameBuffer, version, Con::DSOVersion);
  1951. delete compiledStream;
  1952. compiledStream = NULL;
  1953. }
  1954. }
  1955. }
  1956. // If we're journalling, let's write some info out.
  1957. if(journal && Journal::IsRecording())
  1958. Journal::WriteString(scriptFileName);
  1959. if(scriptFile != NULL && !compiledStream)
  1960. {
  1961. // If we have source but no compiled version, then we need to compile
  1962. // (and journal as we do so, if that's required).
  1963. void *data;
  1964. U32 dataSize = 0;
  1965. Torque::FS::ReadFile(scriptFileName, data, dataSize, true);
  1966. if(journal && Journal::IsRecording())
  1967. Journal::Write(bool(data != NULL));
  1968. if( data == NULL )
  1969. {
  1970. Con::errorf(ConsoleLogEntry::Script, "exec: invalid script file %s.", scriptFileName);
  1971. execDepth--;
  1972. return false;
  1973. }
  1974. else
  1975. {
  1976. if( !dataSize )
  1977. {
  1978. execDepth --;
  1979. return false;
  1980. }
  1981. script = (char *)data;
  1982. if(journal && Journal::IsRecording())
  1983. {
  1984. Journal::Write(dataSize);
  1985. Journal::Write(dataSize, data);
  1986. }
  1987. }
  1988. #ifndef TORQUE_NO_DSO_GENERATION
  1989. if(compiled)
  1990. {
  1991. // compile this baddie.
  1992. #ifdef TORQUE_DEBUG
  1993. Con::printf("Compiling %s...", scriptFileName);
  1994. #endif
  1995. CodeBlock *code = new CodeBlock();
  1996. code->compile(nameBuffer, scriptFileName, script);
  1997. delete code;
  1998. code = NULL;
  1999. compiledStream = FileStream::createAndOpen( nameBuffer, Torque::FS::File::Read );
  2000. if(compiledStream)
  2001. {
  2002. compiledStream->read(&version);
  2003. }
  2004. else
  2005. {
  2006. // We have to exit out here, as otherwise we get double error reports.
  2007. delete [] script;
  2008. execDepth--;
  2009. return false;
  2010. }
  2011. }
  2012. #endif
  2013. }
  2014. else
  2015. {
  2016. if(journal && Journal::IsRecording())
  2017. Journal::Write(bool(false));
  2018. }
  2019. if(compiledStream)
  2020. {
  2021. // Delete the script object first to limit memory used
  2022. // during recursive execs.
  2023. delete [] script;
  2024. script = 0;
  2025. // We're all compiled, so let's run it.
  2026. #ifdef TORQUE_DEBUG
  2027. Con::printf("Loading compiled script %s.", scriptFileName);
  2028. #endif
  2029. CodeBlock *code = new CodeBlock;
  2030. code->read(scriptFileName, *compiledStream);
  2031. delete compiledStream;
  2032. code->exec(0, scriptFileName, NULL, 0, NULL, noCalls, NULL, 0);
  2033. ret = true;
  2034. }
  2035. else
  2036. if(scriptFile)
  2037. {
  2038. // No compiled script, let's just try executing it
  2039. // directly... this is either a mission file, or maybe
  2040. // we're on a readonly volume.
  2041. #ifdef TORQUE_DEBUG
  2042. Con::printf("Executing %s.", scriptFileName);
  2043. #endif
  2044. CodeBlock *newCodeBlock = new CodeBlock();
  2045. StringTableEntry name = StringTable->insert(scriptFileName);
  2046. newCodeBlock->compileExec(name, script, noCalls, 0);
  2047. ret = true;
  2048. }
  2049. else
  2050. {
  2051. // Don't have anything.
  2052. Con::warnf(ConsoleLogEntry::Script, "Missing file: %s!", scriptFileName);
  2053. ret = false;
  2054. }
  2055. delete [] script;
  2056. execDepth--;
  2057. return ret;
  2058. }
  2059. DefineConsoleFunction( eval, const char*, ( const char* consoleString ), , "eval(consoleString)" )
  2060. {
  2061. return Con::evaluate(consoleString, false, NULL);
  2062. }
  2063. DefineConsoleFunction( getVariable, const char*, ( const char* varName ), , "(string varName)\n"
  2064. "@brief Returns the value of the named variable or an empty string if not found.\n\n"
  2065. "@varName Name of the variable to search for\n"
  2066. "@return Value contained by varName, \"\" if the variable does not exist\n"
  2067. "@ingroup Scripting")
  2068. {
  2069. return Con::getVariable(varName);
  2070. }
  2071. DefineConsoleFunction( setVariable, void, ( const char* varName, const char* value ), , "(string varName, string value)\n"
  2072. "@brief Sets the value of the named variable.\n\n"
  2073. "@param varName Name of the variable to locate\n"
  2074. "@param value New value of the variable\n"
  2075. "@return True if variable was successfully found and set\n"
  2076. "@ingroup Scripting")
  2077. {
  2078. return Con::setVariable(varName, value);
  2079. }
  2080. DefineConsoleFunction( isFunction, bool, ( const char* funcName ), , "(string funcName)"
  2081. "@brief Determines if a function exists or not\n\n"
  2082. "@param funcName String containing name of the function\n"
  2083. "@return True if the function exists, false if not\n"
  2084. "@ingroup Scripting")
  2085. {
  2086. return Con::isFunction(funcName);
  2087. }
  2088. DefineConsoleFunction( getFunctionPackage, const char*, ( const char* funcName ), , "(string funcName)"
  2089. "@brief Provides the name of the package the function belongs to\n\n"
  2090. "@param funcName String containing name of the function\n"
  2091. "@return The name of the function's package\n"
  2092. "@ingroup Packages")
  2093. {
  2094. Namespace::Entry* nse = Namespace::global()->lookup( StringTable->insert( funcName ) );
  2095. if( !nse )
  2096. return "";
  2097. return nse->mPackage;
  2098. }
  2099. DefineConsoleFunction( isMethod, bool, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  2100. "@brief Determines if a class/namespace method exists\n\n"
  2101. "@param namespace Class or namespace, such as Player\n"
  2102. "@param method Name of the function to search for\n"
  2103. "@return True if the method exists, false if not\n"
  2104. "@ingroup Scripting\n")
  2105. {
  2106. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  2107. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  2108. if( !nse )
  2109. return false;
  2110. return true;
  2111. }
  2112. DefineConsoleFunction( getMethodPackage, const char*, ( const char* nameSpace, const char* method ), , "(string namespace, string method)"
  2113. "@brief Provides the name of the package the method belongs to\n\n"
  2114. "@param namespace Class or namespace, such as Player\n"
  2115. "@param method Name of the funciton to search for\n"
  2116. "@return The name of the method's package\n"
  2117. "@ingroup Packages")
  2118. {
  2119. Namespace* ns = Namespace::find( StringTable->insert( nameSpace ) );
  2120. if( !ns )
  2121. return "";
  2122. Namespace::Entry* nse = ns->lookup( StringTable->insert( method ) );
  2123. if( !nse )
  2124. return "";
  2125. return nse->mPackage;
  2126. }
  2127. DefineConsoleFunction( isDefined, bool, ( const char* varName, const char* varValue ), ("") , "(string varName)"
  2128. "@brief Determines if a variable exists and contains a value\n"
  2129. "@param varName Name of the variable to search for\n"
  2130. "@return True if the variable was defined in script, false if not\n"
  2131. "@tsexample\n"
  2132. "isDefined( \"$myVar\" );\n"
  2133. "@endtsexample\n\n"
  2134. "@ingroup Scripting")
  2135. {
  2136. if(dStrIsEmpty(varName))
  2137. {
  2138. Con::errorf("isDefined() - did you forget to put quotes around the variable name?");
  2139. return false;
  2140. }
  2141. StringTableEntry name = StringTable->insert(varName);
  2142. // Deal with <var>.<value>
  2143. if (dStrchr(name, '.'))
  2144. {
  2145. static char scratchBuffer[4096];
  2146. S32 len = dStrlen(name);
  2147. AssertFatal(len < sizeof(scratchBuffer)-1, "isDefined() - name too long");
  2148. dMemcpy(scratchBuffer, name, len+1);
  2149. char * token = dStrtok(scratchBuffer, ".");
  2150. if (!token || token[0] == '\0')
  2151. return false;
  2152. StringTableEntry objName = StringTable->insert(token);
  2153. // Attempt to find the object
  2154. SimObject * obj = Sim::findObject(objName);
  2155. // If we didn't find the object then we can safely
  2156. // assume that the field variable doesn't exist
  2157. if (!obj)
  2158. return false;
  2159. // Get the name of the field
  2160. token = dStrtok(0, ".\0");
  2161. if (!token)
  2162. return false;
  2163. while (token != NULL)
  2164. {
  2165. StringTableEntry valName = StringTable->insert(token);
  2166. // Store these so we can restore them after we search for the variable
  2167. bool saveModStatic = obj->canModStaticFields();
  2168. bool saveModDyn = obj->canModDynamicFields();
  2169. // Set this so that we can search both static and dynamic fields
  2170. obj->setModStaticFields(true);
  2171. obj->setModDynamicFields(true);
  2172. const char* value = obj->getDataField(valName, 0);
  2173. // Restore our mod flags to be safe
  2174. obj->setModStaticFields(saveModStatic);
  2175. obj->setModDynamicFields(saveModDyn);
  2176. if (!value)
  2177. {
  2178. obj->setDataField(valName, 0, varValue);
  2179. return false;
  2180. }
  2181. else
  2182. {
  2183. // See if we are field on a field
  2184. token = dStrtok(0, ".\0");
  2185. if (token)
  2186. {
  2187. // The previous field must be an object
  2188. obj = Sim::findObject(value);
  2189. if (!obj)
  2190. return false;
  2191. }
  2192. else
  2193. {
  2194. if (dStrlen(value) > 0)
  2195. return true;
  2196. else if (!dStrIsEmpty(varValue))
  2197. {
  2198. obj->setDataField(valName, 0, varValue);
  2199. }
  2200. }
  2201. }
  2202. }
  2203. }
  2204. else if (name[0] == '%')
  2205. {
  2206. // Look up a local variable
  2207. if( gEvalState.getStackDepth() > 0 )
  2208. {
  2209. Dictionary::Entry* ent = gEvalState.getCurrentFrame().lookup(name);
  2210. if (ent)
  2211. return true;
  2212. else if (!dStrIsEmpty(varValue))
  2213. {
  2214. gEvalState.getCurrentFrame().setVariable(name, varValue);
  2215. }
  2216. }
  2217. else
  2218. Con::errorf("%s() - no local variable frame.", __FUNCTION__);
  2219. }
  2220. else if (name[0] == '$')
  2221. {
  2222. // Look up a global value
  2223. Dictionary::Entry* ent = gEvalState.globalVars.lookup(name);
  2224. if (ent)
  2225. return true;
  2226. else if (!dStrIsEmpty(varValue))
  2227. {
  2228. gEvalState.globalVars.setVariable(name, varValue);
  2229. }
  2230. }
  2231. else
  2232. {
  2233. // Is it an object?
  2234. if (dStrcmp(varName, "0") && dStrcmp(varName, "") && (Sim::findObject(varName) != NULL))
  2235. return true;
  2236. else if (!dStrIsEmpty(varValue))
  2237. {
  2238. Con::errorf("%s() - can't assign a value to a variable of the form \"%s\"", __FUNCTION__, varValue);
  2239. }
  2240. }
  2241. return false;
  2242. }
  2243. //-----------------------------------------------------------------------------
  2244. DefineConsoleFunction( isCurrentScriptToolScript, bool, (), , "()"
  2245. "Returns true if the calling script is a tools script.\n"
  2246. "@hide")
  2247. {
  2248. return Con::isCurrentScriptToolScript();
  2249. }
  2250. DefineConsoleFunction( getModNameFromPath, const char *, ( const char* path ), , "(string path)"
  2251. "@brief Attempts to extract a mod directory from path. Returns empty string on failure.\n\n"
  2252. "@param File path of mod folder\n"
  2253. "@note This is no longer relevant in Torque 3D (which does not use mod folders), should be deprecated\n"
  2254. "@internal")
  2255. {
  2256. StringTableEntry modPath = Con::getModNameFromPath(path);
  2257. return modPath ? modPath : "";
  2258. }
  2259. //-----------------------------------------------------------------------------
  2260. DefineConsoleFunction( pushInstantGroup, void, ( String group ),("") , "([group])"
  2261. "@brief Pushes the current $instantGroup on a stack "
  2262. "and sets it to the given value (or clears it).\n\n"
  2263. "@note Currently only used for editors\n"
  2264. "@ingroup Editors\n"
  2265. "@internal")
  2266. {
  2267. if( group.size() > 0 )
  2268. Con::pushInstantGroup( group );
  2269. else
  2270. Con::pushInstantGroup();
  2271. }
  2272. DefineConsoleFunction( popInstantGroup, void, (), , "()"
  2273. "@brief Pop and restore the last setting of $instantGroup off the stack.\n\n"
  2274. "@note Currently only used for editors\n\n"
  2275. "@ingroup Editors\n"
  2276. "@internal")
  2277. {
  2278. Con::popInstantGroup();
  2279. }
  2280. //-----------------------------------------------------------------------------
  2281. DefineConsoleFunction( getPrefsPath, const char *, ( const char* relativeFileName ), (""), "([relativeFileName])"
  2282. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2283. "@internal")
  2284. {
  2285. const char *filename = Platform::getPrefsPath(relativeFileName);
  2286. if(filename == NULL || *filename == 0)
  2287. return "";
  2288. return filename;
  2289. }
  2290. //-----------------------------------------------------------------------------
  2291. ConsoleFunction( execPrefs, bool, 2, 4, "( string relativeFileName, bool noCalls=false, bool journalScript=false )"
  2292. "@brief Manually execute a special script file that contains game or editor preferences\n\n"
  2293. "@param relativeFileName Name and path to file from project folder\n"
  2294. "@param noCalls Deprecated\n"
  2295. "@param journalScript Deprecated\n"
  2296. "@return True if script was successfully executed\n"
  2297. "@note Appears to be useless in Torque 3D, should be deprecated\n"
  2298. "@ingroup Scripting")
  2299. {
  2300. const char *filename = Platform::getPrefsPath(argv[1]);
  2301. if(filename == NULL || *filename == 0)
  2302. return false;
  2303. // Scripts do this a lot, so we may as well help them out
  2304. if(! Platform::isFile(filename) && ! Torque::FS::IsFile(filename))
  2305. return true;
  2306. argv[0] = "exec";
  2307. argv[1] = filename;
  2308. return dAtob(Con::execute(argc, argv));
  2309. }
  2310. //-----------------------------------------------------------------------------
  2311. DefineConsoleFunction( export, void, ( const char* pattern, const char* filename, bool append ), ( "", false ),
  2312. "Write out the definitions of all global variables matching the given name @a pattern.\n"
  2313. "If @a fileName is not \"\", the variable definitions are written to the specified file. Otherwise the "
  2314. "definitions will be printed to the console.\n\n"
  2315. "The output are valid TorqueScript statements that can be executed to restore the global variable "
  2316. "values.\n\n"
  2317. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2318. "@param filename %Path of the file to which to write the definitions or \"\" to write the definitions "
  2319. "to the console.\n"
  2320. "@param append If true and @a fileName is not \"\", then the definitions are appended to the specified file. "
  2321. "Otherwise existing contents of the file (if any) will be overwritten.\n\n"
  2322. "@tsexample\n"
  2323. "// Write out all preference variables to a prefs.cs file.\n"
  2324. "export( \"$prefs::*\", \"prefs.cs\" );\n"
  2325. "@endtsexample\n\n"
  2326. "@ingroup Scripting" )
  2327. {
  2328. if( filename && filename[ 0 ] )
  2329. {
  2330. #ifndef TORQUE2D_TOOLS_FIXME
  2331. if(Con::expandScriptFilename(scriptFilenameBuffer, sizeof(scriptFilenameBuffer), filename))
  2332. filename = scriptFilenameBuffer;
  2333. #else
  2334. filename = Platform::getPrefsPath( filename );
  2335. if(filename == NULL || *filename == 0)
  2336. return;
  2337. #endif
  2338. }
  2339. else
  2340. filename = NULL;
  2341. gEvalState.globalVars.exportVariables( pattern, filename, append );
  2342. }
  2343. //-----------------------------------------------------------------------------
  2344. DefineEngineFunction( deleteVariables, void, ( const char* pattern ),,
  2345. "Undefine all global variables matching the given name @a pattern.\n"
  2346. "@param pattern A global variable name pattern. Must begin with '$'.\n"
  2347. "@tsexample\n"
  2348. "// Define a global variable in the \"My\" namespace.\n"
  2349. "$My::Variable = \"value\";\n\n"
  2350. "// Undefine all variable in the \"My\" namespace.\n"
  2351. "deleteVariables( \"$My::*\" );\n"
  2352. "@endtsexample\n\n"
  2353. "@see strIsMatchExpr\n"
  2354. "@ingroup Scripting" )
  2355. {
  2356. gEvalState.globalVars.deleteVariables( pattern );
  2357. }
  2358. //-----------------------------------------------------------------------------
  2359. DefineConsoleFunction( trace, void, ( bool enable ), ( true ),
  2360. "Enable or disable tracing in the script code VM.\n\n"
  2361. "When enabled, the script code runtime will trace the invocation and returns "
  2362. "from all functions that are called and log them to the console. This is helpful in "
  2363. "observing the flow of the script program.\n\n"
  2364. "@param enable New setting for script trace execution, on by default.\n"
  2365. "@ingroup Debugging" )
  2366. {
  2367. gEvalState.traceOn = enable;
  2368. Con::printf( "Console trace %s", gEvalState.traceOn ? "enabled." : "disabled." );
  2369. }
  2370. //-----------------------------------------------------------------------------
  2371. #if defined(TORQUE_DEBUG) || !defined(TORQUE_SHIPPING)
  2372. DefineConsoleFunction( debug, void, (),,
  2373. "Drops the engine into the native C++ debugger.\n\n"
  2374. "This function triggers a debug break and drops the process into the IDE's debugger. If the process is not "
  2375. "running with a debugger attached it will generate a runtime error on most platforms.\n\n"
  2376. "@note This function is not available in shipping builds."
  2377. "@ingroup Debugging" )
  2378. {
  2379. Platform::debugBreak();
  2380. }
  2381. #endif
  2382. //-----------------------------------------------------------------------------
  2383. DefineEngineFunction( isShippingBuild, bool, (),,
  2384. "Test whether the engine has been compiled with TORQUE_SHIPPING, i.e. in a form meant for final release.\n\n"
  2385. "@return True if this is a shipping build; false otherwise.\n\n"
  2386. "@ingroup Platform" )
  2387. {
  2388. #ifdef TORQUE_SHIPPING
  2389. return true;
  2390. #else
  2391. return false;
  2392. #endif
  2393. }
  2394. //-----------------------------------------------------------------------------
  2395. DefineEngineFunction( isDebugBuild, bool, (),,
  2396. "Test whether the engine has been compiled with TORQUE_DEBUG, i.e. if it includes debugging functionality.\n\n"
  2397. "@return True if this is a debug build; false otherwise.\n\n"
  2398. "@ingroup Platform" )
  2399. {
  2400. #ifdef TORQUE_DEBUG
  2401. return true;
  2402. #else
  2403. return false;
  2404. #endif
  2405. }
  2406. //-----------------------------------------------------------------------------
  2407. DefineEngineFunction( isToolBuild, bool, (),,
  2408. "Test whether the engine has been compiled with TORQUE_TOOLS, i.e. if it includes tool-related functionality.\n\n"
  2409. "@return True if this is a tool build; false otherwise.\n\n"
  2410. "@ingroup Platform" )
  2411. {
  2412. #ifdef TORQUE_TOOLS
  2413. return true;
  2414. #else
  2415. return false;
  2416. #endif
  2417. }