consoleFunctions.cpp 93 KB

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