util.c 11 KB

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