Debian Codegraph @

port/sdl/hamfake.cpp

raw symbols SCIP
1 /*
2 * PROPRIETARY INFORMATION. This software is proprietary to POWDER
3 * Development, and is not to be reproduced, transmitted, or disclosed
4 * in any way without written permission.
5 *
6 * Produced by: Jeff Lait
7 *
8 * POWDER Development
9 *
10 * NAME: hamfake.cpp ( POWDER Library, C++ )
11 *
12 * COMMENTS:
13 * This file implements all the fake ham functions.
14 * It also stores the global state of the hardware.
15 */
16
17 #ifdef WIN32
18 #pragma comment(lib, "SDL.lib")
19 #pragma comment(lib, "SDLmain.lib")
20 #endif
21
22 #ifdef _WIN32_WCE
23 #include <windows.h>
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <memory.h>
29 #include <assert.h>
30
31 #ifndef ANDROID
32 #include <iostream>
33 #endif
34
35 using namespace std;
36
37 #include "mygba.h"
38 #include "hamfake.h"
39
40 #ifndef USE_VIRTUAL_SCREEN
41 #include "SDL.h"
42 #endif
43
44 #include "../../gfxengine.h"
45 #include "../../bmp.h"
46 #include "../../assert.h"
47 #include "../../buf.h"
48
49 #include "../../gfx/icon_sdl.bmp.c"
50
51 #ifdef USE_VIRTUAL_SCREEN
52 #include "../../queue.h"
53 #endif
54
55 #define SRAMSIZE 65536
56
57 #define KEY_REPEAT_INITIAL 15
58 #define KEY_REPEAT_AFTER 7
59
60 #define SAVENAME "powder.sav"
61 #define TRANSACTIONNAME "recover.sav"
62
63 //
64 // Global GBA state:
65 //
66 void (*glb_vblcallback)() = 0;
67
68 #ifndef USE_VIRTUAL_SCREEN
69 SDL_Surface *glbVideoSurface;
70 #else
71 // This must be static for thread safety!
72 SCREENDATA glbOurScreen;
73 LOCK glbScreenLock;
74 int glbOurScreenId = 1;
75 QUEUE<int> glbOurEventQueue(1); // Just used for pings, don't accum
76 QUEUE<int> glbOurActionQueue;
77 QUEUE<int> glbOurSpellQueue;
78 QUEUE<int> glbOurButtonQueue;
79 QUEUE<int> glbOurShutdownQueue;
80 QUEUE<int> glbOurResurrectQueue;
81 QUEUE<int> glbOurDirQueue;
82 QUEUE<int> glbOurInputQueue;
83 char *glbOurDataPath = 0;
84
85 #endif
86 bool glbFullScreen = false;
87
88 #ifdef USING_TILE10
89 int glbScreenWidth = 320;
90 int glbScreenHeight = 240;
91 int glbTileWidth = 10;
92 int glbTileHeight = 10;
93 #else
94 int glbScreenWidth = 256;
95 int glbScreenHeight = 192;
96 int glbTileWidth = 8;
97 int glbTileHeight = 8;
98 #endif
99
100 int glbScaleFactor = 1;
101 int glbScreenFudgeX = 0;
102 int glbScreenFudgeY = 0;
103
104 // These are set by another thread.
105 volatile int glbStylusX = 0, glbStylusY = 0;
106 volatile bool glbStylusState = false;
107 volatile bool glbExternalActionsEnabled = false;
108 volatile bool glbIsInventoryMode = false;
109 volatile bool glbIsForceQuit = false;
110 volatile bool glbIsPortrait = true;
111 volatile bool glbRevertDefault = false;
112 volatile bool glbHasBeenShook = true;
113
114 #ifndef HAS_KEYBOARD
115 volatile bool glbFakeButtonState[NUM_FAKE_BUTTONS];
116 #endif
117
118 tile_info_ptr glbTheTileSet = 0;
119
120 #define TILEWIDTH (glbTileWidth)
121 #define TILEHEIGHT (glbTileHeight)
122
123 #define HAM_SCRW (TILEWIDTH*HAM_SCRW_T)
124 #define HAM_SCRH (TILEWIDTH*HAM_SCRH_T)
125
126 struct SPRITEDATA
127 {
128 bool active;
129 int x, y;
130 u8 *data;
131 };
132
133 SPRITEDATA *glbSpriteList;
134
135 #define MAX_SPRITES 128
136
137 // Do we have an extra tileset loaded?
138 bool ham_extratileset = false;
139
140 // Keyboard state:
141 #ifndef USE_VIRTUAL_SCREEN
142 bool glb_keystate[SDLK_LAST];
143 #endif
144
145 // Key to push
146 int glb_keypusher = 0;
147 int glb_keypusherraw = 0;
148 // Frame to push on.
149 int glb_keypushtime = 0;
150
151 int glb_keybuf[16];
152 s8 glb_keybufentry = -1;
153
154 int glb_keymod = 0;
155
156 // Background state:
157 bg_info ham_bg[4];
158
159 // Always set from vblanks.
160 volatile bool glb_isnewframe = 0;
161 bool glb_isdirty = false;
162
163 u8 glb_palette[2048];
164
165 // Mode 3 screen - a raw 15bit bitmap.
166 u16 *glb_rawscreen = 0;
167
168 // Paletted version of screen which is scaled into final SDL surface
169 // We use u16 as the high bit selects whether to use sprite or
170 // global palette
171 u16 *glb_nativescreen = 0;
172
173 char glb_rawSRAM[SRAMSIZE];
174
175 int glb_videomode = -1;
176
177 #ifdef USE_VIRTUAL_SCREEN
178
179 volatile bool glb_isunlocked = false;
180
181 volatile bool glbCanSendEmail = true;
182
183 bool hamfake_isunlocked()
184 {
185 #ifdef ANDROID
186 // One reward of being an open platform which allows side
187 // loading is that we can bypass the whole Jobsian approach
188 // to revenue collection.
189 return true;
190 #else
191 return glb_isunlocked;
192 #endif
193 }
194
195 void hamfake_setunlocked(bool state)
196 {
197 glb_isunlocked = state;
198 }
199
200 volatile bool glb_allowunlocks = true;
201
202 bool hamfake_allowunlocks()
203 {
204 return glb_allowunlocks;
205 }
206
207 void hamfake_setallowunlocks(bool state)
208 {
209 glb_allowunlocks = state;
210 }
211
212 bool hamfake_cansendemail()
213 {
214 return glbCanSendEmail;
215 }
216
217 void hamfake_sendemail(const char *to, const char *subject, const char *body)
218 {
219 glbEmailData.myTo = to;
220 glbEmailData.mySubject = subject;
221 glbEmailData.myBody = body;
222 hamfake_buttonreq(8, 0);
223 glbEmailData.myTo = 0;
224 glbEmailData.mySubject = 0;
225 glbEmailData.myBody = 0;
226 }
227
228 //
229 // SCREENDATA_REF funcs
230 //
231
232 class SCREENDATA_REF
233 {
234 public:
235 void incRef();
236 void decRef();
237
238 const u8 *data() { return myData; }
239 // Steals ownership of data!
240 static SCREENDATA_REF *create(u8 *srcdata);
241 private:
242 SCREENDATA_REF();
243 virtual ~SCREENDATA_REF();
244
245 ATOMIC_INT32 myRef;
246 u8 *myData;
247 };
248
249 SCREENDATA_REF::SCREENDATA_REF()
250 {
251 myData = 0;
252 myRef.set(0);
253 }
254
255 SCREENDATA_REF::~SCREENDATA_REF()
256 {
257 delete [] myData;
258 }
259
260 void
261 SCREENDATA_REF::incRef()
262 {
263 myRef.add(1);
264 }
265
266 void
267 SCREENDATA_REF::decRef()
268 {
269 int ref = myRef.add(-1);
270
271 if (ref <= 0)
272 {
273 // Must be only owned by one thread!
274 delete this;
275 }
276 }
277
278 SCREENDATA_REF *
279 SCREENDATA_REF::create(u8 *data)
280 {
281 SCREENDATA_REF *result;
282
283 result = new SCREENDATA_REF;
284 result->incRef();
285 result->myData = data;
286
287 return result;
288
289 }
290
291 //
292 // SCREENDATA funcs
293 //
294 SCREENDATA::SCREENDATA()
295 {
296 myWidth = myHeight = myId = 0;
297 myRef = 0;
298 }
299
300 SCREENDATA::SCREENDATA(u8 *data, int w, int h, int i)
301 {
302 myWidth = w;
303 myHeight = h;
304 myId = i;
305 myRef = SCREENDATA_REF::create(data);
306 }
307
308 SCREENDATA::SCREENDATA(const SCREENDATA &data)
309 {
310 myRef = 0;
311 *this = data;
312 }
313
314 SCREENDATA &
315 SCREENDATA::operator=(const SCREENDATA &data)
316 {
317 if (this == &data)
318 return *this;
319
320 myWidth = data.myWidth;
321 myHeight = data.myHeight;
322 myId = data.myId;
323
324 if (data.myRef)
325 data.myRef->incRef();
326 if (myRef)
327 myRef->decRef();
328 myRef = data.myRef;
329
330 return *this;
331 }
332
333 SCREENDATA::~SCREENDATA()
334 {
335 if (myRef)
336 myRef->decRef();
337 }
338
339 const u8 *
340 SCREENDATA::data()
341 {
342 if (!myRef)
343 return 0;
344
345 return myRef->data();
346 }
347
348 void
349 hamfake_postScreenUpdate(u8 *data, int w, int h, int id)
350 {
351 SCREENDATA screen(data, w, h, id);
352
353 AUTOLOCK a(glbScreenLock);
354
355 glbOurScreen = screen;
356 }
357
358
359 void
360 hamfake_getActualScreen(SCREENDATA &screen)
361 {
362 AUTOLOCK a(glbScreenLock);
363 screen = glbOurScreen;
364 }
365
366 void
367 hamfake_setdatapath(const char *path)
368 {
369 if (glbOurDataPath)
370 free(glbOurDataPath);
371
372 glbOurDataPath = strdup(path);
373 }
374
375 void
376 hamfake_postdir(int dx, int dy)
377 {
378 glbOurDirQueue.flush();
379 glbOurDirQueue.append( ((dy + 2) << 2) + (dx + 1) );
380 }
381
382 void
383 hamfake_finishexternalinput()
384 {
385 glbOurInputQueue.append(0);
386 }
387
388 void
389 hamfake_flushdir()
390 {
391 glbOurDirQueue.flush();
392 }
393
394 bool
395 hamfake_externaldir(int &dx, int &dy)
396 {
397 int val;
398 if (glbOurDirQueue.remove(val))
399 {
400 dx = (val & 3) - 1;
401 dy = (val >> 2) - 2;
402 return true;
403 }
404 return false;
405 }
406
407 void
408 hamfake_postaction(int action, int spell)
409 {
410 if (action == 0 && spell == 0)
411 return;
412
413 // We do not want multiple actions!
414 glbOurActionQueue.flush();
415 glbOurSpellQueue.flush();
416
417 if (action != 0)
418 glbOurActionQueue.append(action);
419 if (spell != 0)
420 glbOurSpellQueue.append(spell);
421 }
422
423 void
424 hamfake_postorientation(bool isportrait)
425 {
426 glbIsPortrait = isportrait;
427 }
428
429 void
430 hamfake_revertdefault()
431 {
432 glbRevertDefault = true;
433 }
434
435 void
436 hamfake_postshake(bool isshook)
437 {
438 glbHasBeenShook = isshook;
439 }
440
441 bool
442 hamfake_hasbeenshaken()
443 {
444 bool result = glbHasBeenShook;
445 glbHasBeenShook = false;
446 return result;
447 }
448
449 INPUTDATA glbInputData;
450 EMAILDATA glbEmailData;
451
452 void
453 hamfake_buttonreq(int mode, int type)
454 {
455 int val;
456 val = (mode << 16) + type;
457
458 // Email and Keyboard inputs are locked.
459 if (mode == 7 || mode == 8)
460 glbOurInputQueue.flush();
461
462 glbOurButtonQueue.append(val);
463
464 if (mode == 7 || mode == 8)
465 {
466 glbOurInputQueue.waitAndRemove();
467 glbOurInputQueue.flush();
468 }
469 }
470
471 bool
472 hamfake_getbuttonreq(int &mode, int &type)
473 {
474 int val;
475
476 if (glbOurButtonQueue.remove(val))
477 {
478 mode = val >> 16;
479 type = val & 0xffff;
480 return true;
481 }
482 return false;
483 }
484
485 void
486 hamfake_externalaction(int &action, int &spell)
487 {
488 action = 0;
489 spell = 0;
490
491 glbOurActionQueue.remove(action);
492 glbOurSpellQueue.remove(spell);
493
494 glbOurActionQueue.flush();
495 glbOurSpellQueue.flush();
496 }
497
498 void
499 hamfake_enableexternalactions(bool allow)
500 {
501 glbExternalActionsEnabled = allow;
502 glbOurActionQueue.flush();
503 glbOurSpellQueue.flush();
504 }
505
506
507 bool
508 hamfake_externalactionsenabled()
509 {
510 return glbExternalActionsEnabled;
511 }
512
513 void
514 hamfake_setinventorymode(bool inventory)
515 {
516 glbIsInventoryMode = inventory;
517 }
518
519 #endif
520
521 bool
522 hamfake_isinventorymode()
523 {
524 return glbIsInventoryMode;
525 }
526
527 void
528 rebuildVideoSystemFromGlobals()
529 {
530 #ifndef USE_VIRTUAL_SCREEN
531 int flags = SDL_RESIZABLE;
532
533 if (glbFullScreen)
534 flags |= SDL_FULLSCREEN;
535
536 // Yes, we want a guaranteed 24bit video mode.
537 glbVideoSurface = SDL_SetVideoMode(glbScreenWidth, glbScreenHeight,
538 24, flags);
539
540 if (!glbVideoSurface)
541 {
542 fprintf(stderr, "Failed to create screen: %s\n",
543 SDL_GetError());
544 SDL_Quit();
545 exit(1);
546 }
547
548 // Setup our window environment.
549 SDL_WM_SetCaption("POWDER", 0);
550
551 // We want the cursor enabled now that you can click on stuff.
552 // SDL_ShowCursor(SDL_DISABLE);
553 #endif
554
555 glb_isdirty = true;
556 }
557
558 void
559 hamfake_setFullScreen(bool fullscreen)
560 {
561 // Pretty straight forward :>
562 glbFullScreen = fullscreen;
563
564 rebuildVideoSystemFromGlobals();
565 }
566
567 bool
568 hamfake_isFullScreen()
569 {
570 return glbFullScreen;
571 }
572
573 // Updates our glbScreenWidth & glbScreenHeight appropriately. Finds a scale
574 // factor that will fit.
575 void
576 setResolution(int width, int height)
577 {
578 // Find maximum scale factor that fits.
579 glbScaleFactor = 2;
580 while (1)
581 {
582 glbScreenWidth = HAM_SCRW * glbScaleFactor;
583 glbScreenHeight = HAM_SCRH * glbScaleFactor;
584 if (glbScreenWidth > width || glbScreenHeight > height)
585 {
586 glbScaleFactor--;
587 break;
588 }
589 glbScaleFactor++;
590 }
591
592 glbScreenWidth = width;
593 glbScreenHeight = height;
594
595 // Do not allow fractional scales.
596 if (glbScreenWidth < HAM_SCRW)
597 glbScreenWidth = HAM_SCRW;
598 if (glbScreenHeight < HAM_SCRH)
599 glbScreenHeight = HAM_SCRH;
600
601 // Calculate our fudge factor...
602 glbScreenFudgeX = ((glbScreenWidth - HAM_SCRW * glbScaleFactor) / 2);
603 glbScreenFudgeY = ((glbScreenHeight - HAM_SCRH * glbScaleFactor) / 2);
604
605 // Take effect!
606 rebuildVideoSystemFromGlobals();
607 }
608
609 void
610 scaleScreenFromPaletted(u8 *dst, int pitch)
611 {
612 int x, y, s_y, s_x;
613 u8 pixel[3];
614 u16 idx;
615 u16 *src;
616
617 // Clear initial dst...
618 memset(dst, 0, pitch * glbScreenHeight);
619
620 // Add in fudge factor
621 dst += glbScreenFudgeX * 3 + glbScreenFudgeY * pitch;
622
623 src = glb_nativescreen;
624 for (y = 0; y < HAM_SCRH; y++)
625 {
626 for (s_y = 0; s_y < glbScaleFactor; s_y++)
627 {
628 for (x = 0; x < HAM_SCRW; x++)
629 {
630 // Read in a pixel & decode
631 idx = src[x];
632 #ifndef USE_VIRTUAL_SCREEN
633 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
634 pixel[0] = glb_palette[idx*4+3];
635 pixel[1] = glb_palette[idx*4+2];
636 pixel[2] = glb_palette[idx*4+1];
637 #else
638 pixel[0] = glb_palette[idx*4+1];
639 pixel[1] = glb_palette[idx*4+2];
640 pixel[2] = glb_palette[idx*4+3];
641 #endif
642 #else
643 pixel[0] = glb_palette[idx*4+3];
644 pixel[1] = glb_palette[idx*4+2];
645 pixel[2] = glb_palette[idx*4+1];
646 #endif
647 // Now write out the needed number of times...
648 for (s_x = 0; s_x < glbScaleFactor; s_x++)
649 {
650 *dst++ = pixel[0];
651 *dst++ = pixel[1];
652 *dst++ = pixel[2];
653 }
654 }
655 // Add remainder of pitch.
656 dst += pitch - 3 * glbScaleFactor * HAM_SCRW;
657 }
658 src += HAM_SCRW;
659 }
660 }
661
662 void
663 scaleScreenFrom15bit(u8 *dst, int pitch)
664 {
665 int x, y, s_y, s_x;
666 u8 pixel[3];
667 u16 raw;
668 u16 *src;
669
670 // Clear initial dst...
671 memset(dst, 0, pitch * glbScreenHeight);
672
673 // Add in fudge factor
674 dst += glbScreenFudgeX * 3 + glbScreenFudgeY * pitch;
675
676 src = glb_rawscreen;
677 for (y = 0; y < HAM_SCRH; y++)
678 {
679 for (s_y = 0; s_y < glbScaleFactor; s_y++)
680 {
681 for (x = 0; x < HAM_SCRW; x++)
682 {
683 // Read in a pixel & decode
684 raw = src[x];
685
686 #ifndef USE_VIRTUAL_SCREEN
687 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
688 pixel[0] = (raw & 31) << 3;
689 pixel[1] = ((raw >> 5) & 31) << 3;
690 pixel[2] = ((raw >> 10) & 31) << 3;
691 #else
692 pixel[2] = (raw & 31) << 3;
693 pixel[1] = ((raw >> 5) & 31) << 3;
694 pixel[0] = ((raw >> 10) & 31) << 3;
695 #endif
696 #else
697 pixel[0] = (raw & 31) << 3;
698 pixel[1] = ((raw >> 5) & 31) << 3;
699 pixel[2] = ((raw >> 10) & 31) << 3;
700 #endif
701
702 // Now write out the needed number of times...
703 for (s_x = 0; s_x < glbScaleFactor; s_x++)
704 {
705 *dst++ = pixel[0];
706 *dst++ = pixel[1];
707 *dst++ = pixel[2];
708 }
709 }
710 // Add remainder of pitch.
711 dst += pitch - 3 * glbScaleFactor * HAM_SCRW;
712 }
713 src += HAM_SCRW;
714 }
715 }
716
717 // Draws the given sprite to the native buffer.
718 void
719 blitSprite(const SPRITEDATA &sprite)
720 {
721 if (sprite.active)
722 {
723 // Finally, blit the sprite.
724 int sx, sy, x, y, tx, ty, srcoffset;
725 u8 src;
726
727 for (sy = 0; sy < TILEHEIGHT*2; sy++)
728 {
729 for (sx = 0; sx < TILEWIDTH*2; sx++)
730 {
731 x = sprite.x + sx;
732 y = sprite.y + sy;
733 // Convert to DS coords from GBA
734 x += TILEWIDTH;
735 #ifdef USE_EXTENDED_HEIGHT
736 y += 3*TILEHEIGHT;
737 #else
738 y += 2*TILEHEIGHT;
739 #endif
740
741 tx = (sx >= TILEWIDTH) ? 1 : 0;
742 ty = (sy >= TILEHEIGHT) ? 1 : 0;
743 srcoffset = sx + tx * TILEWIDTH * (TILEHEIGHT-1) +
744 ty * 1 * TILEWIDTH * (TILEHEIGHT) + sy * TILEWIDTH;
745 src = sprite.data[srcoffset];
746 if (src &&
747 x >= 0 && x < HAM_SCRW &&
748 y >= 0 && y < HAM_SCRH)
749 {
750 glb_nativescreen[x + y * HAM_SCRW] = src + 256;
751 }
752 }
753 }
754 }
755 }
756
757 void
758 hamfake_rebuildScreen()
759 {
760 int i, layer, x, y, tileidx, tx, ty, px, py;
761 int offset;
762 static bool oldorient = true;
763
764 if (glbRevertDefault)
765 {
766 glb_isdirty = true;
767 #ifdef USE_VIRTUAL_SCREEN
768 #ifdef ANDROID
769 gfx_settilesetmode(0, 2); // 8 pixel
770 gfx_settilesetmode(1, 4); // 10 pixel
771 #else
772 gfx_settilesetmode(0, 4); // 10 pixel
773 gfx_settilesetmode(1, 3); // 12 pixel
774 #endif
775 #else
776 gfx_settilesetmode(0, 4); // Akoi Meexx
777 #endif
778
779 glbRevertDefault = false;
780 }
781
782 if (glbIsPortrait != oldorient)
783 {
784 oldorient = glbIsPortrait;
785 glb_isdirty = true;
786 gfx_tilesetmode(!glbIsPortrait);
787 }
788
789 if (!glb_isdirty)
790 return;
791
792 glb_isdirty = false;
793
794 if (glb_videomode == 3)
795 {
796 u8 *dst;
797
798 #ifndef USE_VIRTUAL_SCREEN
799 SDL_LockSurface(glbVideoSurface);
800
801 dst = (u8 *) glbVideoSurface->pixels;
802 if (!dst)
803 {
804 printf("Lock failure: %s\n", SDL_GetError());
805 }
806
807 scaleScreenFrom15bit(dst, glbVideoSurface->pitch);
808
809 SDL_UnlockSurface(glbVideoSurface);
810 // Rebuild from 15bit screen.
811 SDL_UpdateRect(glbVideoSurface, 0, 0, 0, 0);
812 #else
813 dst = new u8[glbScreenWidth * glbScreenHeight * 3];
814 scaleScreenFrom15bit(dst, glbScreenWidth*3);
815 // Gains ownership...
816 hamfake_postScreenUpdate(dst, glbScreenWidth, glbScreenHeight, glbOurScreenId);
817 glbOurScreenId++;
818 #endif
819 return;
820 }
821
822 // Clear our video surface.
823 memset(glb_nativescreen, 0, HAM_SCRH * HAM_SCRW * sizeof(u16));
824
825 // Blit each layer in turn.
826 // Hard coded layer order:
827 int lay_ord[4] = { 1, 2, 3, 0 };
828 for (i = 0; i < 4; i++)
829 {
830 layer = lay_ord[i];
831
832 ty = ham_bg[layer].scrolly;
833 if (ty < 0)
834 ty = - ((-ty + TILEHEIGHT-1) / TILEHEIGHT);
835 else
836 ty = (ty + TILEHEIGHT-1) / TILEHEIGHT;
837 py = ham_bg[layer].scrolly % TILEHEIGHT;
838 if (py < 0)
839 {
840 ty++;
841 py += TILEHEIGHT;
842 }
843
844 ty %= ham_bg[layer].mi->height;
845 if (ty < 0)
846 ty += ham_bg[layer].mi->height;
847
848 for (y = (py ? 1 : 0); y < HAM_SCRH_T; y++)
849 {
850 tx = ham_bg[layer].scrollx;
851 if (tx < 0)
852 tx = - ((-tx + TILEWIDTH-1) / TILEWIDTH);
853 else
854 tx = (tx + TILEWIDTH-1) / TILEWIDTH;
855 px = ham_bg[layer].scrollx % TILEWIDTH;
856 if (px < 0)
857 {
858 px += TILEWIDTH;
859 tx++;
860 }
861
862 tx %= ham_bg[layer].mi->width;
863 if (tx < 0)
864 tx += ham_bg[layer].mi->width;
865
866 for (x = (px ? 1 : 0); x < HAM_SCRW_T; x++)
867 {
868 u8 *tile;
869
870 tileidx = ham_bg[layer].mi->tiles[ty * ham_bg[layer].mi->width + tx];
871
872 // Out of bound tiles are ignored.
873 if ((tileidx & 1023) < ham_bg[layer].ti->numtiles)
874 {
875 tile = ham_bg[layer].ti->tiles[tileidx & 1023];
876
877 // Compute offset into native screen
878 // This computation is very suspect and has only
879 // been vetted with px == 4, so may not work with
880 // other sub pixel scroll values.
881 offset = x * TILEWIDTH - px + (y * TILEHEIGHT - py) * HAM_SCRW;
882
883 // Figure out any flip flags.
884 if (tileidx & (2048 | 1024))
885 {
886 int sx, sy, fx, fy;
887
888 for (sy = 0; sy < TILEHEIGHT; sy++)
889 {
890 if (tileidx & 2048)
891 fy = TILEHEIGHT-1 - sy;
892 else
893 fy = sy;
894
895 for (sx = 0; sx < TILEWIDTH; sx++)
896 {
897 if (tileidx & 1024)
898 fx = TILEWIDTH-1 - sx;
899 else
900 fx = sx;
901
902 // Write if non-zero
903 if (tile[fx + fy * TILEWIDTH])
904 glb_nativescreen[offset] = tile[fx + fy * TILEWIDTH];
905 offset++;
906 }
907 offset += HAM_SCRW - TILEWIDTH;
908 }
909 }
910 else
911 {
912 int sx, sy;
913
914 // Straight forward write...
915 for (sy = 0; sy < TILEHEIGHT; sy++)
916 {
917 for (sx = 0; sx < TILEWIDTH; sx++)
918 {
919 if (*tile)
920 {
921 glb_nativescreen[offset] = *tile;
922 }
923 tile++;
924 offset++;
925 }
926 offset += HAM_SCRW - TILEWIDTH;
927 }
928 }
929 }
930
931 tx++;
932 if (tx >= ham_bg[layer].mi->width)
933 tx -= ham_bg[layer].mi->width;
934 }
935
936 ty++;
937 if (ty >= ham_bg[layer].mi->height)
938 ty -= ham_bg[layer].mi->height;
939 }
940
941 // Just before the text layer we draw our sprites
942 // This ensures the buttons are under the text.
943 if (i == 2)
944 {
945 int j;
946
947 // Since we composite on top, we want to do in reverse order of
948 // priority. Hence the backwards loop.
949 // The last sprite is the cursor and is done at the very end.
950 for (j = MAX_SPRITES; j --> 1; )
951 {
952 blitSprite(glbSpriteList[j]);
953 }
954 }
955 }
956
957 // Draw the cursor sprite
958 blitSprite(glbSpriteList[0]);
959
960 // Lock and update the final surface using our lookup...
961 {
962 u8 *dst;
963
964 #ifndef USE_VIRTUAL_SCREEN
965 SDL_LockSurface(glbVideoSurface);
966 dst = (u8 *) glbVideoSurface->pixels;
967 if (!dst)
968 {
969 printf("Lock failure: %s\n", SDL_GetError());
970 }
971
972 scaleScreenFromPaletted(dst, glbVideoSurface->pitch);
973
974 SDL_UnlockSurface(glbVideoSurface);
975 // Rebuild from 8bit screen.
976 SDL_UpdateRect(glbVideoSurface, 0, 0, 0, 0);
977 #else
978 dst = new u8[glbScreenWidth * glbScreenHeight * 3];
979 scaleScreenFromPaletted(dst, glbScreenWidth*3);
980 // Gains ownership...
981 hamfake_postScreenUpdate(dst, glbScreenWidth, glbScreenHeight, glbOurScreenId);
982 glbOurScreenId++;
983 #endif
984 }
985 }
986
987 // Converts a unicode key into an ASCII key.
988 int
989 processSDLKey(int unicode, int sdlkey)
990 {
991 #ifndef USE_VIRTUAL_SCREEN
992 #ifdef _WIN32_WCE
993 // Windows CE defines some hard-coded buttons we
994 // want to re-interpret
995 // Ideally we'd handle these remaps using an actual
996 // new defaults for the character mapping, but since POWDER
997 // is still all 1970's with hardcoded key definitions, we'll
998 // suffer with this for now.
999 switch (unicode)
1000 {
1001 case 'r':
1002 return '\x1b';
1003 case 'p':
1004 return 'g';
1005 case 'q':
1006 return 'x';
1007 case 's':
1008 return 'm';
1009
1010 // Shortcut buttons
1011 case 193:
1012 return 'O';
1013 case 195:
1014 return '\x1b';
1015 case 194:
1016 return 'V';
1017 case 196:
1018 return 'i';
1019 }
1020 #endif
1021
1022 // Check to see if we are intelligble unicode.
1023 if (unicode && unicode < 128)
1024 {
1025 // The control characters usually report as unicode
1026 // values, we want to instead treat these as the normal
1027 // lower case alpha just with the ctrl- modifier set.
1028 // This then allows control to be a modifier on any
1029 // normal key.
1030 if (unicode < ' ')
1031 {
1032 if (sdlkey >= SDLK_a && sdlkey <= SDLK_z)
1033 {
1034 return 'a' + sdlkey - SDLK_a;
1035 }
1036 }
1037 // We want delete aliased to backspace because Macs lack
1038 // a backspace and I'm too lazy to support both elsewhere.
1039 if (unicode == SDLK_DELETE)
1040 unicode = '\b';
1041 return unicode;
1042 }
1043
1044 // Process stupid exceptions.
1045 switch (sdlkey)
1046 {
1047 // The mac often ships without a backspace key. Out of laziness,
1048 // alias delete to backspace
1049 case SDLK_DELETE:
1050 // Remapping backspace should be a no-op, but I'm not
1051 // holding my breath and heard reports of backspace going
1052 // 'b' on me.
1053 case SDLK_BACKSPACE:
1054 return '\b';
1055 // Insert several curses here... This isn't necessary
1056 // anywhere except WIndows XP it seems...
1057 case SDLK_KP0:
1058 return '0';
1059 case SDLK_KP1:
1060 return '1';
1061 case SDLK_KP2:
1062 return '2';
1063 case SDLK_KP3:
1064 return '3';
1065 case SDLK_KP4:
1066 return '4';
1067 case SDLK_KP5:
1068 return '5';
1069 case SDLK_KP6:
1070 return '6';
1071 case SDLK_KP7:
1072 return '7';
1073 case SDLK_KP8:
1074 return '8';
1075 case SDLK_KP9:
1076 return '9';
1077 case SDLK_UP:
1078 return GFX_KEYUP;
1079 case SDLK_DOWN:
1080 return GFX_KEYDOWN;
1081 case SDLK_LEFT:
1082 return GFX_KEYLEFT;
1083 case SDLK_RIGHT:
1084 return GFX_KEYRIGHT;
1085 case SDLK_PAGEUP:
1086 return GFX_KEYPGUP;
1087 case SDLK_PAGEDOWN:
1088 return GFX_KEYPGDOWN;
1089 case SDLK_F1:
1090 return GFX_KEYF1;
1091 case SDLK_F2:
1092 return GFX_KEYF2;
1093 case SDLK_F3:
1094 return GFX_KEYF3;
1095 case SDLK_F4:
1096 return GFX_KEYF4;
1097 case SDLK_F5:
1098 return GFX_KEYF5;
1099 case SDLK_F6:
1100 return GFX_KEYF6;
1101 case SDLK_F7:
1102 return GFX_KEYF7;
1103 case SDLK_F8:
1104 return GFX_KEYF8;
1105 case SDLK_F9:
1106 return GFX_KEYF9;
1107 case SDLK_F10:
1108 return GFX_KEYF10;
1109 case SDLK_F11:
1110 return GFX_KEYF11;
1111 case SDLK_F12:
1112 return GFX_KEYF12;
1113 case SDLK_F13:
1114 return GFX_KEYF13;
1115 case SDLK_F14:
1116 return GFX_KEYF14;
1117 case SDLK_F15:
1118 return GFX_KEYF15;
1119 }
1120
1121 #endif
1122 // Failed to parse key, 0.
1123 return 0;
1124 }
1125
1126 // Wait for an event to occur.
1127 void
1128 hamfake_awaitEvent()
1129 {
1130 if (hamfake_forceQuit())
1131 {
1132 if (glb_vblcallback)
1133 (*glb_vblcallback)();
1134 return;
1135 }
1136 #ifndef USE_VIRTUAL_SCREEN
1137 SDL_WaitEvent(0);
1138 #else
1139 glbOurEventQueue.waitAndRemove();
1140
1141 glbOurEventQueue.flush();
1142 #endif
1143 }
1144
1145 #ifdef USE_VIRTUAL_SCREEN
1146 void
1147 hamfake_awaitShutdown()
1148 {
1149 glbOurShutdownQueue.waitAndRemove();
1150 }
1151
1152 void
1153 hamfake_postShutdown()
1154 {
1155 glbOurShutdownQueue.append(0);
1156 }
1157
1158 void
1159 hamfake_awaitResurrect()
1160 {
1161 glbOurResurrectQueue.waitAndRemove();
1162 }
1163
1164 void
1165 hamfake_postResurrect()
1166 {
1167 glbOurResurrectQueue.append(0);
1168 }
1169
1170 #endif
1171
1172 // Return our internal screen.
1173 u16 *
1174 hamfake_lockScreen()
1175 {
1176 // Note we have to offset to the normal GBA start
1177 // location to account for our official offset.
1178 #ifdef USE_EXTENDED_HEIGHT
1179 return glb_rawscreen + TILEWIDTH + 3*TILEHEIGHT * HAM_SCRW;
1180 #else
1181 return glb_rawscreen + TILEWIDTH + 2*TILEHEIGHT * HAM_SCRW;
1182 #endif
1183 }
1184
1185 void
1186 hamfake_unlockScreen(u16 *)
1187 {
1188 glb_isdirty = true;
1189 }
1190
1191 // Deal with our SRAM buffer.
1192 char *
1193 hamfake_writeLockSRAM()
1194 {
1195 return glb_rawSRAM;
1196 }
1197
1198 void
1199 hamfake_writeUnlockSRAM(char *)
1200 {
1201 }
1202
1203 char *
1204 hamfake_readLockSRAM()
1205 {
1206 return glb_rawSRAM;
1207 }
1208
1209 void
1210 hamfake_readUnlockSRAM(char *)
1211 {
1212 }
1213
1214 void
1215 hamfake_endWritingSession()
1216 {
1217 FILE *fp;
1218 int bytes;
1219
1220 // We run a simple transaction model here to try
1221 // and ensure even if we crash in the process the last
1222 // good save file will still be found.
1223
1224 fp = hamfake_fopen(TRANSACTIONNAME, "wb");
1225 if (!fp)
1226 {
1227 fprintf(stderr, "Failure to open " TRANSACTIONNAME " for writing!\r\n");
1228 return;
1229 }
1230
1231 bytes = fwrite(glb_rawSRAM, 1, SRAMSIZE, fp);
1232 fclose(fp);
1233 if (bytes != SRAMSIZE)
1234 {
1235 fprintf(stderr, "Only wrote %d to " TRANSACTIONNAME "\r\n", bytes);
1236 return;
1237 }
1238
1239 // Now delete the old file and rename
1240 hamfake_move(SAVENAME, TRANSACTIONNAME);
1241 }
1242
1243 #ifndef USE_VIRTUAL_SCREEN
1244 void
1245 processKeyMod(int mod)
1246 {
1247 #ifdef HAS_KEYBOARD
1248 if (mod & KMOD_CTRL || mod & KMOD_META)
1249 glb_keymod |= GFX_KEYMODCTRL;
1250 else
1251 glb_keymod &= ~GFX_KEYMODCTRL;
1252
1253 if (mod & KMOD_SHIFT)
1254 glb_keymod |= GFX_KEYMODSHIFT;
1255 else
1256 glb_keymod &= ~GFX_KEYMODSHIFT;
1257
1258 // Modal-T? Is that a type of car?
1259 if (mod & KMOD_ALT)
1260 glb_keymod |= GFX_KEYMODALT;
1261 else
1262 glb_keymod &= ~GFX_KEYMODALT;
1263 #endif
1264 }
1265 #endif
1266
1267 // Called to run our event poll
1268 void
1269 hamfake_pollEvents()
1270 {
1271 #ifndef USE_VIRTUAL_SCREEN
1272 SDL_Event event;
1273 int cookedkey;
1274
1275 while (SDL_PollEvent(&event))
1276 {
1277 switch (event.type)
1278 {
1279 case SDL_VIDEORESIZE:
1280 setResolution(event.resize.w, event.resize.h);
1281 break;
1282 case SDL_KEYDOWN:
1283 if (event.key.keysym.sym < SDLK_LAST)
1284 {
1285 glb_keystate[event.key.keysym.sym] = 1;
1286
1287 cookedkey = processSDLKey(event.key.keysym.unicode, event.key.keysym.sym);
1288 processKeyMod(event.key.keysym.mod);
1289
1290 // What sort of drunk would insert the keypress
1291 // on a key up?
1292 hamfake_insertKeyPress(cookedkey);
1293
1294 if (cookedkey)
1295 {
1296 glb_keypushtime = gfx_getframecount() + KEY_REPEAT_INITIAL;
1297 glb_keypusher = cookedkey;
1298 glb_keypusherraw = event.key.keysym.sym;
1299 }
1300 }
1301 break;
1302 case SDL_KEYUP:
1303 if (event.key.keysym.sym < SDLK_LAST)
1304 {
1305 glb_keystate[event.key.keysym.sym] = 0;
1306
1307 // Sadly, unicode is *not* cooked on a keyup!
1308 // Damn SDL!
1309 // Thus, we always clear out on a key going high.
1310 // cookedkey = processSDLKey(event.key.keysym.unicode);
1311 // This will annoy copx, however, so we instead
1312 // stop being lazy and store the original raw code.
1313
1314 // If our currently repeated key goes high,
1315 // clear it out.
1316 if (event.key.keysym.sym == glb_keypusherraw)
1317 {
1318 glb_keypusher = 0;
1319 }
1320 }
1321 break;
1322
1323 case SDL_MOUSEMOTION:
1324 {
1325 glbStylusX = event.motion.x;
1326 glbStylusY = event.motion.y;
1327
1328 int x, y;
1329 hamfake_getstyluspos(x, y);
1330 break;
1331 }
1332
1333 case SDL_MOUSEBUTTONDOWN:
1334 glbStylusX = event.button.x;
1335 glbStylusY = event.button.y;
1336 cookedkey = 0;
1337 switch (event.button.button)
1338 {
1339 case SDL_BUTTON_LEFT:
1340 cookedkey = GFX_KEYLMB;
1341 glbStylusState = true;
1342 break;
1343 case SDL_BUTTON_MIDDLE:
1344 cookedkey = GFX_KEYMMB;
1345 break;
1346 case SDL_BUTTON_RIGHT:
1347 cookedkey = GFX_KEYRMB;
1348 break;
1349 }
1350 if (cookedkey)
1351 {
1352 hamfake_insertKeyPress(cookedkey);
1353 glb_keypushtime = gfx_getframecount() + KEY_REPEAT_INITIAL;
1354 glb_keypusher = cookedkey;
1355 // Special value for these...
1356 glb_keypusherraw = -cookedkey;
1357 }
1358 break;
1359
1360 case SDL_MOUSEBUTTONUP:
1361 glbStylusX = event.button.x;
1362 glbStylusY = event.button.y;
1363 cookedkey = 0;
1364 switch (event.button.button)
1365 {
1366 case SDL_BUTTON_LEFT:
1367 glbStylusState = false;
1368 cookedkey = GFX_KEYLMB;
1369 break;
1370 case SDL_BUTTON_MIDDLE:
1371 cookedkey = GFX_KEYMMB;
1372 break;
1373 case SDL_BUTTON_RIGHT:
1374 cookedkey = GFX_KEYRMB;
1375 break;
1376 }
1377 // Wipe out the pusher if we match.
1378 if (-cookedkey == glb_keypusherraw)
1379 {
1380 glb_keypusher = 0;
1381 }
1382 break;
1383
1384 case SDL_QUIT:
1385 SDL_Quit();
1386 exit(0);
1387 break;
1388 }
1389 }
1390
1391 // After chewing up all the events, we pump the keyboard repeat
1392 // This ensures it is the same thread as the keyboard repeat
1393 // set up. It also ensures that if we are stalling on the main
1394 // thread, so weren't able to respond to the users key up command,
1395 // we will not send extra keys.
1396 // It is reasoned that extra repeats are more frustrating than
1397 // missed repeats.
1398 {
1399 int frame;
1400
1401 frame = gfx_getframecount();
1402 if (glb_keypusher)
1403 {
1404 if (frame >= glb_keypushtime)
1405 {
1406 hamfake_insertKeyPress(glb_keypusher);
1407 glb_keypushtime = frame + KEY_REPEAT_AFTER;
1408 }
1409 }
1410 }
1411 #endif
1412 }
1413
1414 int
1415 hamfake_isAnyPressed()
1416 {
1417 hamfake_pollEvents();
1418 hamfake_rebuildScreen();
1419
1420 int i;
1421 #ifndef USE_VIRTUAL_SCREEN
1422 for (i = 0; i < SDLK_LAST; i++)
1423 if (glb_keystate[i]) return 0x0;
1424 #else
1425 for (i = 0; i < NUM_FAKE_BUTTONS; i++)
1426 if (hamfake_isFakeButtonPressed((FAKE_BUTTONS) i))
1427 return 0;
1428 if (glbStylusState)
1429 return 0;
1430
1431 // Eat any external action key press as an any key.
1432 int action, spell;
1433 hamfake_externalaction(action, spell);
1434 if (action || spell)
1435 return 0;
1436 #endif
1437 return 0x3FF;
1438 }
1439
1440 #ifdef USE_VIRTUAL_SCREEN
1441 bool
1442 hamfake_forceQuit()
1443 {
1444 return glbIsForceQuit;
1445 }
1446
1447 void
1448 hamfake_setForceQuit()
1449 {
1450 glbIsForceQuit = true;
1451
1452 // Ensure we aren't stalled on input.
1453 hamfake_finishexternalinput();
1454
1455 // Trigger an event so we wake up immediately.
1456 hamfake_callThisFromVBL();
1457 }
1458 void
1459 hamfake_clearForceQuit()
1460 {
1461 glbIsForceQuit = false;
1462 }
1463
1464 #endif
1465
1466 #ifndef HAS_KEYBOARD
1467 bool hamfake_isFakeButtonPressed(FAKE_BUTTONS button)
1468 {
1469 if (button < 0 || button >= NUM_FAKE_BUTTONS)
1470 return false;
1471 hamfake_pollEvents();
1472 hamfake_rebuildScreen();
1473 return glbFakeButtonState[button];
1474 }
1475
1476 void hamfake_setFakeButtonState(FAKE_BUTTONS button, bool state)
1477 {
1478 if (button < 0 || button >= NUM_FAKE_BUTTONS)
1479 return;
1480 glbFakeButtonState[button] = state;
1481 }
1482 #endif
1483
1484 int
1485 hamfake_peekKeyPress()
1486 {
1487 hamfake_pollEvents();
1488 hamfake_rebuildScreen();
1489
1490 // Nothing available.
1491 if (glb_keybufentry < 0)
1492 return 0;
1493
1494 return glb_keybuf[0];
1495 }
1496
1497 int
1498 hamfake_getKeyModifiers()
1499 {
1500 hamfake_pollEvents();
1501 hamfake_rebuildScreen();
1502
1503 return glb_keymod;
1504 }
1505
1506 int
1507 hamfake_getKeyPress(bool onlyascii)
1508 {
1509 hamfake_pollEvents();
1510 hamfake_rebuildScreen();
1511
1512 // Nothing available.
1513 if (glb_keybufentry < 0)
1514 return 0;
1515
1516 int newkey;
1517
1518 newkey = glb_keybuf[0];
1519
1520 // Eat up the keys.
1521 if (glb_keybufentry)
1522 memmove(glb_keybuf, &glb_keybuf[1], glb_keybufentry * sizeof(int));
1523
1524 glb_keybufentry--;
1525
1526 // If the key isn't ascii and we only want ascii, eat the key and try
1527 // again.
1528 if (onlyascii && newkey > 255)
1529 {
1530 return hamfake_getKeyPress(onlyascii);
1531 }
1532
1533 return newkey;
1534 }
1535
1536 void
1537 hamfake_insertKeyPress(int key)
1538 {
1539 // Ignore illegal keys.
1540 if (!key)
1541 return;
1542
1543 if (glb_keybufentry < 15)
1544 {
1545 glb_keybuf[glb_keybufentry+1] = key;
1546 glb_keybufentry++;
1547 }
1548 }
1549
1550 void
1551 hamfake_clearKeyboardBuffer()
1552 {
1553 // Stop pushing keys!
1554 glb_keypusher = 0;
1555 // Flush the buffer!
1556 glb_keybufentry = -1;
1557
1558 #ifndef USE_VIRTUAL_SCREEN
1559 // I think this is actually very questionable. The DS, which as
1560 // the best stylus support, never releases it.
1561 // Release the stylus
1562 glbStylusState = false;
1563 #else
1564 // Empty our action queues.
1565 glbOurActionQueue.flush();
1566 glbOurSpellQueue.flush();
1567 #endif
1568 }
1569
1570 void
1571 hamfake_setScrollX(int layer, int scroll)
1572 {
1573 ham_bg[layer].scrollx = scroll;
1574 }
1575
1576 void
1577 hamfake_setScrollY(int layer, int scroll)
1578 {
1579 ham_bg[layer].scrolly = scroll;
1580 }
1581
1582 u8 *
1583 convertTo32Bit(const unsigned short *s, int numpixel)
1584 {
1585 u8 *result, *d;
1586 unsigned short p;
1587
1588 result = (u8 *) malloc(numpixel * 4);
1589 d = result;
1590
1591 while (numpixel--)
1592 {
1593 p = *s++;
1594 *d++ = (p & 31) * 8 + 4;
1595 p >>= 5;
1596 *d++ = (p & 31) * 8 + 4;
1597 p >>= 5;
1598 *d++ = (p & 31) * 8 + 4;
1599 *d++ = 0xff;
1600 }
1601 return result;
1602 }
1603
1604 #ifdef CHANGE_WORK_DIRECTORY
1605 // This is Linux friendly.
1606 #include <sys/stat.h>
1607 #include <sys/types.h>
1608 #include <unistd.h>
1609 #include <pwd.h>
1610
1611 const char *
1612 gethomedir()
1613 {
1614 static char *home = 0;
1615
1616 if (!home)
1617 home = getenv("HOME");
1618 if (!home)
1619 {
1620 struct passwd *pw = getpwuid(getuid());
1621 if (pw) home = pw->pw_dir;
1622 }
1623
1624 return home;
1625 }
1626
1627 bool
1628 changeworkdir()
1629 {
1630 struct stat buffer;
1631 int status;
1632
1633 const char *home = gethomedir();
1634 if (!home)
1635 {
1636 fprintf(stderr, "Error finding home directory.\r\n");
1637 return false;
1638 }
1639
1640 if (chdir(home))
1641 {
1642 perror("Changing home directory");
1643 return false;
1644 }
1645
1646 const char *powderdir = ".powder";
1647
1648 status = stat(powderdir, &buffer);
1649 if (status)
1650 {
1651 if (mkdir(powderdir, S_IRWXU | S_IRWXG | S_IRWXO))
1652 {
1653 perror(powderdir);
1654 return false;
1655 }
1656 }
1657 else if (!S_ISDIR(buffer.st_mode))
1658 {
1659 fprintf(stderr, "~/%s is not a directory!\r\n", powderdir);
1660 return false;
1661 }
1662
1663 return !chdir(powderdir);
1664 }
1665 #endif
1666
1667 void
1668 ham_Init()
1669 {
1670 int i;
1671
1672 printf("\nPOWDER initializing...\n");
1673
1674 #ifdef CHANGE_WORK_DIRECTORY
1675 if (!changeworkdir())
1676 {
1677 fprintf(stderr, "Failed to initialize ~/.powder\r\n");
1678 exit(-1);
1679 }
1680 #endif
1681
1682 #ifndef USE_VIRTUAL_SCREEN
1683 /* initialize SDL */
1684 if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
1685 {
1686 fprintf( stderr, "Video initialization failed: %s\n",
1687 SDL_GetError( ) );
1688 SDL_Quit( );
1689 }
1690 #endif
1691
1692 #ifndef USE_VIRTUAL_SCREEN
1693 u8 *rgbpixel;
1694
1695 rgbpixel = convertTo32Bit(bmp_icon_sdl, 32 * 32);
1696
1697 /* SDL interprets each pixel as a 32-bit number, so our masks must depend
1698 on the endianness (byte order) of the machine */
1699 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
1700 const Uint32 rmask = 0xff000000;
1701 const Uint32 gmask = 0x00ff0000;
1702 const Uint32 bmask = 0x0000ff00;
1703 const Uint32 amask = 0x000000ff;
1704 #else
1705 const Uint32 rmask = 0x000000ff;
1706 const Uint32 gmask = 0x0000ff00;
1707 const Uint32 bmask = 0x00ff0000;
1708 const Uint32 amask = 0xff000000;
1709 #endif
1710
1711 SDL_Surface *surf = SDL_CreateRGBSurfaceFrom((char *)rgbpixel, 32, 32, 32, 32*4,
1712 rmask, gmask, bmask, amask);
1713
1714 SDL_WM_SetIcon(surf, NULL);
1715
1716 SDL_EnableUNICODE(1);
1717 #endif
1718
1719 glbSpriteList = new SPRITEDATA[MAX_SPRITES];
1720 for (i = 0; i < MAX_SPRITES; i++)
1721 {
1722 glbSpriteList[i].active = false;
1723 glbSpriteList[i].data = new u8[TILEWIDTH * TILEHEIGHT * 4];
1724 }
1725
1726 #ifndef USE_VIRTUAL_SCREEN
1727 memset(glb_keystate, 0, SDLK_LAST);
1728 #endif
1729
1730 glb_rawscreen = new u16[HAM_SCRW*HAM_SCRH];
1731 memset(glb_rawscreen, 0, HAM_SCRW*HAM_SCRH*sizeof(u16));
1732 glb_nativescreen = new u16[HAM_SCRW*HAM_SCRH];
1733
1734 // Load any save games.
1735 // We give preference to the recovery name. If it crashes
1736 // post unlink but before moving, this is cool.
1737 // We do, however, validate the fread. If it fails to
1738 // get SRAMSIZE we had failure to save the complete file
1739 // so backup to powder.sav.
1740 FILE *fp;
1741 bool foundtransaction = false;
1742
1743 fp = hamfake_fopen(TRANSACTIONNAME, "rb");
1744 if (fp)
1745 {
1746 int transactionsize;
1747 transactionsize = fread(glb_rawSRAM, 1, SRAMSIZE, fp);
1748 if (transactionsize == SRAMSIZE)
1749 {
1750 // Successful recovery!
1751 fprintf(stderr, "Loaded recover.sav\r\n");
1752 foundtransaction = true;
1753 }
1754 else
1755 {
1756 fprintf(stderr, TRANSACTIONNAME " is corrupt: %d, ignoring it.\r\n", transactionsize);
1757 }
1758 fclose(fp);
1759 }
1760 // Now try to load the normal powder.sav
1761 if (!foundtransaction)
1762 {
1763 fp = hamfake_fopen(SAVENAME, "rb");
1764 if (fp)
1765 {
1766 int savesize;
1767 savesize = fread(glb_rawSRAM, 1, SRAMSIZE, fp);
1768 if (savesize != SRAMSIZE)
1769 {
1770 fprintf(stderr, SAVENAME " is corrupt: %d, but still reading it.\r\n", savesize);
1771 }
1772 else
1773 {
1774 fprintf(stderr, "Loaded powder.sav\r\n");
1775 }
1776 fclose(fp);
1777 }
1778 }
1779
1780 // Load any extra tilesets.
1781 if (bmp_loadExtraTileset())
1782 {
1783 ham_extratileset = true;
1784 }
1785
1786 return;
1787 }
1788
1789 #ifndef USE_VIRTUAL_SCREEN
1790 Uint32
1791 glb_VBLTimerCallback(Uint32 interval, void *fp)
1792 {
1793 glb_isnewframe = 1;
1794 (*glb_vblcallback)();
1795
1796 // Push a fake event so we wake up.
1797 SDL_Event event;
1798
1799 event.type = SDL_USEREVENT;
1800 SDL_PushEvent(&event);
1801
1802 return 16;
1803 }
1804 #else
1805 void
1806 hamfake_callThisFromVBL()
1807 {
1808 glb_isnewframe = 1;
1809 if (glb_vblcallback)
1810 (*glb_vblcallback)();
1811
1812 glbOurEventQueue.append(0);
1813 }
1814
1815 #endif
1816
1817 void
1818 ham_StartIntHandler(u8 intno, void (*fp)())
1819 {
1820 assert(intno == INT_TYPE_VBL);
1821
1822 glb_vblcallback = fp;
1823 #ifndef USE_VIRTUAL_SCREEN
1824 SDL_AddTimer(16, glb_VBLTimerCallback, 0);
1825 #endif
1826 }
1827
1828 void
1829 ham_SetBgMode(u8 mode)
1830 {
1831 if (glb_videomode == -1)
1832 {
1833 #if defined(_WIN32_WCE) || defined(USE_VIRTUAL_SCREEN)
1834 // For mobiles we want to default to the lowest res.
1835 setResolution(HAM_SCRW, HAM_SCRH);
1836 #else
1837 setResolution(HAM_SCRW * 2, HAM_SCRH * 2);
1838 #endif
1839 rebuildVideoSystemFromGlobals();
1840 }
1841
1842 glb_videomode = mode;
1843 }
1844
1845
1846 void
1847 ham_LoadBGPal(void *vpal, int bytes)
1848 {
1849 // Need to promote our 15bit palette to a 24 bit one.
1850 int entries = bytes / 2, i;
1851 u16 *pal = (u16 *) vpal;
1852
1853 for (i = 0; i < entries; i++)
1854 {
1855 glb_palette[i*4+3] = (pal[i] & 31) << 3;
1856 glb_palette[i*4+2] = ((pal[i] >> 5) & 31) << 3;
1857 glb_palette[i*4+1] = ((pal[i] >> 10) & 31) << 3;
1858 if (i)
1859 glb_palette[i*4] = 255;
1860 else
1861 glb_palette[i*4] = 0;
1862 }
1863 }
1864
1865 map_info_ptr
1866 ham_InitMapEmptySet(u8 size, u8 )
1867 {
1868 map_info_ptr mi;
1869
1870 mi = new map_info;
1871
1872 if (size == 0)
1873 {
1874 mi->width = 32;
1875 mi->height = 32;
1876 }
1877 else
1878 {
1879 mi->width = 64;
1880 mi->height = 64;
1881 }
1882
1883 mi->tiles = new int[mi->width * mi->height];
1884 memset(mi->tiles, 0, sizeof(int) * mi->width * mi->height);
1885
1886 return mi;
1887 }
1888
1889 tile_info_ptr
1890 ham_InitTileEmptySet(int entries, int , int)
1891 {
1892 tile_info_ptr ti;
1893 int i;
1894
1895 ti = new tile_info;
1896 ti->numtiles = entries;
1897 ti->tiles = new u8 *[entries];
1898
1899 for (i = 0; i < entries; i++)
1900 {
1901 ti->tiles[i] = new u8 [TILEWIDTH * TILEHEIGHT];
1902 }
1903 glbTheTileSet = ti;
1904 return ti;
1905 }
1906
1907 void
1908 ham_InitBg(int layer, int foo, int bar, int baz)
1909 {
1910 ham_bg[layer].scrollx = 0;
1911 ham_bg[layer].scrolly = 0;
1912 }
1913
1914 void
1915 ham_CreateWin(int , int, int, int, int, int, int, int)
1916 {
1917 }
1918
1919 void
1920 ham_DeleteWin(int wid)
1921 {
1922 }
1923
1924 void
1925 ham_SetMapTile(int layer, int mx, int my, int tileidx)
1926 {
1927 map_info_ptr mi;
1928
1929 mi = ham_bg[layer].mi;
1930
1931 mx = (mx % mi->width);
1932 if (mx < 0)
1933 mx += mi->width;
1934 my = (my % mi->height);
1935 if (my < 0)
1936 my += mi->height;
1937
1938 mi->tiles[mx + my * mi->width] = tileidx;
1939
1940 glb_isdirty = true;
1941 }
1942
1943 void
1944 hamfake_setTileSize(int tilewidth, int tileheight)
1945 {
1946 int i;
1947
1948 glbTileWidth = tilewidth;
1949 glbTileHeight = tileheight;
1950
1951 delete [] glb_rawscreen;
1952 delete [] glb_nativescreen;
1953 glb_rawscreen = new u16[HAM_SCRW*HAM_SCRH];
1954 memset(glb_rawscreen, 0, HAM_SCRW*HAM_SCRH*sizeof(u16));
1955 glb_nativescreen = new u16[HAM_SCRW*HAM_SCRH];
1956
1957 for (i = 0; glbTheTileSet && (i < glbTheTileSet->numtiles); i++)
1958 {
1959 delete [] glbTheTileSet->tiles[i];
1960 glbTheTileSet->tiles[i] = new u8 [TILEWIDTH * TILEHEIGHT];
1961 memset(glbTheTileSet->tiles[i], 0, TILEWIDTH * TILEHEIGHT);
1962 }
1963
1964 for (i = 0; i < MAX_SPRITES; i++)
1965 {
1966 delete [] glbSpriteList[i].data;
1967 glbSpriteList[i].data = new u8[TILEWIDTH * TILEHEIGHT * 4];
1968 memset(glbSpriteList[i].data, 0, TILEWIDTH * TILEHEIGHT * 4);
1969 }
1970 #ifdef USE_VIRTUAL_SCREEN
1971 // This platform works with a virtual screen so we never use
1972 // the black fudge space.
1973 glbScreenWidth = HAM_SCRW;
1974 glbScreenHeight = HAM_SCRH;
1975 #endif
1976 setResolution(glbScreenWidth, glbScreenHeight);
1977 }
1978
1979 void
1980 ham_ReloadTileGfx(tile_info_ptr tiledata, const u16 *data, int destidx,
1981 int numtile)
1982 {
1983 int t;
1984 u8 *raw;
1985 u8 *dst;
1986
1987 raw = (u8*) data;
1988 for (t = destidx; t < destidx + numtile; t++)
1989 {
1990 dst = tiledata->tiles[t];
1991
1992 memcpy(dst, raw, TILEWIDTH*TILEHEIGHT);
1993 raw += TILEWIDTH*TILEHEIGHT;
1994 }
1995 glb_isdirty = true;
1996 }
1997
1998 void
1999 hamfake_ReloadSpriteGfx(const u16 *data, int tileno, int numtile)
2000 {
2001 tileno /= 4;
2002 UT_ASSERT(tileno >= 0 && tileno < MAX_SPRITES);
2003 if (tileno < 0 || tileno >= MAX_SPRITES)
2004 return;
2005
2006 memcpy(glbSpriteList[tileno].data, data, numtile * TILEWIDTH*TILEHEIGHT);
2007 glb_isdirty = true;
2008 }
2009
2010 void
2011 hamfake_LoadSpritePal(void *vpal, int bytes)
2012 {
2013 // Need to promote our 15bit palette to a 24 bit one.
2014 int entries = bytes / 2, i;
2015 u16 *pal = (u16 *) vpal;
2016
2017 for (i = 0; i < entries; i++)
2018 {
2019 glb_palette[1024+i*4+3] = (pal[i] & 31) << 3;
2020 glb_palette[1024+i*4+2] = ((pal[i] >> 5) & 31) << 3;
2021 glb_palette[1024+i*4+1] = ((pal[i] >> 10) & 31) << 3;
2022 if (i)
2023 glb_palette[1024+i*4] = 255;
2024 else
2025 glb_palette[1024+i*4] = 0;
2026 }
2027 glb_isdirty = true;
2028 }
2029
2030 void
2031 hamfake_softReset()
2032 {
2033 hamfake_postShutdown();
2034 #ifdef ANDROID
2035
2036 // We do not want to actually kill the android thread
2037 // as then we'd have to repopulate our global variables. Instead
2038 // we maintain our state in the hopes we'll be magically reactivated.
2039 hamfake_clearForceQuit();
2040 hamfake_awaitResurrect();
2041
2042 // Having resurected, we should rebuild
2043 hamfake_rebuildScreen();
2044
2045 #else
2046 #ifdef USE_VIRTUAL_SCREEN
2047 #else
2048 SDL_Quit();
2049 #endif
2050 exit(0);
2051 #endif
2052 }
2053
2054 bool
2055 hamfake_extratileset()
2056 {
2057 return ham_extratileset;
2058 }
2059
2060 void
2061 hamfake_setstyluspos(bool state, int x, int y)
2062 {
2063 // Since we are threading, we want to make sure mouse up
2064 // occurs always before mouse down!
2065 if (!state)
2066 {
2067 glbStylusState = false;
2068 }
2069 else
2070 {
2071 glbStylusX = x;
2072 glbStylusY = y;
2073 glbStylusState = true;
2074 }
2075 #ifdef USE_VIRTUAL_SCREEN
2076 glbOurEventQueue.append(1);
2077 #endif
2078 }
2079
2080 void
2081 hamfake_getstyluspos(int &x, int &y)
2082 {
2083 x = glbStylusX;
2084 y = glbStylusY;
2085 // Convert accordint to our scale.
2086 x -= glbScreenFudgeX;
2087 y -= glbScreenFudgeY;
2088 x /= glbScaleFactor;
2089 y /= glbScaleFactor;
2090 // After conversion we can be out of the valid bounds.
2091 if (x < 0)
2092 x = 0;
2093 if (y < 0)
2094 y = 0;
2095 if (x >= HAM_SCRW)
2096 x = HAM_SCRW-1;
2097 if (y >= HAM_SCRH)
2098 y = HAM_SCRH-1;
2099
2100 // Now return to the GBA coordinate system by adjusting for the DS coords.
2101 x -= TILEWIDTH;
2102 #ifdef USE_EXTENDED_HEIGHT
2103 y -= 3*TILEHEIGHT;
2104 #else
2105 y -= 2*TILEHEIGHT;
2106 #endif
2107 }
2108
2109 bool
2110 hamfake_getstylusstate()
2111 {
2112 return glbStylusState;
2113 }
2114
2115 void
2116 hamfake_movesprite(int spriteno, int x, int y)
2117 {
2118 UT_ASSERT(spriteno >= 0 && spriteno < MAX_SPRITES);
2119 if (spriteno < 0 || spriteno >= MAX_SPRITES)
2120 return;
2121 glb_isdirty = true;
2122 glbSpriteList[spriteno].x = x;
2123 glbSpriteList[spriteno].y = y;
2124 }
2125
2126 void
2127 hamfake_enablesprite(int spriteno, bool enabled)
2128 {
2129 UT_ASSERT(spriteno >= 0 && spriteno < MAX_SPRITES);
2130 if (spriteno < 0 || spriteno >= MAX_SPRITES)
2131 return;
2132 glb_isdirty = true;
2133 glbSpriteList[spriteno].active = enabled;
2134 }
2135
2136 void
2137 hamfake_move(const char *dst, const char *src)
2138 {
2139 BUF fulldst, fullsrc;
2140
2141 #ifdef _WIN32_WCE
2142 CreateDirectory(L"\\My Documents", NULL);
2143 CreateDirectory(L"\\My Documents\\POWDER", NULL);
2144 fulldst.sprintf("\\My Documents\\POWDER\\%s", dst);
2145 fullsrc.sprintf("\\My Documents\\POWDER\\%s", src);
2146 #else
2147 #ifdef USE_VIRTUAL_SCREEN
2148 if (glbOurDataPath)
2149 {
2150 fullsrc.sprintf("%s/%s", glbOurDataPath, src);
2151 fulldst.sprintf("%s/%s", glbOurDataPath, dst);
2152 }
2153 else
2154 return;
2155 #else
2156 fullsrc.strcpy(src);
2157 fulldst.strcpy(dst);
2158 #endif
2159 #endif
2160
2161 ::remove(fulldst.buffer());
2162 ::rename(fullsrc.buffer(), fulldst.buffer());
2163 }
2164
2165 FILE *
2166 hamfake_fopen(const char *path, const char *mode)
2167 {
2168 #ifdef _WIN32_WCE
2169 // No concept of current directory in Windows CE, so we
2170 // hard code into their documents.
2171 BUF fullpath;
2172 CreateDirectory(L"\\My Documents", NULL);
2173 CreateDirectory(L"\\My Documents\\POWDER", NULL);
2174 fullpath.sprintf("\\My Documents\\POWDER\\%s", path);
2175
2176 return fopen(fullpath.buffer(), mode);
2177 #else
2178 #ifdef USE_VIRTUAL_SCREEN
2179 // Prepend our given global path, if it exists.
2180 BUF fullpath;
2181
2182 // If no data path set yet, we shouldn't write as we should
2183 // not rely on the sandbox being secure.
2184 if (glbOurDataPath)
2185 fullpath.sprintf("%s/%s", glbOurDataPath, path);
2186 else
2187 return 0;
2188 return fopen(fullpath.buffer(), mode);
2189 #else
2190 // Use the local directory on these platforms.
2191 return fopen(path, mode);
2192 #endif
2193 #endif
2194 }
2195
2196 bool
2197 hamfake_fatvalid()
2198 {
2199 return true;
2200 }