2 // Apple 2 SDL Portable Apple Emulator
5 // © 2014 Underground Software
7 // Loosely based on AppleWin by Tom Charlesworth which was based on AppleWin by
8 // Oliver Schmidt which was based on AppleWin by Michael O'Brien. :-) Parts are
9 // also derived from ApplePC. Too bad it was closed source--it could have been
10 // *the* premier Apple II emulator out there.
12 // JLH = James Hammons <jlhamm@acm.org>
15 // --- ---------- ------------------------------------------------------------
16 // JLH 11/12/2005 Initial port to SDL
17 // JLH 11/18/2005 Wired up graphic soft switches
18 // JLH 12/02/2005 Setup timer subsystem for more accurate time keeping
19 // JLH 12/12/2005 Added preliminary state saving support
20 // JLH 09/24/2013 Added //e support
25 // - Port to SDL [DONE]
27 // - Weed out unneeded functions [DONE]
29 // - 128K IIe related stuff [DONE]
30 // - State loading/saving
48 #include "applevideo.h"
56 // Debug and misc. defines
58 #define THREADED_65C02
59 #define CPU_THREAD_OVERFLOW_COMPENSATION
61 //#define CPU_CLOCK_CHECKING
62 //#define THREAD_DEBUGGING
63 #define SOFT_SWITCH_DEBUGGING
67 uint8_t ram[0x10000], rom[0x10000]; // RAM & ROM spaces
68 uint8_t ram2[0x10000]; // Auxillary RAM
69 //uint8_t diskRom[0x100]; // Disk ROM space
70 V65C02REGS mainCPU; // v65C02 execution context
71 uint8_t appleType = APPLE_TYPE_IIE;
72 FloppyDrive floppyDrive;
73 //bool powerOnState = true; // Virtual power switch
74 bool powerStateChangeRequested = false;
78 uint8_t lastKeyPressed = 0;
80 bool openAppleDown = false;
81 bool closedAppleDown = false;
82 bool store80Mode = false;
84 bool slotCXROM = false;
85 bool slotC3ROM = false;
91 // Language card state (ROM read, no write)
92 uint8_t lcState = 0x02;
94 static bool running = true; // Machine running state flag...
95 static uint32_t startTicks;
96 static bool pauseMode = false;
97 static bool fullscreenDebounce = false;
98 static bool capsLock = false;
99 static bool capsLockDebounce = false;
101 // Local functions (technically, they're global...)
103 bool LoadImg(char * filename, uint8_t * ram, int size);
104 static void SaveApple2State(const char * filename);
105 static bool LoadApple2State(const char * filename);
106 static void ResetApple2State(void);
108 // Local timer callback functions
110 static void FrameCallback(void);
111 static void BlinkTimer(void);
113 #ifdef THREADED_65C02
114 // Test of threaded execution of 6502
115 static SDL_Thread * cpuThread = NULL;
116 //static SDL_mutex * cpuMutex = NULL;
117 static SDL_cond * cpuCond = NULL;
118 static SDL_sem * mainSem = NULL;
119 static bool cpuFinished = false;
120 static bool cpuSleep = false;
122 // NB: Apple //e Manual sez 6502 is running @ 1,022,727 Hz
124 // Let's try a thread...
126 Here's how it works: Execute 1 frame's worth, then sleep.
127 Other stuff wakes it up
129 int CPUThreadFunc(void * data)
131 // Mutex must be locked for conditional to work...
132 // Also, must be created in the thread that uses it...
133 SDL_mutex * cpuMutex = SDL_CreateMutex();
135 // decrement mainSem...
136 //SDL_SemWait(mainSem);
137 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
138 float overflow = 0.0;
144 SDL_CondWait(cpuCond, cpuMutex);
146 // decrement mainSem...
147 #ifdef THREAD_DEBUGGING
148 WriteLog("CPU: SDL_SemWait(mainSem);\n");
150 SDL_SemWait(mainSem);
152 // There are exactly 800 slices of 21.333 cycles per frame, so it works out
155 uint32_t cycles = 17066;
156 #ifdef CPU_THREAD_OVERFLOW_COMPENSATION
157 // ODD! It's closer *without* this overflow compensation. ??? WHY ???
158 overflow += 0.666666667;
167 #ifdef THREAD_DEBUGGING
168 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
170 Execute65C02(&mainCPU, cycles); // how much? 1 frame (after 1 s, off by 40 cycles) not any more--it's off by as much as 240 now!
172 // Adjust the sound routine's last cycle toggled time base
173 // Also, since we're finished executing, .clock is now valid
174 #ifdef THREAD_DEBUGGING
175 WriteLog("CPU: AdjustLastToggleCycles(mainCPU.clock);\n");
177 AdjustLastToggleCycles(mainCPU.clock);
179 #ifdef THREAD_DEBUGGING
180 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
182 for(int i=0; i<800; i++)
184 uint32_t cycles = 21;
185 overflow += 0.333333334;
193 Execute65C02(&mainCPU, cycles);
194 WriteSampleToBuffer();
196 // Dunno if this is correct (seems to be close enough)...
197 vbl = (i < 670 ? true : false);
201 #ifdef THREAD_DEBUGGING
202 WriteLog("CPU: SDL_mutexP(cpuMutex);\n");
204 SDL_mutexP(cpuMutex);
205 // increment mainSem...
206 #ifdef THREAD_DEBUGGING
207 WriteLog("CPU: SDL_SemPost(mainSem);\n");
209 SDL_SemPost(mainSem);
210 #ifdef THREAD_DEBUGGING
211 WriteLog("CPU: SDL_CondWait(cpuCond, cpuMutex);\n");
213 SDL_CondWait(cpuCond, cpuMutex);
215 #ifdef THREAD_DEBUGGING
216 WriteLog("CPU: SDL_mutexV(cpuMutex);\n");
218 SDL_mutexV(cpuMutex);
220 while (!cpuFinished);
222 SDL_DestroyMutex(cpuMutex);
231 // Request a change in the power state of the emulated Apple
233 void SetPowerState(void)
235 // powerOnState = state;
236 // pauseMode = !state;
240 //printf("Turning on...\n");
241 // Transitioning from OFF to ON
242 // mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
247 //printf("Turning off...\n");
251 powerStateChangeRequested = true;
257 // Load a file into RAM/ROM image space
259 bool LoadImg(char * filename, uint8_t * ram, int size)
261 FILE * fp = fopen(filename, "rb");
266 fread(ram, 1, size, fp);
273 static void SaveApple2State(const char * filename)
278 static bool LoadApple2State(const char * filename)
284 static void ResetApple2State(void)
286 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
288 openAppleDown = false;
289 closedAppleDown = false;
300 SwitchLC(); // Make sure MMU is in sane state
301 memset(ram, 0, 0x10000);
302 memset(ram2, 0, 0x10000);
306 #ifdef CPU_CLOCK_CHECKING
308 uint32_t totalCPU = 0;
309 uint64_t lastClock = 0;
314 int main(int /*argc*/, char * /*argv*/[])
316 InitLog("./apple2.log");
318 srand(time(NULL)); // Initialize RNG
321 memset(ram, 0, 0x10000);
322 memset(rom, 0, 0x10000);
323 memset(ram2, 0, 0x10000);
328 // Set up V65C02 execution context
329 memset(&mainCPU, 0, sizeof(V65C02REGS));
330 mainCPU.RdMem = AppleReadMem;
331 mainCPU.WrMem = AppleWriteMem;
332 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
334 // alternateCharset = true;
335 // if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
336 if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
338 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
342 //Load up disk image from config file (for now)...
343 floppyDrive.LoadImage(settings.diskImagePath1, 0);
344 floppyDrive.LoadImage(settings.diskImagePath2, 1);
345 // floppyDrive.LoadImage("./disks/temp.nib", 1); // Load temp .nib file into second drive...
347 WriteLog("About to initialize video...\n");
351 std::cout << "Aborting!" << std::endl;
355 GUI::Init(sdlRenderer);
357 // Have to do this *after* video init but *before* sound init...!
358 //Shouldn't be necessary since we're not doing emulation in the ISR...
359 if (settings.autoStateSaving)
361 // Load last state from file...
362 if (!LoadApple2State(settings.autoStatePath))
363 WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
366 WriteLog("About to initialize audio...\n");
368 SetupBlurTable(); // Set up the color TV emulation blur table
369 running = true; // Set running status...
370 InitializeEventList(); // Clear the event list before we use it...
371 SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
372 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 s intervals
373 startTicks = SDL_GetTicks();
375 #ifdef THREADED_65C02
376 cpuCond = SDL_CreateCond();
377 mainSem = SDL_CreateSemaphore(1);
378 cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
379 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
380 // SDL_sem * mainMutex = SDL_CreateMutex();
383 WriteLog("Entering main loop...\n");
387 double timeToNextEvent = GetTimeToNextEvent();
388 #ifndef THREADED_65C02
389 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
392 #ifdef CPU_CLOCK_CHECKING
393 #ifndef THREADED_65C02
394 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
400 #ifdef THREADED_65C02
401 WriteLog("Main: cpuFinished = true;\n");
403 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
404 //What to do? How do you know when the CPU is sleeping???
405 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
406 //Nope, use a semaphore...
407 WriteLog("Main: SDL_SemWait(mainSem);\n");
408 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
411 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
412 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
413 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
414 SDL_WaitThread(cpuThread, NULL);
415 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
416 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
417 SDL_DestroyCond(cpuCond);
419 SDL_DestroySemaphore(mainSem);
421 if (settings.autoStateSaving)
423 // Save state here...
424 SaveApple2State(settings.autoStatePath);
426 floppyDrive.SaveImage(0);
427 floppyDrive.SaveImage(1);
443 -----------------------
444 space $A0 $A0 $A0 $A0 No xlation
445 RETURN $8D $8D $8D $8D No xlation
446 0 $B0 $B0 $B0 $B0 Need to screen shift+0 (?)
447 1! $B1 $B1 $A1 $A1 No xlation
448 2" $B2 $B2 $A2 $A2 No xlation
449 3# $B3 $B3 $A3 $A3 No xlation
450 4$ $B4 $B4 $A4 $A4 No xlation
451 5% $B5 $B5 $A5 $A5 No xlation
452 6& $B6 $B6 $A6 $A6 No xlation
453 7' $B7 $B7 $A7 $A7 No xlation
454 8( $B8 $B8 $A8 $A8 No xlation
455 9) $B9 $B9 $A9 $A9 No xlation
456 :* $BA $BA $AA $AA No xlation
457 ;+ $BB $BB $AB $AB No xlation
458 ,< $AC $AC $BC $BC No xlation
459 -= $AD $AD $BD $BD No xlation
460 .> $AE $AE $BE $BE No xlation
461 /? $AF $AF $BF $BF No xlation
474 M $CD $8D $DD $9D -> ODD
475 N^ $CE $8E $DE $9E -> ODD
477 P@ $D0 $90 $C0 $80 Need to xlate CTL+SHFT+P & SHFT+P (?)
490 ESC $9B $9B $9B $9B No xlation
493 //static uint64_t lastCPUCycles = 0;
494 static uint32_t frameCount = 0;
495 static void FrameCallback(void)
499 while (SDL_PollEvent(&event))
503 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
506 //Need to do some key translation here, and screen out non-apple keys as well...
507 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
508 // everything else done separately. this is slightly easier. :-P)
509 // if (event.key.keysym.sym == SDLK_TAB) // Prelim key screening...
510 if (event.edit.text[0] == '\t') // Prelim key screening...
513 lastKeyPressed = event.edit.text[0];
516 //kludge: should have a caps lock thingy here...
517 //or all uppercase for ][+...
518 // if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
519 // lastKeyPressed &= 0xDF; // Convert to upper case...
524 // Use ALT+Q to exit, as well as the usual window decoration method
525 if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
528 // CTRL+RESET key emulation (mapped to CTRL+`)
529 // This doesn't work...
530 // if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
531 // if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
532 if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
534 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
535 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
536 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
540 if (event.key.keysym.sym == SDLK_RIGHT)
541 lastKeyPressed = 0x15, keyDown = true;
542 else if (event.key.keysym.sym == SDLK_LEFT)
543 lastKeyPressed = 0x08, keyDown = true;
544 else if (event.key.keysym.sym == SDLK_UP)
545 lastKeyPressed = 0x0B, keyDown = true;
546 else if (event.key.keysym.sym == SDLK_DOWN)
547 lastKeyPressed = 0x0A, keyDown = true;
548 else if (event.key.keysym.sym == SDLK_RETURN)
549 lastKeyPressed = 0x0D, keyDown = true;
550 else if (event.key.keysym.sym == SDLK_ESCAPE)
551 lastKeyPressed = 0x1B, keyDown = true;
552 else if (event.key.keysym.sym == SDLK_BACKSPACE)
553 lastKeyPressed = 0x7F, keyDown = true;
555 // Fix CTRL+key combo...
556 if (event.key.keysym.mod & KMOD_CTRL)
558 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
560 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
562 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
568 // Fix SHIFT+key combo...
569 if (event.key.keysym.mod & KMOD_SHIFT)
571 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
573 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
575 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
578 else if (event.key.keysym.sym == SDLK_1)
580 lastKeyPressed = '!';
584 else if (event.key.keysym.sym == SDLK_2)
586 lastKeyPressed = '@';
590 else if (event.key.keysym.sym == SDLK_3)
592 lastKeyPressed = '#';
596 else if (event.key.keysym.sym == SDLK_3)
598 lastKeyPressed = '#';
602 else if (event.key.keysym.sym == SDLK_4)
604 lastKeyPressed = '$';
608 else if (event.key.keysym.sym == SDLK_5)
610 lastKeyPressed = '%';
614 else if (event.key.keysym.sym == SDLK_6)
616 lastKeyPressed = '^';
620 else if (event.key.keysym.sym == SDLK_7)
622 lastKeyPressed = '&';
626 else if (event.key.keysym.sym == SDLK_8)
628 lastKeyPressed = '*';
632 else if (event.key.keysym.sym == SDLK_9)
634 lastKeyPressed = '(';
638 else if (event.key.keysym.sym == SDLK_0)
640 lastKeyPressed = ')';
644 else if (event.key.keysym.sym == SDLK_MINUS)
646 lastKeyPressed = '_';
650 else if (event.key.keysym.sym == SDLK_EQUALS)
652 lastKeyPressed = '+';
656 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
658 lastKeyPressed = '{';
662 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
664 lastKeyPressed = '}';
668 else if (event.key.keysym.sym == SDLK_BACKSLASH)
670 lastKeyPressed = '|';
674 else if (event.key.keysym.sym == SDLK_SEMICOLON)
676 lastKeyPressed = ':';
680 else if (event.key.keysym.sym == SDLK_QUOTE)
682 lastKeyPressed = '"';
686 else if (event.key.keysym.sym == SDLK_COMMA)
688 lastKeyPressed = '<';
692 else if (event.key.keysym.sym == SDLK_PERIOD)
694 lastKeyPressed = '>';
698 else if (event.key.keysym.sym == SDLK_SLASH)
700 lastKeyPressed = '?';
704 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
706 lastKeyPressed = '~';
714 if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
716 lastKeyPressed = event.key.keysym.sym;
719 // Check for Caps Lock key...
720 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
721 lastKeyPressed -= 0x20;
726 if (event.key.keysym.sym == SDLK_PAUSE)
728 pauseMode = !pauseMode;
733 SpawnMessage("*** PAUSED ***");
738 SpawnMessage("*** RESUME ***");
742 // Paddle buttons 0 & 1
743 if (event.key.keysym.sym == SDLK_INSERT)
744 openAppleDown = true;
745 if (event.key.keysym.sym == SDLK_PAGEUP)
746 closedAppleDown = true;
748 if (event.key.keysym.sym == SDLK_F11)
749 dumpDis = !dumpDis; // Toggle the disassembly process
751 /*else if (event.key.keysym.sym == SDLK_F9)
753 floppyDrive.CreateBlankImage(0);
754 // SpawnMessage("Image cleared...");
756 /*else if (event.key.keysym.sym == SDLK_F10)
758 floppyDrive.SwapImages();
759 // SpawnMessage("Image swapped...");
762 if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
764 else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
766 else if (event.key.keysym.sym == SDLK_F5)
769 char volStr[19] = "[****************]";
770 // volStr[GetVolume()] = 0;
771 for(int i=GetVolume(); i<16; i++)
773 SpawnMessage("Volume: %s", volStr);
775 else if (event.key.keysym.sym == SDLK_F6)
778 char volStr[19] = "[****************]";
779 // volStr[GetVolume()] = 0;
780 for(int i=GetVolume(); i<16; i++)
782 SpawnMessage("Volume: %s", volStr);
784 else if (event.key.keysym.sym == SDLK_F12)
786 if (!fullscreenDebounce)
789 fullscreenDebounce = true;
793 if (event.key.keysym.sym == SDLK_CAPSLOCK)
795 if (!capsLockDebounce)
797 capsLock = !capsLock;
798 capsLockDebounce = true;
804 if (event.key.keysym.sym == SDLK_F12)
805 fullscreenDebounce = false;
806 if (event.key.keysym.sym == SDLK_CAPSLOCK)
807 capsLockDebounce = false;
809 // Paddle buttons 0 & 1
810 if (event.key.keysym.sym == SDLK_INSERT)
811 openAppleDown = false;
812 if (event.key.keysym.sym == SDLK_PAGEUP)
813 closedAppleDown = false;
815 // if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
819 case SDL_MOUSEBUTTONDOWN:
820 GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
822 case SDL_MOUSEBUTTONUP:
823 GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
825 case SDL_MOUSEMOTION:
826 GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
828 case SDL_WINDOWEVENT:
829 if (event.window.event == SDL_WINDOWEVENT_LEAVE)
830 GUI::MouseMove(0, 0, 0);
838 // Handle power request from the GUI
839 if (powerStateChangeRequested)
841 if (GUI::powerOnState)
851 //NOPE SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
852 // ResetApple2State();
855 powerStateChangeRequested = false;
858 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
864 RenderScreenBuffer();
865 GUI::Render(sdlRenderer);
866 SDL_RenderPresent(sdlRenderer);
867 SetCallbackTime(FrameCallback, 16666.66666667);
869 #ifdef CPU_CLOCK_CHECKING
870 //We know it's stopped, so we can get away with this...
874 uint64_t clock = GetCurrentV65C02Clock();
875 //totalCPU += (uint32_t)(clock - lastClock);
877 printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
884 // This is the problem: If you set the interval to 16, it runs faster than
885 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
886 // have it do 16 for one frame, then 17 for two others. Then it should average
887 // out to 1/60s per frame every 3 frames.
888 frameCount = (frameCount + 1) % 3;
889 uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
891 // Wait for next frame...
892 while (SDL_GetTicks() - startTicks < waitFrameTime)
895 startTicks = SDL_GetTicks();
897 uint64_t cpuCycles = GetCurrentV65C02Clock();
898 uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
899 WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
900 lastCPUCycles = cpuCycles;
903 //let's wait, then signal...
904 //works longer, but then still falls behind...
905 #ifdef THREADED_65C02
907 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
912 static void BlinkTimer(void)
915 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 sec intervals
920 Next problem is this: How to have events occur and synchronize with the rest
923 o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
924 remainder CPU cycles over...)
926 One way would be to use a fractional accumulator, then subtract 1 every
927 time it overflows. Like so:
933 Execute6808(&soundCPU, time);
934 overflow += 0.289115646;