From bef89c66045a3ef1eb959326db95a6f14547b40d Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Sun, 21 May 2017 21:44:28 +0300 Subject: [PATCH 1/6] Upgraded Sameboy-SDL to SDL2, fixed Windows build, fixed save states in SDL, added reset and mute to SDL. The SDL port now renders via OpenGL. --- Core/apu.c | 8 ++ Core/gb.c | 6 +- Makefile | 24 ++-- SDL/SDLMain.h | 16 --- SDL/SDLMain.m | 382 -------------------------------------------------- SDL/main.c | 184 +++++++++++++++--------- 6 files changed, 141 insertions(+), 479 deletions(-) delete mode 100644 SDL/SDLMain.h delete mode 100644 SDL/SDLMain.m diff --git a/Core/apu.c b/Core/apu.c index cb87e66..5b43d77 100755 --- a/Core/apu.c +++ b/Core/apu.c @@ -15,6 +15,14 @@ _a > _b ? _a : _b; }) __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) +#ifdef _WIN32 +/* "Old" (Pre-2015) Windows headers/libc don't have round. */ +static inline double round(double f) +{ + return f >= 0? (int)(f + 0.5) : (int)(f - 0.5); +} +#endif + #define APU_FREQUENCY 0x80000 static int16_t generate_square(uint64_t phase, uint32_t wave_length, int16_t amplitude, uint8_t duty) diff --git a/Core/gb.c b/Core/gb.c index 214cbcb..cf334b5 100755 --- a/Core/gb.c +++ b/Core/gb.c @@ -651,12 +651,14 @@ void GB_switch_model_and_reset(GB_gameboy_t *gb, bool is_cgb) void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank) { /* Set size and bank to dummy pointers if not set */ + size_t dummy_size; + uint16_t dummy_bank; if (!size) { - size = alloca(sizeof(size)); + size = &dummy_size; } if (!bank) { - bank = alloca(sizeof(bank)); + bank = &dummy_bank; } diff --git a/Makefile b/Makefile index 18dbe23..2779032 100755 --- a/Makefile +++ b/Makefile @@ -43,10 +43,10 @@ endif # Set compilation and linkage flags based on target, platform and configuration CFLAGS += -Werror -Wall -std=gnu11 -ICore -D_GNU_SOURCE -DVERSION="$(VERSION)" -I. -D_USE_MATH_DEFINES -SDL_LDFLAGS := -lSDL +SDL_LDFLAGS := -lSDL2 ifeq ($(PLATFORM),windows32) CFLAGS += -IWindows -LDFLAGS += -lmsvcrt -lSDLmain -Wl,/MANIFESTFILE:NUL +LDFLAGS += -lmsvcrt -lSDL2main -Wl,/MANIFESTFILE:NUL else LDFLAGS += -lc -lm endif @@ -56,19 +56,16 @@ SYSROOT := $(shell xcodebuild -sdk macosx -version Path 2> /dev/null) CFLAGS += -F/Library/Frameworks OCFLAGS += -x objective-c -fobjc-arc -Wno-deprecated-declarations -isysroot $(SYSROOT) -mmacosx-version-min=10.9 LDFLAGS += -framework AppKit -framework PreferencePanes -framework Carbon -framework QuartzCore -SDL_LDFLAGS := -F/Library/Frameworks -framework SDL +SDL_LDFLAGS := -F/Library/Frameworks -framework SDL2 endif - +CFLAGS += -Wno-deprecated-declarations ifeq ($(PLATFORM),windows32) -CFLAGS += -Wno-deprecated-declarations # Seems like Microsoft deprecated every single LIBC function -LDFLAGS += -Wl,/NODEFAULTLIB:libcmt +CFLAGS += -Wno-deprecated-declarations -Dstrdup=_strdup # Seems like Microsoft deprecated every single LIBC function +LDFLAGS += -Wl,/NODEFAULTLIB:libcmt.lib endif ifeq ($(CONF),debug) CFLAGS += -g -ifeq ($(PLATFORM),windows32) -LDFLAGS += -Wl,/debug -endif else ifeq ($(CONF), release) CFLAGS += -O3 -DNDEBUG ifneq ($(PLATFORM),windows32) @@ -82,7 +79,7 @@ endif # Define our targets ifeq ($(PLATFORM),windows32) -SDL_TARGET := $(BIN)/sdl/sameboy.exe $(BIN)/sdl/sameboy_debugger.exe $(BIN)/sdl/SDL.dll +SDL_TARGET := $(BIN)/sdl/sameboy.exe $(BIN)/sdl/sameboy_debugger.exe $(BIN)/sdl/SDL2.dll TESTER_TARGET := $(BIN)/tester/sameboy_tester.exe else SDL_TARGET := $(BIN)/sdl/sameboy @@ -105,7 +102,6 @@ TESTER_SOURCES := $(shell ls Tester/*.c) ifeq ($(PLATFORM),Darwin) COCOA_SOURCES := $(shell ls Cocoa/*.m) $(shell ls HexFiend/*.m) QUICKLOOK_SOURCES := $(shell ls QuickLook/*.m) $(shell ls QuickLook/*.c) -SDL_SOURCES += $(shell ls SDL/*.m) endif CORE_OBJECTS := $(patsubst %,$(OBJ)/%.o,$(CORE_SOURCES)) @@ -236,11 +232,11 @@ $(OBJ)/%.res: %.rc %.o: %.res cvtres /OUT:"$@" $^ -# We must provide SDL.dll with the Windows port. This is an AWFUL HACK to find it. +# We must provide SDL2.dll with the Windows port. This is an AWFUL HACK to find it. SPACE := SPACE += -$(BIN)/sdl/SDL.dll: - @$(eval POTENTIAL_MATCHES := $(subst @@@," ",$(patsubst %,%/SDL.dll,$(subst ;,$(SPACE),$(subst $(SPACE),@@@,$(lib)))))) +$(BIN)/sdl/SDL2.dll: + @$(eval POTENTIAL_MATCHES := $(subst @@@," ",$(patsubst %,%/SDL2.dll,$(subst ;,$(SPACE),$(subst $(SPACE),@@@,$(lib)))))) @$(eval MATCH := $(shell ls $(POTENTIAL_MATCHES) 2> NUL | head -n 1)) cp "$(MATCH)" $@ diff --git a/SDL/SDLMain.h b/SDL/SDLMain.h deleted file mode 100644 index 9bddc9c..0000000 --- a/SDL/SDLMain.h +++ /dev/null @@ -1,16 +0,0 @@ -/* SDLMain.m - main entry point for our Cocoa-ized SDL app - Initial Version: Darrell Walisser - Non-NIB-Code & other changes: Max Horn - - Feel free to customize this file to suit your needs -*/ - -#ifndef _SDLMain_h_ -#define _SDLMain_h_ - -#import - -@interface SDLMain : NSObject -@end - -#endif /* _SDLMain_h_ */ diff --git a/SDL/SDLMain.m b/SDL/SDLMain.m deleted file mode 100644 index d8aadf5..0000000 --- a/SDL/SDLMain.m +++ /dev/null @@ -1,382 +0,0 @@ -/* SDLMain.m - main entry point for our Cocoa-ized SDL app - Initial Version: Darrell Walisser - Non-NIB-Code & other changes: Max Horn - - Feel free to customize this file to suit your needs -*/ - -#include -#include "SDLMain.h" -#include /* for MAXPATHLEN */ -#include -#import - -/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, - but the method still is there and works. To avoid warnings, we declare - it ourselves here. */ -@interface NSApplication(SDL_Missing_Methods) -- (void)setAppleMenu:(NSMenu *)menu; -@end - -/* Use this flag to determine whether we use SDLMain.nib or not */ -#define SDL_USE_NIB_FILE 0 - -/* Use this flag to determine whether we use CPS (docking) or not */ -#define SDL_USE_CPS 1 -#ifdef SDL_USE_CPS -/* Portions of CPS.h */ -typedef struct CPSProcessSerNum -{ - UInt32 lo; - UInt32 hi; -} CPSProcessSerNum; - -extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); -extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); -extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); - -#endif /* SDL_USE_CPS */ - -static int gArgc; -static char **gArgv; -static BOOL gFinderLaunch; -static BOOL gCalledAppMainline = FALSE; - -static NSString *getApplicationName(void) -{ - const NSDictionary *dict; - NSString *appName = 0; - - /* Determine the application name */ - dict = (__bridge const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); - if (dict) - appName = [dict objectForKey: @"CFBundleName"]; - - if (![appName length]) - appName = [[NSProcessInfo processInfo] processName]; - - return appName; -} - -#if SDL_USE_NIB_FILE -/* A helper category for NSString */ -@interface NSString (ReplaceSubString) -- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString; -@end -#endif - -@interface NSApplication (SDLApplication) -@end - -@implementation NSApplication (SDLApplication) -/* Invoked from the Quit menu item */ -- (void)_terminate:(id)sender -{ - /* Post a SDL_QUIT event */ - SDL_Event event; - event.type = SDL_QUIT; - SDL_PushEvent(&event); - /* Call "super" */ - [self _terminate:sender]; -} - -/* Use swizzling to avoid warning and undocumented Obj C runtime behavior. Didn't feel like rewriting SDLMain for this. */ -+ (void) load -{ - method_exchangeImplementations(class_getInstanceMethod(self, @selector(terminate:)), class_getInstanceMethod(self, @selector(_terminate:))); -} -@end - -/* The main class of the application, the application's delegate */ -@implementation SDLMain - -/* Set the working directory to the .app's parent directory */ -- (void) setupWorkingDirectory:(BOOL)shouldChdir -{ - if (shouldChdir) - { - char parentdir[MAXPATHLEN]; - CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle()); - CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url); - if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) { - chdir(parentdir); /* chdir to the binary app's parent */ - } - CFRelease(url); - CFRelease(url2); - } -} - -#if SDL_USE_NIB_FILE - -/* Fix menu to contain the real app name instead of "SDL App" */ -- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName -{ - NSRange aRange; - NSEnumerator *enumerator; - NSMenuItem *menuItem; - - aRange = [[aMenu title] rangeOfString:@"SDL App"]; - if (aRange.length != 0) - [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; - - enumerator = [[aMenu itemArray] objectEnumerator]; - while ((menuItem = [enumerator nextObject])) - { - aRange = [[menuItem title] rangeOfString:@"SDL App"]; - if (aRange.length != 0) - [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; - if ([menuItem hasSubmenu]) - [self fixMenu:[menuItem submenu] withAppName:appName]; - } -} - -#else - -static void setApplicationMenu(void) -{ - /* warning: this code is very odd */ - NSMenu *appleMenu; - NSMenuItem *menuItem; - NSString *title; - NSString *appName; - - appName = getApplicationName(); - appleMenu = [[NSMenu alloc] initWithTitle:@""]; - - /* Add menu items */ - title = [@"About " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; - - [appleMenu addItem:[NSMenuItem separatorItem]]; - - title = [@"Hide " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; - - menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; - [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; - - [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; - - [appleMenu addItem:[NSMenuItem separatorItem]]; - - title = [@"Quit " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; - - - /* Put menu into the menubar */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; - [menuItem setSubmenu:appleMenu]; - [[NSApp mainMenu] addItem:menuItem]; - - /* Tell the application object that this is now the application menu */ - [NSApp setAppleMenu:appleMenu]; - -} - -/* Create a window menu */ -static void setupWindowMenu(void) -{ - NSMenu *windowMenu; - NSMenuItem *windowMenuItem; - NSMenuItem *menuItem; - - windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; - - /* "Minimize" item */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; - [windowMenu addItem:menuItem]; - - /* Put menu into the menubar */ - windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; - [windowMenuItem setSubmenu:windowMenu]; - [[NSApp mainMenu] addItem:windowMenuItem]; - - /* Tell the application object that this is now the window menu */ - [NSApp setWindowsMenu:windowMenu]; - - /* Finally give up our references to the objects */ -} - -/* Replacement for NSApplicationMain */ -static void CustomApplicationMain (int argc, char **argv) -{ - SDLMain *sdlMain; - - /* Ensure the application object is initialised */ - [NSApplication sharedApplication]; - -#ifdef SDL_USE_CPS - { - CPSProcessSerNum PSN; - /* Tell the dock about us */ - if (!CPSGetCurrentProcess(&PSN)) - if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) - if (!CPSSetFrontProcess(&PSN)) - [NSApplication sharedApplication]; - } -#endif /* SDL_USE_CPS */ - - /* Set up the menubar */ - [NSApp setMainMenu:[[NSMenu alloc] init]]; - setApplicationMenu(); - setupWindowMenu(); - - /* Create SDLMain and make it the app delegate */ - sdlMain = [[SDLMain alloc] init]; - [NSApp setDelegate:sdlMain]; - - /* Start the main event loop */ - [NSApp run]; -} - -#endif - - -/* - * Catch document open requests...this lets us notice files when the app - * was launched by double-clicking a document, or when a document was - * dragged/dropped on the app's icon. You need to have a - * CFBundleDocumentsType section in your Info.plist to get this message, - * apparently. - * - * Files are added to gArgv, so to the app, they'll look like command line - * arguments. Previously, apps launched from the finder had nothing but - * an argv[0]. - * - * This message may be received multiple times to open several docs on launch. - * - * This message is ignored once the app's mainline has been called. - */ -- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename -{ - const char *temparg; - size_t arglen; - char *arg; - char **newargv; - - if (!gFinderLaunch) /* MacOS is passing command line args. */ - return FALSE; - - if (gCalledAppMainline) /* app has started, ignore this document. */ - return FALSE; - - temparg = [filename UTF8String]; - arglen = SDL_strlen(temparg) + 1; - arg = (char *) SDL_malloc(arglen); - if (arg == NULL) - return FALSE; - - newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); - if (newargv == NULL) - { - SDL_free(arg); - return FALSE; - } - gArgv = newargv; - - SDL_strlcpy(arg, temparg, arglen); - gArgv[gArgc++] = arg; - gArgv[gArgc] = NULL; - return TRUE; -} - - -/* Called when the internal event loop has just started running */ -- (void) applicationDidFinishLaunching: (NSNotification *) note -{ - int status; - - /* Set the working directory to the .app's parent directory */ - [self setupWorkingDirectory:gFinderLaunch]; - -#if SDL_USE_NIB_FILE - /* Set the main menu to contain the real app name instead of "SDL App" */ - [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; -#endif - - /* Hand off to main application code */ - gCalledAppMainline = TRUE; - status = SDL_main (gArgc, gArgv); - - /* We're done, thank you for playing */ - exit(status); -} -@end - - -@implementation NSString (ReplaceSubString) - -- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString -{ - unsigned int bufferSize; - unsigned int selfLen = [self length]; - unsigned int aStringLen = [aString length]; - unichar *buffer; - NSRange localRange; - NSString *result; - - bufferSize = selfLen + aStringLen - aRange.length; - buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar)); - - /* Get first part into buffer */ - localRange.location = 0; - localRange.length = aRange.location; - [self getCharacters:buffer range:localRange]; - - /* Get middle part into buffer */ - localRange.location = 0; - localRange.length = aStringLen; - [aString getCharacters:(buffer+aRange.location) range:localRange]; - - /* Get last part into buffer */ - localRange.location = aRange.location + aRange.length; - localRange.length = selfLen - localRange.location; - [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; - - /* Build output string */ - result = [NSString stringWithCharacters:buffer length:bufferSize]; - - NSDeallocateMemoryPages(buffer, bufferSize); - - return result; -} - -@end - - -void cocoa_disable_filtering(void) { - CGContextSetInterpolationQuality([[NSGraphicsContext currentContext] CGContext], kCGInterpolationNone); -} - -#ifdef main -# undef main -#endif - -/* Main entry point to executable - should *not* be SDL_main! */ -int main (int argc, char **argv) -{ - /* Copy the arguments into a global variable */ - /* This is passed if we are launched by double-clicking */ - if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { - gArgv = (char **) SDL_malloc(sizeof (char *) * 2); - gArgv[0] = argv[0]; - gArgv[1] = NULL; - gArgc = 1; - gFinderLaunch = YES; - } else { - int i; - gArgc = argc; - gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); - for (i = 0; i <= argc; i++) - gArgv[i] = argv[i]; - gFinderLaunch = NO; - } - -#if SDL_USE_NIB_FILE - NSApplicationMain (argc, argv); -#else - CustomApplicationMain (argc, argv); -#endif - return 0; -} - diff --git a/SDL/main.c b/SDL/main.c index cd7cf18..df72d49 100755 --- a/SDL/main.c +++ b/SDL/main.c @@ -4,7 +4,7 @@ #include #include #include -#include +#include #ifndef _WIN32 #define AUDIO_FREQUENCY 96000 #else @@ -15,28 +15,94 @@ #define snprintf _snprintf #endif +#if defined(__APPLE__) && SDL_MAJOR_VERSION == 2 && SDL_MINOR_VERSION == 0 && SDL_PATCHLEVEL == 5 +#error You are using SDL2-2.0.5, which contains a bug that prevents 96KHz audio playback on macOS. Use SDL2-2.0.4 or alternatively modify this file to reduce the frequency to 44100 and disable this error. +#endif + #include "gb.h" -static bool running = false; static char *filename; +static char *battery_save_path_ptr; static void replace_extension(const char *src, size_t length, char *dest, const char *ext); + +static SDL_Window *window = NULL; +static SDL_Renderer *renderer = NULL; +static SDL_Texture *texture = NULL; +static SDL_PixelFormat *pixel_format = NULL; +static uint32_t pixels[160*144]; GB_gameboy_t gb; -static void GB_update_keys_status(GB_gameboy_t *gb) +static enum { + GB_SDL_NO_COMMAND, + GB_SDL_SAVE_STATE_COMMAND, + GB_SDL_LOAD_STATE_COMMAND, + GB_SDL_RESET_COMMAND, +} pending_command; +static unsigned command_parameter; + +static void handle_events(GB_gameboy_t *gb) { static bool ctrl = false; static bool shift = false; #ifdef __APPLE__ static bool cmd = false; +#define MODIFIER cmd +#else +#define MODIFIER ctrl #endif SDL_Event event; while (SDL_PollEvent(&event)) { switch( event.type ){ case SDL_QUIT: - running = false; + GB_save_battery(gb, battery_save_path_ptr); + exit(0); + case SDL_KEYDOWN: - case SDL_KEYUP: + switch (event.key.keysym.sym) { + case SDLK_c: + if (ctrl && event.type == SDL_KEYDOWN) { + ctrl = false; + GB_debugger_break(gb); + + } + break; + + case SDLK_r: + if (MODIFIER) { + pending_command = GB_SDL_RESET_COMMAND; + } + break; + + case SDLK_m: + if (MODIFIER) { +#ifdef __APPLE__ + // Can't over CMD+M (Minimize) in SDL + if (!shift) { + break; + } +#endif + SDL_PauseAudio(SDL_GetAudioStatus() == SDL_AUDIO_PLAYING? true : false); + } + break; + + default: + /* Save states */ + if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) { + if (MODIFIER) { + command_parameter = event.key.keysym.sym - SDLK_0; + + if (shift) { + pending_command = GB_SDL_LOAD_STATE_COMMAND; + } + else { + pending_command = GB_SDL_SAVE_STATE_COMMAND; + } + } + } + break; + } + case SDL_KEYUP: // Fallthrough switch (event.key.keysym.sym) { case SDLK_RIGHT: GB_set_key_state(gb, GB_KEY_RIGHT, event.type == SDL_KEYDOWN); @@ -74,42 +140,11 @@ static void GB_update_keys_status(GB_gameboy_t *gb) shift = event.type == SDL_KEYDOWN; break; #ifdef __APPLE__ - case SDLK_LMETA: - case SDLK_RMETA: + case SDLK_LGUI: + case SDLK_RGUI: cmd = event.type == SDL_KEYDOWN; break; #endif - - case SDLK_c: - if (ctrl && event.type == SDL_KEYDOWN) { - ctrl = false; - GB_debugger_break(gb); - - } - break; - - default: - /* Save states */ - if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) { -#ifdef __APPLE__ - if (cmd) { -#else - if (ctrl) { -#endif - char save_path[strlen(filename) + 4]; - char save_extension[] =".s0"; - save_extension[2] += event.key.keysym.sym - SDLK_0; - replace_extension(filename, strlen(filename), save_path, save_extension); - - if (shift) { - GB_load_state(gb, save_path); - } - else { - GB_save_state(gb, save_path); - } - } - } - break; } break; default: @@ -120,11 +155,11 @@ static void GB_update_keys_status(GB_gameboy_t *gb) static void vblank(GB_gameboy_t *gb) { - SDL_Surface *screen = GB_get_user_data(gb); - SDL_Flip(screen); - GB_update_keys_status(gb); - - GB_set_pixels_output(gb, screen->pixels); + SDL_UpdateTexture(texture, NULL, pixels, 160 * sizeof (uint32_t)); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); + handle_events(gb); } #ifdef __APPLE__ @@ -177,11 +212,10 @@ static char *executable_relative_path(const char *filename) snprintf(path, sizeof(path), "%s/%s", executable_folder(), filename); return path; } - -static SDL_Surface *screen = NULL; + static uint32_t rgb_encode(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b) { - return SDL_MapRGB(screen->format, r, g, b); + return SDL_MapRGB(pixel_format, r, g, b); } static void debugger_interrupt(int ignore) @@ -217,9 +251,6 @@ static void replace_extension(const char *src, size_t length, char *dest, const strcat(dest, ext); } -#ifdef __APPLE__ -extern void cocoa_disable_filtering(void); -#endif int main(int argc, char **argv) { bool dmg = false; @@ -270,16 +301,18 @@ usage: signal(SIGINT, debugger_interrupt); SDL_Init( SDL_INIT_EVERYTHING ); - screen = SDL_SetVideoMode(160, 144, 32, SDL_SWSURFACE ); - SDL_WM_SetCaption("SameBoy v" xstr(VERSION), "SameBoy v" xstr(VERSION)); -#ifdef __APPLE__ - cocoa_disable_filtering(); -#endif + + window = SDL_CreateWindow("SameBoy v" xstr(VERSION), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + 160, 144, SDL_WINDOW_OPENGL); + renderer = SDL_CreateRenderer(window, -1, 0); + + texture = SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 160, 144); + + pixel_format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); + /* Configure Screen */ - SDL_LockSurface(screen); GB_set_vblank_callback(&gb, (GB_vblank_callback_t) vblank); - GB_set_user_data(&gb, screen); - GB_set_pixels_output(&gb, screen->pixels); + GB_set_pixels_output(&gb, pixels); GB_set_rgb_encode_callback(&gb, rgb_encode); size_t path_length = strlen(filename); @@ -287,6 +320,7 @@ usage: /* Configure battery */ char battery_save_path[path_length + 5]; /* At the worst case, size is strlen(path) + 4 bytes for .sav + NULL */ replace_extension(filename, path_length, battery_save_path, ".sav"); + battery_save_path_ptr = battery_save_path; GB_load_battery(&gb, battery_save_path); /* Configure symbols */ @@ -306,19 +340,39 @@ usage: want.callback = audio_callback; want.userdata = &gb; SDL_OpenAudio(&want, &have); - GB_set_sample_rate(&gb, AUDIO_FREQUENCY); + GB_set_sample_rate(&gb, have.freq); /* Start Audio */ - SDL_PauseAudio(0); + SDL_PauseAudio(false); /* Run emulation */ - running = true; - while (running) { + while (true) { GB_run(&gb); + switch (pending_command) { + case GB_SDL_LOAD_STATE_COMMAND: + case GB_SDL_SAVE_STATE_COMMAND: { + char save_path[strlen(filename) + 4]; + char save_extension[] = ".s0"; + save_extension[2] += command_parameter; + replace_extension(filename, strlen(filename), save_path, save_extension); + + if (pending_command == GB_SDL_LOAD_STATE_COMMAND) { + GB_load_state(&gb, save_path); + } + else { + GB_save_state(&gb, save_path); + } + break; + } + + case GB_SDL_RESET_COMMAND: + GB_reset(&gb); + break; + + case GB_SDL_NO_COMMAND: + break; + } + pending_command = GB_SDL_NO_COMMAND; } - SDL_CloseAudio(); - - GB_save_battery(&gb, battery_save_path); - return 0; } From 00439f4d4925d1ba60a2aaf36849df8aeb00f246 Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Tue, 23 May 2017 23:18:16 +0300 Subject: [PATCH 2/6] SDL port: added drag and drop support, added model switch command, fixed macOS audio --- Makefile | 23 +++--- SDL/drop.bmp | Bin 0 -> 69176 bytes SDL/main.c | 209 ++++++++++++++++++++++++++++++++++----------------- 3 files changed, 155 insertions(+), 77 deletions(-) create mode 100644 SDL/drop.bmp diff --git a/Makefile b/Makefile index 2779032..3205ec3 100755 --- a/Makefile +++ b/Makefile @@ -79,16 +79,16 @@ endif # Define our targets ifeq ($(PLATFORM),windows32) -SDL_TARGET := $(BIN)/sdl/sameboy.exe $(BIN)/sdl/sameboy_debugger.exe $(BIN)/sdl/SDL2.dll +SDL_TARGET := $(BIN)/SDL/sameboy.exe $(BIN)/SDL/sameboy_debugger.exe $(BIN)/SDL/SDL2.dll TESTER_TARGET := $(BIN)/tester/sameboy_tester.exe else -SDL_TARGET := $(BIN)/sdl/sameboy +SDL_TARGET := $(BIN)/SDL/sameboy TESTER_TARGET := $(BIN)/tester/sameboy_tester endif cocoa: $(BIN)/SameBoy.app quicklook: $(BIN)/SameBoy.qlgenerator -sdl: $(SDL_TARGET) $(BIN)/sdl/dmg_boot.bin $(BIN)/sdl/cgb_boot.bin $(BIN)/sdl/LICENSE $(BIN)/sdl/registers.sym +sdl: $(SDL_TARGET) $(BIN)/SDL/dmg_boot.bin $(BIN)/SDL/cgb_boot.bin $(BIN)/SDL/LICENSE $(BIN)/SDL/registers.sym $(BIN)/SDL/drop.bmp bootroms: $(BIN)/BootROMs/cgb_boot.bin $(BIN)/BootROMs/dmg_boot.bin tester: $(TESTER_TARGET) $(BIN)/tester/dmg_boot.bin $(BIN)/tester/cgb_boot.bin all: cocoa sdl tester @@ -209,7 +209,7 @@ $(BIN)/SameBoy.qlgenerator/Contents/Resources/cgb_boot_fast.bin: $(BIN)/BootROMs # SDL Port # Unix versions build only one binary -$(BIN)/sdl/sameboy: $(CORE_OBJECTS) $(SDL_OBJECTS) +$(BIN)/SDL/sameboy: $(CORE_OBJECTS) $(SDL_OBJECTS) -@$(MKDIR) -p $(dir $@) $(CC) $^ -o $@ $(LDFLAGS) $(SDL_LDFLAGS) ifeq ($(CONF), release) @@ -217,11 +217,11 @@ ifeq ($(CONF), release) endif # Windows version builds two, one with a conole and one without it -$(BIN)/sdl/sameboy.exe: $(CORE_OBJECTS) $(SDL_OBJECTS) $(OBJ)/Windows/resources.o +$(BIN)/SDL/sameboy.exe: $(CORE_OBJECTS) $(SDL_OBJECTS) $(OBJ)/Windows/resources.o -@$(MKDIR) -p $(dir $@) $(CC) $^ -o $@ $(LDFLAGS) $(SDL_LDFLAGS) -Wl,/subsystem:windows -$(BIN)/sdl/sameboy_debugger.exe: $(CORE_OBJECTS) $(SDL_OBJECTS) $(OBJ)/Windows/resources.o +$(BIN)/SDL/sameboy_debugger.exe: $(CORE_OBJECTS) $(SDL_OBJECTS) $(OBJ)/Windows/resources.o -@$(MKDIR) -p $(dir $@) $(CC) $^ -o $@ $(LDFLAGS) $(SDL_LDFLAGS) -Wl,/subsystem:console @@ -235,7 +235,7 @@ $(OBJ)/%.res: %.rc # We must provide SDL2.dll with the Windows port. This is an AWFUL HACK to find it. SPACE := SPACE += -$(BIN)/sdl/SDL2.dll: +$(BIN)/SDL/SDL2.dll: @$(eval POTENTIAL_MATCHES := $(subst @@@," ",$(patsubst %,%/SDL2.dll,$(subst ;,$(SPACE),$(subst $(SPACE),@@@,$(lib)))))) @$(eval MATCH := $(shell ls $(POTENTIAL_MATCHES) 2> NUL | head -n 1)) cp "$(MATCH)" $@ @@ -253,7 +253,7 @@ $(BIN)/tester/sameboy_tester.exe: $(CORE_OBJECTS) $(SDL_OBJECTS) -@$(MKDIR) -p $(dir $@) $(CC) $^ -o $@ $(LDFLAGS) -Wl,/subsystem:console -$(BIN)/sdl/%.bin $(BIN)/tester/%.bin: $(BOOTROMS_DIR)/%.bin +$(BIN)/SDL/%.bin $(BIN)/tester/%.bin: $(BOOTROMS_DIR)/%.bin -@$(MKDIR) -p $(dir $@) cp -f $^ $@ @@ -261,10 +261,13 @@ $(BIN)/SameBoy.app/Contents/Resources/%.bin: $(BOOTROMS_DIR)/%.bin -@$(MKDIR) -p $(dir $@) cp -f $^ $@ -$(BIN)/sdl/LICENSE: LICENSE +$(BIN)/SDL/LICENSE: LICENSE cp -f $^ $@ -$(BIN)/sdl/registers.sym: Misc/registers.sym +$(BIN)/SDL/registers.sym: Misc/registers.sym + cp -f $^ $@ + +$(BIN)/SDL/drop.bmp: SDL/drop.bmp cp -f $^ $@ # Boot ROMs diff --git a/SDL/drop.bmp b/SDL/drop.bmp new file mode 100644 index 0000000000000000000000000000000000000000..fbdc3748735458d782bf91e36ce42b8838b9bfb0 GIT binary patch literal 69176 zcmeI5`F9+}oxn}9kO#!JWZm~Yx<=AybRTnSW;D7-l4V`KIf9KbI02j(L%0({0Gq== zE=aV&f-$gfbFfR;HJbp2eJ{&p@?!%01KCgYcT{d>Bw4m>7|Y$S)UUd_y1VN8 zsqeSGRbA8a545g0W0~5T`K#dXLH_pecgC_z_RE%ih4ZVRe*|qlS`nuXv zB{*tps;eqXii{h_jy9Wu5c(|gkU(7fFaNw3Umj% zf?a;U*VEb2-qhIOsH-h3$Up0>GZ!z4C3y$ndOfazzMhfD;OIzXb;1VKTvuaHPEJ~qfEHOPS4TTiT0J^EJ~n!4g*B^3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%l~KRgF+a$i@tH; zwu`r((t#>a5vs#SkCzgo#nk01U-?R{y_#>nng8vS`EyC9N?iU`78Rj7RBACYv97fw zU`fD|fF%J-0+s|U30M-aBw$Ivl7J-vO9GYzED2Z=uq0qfz> 3) { -usage: - fprintf(stderr, "Usage: %s [--dmg] rom\n", argv[0]); - exit(1); +restart: + if (GB_is_inited(&gb)) { + GB_switch_model_and_reset(&gb, !dmg); } - - if (argc == 3) { - if (strcmp(argv[1], "--dmg") == 0) { - dmg = true; + else { + if (dmg) { + GB_init(&gb); } else { - goto usage; + GB_init_cgb(&gb); } + + GB_set_vblank_callback(&gb, (GB_vblank_callback_t) vblank); + GB_set_pixels_output(&gb, pixels); + GB_set_rgb_encode_callback(&gb, rgb_encode); + GB_set_sample_rate(&gb, have_aspec.freq); } - - + if (dmg) { - GB_init(&gb); if (GB_load_boot_rom(&gb, executable_relative_path("dmg_boot.bin"))) { perror("Failed to load boot ROM"); exit(1); } } else { - GB_init_cgb(&gb); if (GB_load_boot_rom(&gb, executable_relative_path("cgb_boot.bin"))) { perror("Failed to load boot ROM"); exit(1); } } - - filename = argv[argc - 1]; - + if (GB_load_rom(&gb, filename)) { perror("Failed to load ROM"); exit(1); } - - signal(SIGINT, debugger_interrupt); - - SDL_Init( SDL_INIT_EVERYTHING ); - - window = SDL_CreateWindow("SameBoy v" xstr(VERSION), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - 160, 144, SDL_WINDOW_OPENGL); - renderer = SDL_CreateRenderer(window, -1, 0); - - texture = SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 160, 144); - - pixel_format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); - - /* Configure Screen */ - GB_set_vblank_callback(&gb, (GB_vblank_callback_t) vblank); - GB_set_pixels_output(&gb, pixels); - GB_set_rgb_encode_callback(&gb, rgb_encode); - size_t path_length = strlen(filename); - + /* Configure battery */ char battery_save_path[path_length + 5]; /* At the worst case, size is strlen(path) + 4 bytes for .sav + NULL */ replace_extension(filename, path_length, battery_save_path, ".sav"); battery_save_path_ptr = battery_save_path; GB_load_battery(&gb, battery_save_path); - + /* Configure symbols */ GB_debugger_load_symbol_file(&gb, executable_relative_path("registers.sym")); char symbols_path[path_length + 5]; replace_extension(filename, path_length, symbols_path, ".sym"); GB_debugger_load_symbol_file(&gb, symbols_path); - - /* Configure Audio */ - SDL_AudioSpec want, have; - SDL_memset(&want, 0, sizeof(want)); - want.freq = AUDIO_FREQUENCY; - want.format = AUDIO_S16SYS; - want.channels = 2; - want.samples = 512; - want.callback = audio_callback; - want.userdata = &gb; - SDL_OpenAudio(&want, &have); - GB_set_sample_rate(&gb, have.freq); - /* Start Audio */ - SDL_PauseAudio(false); - /* Run emulation */ while (true) { GB_run(&gb); @@ -362,7 +345,7 @@ usage: else { GB_save_state(&gb, save_path); } - break; + break; } case GB_SDL_RESET_COMMAND: @@ -371,8 +354,100 @@ usage: case GB_SDL_NO_COMMAND: break; + + case GB_SDL_NEW_FILE_COMMAND: + pending_command = GB_SDL_NO_COMMAND; + goto restart; + + case GB_SDL_TOGGLE_MODEL_COMMAND: + dmg = !dmg; + pending_command = GB_SDL_NO_COMMAND; + goto restart; } pending_command = GB_SDL_NO_COMMAND; } } + +int main(int argc, char **argv) +{ +#define str(x) #x +#define xstr(x) str(x) + fprintf(stderr, "SameBoy v" xstr(VERSION) "\n"); + if (argc > 3) { +usage: + fprintf(stderr, "Usage: %s [--dmg] [rom]\n", argv[0]); + exit(1); + } + + for (unsigned i = 1; i < argc; i++) { + if (strcmp(argv[i], "--dmg") == 0) { + if (dmg) { + goto usage; + } + dmg = true; + } + else if (!filename) { + filename = argv[i]; + } + else { + goto usage; + } + } + + signal(SIGINT, debugger_interrupt); + + SDL_Init( SDL_INIT_EVERYTHING ); + + window = SDL_CreateWindow("SameBoy v" xstr(VERSION), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + 160, 144, SDL_WINDOW_OPENGL); + renderer = SDL_CreateRenderer(window, -1, 0); + + texture = SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 160, 144); + + pixel_format = SDL_AllocFormat(SDL_GetWindowPixelFormat(window)); + + /* Configure Audio */ + memset(&want_aspec, 0, sizeof(want_aspec)); + want_aspec.freq = AUDIO_FREQUENCY; + want_aspec.format = AUDIO_S16SYS; + want_aspec.channels = 2; + want_aspec.samples = 2048; + want_aspec.callback = audio_callback; + want_aspec.userdata = &gb; + SDL_OpenAudio(&want_aspec, &have_aspec); + + /* Start Audio */ + SDL_PauseAudio(false); + + SDL_EventState(SDL_DROPFILE, SDL_ENABLE); + + if (filename == NULL) { + /* Draw the "Drop file" screen */ + SDL_Surface *drop_backround = SDL_LoadBMP(executable_relative_path("drop.bmp")); + SDL_Surface *drop_converted = SDL_ConvertSurface(drop_backround, pixel_format, 0); + SDL_LockSurface(drop_converted); + SDL_UpdateTexture(texture, NULL, drop_converted->pixels, drop_converted->pitch); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); + SDL_FreeSurface(drop_converted); + SDL_FreeSurface(drop_backround) + ; + SDL_Event event; + while (SDL_WaitEvent(&event)) + { + if (event.type == SDL_QUIT) { + exit(0); + } + else if (event.type == SDL_DROPFILE) { + filename = event.drop.file; + should_free_filename = true; + break; + } + } + } + + run(); // Never returns + return 0; +} From 52e99adc32b56ae6e2fbcb888ba79afba034ca94 Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Wed, 24 May 2017 20:33:39 +0300 Subject: [PATCH 3/6] SDL port: Resizing, resizing modes, and pause support --- SDL/main.c | 110 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 99 insertions(+), 11 deletions(-) diff --git a/SDL/main.c b/SDL/main.c index d4bb447..c9afe0a 100755 --- a/SDL/main.c +++ b/SDL/main.c @@ -5,6 +5,7 @@ #include #include #include + #ifndef _WIN32 #define AUDIO_FREQUENCY 96000 #else @@ -28,6 +29,8 @@ static SDL_Texture *texture = NULL; static SDL_PixelFormat *pixel_format = NULL; static SDL_AudioSpec want_aspec, have_aspec; +static bool paused = false; + static uint32_t pixels[160*144]; GB_gameboy_t gb; @@ -39,8 +42,54 @@ static enum { GB_SDL_NEW_FILE_COMMAND, GB_SDL_TOGGLE_MODEL_COMMAND, } pending_command; + +static enum { + GB_SDL_SCALING_ENTIRE_WINDOW, + GB_SDL_SCALING_KEEP_RATIO, + GB_SDL_SCALING_INTEGER_FACTOR, + GB_SDL_SCALING_MAX, +} scaling_mode = GB_SDL_SCALING_INTEGER_FACTOR; static unsigned command_parameter; +static void update_viewport(void) +{ + int win_width, win_height; + SDL_GetWindowSize(window, &win_width, &win_height); + double x_factor = win_width / 160.0; + double y_factor = win_height / 144.0; + + if (scaling_mode == GB_SDL_SCALING_INTEGER_FACTOR) { + x_factor = floor(x_factor); + y_factor = floor(y_factor); + } + + if (scaling_mode != GB_SDL_SCALING_ENTIRE_WINDOW) { + if (x_factor > y_factor) { + x_factor = y_factor; + } + else { + y_factor = x_factor; + } + } + + unsigned new_width = x_factor * 160; + unsigned new_height = y_factor * 144; + + SDL_Rect rect = (SDL_Rect){(win_width - new_width) / 2, (win_height - new_height) /2, + new_width, new_height}; + SDL_RenderSetViewport(renderer, &rect); +} + +static void cycle_scaling(void) +{ + scaling_mode++; + scaling_mode %= GB_SDL_SCALING_MAX; + update_viewport(); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); +} + static void handle_events(GB_gameboy_t *gb) { static bool ctrl = false; @@ -54,7 +103,7 @@ static void handle_events(GB_gameboy_t *gb) SDL_Event event; while (SDL_PollEvent(&event)) { - switch( event.type ){ + switch (event.type) { case SDL_QUIT: GB_save_battery(gb, battery_save_path_ptr); exit(0); @@ -69,6 +118,12 @@ static void handle_events(GB_gameboy_t *gb) break; } + case SDL_WINDOWEVENT: { + if (event.window.event == SDL_WINDOWEVENT_RESIZED) { + update_viewport(); + } + } + case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_c: @@ -90,6 +145,12 @@ static void handle_events(GB_gameboy_t *gb) pending_command = GB_SDL_TOGGLE_MODEL_COMMAND; } break; + + case SDLK_p: + if (MODIFIER) { + paused = !paused; + } + break; case SDLK_m: if (MODIFIER) { @@ -103,6 +164,10 @@ static void handle_events(GB_gameboy_t *gb) } break; + case SDLK_TAB: + cycle_scaling(); + break; + default: /* Save states */ if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) { @@ -330,7 +395,13 @@ restart: /* Run emulation */ while (true) { - GB_run(&gb); + if (paused) { + SDL_WaitEvent(NULL); + handle_events(&gb); + } + else { + GB_run(&gb); + } switch (pending_command) { case GB_SDL_LOAD_STATE_COMMAND: case GB_SDL_SAVE_STATE_COMMAND: { @@ -400,7 +471,8 @@ usage: SDL_Init( SDL_INIT_EVERYTHING ); window = SDL_CreateWindow("SameBoy v" xstr(VERSION), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - 160, 144, SDL_WINDOW_OPENGL); + 160 * 2, 144 * 2, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); + SDL_SetWindowMinimumSize(window, 160, 144); renderer = SDL_CreateRenderer(window, -1, 0); texture = SDL_CreateTexture(renderer, SDL_GetWindowPixelFormat(window), SDL_TEXTUREACCESS_STREAMING, 160, 144); @@ -437,17 +509,33 @@ usage: SDL_Event event; while (SDL_WaitEvent(&event)) { - if (event.type == SDL_QUIT) { - exit(0); - } - else if (event.type == SDL_DROPFILE) { - filename = event.drop.file; - should_free_filename = true; - break; + switch (event.type) { + case SDL_QUIT: { + exit(0); + } + case SDL_WINDOWEVENT: { + if (event.window.event == SDL_WINDOWEVENT_RESIZED) { + update_viewport(); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); + } + break; + } + case SDL_DROPFILE: { + filename = event.drop.file; + should_free_filename = true; + goto start; + } + case SDL_KEYDOWN: + if (event.key.keysym.sym == SDLK_TAB) { + cycle_scaling(); + } + break; } } } - +start: run(); // Never returns return 0; } From 4d5dc6a30eacc8e04a3008ddbcdf46c4dd119114 Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Wed, 24 May 2017 21:44:43 +0300 Subject: [PATCH 4/6] Cleanup --- Core/apu.c | 8 --- Core/display.c | 1 - Core/gb.c | 7 +- Core/symbol_hash.c | 5 +- Makefile | 2 +- SDL/main.c | 163 +++++++++++++------------------------------ SDL/utils.c | 76 ++++++++++++++++++++ SDL/utils.h | 8 +++ Windows/math.h | 7 ++ Windows/stdint.h | 3 + Windows/stdio.h | 4 +- Windows/string.h | 3 + Windows/sys/select.h | 0 Windows/sys/time.h | 0 Windows/unistd.h | 0 15 files changed, 154 insertions(+), 133 deletions(-) create mode 100644 SDL/utils.c create mode 100644 SDL/utils.h create mode 100755 Windows/math.h create mode 100755 Windows/stdint.h create mode 100755 Windows/string.h delete mode 100755 Windows/sys/select.h delete mode 100755 Windows/sys/time.h delete mode 100755 Windows/unistd.h diff --git a/Core/apu.c b/Core/apu.c index 5b43d77..cb87e66 100755 --- a/Core/apu.c +++ b/Core/apu.c @@ -15,14 +15,6 @@ _a > _b ? _a : _b; }) __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) -#ifdef _WIN32 -/* "Old" (Pre-2015) Windows headers/libc don't have round. */ -static inline double round(double f) -{ - return f >= 0? (int)(f + 0.5) : (int)(f - 0.5); -} -#endif - #define APU_FREQUENCY 0x80000 static int16_t generate_square(uint64_t phase, uint32_t wave_length, int16_t amplitude, uint8_t duty) diff --git a/Core/display.c b/Core/display.c index 61a31f3..c8c326e 100755 --- a/Core/display.c +++ b/Core/display.c @@ -1,5 +1,4 @@ #include -#include #include #include #include diff --git a/Core/gb.c b/Core/gb.c index cf334b5..a0dc414 100755 --- a/Core/gb.c +++ b/Core/gb.c @@ -2,12 +2,13 @@ #include #include #include -#include #include #include #include -#include +#ifndef _WIN32 +#include #include +#endif #include "gb.h" void GB_attributed_logv(GB_gameboy_t *gb, GB_log_attributes attributes, const char *fmt, va_list args) @@ -34,7 +35,7 @@ void GB_attributed_log(GB_gameboy_t *gb, GB_log_attributes attributes, const cha va_end(args); } -void GB_log(GB_gameboy_t *gb,const char *fmt, ...) +void GB_log(GB_gameboy_t *gb, const char *fmt, ...) { va_list args; va_start(args, fmt); diff --git a/Core/symbol_hash.c b/Core/symbol_hash.c index 37664e1..709421c 100755 --- a/Core/symbol_hash.c +++ b/Core/symbol_hash.c @@ -1,7 +1,4 @@ #include "gb.h" -#ifdef _WIN32 -typedef intptr_t ssize_t; -#endif static size_t GB_map_find_symbol_index(GB_symbol_map_t *map, uint16_t addr) { @@ -106,4 +103,4 @@ const GB_symbol_t *GB_reversed_map_find_symbol(GB_reversed_symbol_map_t *map, co } return NULL; -} \ No newline at end of file +} diff --git a/Makefile b/Makefile index 3205ec3..15f675f 100755 --- a/Makefile +++ b/Makefile @@ -60,7 +60,7 @@ SDL_LDFLAGS := -F/Library/Frameworks -framework SDL2 endif CFLAGS += -Wno-deprecated-declarations ifeq ($(PLATFORM),windows32) -CFLAGS += -Wno-deprecated-declarations -Dstrdup=_strdup # Seems like Microsoft deprecated every single LIBC function +CFLAGS += -Wno-deprecated-declarations # Seems like Microsoft deprecated every single LIBC function LDFLAGS += -Wl,/NODEFAULTLIB:libcmt.lib endif diff --git a/SDL/main.c b/SDL/main.c index c9afe0a..072a97f 100755 --- a/SDL/main.c +++ b/SDL/main.c @@ -1,27 +1,26 @@ -#include #include -#include -#include -#include #include #include +#include "gb.h" + +#include "utils.h" #ifndef _WIN32 #define AUDIO_FREQUENCY 96000 #else /* Windows (well, at least my VM) can't handle 96KHz sound well :( */ #define AUDIO_FREQUENCY 44100 -#include -#include -#define snprintf _snprintf #endif -#include "gb.h" + +GB_gameboy_t gb; +static bool dmg = false; +static bool paused = false; +static uint32_t pixels[160*144]; static char *filename = NULL; static bool should_free_filename = false; static char *battery_save_path_ptr; -static void replace_extension(const char *src, size_t length, char *dest, const char *ext); static SDL_Window *window = NULL; static SDL_Renderer *renderer = NULL; @@ -29,11 +28,6 @@ static SDL_Texture *texture = NULL; static SDL_PixelFormat *pixel_format = NULL; static SDL_AudioSpec want_aspec, have_aspec; -static bool paused = false; - -static uint32_t pixels[160*144]; -GB_gameboy_t gb; - static enum { GB_SDL_NO_COMMAND, GB_SDL_SAVE_STATE_COMMAND, @@ -59,8 +53,8 @@ static void update_viewport(void) double y_factor = win_height / 144.0; if (scaling_mode == GB_SDL_SCALING_INTEGER_FACTOR) { - x_factor = floor(x_factor); - y_factor = floor(y_factor); + x_factor = (int)(x_factor); + y_factor = (int)(y_factor); } if (scaling_mode != GB_SDL_SCALING_ENTIRE_WINDOW) { @@ -244,57 +238,7 @@ static void vblank(GB_gameboy_t *gb) handle_events(gb); } -#ifdef __APPLE__ -#include -#endif -static const char *executable_folder(void) -{ - static char path[1024] = {0,}; - if (path[0]) { - return path; - } - /* Ugly unportable code! :( */ -#ifdef __APPLE__ - unsigned int length = sizeof(path) - 1; - _NSGetExecutablePath(&path[0], &length); -#else -#ifdef __linux__ - ssize_t length = readlink("/proc/self/exe", &path[0], sizeof(path) - 1); - assert (length != -1); -#else -#ifdef _WIN32 - HMODULE hModule = GetModuleHandle(NULL); - GetModuleFileName(hModule, path, sizeof(path) - 1); -#else - /* No OS-specific way, assume running from CWD */ - getcwd(&path[0], sizeof(path) - 1); - return path; -#endif -#endif -#endif - size_t pos = strlen(path); - while (pos) { - pos--; -#ifdef _WIN32 - if (path[pos] == '\\') { -#else - if (path[pos] == '/') { -#endif - path[pos] = 0; - break; - } - } - return path; -} - -static char *executable_relative_path(const char *filename) -{ - static char path[1024]; - snprintf(path, sizeof(path), "%s/%s", executable_folder(), filename); - return path; -} - static uint32_t rgb_encode(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b) { return SDL_MapRGB(pixel_format, r, g, b); @@ -319,27 +263,43 @@ static void audio_callback(void *gb, Uint8 *stream, int len) memset(stream, 0, len); } } - -static void replace_extension(const char *src, size_t length, char *dest, const char *ext) + +static bool handle_pending_command(void) { - memcpy(dest, src, length); - dest[length] = 0; - - /* Remove extension */ - for (size_t i = length; i--;) { - if (dest[i] == '/') break; - if (dest[i] == '.') { - dest[i] = 0; - break; + switch (pending_command) { + case GB_SDL_LOAD_STATE_COMMAND: + case GB_SDL_SAVE_STATE_COMMAND: { + char save_path[strlen(filename) + 4]; + char save_extension[] = ".s0"; + save_extension[2] += command_parameter; + replace_extension(filename, strlen(filename), save_path, save_extension); + + if (pending_command == GB_SDL_LOAD_STATE_COMMAND) { + GB_load_state(&gb, save_path); + } + else { + GB_save_state(&gb, save_path); + } + return false; } + + case GB_SDL_RESET_COMMAND: + GB_reset(&gb); + return false; + + case GB_SDL_NO_COMMAND: + return false; + + case GB_SDL_NEW_FILE_COMMAND: + return true; + + case GB_SDL_TOGGLE_MODEL_COMMAND: + dmg = !dmg; + return true; } - - /* Add new extension */ - strcat(dest, ext); + return false; } - -static bool dmg = false; - + static void run(void) { restart: @@ -402,38 +362,11 @@ restart: else { GB_run(&gb); } - switch (pending_command) { - case GB_SDL_LOAD_STATE_COMMAND: - case GB_SDL_SAVE_STATE_COMMAND: { - char save_path[strlen(filename) + 4]; - char save_extension[] = ".s0"; - save_extension[2] += command_parameter; - replace_extension(filename, strlen(filename), save_path, save_extension); - - if (pending_command == GB_SDL_LOAD_STATE_COMMAND) { - GB_load_state(&gb, save_path); - } - else { - GB_save_state(&gb, save_path); - } - break; - } - - case GB_SDL_RESET_COMMAND: - GB_reset(&gb); - break; - - case GB_SDL_NO_COMMAND: - break; - - case GB_SDL_NEW_FILE_COMMAND: - pending_command = GB_SDL_NO_COMMAND; - goto restart; - - case GB_SDL_TOGGLE_MODEL_COMMAND: - dmg = !dmg; - pending_command = GB_SDL_NO_COMMAND; - goto restart; + + /* These commands can't run in the handle_event function, because they're not safe in a vblank context. */ + if (handle_pending_command()) { + pending_command = GB_SDL_NO_COMMAND; + goto restart; } pending_command = GB_SDL_NO_COMMAND; } diff --git a/SDL/utils.c b/SDL/utils.c new file mode 100644 index 0000000..56ba7ac --- /dev/null +++ b/SDL/utils.c @@ -0,0 +1,76 @@ +#include +#include +#ifdef __APPLE__ +#include +#endif +#ifdef _WIN32 +#include +#include +#endif +#include "utils.h" + +const char *executable_folder(void) +{ + static char path[1024] = {0,}; + if (path[0]) { + return path; + } + /* Ugly unportable code! :( */ +#ifdef __APPLE__ + unsigned int length = sizeof(path) - 1; + _NSGetExecutablePath(&path[0], &length); +#else +#ifdef __linux__ + ssize_t length = readlink("/proc/self/exe", &path[0], sizeof(path) - 1); + assert (length != -1); +#else +#ifdef _WIN32 + HMODULE hModule = GetModuleHandle(NULL); + GetModuleFileName(hModule, path, sizeof(path) - 1); +#else + /* No OS-specific way, assume running from CWD */ + getcwd(&path[0], sizeof(path) - 1); + return path; +#endif +#endif +#endif + size_t pos = strlen(path); + while (pos) { + pos--; +#ifdef _WIN32 + if (path[pos] == '\\') { +#else + if (path[pos] == '/') { +#endif + path[pos] = 0; + break; + } + } + return path; +} + +char *executable_relative_path(const char *filename) +{ + static char path[1024]; + snprintf(path, sizeof(path), "%s/%s", executable_folder(), filename); + return path; +} + + +void replace_extension(const char *src, size_t length, char *dest, const char *ext) +{ + memcpy(dest, src, length); + dest[length] = 0; + + /* Remove extension */ + for (size_t i = length; i--;) { + if (dest[i] == '/') break; + if (dest[i] == '.') { + dest[i] = 0; + break; + } + } + + /* Add new extension */ + strcat(dest, ext); +} diff --git a/SDL/utils.h b/SDL/utils.h new file mode 100644 index 0000000..21e900a --- /dev/null +++ b/SDL/utils.h @@ -0,0 +1,8 @@ +#ifndef utils_h +#define utils_h + +const char *executable_folder(void); +char *executable_relative_path(const char *filename); +void replace_extension(const char *src, size_t length, char *dest, const char *ext); + +#endif /* utils_h */ diff --git a/Windows/math.h b/Windows/math.h new file mode 100755 index 0000000..41d6d8a --- /dev/null +++ b/Windows/math.h @@ -0,0 +1,7 @@ +#pragma once +#include_next +/* "Old" (Pre-2015) Windows headers/libc don't have round. */ +static inline double round(double f) +{ + return f >= 0? (int)(f + 0.5) : (int)(f - 0.5); +} \ No newline at end of file diff --git a/Windows/stdint.h b/Windows/stdint.h new file mode 100755 index 0000000..cbe84d5 --- /dev/null +++ b/Windows/stdint.h @@ -0,0 +1,3 @@ +#pragma once +#include_next +typedef intptr_t ssize_t; \ No newline at end of file diff --git a/Windows/stdio.h b/Windows/stdio.h index 8ff90e4..33ced45 100755 --- a/Windows/stdio.h +++ b/Windows/stdio.h @@ -66,4 +66,6 @@ static inline size_t getline(char **lineptr, size_t *n, FILE *stream) { *n = size; return p - bufptr - 1; -} \ No newline at end of file +} + +#define snprintf _snprintf \ No newline at end of file diff --git a/Windows/string.h b/Windows/string.h new file mode 100755 index 0000000..b899ca9 --- /dev/null +++ b/Windows/string.h @@ -0,0 +1,3 @@ +#pragma once +#include_next +#define strdup _strdup \ No newline at end of file diff --git a/Windows/sys/select.h b/Windows/sys/select.h deleted file mode 100755 index e69de29..0000000 diff --git a/Windows/sys/time.h b/Windows/sys/time.h deleted file mode 100755 index e69de29..0000000 diff --git a/Windows/unistd.h b/Windows/unistd.h deleted file mode 100755 index e69de29..0000000 From ece1a11a2324160a0ffa15dd60c60c01aa7129c4 Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Thu, 25 May 2017 23:28:48 +0300 Subject: [PATCH 5/6] SDL port: GUI-based error reporting, added help dialog (? on macOS, F1 on everything else) --- Core/gb.c | 13 ++++- SDL/main.c | 152 ++++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 121 insertions(+), 44 deletions(-) diff --git a/Core/gb.c b/Core/gb.c index a0dc414..a4b3b26 100755 --- a/Core/gb.c +++ b/Core/gb.c @@ -151,7 +151,10 @@ void GB_free(GB_gameboy_t *gb) int GB_load_boot_rom(GB_gameboy_t *gb, const char *path) { FILE *f = fopen(path, "rb"); - if (!f) return errno; + if (!f) { + GB_log(gb, "Could not open boot ROM: %s.\n", strerror(errno)); + return errno; + } fread(gb->boot_rom, sizeof(gb->boot_rom), 1, f); fclose(f); return 0; @@ -160,7 +163,10 @@ int GB_load_boot_rom(GB_gameboy_t *gb, const char *path) int GB_load_rom(GB_gameboy_t *gb, const char *path) { FILE *f = fopen(path, "rb"); - if (!f) return errno; + if (!f) { + GB_log(gb, "Could not open ROM: %s.\n", strerror(errno)); + return errno; + } fseek(f, 0, SEEK_END); gb->rom_size = (ftell(f) + 0x3FFF) & ~0x3FFF; /* Round to bank */ /* And then round to a power of two */ @@ -202,6 +208,7 @@ int GB_save_state(GB_gameboy_t *gb, const char *path) { FILE *f = fopen(path, "wb"); if (!f) { + GB_log(gb, "Could not open save state: %s.\n", strerror(errno)); return errno; } @@ -269,6 +276,7 @@ int GB_load_state(GB_gameboy_t *gb, const char *path) FILE *f = fopen(path, "rb"); if (!f) { + GB_log(gb, "Could not open save state: %s.\n", strerror(errno)); return errno; } @@ -345,6 +353,7 @@ int GB_save_battery(GB_gameboy_t *gb, const char *path) if (gb->mbc_ram_size == 0 && !gb->cartridge_type->has_rtc) return 0; /* Claims to have battery, but has no RAM or RTC */ FILE *f = fopen(path, "wb"); if (!f) { + GB_log(gb, "Could not open save state: %s.\n", strerror(errno)); return errno; } diff --git a/SDL/main.c b/SDL/main.c index 072a97f..21f18db 100755 --- a/SDL/main.c +++ b/SDL/main.c @@ -12,6 +12,36 @@ #define AUDIO_FREQUENCY 44100 #endif +#ifdef __APPLE__ +#define MODIFIER_NAME "Cmd" +#else +#define MODIFIER_NAME "Ctrl" +#endif + +static const char help[] = +"Drop a GB or GBC ROM file to play.\n" +"\n" +"Controls:\n" +" D-Pad: Arrow Keys\n" +" A: X\n" +" B: Z\n" +" Start: Enter\n" +" Select: Backspace\n" +"\n" +"Keyboard Shortcuts: \n" +" Restart: " MODIFIER_NAME "+R\n" +" Pause: " MODIFIER_NAME "+P\n" +" Turbo: Space\n" +#ifdef __APPLE__ +" Mute/Unmute: " MODIFIER_NAME "+Shift+M\n" +#else +" Mute/Unmute: " MODIFIER_NAME "+M\n" +#endif +" Save state: " MODIFIER_NAME "+Number (0-9)\n" +" Load state: " MODIFIER_NAME "+Shift+Number (0-9)\n" +" Cycle between DMG/CGB emulation: " MODIFIER_NAME "+T\n" +" Cycle scaling modes: Tab" +; GB_gameboy_t gb; static bool dmg = false; @@ -28,6 +58,45 @@ static SDL_Texture *texture = NULL; static SDL_PixelFormat *pixel_format = NULL; static SDL_AudioSpec want_aspec, have_aspec; +static char *captured_log = NULL; + +static void log_capture_callback(GB_gameboy_t *gb, const char *string, GB_log_attributes attributes) +{ + size_t current_len = strlen(captured_log); + size_t len_to_add = strlen(string); + captured_log = realloc(captured_log, current_len + len_to_add + 1); + memcpy(captured_log + current_len, string, len_to_add); + captured_log[current_len + len_to_add] = 0; +} + +static void start_capturing_logs(void) +{ + if (captured_log != NULL) { + free(captured_log); + } + captured_log = malloc(1); + captured_log[0] = 0; + GB_set_log_callback(&gb, log_capture_callback); +} + +static const char *end_capturing_logs(bool show_popup, bool should_exit) +{ + GB_set_log_callback(&gb, NULL); + if (captured_log[0] == 0) { + free(captured_log); + captured_log = NULL; + } + else { + if (show_popup) { + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", captured_log, window); + } + if (should_exit) { + exit(1); + } + } + return captured_log; +} + static enum { GB_SDL_NO_COMMAND, GB_SDL_SAVE_STATE_COMMAND, @@ -86,13 +155,10 @@ static void cycle_scaling(void) static void handle_events(GB_gameboy_t *gb) { - static bool ctrl = false; - static bool shift = false; #ifdef __APPLE__ - static bool cmd = false; -#define MODIFIER cmd +#define MODIFIER KMOD_GUI #else -#define MODIFIER ctrl +#define MODIFIER KMOD_CTRL #endif SDL_Event event; while (SDL_PollEvent(&event)) @@ -121,36 +187,35 @@ static void handle_events(GB_gameboy_t *gb) case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_c: - if (ctrl && event.type == SDL_KEYDOWN) { - ctrl = false; + if (event.type == SDL_KEYDOWN && (event.key.keysym.mod & KMOD_CTRL)) { GB_debugger_break(gb); } break; case SDLK_r: - if (MODIFIER) { + if (event.key.keysym.mod & MODIFIER) { pending_command = GB_SDL_RESET_COMMAND; } break; case SDLK_t: - if (MODIFIER) { + if (event.key.keysym.mod & MODIFIER) { pending_command = GB_SDL_TOGGLE_MODEL_COMMAND; } break; case SDLK_p: - if (MODIFIER) { + if (event.key.keysym.mod & MODIFIER) { paused = !paused; } break; case SDLK_m: - if (MODIFIER) { + if (event.key.keysym.mod & MODIFIER) { #ifdef __APPLE__ // Can't override CMD+M (Minimize) in SDL - if (!shift) { + if (!(event.key.keysym.mod & KMOD_SHIFT)) { break; } #endif @@ -161,14 +226,26 @@ static void handle_events(GB_gameboy_t *gb) case SDLK_TAB: cycle_scaling(); break; +#ifndef __APPLE__ + case SDLK_F1: + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Help", help, window); + break; +#else + case SDLK_SLASH: + if (!(event.key.keysym.sym && (event.key.keysym.mod & KMOD_SHIFT))) { + break; + } + case SDLK_QUESTION: + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Help", help, window); +#endif default: /* Save states */ if (event.key.keysym.sym >= SDLK_0 && event.key.keysym.sym <= SDLK_9) { - if (MODIFIER) { + if (event.key.keysym.mod & MODIFIER) { command_parameter = event.key.keysym.sym - SDLK_0; - if (shift) { + if (event.key.keysym.mod & KMOD_SHIFT) { pending_command = GB_SDL_LOAD_STATE_COMMAND; } else { @@ -207,20 +284,6 @@ static void handle_events(GB_gameboy_t *gb) case SDLK_SPACE: GB_set_turbo_mode(gb, event.type == SDL_KEYDOWN, false); break; - case SDLK_LCTRL: - case SDLK_RCTRL: - ctrl = event.type == SDL_KEYDOWN; - break; - case SDLK_LSHIFT: - case SDLK_RSHIFT: - shift = event.type == SDL_KEYDOWN; - break; -#ifdef __APPLE__ - case SDLK_LGUI: - case SDLK_RGUI: - cmd = event.type == SDL_KEYDOWN; - break; -#endif } break; default: @@ -274,12 +337,14 @@ static bool handle_pending_command(void) save_extension[2] += command_parameter; replace_extension(filename, strlen(filename), save_path, save_extension); + start_capturing_logs(); if (pending_command == GB_SDL_LOAD_STATE_COMMAND) { GB_load_state(&gb, save_path); } else { GB_save_state(&gb, save_path); } + end_capturing_logs(true, false); return false; } @@ -320,23 +385,18 @@ restart: GB_set_sample_rate(&gb, have_aspec.freq); } + start_capturing_logs(); if (dmg) { - if (GB_load_boot_rom(&gb, executable_relative_path("dmg_boot.bin"))) { - perror("Failed to load boot ROM"); - exit(1); - } + GB_load_boot_rom(&gb, executable_relative_path("dmg_boot.bin")); } else { - if (GB_load_boot_rom(&gb, executable_relative_path("cgb_boot.bin"))) { - perror("Failed to load boot ROM"); - exit(1); - } + GB_load_boot_rom(&gb, executable_relative_path("cgb_boot.bin")); } + end_capturing_logs(true, true); - if (GB_load_rom(&gb, filename)) { - perror("Failed to load ROM"); - exit(1); - } + start_capturing_logs(); + GB_load_rom(&gb, filename); + end_capturing_logs(true, true); size_t path_length = strlen(filename); @@ -437,8 +497,7 @@ usage: SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); SDL_FreeSurface(drop_converted); - SDL_FreeSurface(drop_backround) - ; + SDL_FreeSurface(drop_backround); SDL_Event event; while (SDL_WaitEvent(&event)) { @@ -464,6 +523,15 @@ usage: if (event.key.keysym.sym == SDLK_TAB) { cycle_scaling(); } +#ifndef __APPLE__ + else if (event.key.keysym.sym == SDLK_F1) { + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Help", help, window); + } +#else + else if (event.key.keysym.sym == SDLK_QUESTION || (event.key.keysym.sym && (event.key.keysym.mod & KMOD_SHIFT))) { + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Help", help, window); + } +#endif break; } } From 6e7ab3558a6aa08bf1130ee6fab8ac97f692dbce Mon Sep 17 00:00:00 2001 From: Lior Halphon Date: Sat, 27 May 2017 12:29:36 +0300 Subject: [PATCH 6/6] Use a smaller audio buffer size if supported. --- SDL/main.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/SDL/main.c b/SDL/main.c index 21f18db..8105927 100755 --- a/SDL/main.c +++ b/SDL/main.c @@ -477,7 +477,13 @@ usage: want_aspec.freq = AUDIO_FREQUENCY; want_aspec.format = AUDIO_S16SYS; want_aspec.channels = 2; +#if SDL_COMPILEDVERSION == 2005 && defined(__APPLE__) + /* SDL 2.0.5 on macOS introduced a bug where certain combinations of buffer lengths and frequencies + fail to produce audio correctly. This bug was fixed 2.0.6. */ want_aspec.samples = 2048; +#else + want_aspec.samples = 512; +#endif want_aspec.callback = audio_callback; want_aspec.userdata = &gb; SDL_OpenAudio(&want_aspec, &have_aspec);