util.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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_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. FILE *fp;
  312. fp = fopen(va("%s%s", PAL_PREFIX, lpszFileName), "rb");
  313. #ifndef _WIN32
  314. if (fp == NULL)
  315. {
  316. //
  317. // try converting the filename to upper-case.
  318. //
  319. char *pBuf = strdup(lpszFileName);
  320. char *p = pBuf;
  321. while (*p)
  322. {
  323. if (*p >= 'a' && *p <= 'z')
  324. {
  325. *p -= 'a' - 'A';
  326. }
  327. p++;
  328. }
  329. fp = fopen(va("%s%s", PAL_PREFIX, pBuf), "rb");
  330. free(pBuf);
  331. }
  332. #endif
  333. if (fp == NULL)
  334. {
  335. TerminateOnError("File not found: %s!\n", lpszFileName);
  336. }
  337. return fp;
  338. }
  339. FILE *
  340. UTIL_OpenFile(
  341. LPCSTR lpszFileName
  342. )
  343. /*++
  344. Purpose:
  345. Open a file. If fails, return NULL.
  346. Parameters:
  347. [IN] lpszFileName - file name to open.
  348. Return value:
  349. Pointer to the file.
  350. --*/
  351. {
  352. FILE *fp;
  353. fp = fopen(va("%s%s", PAL_PREFIX, lpszFileName), "rb");
  354. #ifndef _WIN32
  355. if (fp == NULL)
  356. {
  357. //
  358. // try converting the filename to upper-case.
  359. //
  360. char *pBuf = strdup(lpszFileName);
  361. char *p = pBuf;
  362. while (*p)
  363. {
  364. *p++ = toupper(*p);
  365. }
  366. fp = fopen(va("%s%s", PAL_PREFIX, pBuf), "rb");
  367. free(pBuf);
  368. }
  369. #endif
  370. return fp;
  371. }
  372. VOID
  373. UTIL_CloseFile(
  374. FILE *fp
  375. )
  376. /*++
  377. Purpose:
  378. Close a file.
  379. Parameters:
  380. [IN] fp - file handle to be closed.
  381. Return value:
  382. None.
  383. --*/
  384. {
  385. if (fp != NULL)
  386. {
  387. fclose(fp);
  388. }
  389. }
  390. #ifdef ENABLE_LOG
  391. static FILE *pLogFile = NULL;
  392. FILE *
  393. UTIL_OpenLog(
  394. VOID
  395. )
  396. {
  397. if ((pLogFile = fopen(_PATH_LOG, "a+")) == NULL)
  398. {
  399. return NULL;
  400. }
  401. return pLogFile;
  402. }
  403. VOID
  404. UTIL_CloseLog(
  405. VOID
  406. )
  407. {
  408. if (pLogFile != NULL)
  409. {
  410. fclose(pLogFile);
  411. }
  412. }
  413. VOID
  414. UTIL_WriteLog(
  415. int Priority,
  416. const char *Fmt,
  417. ...
  418. )
  419. {
  420. va_list vaa;
  421. time_t lTime;
  422. struct tm *curTime;
  423. char szDateBuf[260];
  424. time(&lTime);
  425. if ((Priority < LOG_EMERG) || (Priority >= LOG_LAST_PRIORITY))
  426. {
  427. return;
  428. }
  429. curTime = localtime(&lTime);
  430. strftime(szDateBuf, 128, "%Y-%m-%d %H:%M:%S", curTime);
  431. szDateBuf[strlen(szDateBuf) - 1] = '\0'; //remove the
  432. va_start(vaa,Fmt);
  433. fprintf(pLogFile, "[%s]", szDateBuf);
  434. vfprintf(pLogFile, Fmt, vaa);
  435. fprintf(pLogFile, "\n");
  436. fflush(pLogFile);
  437. va_end(vaa);
  438. }
  439. #endif