util.c 11 KB

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