util.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. #if PAL_HAS_NATIVEMIDI
  27. #include "midi.h"
  28. #endif
  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. #if PAL_HAS_NATIVEMIDI
  220. MIDI_CheckLoop();
  221. #endif
  222. }
  223. void
  224. TerminateOnError(
  225. const char *fmt,
  226. ...
  227. )
  228. // This function terminates the game because of an error and
  229. // prints the message string pointed to by fmt both in the
  230. // console and in a messagebox.
  231. {
  232. va_list argptr;
  233. char string[256];
  234. extern VOID PAL_Shutdown(VOID);
  235. // concatenate all the arguments in one string
  236. va_start(argptr, fmt);
  237. vsnprintf(string, sizeof(string), fmt, argptr);
  238. va_end(argptr);
  239. fprintf(stderr, "\nFATAL ERROR: %s\n", string);
  240. #if SDL_VERSION_ATLEAST(2, 0, 0)
  241. {
  242. extern SDL_Window *gpWindow;
  243. SDL_ShowSimpleMessageBox(0, "FATAL ERROR", string, gpWindow);
  244. }
  245. #else
  246. # if defined(_WIN32)
  247. MessageBoxA(0, string, "FATAL ERROR", MB_ICONERROR);
  248. # elif defined(__linux__)
  249. system(va("beep; xmessage -center \"FATAL ERROR: %s\"", string));
  250. # elif defined(__SYMBIAN32__)
  251. UTIL_WriteLog(LOG_DEBUG,"[0x%08x][%s][%s] - %s",(long)TerminateOnError,"TerminateOnError",__FILE__, string);
  252. SDL_Delay(3000);
  253. # endif
  254. #endif
  255. #ifdef _DEBUG
  256. assert(!"TerminateOnError()"); // allows jumping to debugger
  257. #endif
  258. PAL_Shutdown();
  259. #if defined (NDS)
  260. while (1);
  261. #else
  262. exit(255);
  263. #endif
  264. }
  265. void *
  266. UTIL_malloc(
  267. size_t buffer_size
  268. )
  269. {
  270. // handy wrapper for operations we always forget, like checking malloc's returned pointer.
  271. void *buffer;
  272. // first off, check if buffer size is valid
  273. if (buffer_size == 0)
  274. TerminateOnError("UTIL_malloc() called with invalid buffer size: %d\n", buffer_size);
  275. buffer = malloc(buffer_size); // allocate real memory space
  276. // last check, check if malloc call succeeded
  277. if (buffer == NULL)
  278. TerminateOnError("UTIL_malloc() failure for %d bytes (out of memory?)\n", buffer_size);
  279. return buffer; // nothing went wrong, so return buffer pointer
  280. }
  281. void *
  282. UTIL_calloc(
  283. size_t n,
  284. size_t size
  285. )
  286. {
  287. // handy wrapper for operations we always forget, like checking calloc's returned pointer.
  288. void *buffer;
  289. // first off, check if buffer size is valid
  290. if (n == 0 || size == 0)
  291. TerminateOnError ("UTIL_calloc() called with invalid parameters\n");
  292. buffer = calloc(n, size); // allocate real memory space
  293. // last check, check if malloc call succeeded
  294. if (buffer == NULL)
  295. TerminateOnError("UTIL_calloc() failure for %d bytes (out of memory?)\n", size * n);
  296. return buffer; // nothing went wrong, so return buffer pointer
  297. }
  298. FILE *
  299. UTIL_OpenRequiredFile(
  300. LPCSTR lpszFileName
  301. )
  302. /*++
  303. Purpose:
  304. Open a required file. If fails, quit the program.
  305. Parameters:
  306. [IN] lpszFileName - file name to open.
  307. Return value:
  308. Pointer to the file.
  309. --*/
  310. {
  311. return UTIL_OpenRequiredFileForMode(lpszFileName, "rb");
  312. }
  313. FILE *
  314. UTIL_OpenRequiredFileForMode(
  315. LPCSTR lpszFileName,
  316. LPCSTR szMode
  317. )
  318. /*++
  319. Purpose:
  320. Open a required file. If fails, quit the program.
  321. Parameters:
  322. [IN] lpszFileName - file name to open.
  323. [IN] szMode - file open mode.
  324. Return value:
  325. Pointer to the file.
  326. --*/
  327. {
  328. FILE *fp = UTIL_OpenFileForMode(lpszFileName, szMode);
  329. if (fp == NULL)
  330. {
  331. TerminateOnError("File not found: %s!\n", lpszFileName);
  332. }
  333. return fp;
  334. }
  335. FILE *
  336. UTIL_OpenFile(
  337. LPCSTR lpszFileName
  338. )
  339. /*++
  340. Purpose:
  341. Open a file. If fails, return NULL.
  342. Parameters:
  343. [IN] lpszFileName - file name to open.
  344. Return value:
  345. Pointer to the file.
  346. --*/
  347. {
  348. return UTIL_OpenFileForMode(lpszFileName, "rb");
  349. }
  350. FILE *
  351. UTIL_OpenFileForMode(
  352. LPCSTR lpszFileName,
  353. LPCSTR szMode
  354. )
  355. /*++
  356. Purpose:
  357. Open a file. If fails, return NULL.
  358. Parameters:
  359. [IN] lpszFileName - file name to open.
  360. [IN] szMode - file open mode.
  361. Return value:
  362. Pointer to the file.
  363. --*/
  364. {
  365. FILE *fp;
  366. fp = fopen(va("%s%s", PAL_PREFIX, lpszFileName), szMode);
  367. #ifndef _WIN32
  368. if (fp == NULL)
  369. {
  370. //
  371. // try to find the matching file in the directory.
  372. //
  373. struct dirent **list;
  374. int n = scandir(PAL_PREFIX, &list, 0, alphasort);
  375. while (n-- > 0)
  376. {
  377. if (!fp && strcasecmp(list[n]->d_name, lpszFileName) == 0)
  378. fp = fopen(va("%s%s", PAL_PREFIX, list[n]->d_name), szMode);
  379. free(list[n]);
  380. }
  381. free(list);
  382. }
  383. #endif
  384. return fp;
  385. }
  386. VOID
  387. UTIL_CloseFile(
  388. FILE *fp
  389. )
  390. /*++
  391. Purpose:
  392. Close a file.
  393. Parameters:
  394. [IN] fp - file handle to be closed.
  395. Return value:
  396. None.
  397. --*/
  398. {
  399. if (fp != NULL)
  400. {
  401. fclose(fp);
  402. }
  403. }
  404. #ifdef ENABLE_LOG
  405. static FILE *pLogFile = NULL;
  406. FILE *
  407. UTIL_OpenLog(
  408. VOID
  409. )
  410. {
  411. if ((pLogFile = fopen(_PATH_LOG, "a+")) == NULL)
  412. {
  413. return NULL;
  414. }
  415. return pLogFile;
  416. }
  417. VOID
  418. UTIL_CloseLog(
  419. VOID
  420. )
  421. {
  422. if (pLogFile != NULL)
  423. {
  424. fclose(pLogFile);
  425. }
  426. }
  427. VOID
  428. UTIL_WriteLog(
  429. int Priority,
  430. const char *Fmt,
  431. ...
  432. )
  433. {
  434. va_list vaa;
  435. time_t lTime;
  436. struct tm *curTime;
  437. char szDateBuf[260];
  438. time(&lTime);
  439. if ((Priority < LOG_EMERG) || (Priority >= LOG_LAST_PRIORITY))
  440. {
  441. return;
  442. }
  443. curTime = localtime(&lTime);
  444. strftime(szDateBuf, 128, "%Y-%m-%d %H:%M:%S", curTime);
  445. szDateBuf[strlen(szDateBuf) - 1] = '\0'; //remove the
  446. va_start(vaa,Fmt);
  447. fprintf(pLogFile, "[%s]", szDateBuf);
  448. vfprintf(pLogFile, Fmt, vaa);
  449. fprintf(pLogFile, "\n");
  450. fflush(pLogFile);
  451. va_end(vaa);
  452. }
  453. #endif