Skip to content

Instantly share code, notes, and snippets.

@brook2
Created December 30, 2013 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brook2/8184960 to your computer and use it in GitHub Desktop.
Save brook2/8184960 to your computer and use it in GitHub Desktop.
#include <SDL/SDL.h>
// gcc `sdl-config --cflags --libs` gbtiles.c
// VIEW TILES FROM A GAMEBOY ROM
// ARROW KEYS TO MOVE
#define cols 64
#define rows 64
void print_tile(unsigned char *bytes, int x, int y, int l, char *data) {
int i, j;
int b1, b2;
int b1_bit, b2_bit;
for(i = 0; i < 16; i += 2) {
b1 = bytes[i];
b2 = bytes[i+1];
for(j = 0; j < 8; j++) {
b1_bit = !(!(b1 & (0x80>>j)));
b2_bit = !(!(b2 & (0x80>>j)));
data[(x+j)+(y+i/2)*l] = 0xff-((2*b2_bit+b1_bit))*(0xff/4);
}
//puts("");
}
}
SDL_Surface *read_rom(char *filename, int doff, int *dout) {
int w, h, i;
unsigned char bytes[] = {0x7C,0x7C,0x00,0xC6,0xC6,0x00,0x00,0xFE,0xC6,0xC6,0x00,0xC6,0xC6,0x00,0x00,0x00};
w = 8*cols;
h = 8*rows;
char *pixels = malloc(w*h*8);
for(i = 0; i < w*h*8; i++) {
pixels[i] = 0; //(i*0xff)/(w*h*8);
}
FILE *fptr;
int er;
if(!(fptr = fopen(filename, "rb"))) { puts("fopen fail"); return NULL; }
int size;// = 65536;
fseek(fptr, 0, SEEK_END);
size = ftell(fptr);
fseek(fptr, 0, SEEK_SET);
unsigned char *data = malloc(size);
if((er = fread(data, size, 1, fptr)) != 1) { printf("fread fail %d\n", er); return NULL; }
int x = 0, y = 0, d = 0;
for(d = doff; d < size; d += 16) {
print_tile(data+d, x*8, y*8, w, pixels);
x++;
if(x>= cols) {
x=0;
y++;
}
if(y >= rows) break;
}
d+=16;
*dout = d;
//if(d < size)
// printf("didn't show everything! %d/%d\n", d, size);
return SDL_CreateRGBSurfaceFrom(pixels, w, h,
8, w,
0xff, 0xff, 0xff, 0);
}
int main(int argc, char* args[]) {
SDL_Surface* tiles = NULL;
SDL_Surface* screen = NULL;
int oldd, d;
if(argc != 2) { puts("give a gb rom as input"); return 0; }
SDL_Init(SDL_INIT_EVERYTHING);
screen = SDL_SetVideoMode( cols*8, rows*8, 32, SDL_SWSURFACE );
oldd = 0;
tiles = read_rom(args[1], 0, &d);
if(!tiles) { puts("error"); return; }
SDL_BlitSurface(tiles, NULL, screen, NULL);
SDL_Flip(screen);
SDL_Event e;
while(SDL_WaitEvent(&e)) {
if(e.type == SDL_QUIT)
break;
if(e.type == SDL_KEYDOWN) {
if(e.key.keysym.sym == SDLK_LEFT) {
if(oldd>0) oldd--;
}
else if(e.key.keysym.sym == SDLK_RIGHT) {
oldd++;
}
else if(e.key.keysym.sym == SDLK_UP) {
oldd = 0;
}
else {
oldd = d;
}
tiles = read_rom(args[1], oldd, &d);
if(!tiles) { puts("error"); return; }
SDL_BlitSurface(tiles, NULL, screen, NULL);
SDL_Flip(screen);
}
}
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment