1 #ifndef GB_h
2 #define GB_h
3 #define typeof __typeof__
4 #include <stdbool.h>
5 #include <stdint.h>
6 #include <time.h>
7 
8 #include "gb_struct_def.h"
9 #include "save_state.h"
10 
11 #include "apu.h"
12 #include "camera.h"
13 #include "debugger.h"
14 #include "display.h"
15 #include "joypad.h"
16 #include "mbc.h"
17 #include "memory.h"
18 #include "printer.h"
19 #include "timing.h"
20 #include "rewind.h"
21 #include "sm83_cpu.h"
22 #include "symbol_hash.h"
23 #include "sgb.h"
24 #include "cheats.h"
25 #include "rumble.h"
26 #include "workboy.h"
27 #include "random.h"
28 
29 #define GB_STRUCT_VERSION 13
30 
31 #define GB_MODEL_FAMILY_MASK 0xF00
32 #define GB_MODEL_DMG_FAMILY 0x000
33 #define GB_MODEL_MGB_FAMILY 0x100
34 #define GB_MODEL_CGB_FAMILY 0x200
35 #define GB_MODEL_PAL_BIT 0x40
36 #define GB_MODEL_NO_SFC_BIT 0x80
37 
38 #define GB_MODEL_PAL_BIT_OLD 0x1000
39 #define GB_MODEL_NO_SFC_BIT_OLD 0x2000
40 
41 #ifdef GB_INTERNAL
42 #if __clang__
43 #define unrolled _Pragma("unroll")
44 #elif __GNUC__ >= 8
45 #define unrolled _Pragma("GCC unroll 8")
46 #else
47 #define unrolled
48 #endif
49 
50 #endif
51 
52 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
53 #define GB_BIG_ENDIAN
54 #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
55 #define GB_LITTLE_ENDIAN
56 #else
57 #error Unable to detect endianess
58 #endif
59 
60 #ifdef GB_INTERNAL
61 /* Todo: similar macros are everywhere, clean this up and remove direct calls to bswap */
62 #ifdef GB_BIG_ENDIAN
63 #define LE16(x) __builtin_bswap16(x)
64 #define LE32(x) __builtin_bswap32(x)
65 #define LE64(x) __builtin_bswap64(x)
66 #define BE16(x) (x)
67 #define BE32(x) (x)
68 #define BE64(x) (x)
69 #else
70 #define LE16(x) (x)
71 #define LE32(x) (x)
72 #define LE64(x) (x)
73 #define BE16(x) __builtin_bswap16(x)
74 #define BE32(x) __builtin_bswap32(x)
75 #define BE64(x) __builtin_bswap64(x)
76 #endif
77 #endif
78 
79 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
80 #define __builtin_bswap16(x) ({ typeof(x) _x = (x); _x >> 8 | _x << 8; })
81 #endif
82 
83 typedef struct {
84     struct {
85         uint8_t r, g, b;
86     } colors[5];
87 } GB_palette_t;
88 
89 extern const GB_palette_t GB_PALETTE_GREY;
90 extern const GB_palette_t GB_PALETTE_DMG;
91 extern const GB_palette_t GB_PALETTE_MGB;
92 extern const GB_palette_t GB_PALETTE_GBL;
93 
94 typedef union {
95     struct {
96         uint8_t seconds;
97         uint8_t minutes;
98         uint8_t hours;
99         uint8_t days;
100         uint8_t high;
101     };
102     struct {
103         uint8_t seconds;
104         uint8_t minutes;
105         uint8_t hours:5;
106         uint8_t weekday:3;
107         uint8_t weeks;
108     } tpp1;
109     uint8_t data[5];
110 } GB_rtc_time_t;
111 
112 typedef struct __attribute__((packed)) {
113     uint64_t last_rtc_second;
114     uint16_t minutes;
115     uint16_t days;
116     uint16_t alarm_minutes, alarm_days;
117     uint8_t alarm_enabled;
118 } GB_huc3_rtc_time_t;
119 
120 typedef enum {
121     // GB_MODEL_DMG_0 = 0x000,
122     // GB_MODEL_DMG_A = 0x001,
123     GB_MODEL_DMG_B = 0x002,
124     // GB_MODEL_DMG_C = 0x003,
125     GB_MODEL_SGB = 0x004,
126     GB_MODEL_SGB_NTSC = GB_MODEL_SGB,
127     GB_MODEL_SGB_PAL = GB_MODEL_SGB | GB_MODEL_PAL_BIT,
128     GB_MODEL_SGB_NTSC_NO_SFC = GB_MODEL_SGB | GB_MODEL_NO_SFC_BIT,
129     GB_MODEL_SGB_NO_SFC = GB_MODEL_SGB_NTSC_NO_SFC,
130     GB_MODEL_SGB_PAL_NO_SFC = GB_MODEL_SGB | GB_MODEL_NO_SFC_BIT | GB_MODEL_PAL_BIT,
131     // GB_MODEL_MGB = 0x100,
132     GB_MODEL_SGB2 = 0x101,
133     GB_MODEL_SGB2_NO_SFC = GB_MODEL_SGB2 | GB_MODEL_NO_SFC_BIT,
134     // GB_MODEL_CGB_0 = 0x200,
135     // GB_MODEL_CGB_A = 0x201,
136     // GB_MODEL_CGB_B = 0x202,
137     GB_MODEL_CGB_C = 0x203,
138     // GB_MODEL_CGB_D = 0x204,
139     GB_MODEL_CGB_E = 0x205,
140     GB_MODEL_AGB = 0x206,
141 } GB_model_t;
142 
143 enum {
144     GB_REGISTER_AF,
145     GB_REGISTER_BC,
146     GB_REGISTER_DE,
147     GB_REGISTER_HL,
148     GB_REGISTER_SP,
149     GB_REGISTERS_16_BIT /* Count */
150 };
151 
152 /* Todo: Actually use these! */
153 enum {
154     GB_CARRY_FLAG = 16,
155     GB_HALF_CARRY_FLAG = 32,
156     GB_SUBTRACT_FLAG = 64,
157     GB_ZERO_FLAG = 128,
158 };
159 
160 typedef enum {
161     GB_BORDER_SGB,
162     GB_BORDER_NEVER,
163     GB_BORDER_ALWAYS,
164 } GB_border_mode_t;
165 
166 enum {
167     /* Joypad and Serial */
168     GB_IO_JOYP       = 0x00, // Joypad (R/W)
169     GB_IO_SB         = 0x01, // Serial transfer data (R/W)
170     GB_IO_SC         = 0x02, // Serial Transfer Control (R/W)
171 
172     /* Missing */
173 
174     /* Timers */
175     GB_IO_DIV        = 0x04, // Divider Register (R/W)
176     GB_IO_TIMA       = 0x05, // Timer counter (R/W)
177     GB_IO_TMA        = 0x06, // Timer Modulo (R/W)
178     GB_IO_TAC        = 0x07, // Timer Control (R/W)
179 
180     /* Missing */
181 
182     GB_IO_IF         = 0x0f, // Interrupt Flag (R/W)
183 
184     /* Sound */
185     GB_IO_NR10       = 0x10, // Channel 1 Sweep register (R/W)
186     GB_IO_NR11       = 0x11, // Channel 1 Sound length/Wave pattern duty (R/W)
187     GB_IO_NR12       = 0x12, // Channel 1 Volume Envelope (R/W)
188     GB_IO_NR13       = 0x13, // Channel 1 Frequency lo (Write Only)
189     GB_IO_NR14       = 0x14, // Channel 1 Frequency hi (R/W)
190     /* NR20 does not exist */
191     GB_IO_NR21       = 0x16, // Channel 2 Sound Length/Wave Pattern Duty (R/W)
192     GB_IO_NR22       = 0x17, // Channel 2 Volume Envelope (R/W)
193     GB_IO_NR23       = 0x18, // Channel 2 Frequency lo data (W)
194     GB_IO_NR24       = 0x19, // Channel 2 Frequency hi data (R/W)
195     GB_IO_NR30       = 0x1a, // Channel 3 Sound on/off (R/W)
196     GB_IO_NR31       = 0x1b, // Channel 3 Sound Length
197     GB_IO_NR32       = 0x1c, // Channel 3 Select output level (R/W)
198     GB_IO_NR33       = 0x1d, // Channel 3 Frequency's lower data (W)
199     GB_IO_NR34       = 0x1e, // Channel 3 Frequency's higher data (R/W)
200     /* NR40 does not exist */
201     GB_IO_NR41       = 0x20, // Channel 4 Sound Length (R/W)
202     GB_IO_NR42       = 0x21, // Channel 4 Volume Envelope (R/W)
203     GB_IO_NR43       = 0x22, // Channel 4 Polynomial Counter (R/W)
204     GB_IO_NR44       = 0x23, // Channel 4 Counter/consecutive, Inital (R/W)
205     GB_IO_NR50       = 0x24, // Channel control / ON-OFF / Volume (R/W)
206     GB_IO_NR51       = 0x25, // Selection of Sound output terminal (R/W)
207     GB_IO_NR52       = 0x26, // Sound on/off
208 
209     /* Missing */
210 
211     GB_IO_WAV_START  = 0x30, // Wave pattern start
212     GB_IO_WAV_END    = 0x3f, // Wave pattern end
213 
214     /* Graphics */
215     GB_IO_LCDC       = 0x40, // LCD Control (R/W)
216     GB_IO_STAT       = 0x41, // LCDC Status (R/W)
217     GB_IO_SCY        = 0x42, // Scroll Y (R/W)
218     GB_IO_SCX        = 0x43, // Scroll X (R/W)
219     GB_IO_LY         = 0x44, // LCDC Y-Coordinate (R)
220     GB_IO_LYC        = 0x45, // LY Compare (R/W)
221     GB_IO_DMA        = 0x46, // DMA Transfer and Start Address (W)
222     GB_IO_BGP        = 0x47, // BG Palette Data (R/W) - Non CGB Mode Only
223     GB_IO_OBP0       = 0x48, // Object Palette 0 Data (R/W) - Non CGB Mode Only
224     GB_IO_OBP1       = 0x49, // Object Palette 1 Data (R/W) - Non CGB Mode Only
225     GB_IO_WY         = 0x4a, // Window Y Position (R/W)
226     GB_IO_WX         = 0x4b, // Window X Position minus 7 (R/W)
227     // Has some undocumented compatibility flags written at boot.
228     // Unfortunately it is not readable or writable after boot has finished, so research of this
229     // register is quite limited. The value written to this register, however, can be controlled
230     // in some cases.
231     GB_IO_KEY0 = 0x4c,
232 
233     /* General CGB features */
234     GB_IO_KEY1       = 0x4d, // CGB Mode Only - Prepare Speed Switch
235 
236     /* Missing */
237 
238     GB_IO_VBK        = 0x4f, // CGB Mode Only - VRAM Bank
239     GB_IO_BANK       = 0x50, // Write to disable the BIOS mapping
240 
241     /* CGB DMA */
242     GB_IO_HDMA1      = 0x51, // CGB Mode Only - New DMA Source, High
243     GB_IO_HDMA2      = 0x52, // CGB Mode Only - New DMA Source, Low
244     GB_IO_HDMA3      = 0x53, // CGB Mode Only - New DMA Destination, High
245     GB_IO_HDMA4      = 0x54, // CGB Mode Only - New DMA Destination, Low
246     GB_IO_HDMA5      = 0x55, // CGB Mode Only - New DMA Length/Mode/Start
247 
248     /* IR */
249     GB_IO_RP         = 0x56, // CGB Mode Only - Infrared Communications Port
250 
251     /* Missing */
252 
253     /* CGB Paletts */
254     GB_IO_BGPI       = 0x68, // CGB Mode Only - Background Palette Index
255     GB_IO_BGPD       = 0x69, // CGB Mode Only - Background Palette Data
256     GB_IO_OBPI       = 0x6a, // CGB Mode Only - Sprite Palette Index
257     GB_IO_OBPD       = 0x6b, // CGB Mode Only - Sprite Palette Data
258     GB_IO_OPRI       = 0x6c, // Affects object priority (X based or index based)
259 
260     /* Missing */
261 
262     GB_IO_SVBK       = 0x70, // CGB Mode Only - WRAM Bank
263     GB_IO_UNKNOWN2   = 0x72, // (00h) - Bit 0-7 (Read/Write)
264     GB_IO_UNKNOWN3   = 0x73, // (00h) - Bit 0-7 (Read/Write)
265     GB_IO_UNKNOWN4   = 0x74, // (00h) - Bit 0-7 (Read/Write) - CGB Mode Only
266     GB_IO_UNKNOWN5   = 0x75, // (8Fh) - Bit 4-6 (Read/Write)
267     GB_IO_PCM_12     = 0x76, // Channels 1 and 2 amplitudes
268     GB_IO_PCM_34     = 0x77, // Channels 3 and 4 amplitudes
269     GB_IO_UNKNOWN8   = 0x7F, // Unknown, write only
270 };
271 
272 typedef enum {
273     GB_LOG_BOLD = 1,
274     GB_LOG_DASHED_UNDERLINE = 2,
275     GB_LOG_UNDERLINE = 4,
276     GB_LOG_UNDERLINE_MASK =  GB_LOG_DASHED_UNDERLINE | GB_LOG_UNDERLINE
277 } GB_log_attributes;
278 
279 typedef enum {
280     GB_BOOT_ROM_DMG0,
281     GB_BOOT_ROM_DMG,
282     GB_BOOT_ROM_MGB,
283     GB_BOOT_ROM_SGB,
284     GB_BOOT_ROM_SGB2,
285     GB_BOOT_ROM_CGB0,
286     GB_BOOT_ROM_CGB,
287     GB_BOOT_ROM_AGB,
288 } GB_boot_rom_t;
289 
290 typedef enum {
291     GB_RTC_MODE_SYNC_TO_HOST,
292     GB_RTC_MODE_ACCURATE,
293 } GB_rtc_mode_t;
294 
295 #ifdef GB_INTERNAL
296 #define LCDC_PERIOD 70224
297 #define CPU_FREQUENCY 0x400000
298 #define SGB_NTSC_FREQUENCY (21477272 / 5)
299 #define SGB_PAL_FREQUENCY (21281370 / 5)
300 #define DIV_CYCLES (0x100)
301 
302 #if !defined(MIN)
303 #define MIN(A, B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })
304 #endif
305 
306 #if !defined(MAX)
307 #define MAX(A, B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })
308 #endif
309 #endif
310 
311 typedef void (*GB_vblank_callback_t)(GB_gameboy_t *gb);
312 typedef void (*GB_log_callback_t)(GB_gameboy_t *gb, const char *string, GB_log_attributes attributes);
313 typedef char *(*GB_input_callback_t)(GB_gameboy_t *gb);
314 typedef uint32_t (*GB_rgb_encode_callback_t)(GB_gameboy_t *gb, uint8_t r, uint8_t g, uint8_t b);
315 typedef void (*GB_infrared_callback_t)(GB_gameboy_t *gb, bool on);
316 typedef void (*GB_rumble_callback_t)(GB_gameboy_t *gb, double rumble_amplitude);
317 typedef void (*GB_serial_transfer_bit_start_callback_t)(GB_gameboy_t *gb, bool bit_to_send);
318 typedef bool (*GB_serial_transfer_bit_end_callback_t)(GB_gameboy_t *gb);
319 typedef void (*GB_update_input_hint_callback_t)(GB_gameboy_t *gb);
320 typedef void (*GB_joyp_write_callback_t)(GB_gameboy_t *gb, uint8_t value);
321 typedef void (*GB_icd_pixel_callback_t)(GB_gameboy_t *gb, uint8_t row);
322 typedef void (*GB_icd_hreset_callback_t)(GB_gameboy_t *gb);
323 typedef void (*GB_icd_vreset_callback_t)(GB_gameboy_t *gb);
324 typedef void (*GB_boot_rom_load_callback_t)(GB_gameboy_t *gb, GB_boot_rom_t type);
325 
326 struct GB_breakpoint_s;
327 struct GB_watchpoint_s;
328 
329 typedef struct {
330     uint8_t pixel; // Color, 0-3
331     uint8_t palette; // Palette, 0 - 7 (CGB); 0-1 in DMG (or just 0 for BG)
332     uint8_t priority; // Sprite priority – 0 in DMG, OAM index in CGB
333     bool bg_priority; // For sprite FIFO – the BG priority bit. For the BG FIFO – the CGB attributes priority bit
334 } GB_fifo_item_t;
335 
336 #define GB_FIFO_LENGTH 16
337 typedef struct {
338     GB_fifo_item_t fifo[GB_FIFO_LENGTH];
339     uint8_t read_end;
340     uint8_t write_end;
341 } GB_fifo_t;
342 
343 typedef struct {
344     uint32_t magic;
345     uint8_t track_count;
346     uint8_t first_track;
347     uint16_t load_address;
348     uint16_t init_address;
349     uint16_t play_address;
350     uint16_t sp;
351     uint8_t TMA;
352     uint8_t TAC;
353     char title[32];
354     char author[32];
355     char copyright[32];
356 } GB_gbs_header_t;
357 
358 typedef struct {
359     uint8_t track_count;
360     uint8_t first_track;
361     char title[33];
362     char author[33];
363     char copyright[33];
364 } GB_gbs_info_t;
365 
366 /* When state saving, each section is dumped independently of other sections.
367    This allows adding data to the end of the section without worrying about future compatibility.
368    Some other changes might be "safe" as well.
369    This struct is not packed, but dumped sections exclusively use types that have the same alignment in both 32 and 64
370    bit platforms. */
371 
372 #ifdef GB_INTERNAL
373 struct GB_gameboy_s {
374 #else
375 struct GB_gameboy_internal_s {
376 #endif
377     GB_SECTION(header,
378         /* The magic makes sure a state file is:
379             - Indeed a SameBoy state file.
380             - Has the same endianess has the current platform. */
381         volatile uint32_t magic;
382         /* The version field makes sure we don't load save state files with a completely different structure.
383            This happens when struct fields are removed/resized in an backward incompatible manner. */
384         uint32_t version;
385     );
386 
387     GB_SECTION(core_state,
388         /* Registers */
389         uint16_t pc;
390            union {
391                uint16_t registers[GB_REGISTERS_16_BIT];
392                struct {
393                    uint16_t af,
394                             bc,
395                             de,
396                             hl,
397                             sp;
398                };
399                struct {
400 #ifdef GB_BIG_ENDIAN
401                    uint8_t a, f,
402                            b, c,
403                            d, e,
404                            h, l;
405 #else
406                    uint8_t f, a,
407                            c, b,
408                            e, d,
409                            l, h;
410 #endif
411                };
412 
413            };
414         uint8_t ime;
415         uint8_t interrupt_enable;
416         uint8_t cgb_ram_bank;
417 
418         /* CPU and General Hardware Flags*/
419         GB_model_t model;
420         bool cgb_mode;
421         bool cgb_double_speed;
422         bool halted;
423         bool stopped;
424         bool boot_rom_finished;
425         bool ime_toggle; /* ei has delayed a effect.*/
426         bool halt_bug;
427         bool just_halted;
428 
429         /* Misc state */
430         bool infrared_input;
431         GB_printer_t printer;
432         uint8_t extra_oam[0xff00 - 0xfea0];
433         uint32_t ram_size; // Different between CGB and DMG
434         GB_workboy_t workboy;
435 
436        int32_t ir_sensor;
437        bool effective_ir_input;
438        uint16_t address_bus;
439     );
440 
441     /* DMA and HDMA */
442     GB_SECTION(dma,
443         bool hdma_on;
444         bool hdma_on_hblank;
445         uint8_t hdma_steps_left;
446         int16_t hdma_cycles; // in 8MHz units
447         uint16_t hdma_current_src, hdma_current_dest;
448 
449         uint8_t dma_steps_left;
450         uint8_t dma_current_dest;
451         uint16_t dma_current_src;
452         int16_t dma_cycles;
453         bool is_dma_restarting;
454         uint8_t last_opcode_read; /* Required to emulte HDMA reads from Exxx */
455         bool hdma_starting;
456     );
457 
458     /* MBC */
459     GB_SECTION(mbc,
460         uint16_t mbc_rom_bank;
461         uint8_t mbc_ram_bank;
462         uint32_t mbc_ram_size;
463         bool mbc_ram_enable;
464         union {
465             struct {
466                 uint8_t bank_low:5;
467                 uint8_t bank_high:2;
468                 uint8_t mode:1;
469             } mbc1;
470 
471             struct {
472                 uint8_t rom_bank:4;
473             } mbc2;
474 
475             struct {
476                 uint8_t rom_bank:8;
477                 uint8_t ram_bank:3;
478             } mbc3;
479 
480             struct {
481                 uint8_t rom_bank_low;
482                 uint8_t rom_bank_high:1;
483                 uint8_t ram_bank:4;
484             } mbc5;
485 
486             struct {
487                 uint8_t bank_low:6;
488                 uint8_t bank_high:3;
489                 bool mode:1;
490                 bool ir_mode:1;
491             } huc1;
492 
493             struct {
494                 uint8_t rom_bank:7;
495                 uint8_t padding:1;
496                 uint8_t ram_bank:4;
497             } huc3;
498         };
499         uint16_t mbc_rom0_bank; /* For some MBC1 wirings. */
500         bool camera_registers_mapped;
501         uint8_t camera_registers[0x36];
502         uint8_t rumble_strength;
503         bool cart_ir;
504 
505         // TODO: move to huc3/mbc3/tpp1 struct when breaking save compat
506         uint8_t huc3_mode;
507         uint8_t huc3_access_index;
508         uint16_t huc3_minutes, huc3_days;
509         uint16_t huc3_alarm_minutes, huc3_alarm_days;
510         bool huc3_alarm_enabled;
511         uint8_t huc3_read;
512         uint8_t huc3_access_flags;
513         bool mbc3_rtc_mapped;
514         uint16_t tpp1_rom_bank;
515         uint8_t tpp1_ram_bank;
516         uint8_t tpp1_mode;
517     );
518 
519 
520     /* HRAM and HW Registers */
521     GB_SECTION(hram,
522         uint8_t hram[0xFFFF - 0xFF80];
523         uint8_t io_registers[0x80];
524     );
525 
526     /* Timing */
527     GB_SECTION(timing,
528         GB_UNIT(display);
529         GB_UNIT(div);
530         uint16_t div_counter;
531         uint8_t tima_reload_state; /* After TIMA overflows, it becomes 0 for 4 cycles before actually reloading. */
532         uint16_t serial_cycles;
533         uint16_t serial_length;
534         uint8_t double_speed_alignment;
535         uint8_t serial_count;
536         int32_t speed_switch_halt_countdown;
537         uint8_t speed_switch_countdown; // To compensate for the lack of pipeline emulation
538         uint8_t speed_switch_freeze; // Solely for realigning the PPU, should be removed when the odd modes are implemented
539     );
540 
541     /* APU */
542     GB_SECTION(apu,
543         GB_apu_t apu;
544     );
545 
546     /* RTC */
547     GB_SECTION(rtc,
548         GB_rtc_time_t rtc_real, rtc_latched;
549         uint64_t last_rtc_second;
550         GB_PADDING(bool, rtc_latch);
551         uint32_t rtc_cycles;
552         uint8_t tpp1_mr4;
553     );
554 
555     /* Video Display */
556     GB_SECTION(video,
557         uint32_t vram_size; // Different between CGB and DMG
558         bool cgb_vram_bank;
559         uint8_t oam[0xA0];
560         uint8_t background_palettes_data[0x40];
561         uint8_t sprite_palettes_data[0x40];
562         uint8_t position_in_line;
563         bool stat_interrupt_line;
564         uint8_t effective_scx;
565         uint8_t window_y;
566         /* The LCDC will skip the first frame it renders after turning it on.
567            On the CGB, a frame is not skipped if the previous frame was skipped as well.
568            See https://www.reddit.com/r/EmuDev/comments/6exyxu/ */
569 
570         /* TODO: Drop this and properly emulate the dropped vreset signal*/
571         enum {
572             GB_FRAMESKIP_LCD_TURNED_ON, // On a DMG, the LCD renders a blank screen during this state,
573                                         // on a CGB, the previous frame is repeated (which might be
574                                         // blank if the LCD was off for more than a few cycles)
575             GB_FRAMESKIP_FIRST_FRAME_SKIPPED, // This state is 'skipped' when emulating a DMG
576             GB_FRAMESKIP_SECOND_FRAME_RENDERED,
577         } frame_skip_state;
578         bool oam_read_blocked;
579         bool vram_read_blocked;
580         bool oam_write_blocked;
581         bool vram_write_blocked;
582         bool fifo_insertion_glitch;
583         uint8_t current_line;
584         uint16_t ly_for_comparison;
585         GB_fifo_t bg_fifo, oam_fifo;
586         GB_PADDING(uint8_t, fetcher_x);
587         uint8_t fetcher_y;
588         uint16_t cycles_for_line;
589         uint8_t current_tile;
590         uint8_t current_tile_attributes;
591         uint8_t current_tile_data[2];
592         uint8_t fetcher_state;
593         bool window_is_being_fetched;
594         bool wx166_glitch;
595         bool wx_triggered;
596         uint8_t visible_objs[10];
597         uint8_t obj_comparators[10];
598         uint8_t n_visible_objs;
599         uint8_t oam_search_index;
600         uint8_t accessed_oam_row;
601         uint8_t extra_penalty_for_sprite_at_0;
602         uint8_t mode_for_interrupt;
603         bool lyc_interrupt_line;
604         bool cgb_palettes_blocked;
605         uint8_t current_lcd_line; // The LCD can go out of sync since the vsync signal is skipped in some cases.
606         uint32_t cycles_in_stop_mode;
607         uint8_t object_priority;
608         bool oam_ppu_blocked;
609         bool vram_ppu_blocked;
610         bool cgb_palettes_ppu_blocked;
611         bool object_fetch_aborted;
612         bool during_object_fetch;
613         uint16_t object_low_line_address;
614         bool wy_triggered;
615         uint8_t window_tile_x;
616         uint8_t lcd_x; // The LCD can go out of sync since the push signal is skipped in some cases.
617         bool is_odd_frame;
618         uint16_t last_tile_data_address;
619         uint16_t last_tile_index_address;
620         bool cgb_repeated_a_frame;
621         uint8_t data_for_sel_glitch;
622     );
623 
624     /* Unsaved data. This includes all pointers, as well as everything that shouldn't be on a save state */
625     /* This data is reserved on reset and must come last in the struct */
626     GB_SECTION(unsaved,
627         /* ROM */
628         uint8_t *rom;
629         uint32_t rom_size;
630         const GB_cartridge_t *cartridge_type;
631         enum {
632             GB_STANDARD_MBC1_WIRING,
633             GB_MBC1M_WIRING,
634         } mbc1_wiring;
635         bool is_mbc30;
636 
637         unsigned pending_cycles;
638 
639         /* Various RAMs */
640         uint8_t *ram;
641         uint8_t *vram;
642         uint8_t *mbc_ram;
643 
644         /* I/O */
645         uint32_t *screen;
646         uint32_t background_palettes_rgb[0x20];
647         uint32_t sprite_palettes_rgb[0x20];
648         const GB_palette_t *dmg_palette;
649         GB_color_correction_mode_t color_correction_mode;
650         double light_temperature;
651         bool keys[4][GB_KEY_MAX];
652         GB_border_mode_t border_mode;
653         GB_sgb_border_t borrowed_border;
654         bool tried_loading_sgb_border;
655         bool has_sgb_border;
656 
657         /* Timing */
658         uint64_t last_sync;
659         uint64_t cycles_since_last_sync; // In 8MHz units
660         GB_rtc_mode_t rtc_mode;
661 
662         /* Audio */
663         GB_apu_output_t apu_output;
664 
665         /* Callbacks */
666         void *user_data;
667         GB_log_callback_t log_callback;
668         GB_input_callback_t input_callback;
669         GB_input_callback_t async_input_callback;
670         GB_rgb_encode_callback_t rgb_encode_callback;
671         GB_vblank_callback_t vblank_callback;
672         GB_infrared_callback_t infrared_callback;
673         GB_camera_get_pixel_callback_t camera_get_pixel_callback;
674         GB_camera_update_request_callback_t camera_update_request_callback;
675         GB_rumble_callback_t rumble_callback;
676         GB_serial_transfer_bit_start_callback_t serial_transfer_bit_start_callback;
677         GB_serial_transfer_bit_end_callback_t serial_transfer_bit_end_callback;
678         GB_update_input_hint_callback_t update_input_hint_callback;
679         GB_joyp_write_callback_t joyp_write_callback;
680         GB_icd_pixel_callback_t icd_pixel_callback;
681         GB_icd_vreset_callback_t icd_hreset_callback;
682         GB_icd_vreset_callback_t icd_vreset_callback;
683         GB_read_memory_callback_t read_memory_callback;
684         GB_boot_rom_load_callback_t boot_rom_load_callback;
685         GB_print_image_callback_t printer_callback;
686         GB_workboy_set_time_callback workboy_set_time_callback;
687         GB_workboy_get_time_callback workboy_get_time_callback;
688 
689         /*** Debugger ***/
690         volatile bool debug_stopped, debug_disable;
691         bool debug_fin_command, debug_next_command;
692 
693         /* Breakpoints */
694         uint16_t n_breakpoints;
695         struct GB_breakpoint_s *breakpoints;
696         bool has_jump_to_breakpoints, has_software_breakpoints;
697         void *nontrivial_jump_state;
698         bool non_trivial_jump_breakpoint_occured;
699 
700         /* SLD (Todo: merge with backtrace) */
701         bool stack_leak_detection;
702         signed debug_call_depth;
703         uint16_t sp_for_call_depth[0x200]; /* Should be much more than enough */
704         uint16_t addr_for_call_depth[0x200];
705 
706         /* Backtrace */
707         unsigned backtrace_size;
708         uint16_t backtrace_sps[0x200];
709         struct {
710             uint16_t bank;
711             uint16_t addr;
712         } backtrace_returns[0x200];
713 
714         /* Watchpoints */
715         uint16_t n_watchpoints;
716         struct GB_watchpoint_s *watchpoints;
717 
718         /* Symbol tables */
719         GB_symbol_map_t *bank_symbols[0x200];
720         GB_reversed_symbol_map_t reversed_symbol_map;
721 
722         /* Ticks command */
723         uint64_t debugger_ticks;
724         uint64_t absolute_debugger_ticks;
725 
726         /* Undo */
727         uint8_t *undo_state;
728         const char *undo_label;
729 
730         /* Rewind */
731 #define GB_REWIND_FRAMES_PER_KEY 255
732         size_t rewind_buffer_length;
733         struct {
734             uint8_t *key_state;
735             uint8_t *compressed_states[GB_REWIND_FRAMES_PER_KEY];
736             unsigned pos;
737         } *rewind_sequences; // lasts about 4 seconds
738         size_t rewind_pos;
739 
740         /* SGB - saved and allocated optionally */
741         GB_sgb_t *sgb;
742 
743         double sgb_intro_jingle_phases[7];
744         double sgb_intro_sweep_phase;
745         double sgb_intro_sweep_previous_sample;
746 
747         /* Cheats */
748         bool cheat_enabled;
749         size_t cheat_count;
750         GB_cheat_t **cheats;
751         GB_cheat_hash_t *cheat_hash[256];
752 
753         /* Misc */
754         bool turbo;
755         bool turbo_dont_skip;
756         bool disable_rendering;
757         uint8_t boot_rom[0x900];
758         bool vblank_just_occured; // For slow operations involving syscalls; these should only run once per vblank
759         uint8_t cycles_since_run; // How many cycles have passed since the last call to GB_run(), in 8MHz units
760         double clock_multiplier;
761         GB_rumble_mode_t rumble_mode;
762         uint32_t rumble_on_cycles;
763         uint32_t rumble_off_cycles;
764 
765         /* Temporary state */
766         bool wx_just_changed;
767         bool tile_sel_glitch;
768 
769         GB_gbs_header_t gbs_header;
770    );
771 };
772 
773 #ifndef GB_INTERNAL
774 struct GB_gameboy_s {
775     char __internal[sizeof(struct GB_gameboy_internal_s)];
776 };
777 #endif
778 
779 
780 #ifndef __printflike
781 /* Missing from Linux headers. */
782 #define __printflike(fmtarg, firstvararg) \
783 __attribute__((__format__ (__printf__, fmtarg, firstvararg)))
784 #endif
785 
786 void GB_init(GB_gameboy_t *gb, GB_model_t model);
787 bool GB_is_inited(GB_gameboy_t *gb);
788 bool GB_is_cgb(GB_gameboy_t *gb);
789 bool GB_is_sgb(GB_gameboy_t *gb); // Returns true if the model is SGB or SGB2
790 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
791 GB_model_t GB_get_model(GB_gameboy_t *gb);
792 void GB_free(GB_gameboy_t *gb);
793 void GB_reset(GB_gameboy_t *gb);
794 void GB_switch_model_and_reset(GB_gameboy_t *gb, GB_model_t model);
795 
796 /* Returns the time passed, in 8MHz ticks. */
797 uint8_t GB_run(GB_gameboy_t *gb);
798 /* Returns the time passed since the last frame, in nanoseconds */
799 uint64_t GB_run_frame(GB_gameboy_t *gb);
800 
801 typedef enum {
802     GB_DIRECT_ACCESS_ROM,
803     GB_DIRECT_ACCESS_RAM,
804     GB_DIRECT_ACCESS_CART_RAM,
805     GB_DIRECT_ACCESS_VRAM,
806     GB_DIRECT_ACCESS_HRAM,
807     GB_DIRECT_ACCESS_IO, /* Warning: Some registers can only be read/written correctly via GB_memory_read/write. */
808     GB_DIRECT_ACCESS_BOOTROM,
809     GB_DIRECT_ACCESS_OAM,
810     GB_DIRECT_ACCESS_BGP,
811     GB_DIRECT_ACCESS_OBP,
812     GB_DIRECT_ACCESS_IE,
813 } GB_direct_access_t;
814 
815 /* Returns a mutable pointer to various hardware memories. If that memory is banked, the current bank
816    is returned at *bank, even if only a portion of the memory is banked. */
817 void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank);
818 
819 void *GB_get_user_data(GB_gameboy_t *gb);
820 void GB_set_user_data(GB_gameboy_t *gb, void *data);
821 
822 int GB_load_boot_rom(GB_gameboy_t *gb, const char *path);
823 void GB_load_boot_rom_from_buffer(GB_gameboy_t *gb, const unsigned char *buffer, size_t size);
824 int GB_load_rom(GB_gameboy_t *gb, const char *path);
825 void GB_load_rom_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size);
826 int GB_load_isx(GB_gameboy_t *gb, const char *path);
827 int GB_load_gbs_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size, GB_gbs_info_t *info);
828 int GB_load_gbs(GB_gameboy_t *gb, const char *path, GB_gbs_info_t *info);
829 void GB_gbs_switch_track(GB_gameboy_t *gb, uint8_t track);
830 
831 int GB_save_battery_size(GB_gameboy_t *gb);
832 int GB_save_battery_to_buffer(GB_gameboy_t *gb, uint8_t *buffer, size_t size);
833 int GB_save_battery(GB_gameboy_t *gb, const char *path);
834 
835 void GB_load_battery_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size);
836 void GB_load_battery(GB_gameboy_t *gb, const char *path);
837 
838 void GB_set_turbo_mode(GB_gameboy_t *gb, bool on, bool no_frame_skip);
839 void GB_set_rendering_disabled(GB_gameboy_t *gb, bool disabled);
840 
841 void GB_log(GB_gameboy_t *gb, const char *fmt, ...) __printflike(2, 3);
842 void GB_attributed_log(GB_gameboy_t *gb, GB_log_attributes attributes, const char *fmt, ...) __printflike(3, 4);
843 
844 void GB_set_pixels_output(GB_gameboy_t *gb, uint32_t *output);
845 void GB_set_border_mode(GB_gameboy_t *gb, GB_border_mode_t border_mode);
846 
847 void GB_set_infrared_input(GB_gameboy_t *gb, bool state);
848 
849 void GB_set_vblank_callback(GB_gameboy_t *gb, GB_vblank_callback_t callback);
850 void GB_set_log_callback(GB_gameboy_t *gb, GB_log_callback_t callback);
851 void GB_set_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback);
852 void GB_set_async_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback);
853 void GB_set_rgb_encode_callback(GB_gameboy_t *gb, GB_rgb_encode_callback_t callback);
854 void GB_set_infrared_callback(GB_gameboy_t *gb, GB_infrared_callback_t callback);
855 void GB_set_rumble_callback(GB_gameboy_t *gb, GB_rumble_callback_t callback);
856 void GB_set_update_input_hint_callback(GB_gameboy_t *gb, GB_update_input_hint_callback_t callback);
857 /* Called when a new boot ROM is needed. The callback should call GB_load_boot_rom or GB_load_boot_rom_from_buffer */
858 void GB_set_boot_rom_load_callback(GB_gameboy_t *gb, GB_boot_rom_load_callback_t callback);
859 
860 void GB_set_palette(GB_gameboy_t *gb, const GB_palette_t *palette);
861 
862 /* These APIs are used when using internal clock */
863 void GB_set_serial_transfer_bit_start_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_start_callback_t callback);
864 void GB_set_serial_transfer_bit_end_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_end_callback_t callback);
865 
866 /* These APIs are used when using external clock */
867 bool GB_serial_get_data_bit(GB_gameboy_t *gb);
868 void GB_serial_set_data_bit(GB_gameboy_t *gb, bool data);
869 
870 void GB_disconnect_serial(GB_gameboy_t *gb);
871 
872 /* For cartridges with an alarm clock */
873 unsigned GB_time_to_alarm(GB_gameboy_t *gb); // 0 if no alarm
874 
875 /* RTC emulation mode */
876 void GB_set_rtc_mode(GB_gameboy_t *gb, GB_rtc_mode_t mode);
877 
878 /* For integration with SFC/SNES emulators */
879 void GB_set_joyp_write_callback(GB_gameboy_t *gb, GB_joyp_write_callback_t callback);
880 void GB_set_icd_pixel_callback(GB_gameboy_t *gb, GB_icd_pixel_callback_t callback);
881 void GB_set_icd_hreset_callback(GB_gameboy_t *gb, GB_icd_hreset_callback_t callback);
882 void GB_set_icd_vreset_callback(GB_gameboy_t *gb, GB_icd_vreset_callback_t callback);
883 
884 uint32_t GB_get_clock_rate(GB_gameboy_t *gb);
885 uint32_t GB_get_unmultiplied_clock_rate(GB_gameboy_t *gb);
886 void GB_set_clock_multiplier(GB_gameboy_t *gb, double multiplier);
887 
888 unsigned GB_get_screen_width(GB_gameboy_t *gb);
889 unsigned GB_get_screen_height(GB_gameboy_t *gb);
890 double GB_get_usual_frame_rate(GB_gameboy_t *gb);
891 unsigned GB_get_player_count(GB_gameboy_t *gb);
892 
893 /* Handy ROM info APIs */
894 // `title` must be at least 17 bytes in size
895 void GB_get_rom_title(GB_gameboy_t *gb, char *title);
896 uint32_t GB_get_rom_crc32(GB_gameboy_t *gb);
897 
898 #ifdef GB_INTERNAL
899 void GB_borrow_sgb_border(GB_gameboy_t *gb);
900 #endif
901 
902 #endif /* GB_h */
903