git.y1.nz

SameBoy

Accurate GB/GBC emulator
download: https://git.y1.nz/archives/sameboy.tar.gz
README | Files | Log | Refs | LICENSE

Core/gb.h

      1 #pragma once
      2 
      3 #ifdef __cplusplus
      4 extern "C" {
      5 #endif
      6 
      7 #include <stdbool.h>
      8 #include <stdint.h>
      9 #include <stdalign.h>
     10 #include <time.h>
     11 
     12 #ifndef GB_DISABLE_CHEAT_SEARCH
     13 #ifdef GB_DISABLE_CHEATS
     14 #define GB_DISABLE_CHEAT_SEARCH
     15 #else
     16 #ifdef GB_DISABLE_DEBUGGER
     17 #define GB_DISABLE_CHEAT_SEARCH
     18 #endif
     19 #endif
     20 #endif
     21 
     22 #include "model.h"
     23 #include "defs.h"
     24 #include "save_state.h"
     25 
     26 #include "apu.h"
     27 #include "camera.h"
     28 #include "debugger.h"
     29 #include "display.h"
     30 #include "joypad.h"
     31 #include "mbc.h"
     32 #include "memory.h"
     33 #include "printer.h"
     34 #include "timing.h"
     35 #include "rewind.h"
     36 #include "sm83_cpu.h"
     37 #include "symbol_hash.h"
     38 #include "sgb.h"
     39 #include "cheats.h"
     40 #include "cheat_search.h"
     41 #include "rumble.h"
     42 #include "workboy.h"
     43 #include "random.h"
     44 
     45 #ifdef GB_INTERNAL
     46 #define STRUCT_VERSION 15
     47 #endif
     48 
     49 #define GB_REWIND_FRAMES_PER_KEY 255
     50 
     51 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
     52 #define GB_BIG_ENDIAN
     53 #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
     54 #define GB_LITTLE_ENDIAN
     55 #else
     56 #error Unable to detect endianess
     57 #endif
     58 
     59 #ifdef GB_BIG_ENDIAN
     60 #define GB_REGISTER_ORDER a, f, \
     61                           b, c, \
     62                           d, e, \
     63                           h, l
     64 #else
     65 #define GB_REGISTER_ORDER f, a, \
     66                           c, b, \
     67                           e, d, \
     68                           l, h
     69 #endif
     70 
     71 typedef union {
     72     struct {
     73         uint8_t seconds;
     74         uint8_t minutes;
     75         uint8_t hours;
     76         uint8_t days;
     77         uint8_t high;
     78     };
     79     struct {
     80         uint8_t seconds;
     81         uint8_t minutes;
     82         uint8_t hours:5;
     83         uint8_t weekday:3;
     84         uint8_t weeks;
     85     } tpp1;
     86     uint8_t data[5];
     87 } GB_rtc_time_t;
     88 
     89 typedef struct __attribute__((packed)) {
     90     uint64_t last_rtc_second;
     91     uint16_t minutes;
     92     uint16_t days;
     93     uint16_t alarm_minutes, alarm_days;
     94     uint8_t alarm_enabled;
     95 } GB_huc3_rtc_time_t;
     96 
     97 enum {
     98     GB_REGISTER_AF,
     99     GB_REGISTER_BC,
    100     GB_REGISTER_DE,
    101     GB_REGISTER_HL,
    102     GB_REGISTER_SP,
    103     GB_REGISTER_PC,
    104     GB_REGISTERS_16_BIT /* Count */
    105 };
    106 
    107 /* Todo: Actually use these! */
    108 enum {
    109     GB_CARRY_FLAG = 0x10,
    110     GB_HALF_CARRY_FLAG = 0x20,
    111     GB_SUBTRACT_FLAG = 0x40,
    112     GB_ZERO_FLAG = 0x80,
    113 };
    114 
    115 enum {
    116     GB_LCDC_BG_EN = 1,
    117     GB_LCDC_OBJ_EN = 2,
    118     GB_LCDC_OBJ_SIZE = 4,
    119     GB_LCDC_BG_MAP = 8,
    120     GB_LCDC_TILE_SEL = 0x10,
    121     GB_LCDC_WIN_ENABLE = 0x20,
    122     GB_LCDC_WIN_MAP = 0x40,
    123     GB_LCDC_ENABLE = 0x80,
    124 };
    125 
    126 typedef enum {
    127     GB_BORDER_SGB,
    128     GB_BORDER_NEVER,
    129     GB_BORDER_ALWAYS,
    130 } GB_border_mode_t;
    131 
    132 enum {
    133     /* Joypad and Serial */
    134     GB_IO_JOYP       = 0x00, // Joypad (R/W)
    135     GB_IO_SB         = 0x01, // Serial transfer data (R/W)
    136     GB_IO_SC         = 0x02, // Serial Transfer Control (R/W)
    137 
    138     /* Missing */
    139 
    140     /* Timers */
    141     GB_IO_DIV        = 0x04, // Divider Register (R/W)
    142     GB_IO_TIMA       = 0x05, // Timer counter (R/W)
    143     GB_IO_TMA        = 0x06, // Timer Modulo (R/W)
    144     GB_IO_TAC        = 0x07, // Timer Control (R/W)
    145 
    146     /* Missing */
    147 
    148     GB_IO_IF         = 0x0F, // Interrupt Flag (R/W)
    149 
    150     /* Sound */
    151     GB_IO_NR10       = 0x10, // Channel 1 Sweep register (R/W)
    152     GB_IO_NR11       = 0x11, // Channel 1 Sound length/Wave pattern duty (R/W)
    153     GB_IO_NR12       = 0x12, // Channel 1 Volume Envelope (R/W)
    154     GB_IO_NR13       = 0x13, // Channel 1 Frequency lo (Write Only)
    155     GB_IO_NR14       = 0x14, // Channel 1 Frequency hi (R/W)
    156     /* NR20 does not exist */
    157     GB_IO_NR21       = 0x16, // Channel 2 Sound Length/Wave Pattern Duty (R/W)
    158     GB_IO_NR22       = 0x17, // Channel 2 Volume Envelope (R/W)
    159     GB_IO_NR23       = 0x18, // Channel 2 Frequency lo data (W)
    160     GB_IO_NR24       = 0x19, // Channel 2 Frequency hi data (R/W)
    161     GB_IO_NR30       = 0x1A, // Channel 3 Sound on/off (R/W)
    162     GB_IO_NR31       = 0x1B, // Channel 3 Sound Length
    163     GB_IO_NR32       = 0x1C, // Channel 3 Select output level (R/W)
    164     GB_IO_NR33       = 0x1D, // Channel 3 Frequency's lower data (W)
    165     GB_IO_NR34       = 0x1E, // Channel 3 Frequency's higher data (R/W)
    166     /* NR40 does not exist */
    167     GB_IO_NR41       = 0x20, // Channel 4 Sound Length (R/W)
    168     GB_IO_NR42       = 0x21, // Channel 4 Volume Envelope (R/W)
    169     GB_IO_NR43       = 0x22, // Channel 4 Polynomial Counter (R/W)
    170     GB_IO_NR44       = 0x23, // Channel 4 Counter/consecutive, Initial (R/W)
    171     GB_IO_NR50       = 0x24, // Channel control / ON-OFF / Volume (R/W)
    172     GB_IO_NR51       = 0x25, // Selection of Sound output terminal (R/W)
    173     GB_IO_NR52       = 0x26, // Sound on/off
    174 
    175     /* Missing */
    176 
    177     GB_IO_WAV_START  = 0x30, // Wave pattern start
    178     GB_IO_WAV_END    = 0x3F, // Wave pattern end
    179 
    180     /* Graphics */
    181     GB_IO_LCDC       = 0x40, // LCD Control (R/W)
    182     GB_IO_STAT       = 0x41, // LCDC Status (R/W)
    183     GB_IO_SCY        = 0x42, // Scroll Y (R/W)
    184     GB_IO_SCX        = 0x43, // Scroll X (R/W)
    185     GB_IO_LY         = 0x44, // LCDC Y-Coordinate (R)
    186     GB_IO_LYC        = 0x45, // LY Compare (R/W)
    187     GB_IO_DMA        = 0x46, // DMA Transfer and Start Address (W)
    188     GB_IO_BGP        = 0x47, // BG Palette Data (R/W) - Non CGB Mode Only
    189     GB_IO_OBP0       = 0x48, // Object Palette 0 Data (R/W) - Non CGB Mode Only
    190     GB_IO_OBP1       = 0x49, // Object Palette 1 Data (R/W) - Non CGB Mode Only
    191     GB_IO_WY         = 0x4A, // Window Y Position (R/W)
    192     GB_IO_WX         = 0x4B, // Window X Position minus 7 (R/W)
    193     // Controls DMG mode and PGB mode
    194     GB_IO_KEY0 = 0x4C,
    195 
    196     /* General CGB features */
    197     GB_IO_KEY1       = 0x4D, // CGB Mode Only - Prepare Speed Switch
    198 
    199     /* Missing */
    200 
    201     GB_IO_VBK        = 0x4F, // CGB Mode Only - VRAM Bank
    202     GB_IO_BANK       = 0x50, // Write to disable the boot ROM mapping
    203 
    204     /* CGB DMA */
    205     GB_IO_HDMA1      = 0x51, // CGB Mode Only - New DMA Source, High
    206     GB_IO_HDMA2      = 0x52, // CGB Mode Only - New DMA Source, Low
    207     GB_IO_HDMA3      = 0x53, // CGB Mode Only - New DMA Destination, High
    208     GB_IO_HDMA4      = 0x54, // CGB Mode Only - New DMA Destination, Low
    209     GB_IO_HDMA5      = 0x55, // CGB Mode Only - New DMA Length/Mode/Start
    210 
    211     /* IR */
    212     GB_IO_RP         = 0x56, // CGB Mode Only - Infrared Communications Port
    213 
    214     /* Missing */
    215 
    216     /* CGB Palettes */
    217     GB_IO_BGPI       = 0x68, // CGB Mode Only - Background Palette Index
    218     GB_IO_BGPD       = 0x69, // CGB Mode Only - Background Palette Data
    219     GB_IO_OBPI       = 0x6A, // CGB Mode Only - Object Palette Index
    220     GB_IO_OBPD       = 0x6B, // CGB Mode Only - Object Palette Data
    221     GB_IO_OPRI       = 0x6C, // Affects object priority (X based or index based)
    222 
    223     /* Missing */
    224 
    225     GB_IO_SVBK       = 0x70, // CGB Mode Only - WRAM Bank
    226     GB_IO_PSM        = 0x71, // Palette Selection Mode, controls the PSW and key combo
    227     GB_IO_PSWX       = 0x72, // X position of the palette switching window
    228     GB_IO_PSWY       = 0x73, // Y position of the palette switching window
    229     GB_IO_PSW        = 0x74, // Key combo to trigger the palette switching window
    230     GB_IO_PGB        = 0x75, // Bits 0-2 control PHI, A15 and ¬CS, respectively.  Bits 4-6 control the I/O directions of bits 0-2 (0 is R, 1 is W)
    231     GB_IO_PCM12      = 0x76, // Channels 1 and 2 amplitudes
    232     GB_IO_PCM34      = 0x77, // Channels 3 and 4 amplitudes
    233 };
    234 
    235 static const typeof(GB_IO_PGB) __attribute__((deprecated("Use GB_IO_PGB instead"))) GB_IO_UNKNOWN5 = GB_IO_PGB;
    236 
    237 typedef enum {
    238     GB_LOG_BOLD = 1,
    239     GB_LOG_DASHED_UNDERLINE = 2,
    240     GB_LOG_UNDERLINE = 4,
    241     GB_LOG_UNDERLINE_MASK =  GB_LOG_DASHED_UNDERLINE | GB_LOG_UNDERLINE
    242 } GB_log_attributes_t;
    243 
    244 typedef enum {
    245     GB_BOOT_ROM_DMG_0,
    246     GB_BOOT_ROM_DMG,
    247     GB_BOOT_ROM_MGB,
    248     GB_BOOT_ROM_SGB,
    249     GB_BOOT_ROM_SGB2,
    250     GB_BOOT_ROM_CGB_0,
    251     GB_BOOT_ROM_CGB,
    252     GB_BOOT_ROM_CGB_E,
    253     GB_BOOT_ROM_AGB_0,
    254     GB_BOOT_ROM_AGB,
    255 } GB_boot_rom_t;
    256 
    257 #ifdef GB_INTERNAL
    258 #define LCDC_PERIOD 70224
    259 #define CPU_FREQUENCY 0x400000
    260 #define SGB_NTSC_FREQUENCY (21477272 / 5)
    261 #define SGB_PAL_FREQUENCY (21281370 / 5)
    262 #define DIV_CYCLES (0x100)
    263 
    264 #ifdef GB_DISABLE_REWIND
    265 #define GB_rewind_reset(...)
    266 #define GB_rewind_push(...)
    267 #define GB_rewind_invalidate_for_backstepping(...)
    268 #endif
    269 
    270 #endif
    271 
    272 typedef void (*GB_log_callback_t)(GB_gameboy_t *gb, const char *string, GB_log_attributes_t attributes);
    273 typedef char *(*GB_input_callback_t)(GB_gameboy_t *gb);
    274 typedef void (*GB_infrared_callback_t)(GB_gameboy_t *gb, bool on);
    275 typedef void (*GB_rumble_callback_t)(GB_gameboy_t *gb, double rumble_amplitude);
    276 typedef void (*GB_serial_transfer_bit_start_callback_t)(GB_gameboy_t *gb, bool bit_to_send);
    277 typedef bool (*GB_serial_transfer_bit_end_callback_t)(GB_gameboy_t *gb);
    278 typedef void (*GB_joyp_write_callback_t)(GB_gameboy_t *gb, uint8_t value);
    279 typedef void (*GB_icd_pixel_callback_t)(GB_gameboy_t *gb, uint8_t row);
    280 typedef void (*GB_icd_hreset_callback_t)(GB_gameboy_t *gb);
    281 typedef void (*GB_icd_vreset_callback_t)(GB_gameboy_t *gb);
    282 typedef void (*GB_boot_rom_load_callback_t)(GB_gameboy_t *gb, GB_boot_rom_t type);
    283 
    284 typedef void (*GB_execution_callback_t)(GB_gameboy_t *gb, uint16_t address, uint8_t opcode);
    285 typedef void (*GB_lcd_line_callback_t)(GB_gameboy_t *gb, uint8_t line);
    286 typedef void (*GB_lcd_status_callback_t)(GB_gameboy_t *gb, bool on);
    287 
    288 struct GB_breakpoint_s;
    289 struct GB_watchpoint_s;
    290 
    291 typedef struct {
    292     uint32_t magic;
    293     uint8_t track_count;
    294     uint8_t first_track;
    295     uint16_t load_address;
    296     uint16_t init_address;
    297     uint16_t play_address;
    298     uint16_t sp;
    299     uint8_t TMA;
    300     uint8_t TAC;
    301     char title[32];
    302     char author[32];
    303     char copyright[32];
    304 } GB_gbs_header_t;
    305 
    306 typedef struct {
    307     uint8_t track_count;
    308     uint8_t first_track;
    309     char title[33];
    310     char author[33];
    311     char copyright[33];
    312 } GB_gbs_info_t;
    313 
    314 /* Duplicated so it can remain anonymous in GB_gameboy_t */
    315 typedef union {
    316     uint16_t registers[GB_REGISTERS_16_BIT];
    317     struct {
    318         uint16_t af,
    319                  bc,
    320                  de,
    321                  hl,
    322                  sp,
    323                  pc;
    324     };
    325     struct {
    326         uint8_t GB_REGISTER_ORDER;
    327     };
    328 } GB_registers_t;
    329 
    330 typedef GB_ENUM(uint8_t, {
    331     GB_ACCESSORY_NONE,
    332     GB_ACCESSORY_PRINTER,
    333     GB_ACCESSORY_WORKBOY,
    334 }) GB_accessory_t;
    335 
    336 /* When state saving, each section is dumped independently of other sections.
    337    This allows adding data to the end of the section without worrying about future compatibility.
    338    Some other changes might be "safe" as well.
    339    This struct is not packed, but dumped sections exclusively use types that have the same alignment in both 32 and 64
    340    bit platforms. */
    341 
    342 #ifdef GB_INTERNAL
    343 struct GB_gameboy_s {
    344 #else
    345 struct GB_gameboy_internal_s {
    346 #endif
    347     GB_SECTION(header,
    348         /* The magic makes sure a state file is:
    349             - Indeed a SameBoy state file.
    350             - Has the same endianess has the current platform. */
    351         volatile uint32_t magic;
    352         /* The version field makes sure we don't load save state files with a completely different structure.
    353            This happens when struct fields are removed/resized in an backward incompatible manner. */
    354         uint32_t version;
    355     )
    356 
    357     GB_SECTION(core_state,
    358         /* Registers */
    359         union {
    360             uint16_t registers[GB_REGISTERS_16_BIT];
    361             struct {
    362                 uint16_t af,
    363                          bc,
    364                          de,
    365                          hl,
    366                          sp,
    367                          pc;
    368             };
    369             struct {
    370                 uint8_t GB_REGISTER_ORDER;
    371             };
    372         };
    373         uint8_t ime;
    374         uint8_t interrupt_enable;
    375         uint8_t cgb_ram_bank;
    376 
    377         /* CPU and General Hardware Flags*/
    378         GB_model_t model;
    379         bool cgb_mode;
    380         bool cgb_double_speed;
    381         bool halted;
    382         bool stopped;
    383         bool boot_rom_finished;
    384         bool ime_toggle; /* ei has delayed a effect.*/
    385         bool halt_bug;
    386         bool just_halted;
    387 
    388         /* Misc state */
    389         bool infrared_input;
    390         uint8_t extra_oam[0xFF00 - 0xFEA0];
    391         uint32_t ram_size; // Different between CGB and DMG
    392                
    393         int32_t ir_sensor;
    394         bool effective_ir_input;
    395         uint16_t address_bus;
    396         uint8_t data_bus; // cart data bus (MAIN)
    397         uint32_t data_bus_decay_countdown;
    398     )
    399 
    400     /* DMA and HDMA */
    401     GB_SECTION(dma,
    402         bool hdma_on;
    403         bool hdma_on_hblank;
    404         uint8_t hdma_steps_left;
    405         uint16_t hdma_current_src, hdma_current_dest;
    406 
    407         uint8_t dma_current_dest;
    408         uint8_t last_dma_read;
    409         uint16_t dma_current_src;
    410         uint16_t dma_cycles;
    411         int8_t dma_cycles_modulo;
    412         bool dma_ppu_vram_conflict;
    413         uint16_t dma_ppu_vram_conflict_addr;
    414         bool allow_hdma_on_wake;
    415         bool dma_restarting;
    416     )
    417     
    418     /* MBC */
    419     GB_SECTION(mbc,
    420         uint16_t mbc_rom_bank;
    421         uint16_t mbc_rom0_bank; /* For multicart mappings . */
    422         uint8_t mbc_ram_bank;
    423         uint32_t mbc_ram_size;
    424         bool mbc_ram_enable;
    425         union {
    426             struct {
    427                 uint8_t bank_low:5;
    428                 uint8_t bank_high:2;
    429                 uint8_t mode:1;
    430             } mbc1;
    431 
    432             struct {
    433                 uint8_t rom_bank:4;
    434             } mbc2;
    435 
    436             struct {
    437                 uint8_t rom_bank:8;
    438                 uint8_t ram_bank:3;
    439                 bool rtc_mapped:1;
    440             } mbc3;
    441 
    442             struct {
    443                 uint8_t rom_bank_low;
    444                 uint8_t rom_bank_high:1;
    445                 uint8_t ram_bank:4;
    446             } mbc5; // Also used for GB_CAMERA
    447                
    448             struct {
    449                 uint16_t x_latch;
    450                 uint16_t y_latch;
    451                 uint8_t rom_bank;
    452                 bool latch_ready:1;
    453                 bool eeprom_do:1;
    454                 bool eeprom_di:1;
    455                 bool eeprom_clk:1;
    456                 bool eeprom_cs:1;
    457                 uint16_t eeprom_command:11;
    458                 uint16_t read_bits;
    459                 uint8_t argument_bits_left:5;
    460                 bool secondary_ram_enable:1;
    461                 bool eeprom_write_enabled:1;
    462             } mbc7;
    463                
    464             struct {
    465                 uint8_t rom_bank_low:5;
    466                 uint8_t rom_bank_mid:2;
    467                 bool mbc1_mode:1;
    468                
    469                 uint8_t rom_bank_mask:4;
    470                 uint8_t rom_bank_high:2;
    471                 uint8_t ram_bank_low:2;
    472                
    473                 uint8_t ram_bank_high:2;
    474                 uint8_t ram_bank_mask:2;
    475 
    476                 bool locked:1;
    477                 bool mbc1_mode_disable:1;
    478                 bool multiplex_mode:1;
    479             } mmm01;
    480             
    481             struct {
    482                 uint8_t bank_low:6;
    483                 uint8_t bank_high:3;
    484                 bool ir_mode:1;
    485             } huc1;
    486 
    487             struct {
    488                 uint8_t rom_bank:7;
    489                 uint8_t padding:1;
    490                 uint8_t ram_bank:4;
    491                 uint8_t mode:4;
    492                 uint16_t minutes, days;
    493                 uint16_t alarm_minutes, alarm_days;
    494                 uint8_t access_index;
    495                 bool alarm_enabled;
    496                 uint8_t read;
    497                 uint8_t access_flags;
    498             } huc3;
    499                
    500            struct {
    501                uint16_t rom_bank;
    502                uint8_t ram_bank;
    503                uint8_t mode;
    504            } tpp1;
    505         };
    506         uint8_t rumble_strength;
    507         bool cart_ir;
    508                
    509         bool camera_registers_mapped;
    510         uint8_t camera_registers[0x36];
    511         uint8_t camera_alignment;
    512         int32_t camera_countdown;
    513     )
    514 
    515     /* HRAM and HW Registers */
    516     GB_SECTION(hram,
    517         uint8_t hram[0xFFFF - 0xFF80];
    518         uint8_t io_registers[0x80];
    519     )
    520 
    521     /* Timing */
    522     GB_SECTION(timing,
    523         GB_UNIT(display);
    524         GB_UNIT(div);
    525         uint16_t div_counter;
    526         GB_ENUM(uint8_t, {
    527             GB_TIMA_RUNNING = 0,
    528             GB_TIMA_RELOADING = 1,
    529             GB_TIMA_RELOADED = 2
    530         }) tima_reload_state; /* After TIMA overflows, it becomes 0 for 4 cycles before actually reloading. */
    531         bool serial_master_clock;
    532         uint8_t serial_mask;
    533         uint8_t double_speed_alignment;
    534         uint8_t serial_count;
    535         int32_t speed_switch_halt_countdown;
    536         uint8_t speed_switch_countdown; // To compensate for the lack of pipeline emulation
    537         uint8_t speed_switch_freeze; // Solely for realigning the PPU, should be removed when the odd modes are implemented
    538         /* For timing of the vblank callback */
    539         uint32_t cycles_since_vblank_callback;
    540         bool lcd_disabled_outside_of_vblank;
    541         int32_t allowed_pending_cycles;
    542         uint16_t mode3_batching_length;
    543         uint8_t joyp_switching_delay;
    544         uint8_t joyp_switch_value;
    545         uint16_t key_bounce_timing[GB_KEY_MAX];
    546     )
    547 
    548     /* APU */
    549     GB_SECTION(apu,
    550         GB_apu_t apu;
    551     )
    552 
    553     /* RTC */
    554     GB_SECTION(rtc,
    555         GB_rtc_time_t rtc_real, rtc_latched;
    556         uint64_t last_rtc_second;
    557         uint32_t rtc_cycles;
    558         uint8_t tpp1_mr4;
    559     )
    560 
    561     /* Video Display */
    562     GB_SECTION(video,
    563         uint32_t vram_size; // Different between CGB and DMG
    564         bool cgb_vram_bank;
    565         uint8_t oam[0xA0];
    566         uint8_t background_palettes_data[0x40];
    567         uint8_t object_palettes_data[0x40];
    568         uint8_t position_in_line;
    569         bool stat_interrupt_line;
    570         uint8_t window_y;
    571         /* The LCDC will skip the first frame it renders after turning it on.
    572            On the CGB, a frame is not skipped if the previous frame was skipped as well.
    573            See https://www.reddit.com/r/EmuDev/comments/6exyxu/ */
    574                
    575         /* TODO: Drop this and properly emulate the dropped vreset signal*/
    576         GB_ENUM(uint8_t, {
    577             GB_FRAMESKIP_LCD_TURNED_ON, // On a DMG, the LCD renders a blank screen during this state,
    578                                         // on a CGB, the previous frame is repeated (which might be
    579                                         // blank if the LCD was off for more than a few cycles)
    580             GB_FRAMESKIP_FIRST_FRAME_RENDERED,
    581         }) frame_skip_state;
    582         bool oam_read_blocked;
    583         bool vram_read_blocked;
    584         bool oam_write_blocked;
    585         bool vram_write_blocked;
    586         uint8_t current_line;
    587         uint16_t ly_for_comparison;
    588         GB_fifo_t bg_fifo, oam_fifo;
    589         uint8_t fetcher_y;
    590         uint16_t cycles_for_line;
    591         uint8_t current_tile;
    592         uint8_t current_tile_attributes;
    593         uint8_t current_tile_data[2];
    594         uint8_t fetcher_state;
    595         bool window_is_being_fetched;
    596         GB_PADDING(bool, wx166_glitch);
    597         bool wx_triggered;
    598         uint8_t visible_objs[10];
    599         uint8_t objects_x[10];
    600         uint8_t objects_y[10];
    601         uint8_t object_tile_data[2];
    602         uint8_t mode2_y_bus;
    603         // They're the same bus
    604         union {
    605             uint8_t mode2_x_bus;
    606             uint8_t object_flags;
    607         };
    608         uint8_t n_visible_objs;
    609         uint8_t orig_n_visible_objs;
    610         uint8_t oam_search_index;
    611         uint8_t accessed_oam_row;
    612         uint8_t mode_for_interrupt;
    613         bool lyc_interrupt_line;
    614         bool cgb_palettes_blocked;
    615         uint8_t current_lcd_line; // The LCD can go out of sync since the vsync signal is skipped in some cases.
    616         uint8_t object_priority;
    617         bool oam_ppu_blocked;
    618         bool vram_ppu_blocked;
    619         bool cgb_palettes_ppu_blocked;
    620         bool object_fetch_aborted;
    621         bool during_object_fetch;
    622         uint16_t object_low_line_address;
    623         bool wy_triggered;
    624         uint8_t window_tile_x;
    625         uint8_t lcd_x; // The LCD can go out of sync since the push signal is skipped in some cases.
    626         bool is_odd_frame;
    627         uint16_t last_tile_data_address;
    628         uint16_t last_tile_index_address;
    629         uint8_t data_for_sel_glitch;
    630         bool delayed_glitch_hblank_interrupt;
    631         uint32_t frame_repeat_countdown;
    632         bool disable_window_pixel_insertion_glitch;
    633         bool insert_bg_pixel;
    634         uint8_t cpu_vram_bus;
    635         uint32_t frame_parity_ticks;
    636         bool last_tileset;
    637         bool cgb_wx_glitch;
    638         bool line_has_fractional_scrolling;
    639         uint8_t wy_check_modulo;
    640         bool wy_check_scheduled;
    641         bool wy_just_checked;
    642         bool wx_166_interrupt_glitch;
    643     )
    644     
    645     GB_SECTION(accessory,
    646         GB_accessory_t accessory;
    647         union {
    648             GB_printer_t printer;
    649             GB_workboy_t workboy;
    650         };
    651     )
    652 
    653     /* Unsaved data. This includes all pointers, as well as everything that shouldn't be on a save state */
    654     /* This data is reserved on reset and must come last in the struct */
    655     GB_SECTION(unsaved,
    656         /* ROM */
    657         uint8_t *rom;
    658         uint32_t rom_size;
    659         const GB_cartridge_t *cartridge_type;
    660         enum {
    661             GB_STANDARD_MBC1_WIRING,
    662             GB_MBC1M_WIRING,
    663         } mbc1_wiring;
    664         bool is_mbc30;
    665 
    666         unsigned pending_cycles;
    667                
    668         /* Various RAMs */
    669         uint8_t *ram;
    670         uint8_t *vram;
    671         uint8_t *mbc_ram;
    672 
    673         /* I/O */
    674         uint32_t *screen;
    675         uint32_t background_palettes_rgb[0x20];
    676         uint32_t object_palettes_rgb[0x20];
    677         const GB_palette_t *dmg_palette;
    678         GB_color_correction_mode_t color_correction_mode;
    679         double light_temperature;
    680         bool keys[4][GB_KEY_MAX];
    681         bool use_faux_analog[4];
    682         struct {
    683             int8_t x, y;
    684         } faux_analog_inputs[4];
    685         uint8_t faux_analog_ticks;
    686         double accelerometer_x, accelerometer_y;
    687         GB_border_mode_t border_mode;
    688         GB_sgb_border_t borrowed_border;
    689         bool tried_loading_sgb_border;
    690         bool has_sgb_border;
    691         bool objects_disabled;
    692         bool background_disabled;
    693         bool joyp_accessed;
    694         bool illegal_inputs_allowed;
    695         bool no_bouncing_emulation;
    696         bool joypad_is_stable;
    697 
    698         /* Timing */
    699         uint64_t last_sync;
    700         uint64_t last_render;
    701         uint64_t cycles_since_last_sync; // In 8MHz units
    702         GB_rtc_mode_t rtc_mode;
    703         uint32_t rtc_second_length;
    704         uint32_t clock_rate;
    705         uint32_t unmultiplied_clock_rate;
    706         uint32_t data_bus_decay;
    707 
    708         /* Audio */
    709         GB_apu_output_t apu_output;
    710 
    711         /* Callbacks */
    712         void *user_data;
    713         GB_log_callback_t log_callback;
    714         GB_input_callback_t input_callback;
    715         GB_input_callback_t async_input_callback;
    716         GB_rgb_encode_callback_t rgb_encode_callback;
    717         GB_vblank_callback_t vblank_callback;
    718         GB_infrared_callback_t infrared_callback;
    719         GB_camera_get_pixel_callback_t camera_get_pixel_callback;
    720         GB_camera_update_request_callback_t camera_update_request_callback;
    721         GB_rumble_callback_t rumble_callback;
    722         GB_serial_transfer_bit_start_callback_t serial_transfer_bit_start_callback;
    723         GB_serial_transfer_bit_end_callback_t serial_transfer_bit_end_callback;
    724         GB_update_input_hint_callback_t update_input_hint_callback;
    725         GB_joyp_write_callback_t joyp_write_callback;
    726         GB_icd_pixel_callback_t icd_pixel_callback;
    727         GB_icd_vreset_callback_t icd_hreset_callback;
    728         GB_icd_vreset_callback_t icd_vreset_callback;
    729         GB_read_memory_callback_t read_memory_callback;
    730         GB_write_memory_callback_t write_memory_callback;
    731         GB_boot_rom_load_callback_t boot_rom_load_callback;
    732         GB_print_image_callback_t printer_callback;
    733         GB_printer_done_callback_t printer_done_callback;
    734         GB_workboy_set_time_callback_t workboy_set_time_callback;
    735         GB_workboy_get_time_callback_t workboy_get_time_callback;
    736         GB_execution_callback_t execution_callback;
    737         GB_lcd_line_callback_t lcd_line_callback;
    738         GB_lcd_status_callback_t lcd_status_callback;
    739                
    740 #ifndef GB_DISABLE_DEBUGGER
    741         /*** Debugger ***/
    742         volatile bool debug_stopped, debug_disable;
    743         bool debug_fin_command, debug_next_command;
    744         bool debug_active; // Cached value determining if GB_debugger_run does anything
    745         bool help_shown;
    746         uint32_t backstep_instructions;
    747 
    748         /* Breakpoints */
    749         uint16_t n_breakpoints;
    750         struct GB_breakpoint_s *breakpoints;
    751         bool has_jump_to_breakpoints, has_software_breakpoints;
    752         void *nontrivial_jump_state;
    753         bool non_trivial_jump_breakpoint_occured;
    754 
    755         signed debug_call_depth;
    756         uint16_t sp_for_call_depth[0x200]; /* Should be much more than enough */
    757         uint16_t addr_for_call_depth[0x200];
    758 
    759         /* Backtrace */
    760         unsigned backtrace_size;
    761         uint16_t backtrace_sps[0x200];
    762         struct {
    763             uint16_t bank;
    764             uint16_t addr;
    765         } backtrace_returns[0x200];
    766 
    767         /* Watchpoints */
    768         uint16_t n_watchpoints;
    769         struct GB_watchpoint_s *watchpoints;
    770 
    771         /* Symbol tables */
    772         GB_symbol_map_t **bank_symbols;
    773         size_t n_symbol_maps;
    774         GB_reversed_symbol_map_t reversed_symbol_map;
    775 
    776         /* Ticks command */
    777         uint64_t debugger_ticks;
    778         uint64_t absolute_debugger_ticks;
    779                
    780         /* Undo */
    781         uint8_t *undo_state;
    782         const char *undo_label;
    783                
    784         /* Callbacks */
    785         GB_debugger_reload_callback_t debugger_reload_callback;
    786                
    787         /* CPU usage */
    788         uint32_t current_frame_idle_cycles, current_frame_busy_cycles;
    789         uint32_t last_frame_idle_cycles, last_frame_busy_cycles;
    790         
    791         uint32_t current_second_idle_cycles, current_second_busy_cycles;
    792         uint32_t last_second_idle_cycles, last_second_busy_cycles;
    793         uint8_t usage_frame_count;
    794 #endif
    795 
    796 #ifndef GB_DISABLE_REWIND
    797         /* Rewind */
    798         size_t rewind_buffer_length;
    799         size_t rewind_state_size;
    800         struct {
    801             uint8_t *key_state;
    802             uint8_t *compressed_states[GB_REWIND_FRAMES_PER_KEY];
    803             uint32_t instruction_count[GB_REWIND_FRAMES_PER_KEY + 1];
    804             unsigned pos;
    805         } *rewind_sequences; // lasts about 4 seconds
    806         size_t rewind_pos;
    807         bool rewind_disable_invalidation;
    808 #endif
    809                
    810         /* SGB - saved and allocated optionally */
    811         GB_sgb_t *sgb;
    812         
    813         double sgb_intro_jingle_phases[7];
    814         double sgb_intro_sweep_phase;
    815         double sgb_intro_sweep_previous_sample;
    816                
    817 #ifndef GB_DISABLE_CHEATS
    818        /* Cheats */
    819         bool cheat_enabled;
    820         size_t cheat_count;
    821         GB_cheat_t **cheats;
    822         GB_cheat_hash_t *cheat_hash[256];
    823 #endif
    824 #ifndef GB_DISABLE_CHEAT_SEARCH
    825         uint8_t *cheat_search_data;
    826         uint8_t *cheat_search_bitmap;
    827         size_t cheat_search_count;
    828         GB_cheat_search_data_type_t cheat_search_data_type;
    829 #endif
    830 
    831         /* Misc */
    832         bool turbo;
    833         bool turbo_dont_skip;
    834         double turbo_cap_multiplier;
    835         bool enable_skipped_frame_vblank_callbacks;
    836         bool disable_rendering;
    837         uint8_t boot_rom[0x900];
    838         bool vblank_just_occured; // For slow operations involving syscalls; these should only run once per vblank
    839         unsigned cycles_since_run; // How many cycles have passed since the last call to GB_run(), in 8MHz units
    840         double clock_multiplier;
    841         GB_rumble_mode_t rumble_mode;
    842         uint32_t rumble_on_cycles;
    843         uint32_t rumble_off_cycles;
    844         bool battery_dirty;
    845                
    846         /* Temporary state */
    847         bool wx_just_changed;
    848         bool tile_sel_glitch;
    849         bool disable_oam_corruption; // For safe memory reads
    850         bool in_dma_read;
    851         bool hdma_in_progress;
    852         bool returned_open_bus;
    853         uint16_t addr_for_hdma_conflict;
    854         bool during_div_write;
    855                
    856         /* Thread safety (debug only) */
    857         void *running_thread_id;
    858                
    859         GB_gbs_header_t gbs_header;
    860    )
    861 };
    862     
    863 #ifndef GB_INTERNAL
    864 struct GB_gameboy_s {
    865     alignas(struct GB_gameboy_internal_s) uint8_t __internal[sizeof(struct GB_gameboy_internal_s)];
    866 };
    867 #endif
    868 
    869 
    870 #ifndef __printflike
    871 /* Missing from Linux headers. */
    872 #define __printflike(fmtarg, firstvararg) \
    873 __attribute__((__format__ (__printf__, fmtarg, firstvararg)))
    874 #endif
    875 
    876 /*
    877     There are two instance allocation styles – one where you manage your
    878     own instance allocation, and one where you use provided allocators.
    879  
    880     Managing allocations yourself:
    881     GB_gameboy_t gb;
    882     GB_init(&gb, model);
    883     ...
    884     GB_free(&gb);
    885  
    886     Using the provided allocators:
    887     GB_gameboy_t *gb = GB_init(GB_alloc(), model);
    888     ...
    889     GB_free(gb); // optional
    890     GB_dealloc(gb);
    891  
    892 */
    893 GB_gameboy_t *GB_init(GB_gameboy_t *gb, GB_model_t model);
    894 void GB_free(GB_gameboy_t *gb);
    895 GB_gameboy_t *GB_alloc(void);
    896 void GB_dealloc(GB_gameboy_t *gb);
    897 
    898 // For when you want to use your own malloc implementation without having to rely on the header struct
    899 size_t GB_allocation_size(void);
    900     
    901 bool GB_is_inited(GB_gameboy_t *gb);
    902 bool GB_is_cgb(const GB_gameboy_t *gb);
    903 bool GB_is_cgb_in_cgb_mode(GB_gameboy_t *gb);
    904 bool GB_is_sgb(GB_gameboy_t *gb); // Returns true if the model is SGB or SGB2
    905 bool GB_is_hle_sgb(GB_gameboy_t *gb); // Returns true if the model is SGB or SGB2 and the SFC/SNES side is HLE'd
    906 GB_model_t GB_get_model(GB_gameboy_t *gb);
    907 void GB_reset(GB_gameboy_t *gb);
    908 void GB_quick_reset(GB_gameboy_t *gb); // Similar to the cart reset line
    909 void GB_switch_model_and_reset(GB_gameboy_t *gb, GB_model_t model);
    910 
    911 /* Returns the time passed, in 8MHz ticks. */
    912 unsigned GB_run(GB_gameboy_t *gb);
    913 /* Returns the time passed since the last frame, in nanoseconds */
    914 uint64_t GB_run_frame(GB_gameboy_t *gb);
    915 
    916 typedef enum {
    917     GB_DIRECT_ACCESS_ROM,
    918     GB_DIRECT_ACCESS_RAM,
    919     GB_DIRECT_ACCESS_CART_RAM,
    920     GB_DIRECT_ACCESS_VRAM,
    921     GB_DIRECT_ACCESS_HRAM,
    922     GB_DIRECT_ACCESS_IO, /* Warning: Some registers can only be read/written correctly via GB_read/write_memory. */
    923     GB_DIRECT_ACCESS_BOOTROM,
    924     GB_DIRECT_ACCESS_OAM,
    925     GB_DIRECT_ACCESS_BGP,
    926     GB_DIRECT_ACCESS_OBP,
    927     GB_DIRECT_ACCESS_IE,
    928     GB_DIRECT_ACCESS_ROM0, // Identical to ROM, but returns the correct rom0 bank in the bank output argument
    929 } GB_direct_access_t;
    930 
    931 /* Returns a mutable pointer to various hardware memories. If that memory is banked, the current bank
    932    is returned at *bank, even if only a portion of the memory is banked. */
    933 void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank);
    934 GB_registers_t *GB_get_registers(GB_gameboy_t *gb);
    935 
    936 void *GB_get_user_data(GB_gameboy_t *gb);
    937 void GB_set_user_data(GB_gameboy_t *gb, void *data);
    938 
    939 int GB_load_boot_rom(GB_gameboy_t *gb, const char *path);
    940 void GB_load_boot_rom_from_buffer(GB_gameboy_t *gb, const unsigned char *buffer, size_t size);
    941 int GB_load_rom(GB_gameboy_t *gb, const char *path);
    942 void GB_load_rom_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size);
    943 int GB_load_isx(GB_gameboy_t *gb, const char *path);
    944 int GB_load_gbs_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size, GB_gbs_info_t *info);
    945 int GB_load_gbs(GB_gameboy_t *gb, const char *path, GB_gbs_info_t *info);
    946 void GB_gbs_switch_track(GB_gameboy_t *gb, uint8_t track);
    947 
    948 int GB_save_battery_size(GB_gameboy_t *gb);
    949 int GB_save_battery_to_buffer(GB_gameboy_t *gb, uint8_t *buffer, size_t size);
    950 int GB_save_battery(GB_gameboy_t *gb, const char *path);
    951 
    952 void GB_load_battery_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size);
    953 int GB_load_battery(GB_gameboy_t *gb, const char *path);
    954 
    955 void GB_set_turbo_mode(GB_gameboy_t *gb, bool on, bool no_frame_skip);
    956 void GB_set_turbo_cap(GB_gameboy_t *gb, double multiplier); // Use 0 to use no cap
    957 void GB_set_rendering_disabled(GB_gameboy_t *gb, bool disabled);
    958     
    959 void GB_log(GB_gameboy_t *gb, const char *fmt, ...) __printflike(2, 3);
    960 void GB_attributed_log(GB_gameboy_t *gb, GB_log_attributes_t attributes, const char *fmt, ...) __printflike(3, 4);
    961 
    962 uint32_t *GB_get_pixels_output(GB_gameboy_t *gb);
    963 void GB_set_border_mode(GB_gameboy_t *gb, GB_border_mode_t border_mode);
    964     
    965 void GB_set_infrared_input(GB_gameboy_t *gb, bool state);
    966     
    967 void GB_set_log_callback(GB_gameboy_t *gb, GB_log_callback_t callback);
    968 void GB_set_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback);
    969 void GB_set_async_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback);
    970 void GB_set_infrared_callback(GB_gameboy_t *gb, GB_infrared_callback_t callback);
    971 void GB_set_rumble_callback(GB_gameboy_t *gb, GB_rumble_callback_t callback);
    972 /* Called when a new boot ROM is needed. The callback should call GB_load_boot_rom or GB_load_boot_rom_from_buffer */
    973 void GB_set_boot_rom_load_callback(GB_gameboy_t *gb, GB_boot_rom_load_callback_t callback);
    974     
    975 void GB_set_execution_callback(GB_gameboy_t *gb, GB_execution_callback_t callback);
    976 void GB_set_lcd_line_callback(GB_gameboy_t *gb, GB_lcd_line_callback_t callback);
    977 void GB_set_lcd_status_callback(GB_gameboy_t *gb, GB_lcd_status_callback_t callback);
    978 
    979 /* These APIs are used when using internal clock */
    980 void GB_set_serial_transfer_bit_start_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_start_callback_t callback);
    981 void GB_set_serial_transfer_bit_end_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_end_callback_t callback);
    982 
    983 /* These APIs are used when using external clock */
    984 bool GB_serial_get_data_bit(GB_gameboy_t *gb);
    985 void GB_serial_set_data_bit(GB_gameboy_t *gb, bool data);
    986     
    987 void GB_disconnect_serial(GB_gameboy_t *gb);
    988 GB_accessory_t GB_get_built_in_accessory(GB_gameboy_t *gb);
    989     
    990 /* For cartridges with an alarm clock */
    991 bool GB_rom_supports_alarms(GB_gameboy_t *gb);
    992 unsigned GB_time_to_alarm(GB_gameboy_t *gb); // 0 if no alarm
    993 
    994 /* For cartridges motion controls */
    995 bool GB_has_accelerometer(GB_gameboy_t *gb);
    996 // In units of g (gravity's acceleration).
    997 // Values within ±4 recommended
    998 void GB_set_accelerometer_values(GB_gameboy_t *gb, double x, double y);
    999     
   1000 // Time it takes for a value in the data bus to decay to FF, in 8MHz units. (0 to never decay, like e.g. an EverDrive)
   1001 void GB_set_open_bus_decay_time(GB_gameboy_t *gb, uint32_t decay);
   1002     
   1003 /* For integration with SFC/SNES emulators */
   1004 void GB_set_joyp_write_callback(GB_gameboy_t *gb, GB_joyp_write_callback_t callback);
   1005 void GB_set_icd_pixel_callback(GB_gameboy_t *gb, GB_icd_pixel_callback_t callback);
   1006 void GB_set_icd_hreset_callback(GB_gameboy_t *gb, GB_icd_hreset_callback_t callback);
   1007 void GB_set_icd_vreset_callback(GB_gameboy_t *gb, GB_icd_vreset_callback_t callback);
   1008     
   1009 uint32_t GB_get_clock_rate(GB_gameboy_t *gb);
   1010 uint32_t GB_get_unmultiplied_clock_rate(GB_gameboy_t *gb);
   1011 void GB_set_clock_multiplier(GB_gameboy_t *gb, double multiplier);
   1012 
   1013 /* Checks if the ROM has modified battery-backed data since the last call to GB_clear_battery_dirty */
   1014 bool GB_get_battery_dirty(GB_gameboy_t *gb);
   1015 void GB_clear_battery_dirty(GB_gameboy_t *gb);
   1016     
   1017 /* Handy ROM info APIs */
   1018 // `title` must be at least 17 bytes in size
   1019 void GB_get_rom_title(GB_gameboy_t *gb, char *title);
   1020 uint32_t GB_get_rom_crc32(GB_gameboy_t *gb);
   1021 
   1022 #ifdef GB_INTERNAL
   1023 internal void GB_borrow_sgb_border(GB_gameboy_t *gb);
   1024 internal void GB_update_clock_rate(GB_gameboy_t *gb);
   1025 #endif
   1026     
   1027 #ifdef GB_INTERNAL
   1028 
   1029 #ifndef NDEBUG
   1030 #define GB_CONTEXT_SAFETY
   1031 #endif
   1032     
   1033 #ifdef GB_CONTEXT_SAFETY
   1034 #include <assert.h>
   1035 internal void *GB_get_thread_id(void);
   1036 internal void GB_set_running_thread(GB_gameboy_t *gb);
   1037 internal void GB_clear_running_thread(GB_gameboy_t *gb);
   1038 #define GB_ASSERT_NOT_RUNNING(gb) if (gb->running_thread_id) {GB_log(gb, "Function %s must not be called in a running context.\n", __FUNCTION__); assert(!gb->running_thread_id);}
   1039 #define GB_ASSERT_NOT_RUNNING_OTHER_THREAD(gb) if (gb->running_thread_id && gb->running_thread_id != GB_get_thread_id()) {GB_log(gb, "Function %s must not be called while running in another thread.\n", __FUNCTION__); assert(!gb->running_thread_id || gb->running_thread_id == GB_get_thread_id());}
   1040 
   1041 #else
   1042 #define GB_ASSERT_NOT_RUNNING(gb)
   1043 #define GB_ASSERT_NOT_RUNNING_OTHER_THREAD(gb)
   1044 #define GB_set_running_thread(gb)
   1045 #define GB_clear_running_thread(gb)
   1046 #endif
   1047     
   1048 #endif
   1049 
   1050 #ifdef __cplusplus
   1051 }
   1052 #endif

This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.