MiscFunctions.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "../common/debug.h"
  17. #include "../common/Log.h"
  18. #include "MiscFunctions.h"
  19. #include <string.h>
  20. #include <time.h>
  21. #include <math.h>
  22. #include <chrono>
  23. #include <random>
  24. #ifndef WIN32
  25. #include <netinet/in.h>
  26. #include <sys/socket.h>
  27. #endif
  28. #include <iostream>
  29. #include <iomanip>
  30. #ifdef WIN32
  31. #include <io.h>
  32. #endif
  33. #include "../common/timer.h"
  34. #include "../common/seperator.h"
  35. #include "../common/packet_dump.h"
  36. #include <algorithm>
  37. using namespace std;
  38. #ifndef PATCHER
  39. extern map<int16, int16> EQOpcodeVersions;
  40. #endif
  41. #ifdef WIN32
  42. #include <WinSock2.h>
  43. #include <windows.h>
  44. #define snprintf _snprintf
  45. #define vsnprintf _vsnprintf
  46. #define strncasecmp _strnicmp
  47. #define strcasecmp _stricmp
  48. #else
  49. #include <stdlib.h>
  50. #include <ctype.h>
  51. #include <stdarg.h>
  52. #include <sys/types.h>
  53. #include <sys/time.h>
  54. #ifdef FREEBSD //Timothy Whitman - January 7, 2003
  55. #include <sys/socket.h>
  56. #include <netinet/in.h>
  57. #endif
  58. #include <sys/stat.h>
  59. #include <unistd.h>
  60. #include <netdb.h>
  61. #include <errno.h>
  62. #endif
  63. void CoutTimestamp(bool ms) {
  64. time_t rawtime;
  65. struct tm* gmt_t;
  66. time(&rawtime);
  67. gmt_t = gmtime(&rawtime);
  68. struct timeval read_time;
  69. gettimeofday(&read_time,0);
  70. cout << (gmt_t->tm_year + 1900) << "/" << setw(2) << setfill('0') << (gmt_t->tm_mon + 1) << "/" << setw(2) << setfill('0') << gmt_t->tm_mday << " " << setw(2) << setfill('0') << gmt_t->tm_hour << ":" << setw(2) << setfill('0') << gmt_t->tm_min << ":" << setw(2) << setfill('0') << gmt_t->tm_sec;
  71. if (ms)
  72. cout << "." << setw(3) << setfill('0') << (read_time.tv_usec / 1000);
  73. cout << " GMT";
  74. }
  75. string loadInt32String(uchar* buffer, int16 buffer_size, int16* pos, EQ2_32BitString* eq_string){
  76. buffer += *pos;
  77. int32 size = *(int32*)buffer;
  78. if((size + *pos + sizeof(int16)) > buffer_size){
  79. cout << "Error in loadInt32String: Corrupt packet.\n";
  80. return string("");
  81. }
  82. buffer += sizeof(int32);
  83. string ret((char*)buffer, 0, size);
  84. if(eq_string){
  85. eq_string->size = size;
  86. eq_string->data = ret;
  87. }
  88. *pos += (size + sizeof(int32));
  89. return ret;
  90. }
  91. string loadInt16String(uchar* buffer, int16 buffer_size, int16* pos, EQ2_16BitString* eq_string){
  92. buffer += *pos;
  93. int16 size = *(int16*)buffer;
  94. if((size + *pos + sizeof(int16))> buffer_size){
  95. cout << "Error in loadInt16String: Corrupt packet.\n";
  96. return string("");
  97. }
  98. buffer += sizeof(int16);
  99. string ret((char*)buffer, 0, size);
  100. if(eq_string){
  101. eq_string->size = size;
  102. eq_string->data = ret;
  103. }
  104. *pos += (size + sizeof(int16));
  105. return ret;
  106. }
  107. string loadInt8String(uchar* buffer, int16 buffer_size, int16* pos, EQ2_8BitString* eq_string){
  108. buffer += *pos;
  109. int8 size = *(int8*)buffer;
  110. if((size + *pos + sizeof(int16)) > buffer_size){
  111. cout << "Error in loadInt8String: Corrupt packet.\n";
  112. return string("");
  113. }
  114. buffer += sizeof(int8);
  115. string ret((char*)buffer, 0, size);
  116. if(eq_string){
  117. eq_string->size = size;
  118. eq_string->data = ret;
  119. }
  120. *pos += (size + sizeof(int8));
  121. return ret;
  122. }
  123. sint16 storeInt32String(uchar* buffer, int16 buffer_size, string in_str){
  124. sint16 string_size = in_str.length();
  125. if((string_size + sizeof(int32)) > buffer_size)
  126. return -1;
  127. memcpy(buffer, &string_size, sizeof(int32));
  128. buffer += sizeof(int32);
  129. memcpy(buffer, in_str.c_str(), string_size);
  130. buffer += string_size;
  131. return (buffer_size - (string_size + sizeof(int32)));
  132. }
  133. sint16 storeInt16String(uchar* buffer, int16 buffer_size, string in_str){
  134. sint16 string_size = in_str.length();
  135. if((string_size + sizeof(int16)) > buffer_size)
  136. return -1;
  137. memcpy(buffer, &string_size, sizeof(int16));
  138. buffer += sizeof(int16);
  139. memcpy(buffer, in_str.c_str(), string_size);
  140. buffer += string_size;
  141. return (buffer_size - (string_size + sizeof(int16)));
  142. }
  143. sint16 storeInt8String(uchar* buffer, int16 buffer_size, string in_str){
  144. sint16 string_size = in_str.length();
  145. if((string_size + sizeof(int8)) > buffer_size)
  146. return -1;
  147. memcpy(buffer, &string_size, sizeof(int8));
  148. buffer += sizeof(int8);
  149. memcpy(buffer, in_str.c_str(), string_size);
  150. buffer += string_size;
  151. return (buffer_size - (string_size + sizeof(int8)));
  152. }
  153. sint32 filesize(FILE* fp) {
  154. #ifdef WIN32
  155. return _filelength(_fileno(fp));
  156. #else
  157. struct stat file_stat;
  158. fstat(fileno(fp), &file_stat);
  159. return (sint32) file_stat.st_size;
  160. #endif
  161. }
  162. int32 ResolveIP(const char* hostname, char* errbuf) {
  163. #ifdef WIN32
  164. static InitWinsock ws;
  165. #endif
  166. if (errbuf)
  167. errbuf[0] = 0;
  168. if (hostname == 0) {
  169. if (errbuf)
  170. snprintf(errbuf, ERRBUF_SIZE, "ResolveIP(): hostname == 0");
  171. return 0;
  172. }
  173. struct sockaddr_in server_sin;
  174. #ifdef WIN32
  175. PHOSTENT phostent = NULL;
  176. #else
  177. struct hostent *phostent = NULL;
  178. #endif
  179. server_sin.sin_family = AF_INET;
  180. if ((phostent = gethostbyname(hostname)) == NULL) {
  181. #ifdef WIN32
  182. if (errbuf)
  183. snprintf(errbuf, ERRBUF_SIZE, "Unable to get the host name. Error: %i", WSAGetLastError());
  184. #else
  185. if (errbuf)
  186. snprintf(errbuf, ERRBUF_SIZE, "Unable to get the host name. Error: %s", strerror(errno));
  187. #endif
  188. return 0;
  189. }
  190. #ifdef WIN32
  191. memcpy ((char FAR *)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length);
  192. #else
  193. memcpy ((char*)&(server_sin.sin_addr), phostent->h_addr, phostent->h_length);
  194. #endif
  195. return server_sin.sin_addr.s_addr;
  196. }
  197. #ifdef WIN32
  198. InitWinsock::InitWinsock() {
  199. WORD version = MAKEWORD (1,1);
  200. WSADATA wsadata;
  201. WSAStartup (version, &wsadata);
  202. }
  203. InitWinsock::~InitWinsock() {
  204. WSACleanup();
  205. }
  206. #endif
  207. #ifndef WIN32
  208. const char * itoa(int value) {
  209. static char temp[_ITOA_BUFLEN];
  210. memset(temp, 0, _ITOA_BUFLEN);
  211. snprintf(temp, _ITOA_BUFLEN,"%d", value);
  212. return temp;
  213. }
  214. char * itoa(int value, char *result, int base) {
  215. char *ptr1, *ptr2;
  216. char c;
  217. int tmp_value;
  218. //need a valid base
  219. if (base < 2 || base > 36) {
  220. *result = '\0';
  221. return result;
  222. }
  223. ptr1 = ptr2 = result;
  224. do {
  225. tmp_value = value;
  226. value /= base;
  227. *ptr1++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
  228. }
  229. while (value > 0);
  230. //apply a negative sign if need be
  231. if (tmp_value < 0)
  232. *ptr1++ = '-';
  233. *ptr1-- = '\0';
  234. while (ptr2 < ptr1) {
  235. c = *ptr1;
  236. *ptr1-- = *ptr2;
  237. *ptr2++ = c;
  238. }
  239. return result;
  240. }
  241. #endif
  242. /*
  243. * solar: generate a random integer in the range low-high
  244. * this should be used instead of the rand()%limit method
  245. */
  246. int MakeRandomInt(int low, int high)
  247. {
  248. return (int)MakeRandomFloat((double)low, (double)high + 0.999);
  249. }
  250. int32 hextoi(char* num) {
  251. int len = strlen(num);
  252. if (len < 3)
  253. return 0;
  254. if (num[0] != '0' || (num[1] != 'x' && num[1] != 'X'))
  255. return 0;
  256. int32 ret = 0;
  257. int mul = 1;
  258. for (int i=len-1; i>=2; i--) {
  259. if (num[i] >= 'A' && num[i] <= 'F')
  260. ret += ((num[i] - 'A') + 10) * mul;
  261. else if (num[i] >= 'a' && num[i] <= 'f')
  262. ret += ((num[i] - 'a') + 10) * mul;
  263. else if (num[i] >= '0' && num[i] <= '9')
  264. ret += (num[i] - '0') * mul;
  265. else
  266. return 0;
  267. mul *= 16;
  268. }
  269. return ret;
  270. }
  271. int64 hextoi64(char* num) {
  272. int len = strlen(num);
  273. if (len < 3)
  274. return 0;
  275. if (num[0] != '0' || (num[1] != 'x' && num[1] != 'X'))
  276. return 0;
  277. int64 ret = 0;
  278. int mul = 1;
  279. for (int i=len-1; i>=2; i--) {
  280. if (num[i] >= 'A' && num[i] <= 'F')
  281. ret += ((num[i] - 'A') + 10) * mul;
  282. else if (num[i] >= 'a' && num[i] <= 'f')
  283. ret += ((num[i] - 'a') + 10) * mul;
  284. else if (num[i] >= '0' && num[i] <= '9')
  285. ret += (num[i] - '0') * mul;
  286. else
  287. return 0;
  288. mul *= 16;
  289. }
  290. return ret;
  291. }
  292. float MakeRandomFloat(float low, float high) {
  293. // Handle edge case where range is zero or inverted
  294. float diff = high - low;
  295. if(!diff) return low;
  296. if (low == high) return low;
  297. if (low > high) std::swap(low, high);
  298. // Use a thread-local random generator for thread safety
  299. thread_local std::mt19937 generator(std::random_device{}()); // Seed once per thread
  300. std::uniform_real_distribution<float> distribution(low, high);
  301. return distribution(generator);
  302. }
  303. int32 GenerateEQ2Color(float* r, float* g, float* b){
  304. int8 rgb[4] = {0};
  305. rgb[0] = (int8)((*r)*255);
  306. rgb[1] = (int8)((*b)*255);
  307. rgb[2] = (int8)((*g)*255);
  308. int32 color = 0;
  309. memcpy(&color, rgb, sizeof(int32));
  310. return color;
  311. }
  312. int32 GenerateEQ2Color(float* rgb[3]){
  313. return GenerateEQ2Color(rgb[0], rgb[1], rgb[2]);
  314. }
  315. int8 MakeInt8(float* input){
  316. float input2 = *input;
  317. if(input2 < 0)
  318. input2 *= -1;
  319. return (int8)(input2*255);
  320. }
  321. vector<string>* SplitString(string str, char delim){
  322. vector<string>* results = new vector<string>;
  323. int32 pos;
  324. while((pos = str.find_first_of(delim))!= str.npos){
  325. if(pos > 0){
  326. results->push_back(str.substr(0,pos));
  327. }
  328. if(str.length() > pos)
  329. str = str.substr(pos+1);
  330. else
  331. break;
  332. }
  333. if(str.length() > 0)
  334. results->push_back(str);
  335. return results;
  336. }
  337. bool Unpack(uchar* data, uchar* dst, int16 dstLen, int16 version, bool reverse){
  338. int32 srcLen = 0;
  339. memcpy(&srcLen, data, sizeof(int32));
  340. return Unpack(srcLen, data + 4, dst, dstLen, version, reverse);
  341. }
  342. bool Unpack(int32 srcLen, uchar* data, uchar* dst, int16 dstLen, int16 version, bool reverse) {
  343. // int32 srcLen = 0;
  344. // memcpy(&srcLen, data, sizeof(int32));
  345. // data+=4;
  346. if(reverse)
  347. Reverse(data, srcLen);
  348. int16 pos = 0;
  349. int16 real_pos = 0;
  350. while(srcLen && pos < dstLen) {
  351. if(srcLen >= 0 && !srcLen--)
  352. return false;
  353. int8 code = data[real_pos++];
  354. if(code >= 128) {
  355. for(int8 index=0; index<7; index++) {
  356. if(code & 1) {
  357. if(pos >= dstLen)
  358. return false;
  359. if(srcLen >= 0 && !srcLen--)
  360. return false;
  361. dst[pos++] = data[real_pos++];
  362. } else {
  363. if(pos < dstLen) dst[pos++] = 0;
  364. }
  365. code >>= 1;
  366. }
  367. } else {
  368. if(pos + code > dstLen)
  369. return false;
  370. memset(dst+pos, 0, code);
  371. pos+=code;
  372. }
  373. }
  374. return srcLen <= 0;
  375. }
  376. int32 Pack(uchar* data, uchar* src, int16 srcLen, int16 dstLen, int16 version, bool reverse) {
  377. int16 real_pos = 4;
  378. int32 pos = 0;
  379. int32 code = 0;
  380. int codePos = 0;
  381. int codeLen = 0;
  382. int8 zeroLen = 0;
  383. memset(data,0,dstLen);
  384. if (version > 1 && version <= 374)
  385. reverse = false;
  386. while(pos < srcLen) {
  387. if(src[pos] || codeLen) {
  388. if(!codeLen) {
  389. /*if(zeroLen > 5) {
  390. data[real_pos++] = zeroLen;
  391. zeroLen = 0;
  392. }
  393. else if(zeroLen >= 1 && zeroLen<=5){
  394. for(;zeroLen>0;zeroLen--)
  395. codeLen++;
  396. }*/
  397. if (zeroLen) {
  398. data[real_pos++] = zeroLen;
  399. zeroLen = 0;
  400. }
  401. codePos = real_pos;
  402. code = 0;
  403. data[real_pos++] = 0;
  404. }
  405. if(src[pos]) {
  406. data[real_pos++] = src[pos];
  407. code |= 0x80;
  408. }
  409. code >>= 1;
  410. codeLen++;
  411. if(codeLen == 7) {
  412. data[codePos] = int8(0x80 | code);
  413. codeLen = 0;
  414. }
  415. } else {
  416. if(zeroLen == 0x7F) {
  417. data[real_pos++] = zeroLen;
  418. zeroLen = 0;
  419. }
  420. zeroLen++;
  421. }
  422. pos++;
  423. }
  424. if(codeLen) {
  425. code >>= (7 - codeLen);
  426. data[codePos] = int8(0x80 | code);
  427. } else if(zeroLen) {
  428. data[real_pos++] = zeroLen;
  429. }
  430. if(reverse)
  431. Reverse(data + 4, real_pos - 4);
  432. int32 dataLen = real_pos - 4;
  433. memcpy(&data[0], &dataLen, sizeof(int32));
  434. return dataLen + 4;
  435. }
  436. void Reverse(uchar* input, int32 srcLen){
  437. int16 real_pos = 0;
  438. int16 orig_pos = 0;
  439. int8 reverse_count = 0;
  440. while(srcLen > 0 && srcLen < 0xFFFFFFFF){ // XXX it was >=0 before. but i think it was a bug
  441. int8 code = input[real_pos++];
  442. srcLen--;
  443. if(code >= 128) {
  444. for(int8 index=0; index<7; index++) {
  445. if(code & 1) {
  446. if(srcLen >= 0 && !srcLen--)
  447. return;
  448. real_pos++;
  449. reverse_count++;
  450. }
  451. code >>= 1;
  452. }
  453. }
  454. if(reverse_count > 0){
  455. int8 tmp_data[8] = {0};
  456. for(int8 i=0;i<reverse_count;i++){
  457. tmp_data[i] = input[orig_pos + reverse_count-i];
  458. }
  459. memcpy(input + orig_pos + 1, tmp_data, reverse_count);
  460. reverse_count = 0;
  461. }
  462. orig_pos = real_pos;
  463. }
  464. }
  465. void MovementDecode(uchar* dst, uchar* newval, uchar* orig, int16 len){
  466. int16 pos = len;
  467. while(pos--)
  468. dst[pos] = newval[pos] ^ orig[pos];
  469. }
  470. void Decode(uchar* dst, uchar* src, int16 len) {
  471. int16 pos = len;
  472. while(pos--)
  473. dst[pos] ^= src[pos];
  474. memcpy(src, dst, len);
  475. }
  476. void Encode(uchar* dst, uchar* src, int16 len) {
  477. uchar* data = new uchar[len];
  478. int16 pos = len;
  479. while(pos--)
  480. data[pos] = int8(src[pos] ^ dst[pos]);
  481. memcpy(src, dst, len);
  482. memcpy(dst, data, len);
  483. safe_delete_array(data);
  484. }
  485. float TransformToFloat(sint16 data, int8 bits) {
  486. return (float)(data / (float)(1 << bits));
  487. }
  488. sint16 TransformFromFloat(float data, int8 bits) {
  489. return (sint16)(data * (1 << bits));
  490. }
  491. void SetColor(EQ2_Color* color, long data){
  492. memcpy(color, &data, sizeof(EQ2_Color));
  493. }
  494. string ToUpper(string input){
  495. string ret = input;
  496. transform(input.begin(), input.end(), ret.begin(), ::toupper);
  497. return ret;
  498. }
  499. string ToLower(string input){
  500. string ret = input;
  501. transform(input.begin(), input.end(), ret.begin(), ::tolower);
  502. return ret;
  503. }
  504. int32 ParseIntValue(string input){
  505. int32 ret = 0xFFFFFFFF;
  506. try{
  507. if(input.length() > 0){
  508. ret = atoul(input.c_str());
  509. }
  510. }
  511. catch(...){}
  512. return ret;
  513. }
  514. int64 ParseLongLongValue(string input){
  515. int64 ret = 0xFFFFFFFFFFFFFFFF;
  516. try{
  517. if(input.length() > 0){
  518. #ifdef WIN32
  519. ret = _strtoui64(input.c_str(), NULL, 10);
  520. #else
  521. ret = strtoull(input.c_str(), 0, 10);
  522. #endif
  523. }
  524. }
  525. catch(...){}
  526. return ret;
  527. }
  528. map<string, string> TranslateBrokerRequest(string request){
  529. map<string, string> ret;
  530. string key;
  531. string value;
  532. int32 start_pos = 0;
  533. int32 end_pos = 0;
  534. int32 pos = request.find("=");
  535. bool str_val = false;
  536. while(pos < 0xFFFFFFFF){
  537. str_val = false;
  538. key = request.substr(start_pos, pos-start_pos);
  539. if(request.find("|", pos) == pos+1){
  540. pos++;
  541. end_pos = request.find("|", pos+1);
  542. str_val = true;
  543. }
  544. else
  545. end_pos = request.find(" ", pos);
  546. if(end_pos < 0xFFFFFFFF){
  547. value = request.substr(pos+1, end_pos-pos-1);
  548. start_pos = end_pos+1;
  549. if(str_val){
  550. start_pos++;
  551. ret[key] = ToLower(value);
  552. }
  553. else
  554. ret[key] = value;
  555. pos = request.find("=", start_pos);
  556. }
  557. else{
  558. value = request.substr(pos+1);
  559. if(str_val){
  560. start_pos++;
  561. ret[key] = ToLower(value);
  562. }
  563. else
  564. ret[key] = value;
  565. break;
  566. }
  567. }
  568. return ret;
  569. }
  570. int8 CheckOverLoadSize(int32 val){
  571. int8 ret = 1;
  572. if(val >= 0xFFFF) //int32
  573. ret = sizeof(int16) + sizeof(int32);
  574. else if(val >= 0xFF)
  575. ret = sizeof(int8) + sizeof(int16);
  576. return ret;
  577. }
  578. int8 DoOverLoad(int32 val, uchar* data){
  579. int8 ret = 1;
  580. if(val >= 0xFFFF){ //int32
  581. memset(data, 0xFF, sizeof(int16));
  582. memcpy(data + sizeof(int16), &val, sizeof(int32));
  583. ret = sizeof(int16) + sizeof(int32);
  584. }
  585. else if(val >= 0xFF){ //int16
  586. memset(data, 0xFF, sizeof(int8));
  587. memcpy(data + sizeof(int8), &val, sizeof(int16));
  588. ret = sizeof(int8) + sizeof(int16);
  589. }
  590. else
  591. memcpy(data, &val, sizeof(int8));
  592. return ret;
  593. }
  594. /* Treats contiguous spaces as one space. */
  595. int32 CountWordsInString(const char* text) {
  596. int32 words = 0;
  597. if (text && strlen(text) > 0) {
  598. bool on_word = false;
  599. for (int32 i = 0; i < strlen(text); i++) {
  600. char letter = text[i];
  601. if (on_word && !((letter >= 48 && letter <= 57) || (letter >= 65 && letter <= 90) || (letter >= 97 && letter <= 122)))
  602. on_word = false;
  603. else if (!on_word && ((letter >= 48 && letter <= 57) || (letter >= 65 && letter <= 90) || (letter >= 97 && letter <= 122))){
  604. on_word = true;
  605. words++;
  606. }
  607. }
  608. }
  609. return words;
  610. }
  611. bool IsNumber(const char *num) {
  612. size_t len, i;
  613. if (!num)
  614. return false;
  615. len = strlen(num);
  616. if (len == 0)
  617. return false;
  618. for (i = 0; i < len; i++) {
  619. if (!isdigit(num[i]))
  620. return false;
  621. }
  622. return true;
  623. }
  624. void PrintSep(Seperator *sep, const char *name) {
  625. int32 i = 0;
  626. LogWrite(MISC__DEBUG, 0, "Misc", "Printing sep %s", name ? name : "No Name");
  627. if (!sep)
  628. LogWrite(MISC__DEBUG, 0, "Misc", "\tSep is null");
  629. else {
  630. while (sep->arg[i] && strlen(sep->arg[i]) > 0) {
  631. LogWrite(MISC__DEBUG, 0, "Misc", "\t%i => %s", i, sep->arg[i]);
  632. i++;
  633. }
  634. }
  635. }
  636. #define INI_IGNORE(c) (c == '\n' || c == '\r' || c == '#')
  637. static bool INIGoToSection(FILE *f, const char *section) {
  638. size_t size = strlen(section) + 3;
  639. char line[256], *buf, *tmp;
  640. bool found = false;
  641. if ((buf = (char *)malloc(size)) == NULL) {
  642. fprintf(stderr, "%s: %u: Unable to allocate %zu bytes\n", __FUNCTION__, __LINE__, size);
  643. return false;
  644. }
  645. sprintf(buf, "[%s]", section);
  646. while (fgets(line, sizeof(line), f) != NULL) {
  647. if (INI_IGNORE(line[0]))
  648. continue;
  649. if (line[0] == '[') {
  650. if ((tmp = strstr(line, "\n")) != NULL)
  651. *tmp = '\0';
  652. if ((tmp = strstr(line, "\r")) != NULL)
  653. *tmp = '\0';
  654. if (strcasecmp(buf, line) == 0) {
  655. found = true;
  656. break;
  657. }
  658. }
  659. }
  660. free(buf);
  661. return found;
  662. }
  663. static char * INIFindValue(FILE *f, const char *section, const char *property) {
  664. char line[256], *key, *val;
  665. if (section != NULL && !INIGoToSection(f, section))
  666. return NULL;
  667. while (fgets(line, sizeof(line), f) != NULL) {
  668. if (INI_IGNORE(line[0]))
  669. continue;
  670. if (section != NULL && line[0] == '[')
  671. return NULL;
  672. if ((key = strtok(line, "=")) == NULL)
  673. continue;
  674. if (strcasecmp(key, property) == 0) {
  675. val = strtok(NULL, "\n\r");
  676. if (val == NULL)
  677. return NULL;
  678. return strdup(val);
  679. }
  680. }
  681. return NULL;
  682. }
  683. bool INIReadInt(FILE *f, const char *section, const char *property, int *out) {
  684. char *value;
  685. rewind(f);
  686. if ((value = INIFindValue(f, section, property)) == NULL)
  687. return false;
  688. if (!IsNumber(value)) {
  689. free(value);
  690. return false;
  691. }
  692. *out = atoi(value);
  693. free(value);
  694. return true;
  695. }
  696. bool INIReadBool(FILE *f, const char *section, const char *property, bool *out) {
  697. char *value;
  698. rewind(f);
  699. if ((value = INIFindValue(f, section, property)) == NULL)
  700. return false;
  701. *out = (strcasecmp(value, "1") == 0 || strcasecmp(value, "true") == 0 || strcasecmp(value, "on") == 0 || strcasecmp(value, "yes") == 0);
  702. free(value);
  703. return true;
  704. }
  705. string GetDeviceName(string device) {
  706. if (device == "chemistry_table")
  707. device = "Chemistry Table";
  708. else if (device == "work_desk")
  709. device = "Engraved Desk";
  710. else if (device == "forge")
  711. device = "Forge";
  712. else if (device == "stove and keg")
  713. device = "Stove & Keg";
  714. else if (device == "sewing_table")
  715. device = "Sewing Table & Mannequin";
  716. else if (device == "woodworking_table")
  717. device = "Woodworking Table";
  718. else if (device == "work_bench")
  719. device = "Work Bench";
  720. else if (device == "crafting_intro_anvil")
  721. device = "Mender's Anvil";
  722. return device;
  723. }
  724. int32 GetDeviceID(string device) {
  725. if (device == "Chemistry Table")
  726. return 3;
  727. else if (device == "Engraved Desk")
  728. return 4;
  729. else if (device == "Forge")
  730. return 2;
  731. else if (device == "Stove & Keg")
  732. return 7;
  733. else if (device == "Sewing Table & Mannequin")
  734. return 1;
  735. else if (device == "Woodworking Table")
  736. return 6;
  737. else if (device == "Work Bench")
  738. return 5;
  739. else if (device == "Mender's Anvil")
  740. return 0xFFFFFFFF;
  741. return 0;
  742. }
  743. int16 GetItemPacketType(int32 version) {
  744. int16 item_version;
  745. if (version >= 64707)
  746. item_version = 0x5CFE;
  747. else if (version >= 63119)
  748. item_version = 0x56FE;
  749. else if (version >= 60024)
  750. item_version = 0x51FE;
  751. else if (version >= 57107)
  752. item_version = 0x4CFE;
  753. else if (version >= 57048)
  754. item_version = 0x48FE;
  755. else if (version >= 1199)
  756. item_version = 0x44FE;
  757. else if (version >= 1195)
  758. item_version = 0x40FE;
  759. else if (version >= 1193)
  760. item_version = 0x3FFE;
  761. else if (version >= 1190)
  762. item_version = 0x3EFE;
  763. else if (version >= 1188)
  764. item_version = 0x3DFE;
  765. else if (version >= 1096)
  766. item_version = 0x35FE;
  767. else if (version >= 1027)
  768. item_version = 0x31FE;
  769. else if (version >= 1008)
  770. item_version = 0x2CFE;
  771. else if (version >= 927)
  772. item_version = 0x23FE;
  773. else if (version >= 893)
  774. item_version = 0x22FE;
  775. else if (version >= 860)
  776. item_version = 0x20FE;
  777. else if (version > 546)
  778. item_version = 0x1CFE;
  779. else
  780. item_version = 0;
  781. return item_version;
  782. }
  783. #ifndef PATCHER
  784. int16 GetOpcodeVersion(int16 version) {
  785. int16 ret = version;
  786. int16 version1 = 0;
  787. int16 version2 = 0;
  788. map<int16, int16>::iterator itr;
  789. for (itr = EQOpcodeVersions.begin(); itr != EQOpcodeVersions.end(); itr++) {
  790. version1 = itr->first;
  791. version2 = itr->second;
  792. if (version >= version1 && version <= version2) {
  793. ret = version1;
  794. break;
  795. }
  796. }
  797. return ret;
  798. }
  799. #endif
  800. void SleepMS(int32 milliseconds) {
  801. #if defined(_WIN32)
  802. Sleep(milliseconds);
  803. #else
  804. usleep(milliseconds * 1000);
  805. #endif
  806. }
  807. size_t
  808. strlcpy(char *dst, const char *src, size_t size) {
  809. char *d = dst;
  810. const char *s = src;
  811. size_t n = size;
  812. if (n != 0 && --n != 0) {
  813. do {
  814. if ((*d++ = *s++) == 0)
  815. break;
  816. } while (--n != 0);
  817. }
  818. if (n == 0) {
  819. if (size != 0)
  820. *d = '\0';
  821. while (*s++)
  822. ;
  823. }
  824. return(s - src - 1);
  825. }
  826. float short_to_float(const ushort x) { // IEEE-754 16-bit floating-point format (without infinity): 1-5-10, exp-15, +-131008.0, +-6.1035156E-5, +-5.9604645E-8, 3.311 digits
  827. const uint32 e = (x & 0x7C00) >> 10; // exponent
  828. const uint32 m = (x & 0x03FF) << 13; // mantissa
  829. const uint32 v = as_uint((float)m) >> 23; // evil log2 bit hack to count leading zeros in denormalized format
  830. return as_float((x & 0x8000) << 16 | (e != 0) * ((e + 112) << 23 | m) | ((e == 0) & (m != 0)) * ((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000))); // sign : normalized : denormalized
  831. }
  832. uint32 float_to_int(const float x) { // IEEE-754 16-bit floating-point format (without infinity): 1-5-10, exp-15, +-131008.0, +-6.1035156E-5, +-5.9604645E-8, 3.311 digits
  833. const uint32 b = as_uint(x) + 0x00001000; // round-to-nearest-even: add last bit after truncated mantissa
  834. const uint32 e = (b & 0x7F800000) >> 23; // exponent
  835. const uint32 m = b & 0x007FFFFF; // mantissa; in line below: 0x007FF000 = 0x00800000-0x00001000 = decimal indicator flag - initial rounding
  836. return (b & 0x80000000) >> 16 | (e > 112)* ((((e - 112) << 10) & 0x7C00) | m >> 13) | ((e < 113) & (e > 101))* ((((0x007FF000 + m) >> (125 - e)) + 1) >> 1) | (e > 143) * 0x7FFF; // sign : normalized : denormalized : saturate
  837. }
  838. uint32 as_uint(const float x) {
  839. return *(uint32*)&x;
  840. }
  841. float as_float(const uint32 x) {
  842. return *(float*)&x;
  843. }
  844. // Function to get the current timestamp in milliseconds
  845. int64 getCurrentTimestamp() {
  846. auto now = std::chrono::steady_clock::now();
  847. auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  848. return duration.count();
  849. }
  850. std::tuple<int, int, int, int> convertTimestampDuration(int64 total_seconds) {
  851. std::chrono::milliseconds duration(total_seconds);
  852. // Convert to days, hours, minutes, and seconds
  853. auto days = std::chrono::duration_cast<std::chrono::duration<int, std::ratio<86400000>>>(duration);
  854. duration -= days;
  855. auto hours = std::chrono::duration_cast<std::chrono::hours>(duration);
  856. duration -= hours;
  857. auto minutes = std::chrono::duration_cast<std::chrono::minutes>(duration);
  858. duration -= minutes;
  859. auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
  860. // Return the result as a tuple
  861. return std::make_tuple(days.count(), hours.count(), minutes.count(), seconds.count());
  862. }