-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk15_gb_emulator.h
4879 lines (4135 loc) · 161 KB
/
k15_gb_emulator.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define K15_ENABLE_EMULATOR_DEBUG_FEATURES 0
#define K15_BREAK_ON_UNKNOWN_INSTRUCTION 1
#define K15_BREAK_ON_ILLEGAL_INSTRUCTION 1
#define K15_GB_EMULATOR
#include "k15_types.h"
#include "k15_gb_opcodes.h"
#include "k15_gb_font.h"
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable : 4334)
#endif
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_LITTLE_ENDIAN 1
#define MINIZ_HAS_64BIT_REGISTERS 1
#define MINIZ_NO_STDIO
#define MINIZ_NO_TIME
#define MINIZ_NO_DEFLATE_APIS
#define MINIZ_NO_ARCHIVE_WRITING_APIS
#define MINIZ_NO_MALLOC
#include "../thirdparty/miniz/miniz.c"
#ifdef _MSC_VER
# pragma warning( pop )
#endif
static constexpr uint8_t gbStateVersion = 6;
static constexpr uint32_t gbStateFourCC = FourCC( 'K', 'G', 'B', 'C' ); //FK: FourCC of state files
static constexpr uint8_t gbNintendoLogo[] = { 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E };
static constexpr char gbRamFileExtension[] = ".k15_gb_ram";
static constexpr char gbStateFileExtension[] = ".k15_gb_state";
static constexpr uint32_t gbCyclesPerFrame = 70224u;
static constexpr uint32_t gbSerialClockCyclesPerBitTransfer = 512u;
static constexpr uint32_t gbEmulatorFrameRate = 60u;
static constexpr uint8_t gbOAMSizeInBytes = 0x9Fu;
static constexpr uint8_t gbDMACycleCount = 160u;
static constexpr uint8_t gbSpriteHeight = 16u;
static constexpr uint8_t gbTileResolutionInPixels = 8u; //FK: Tiles are 8x8 pixels
static constexpr uint8_t gbHalfTileResolutionInPixels = 4u;
static constexpr uint8_t gbHorizontalResolutionInPixels = 160u;
static constexpr uint8_t gbVerticalResolutionInPixels = 144u;
static constexpr uint8_t gbHorizontalResolutionInTiles = gbHorizontalResolutionInPixels / gbTileResolutionInPixels;
static constexpr uint8_t gbVerticalResolutionInTiles = gbVerticalResolutionInPixels / gbTileResolutionInPixels;
static constexpr uint8_t gbBackgroundTileCount = 32u; //FK: BG maps are 32x32 tiles
static constexpr uint8_t gbTileSizeInBytes = 16u; //FK: 8x8 pixels with 2bpp
static constexpr uint8_t gbOpcodeHistoryBufferCapacity = 255u;
static constexpr uint8_t gbObjectAttributeCapacity = 40u;
static constexpr uint8_t gbSpritesPerScanline = 10u; //FK: the hardware allowed no more than 10 sprites per scanline
static constexpr uint8_t gbFrameBufferScanlineSizeInBytes = gbHorizontalResolutionInPixels / 4;
static constexpr size_t gbFrameBufferSizeInBytes = gbFrameBufferScanlineSizeInBytes * gbVerticalResolutionInPixels;
static constexpr uint8_t gbFrameBufferCount = 2;
static constexpr size_t gbMappedMemorySizeInBytes = 0x10000;
static constexpr size_t gbCompressionTokenSizeInBytes = 1;
static constexpr size_t gbRamBankSizeInBytes = Kbyte( 8 );
static constexpr size_t gbRomBankSizeInBytes = Kbyte( 16 );
static constexpr size_t gbMaxRomSizeInBytes = Mbyte( 8 );
static constexpr size_t gbMinRomSizeInBytes = Kbyte( 32 );
typedef uint32_t GBEmulatorInstanceEventMask;
enum
{
K15_GB_NO_EVENT_FLAG = 0x00,
K15_GB_VBLANK_EVENT_FLAG = 0x01,
K15_GB_STATE_SAVED_EVENT_FLAG = 0x02,
K15_GB_STATE_LOADED_EVENT_FLAG = 0x04,
};
enum
{
K15_GB_COUNTER_FREQUENCY_BIT_00 = 9,
K15_GB_COUNTER_FREQUENCY_BIT_01 = 3,
K15_GB_COUNTER_FREQUENCY_BIT_10 = 5,
K15_GB_COUNTER_FREQUENCY_BIT_11 = 7,
};
enum GBStateLoadResult
{
K15_GB_STATE_LOAD_SUCCESS = 0,
K15_GB_STATE_LOAD_FAILED_OLD_VERSION,
K15_GB_STATE_LOAD_FAILED_INCOMPATIBLE_DATA,
K15_GB_STATE_LOAD_FAILED_WRONG_ROM
};
enum GBMapCartridgeResult
{
K15_GB_CARTRIDGE_MAPPED_SUCCESSFULLY = 0,
K15_GB_CARTRIDGE_TYPE_UNSUPPORTED
};
enum GBMappedIOAdresses
{
K15_GB_MAPPED_IO_ADDRESS_JOYP = 0xFF00,
K15_GB_MAPPED_IO_ADDRESS_SC = 0xFF02,
K15_GB_MAPPED_IO_ADDRESS_DIV = 0xFF04,
K15_GB_MAPPED_IO_ADDRESS_TIMA = 0xFF05,
K15_GB_MAPPED_IO_ADDRESS_TMA = 0xFF06,
K15_GB_MAPPED_IO_ADDRESS_TAC = 0xFF07,
K15_GB_MAPPED_IO_ADDRESS_NR10 = 0xFF10,
K15_GB_MAPPED_IO_ADDRESS_NR11 = 0xFF11,
K15_GB_MAPPED_IO_ADDRESS_NR12 = 0xFF12,
K15_GB_MAPPED_IO_ADDRESS_NR13 = 0xFF13,
K15_GB_MAPPED_IO_ADDRESS_NR14 = 0xFF14,
K15_GB_MAPPED_IO_ADDRESS_NR21 = 0xFF16,
K15_GB_MAPPED_IO_ADDRESS_NR22 = 0xFF17,
K15_GB_MAPPED_IO_ADDRESS_NR23 = 0xFF18,
K15_GB_MAPPED_IO_ADDRESS_NR24 = 0xFF19,
K15_GB_MAPPED_IO_ADDRESS_NR30 = 0xFF1A,
K15_GB_MAPPED_IO_ADDRESS_NR31 = 0xFF1B,
K15_GB_MAPPED_IO_ADDRESS_NR32 = 0xFF1C,
K15_GB_MAPPED_IO_ADDRESS_NR33 = 0xFF1D,
K15_GB_MAPPED_IO_ADDRESS_NR34 = 0xFF1E,
K15_GB_MAPPED_IO_ADDRESS_NR41 = 0xFF20,
K15_GB_MAPPED_IO_ADDRESS_NR42 = 0xFF21,
K15_GB_MAPPED_IO_ADDRESS_NR43 = 0xFF22,
K15_GB_MAPPED_IO_ADDRESS_NR44 = 0xFF23,
K15_GB_MAPPED_IO_ADDRESS_NR50 = 0xFF24,
K15_GB_MAPPED_IO_ADDRESS_NR51 = 0xFF25,
K15_GB_MAPPED_IO_ADDRESS_NR52 = 0xFF26,
K15_GB_MAPPED_IO_ADDRESS_LCDC = 0xFF40,
K15_GB_MAPPED_IO_ADDRESS_STAT = 0xFF41,
K15_GB_MAPPED_IO_ADDRESS_DMA = 0xFF46,
K15_GB_MAPPED_IO_ADDRESS_BGP = 0xFF47,
K15_GB_MAPPED_IO_ADDRESS_OBP0 = 0xFF48,
K15_GB_MAPPED_IO_ADDRESS_OBP1 = 0xFF49,
K15_GB_MAPPED_IO_ADDRESS_IF = 0xFF0F,
K15_GB_MAPPED_IO_ADDRESS_IE = 0xFFFF
};
struct GBEmulatorJoypadState
{
union
{
struct
{
union
{
struct
{
uint8_t a : 1;
uint8_t b : 1;
uint8_t select : 1;
uint8_t start : 1;
};
uint8_t actionButtonMask;
};
union
{
struct
{
uint8_t right : 1;
uint8_t left : 1;
uint8_t up : 1;
uint8_t down : 1;
};
uint8_t dpadButtonMask;
};
};
uint16_t value = 0;
};
};
struct GBCpuFlags
{
union
{
struct
{
uint8_t NOP : 4;
uint8_t C : 1;
uint8_t H : 1;
uint8_t N : 1;
uint8_t Z : 1;
};
uint8_t value;
};
};
struct GBCpuRegisters
{
union
{
struct
{
GBCpuFlags F;
uint8_t A;
};
uint16_t AF;
};
union
{
struct
{
uint8_t C;
uint8_t B;
};
uint16_t BC;
};
union
{
struct
{
uint8_t E;
uint8_t D;
};
uint16_t DE;
};
union
{
struct
{
uint8_t L;
uint8_t H;
};
uint16_t HL;
};
uint16_t SP;
uint16_t PC;
};
struct GBCpuStateFlags
{
uint8_t IME : 1;
uint8_t halt : 1;
uint8_t stop : 1;
uint8_t dma : 1;
uint8_t haltBug : 1;
uint8_t pendingEI : 1;
};
struct GBCpuState
{
uint8_t* pIE;
uint8_t* pIF;
GBCpuRegisters registers;
uint32_t cycleCounter;
uint16_t dmaAddress;
uint8_t dmaCycleCounter;
GBCpuStateFlags flags; //FK: not to be confused with GBCpuRegisters::F
};
struct GBSerialState
{
uint8_t* pSerialTransferData = nullptr;
uint8_t* pSerialTransferControl = nullptr;
uint8_t shiftIndex = 0u;
uint8_t inByte = 0xFFu;
uint8_t initiateTransfer = 0u;
uint8_t useInternalClock = 0u;
uint32_t cycleCounter = 0u;
};
enum GBCartridgeType : uint8_t
{
ROM_ONLY = 0x00,
ROM_MBC1 = 0x01,
ROM_MBC1_RAM = 0x02,
ROM_MBC1_RAM_BATT = 0x03,
ROM_MBC2 = 0x05,
ROM_MBC2_BATT = 0x06,
ROM_RAM = 0x08,
ROM_RAM_BATT = 0x09,
ROM_MMMD1 = 0x0B,
ROM_MMMD1_SRAM = 0x0C,
ROM_MMMD1_SRAM_BATT = 0x0D,
ROM_MBC3_TIMER_BATT = 0x0F,
ROM_MBC3_TIMER_RAM_BATT = 0x10,
ROM_MBC3 = 0x11,
ROM_MBC3_RAM = 0x12,
ROM_MBC3_RAM_BATT = 0x13,
ROM_MBC5 = 0x19,
ROM_MBC5_RAM = 0x1A,
ROM_MBC5_RAM_BATT = 0x1B,
ROM_MBC5_RUMBLE = 0x1C,
ROM_MBC5_RUMBLE_SRAM = 0x1D,
ROM_MBC5_RUMBLE_SRAM_BATT = 0x1E,
POCKET_CAMERA = 0x1F,
BANDAI_TAMA5 = 0xFD,
HUDSON_HUC_3 = 0xFE,
};
enum GBCpuInterrupt : uint8_t
{
VBlankInterrupt = (1<<0),
LCDStatInterrupt = (1<<1),
TimerInterrupt = (1<<2),
SerialInterrupt = (1<<3),
JoypadInterrupt = (1<<4)
};
struct GBObjectAttributeFlags
{
uint8_t GBCpaletteNumber : 3;
uint8_t GBCtileVramBank : 1;
uint8_t paletteNumber : 1;
uint8_t xflip : 1;
uint8_t yflip : 1;
uint8_t bgOverObj : 1;
};
struct GBObjectAttributes
{
uint8_t y;
uint8_t x;
uint8_t tileIndex;
GBObjectAttributeFlags flags;
};
struct GBLcdControl
{
uint8_t bgEnable : 1;
uint8_t objEnable : 1;
uint8_t objSize : 1;
uint8_t bgTileMapArea : 1;
uint8_t bgAndWindowTileDataArea : 1;
uint8_t windowEnable : 1;
uint8_t windowTileMapArea : 1;
uint8_t enable : 1;
};
struct GBPalette
{
uint8_t color0 : 2;
uint8_t color1 : 2;
uint8_t color2 : 2;
uint8_t color3 : 2;
};
struct GBLcdStatus
{
uint8_t mode : 2;
uint8_t LycEqLyFlag : 1;
uint8_t enableMode0HBlankInterrupt : 1;
uint8_t enableMode1VBlankInterrupt : 1;
uint8_t enableMode2OAMInterrupt : 1;
uint8_t enableLycEqLyInterrupt : 1;
};
struct GBLcdRegisters
{
GBLcdStatus* pStatus;
uint8_t* pScy;
uint8_t* pScx;
uint8_t* pLy;
uint8_t* pLyc;
uint8_t* pWy;
uint8_t* pWx;
};
struct GBPpuFlags
{
uint8_t drawObjects : 1;
uint8_t drawBackground : 1;
uint8_t drawWindow : 1;
};
struct GBPpuState
{
GBPpuFlags flags;
GBLcdRegisters lcdRegisters;
GBObjectAttributes* pOAM;
GBLcdControl* pLcdControl;
GBPalette* pPalettes;
uint8_t* pBackgroundOrWindowTileIds[ 2 ];
uint8_t* pTileBlocks[ 3 ];
uint8_t* pGBFrameBuffers[ gbFrameBufferCount ];
uint32_t cycleCounter;
uint32_t dotCounter;
GBObjectAttributes scanlineSprites[ gbSpritesPerScanline ];
uint8_t objectMonochromePlatte[ 8 ];
uint8_t backgroundMonochromePalette[ 4 ];
uint8_t scanlineSpriteCounter;
uint8_t activeFrameBufferIndex;
};
enum GBMemoryAccess
{
GBMemoryAccess_None = 0,
GBMemoryAccess_Written = 1,
GBMemoryAccess_Read = 2
};
struct GBMemoryMapper
{
uint8_t* pBaseAddress;
uint8_t* pRom0Bank;
uint8_t* pRom1Bank;
uint8_t* pVideoRAM;
uint8_t* pRamBankSwitch;
uint8_t* pSpriteAttributes;
uint16_t lastAddressWrittenTo;
uint16_t lastAddressReadFrom;
uint8_t lastValueWritten;
GBMemoryAccess memoryAccess;
GBLcdStatus lcdStatus; //FK: Mirror lcd status to check whether we can read from VRAM and/or OAM
bool8_t lcdEnabled; //FK: Mirror lcd enabled flag to check whether we can read from VRAM and/or OAM
bool8_t dmaActive; //FK: Mirror dma flag to check whether we can read only from HRAM
bool8_t ramEnabled; //FK: Mirror ram enabled flag to check whether we can write to external RAM
};
struct GBRomHeader
{
uint8_t reserved[4]; //FK: Entry point
uint8_t nintendoLogo[48];
union
{
uint8_t gameTitle[16];
struct
{
uint8_t padding[11];
uint8_t manufactures[4];
uint8_t colorCompatibility;
};
};
uint8_t licenseHigh;
uint8_t licenseLow;
uint8_t superGameBoyCompatibility;
GBCartridgeType cartridgeType;
uint8_t romSize;
uint8_t ramSize;
uint8_t destinationCode;
uint8_t licenseCode;
uint8_t maskRomVersion;
uint8_t headerChecksum;
uint8_t checksumHigher;
uint8_t checksumLower;
};
#if K15_ENABLE_EMULATOR_DEBUG_FEATURES == 1
struct GBEmulatorDebugSettings
{
uint8_t enableBreakAtProgramCounter : 1;
uint8_t enableBreakAtOpcode : 1;
uint8_t enableBreakAtMemoryReadFromAddress : 1;
uint8_t enableBreakAtMemoryWriteToAddress : 1;
};
struct GBOpcodeHistoryElement
{
uint8_t opcode;
uint16_t address;
GBCpuRegisters registers;
};
struct GBEmulatorDebug
{
GBOpcodeHistoryElement opcodeHistory[ gbOpcodeHistoryBufferCapacity ];
uint8_t pauseExecution : 1;
uint8_t continueExecution : 1;
uint8_t runForOneInstruction : 1;
uint8_t runSingleFrame : 1;
uint8_t pauseAtBreakpoint : 1;
uint16_t breakpointAddress;
uint8_t opcodeHistorySize;
};
#endif
struct GBEmulatorInstanceFlags
{
union
{
struct
{
uint8_t vblank : 1;
uint8_t ramAccessed : 1;
};
uint8_t value;
};
};
struct GBTimerState
{
uint8_t* pDivider;
uint8_t* pCounter;
uint8_t* pModulo;
uint8_t* pControl;
uint16_t internalDivCounter;
uint8_t counterFrequencyBit : 4;
uint8_t enableCounter : 1;
uint8_t timerOverflow : 1;
uint8_t timerLoading : 1;
};
struct GBCartridge
{
const uint8_t* pRomBaseAddress;
uint8_t* pRamBaseAddress;
uint32_t romSizeInBytes;
uint32_t ramSizeInBytes;
uint16_t mappedRom0BankNumber;
uint16_t mappedRom1BankNumber;
uint16_t romBankCount;
uint8_t highBankValue;
uint8_t lowBankValue;
GBRomHeader header;
uint8_t ramBankCount;
uint8_t mappedRamBankNumber;
uint8_t ramEnabled : 1;
uint8_t bankingMode : 1;
};
struct GBApuSquareWaveChannel1
{
uint8_t lengthTimer;
};
struct GBApuSquareWaveChannel2
{
uint8_t lengthTimer;
};
struct GBApuWaveChannel
{
uint8_t* pWavePattern;
uint8_t lengthTimer;
uint8_t currentSample;
uint16_t samplePosition;
uint16_t cycleCount;
uint16_t frequencyCycleCountTarget;
uint8_t channelEnabled : 1;
uint8_t volumeShift : 3;
};
struct GBApuNoiseChannel
{
uint8_t lengthTimer;
};
struct GBApuFrameSequencer
{
uint16_t cycleCounter;
uint8_t clockCounter;
};
struct GBApuState
{
GBApuSquareWaveChannel1 squareWaveChannel1;
GBApuSquareWaveChannel2 squareWaveChannel2;
GBApuWaveChannel waveChannel;
GBApuNoiseChannel noiseChannel;
GBApuFrameSequencer frameSequencer;
};
struct GBEmulatorInstance
{
GBCpuState* pCpuState;
GBPpuState* pPpuState;
GBApuState* pApuState;
GBTimerState* pTimerState;
GBMemoryMapper* pMemoryMapper;
GBSerialState* pSerialState;
GBCartridge* pCartridge;
GBEmulatorJoypadState joypadState;
GBEmulatorInstanceFlags flags;
#if K15_ENABLE_EMULATOR_DEBUG_FEATURES == 1
GBEmulatorDebug debug;
#endif
};
struct GBEmulatorState
{
GBCpuState cpuState;
GBPpuState ppuState;
GBApuState apuState;
GBTimerState timerState;
GBSerialState serialState;
GBCartridge cartridge;
uint16_t mappedRom0BankNumber;
uint16_t mappedRom1BankNumber;
uint8_t mappedRamBankNumber;
};
const uint8_t* getFontGlyphPixel( char glyph )
{
//FK: bitmap font starts with space
RuntimeAssert( glyph >= 32 );
const char glyphIndex = glyph - 32;
const uint8_t rowIndex = glyphIndex / glyphRowCount;
const uint8_t columnIndex = glyphIndex % glyphRowCount;
const uint8_t y = ( fontPixelDataHeightInPixels - 1 ) - ( rowIndex * glyphHeightInPixels );
const uint8_t x = columnIndex * glyphWidthInPixels;
return fontPixelData + (x + y * fontPixelDataWidthInPixels) * 3;
}
static inline uint32_t castSizeToUint32( const size_t value )
{
RuntimeAssert( value < 0xFFFFFFFF );
return ( uint32_t )value;
}
static inline int32_t castSizeToInt32( const size_t value )
{
RuntimeAssert( value < INT32_MAX && value > INT32_MIN );
return (int32_t)value;
}
bool8_t isInVideoRamAddressRange( const uint16_t address )
{
return address >= 0x8000 && address < 0xA000;
}
bool8_t isInOAMAddressRange( const uint16_t address )
{
return address >= 0xFE00 && address < 0xFEA0;
}
bool8_t isInCartridgeRomAddressRange( const uint16_t address )
{
return address >= 0x0000 && address < 0x8000;
}
bool8_t isInMBC1BankingModeSelectRegisterRange( const uint16_t address )
{
return address >= 0x6000 && address < 0x8000;
}
bool8_t isInMBC1RamBankNumberRegisterRange( const uint16_t address )
{
return address >= 0x4000 && address < 0x6000;
}
bool8_t isInMBC1RomBankNumberRegisterRange( const uint16_t address )
{
return address >= 0x2000 && address < 0x4000;
}
bool8_t isInMBC5LowRomBankNumberRegisterRange( const uint16_t address )
{
return address >= 0x2000 && address < 0x3000;
}
bool8_t isInMBC5HighRomBankNumberRegisterRange( const uint16_t address )
{
return address >= 0x3000 && address < 0x4000;
}
bool8_t isInMBC5RamBankNumberRegisterRange( const uint16_t address )
{
return address >= 0x4000 && address < 0x6000;
}
bool8_t isInRamEnableRegisterRange( const uint16_t address )
{
return address >= 0x0000 && address < 0x2000;
}
bool8_t isInExternalRamRange( const uint16_t address )
{
return address >= 0xA000 && address < 0xC000;
}
bool8_t isInIORegisterRange( const uint16_t address )
{
return address >= 0xFF00 && address < 0xFF80;
}
bool8_t isInHighRamAddressRange( const uint16_t address )
{
return address >= 0xFF80 && address < 0xFFFF;
}
bool8_t isInWorkRamRange( const uint16_t address )
{
return address >= 0xC000 && address < 0xCFFF;
}
bool8_t isInEchoRamRange( const uint16_t address )
{
return address >= 0xE000 && address < 0xFDFF;
}
void patchIOCartridgeMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBCartridge* pCartridge )
{
pCartridge->pRomBaseAddress = pMemoryMapper->pBaseAddress;
}
void patchIOCpuMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBCpuState* pState )
{
pState->pIE = pMemoryMapper->pBaseAddress + 0xFFFF;
pState->pIF = pMemoryMapper->pBaseAddress + 0xFF0F;
}
void patchIOTimerMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBTimerState* pTimerState )
{
pTimerState->pDivider = pMemoryMapper->pBaseAddress + 0xFF04;
pTimerState->pCounter = pMemoryMapper->pBaseAddress + 0xFF05;
pTimerState->pModulo = pMemoryMapper->pBaseAddress + 0xFF06;
pTimerState->pControl = pMemoryMapper->pBaseAddress + 0xFF07;
}
void patchIOSerialMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBSerialState* pSerialState )
{
pSerialState->pSerialTransferData = pMemoryMapper->pBaseAddress + 0xFF01;
pSerialState->pSerialTransferControl = pMemoryMapper->pBaseAddress + 0xFF02;
}
void patchIOPpuMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBPpuState* pPpuState )
{
pPpuState->pOAM = (GBObjectAttributes*)(pMemoryMapper->pBaseAddress + 0xFE00);
pPpuState->pLcdControl = (GBLcdControl*)(pMemoryMapper->pBaseAddress + 0xFF40);
pPpuState->pPalettes = (GBPalette*)(pMemoryMapper->pBaseAddress + 0xFF47);
pPpuState->pTileBlocks[0] = pMemoryMapper->pBaseAddress + 0x8000;
pPpuState->pTileBlocks[1] = pMemoryMapper->pBaseAddress + 0x8080;
pPpuState->pTileBlocks[2] = pMemoryMapper->pBaseAddress + 0x9000;
pPpuState->pBackgroundOrWindowTileIds[0] = pMemoryMapper->pBaseAddress + 0x9800;
pPpuState->pBackgroundOrWindowTileIds[1] = pMemoryMapper->pBaseAddress + 0x9C00;
pPpuState->dotCounter = 0;
pPpuState->cycleCounter = 0;
pPpuState->lcdRegisters.pStatus = (GBLcdStatus*)(pMemoryMapper->pBaseAddress + 0xFF41);
pPpuState->lcdRegisters.pScy = pMemoryMapper->pBaseAddress + 0xFF42;
pPpuState->lcdRegisters.pScx = pMemoryMapper->pBaseAddress + 0xFF43;
pPpuState->lcdRegisters.pLy = pMemoryMapper->pBaseAddress + 0xFF44;
pPpuState->lcdRegisters.pLyc = pMemoryMapper->pBaseAddress + 0xFF45;
pPpuState->lcdRegisters.pWy = pMemoryMapper->pBaseAddress + 0xFF4A;
pPpuState->lcdRegisters.pWx = pMemoryMapper->pBaseAddress + 0xFF4B;
}
void patchIOApuMappedMemoryPointer( GBMemoryMapper* pMemoryMapper, GBApuState* pApuState )
{
pApuState->waveChannel.pWavePattern = pMemoryMapper->pBaseAddress + 0xFF30;
}
uint8_t calculateGBRomHeaderChecksum( const uint8_t* pRomData )
{
const uint8_t* pData = pRomData + 0x0134;
const uint8_t* pDataEnd = pRomData + 0x014C;
uint8_t checksum = 0u;
while( pData <= pDataEnd )
{
checksum = checksum - *pData - 1;
++pData;
}
return checksum;
}
bool8_t isGBRomData( const uint8_t* pRomData, const size_t romDataSizeInBytes )
{
if( romDataSizeInBytes < gbMinRomSizeInBytes || romDataSizeInBytes > gbMaxRomSizeInBytes )
{
return 0u;
}
GBRomHeader header;
memcpy(&header, pRomData + 0x0100, sizeof(GBRomHeader));
//FK: TODO calculate complete rom checksum eventually...
const uint8_t headerChecksum = calculateGBRomHeaderChecksum( pRomData );
return headerChecksum == header.headerChecksum;
}
GBRomHeader getGBRomHeader(const uint8_t* pRomData)
{
GBRomHeader header;
memcpy(&header, pRomData + 0x0100, sizeof(GBRomHeader));
return header;
}
struct ZipEndOfCentralDirectory
{
uint32_t signature;
uint16_t diskNumber;
uint16_t centralDirDisk;
uint16_t centralDirRecordCount;
uint32_t centralDirectorySizeInBytes;
uint32_t centralDirectoryAbsoluteOffset;
};
struct ZipArchive
{
const uint8_t* restrict_modifier pData;
const ZipEndOfCentralDirectory* restrict_modifier pEocd;
uint32_t dataSizeInBytes;
};
struct GZipDataFlags
{
union
{
struct
{
uint8_t FTEXT : 1;
uint8_t FHCRC : 1;
uint8_t FEXTRA : 1;
uint8_t FNAME : 1;
uint8_t FCOMMENT : 1;
uint8_t reserved : 3;
};
uint8_t value;
};
};
struct GZipFooter
{
uint32_t crc32Checksum;
uint32_t uncompressedSizeInBytes;
};
struct GZipData
{
const uint8_t* pData;
const GZipFooter* pFooter;
uint32_t dataSizeInBytes;
uint8_t compressionMethod;
GZipDataFlags flags;
};
enum class UncompressResult : uint8_t
{
Success,
UnsupportedCompressionMethod,
ChecksumError,
TargetBufferTooSmall
};
struct BitStream
{
const uint8_t* pDataStart;
const uint8_t* pDataEnd;
const uint8_t* pDataCurrent;
uint8_t bitMask;
};
struct MemoryWriteStream
{
uint8_t* pTargetData;
const uint8_t* pTargetDataEnd;
};
struct DeflateBlockHeader
{
uint8_t isFinal : 1;
uint8_t compressionMethod : 2;
};
MemoryWriteStream createMemoryWriteStream( uint8_t* pTargetBuffer, const uint32_t targetBufferCapacityInBytes )
{
MemoryWriteStream writeStream;
writeStream.pTargetData = pTargetBuffer;
writeStream.pTargetDataEnd = pTargetBuffer + targetBufferCapacityInBytes;
return writeStream;
}
bool8_t pushData( MemoryWriteStream* pWriteStream, const uint8_t* pData, const uint32_t dataSizeInBytes )
{
if( pWriteStream->pTargetData + dataSizeInBytes < pWriteStream->pTargetDataEnd )
{
return 0u;
}
memcpy( pWriteStream->pTargetData, pData, dataSizeInBytes );
pWriteStream->pTargetData += dataSizeInBytes;
return 1u;
}
BitStream createBitStream( const uint8_t* pData, uint32_t dataSizeInBytes )
{
BitStream bitStream;
bitStream.pDataStart = pData;
bitStream.pDataCurrent = pData;
bitStream.pDataEnd = pData + dataSizeInBytes;
bitStream.bitMask = 1;
return bitStream;
}
void advanceToNextByte( BitStream* pBitStream )
{
RuntimeAssert( ( pBitStream->pDataCurrent + 1 ) < pBitStream->pDataEnd );
++pBitStream->pDataCurrent;
pBitStream->bitMask = 1;
}
uint8_t reverseBitsInByte( uint8_t value )
{
//FK: https://developer.squareup.com/blog/reversing-bits-in-c/
return (uint8_t)(((value * 0x0802LU & 0x22110LU) |
(value * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16);
}
uint8_t readBit( BitStream* pBitStream )
{
const uint8_t bit = ( *pBitStream->pDataCurrent & pBitStream->bitMask ) > 0;
pBitStream->bitMask <<= 1;
if( pBitStream->bitMask == 0u )
{
advanceToNextByte( pBitStream );
}
return bit;
}
uint8_t readBits( BitStream* pBitStream, uint8_t bitsToRead )
{
RuntimeAssert( bitsToRead <= 8 );
uint8_t value = 0u;
while( true )
{
value |= readBit( pBitStream );
if( ( --bitsToRead ) == 0u )
{
break;
}
value <<= 1u;
}
return value;
}
uint8_t readBitsInverse( BitStream* pBitStream, uint8_t bitsToRead )
{
RuntimeAssert( bitsToRead <= 8 );
uint8_t value = 0u;
for( uint8_t bitIndex = 0u; bitIndex < bitsToRead; ++bitIndex )
{
value |= ( readBit( pBitStream ) << bitIndex );
}
return value;
}
void moveToNextByteBoundary( BitStream* pBitStream )
{
if( pBitStream->bitMask == 1u )
{
return;
}
advanceToNextByte( pBitStream );
}
void skipBytes( BitStream* pBitStream, const uint32_t bytesToSkip )
{
RuntimeAssert( pBitStream->bitMask == 1u );
RuntimeAssert( pBitStream->pDataCurrent + bytesToSkip < pBitStream->pDataEnd );
pBitStream->pDataCurrent += bytesToSkip;
}
const ZipEndOfCentralDirectory* findZipArchiveEndOfCentralDirectory( const uint8_t* pZipData, const uint32_t zipDataSizeInBytes )
{
uint32_t eocdPos = zipDataSizeInBytes - 20;
while( eocdPos != 0 )
{
if( pZipData[ eocdPos + 3 ] == 0x06 &&
pZipData[ eocdPos + 2 ] == 0x05 &&