consoleFunctions.cpp 92 KB

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