-
Notifications
You must be signed in to change notification settings - Fork 2
/
csfec.c
4452 lines (4313 loc) · 182 KB
/
csfec.c
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
// #### #### ###### ###### #### ------------------------- //
// ## ## ## ## ## ## ## ## CSFEC, stock Commodore 64 //
// ## ## ## ## ## (SixtyFour) emulator made //
// ## #### #### #### ## on top of CPCEC's modules //
// ## ## ## ## ## by Cesar Nicolas-Gonzalez //
// ## ## ## ## ## ## ## ## since 2022-01-12 till now //
// #### #### ## ###### #### ------------------------- //
#define MY_CAPTION "CSFEC"
#define my_caption "csfec"
#define MY_LICENSE "Copyright (C) 2019-2024 Cesar Nicolas-Gonzalez"
/* This notice applies to the source code of CPCEC and its binaries.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact information: <mailto:[email protected]> */
// In a similar spirit to ZXSEC, the goal is to adequately emulate the
// Commodore 64 computer, reusing as much of CPCEC as possible despite
// MOS' own hardware: CPU 6510, VIC-II 6569 (video), SID 6581 (audio),
// CIA 6526 (I/O+timers)... plus the chips in the C1541 disc drive.
// This file provides C64-specific features for configuration, VIC-II,
// PAL and CIA logic, 6510 timings and support, snapshots, options...
#include <stdio.h> // printf()...
#include <stdlib.h> // strtol()...
#include <string.h> // strcpy()...
// Commodore 64 PAL metrics and constants defined as general types -- //
#define VIDEO_PLAYBACK 50
#define VIDEO_LENGTH_X (63<<4)
#define VIDEO_LENGTH_Y (39<<4)
#ifndef VIDEO_BORDERLESS
#define VIDEO_OFFSET_X (13<<4)
#define VIDEO_OFFSET_Y (11<<2) // the best balance for "Delta" (score panel on top) and "Megaphoenix" (on bottom)
#define VIDEO_PIXELS_X (48<<4)
#define VIDEO_PIXELS_Y (67<<3)
#else
#define VIDEO_OFFSET_X (17<<4) // show the default 640x400 screen without the border
#define VIDEO_OFFSET_Y (25<<2)
#define VIDEO_PIXELS_X (40<<4)
#define VIDEO_PIXELS_Y (25<<4)
#endif
#define VIDEO_RGB2Y(r,g,b) ((r)*3+(g)*6+(b)) // generic RGB-to-Y expression
#if defined(SDL2)||!defined(_WIN32)
unsigned short session_icon32xx16[32*32] = {
#include "csfec-a4.h"
};
#endif
// The Commodore 64 keyboard ( http://unusedino.de/ec64/technical/aay/c64/keybmatr.htm )
// Bear in mind that the keyboard codes are written in OCTAL rather than HEXADECIMAL!
// +-------------------------------------------------------------------------------+ +----+
// | <- | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | + | - | £ |HOME|DEL | | F1 |
// | 71 | 70 | 73 | 10 | 13 | 20 | 23 | 30 | 33 | 40 | 43 | 50 | 53 | 60 | 63 | 00 | | 04 |
// +-------------------------------------------------------------------------------+ +----+
// | CTRL | Q | W | E | R | T | Y | U | I | O | P | @ | * | ^ |RESTORE| | F3 |
// | 72 | 76 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 |RESTORE| | 05 |
// +-------------------------------------------------------------------------------+ +----+
// |R/S |CAPS| A | S | D | F | G | H | J | K | L | : | ; | = | RETURN | | F5 |
// | 77 |LOCK| 12 | 15 | 22 | 25 | 32 | 35 | 42 | 45 | 52 | 55 | 62 | 65 | 01 | | 06 |
// +-------------------------------------------------------------------------------+ +----+
// | C= |LSHIFT| Z | X | C | V | B | N | M | , | . | / |RSHIFT |C.DN|C.RT| | F7 |
// | 75 | 17 | 14 | 27 | 24 | 37 | 34 | 47 | 44 | 57 | 54 | 67 | 64 | 07 | 02 | | 03 |
// +-------------------------------------------------------------------------------+ +----+
// CLR:SHIFT+HOME | SPACE | C.UP:SHIFT+C.DN CAPS LOCK:
// INST:SHIFT+DEL | 74 | C.LT:SHIFT+C.RT SHIFT+C=
// +-----------------------------------------+
#define KBD_JOY_UNIQUE 5 // four sides + one fire
unsigned char kbd_joy[]= // ATARI norm: up, down, left, right, fire1-fire4
{ 0110,0111,0112,0113,0114,0114,0114,0114 }; // always constant, all joystick bits are hard-wired
#define DEBUG_LONGEST 3 // MOS 65XX opcodes can be up to 3 bytes long
//#define MAUS_EMULATION // ignore!
//#define MAUS_LIGHTGUNS // ignore!
#define VIDEO_LO_X_RES // no "half" (hi-res) pixels are ever drawn
#define RUNLENGTH_OBSOLETE // snap_load/snap_save (oldest!!)
#define RUNLENGTH_ENCODING // snap_load/snap_save (old!)
#define LEMPELZIV_ENCODING // snap_load/snap_save
#define PNG_OUTPUT_MODE 0 // PNG_OUTPUT_MODE implies DEFLATE_RFC1950 and forbids QOI
#define POWER_BOOST1 7 // power_boost default value (enabled)
#define POWER_BOOST0 8
#include "cpcec-rt.h" // emulation framework!
const unsigned char kbd_map_xlt[]=
{
// control keys (range 0X81..0XBF)
KBCODE_F1 ,0x81, KBCODE_F2 ,0x82, KBCODE_F3 ,0x83, KBCODE_F4 ,0x84,
KBCODE_F5 ,0x85, KBCODE_F6 ,0x86, KBCODE_F7 ,0x87, KBCODE_F8 ,0x88,
KBCODE_F9 ,0x89, KBCODE_HOLD ,0x8F, KBCODE_F11 ,0x8B, KBCODE_F12 ,0x8C,
KBCODE_X_ADD ,0x91, KBCODE_X_SUB ,0x92, KBCODE_X_MUL ,0x93, KBCODE_X_DIV ,0x94,
#ifdef DEBUG
KBCODE_PRIOR ,0x95, KBCODE_NEXT ,0x96, //KBCODE_HOME ,0x97, KBCODE_END ,0x98,
#endif
// actual keys; again, notice the octal coding
KBCODE_CHR4_5 ,0071, KBCODE_1 ,0070, KBCODE_2 ,0073, KBCODE_3 ,0010, // "~" = ARROW LEFT
KBCODE_4 ,0013, KBCODE_5 ,0020, KBCODE_6 ,0023, KBCODE_7 ,0030,
KBCODE_8 ,0033, KBCODE_9 ,0040, KBCODE_0 ,0043, KBCODE_CHR1_1 ,0050,
KBCODE_CHR1_2 ,0053, KBCODE_BKSPACE ,0000, KBCODE_INSERT ,0060, KBCODE_HOME ,0063, // INSERT = POUND; HOME = HOME (+SHIFT: CLR)
KBCODE_TAB ,0072, KBCODE_Q ,0076, KBCODE_W ,0011, KBCODE_E ,0016,
KBCODE_R ,0021, KBCODE_T ,0026, KBCODE_Y ,0031, KBCODE_U ,0036,
KBCODE_I ,0041, KBCODE_O ,0046, KBCODE_P ,0051, KBCODE_CHR2_1 ,0056,
KBCODE_CHR2_2 ,0061,
KBCODE_CAPSLOCK ,0175, KBCODE_A ,0012, KBCODE_S ,0015, KBCODE_D ,0022, // CAPS LOCK = CONTROL+SHIFT
KBCODE_F ,0025, KBCODE_G ,0032, KBCODE_H ,0035, KBCODE_J ,0042,
KBCODE_K ,0045, KBCODE_L ,0052, KBCODE_CHR3_1 ,0055, KBCODE_CHR3_2 ,0062,
KBCODE_CHR3_3 ,0065, KBCODE_ENTER ,0001,
KBCODE_L_CTRL ,0075, KBCODE_L_SHIFT ,0017, KBCODE_Z ,0014, KBCODE_X ,0027,
KBCODE_C ,0024, KBCODE_V ,0037, KBCODE_B ,0034, KBCODE_N ,0047,
KBCODE_M ,0044, KBCODE_CHR4_1 ,0057, KBCODE_CHR4_2 ,0054, KBCODE_CHR4_3 ,0067,
KBCODE_SPACE ,0074, KBCODE_R_SHIFT ,0064, KBCODE_R_CTRL ,0075,
KBCODE_ESCAPE ,0077, // RUN/STOP
KBCODE_DELETE ,0066, // ARROW UP
KBCODE_RIGHT ,0002, // CURSOR RIGHT
KBCODE_LEFT ,0102, // CURSOR RIGHT + LSHIFT = CURSOR LEFT
KBCODE_DOWN ,0007, // CURSOR DOWN
KBCODE_UP ,0107, // CURSOR DOWN + LSHIFT = CURSOR UP
// function keys on the numeric pad
KBCODE_X_1 ,0004, // F1
KBCODE_X_2 ,0104, // F1 + LSHIFT = F2
KBCODE_X_3 ,0005, // F3
KBCODE_X_4 ,0105, // F3 + LSHIFT = F4
KBCODE_X_5 ,0006, // F5
KBCODE_X_6 ,0106, // F5 + LSHIFT = F6
KBCODE_X_7 ,0003, // F7
KBCODE_X_8 ,0103, // F7 + LSHIFT = F8
KBCODE_END ,0X90, // RESTORE (the NMI button, not a real key!)
// key mirrors
KBCODE_CHR4_4 ,0071, // this key is missing in 104-key layouts!
};
VIDEO_UNIT video_table[16]; // colour table, 0xRRGGBB style: the 16 original colours
VIDEO_UNIT video_xlat[16]; // all colours are static in the VIC-II
char palette_path[STRMAX]="";
int video_table_load(char *s) // based on VICE's palette files (either RR GG BB or RR GG BB X) for the 16 inks
{
FILE *f=puff_fopen(s,"r"); if (!f) return -1;
unsigned char t[STRMAX],n=0; VIDEO_UNIT p[16];
while (fgets(t,STRMAX,f)&&n<=16) if (*t>'#') // skip "# comment" and others
{ unsigned int r,g,b; if (sscanf(UTF8_BOM(t),"%X%X%X",&r,&g,&b)!=3) n=16; else if (n<16) p[n]=((r&255)<<16)+((g&255)<<8)+(b&255); ++n; }
puff_fclose(f); if (n!=16) return -1;
STRCOPY(palette_path,s); for (n=0;n<16;++n) video_table[n]=p[n]; return 0;
}
void video_table_reset(void)
{
VIDEO_UNIT const p[]={ // different gamma and saturation levels
// Community-Colors v1.2a -- p1x3l.net
0X000000,0XFFFFFF,0XAF2A2A,0X62D8CC,0XB03FB6,0X4AC64A,0X3739C4,0XE4ED4E,
0XB6591C,0X683808,0XEA746C,0X4D4D4D,0X848484,0XA6FA9E,0X707CE6,0XB6B6B6,
// Pepto's Colodore v1 -- colodore.com
//0X000000,0XFFFFFF,0X813338,0X75CEC8,0X8E3C97,0X56AC4D,0X2E2C9B,0XEDF171,
//0X8E5029,0X553800,0XC46C71,0X4A4A4A,0X7B7B7B,0XA9FF9F,0X706DEB,0XB2B2B2,
// VICE 2.4 -- vice-emu.sourceforge.io
//0X000000,0XFFFFFF,0X924A40,0X84C5CC,0X9351B6,0X72B14B,0X483AAA,0XD5DF7C,
//0X99692D,0X675200,0XC18178,0X606060,0X8A8A8A,0XB3EC91,0X867ADE,0XB3B3B3,
};
for (int n=0;n<16;++n) video_table[n]=p[n];
}
// GLOBAL DEFINITIONS =============================================== //
#define TICKS_PER_FRAME ((VIDEO_LENGTH_X*VIDEO_LENGTH_Y)>>5)
#define TICKS_PER_SECOND (TICKS_PER_FRAME*VIDEO_PLAYBACK)
int multi_t=0,multi_u=0; // overclocking shift+bitmask
// HARDWARE DEFINITIONS ============================================= //
#define ram_maxcfg 6 // 0 = 64K, 1 = 128K, 2 = 192K, 3 = 320K, 4 = 576K, 5 = 1088K, 6 = 2112K
BYTE mem_ram[33<<16],mem_rom[5<<12],mem_i_o[1<<12]; // RAM (64K C64 + 2048K REU/GEORAM), ROM (8K KERNAL, 8K BASIC, 4K CHARGEN) and I/O (1K VIC-II, 1K SID, 1K VRAM, 1K CIA+EXTRAS)
#define ext_ram (&mem_ram[1<<16]) // RAM beyond the base 64K, see below
BYTE *mmu_rom[256],*mmu_ram[256]; // pointers to all the 256-byte pages
BYTE mmu_bit[256]; // flags of all the 256-byte pages: +1 PEEK, +2 POKE, +4 DUMBPEEK, +8 DUMBPOKE
#define PEEK(x) mmu_rom[(x)>>8][x] // WARNING, x cannot be `x=EXPR`!
#define POKE(x) mmu_ram[(x)>>8][x] // WARNING, x cannot be `x=EXPR`!
#define VICII_TABLE (mem_i_o)
#define VICII_COLOR (&mem_i_o[0X800])
#define CIA_TABLE_0 (&mem_i_o[0XC00])
#define CIA_TABLE_1 (&mem_i_o[0XD00])
#define SID_TABLE_0 (&mem_i_o[0X400])
BYTE *SID_TABLE[3]={SID_TABLE_0,&mem_i_o[0XE00],&mem_i_o[0XF00]}; // default addresses: $D400 (always 1st), $DE00 (2nd) and $DF00 (3rd)
BYTE disc_disabled=0; // disables the disc drive altogether as well as its related logic; +1 = manual, +2 = automatic
BYTE disc_filemode=1; // +1 = read-only by default instead of read-write; +2 = relaxed disc write errors instead of strict
VIDEO_UNIT video_clut[32]; // precalculated 16-colour palette + $D020 border [16] + $D021.. background 0-3 [17..20] + $D025.. sprite multicolour 0-1 [21,22] + sprite #0-7 colour [23..30] + DEBUG
/*char audio_dirty;*/ int audio_queue=0; // used to clump audio updates together to gain speed
// the MOS 6510 and its MMU ----------------------------------------- //
HLII m6510_pc; BYTE m6510_a,m6510_x,m6510_y,m6510_s,m6510_p; int m6510_irq,m6510_int; // the MOS 6510 registers; we must be able to spy them!
BYTE mmu_cfg[2]; // the first two bytes in the MOS 6510 address map; distinct to the first two bytes of RAM!
BYTE mmu_inp,mmu_out; // the full I/O values defined by the MOS 6510's first two bytes
BYTE mmu_mcr=~0; // the current memory map configuration; used to reduce polling. cfr. mmu_recalc() to force an update of the memory map
BYTE tape_enabled=0; // manual tape playback, i.e. the PLAY button
#define tape_disabled ((mmu_cfg[1]&32)>=tape_enabled) // the machine can disable the tape even when we enable it
BYTE tape_browsing=0; // the signal toggles when the tape deck rewinds or fast-forwards
void mmu_setup(void)
{
for (int i=0;i<256;++i) mmu_rom[i]=mmu_ram[i]=mem_ram; // by default, everything is RAM...
MEMZERO(mmu_bit); mmu_bit[0]=1+2; // ...and only ZEROPAGE triggers events (non-dumb R/W)
}
// the REU and GeoRAM memory extensions are handled through the MMU, so their logic goes here
BYTE ram_depth=0; // extended RAM configuration
int ram_kbytes(int x) { return (32<<x)&-64; } // REU/GEORAM size in kb
void ram_setcfg(int x) { ram_depth=x; }
#define ram_getcfg() (ram_depth)
int ram_cap=0,ram_dirty=0; // up to ((8<<16)-1); see `ext_ram`
HLII reu_word; int reu_addr,reu_size=0; // REU C64-extra offsets+length
BYTE reu_table[32]; // REU config.registers
BYTE georam_yes=0,georam_block,georam_page; // GEORAM configuration
#define reu_ram ext_ram
#define reu_cap ram_cap
#define reu_dirty ram_dirty
#define reu_empty 0XFF // the REU can request bytes from empty space
#define reu_max 0X3FFFFF // i.e. (18<<16)-1, 2048k RAM + 2048k empty space!
#define reu_inc_65xx (!(reu_table[10]&128))
#define reu_inc_addr (!(reu_table[10]& 64))
#define reu_fail() (reu_table[0]|=32)
#define reu_mode (reu_table[1]&3)
#define reu_last() do{ reu_table[0]|=64; if (!(reu_table[1]&32)) reu_table[2]=reu_word.b.l,reu_table[3]=reu_word.b.h,reu_table[4]=reu_addr,reu_table[5]=reu_addr>>8,reu_table[6]=reu_addr>>16,reu_table[7]=1,reu_table[8]=0; } while(0)
void reu_kick(void) // start a REU operation according to the current registers
{
if (reu_table[1]&128)
{
reu_word.b.l=reu_table[2],reu_word.b.h=reu_table[3];
reu_addr=(reu_table[4]+(reu_table[5]<<8)+((reu_table[6]&63)<<16)); // slight mod to catch >2048K invasions
if (!(reu_size=reu_table[7]+(reu_table[8]<<8))) reu_size=1<<16;
//char t[4][5]={"SAVE","LOAD","SWAP","TEST"};
//cprintf("REU-%c:%s-%04X ",ram_depth+'0',t[reu_mode],reu_size-1);
//cprintf("REU: %s offsets $%04X:$%06X length $%05X:$%06X\n",t[reu_mode],reu_word.w,reu_addr,reu_size,ram_cap);
}
}
#define reu_reset() (MEMZERO(reu_table),georam_block=georam_page=ram_dirty=0,reu_table[1]=16) // notice that REU + GEORAM are reset at once
// cartridges use their own memory maps (EasyFlash is the preferred type) although always through the MMU
BYTE *cart=NULL,cart_boot=0,cart_mode,cart_bank; INT8 cart_type=-1; WORD m6510_start; // general cartridge settings, including MOS 6510 RESET override
BYTE cart_poke[64]; // some cartridges embed RAM chips; this is what the first WORD in the CHIP header means.
BYTE cart_easy[256]; // Easyflash RAM page: avoid weird accidents by keeping it separate from other devices!
// generally speaking, cartridges can operate in four ways, as defined by GAME (+1) and EXROM (+2); notice that docs often talk about /GAME and /EXROM, their negative states!
// cart_mode = 0 : the cartridge is invisible, regardless of I/O status
// cart_mode = 1 : Ultimax mode: a 8k page (ROML) is always visible on $8000-$9FFF and another one (ROMH) on $E000-$FFFF, effectively overriding the KERNAL bank!
// cart_mode = 2 : 8K mode: if BASIC is visible at $A000-$BFFF, then ROML occupies $8000-$9FFF
// cart_mode = 3 : 16K mode: if BASIC is visible at $A000-$BFFF, then ROML occupies $8000-$9FFF, as in 8K mode; besides, if KERNAL is visible at $E000-$FFFF, then ROMH occupies $A000-$BFFF
// some cartridges are always stuck in these modes; others can change modes and even make themselves fully invisible until the next system reset.
// For example, type 32 (Easyflash) stores the bank value (0-63) in $DE00 and GAME (bit 0) and EXROM (bit 1) in $DE02.
char cart_path[STRMAX]="";
void cart_remove(void) // remove a cartridge; resetting the system must be done by the caller
{ cart_boot=0; /*cart_reset();*/ cart_type=-1; if (cart) free(cart),cart=NULL; }
int cart_insert(char *s) // insert a cartridge or "inject" a program file thru a subset of the autorun handling
{
FILE *f=puff_fopen(s,"rb"); if (!f) return 1;
BYTE header[32]=""; fread1(header,32,f);
if (!strcmp(header,"C64 CARTRIDGE ")) // notice the trailing spaces and the implied final ZERO!
{
fseek(f,mgetmmmm(&header[16]),SEEK_SET); // skip unused bytes!
if (!cart) cart=malloc(1<<20); // 1 MEGABYTE!
if (!cart||header[20]!=1) return puff_fclose(f),1; // something went wrong!
cart_type=header[23]&127; // no types go above 32 ...AFAIK!
cprintf("CRT: ");
int i; while (fgetmmmm(f)==0X43484950&&(i=fgetmmmm(f))>16&&i<=16400) // "CHIP" header
{
int q=fgetmm(f); int p=fgetmm(f); cart_poke[p&63]=q&3; q=fgetmm(f); // first WORD: bank type: 0 ROM, 1 RAM, 2 FLASH
if (i-fgetmm(f)!=16) { cprintf("%08X? ",i); break; } // the header+body size must match the chunk size!!
cprintf("%04X:%04X ",p,q); // perhaps we should check whether `p` and `q` are valid as well...
fread1(&cart[(p&63)*0X4000+(q&0X2000)],i-16,f);
}
cprintf("END!\n");
cart_boot=cart_type==32?1:(~header[24]&1)*2+(~header[25]&1); /*cart_reset();*/ // boot mode according to header, f.e. 01 00 = ULTIMAX, 00 01 = 8K
}
else if (equalsii(header,0x0801)&&(header[2]+header[3])) // PRG magic numbers?
cart_remove(); // a program file needs BASIC, and thus cannot coexist with a cartridge!
else
return puff_fclose(f),1; // wrong magic number!
STRCOPY(cart_path,s);
return puff_fclose(f),0;
}
#define cart_reset() (cart_bank=0,m6510_start=(cart_mode=cart_boot)==1?mgetii(&cart[0X3FFC]):mgetii(&mem_rom[0X1FFC]))
// PORT $0001 input mask: 0XFF -0X17 (MMU + TAPE INP) -0X20 (TAPE MOTOR) =0XC8!
#define MMU_CFG_GET(w) ((w)?(mmu_cfg[0]&mmu_cfg[1])+(~mmu_cfg[0]&((mmu_out|mmu_inp)&0XDF)):mmu_cfg[0])
BYTE mmu_cfg_get(WORD w) { return MMU_CFG_GET(w); }
#define MMU_CFG_SET(w,b) do{ mmu_cfg[(w)]=(b); mmu_update(); }while(0)
#define mmu_cfg_set MMU_CFG_SET
#define mmu_recalc() (mmu_mcr=~0,mmu_update()) // this overrides the MMU cache; use this with care!
void mmu_update(void) // set the address offsets, as well as the tables for m6510_recv(WORD) and m6510_send(WORD,BYTE)
{
int i; if (cart_mode==1) i=5; // ULTIMAX mode always forces BASIC and KERNAL out and I/O in!
else mmu_out=(~mmu_cfg[0]&mmu_out)+(i=mmu_cfg[0]&mmu_cfg[1]); // other modes rely on MMU CFG
// we build the MMU status cache: low 3 bits are taken from the 6510 I/O ports, top 2 bits are the cartridge
if (mmu_mcr!=(i=(~mmu_cfg[0]&7)+(i&7)+(cart_mode<<6))) // i.e. EG000ZZZ, E = EXROM, G = GAME, Z = 6510 I/O MMU
{
BYTE *recv8=mem_ram,*recva=mem_ram,*recve=mem_ram,*recvd=mem_ram,*sendd=mem_ram; // all RAM by default
switch ((mmu_mcr=i)&7) // notice the "incremental" design and the lack of `break` here!
{
case 7: recva=&mem_rom[0X2000-0XA000]; // BASIC
case 6: recve=&mem_rom[0X0000-0XE000]; // KERNAL
case 5: recvd=sendd=&mem_i_o[-0XD000]; // I/O
case 4: break;
case 3: recva=&mem_rom[0X2000-0XA000]; // BASIC
case 2: recve=&mem_rom[0X0000-0XE000]; // KERNAL
case 1: recvd=&mem_rom[0X4000-0XD000]; // CHARGEN
case 0: break;
}
/*if (cart)*/ switch (mmu_mcr&192) // now we check the cartridge mode; again, the design is incremental
{
case 192: // 16K mode (both low)
if ((mmu_mcr&2)) recva=&cart[((cart_bank&63)<<14)+0X2000-0XA000]; // ROMH
case 128: // 8K mode (/EXROM low)
if (!(~mmu_mcr&3)) recv8=&cart[((cart_bank&63)<<14)+0X0000-0X8000]; // ROML
break;
case 64: // ULTIMAX mode (/GAME low)
recv8=&cart[((cart_bank&63)<<14)+0X0000-0X8000]; // ROML
recve=&cart[((cart_bank&63)<<14)+0X2000-0XE000]; // ROMH
case 0: // invisible!
break;
}
for (i=0;i<16;++i)
mmu_rom[i+0X80]=mmu_rom[i+0X90]=recv8,
mmu_rom[i+0XA0]=mmu_rom[i+0XB0]=recva,
mmu_rom[i+0XE0]=mmu_rom[i+0XF0]=recve,
mmu_rom[i+0XD0]=recvd,mmu_ram[i+0XD0]=sendd;
i=sendd!=mem_ram?15:0; // tag the page I/O only if possible
memset(&mmu_bit[0XD0],i ,4); // $D000-$D3FF, VIC-II: all operations, cfr. "FUNNY RASTERS"
memset(&mmu_bit[0XD4],i&3,4); // $D400-$D7FF, SID #1: non-dumb R/W
memset(&mmu_bit[0XD8],i&2,4); // $D800-$DBFF, COLORS: non-dumb W
memset(&mmu_bit[0XDC],i&7,2); // $DC00-$DDFF, CIA1+2: non-dumb R/W and dumb R, cfr. "4KRAWALL"
//memset(&mmu_bit[0XDE],i&3,0X02); // $DE00-$DFFF, extras: non-dumb R/W
//cprintf("CRT:%02d,M:%d,B:%02X\n",cart_type,mmu_mcr>>6,cart_bank);
}
// the logic of pages $DE00, $DF00 and $FF00 is simpler, the footprint is less severe
/**/ if ((mmu_bit[0XDE]=mmu_bit[0XD4])&&cart_type>=0) // show cartridge in range $DE00-$DFFF?
switch (cart_type)
{
case 32: // Easyflash
mmu_bit[0XDF]=0,mmu_ram[0XDF]=mmu_rom[0XDF]=&cart_easy[0-0XDF00]; // $DF00-$DFFF: Easyflash RAM space
break;
default:
mmu_bit[0XDF]=3; // non-dumb R/W
}
else if ((mmu_bit[0XDF]=mmu_bit[0XD4])&&ram_cap&&georam_yes) // show GEORAM in range $DE00-$DEFF?
{
ram_dirty|=255+(i=(((georam_block<<6)+(georam_page&63))<<8)&ram_cap); // `i` is the first byte, but `ram_dirty` must be the last byte
mmu_bit[0XDE]=0,mmu_ram[0XDE]=mmu_rom[0XDE]=&ext_ram[i-0XDE00]; // notice that `mmu_bit[0XDE]` was set to 3 beforehand, instead of 0
//mmu_bit[0XDF]=3; // $DF00-$DFFF: non-dumb R/W
}
else // merge pages $DE00 and $DF00 with current I/O configuration, be it I/O ports or just the RAM at $D000-$DFFF
mmu_ram[0XDE]=mmu_ram[0XDF]=mmu_ram[0XD4],mmu_rom[0XDE]=mmu_rom[0XDF]=mmu_rom[0XD4];
mmu_bit[0XFF]=(ram_cap&&!georam_yes&&(reu_table[1]&(128+16))==128)?2:0; // $FF00, REU: non-dumb W (the $FF00 "trigger")
}
void mmu_reset(void)
{ cart_reset(); mmu_cfg[0]=0X2F; mmu_cfg[1]=mmu_mcr=0XFF; mmu_out=0; mmu_inp=16+7; mmu_recalc(); }
// the VIC-II video chip ============================================ //
BYTE *vicii_memory,*vicii_attrib,*vicii_bitmap; // pointers to the video data blocks: the 16K page, the attribute map and the pixel table
BYTE vicii_mode,vicii_lastmode; // current video mode: 0..7 video mode proper, +8 LEFT/RIGHT BORDER, +16 = BACKGROUND COLOUR, +32 TOP/BOTTOM BORDER
int vicii_pos_y,vicii_len_y,vicii_irq_y; // coordinates and dimensions of the current frame (PAL-312 or NTSC-262)
int vicii_pos_x,vicii_len_x,vicii_irq_x; // coordinates and dimensions of the current scanline and its sprite fetch point
BYTE vicii_ready; // bit 4 of $D011, the DEN bit; it must stick in several moments of the frame
BYTE vicii_frame; // enabled when a new frame must begin (not exactly the same as vicii_pos_y>=vicii_len_y)
BYTE vicii_crunch; // sprite crunch bitmask
BYTE vicii_badline; // are we in a badline?
BYTE vicii_takeover; // is the VIC-II going to fetch the sprites, a badline...? 0 = idle, 1 = busy, >1 special!
BYTE vicii_dmadelay; // advanced horizontal scroll caused by DMA delay
BYTE vicii_nosprites=0,vicii_noimpacts=0; // cheating!!
unsigned int vicii_sprite_k[8]; // the current 24 bits of each sprite's scanline
BYTE vicii_sprite_y[8]; // the low 6 bits of each sprite's counter
BYTE vicii_copy_border[256],vicii_copy_border_l,vicii_copy_border_r; // backups of border colours and states
void video_xlat_clut(void) // precalculate palette following `video_type`; part of it is managed by the VIC-II
{
for (int i=0;i<16;++i) video_clut[i]=video_xlat[i]; // VIC-II built-in palette
for (int i=0;i<15;++i) video_clut[16+i]=video_xlat[VICII_TABLE[32+i]&15]; // VIC-II dynamic palette
}
void vicii_setmode(void) // recalculate bitmap mode when VIC-II registers 17 or 22 are modified
{ vicii_mode=(vicii_mode&~7)+(((VICII_TABLE[17]&96)+(VICII_TABLE[22]&16))>>4); }
void vicii_setmaps(void) // recalculate memory maps when VIC-II register 17 or 24 or CIA #2 registers 0 or 2 are modified
{
int i=~CIA_TABLE_1[0]&CIA_TABLE_1[2]&3;
vicii_memory=&mem_ram[i<<14];
if (VICII_TABLE[17]&32) // BITMAP MODES?
{
vicii_attrib=&vicii_memory[(VICII_TABLE[24]&240)<<6];
vicii_bitmap=&vicii_memory[(VICII_TABLE[24]& 8)<<10];
}
else // CHARACTER MODES!
{
vicii_attrib=&vicii_memory[(VICII_TABLE[24]&240)<<6];
if (!(i&1)&&((VICII_TABLE[24]&12)==4)) // CHAR ROM?
vicii_bitmap=&mem_rom[0X4000+((VICII_TABLE[24]&2)<<10)];
else // BASE RAM!
vicii_bitmap=&vicii_memory[(VICII_TABLE[24]&14)<<10];
}
}
void vicii_reset(void)
{
memset(vicii_sprite_y,63,sizeof(vicii_sprite_y)); MEMZERO(vicii_sprite_k); MEMZERO(vicii_copy_border);
memset(VICII_TABLE,vicii_mode=vicii_pos_x=vicii_pos_y=vicii_irq_y=vicii_frame=0,64);
vicii_setmaps(); vicii_setmode(); video_xlat_clut();
}
// the CIA #1+#2 gate arrays ======================================== //
BYTE key2joy_flag=0; // alternate joystick ports
BYTE kbd_bits[10]; // combined autorun+keyboard+joystick bits
int cia_count_a[2],cia_count_b[2]; // the CIA event counters: the active value range is 0..65535
int cia_minor_a[2],cia_minor_b[2],cia_major_b[2]; // MINOR = clock tick step, MAJOR = cia_count_a[] underflow
int cia_event_a[2],cia_event_b[2]; // sending a byte to ports 14 and 15 triggers events; >=256 means a new byte
BYTE cia_state_a[2],cia_state_b[2]; // state bits: +8 LOAD, +4 WAIT, +2 MOVE, +1 STOP
int cia_serials[2]; char cia_serialz[2]; // serial bit transfer countdowns and values
#define cia_port_14(i,b) (cia_minor_a[i]=~b&32)
#define cia_port_15(i,b) ((cia_minor_b[i]=!(b&96)),(cia_major_b[i]=(b&96)==64))
unsigned int cia_hhmmssd[2]; // the CIA time-of-day registers
BYTE cia_port_13[2],cia_port_11[2]; // flags: CIA interrupt status + locked time-of-day status
char vicii_n_cia=0; // the counter of frames between decimals of second (5 PAL, 6 NTSC)
char cia_nouveau=1; // the original CIA 6526 had a bug that the later CIA 6526A fixed out: polling port 13 halted the countdown for an instant (?)
char vic_nouveau=1; // the original CIA 6526 - VIC-II 6569 bridge relied on discrete glue logic instead of a custom IC devised for the VIC-II 8565
int cias_alarmclock(int i) // check the alarm; return ZERO if no interruption must trigger, NONZERO otherwise
{
if (equalsiiii(&CIA_TABLE_0[i*(CIA_TABLE_1-CIA_TABLE_0)+8],cia_hhmmssd[i]))
if (((cia_port_13[i]|=4)&CIA_TABLE_0[i*(CIA_TABLE_1-CIA_TABLE_0)+13]&4)&&cia_port_13[i]<128)
return cia_port_13[i]+=128;
return 0;
}
int cias_24hours(int i) // tick the CIA time-of-day clock; return ZERO if no alarm happens, NONZERO otherwise
{
DWORD x=cia_hhmmssd[i]; if (x&0X40000000) return 0;
if ((++x&15)>=10) // tenths of second
if (!(~(x+= 256 - 10 )&0X00000A00)) // seconds
if (!(~(x+=0X00000600)&0X00006000)) // tens of seconds
if (!(~(x+=0X0000A000)&0X000A0000)) // minutes
if (!(~(x+=0X00060000)&0X00600000)) // tens of minutes
{
if (!(~(x+=0X00A00000)&0X13000000)) // hours
x-=0X92000000;
else if (!(~(x&0X0A000000))) // tens of hours
x+=0X06000000;
}
return cia_hhmmssd[i]=x,cias_alarmclock(i);
}
// signals between the C64 main CPU and the C1541 controller:
// on the C1541 side ($1800)
// - bit 7: ATN IN
// - bit 6: 0 in drives 8 and 9, 1 in drives 10 and 11
// - bit 5: 0 in drives 8 and 10, 1 in drives 9 and 11
// - bit 4: ATN ACK OUT
// - bit 3: CLOCK OUT
// - bit 2: CLOCK IN
// - bit 1: DATA OUT
// - bit 0: DATA IN
// on the C64 side ($DD00)
// - bit 7: DATA IN
// - bit 6: CLOCK IN
// - bit 5: DATA OUT
// - bit 4: CLOCK OUT
// - bit 3: ATN OUT
BYTE c1541_peeks_c64(void) // the C1541 requests a byte from the C64
{
return (((CIA_TABLE_1[0]>>7)& 1)+
((CIA_TABLE_1[0]>>4)& 4)+
((CIA_TABLE_1[0]<<3)&128))^133; // negative!?
}
void c1541_pokes_c64(BYTE b) // the C1541 sends a byte to the C64
{
if (b&8)
{
if ((CIA_TABLE_1[13]|=16)&CIA_TABLE_1[14]&63)
m6510_irq|=+128; // C1541 $XXXX raises an IRQ on the C64!
}
}
void cia_reset(void)
{
cia_hhmmssd[0]=cia_hhmmssd[1]=0X01000000; // = 1:00:00.0 AM
memset(CIA_TABLE_0,cia_port_13[0]=0,16);
memset(CIA_TABLE_1,cia_port_13[1]=0,16);
CIA_TABLE_0[11]=CIA_TABLE_1[11]=vicii_n_cia=1;
cia_state_a[0]=cia_state_a[1]=cia_state_b[0]=cia_state_b[1]=+0+0+0+1;
cia_minor_a[0]=cia_minor_a[1]=
cia_minor_b[0]=cia_minor_b[1]=
cia_major_b[0]=cia_major_b[1]=
cia_port_11[0]=cia_port_11[1]=
cia_serials[0]=cia_serials[1]=
cia_serialz[0]=cia_serialz[1]=0;
CIA_TABLE_0[4]=CIA_TABLE_0[5]=CIA_TABLE_0[6]=CIA_TABLE_0[7]=
CIA_TABLE_1[4]=CIA_TABLE_1[5]=CIA_TABLE_1[6]=CIA_TABLE_1[7]=255;
CIA_TABLE_0[0]=CIA_TABLE_0[1]=CIA_TABLE_1[0]=CIA_TABLE_1[1]=255; // *?*
cia_event_a[0]=cia_event_a[1]=cia_event_b[0]=cia_event_b[1]=256; // *!*
cia_count_a[0]=cia_count_a[1]=cia_count_b[0]=cia_count_b[1]=65535;
}
// behind the CIA: tape I/O handling -------------------------------- //
char tape_path[STRMAX]="",tap_magic[]="C64-TAPE-RAW",t64_magic1[]="C64 tape image",t64_magic2[]="C64S tape ";
FILE *tape=NULL; int tape_filetell=0,tape_filesize=0,tape_filebase; // file handle, offset and length
BYTE tape_buffer[8<<8],tape_old_type; int tape_length,tape_offset; // tape buffer/directory (must be >1k!)
int tape_seek(int i) // moves file cursor to `i`, cancels the cache if required
{
if (i<0) i=0; else if (i>tape_filesize) i=tape_filesize; // sanitize
int j=i-tape_filetell+tape_offset; if (j>=0&&j<tape_length) // within cache?
return tape_offset=j,tape_filetell=i;
return fseek(tape,i,SEEK_SET),tape_offset=tape_length=0,tape_filetell=i;
}
void tape_skip(int i) { if (i) tape_seek(tape_filetell+i); } // quick!
int tape_getc(void) // returns the next byte in the file, or -1 on EOF
{
if (tape_offset>=tape_length)
if ((tape_offset=0)>=(tape_length=fread1(tape_buffer,sizeof(tape_buffer),tape)))
return -1; // EOF
return ++tape_filetell,tape_buffer[tape_offset++];
}
int tape_getcc(void) // returns an Intel-style WORD; see tape_getc()
{ int i; if ((i=tape_getc())>=0) i|=tape_getc()<<8; return i; }
int tape_getccc(void) // returns an Intel-style 24-bit; see tape_getc()
{ int i; if ((i=tape_getc())>=0) if ((i|=tape_getc()<<8)>=0) i|=tape_getc()<<16; return i; }
int tape_getcccc(void) // returns an Intel-style DWORD; mind the sign in 32bits!
{ int i; if ((i=tape_getc())>=0) if ((i|=tape_getc()<<8)>=0) if ((i|=tape_getc()<<16)>=0) i|=tape_getc()<<24; return i; }
void tape_flush(void) // flushes the tape buffer onto the tape file
{ fwrite1(tape_buffer,sizeof(tape_buffer),tape),tape_offset=0; }
void tape_putc(int i) // sends one byte to the tape buffer
{ tape_buffer[tape_offset]=i; if (++tape_offset>=sizeof(tape_buffer)) tape_flush(); }
// tape_skipload disables realtime, raises frameskip, etc. during tape operation; tape_fastload hijacks tape loaders
char tape_thru_cia=0,tape_rewind=0,tape_skipload=1,tape_fastload=0; int tape_skipping=0; // tape options and status
INT8 tape_signal,tape_type=0; char tape_status=0,tape_output; // tape status
int tape_wave,tape_waverate,tape_waveskip,tape_wavesign; // WAVE status
int tape_t; // duration of the current tape signal in microseconds
BYTE m6510_t64ok=8; // T64-specific variable: MMU configuration trap (7 enabled, 8 disabled)
#define tape_physical() (m6510_t64ok!=7)
BYTE tape_polarity=0; // signal polarity, only relevant in WAVE files
#define FASTTAPE_STABLE // overkill!
int tape_close(void) // closes tape and cleans up
{
if (tape)
{
if (tape_type<0) tape_flush(); //fseek(tape,16,SEEK_SET),fputiiii(tape_filesize-tape_filebase,tape); // saving a tape? store the real tape length
puff_fclose(tape),tape=NULL;
}
tape_filesize=tape_filetell=tape_waveskip=0; m6510_t64ok=8;
return tape_thru_cia=tape_type=tape_t=tape_output=tape_status=0;
}
int tape_open(char *s) // inserts a tape from path `s`; 0 OK, !0 ERROR
{
tape_close();
if (!(tape=puff_fopen(s,"rb")))
return 1; // cannot open file!
MEMZERO(tape_buffer); tape_length=fread1(tape_buffer,sizeof(tape_buffer),tape);
if (equalsmmmm(tape_buffer,0X52494646)&&equalsmmmm(&tape_buffer[8],0X57415645)&&equalsmmmm(&tape_buffer[12],0X666D7420)) // = "RIFF....WAVEfmt "
{
tape_filetell=tape_offset=16; int i,j=tape_getcccc(); tape_getcccc();
tape_filesize=mgetiiii(&tape_buffer[4])+8;
if (!(tape_waverate=tape_getcccc())) return tape_close(),1; // wrong WAVE header!
tape_waveskip=(tape_getcccc()/tape_waverate)-1; tape_wavesign=(tape_getcccc()&0X100000)?1:0;
tape_seek(20+j); j=-1; while ((i=tape_getcccc())>0&&(j=tape_getcccc())>=0&&i!=0x61746164) tape_skip(j); // skip RIFF blocks
if (j<=0) return tape_close(),1; // broken WAVE datas!
tape_type=+0; tape_filebase=tape_filetell; tape_thru_cia=1; tape_wave=0;
}
else if (!memcmp(tape_buffer,"Compressed Square Wave\032\001",24)) // CSW v1 header
{
fseek(tape,0,SEEK_END); tape_filesize=ftell(tape); fseek(tape,tape_length,SEEK_SET);
tape_filetell=tape_filebase=tape_offset=32; tape_type=+1; tape_waverate=(mgetiiii(&tape_buffer[24])>>8)-65536;
tape_thru_cia=1; tape_wavesign=~tape_buffer[28]&1; // first signal (tape polarity) will toggle on the first read!
tape_wave=0;
}
else if (!memcmp(tape_buffer,tap_magic,12)) // C64 TAP header
{
tape_old_type=!tape_buffer[12]; // in the old versions a zero isn't a prefix ("HAWKEYE") but a signal-less 256-tick duration
//tape_filesize=tape_getcccc()+tape_filetell; // this field is unreliable!!!
fseek(tape,0,SEEK_END); tape_filesize=ftell(tape); fseek(tape,tape_length,SEEK_SET);
tape_thru_cia=1; tape_filetell=tape_filebase=tape_offset=20; tape_type=+2;
}
else if (tape_length>=64+tape_buffer[34]*32&&!memcmp(tape_buffer,t64_magic1,14)&&tape_buffer[33]==1&&tape_buffer[34]>=tape_buffer[36]&&tape_buffer[36])
{
tape_filetell=0; tape_filesize=tape_buffer[36]; // the buffer won't be used as such, so we can rewire it to our purposes
tape_type=+3; m6510_t64ok=7;
}
else if (tape_length>=64&&!memcmp(tape_buffer,t64_magic2,10)&&tape_buffer[36]<2) // obsolete T64 archives made with faulty tools
{
fseek(tape,0,SEEK_END); int i=ftell(tape)+mgetii(&tape_buffer[66])-mgetiiii(&tape_buffer[72]); // the actual size...
mputii(&tape_buffer[68],i); // ...is the archive size plus the loading address minus the offset within the archive
tape_filetell=0; tape_filesize=1; // there's just one file in these archives, we don't need to guess anything else
tape_type=+3; m6510_t64ok=7;
}
else return tape_close(),1; // wrong file type!
STRCOPY(tape_path,s);
return /*tape_output=tape_status=*/0;
}
int tape_create(char *s) // creates a tape on path `s`; 0 OK, !0 ERROR
{
tape_close();
if (!(tape=puff_fopen(s,"wb")))
return 1; // cannot create file!
fwrite1(tap_magic,12,tape); kputiiii(1,tape); kputiiii(0,tape); // the size field is irrelevant
STRCOPY(tape_path,s);
tape_filesize=tape_filetell=tape_offset=0;
return tape_type=-1,tape_t=/*tape_output=tape_status=*/0;
}
void tape_dump(void) // send the latest sample to the recording tape
{
if (tape_t>=256*8)
tape_putc(0),tape_putc(tape_t),tape_putc(tape_t>>8),tape_putc(tape_t>>16),tape_t=0;
else
tape_putc(tape_t>>3),tape_t&=7;
}
int tape_catalog(char *t,int x) // fills the buffer `t` of size `x` with the tape contents as an ASCIZ list; returns <0 ERROR, >=0 CURRENT BLOCK
{
if (!tape) return -1; // no tape!
char *u=t,q=0; x=0; // this won't fill up... will it? :-/
switch (tape_type)
{
case +0: // WAV
q=tape_waveskip;
case +1: // CSW
case +2: // TAP
for (int n=0,m;n<25;++n) // we can afford ignoring `x` because this list is always short
{
m=((tape_filesize-tape_filebase)*n/25)&~q;
u+=1+sprintf(u,"%010d -- %02d%%",m+=tape_filebase,n*4);
if (m<=tape_filetell) x=n;
}
return *u=0,x;
case +3: // T64
for (int n=0;n<tape_filesize;++n) // ditto, the contents of a T64 file are limited
{
char s[17],m,k; for (m=0;m<16;++m)
k=tape_buffer[80+n*32+m]&127,s[m]=k<32?'?':k;
while (m>0&&s[m-1]==' ') --m; // trim spaces!
s[m]=0;
u+=1+sprintf(u,"%010d -- PROGRAM '%s', %d bytes",n,s,mgetii(&tape_buffer[68+n*32])-mgetii(&tape_buffer[66+n*32]));
if (n<=tape_filetell) x=n;
}
return *u=0,x;
}
return -1; // unknown type!
}
int tape_select(int i)
{
if (!tape) return -1; // no tape!
tape_browsing=99; // the C64 "notices" rewinding and fast-forwarding
switch (tape_type)
{
case +1: // CSW
tape_status=i&1;
case +0: // WAV
case +2: // TAP
return tape_seek(i),tape_t=0;
case +3: // T64
return tape_filetell=i,0;
}
return -1; // unknown type!
}
void tape_eofmet(void) // the tape is over, shall we close or rewind?
{
if (tape_type==1) tape_status=0; // CSW requires some caution
if (tape_signal||(tape_signal=-1,!tape_rewind)) tape_close();
else tape_seek(tape_filebase); // rewind to beginning of tape
}
int tape_main(int t) // simulate tape activity for `t` ticks; returns nonzero if a new signal was detected
{
char q=0; switch (tape_type)
{
case +0: // WAV
tape_wave-=tape_waverate*t; while (tape_wave<=0)
{
tape_wave+=98E4; // 980 KHz regardless of PAL or NTSC
tape_skip(tape_waveskip); if ((t=tape_getc())<0) { tape_eofmet(); return 1; }
if ((t=(t>128)?1:0)!=tape_status) if ((tape_status=t)^tape_wavesign==tape_polarity) q=1;
}
return q;
case +1: // CSW
tape_wave-=tape_waverate*t; while (tape_wave<=0)
if (tape_wave+=98E4,--tape_t<=0) // 980 KHz, likewise
{
if ((t=tape_getc())>0||(t=tape_getcccc())>0) tape_t+=t;
else { tape_eofmet(); return 1; } // EOF or ZERO!
if ((tape_status^=1)^tape_wavesign==tape_polarity) q=1;
}
return q;
case +2: // TAP
tape_t-=t; while (tape_t<=0)
{
q=1; if ((t=tape_getc())<0) { tape_eofmet(); return 1; }
else if (t>0) tape_t+=t<<3; // nonzero = normal
else if (!tape_old_type) tape_t+=tape_getccc();
else { do tape_t+=256<<3; while (!(t=tape_getc())); tape_t+=t<<3; }
}
return q;
}
return 0; // T64, REC...
}
// T64 files aren't real tapes, but archives of virtual files; reading them relies on "trapping" the MOS 6510
int tape_t64load(char *s) // loads a file from a T64 archive into the emulated C64; `s` is the filename, NULL if none
{
if (s&&*s!='*') // a filename instead of NULL or a wildcard? search!
{
int i; for (i=0;i<tape_filesize;++i)
if (tape_buffer[64+i*32]==1&&tape_buffer[65+i*32]&&!memcmp(&tape_buffer[80+i*32],s,16))
break; // found!!
if (i>=tape_filesize) return 1; // file not found!
tape_filetell=i;
}
WORD l=mgetii(&tape_buffer[66+tape_filetell*32]),h=mgetii(&tape_buffer[68+tape_filetell*32]);
if (l<2||h<2||h<=l) return 1; // wrong init+exit values!!
fseek(tape,mgetiiii(&tape_buffer[72+tape_filetell*32]),SEEK_SET);
//mputii(&mem_ram[0X002D],h); mputii(&mem_ram[0X002F],h); mputii(&mem_ram[0X0031],h);
mputii(&mem_ram[0X00AC],h); mputii(&mem_ram[0X00AE],h); // end-of-file KERNAL pokes
fread1(&mem_ram[l],h-l,tape); // load the file data into RAM!
if (++tape_filetell>=tape_filesize) tape_filetell=0; // wrap back!
return mem_ram[0X90]=0X00; // OK!
}
int t64_loadfile(void) // handles the KERNAL operation "$F533: Load File From Tape"; 0 OK, !0 ERROR
{
mem_ram[0X90]=0X04; // TAPE ERROR! (in theory FILE NOT FOUND)
int i=mem_ram[0XB7]; // Number of Characters in Filename: see "$FDF9: Set Filename"
if (mem_ram[0X93]||i>16) return 1; // VERIFY (instead of LOAD) or invalid filename? quit!
if (!i) return tape_t64load(NULL); // no filename? load anything!
char t[17]; memcpy(t,&mem_ram[mgetii(&mem_ram[0XBB])],16);
while (i<16) t[i++]=' '; // pad the filename with spaces!
return t[i]=0,tape_t64load(t);
}
// behind the CIA: disc I/O handling -------------------------------- //
char disc_path[STRMAX]="",*disc_ram[4]={NULL,NULL,NULL,NULL},disc_canwrite[4]={0,0,0,0};
FILE *disc[4]={NULL,NULL,NULL,NULL}; BYTE disc_motor[4]={0,0,0,0},disc_track[4]={0,0,0,0},disc_sector[4]={0,0,0,0};
int disc_close(int d)
{
if (disc_canwrite[d]<0) // can write AND must write?
fseek(disc[d],0,SEEK_SET),fwrite1(disc_ram[d],683<<8,disc[d]);
if (disc_ram[d])
free(disc_ram[d]),disc_ram[d]=NULL;
if (disc[d])
puff_fclose(disc[d]),disc[d]=NULL;
return 0;
}
void disc_closeall(void)
{
disc_close(0);
disc_close(1);
}
int disc_create(char *s) // create a blank D64 disc on path `s`; 0 OK, !0 ERROR
{
FILE *f=puff_fopen(s,"wb");
if (!f) return 1; // cannot create file!
char t[256],u[256]=
{
18,1,65,-0,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,
31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,
-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,-1,-1,31,21,
-1,-1,31,17,-4,-1,7,19,-1,-1,7,19,-1,-1,7,19,-1,-1,7,19,-1,-1,7,19,-1,
-1,7,19,-1,-1,7,18,-1,-1,3,18,-1,-1,3,18,-1,-1,3,18,-1,-1,3,18,-1,-1,
3,18,-1,-1,3,17,-1,-1,1,17,-1,-1,1,17,-1,-1,1,17,-1,-1,1,17,-1,-1,1,
85,78,84,73,84,76,69,68,-96,-96,-96,-96,-96,-96,-96,-96,-96,-96,48,32,
-96,50,65,-96,-96,-96,-96,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // "UNTITLED"
};
MEMZERO(t); for (int i=0;i<357;++i) fwrite1(t,256,f); // first 357 sectors
fwrite1(u,256,f); // catalogue in the middle of the disc
t[1]=-1; fwrite1(t,256,f); t[1]=0; // end of catalogue
for (int i=359;i<683;++i) fwrite1(t,256,f); // last 324 sectors
return fclose(f),0;
}
int disc_open(char *s,int drive,int canwrite) // open a disc file from path `s`, into drive 8+`drive`; 0 OK, !0 ERROR
{
disc_close(drive);
if (!(disc[drive]=puff_fopen(s,canwrite?"rb+":"rb")))
return 1; // cannot open file!
if (!(disc_ram[drive]=malloc(684<<8))) // a little more room, see below
return puff_fclose(disc[drive]),disc[drive]=NULL,1; // cannot load file!
if (fread1(disc_ram[drive],684<<8,disc[drive])!=683<<8)
return disc_close(drive),1; // improper file!
disc_canwrite[drive]=canwrite; // 0 or 1; later, 1 may become -1 (modified disc)
STRCOPY(disc_path,s); return 0;
}
#define DISC_R_P_M 300 // revolutions/minute
WORD disc_trackoffset[]= // offset of each track, in 256-byte sectors
{
0, // 1st track is 1, not 0!
0, 21, 42, 63, 84,105,126, // 1.. 7
562,580,147,168,189,210,231, // 8..14
252,273,294,315,336,357,376, // 15..21
395,414,433,452,471,490,508, // 22..28
526,544,598,615,632,649,666, // 29..35
683 // file ends where #36 would begin
}; // this implicitly includes the length of each track in sectors: length[x]=offset[x+1]-offset[x]
char disc_hex2gcr[16]={ 10,11,18,19,14,15,22,23, 9,25,26,27,13,29,30,21 }; // soft-hard translation
INT8 disc_gcr2hex[32]={ -1,-1,-1,-1,-1,-1,-1,-1, // all words below 9 are invalid!
-1, 8, 0, 1,-1,12, 4, 5, -1,-1, 2, 3,-1,15, 6, 7, -1, 9,10,11,-1,13,14,-1,
}; // hard-soft translation; 0..15 is the valid range, everything else is an invalid 5-bit word!
#define DISC_SPEED_DIV 1000000 // using 1 MHz (roughly the 6502 clock) as the disc motion reference
int disc_gears,disc_speed; // the disc moves at variable speeds, resulting in different "gear" steps
int disc_gcr_header,disc_gcr_offset,disc_gcr_length; // delay before first byte, buffer offset, number of bytes
BYTE disc_gcr_buffer[512]; // GCR buffer; byte buffers are never longer than 384 bytes and can safely overlap:
BYTE *disc_ptr[4]={NULL,NULL,NULL,NULL};
#define disc_source (&disc_gcr_buffer[128]) // bit expansion writes bytes faster than it reads them :-(
#define disc_target (disc_gcr_buffer) // bit contraction writes bytes more slowly :-)
int disc_byte2gcr(BYTE *t,BYTE *s,int n) // encode `n` bytes of string `s` into the GCR bitstream `t`
{
for (;n>0;t+=5,s+=4,n-=4) // AAAAAaaa.aaBBBBBb.bbbbCCCC.CcccccDD.DDDddddd!
{
BYTE x[8]={
disc_hex2gcr[s[0]>>4],disc_hex2gcr[s[0]&15],
disc_hex2gcr[s[1]>>4],disc_hex2gcr[s[1]&15],
disc_hex2gcr[s[2]>>4],disc_hex2gcr[s[2]&15],
disc_hex2gcr[s[3]>>4],disc_hex2gcr[s[3]&15]};
t[0]=(x[0]<<3) +(x[1]>>2); // AAAAABBB
t[1]=(x[1]<<6)+(x[2]<<1)+(x[3]>>4); // ........:BBCCCCCD
t[2]=(x[3]<<4) +(x[4]>>1); // ........:........:DDDDEEEE
t[3]=(x[4]<<7)+(x[5]<<2)+(x[6]>>3); // ........:........:........:EFFFFFGG
t[4]=(x[6]<<5) +(x[7]>>0); // ........:........:........:........:GGGHHHHH
}
return n; // 0 OK, !0 ERROR
}
int disc_seek_sector(int d) // prepare the currently active sector at drive `d`; 0 OK, !0 ERROR
{
if (!disc[d]||!disc_motor[d]) return -1; // no disc!
int i=disc_track[d]; if (i<1||i>=length(disc_trackoffset)-1) return -1; // bad track!
if (disc_sector[d]>=disc_trackoffset[i+1]-disc_trackoffset[i]) return -1; // bad sector!
disc_ptr[d]=&disc_ram[d][(disc_trackoffset[i]+disc_sector[d])<<8];
return 0;
}
int disc_head_sector(int d) // generate the currently active sector's header
{
if (disc_seek_sector(d)) return -1; // error!
disc_source[0]=0X08; // HEAD ID
disc_source[1]=(disc_source[2]=disc_sector[d])^(disc_source[3]=disc_track[d])^(disc_source[4]=disc_ram[d][0X165A2])^(disc_source[5]=disc_ram[d][0X165A3]); // EOR8 + SECTOR+TRACK+ID1+ID2
disc_source[6]=disc_source[7]=0X0F; // HEAD END
return disc_byte2gcr(disc_gcr_buffer,disc_source,8);
}
int disc_load_sector(int d) // read the currently active sector's contents
{
if (disc_seek_sector(d)) return -1; // error!
disc_source[0]=0X07; // DATA ID
disc_source[257]=0; for (int i=0;i<256;++i) disc_source[257]^=disc_source[1+i]=disc_ptr[d][i]; // EOR8
disc_source[258]=disc_source[259]=0; // DATA END
memset(&disc_source[260],0,100); // FILLER, ranging from 4 to 12 between sectors within the track, and up to 100 after the last sector
return disc_byte2gcr(disc_gcr_buffer,disc_source,360);
}
int disc_gcr2byte(BYTE *t,BYTE *s,int n) // decode `n` bytes of GCR bitstream `s` into the string `t`
{
BYTE z=0,x[8]; for (;n>0;t+=4,s+=5,n-=5) // AAAAaaaaBB.BBbbbbCCCC.ccccDDDDdd.ddEEEEeeee!
{
z|=x[0]=disc_gcr2hex[ s[0]>>3 ]; // AAAAA___
z|=x[1]=disc_gcr2hex[((s[0]<<2)+(s[1]>>6))&31]; // _____BBB:BB______
z|=x[2]=disc_gcr2hex[ (s[1]>>1) &31]; // ........:__CCCCC_
z|=x[3]=disc_gcr2hex[((s[1]<<4)+(s[2]>>4))&31]; // ........:_______D:DDDD____
z|=x[4]=disc_gcr2hex[((s[2]<<1)+(s[3]>>7))&31]; // ........:........:____EEEE:E_______
z|=x[5]=disc_gcr2hex[ (s[3]>>2) &31]; // ........:........:........:_FFFFF__
z|=x[6]=disc_gcr2hex[((s[3]<<3)+(s[4]>>5))&31]; // ........:........:........:______GG:GGG_____
z|=x[7]=disc_gcr2hex[ s[4] &31]; // ........:........:........:........:___HHHHH
t[0]=(x[0]<<4)+x[1];
t[1]=(x[2]<<4)+x[3];
t[2]=(x[4]<<4)+x[5];
t[3]=(x[6]<<4)+x[7];
}
return n||z>=16; // 0 OK, !0 ERROR
}
int disc_save_sector(int d) // save the currently active sector's contents
{
if (!disc_canwrite[d]) return -1; // read only!
if (disc_seek_sector(d)) return -1; // error!
disc_gcr2byte(disc_gcr_buffer,disc_target,360);
memcpy(disc_ptr[d],disc_target+1,256);
if (disc_canwrite[d]>0) disc_canwrite[d]=-disc_canwrite[d]; // tag disc as modified
return 0;
}
// signals between the disc drive and the C1541 controller:
// bit 7: 0 = SYNC found, 1 = waiting for SYNC
// bit 6: bit rate (hi)
// bit 5: bit rate (lo)
// bit 4: write protect (1 = on)
// bit 3: drive light (1 = on)
// bit 2: drive motor (1 = on)
// bit 1: motor step (hi)
// bit 0: motor step (lo) : if ((new-old)&3)==1 go to next track else if ((new-old)&3)==3 go to prev track
BYTE c1541_peeks_disc(void)
{
return 128+16;
}
void c1541_pokes_disc(BYTE b)
{
;
}
// C1541: MOS 6502 MICROPROCESSOR =================================== //
BYTE c1541_mem[1<<16]; // 48K RAM + 16K ROM
#define c1541_rom &c1541_mem[48<<10]
#define VIA_TABLE_0 (&c1541_mem[0X1800])
#define VIA_TABLE_1 (&c1541_mem[0X1C00])
HLII m6502_pc; BYTE m6502_a,m6502_x,m6502_y,m6502_s,m6502_p; int m6502_irq,m6502_int; // the MOS 6502 registers
int m6502_t=0; // used to keep both clocks in time!
void m6502_sync(int t) // runs the C1541 hardware for `t` microseconds
{
int i; m6502_t+=t;
if (VIA_TABLE_0[14]&64)
{
if ((i=mgetii(&VIA_TABLE_0[4])-t)<0)
{
if ((VIA_TABLE_0[13]|=64)&VIA_TABLE_0[14]&64) m6502_irq|=1;
i+=mgetii(&VIA_TABLE_0[6])+1;
}
mputii(&VIA_TABLE_0[4],i);
}
if (VIA_TABLE_1[14]&64)
{
if ((i=mgetii(&VIA_TABLE_1[4])-t)<0)
{
if ((VIA_TABLE_1[13]|=64)&VIA_TABLE_1[14]&64) m6502_irq|=1;
i+=mgetii(&VIA_TABLE_1[6])+1;
}
mputii(&VIA_TABLE_1[4],i);
}
if (VIA_TABLE_0[15]==0X55) // *!* DUMMY, TODO
disc_head_sector(0);
if (VIA_TABLE_1[15]==0XAA) // *!* DUMMY, TODO
disc_load_sector(0);
}
BYTE c64_peeks_c1541(void) // the C64 requests a byte from the C1541
{
return ((VIA_TABLE_0[0]<<5)&128)+((VIA_TABLE_0[0]<<6)&64);
}
void c64_pokes_c1541(BYTE b) // the C64 sends a byte to the C1541
{
if (b&8)
{
if ((VIA_TABLE_0[13]|=12)&VIA_TABLE_0[14]&2)
m6502_irq|=1; // C64 $ED33 raises an IRQ on the C1541!
}
}
BYTE m6502_recv(WORD w) // receive a byte from the C1541 address `w`
{
if (w<0X1C00)
{
if (w<0X1800)
return w>>8; // $1000-$17FF: unused!
else
switch (w&=15) // $1800: VIA #1
{
case 0: // DATA PORT B
return (VIA_TABLE_0[0]&VIA_TABLE_0[2])+(c1541_peeks_c64()&~VIA_TABLE_0[2]);
case 1: // DATA PORT A
case 15: // DATA PORT A*
return 255;
case 4: // TIMER 1 COUNT LO-BYTE