util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 3; c-file-style: "linux" -*- */
  2. //
  3. // Copyright (c) 2009, Wei Mingzhi <whistler_wmz@users.sf.net>.
  4. // Portions Copyright (c) 2004, Pierre-Marie Baty.
  5. // Portions Copyright (c) 2009, netwan.
  6. //
  7. // All rights reserved.
  8. //
  9. // This file is part of SDLPAL.
  10. //
  11. // SDLPAL is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. #include "util.h"
  25. #include "input.h"
  26. #include "global.h"
  27. #include "palcfg.h"
  28. #include "midi.h"
  29. #if SDL_VERSION_ATLEAST(2, 0, 0)
  30. #include "SDL_video.h"
  31. #include "SDL_messagebox.h"
  32. #endif
  33. void
  34. trim(
  35. char *str
  36. )
  37. /*++
  38. Purpose:
  39. Remove the leading and trailing spaces in a string.
  40. Parameters:
  41. str - the string to proceed.
  42. Return value:
  43. None.
  44. --*/
  45. {
  46. int pos = 0;
  47. char *dest = str;
  48. //
  49. // skip leading blanks
  50. //
  51. while (str[pos] <= ' ' && str[pos] > 0)
  52. pos++;
  53. while (str[pos])
  54. {
  55. *(dest++) = str[pos];
  56. pos++;
  57. }
  58. *(dest--) = '\0'; // store the null
  59. //
  60. // remove trailing blanks
  61. //
  62. while (dest >= str && *dest <= ' ' && *dest > 0)
  63. *(dest--) = '\0';
  64. }
  65. char *
  66. va(
  67. const char *format,
  68. ...
  69. )
  70. /*++
  71. Purpose:
  72. Does a varargs printf into a temp buffer, so we don't need to have
  73. varargs versions of all text functions.
  74. Parameters:
  75. format - the format string.
  76. Return value:
  77. Pointer to the result string.
  78. --*/
  79. {
  80. static char string[256];
  81. va_list argptr;
  82. va_start(argptr, format);
  83. vsnprintf(string, 256, format, argptr);
  84. va_end(argptr);
  85. return string;
  86. }
  87. /*
  88. * RNG code based on RACC by Pierre-Marie Baty.
  89. * http://racc.bots-united.com
  90. *
  91. * Copyright (c) 2004, Pierre-Marie Baty
  92. * All rights reserved.
  93. *
  94. * Redistribution and use in source and binary forms, with or
  95. * without modification, are permitted provided that the following
  96. * conditions are met:
  97. *
  98. * Redistributions of source code must retain the above copyright
  99. * notice, this list of conditions and the following disclaimer.
  100. *
  101. * Redistributions in binary form must reproduce the above copyright
  102. * notice, this list of conditions and the following disclaimer in
  103. * the documentation and/or other materials provided with the
  104. * distribution.
  105. *
  106. * Neither the name of the RACC nor the names of its contributors
  107. * may be used to endorse or promote products derived from this
  108. * software without specific prior written permission.
  109. *
  110. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  111. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  112. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  113. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  114. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  115. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  116. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  117. * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  118. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  119. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  120. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  121. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  122. * POSSIBILITY OF SUCH DAMAGE.
  123. */
  124. //
  125. // Our random number generator's seed.
  126. //
  127. static int glSeed = 0;
  128. static void
  129. lsrand(
  130. unsigned int iInitialSeed
  131. )
  132. /*++
  133. Purpose:
  134. This function initializes the random seed based on the initial seed value passed in the
  135. iInitialSeed parameter.
  136. Parameters:
  137. [IN] iInitialSeed - The initial random seed.
  138. Return value:
  139. None.
  140. --*/
  141. {
  142. //
  143. // fill in the initial seed of the random number generator
  144. //
  145. glSeed = 1664525L * iInitialSeed + 1013904223L;
  146. }
  147. static int
  148. lrand(
  149. void
  150. )
  151. /*++
  152. Purpose:
  153. This function is the equivalent of the rand() standard C library function, except that
  154. whereas rand() works only with short integers (i.e. not above 32767), this function is
  155. able to generate 32-bit random numbers.
  156. Parameters:
  157. None.
  158. Return value:
  159. The generated random number.
  160. --*/
  161. {
  162. if (glSeed == 0) // if the random seed isn't initialized...
  163. lsrand((unsigned int)time(NULL)); // initialize it first
  164. glSeed = 1664525L * glSeed + 1013904223L; // do some twisted math (infinite suite)
  165. return ((glSeed >> 1) + 1073741824L); // and return the result.
  166. }
  167. int
  168. RandomLong(
  169. int from,
  170. int to
  171. )
  172. /*++
  173. Purpose:
  174. This function returns a random integer number between (and including) the starting and
  175. ending values passed by parameters from and to.
  176. Parameters:
  177. from - the starting value.
  178. to - the ending value.
  179. Return value:
  180. The generated random number.
  181. --*/
  182. {
  183. if (to <= from)
  184. return from;
  185. return from + lrand() / (INT_MAX / (to - from + 1));
  186. }
  187. float
  188. RandomFloat(
  189. float from,
  190. float to
  191. )
  192. /*++
  193. Purpose:
  194. This function returns a random floating-point number between (and including) the starting
  195. and ending values passed by parameters from and to.
  196. Parameters:
  197. from - the starting value.
  198. to - the ending value.
  199. Return value:
  200. The generated random number.
  201. --*/
  202. {
  203. if (to <= from)
  204. return from;
  205. return from + (float)lrand() / (INT_MAX / (to - from));
  206. }
  207. void
  208. UTIL_Delay(
  209. unsigned int ms
  210. )
  211. {
  212. unsigned int t = SDL_GetTicks() + ms;
  213. while (PAL_PollEvent(NULL));
  214. while (!SDL_TICKS_PASSED(SDL_GetTicks(), t))
  215. {
  216. SDL_Delay(1);
  217. while (PAL_PollEvent(NULL));
  218. }
  219. MIDI_CheckLoop();
  220. }
  221. void
  222. TerminateOnError(
  223. const char *fmt,
  224. ...
  225. )
  226. // This function terminates the game because of an error and
  227. // prints the message string pointed to by fmt both in the
  228. // console and in a messagebox.
  229. {
  230. va_list argptr;
  231. char string[256];
  232. extern VOID PAL_Shutdown(VOID);
  233. // concatenate all the arguments in one string
  234. va_start(argptr, fmt);
  235. vsnprintf(string, sizeof(string), fmt, argptr);
  236. va_end(argptr);
  237. fprintf(stderr, "\nFATAL ERROR: %s\n", string);
  238. #if SDL_VERSION_ATLEAST(2, 0, 0)
  239. {
  240. extern SDL_Window *gpWindow;
  241. SDL_ShowSimpleMessageBox(0, "FATAL ERROR", string, gpWindow);
  242. }
  243. #else
  244. # if defined(_WIN32)
  245. MessageBoxA(0, string, "FATAL ERROR", MB_ICONERROR);
  246. # elif defined(__linux__)
  247. system(va("beep; xmessage -center \"FATAL ERROR: %s\"", string));
  248. # elif defined(__SYMBIAN32__)
  249. UTIL_WriteLog(LOG_DEBUG,"[0x%08x][%s][%s] - %s",(long)TerminateOnError,"TerminateOnError",__FILE__, string);
  250. SDL_Delay(3000);
  251. # endif
  252. #endif
  253. #ifdef _DEBUG
  254. assert(!"TerminateOnError()"); // allows jumping to debugger
  255. #endif
  256. PAL_Shutdown();
  257. #if defined (NDS)
  258. while (1);
  259. #else
  260. exit(255);
  261. #endif
  262. }
  263. void *
  264. UTIL_malloc(
  265. size_t buffer_size
  266. )
  267. {
  268. // handy wrapper for operations we always forget, like checking malloc's returned pointer.
  269. void *buffer;
  270. // first off, check if buffer size is valid
  271. if (buffer_size == 0)
  272. TerminateOnError("UTIL_malloc() called with invalid buffer size: %d\n", buffer_size);
  273. buffer = malloc(buffer_size); // allocate real memory space
  274. // last check, check if malloc call succeeded
  275. if (buffer == NULL)
  276. TerminateOnError("UTIL_malloc() failure for %d bytes (out of memory?)\n", buffer_size);
  277. return buffer; // nothing went wrong, so return buffer pointer
  278. }
  279. void *
  280. UTIL_calloc(
  281. size_t n,
  282. size_t size
  283. )
  284. {
  285. // handy wrapper for operations we always forget, like checking calloc's returned pointer.
  286. void *buffer;
  287. // first off, check if buffer size is valid
  288. if (n == 0 || size == 0)
  289. TerminateOnError ("UTIL_calloc() called with invalid parameters\n");
  290. buffer = calloc(n, size); // allocate real memory space
  291. // last check, check if malloc call succeeded
  292. if (buffer == NULL)
  293. TerminateOnError("UTIL_calloc() failure for %d bytes (out of memory?)\n", size * n);
  294. return buffer; // nothing went wrong, so return buffer pointer
  295. }
  296. FILE *
  297. UTIL_OpenRequiredFile(
  298. LPCSTR lpszFileName
  299. )
  300. /*++
  301. Purpose:
  302. Open a required file. If fails, quit the program.
  303. Parameters:
  304. [IN] lpszFileName - file name to open.
  305. Return value:
  306. Pointer to the file.
  307. --*/
  308. {
  309. return UTIL_OpenRequiredFileForMode(lpszFileName, "rb");
  310. }
  311. FILE *
  312. UTIL_OpenRequiredFileForMode(
  313. LPCSTR lpszFileName,
  314. LPCSTR szMode
  315. )
  316. /*++
  317. Purpose:
  318. Open a required file. If fails, quit the program.
  319. Parameters:
  320. [IN] lpszFileName - file name to open.
  321. [IN] szMode - file open mode.
  322. Return value:
  323. Pointer to the file.
  324. --*/
  325. {
  326. FILE *fp = UTIL_OpenFileForMode(lpszFileName, szMode);
  327. if (fp == NULL)
  328. {
  329. extern SDL_Window *gpWindow;
  330. SDL_MessageBoxButtonData buttons[2] = { { 0, 0, "Yes" }, { 0, 1, "No"} };
  331. SDL_MessageBoxData mbd = { SDL_MESSAGEBOX_ERROR, gpWindow, "FATAL ERROR", va("File not found: %s!\nLaunch setting dialog on next start?\n", lpszFileName), 2, buttons, NULL };
  332. int btnid;
  333. if (SDL_ShowMessageBox(&mbd, &btnid) == 0 && btnid == 0)
  334. {
  335. gConfig.fLaunchSetting = TRUE;
  336. PAL_SaveConfig();
  337. }
  338. PAL_Shutdown();
  339. exit(255);
  340. }
  341. return fp;
  342. }
  343. FILE *
  344. UTIL_OpenFile(
  345. LPCSTR lpszFileName
  346. )
  347. /*++
  348. Purpose:
  349. Open a file. If fails, return NULL.
  350. Parameters:
  351. [IN] lpszFileName - file name to open.
  352. Return value:
  353. Pointer to the file.
  354. --*/
  355. {
  356. return UTIL_OpenFileForMode(lpszFileName, "rb");
  357. }
  358. FILE *
  359. UTIL_OpenFileForMode(
  360. LPCSTR lpszFileName,
  361. LPCSTR szMode
  362. )
  363. /*++
  364. Purpose:
  365. Open a file. If fails, return NULL.
  366. Parameters:
  367. [IN] lpszFileName - file name to open.
  368. [IN] szMode - file open mode.
  369. Return value:
  370. Pointer to the file.
  371. --*/
  372. {
  373. FILE *fp;
  374. fp = fopen(va("%s%s", gConfig.pszGamePath, lpszFileName), szMode);
  375. #ifndef _WIN32
  376. if (fp == NULL)
  377. {
  378. //
  379. // try to find the matching file in the directory.
  380. //
  381. struct dirent **list;
  382. int n = scandir(gConfig.pszGamePath, &list, 0, alphasort);
  383. while (n-- > 0)
  384. {
  385. if (!fp && strcasecmp(list[n]->d_name, lpszFileName) == 0)
  386. fp = fopen(va("%s%s", gConfig.pszGamePath, list[n]->d_name), szMode);
  387. free(list[n]);
  388. }
  389. free(list);
  390. }
  391. #endif
  392. return fp;
  393. }
  394. VOID
  395. UTIL_CloseFile(
  396. FILE *fp
  397. )
  398. /*++
  399. Purpose:
  400. Close a file.
  401. Parameters:
  402. [IN] fp - file handle to be closed.
  403. Return value:
  404. None.
  405. --*/
  406. {
  407. if (fp != NULL)
  408. {
  409. fclose(fp);
  410. }
  411. }
  412. #ifdef ENABLE_LOG
  413. static FILE *pLogFile = NULL;
  414. FILE *
  415. UTIL_OpenLog(
  416. VOID
  417. )
  418. {
  419. if ((pLogFile = fopen(va("%slog.txt", PAL_SAVE_PREFIX), "a+")) == NULL)
  420. {
  421. return NULL;
  422. }
  423. return pLogFile;
  424. }
  425. VOID
  426. UTIL_CloseLog(
  427. VOID
  428. )
  429. {
  430. if (pLogFile != NULL)
  431. {
  432. fclose(pLogFile);
  433. }
  434. }
  435. VOID
  436. UTIL_WriteLog(
  437. int Priority,
  438. const char *Fmt,
  439. ...
  440. )
  441. {
  442. va_list vaa;
  443. time_t lTime;
  444. struct tm *curTime;
  445. char szDateBuf[260];
  446. time(&lTime);
  447. if ((Priority < LOG_EMERG) || (Priority >= LOG_LAST_PRIORITY))
  448. {
  449. return;
  450. }
  451. curTime = localtime(&lTime);
  452. strftime(szDateBuf, 128, "%Y-%m-%d %H:%M:%S", curTime);
  453. szDateBuf[strlen(szDateBuf) - 1] = '\0'; //remove the
  454. va_start(vaa,Fmt);
  455. fprintf(pLogFile, "[%s]", szDateBuf);
  456. vfprintf(pLogFile, Fmt, vaa);
  457. fprintf(pLogFile, "\n");
  458. fflush(pLogFile);
  459. va_end(vaa);
  460. }
  461. #endif