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;
143 // This is never set to true anywhere...
145 // SDL_CondWait(cpuCond, cpuMutex);
147 // decrement mainSem...
148 #ifdef THREAD_DEBUGGING
149 WriteLog("CPU: SDL_SemWait(mainSem);\n");
151 SDL_SemWait(mainSem);
153 // There are exactly 800 slices of 21.333 cycles per frame, so it works out
155 #ifdef THREAD_DEBUGGING
156 WriteLog("CPU: Execute65C02(&mainCPU, cycles);\n");
158 for(int i=0; i<800; i++)
160 uint32_t cycles = 21;
161 overflow += 0.333333334;
169 Execute65C02(&mainCPU, cycles);
170 WriteSampleToBuffer();
172 // Dunno if this is correct (seems to be close enough)...
173 vbl = (i < 670 ? true : false);
176 #ifdef THREAD_DEBUGGING
177 WriteLog("CPU: SDL_mutexP(cpuMutex);\n");
179 SDL_mutexP(cpuMutex);
180 // increment mainSem...
181 #ifdef THREAD_DEBUGGING
182 WriteLog("CPU: SDL_SemPost(mainSem);\n");
184 SDL_SemPost(mainSem);
185 #ifdef THREAD_DEBUGGING
186 WriteLog("CPU: SDL_CondWait(cpuCond, cpuMutex);\n");
188 SDL_CondWait(cpuCond, cpuMutex);
190 #ifdef THREAD_DEBUGGING
191 WriteLog("CPU: SDL_mutexV(cpuMutex);\n");
193 SDL_mutexV(cpuMutex);
195 while (!cpuFinished);
197 SDL_DestroyMutex(cpuMutex);
206 // Request a change in the power state of the emulated Apple
208 void SetPowerState(void)
210 // powerOnState = state;
211 // pauseMode = !state;
215 //printf("Turning on...\n");
216 // Transitioning from OFF to ON
217 // mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
222 //printf("Turning off...\n");
226 powerStateChangeRequested = true;
232 // Load a file into RAM/ROM image space
234 bool LoadImg(char * filename, uint8_t * ram, int size)
236 FILE * fp = fopen(filename, "rb");
241 fread(ram, 1, size, fp);
248 static void SaveApple2State(const char * filename)
253 static bool LoadApple2State(const char * filename)
259 static void ResetApple2State(void)
262 openAppleDown = false;
263 closedAppleDown = false;
274 // SwitchLC(); // Make sure MMU is in sane state
275 //NOPE, does nothing SetupAddressMap();
278 // Without this, you can wedge the system :-/
279 memset(ram, 0, 0x10000);
280 // memset(ram2, 0, 0x10000);
281 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
285 #ifdef CPU_CLOCK_CHECKING
287 uint32_t totalCPU = 0;
288 uint64_t lastClock = 0;
293 int main(int /*argc*/, char * /*argv*/[])
295 InitLog("./apple2.log");
297 srand(time(NULL)); // Initialize RNG
300 memset(ram, 0, 0x10000);
301 memset(rom, 0, 0x10000);
302 memset(ram2, 0, 0x10000);
308 // Set up V65C02 execution context
309 memset(&mainCPU, 0, sizeof(V65C02REGS));
310 mainCPU.RdMem = AppleReadMem;
311 mainCPU.WrMem = AppleWriteMem;
312 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
314 // alternateCharset = true;
315 // if (!LoadImg(settings.BIOSPath, rom + 0xD000, 0x3000))
316 if (!LoadImg(settings.BIOSPath, rom + 0xC000, 0x4000))
318 WriteLog("Could not open file '%s'!\n", settings.BIOSPath);
322 //Load up disk image from config file (for now)...
323 floppyDrive.LoadImage(settings.diskImagePath1, 0);
324 floppyDrive.LoadImage(settings.diskImagePath2, 1);
325 // floppyDrive.LoadImage("./disks/temp.nib", 1); // Load temp .nib file into second drive...
327 WriteLog("About to initialize video...\n");
331 std::cout << "Aborting!" << std::endl;
335 GUI::Init(sdlRenderer);
337 // Have to do this *after* video init but *before* sound init...!
338 //Shouldn't be necessary since we're not doing emulation in the ISR...
339 if (settings.autoStateSaving)
341 // Load last state from file...
342 if (!LoadApple2State(settings.autoStatePath))
343 WriteLog("Unable to use Apple2 state file \"%s\"!\n", settings.autoStatePath);
346 WriteLog("About to initialize audio...\n");
348 SetupBlurTable(); // Set up the color TV emulation blur table
349 running = true; // Set running status...
350 InitializeEventList(); // Clear the event list before we use it...
351 SetCallbackTime(FrameCallback, 16666.66666667); // Set frame to fire at 1/60 s interval
352 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 s intervals
353 startTicks = SDL_GetTicks();
355 #ifdef THREADED_65C02
356 cpuCond = SDL_CreateCond();
357 mainSem = SDL_CreateSemaphore(1);
358 cpuThread = SDL_CreateThread(CPUThreadFunc, NULL, NULL);
359 //Hmm... CPU does POST (+1), wait, then WAIT (-1)
360 // SDL_sem * mainMutex = SDL_CreateMutex();
363 WriteLog("Entering main loop...\n");
367 double timeToNextEvent = GetTimeToNextEvent();
368 #ifndef THREADED_65C02
369 Execute65C02(&mainCPU, USEC_TO_M6502_CYCLES(timeToNextEvent));
372 #ifdef CPU_CLOCK_CHECKING
373 #ifndef THREADED_65C02
374 totalCPU += USEC_TO_M6502_CYCLES(timeToNextEvent);
380 #ifdef THREADED_65C02
381 WriteLog("Main: cpuFinished = true;\n");
383 //#warning "If sound thread is behind, CPU thread will never wake up... !!! FIX !!!" [DONE]
384 //What to do? How do you know when the CPU is sleeping???
385 //USE A CONDITIONAL!!! OF COURSE!!!!!!11!11!11!!!1!
386 //Nope, use a semaphore...
387 WriteLog("Main: SDL_SemWait(mainSem);\n");
388 // Only do this if NOT in power off/emulation paused mode!
390 // Should lock until CPU thread is waiting...
391 SDL_SemWait(mainSem);
394 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
395 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
396 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
397 SDL_WaitThread(cpuThread, NULL);
398 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
399 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
400 SDL_DestroyCond(cpuCond);
401 SDL_DestroySemaphore(mainSem);
403 if (settings.autoStateSaving)
405 // Save state here...
406 SaveApple2State(settings.autoStatePath);
409 floppyDrive.SaveImage(0);
410 floppyDrive.SaveImage(1);
426 -----------------------
427 space $A0 $A0 $A0 $A0 No xlation
428 RETURN $8D $8D $8D $8D No xlation
429 0 $B0 $B0 $B0 $B0 Need to screen shift+0 (?)
430 1! $B1 $B1 $A1 $A1 No xlation
431 2" $B2 $B2 $A2 $A2 No xlation
432 3# $B3 $B3 $A3 $A3 No xlation
433 4$ $B4 $B4 $A4 $A4 No xlation
434 5% $B5 $B5 $A5 $A5 No xlation
435 6& $B6 $B6 $A6 $A6 No xlation
436 7' $B7 $B7 $A7 $A7 No xlation
437 8( $B8 $B8 $A8 $A8 No xlation
438 9) $B9 $B9 $A9 $A9 No xlation
439 :* $BA $BA $AA $AA No xlation
440 ;+ $BB $BB $AB $AB No xlation
441 ,< $AC $AC $BC $BC No xlation
442 -= $AD $AD $BD $BD No xlation
443 .> $AE $AE $BE $BE No xlation
444 /? $AF $AF $BF $BF No xlation
457 M $CD $8D $DD $9D -> ODD
458 N^ $CE $8E $DE $9E -> ODD
460 P@ $D0 $90 $C0 $80 Need to xlate CTL+SHFT+P & SHFT+P (?)
473 ESC $9B $9B $9B $9B No xlation
476 //static uint64_t lastCPUCycles = 0;
477 static uint32_t frameCount = 0;
478 static void FrameCallback(void)
482 while (SDL_PollEvent(&event))
486 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
489 //Need to do some key translation here, and screen out non-apple keys as well...
490 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
491 // everything else done separately. this is slightly easier. :-P)
492 // if (event.key.keysym.sym == SDLK_TAB) // Prelim key screening...
493 if (event.edit.text[0] == '\t') // Prelim key screening...
496 lastKeyPressed = event.edit.text[0];
499 //kludge: should have a caps lock thingy here...
500 //or all uppercase for ][+...
501 // if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
502 // lastKeyPressed &= 0xDF; // Convert to upper case...
507 // Use ALT+Q to exit, as well as the usual window decoration method
508 if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
511 // CTRL+RESET key emulation (mapped to CTRL+`)
512 // This doesn't work...
513 // if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
514 // if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
515 if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
517 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
518 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
519 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
523 if (event.key.keysym.sym == SDLK_RIGHT)
524 lastKeyPressed = 0x15, keyDown = true;
525 else if (event.key.keysym.sym == SDLK_LEFT)
526 lastKeyPressed = 0x08, keyDown = true;
527 else if (event.key.keysym.sym == SDLK_UP)
528 lastKeyPressed = 0x0B, keyDown = true;
529 else if (event.key.keysym.sym == SDLK_DOWN)
530 lastKeyPressed = 0x0A, keyDown = true;
531 else if (event.key.keysym.sym == SDLK_RETURN)
532 lastKeyPressed = 0x0D, keyDown = true;
533 else if (event.key.keysym.sym == SDLK_ESCAPE)
534 lastKeyPressed = 0x1B, keyDown = true;
535 else if (event.key.keysym.sym == SDLK_BACKSPACE)
536 lastKeyPressed = 0x7F, keyDown = true;
538 // Fix CTRL+key combo...
539 if (event.key.keysym.mod & KMOD_CTRL)
541 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
543 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
545 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
551 // Fix SHIFT+key combo...
552 if (event.key.keysym.mod & KMOD_SHIFT)
554 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
556 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
558 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
561 else if (event.key.keysym.sym == SDLK_1)
563 lastKeyPressed = '!';
567 else if (event.key.keysym.sym == SDLK_2)
569 lastKeyPressed = '@';
573 else if (event.key.keysym.sym == SDLK_3)
575 lastKeyPressed = '#';
579 else if (event.key.keysym.sym == SDLK_3)
581 lastKeyPressed = '#';
585 else if (event.key.keysym.sym == SDLK_4)
587 lastKeyPressed = '$';
591 else if (event.key.keysym.sym == SDLK_5)
593 lastKeyPressed = '%';
597 else if (event.key.keysym.sym == SDLK_6)
599 lastKeyPressed = '^';
603 else if (event.key.keysym.sym == SDLK_7)
605 lastKeyPressed = '&';
609 else if (event.key.keysym.sym == SDLK_8)
611 lastKeyPressed = '*';
615 else if (event.key.keysym.sym == SDLK_9)
617 lastKeyPressed = '(';
621 else if (event.key.keysym.sym == SDLK_0)
623 lastKeyPressed = ')';
627 else if (event.key.keysym.sym == SDLK_MINUS)
629 lastKeyPressed = '_';
633 else if (event.key.keysym.sym == SDLK_EQUALS)
635 lastKeyPressed = '+';
639 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
641 lastKeyPressed = '{';
645 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
647 lastKeyPressed = '}';
651 else if (event.key.keysym.sym == SDLK_BACKSLASH)
653 lastKeyPressed = '|';
657 else if (event.key.keysym.sym == SDLK_SEMICOLON)
659 lastKeyPressed = ':';
663 else if (event.key.keysym.sym == SDLK_QUOTE)
665 lastKeyPressed = '"';
669 else if (event.key.keysym.sym == SDLK_COMMA)
671 lastKeyPressed = '<';
675 else if (event.key.keysym.sym == SDLK_PERIOD)
677 lastKeyPressed = '>';
681 else if (event.key.keysym.sym == SDLK_SLASH)
683 lastKeyPressed = '?';
687 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
689 lastKeyPressed = '~';
697 if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
699 lastKeyPressed = event.key.keysym.sym;
702 // Check for Caps Lock key...
703 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
704 lastKeyPressed -= 0x20;
709 if (event.key.keysym.sym == SDLK_PAUSE)
711 pauseMode = !pauseMode;
716 SpawnMessage("*** PAUSED ***");
721 SpawnMessage("*** RESUME ***");
725 // Paddle buttons 0 & 1
726 if (event.key.keysym.sym == SDLK_INSERT)
727 openAppleDown = true;
728 if (event.key.keysym.sym == SDLK_PAGEUP)
729 closedAppleDown = true;
731 if (event.key.keysym.sym == SDLK_F11)
732 dumpDis = !dumpDis; // Toggle the disassembly process
734 /*else if (event.key.keysym.sym == SDLK_F9)
736 floppyDrive.CreateBlankImage(0);
737 // SpawnMessage("Image cleared...");
739 /*else if (event.key.keysym.sym == SDLK_F10)
741 floppyDrive.SwapImages();
742 // SpawnMessage("Image swapped...");
745 if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
747 else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
749 else if (event.key.keysym.sym == SDLK_F5)
752 char volStr[19] = "[****************]";
753 // volStr[GetVolume()] = 0;
754 for(int i=GetVolume(); i<16; i++)
756 SpawnMessage("Volume: %s", volStr);
758 else if (event.key.keysym.sym == SDLK_F6)
761 char volStr[19] = "[****************]";
762 // volStr[GetVolume()] = 0;
763 for(int i=GetVolume(); i<16; i++)
765 SpawnMessage("Volume: %s", volStr);
767 else if (event.key.keysym.sym == SDLK_F12)
769 if (!fullscreenDebounce)
772 fullscreenDebounce = true;
776 if (event.key.keysym.sym == SDLK_CAPSLOCK)
778 if (!capsLockDebounce)
780 capsLock = !capsLock;
781 capsLockDebounce = true;
787 if (event.key.keysym.sym == SDLK_F12)
788 fullscreenDebounce = false;
789 if (event.key.keysym.sym == SDLK_CAPSLOCK)
790 capsLockDebounce = false;
792 // Paddle buttons 0 & 1
793 if (event.key.keysym.sym == SDLK_INSERT)
794 openAppleDown = false;
795 if (event.key.keysym.sym == SDLK_PAGEUP)
796 closedAppleDown = false;
798 // if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
802 case SDL_MOUSEBUTTONDOWN:
803 GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
805 case SDL_MOUSEBUTTONUP:
806 GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
808 case SDL_MOUSEMOTION:
809 GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
811 case SDL_WINDOWEVENT:
812 if (event.window.event == SDL_WINDOWEVENT_LEAVE)
813 GUI::MouseMove(0, 0, 0);
821 // Handle power request from the GUI
822 if (powerStateChangeRequested)
824 if (GUI::powerOnState)
828 // Unlock the CPU thread...
829 SDL_SemPost(mainSem);
834 // Should lock until CPU thread is waiting...
835 SDL_SemWait(mainSem);
840 powerStateChangeRequested = false;
843 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
849 RenderScreenBuffer();
850 GUI::Render(sdlRenderer);
851 SDL_RenderPresent(sdlRenderer);
852 SetCallbackTime(FrameCallback, 16666.66666667);
854 #ifdef CPU_CLOCK_CHECKING
855 //We know it's stopped, so we can get away with this...
859 uint64_t clock = GetCurrentV65C02Clock();
860 //totalCPU += (uint32_t)(clock - lastClock);
862 printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
869 // This is the problem: If you set the interval to 16, it runs faster than
870 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
871 // have it do 16 for one frame, then 17 for two others. Then it should average
872 // out to 1/60s per frame every 3 frames.
873 frameCount = (frameCount + 1) % 3;
874 uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
876 // Wait for next frame...
877 while (SDL_GetTicks() - startTicks < waitFrameTime)
880 startTicks = SDL_GetTicks();
882 uint64_t cpuCycles = GetCurrentV65C02Clock();
883 uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
884 WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
885 lastCPUCycles = cpuCycles
888 //let's wait, then signal...
889 //works longer, but then still falls behind...
890 #ifdef THREADED_65C02
892 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
897 static void BlinkTimer(void)
900 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 sec intervals
905 Next problem is this: How to have events occur and synchronize with the rest
908 o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
909 remainder CPU cycles over...)
911 One way would be to use a fractional accumulator, then subtract 1 every
912 time it overflows. Like so:
918 Execute6808(&soundCPU, time);
919 overflow += 0.289115646;