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 SDL_SemWait(mainSem);//should lock until CPU thread is waiting...
391 WriteLog("Main: SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up\n");
392 SDL_CondSignal(cpuCond);//thread is probably asleep, wake it up
393 WriteLog("Main: SDL_WaitThread(cpuThread, NULL);\n");
394 SDL_WaitThread(cpuThread, NULL);
395 //nowok:SDL_WaitThread(CPUThreadFunc, NULL);
396 WriteLog("Main: SDL_DestroyCond(cpuCond);\n");
397 SDL_DestroyCond(cpuCond);
399 SDL_DestroySemaphore(mainSem);
401 if (settings.autoStateSaving)
403 // Save state here...
404 SaveApple2State(settings.autoStatePath);
406 floppyDrive.SaveImage(0);
407 floppyDrive.SaveImage(1);
423 -----------------------
424 space $A0 $A0 $A0 $A0 No xlation
425 RETURN $8D $8D $8D $8D No xlation
426 0 $B0 $B0 $B0 $B0 Need to screen shift+0 (?)
427 1! $B1 $B1 $A1 $A1 No xlation
428 2" $B2 $B2 $A2 $A2 No xlation
429 3# $B3 $B3 $A3 $A3 No xlation
430 4$ $B4 $B4 $A4 $A4 No xlation
431 5% $B5 $B5 $A5 $A5 No xlation
432 6& $B6 $B6 $A6 $A6 No xlation
433 7' $B7 $B7 $A7 $A7 No xlation
434 8( $B8 $B8 $A8 $A8 No xlation
435 9) $B9 $B9 $A9 $A9 No xlation
436 :* $BA $BA $AA $AA No xlation
437 ;+ $BB $BB $AB $AB No xlation
438 ,< $AC $AC $BC $BC No xlation
439 -= $AD $AD $BD $BD No xlation
440 .> $AE $AE $BE $BE No xlation
441 /? $AF $AF $BF $BF No xlation
454 M $CD $8D $DD $9D -> ODD
455 N^ $CE $8E $DE $9E -> ODD
457 P@ $D0 $90 $C0 $80 Need to xlate CTL+SHFT+P & SHFT+P (?)
470 ESC $9B $9B $9B $9B No xlation
473 //static uint64_t lastCPUCycles = 0;
474 static uint32_t frameCount = 0;
475 static void FrameCallback(void)
479 while (SDL_PollEvent(&event))
483 // Problem with using SDL_TEXTINPUT is that it causes key delay. :-/
486 //Need to do some key translation here, and screen out non-apple keys as well...
487 //(really, could do it all in SDL_KEYDOWN, would just have to get symbols &
488 // everything else done separately. this is slightly easier. :-P)
489 // if (event.key.keysym.sym == SDLK_TAB) // Prelim key screening...
490 if (event.edit.text[0] == '\t') // Prelim key screening...
493 lastKeyPressed = event.edit.text[0];
496 //kludge: should have a caps lock thingy here...
497 //or all uppercase for ][+...
498 // if (lastKeyPressed >= 'a' && lastKeyPressed <='z')
499 // lastKeyPressed &= 0xDF; // Convert to upper case...
504 // Use ALT+Q to exit, as well as the usual window decoration method
505 if (event.key.keysym.sym == SDLK_q && (event.key.keysym.mod & KMOD_ALT))
508 // CTRL+RESET key emulation (mapped to CTRL+`)
509 // This doesn't work...
510 // if (event.key.keysym.sym == SDLK_BREAK && (event.key.keysym.mod & KMOD_CTRL))
511 // if (event.key.keysym.sym == SDLK_PAUSE && (event.key.keysym.mod & KMOD_CTRL))
512 if (event.key.keysym.sym == SDLK_BACKQUOTE && (event.key.keysym.mod & KMOD_CTRL))
514 //NOTE that this shouldn't take place until the key is lifted... !!! FIX !!!
515 //ALSO it seems to leave the machine in an inconsistent state vis-a-vis the language card...
516 mainCPU.cpuFlags |= V65C02_ASSERT_LINE_RESET;
520 if (event.key.keysym.sym == SDLK_RIGHT)
521 lastKeyPressed = 0x15, keyDown = true;
522 else if (event.key.keysym.sym == SDLK_LEFT)
523 lastKeyPressed = 0x08, keyDown = true;
524 else if (event.key.keysym.sym == SDLK_UP)
525 lastKeyPressed = 0x0B, keyDown = true;
526 else if (event.key.keysym.sym == SDLK_DOWN)
527 lastKeyPressed = 0x0A, keyDown = true;
528 else if (event.key.keysym.sym == SDLK_RETURN)
529 lastKeyPressed = 0x0D, keyDown = true;
530 else if (event.key.keysym.sym == SDLK_ESCAPE)
531 lastKeyPressed = 0x1B, keyDown = true;
532 else if (event.key.keysym.sym == SDLK_BACKSPACE)
533 lastKeyPressed = 0x7F, keyDown = true;
535 // Fix CTRL+key combo...
536 if (event.key.keysym.mod & KMOD_CTRL)
538 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
540 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 1;
542 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
548 // Fix SHIFT+key combo...
549 if (event.key.keysym.mod & KMOD_SHIFT)
551 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
553 lastKeyPressed = (event.key.keysym.sym - SDLK_a) + 0x41;
555 //printf("Key combo pressed: CTRL+%c\n", lastKeyPressed + 0x40);
558 else if (event.key.keysym.sym == SDLK_1)
560 lastKeyPressed = '!';
564 else if (event.key.keysym.sym == SDLK_2)
566 lastKeyPressed = '@';
570 else if (event.key.keysym.sym == SDLK_3)
572 lastKeyPressed = '#';
576 else if (event.key.keysym.sym == SDLK_3)
578 lastKeyPressed = '#';
582 else if (event.key.keysym.sym == SDLK_4)
584 lastKeyPressed = '$';
588 else if (event.key.keysym.sym == SDLK_5)
590 lastKeyPressed = '%';
594 else if (event.key.keysym.sym == SDLK_6)
596 lastKeyPressed = '^';
600 else if (event.key.keysym.sym == SDLK_7)
602 lastKeyPressed = '&';
606 else if (event.key.keysym.sym == SDLK_8)
608 lastKeyPressed = '*';
612 else if (event.key.keysym.sym == SDLK_9)
614 lastKeyPressed = '(';
618 else if (event.key.keysym.sym == SDLK_0)
620 lastKeyPressed = ')';
624 else if (event.key.keysym.sym == SDLK_MINUS)
626 lastKeyPressed = '_';
630 else if (event.key.keysym.sym == SDLK_EQUALS)
632 lastKeyPressed = '+';
636 else if (event.key.keysym.sym == SDLK_LEFTBRACKET)
638 lastKeyPressed = '{';
642 else if (event.key.keysym.sym == SDLK_RIGHTBRACKET)
644 lastKeyPressed = '}';
648 else if (event.key.keysym.sym == SDLK_BACKSLASH)
650 lastKeyPressed = '|';
654 else if (event.key.keysym.sym == SDLK_SEMICOLON)
656 lastKeyPressed = ':';
660 else if (event.key.keysym.sym == SDLK_QUOTE)
662 lastKeyPressed = '"';
666 else if (event.key.keysym.sym == SDLK_COMMA)
668 lastKeyPressed = '<';
672 else if (event.key.keysym.sym == SDLK_PERIOD)
674 lastKeyPressed = '>';
678 else if (event.key.keysym.sym == SDLK_SLASH)
680 lastKeyPressed = '?';
684 else if (event.key.keysym.sym == SDLK_BACKQUOTE)
686 lastKeyPressed = '~';
694 if (event.key.keysym.sym >= SDLK_SPACE && event.key.keysym.sym <= SDLK_z)
696 lastKeyPressed = event.key.keysym.sym;
699 // Check for Caps Lock key...
700 if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z && capsLock)
701 lastKeyPressed -= 0x20;
706 if (event.key.keysym.sym == SDLK_PAUSE)
708 pauseMode = !pauseMode;
713 SpawnMessage("*** PAUSED ***");
718 SpawnMessage("*** RESUME ***");
722 // Paddle buttons 0 & 1
723 if (event.key.keysym.sym == SDLK_INSERT)
724 openAppleDown = true;
725 if (event.key.keysym.sym == SDLK_PAGEUP)
726 closedAppleDown = true;
728 if (event.key.keysym.sym == SDLK_F11)
729 dumpDis = !dumpDis; // Toggle the disassembly process
731 /*else if (event.key.keysym.sym == SDLK_F9)
733 floppyDrive.CreateBlankImage(0);
734 // SpawnMessage("Image cleared...");
736 /*else if (event.key.keysym.sym == SDLK_F10)
738 floppyDrive.SwapImages();
739 // SpawnMessage("Image swapped...");
742 if (event.key.keysym.sym == SDLK_F2)// Toggle the palette
744 else if (event.key.keysym.sym == SDLK_F3)// Cycle through screen types
746 else if (event.key.keysym.sym == SDLK_F5)
749 char volStr[19] = "[****************]";
750 // volStr[GetVolume()] = 0;
751 for(int i=GetVolume(); i<16; i++)
753 SpawnMessage("Volume: %s", volStr);
755 else if (event.key.keysym.sym == SDLK_F6)
758 char volStr[19] = "[****************]";
759 // volStr[GetVolume()] = 0;
760 for(int i=GetVolume(); i<16; i++)
762 SpawnMessage("Volume: %s", volStr);
764 else if (event.key.keysym.sym == SDLK_F12)
766 if (!fullscreenDebounce)
769 fullscreenDebounce = true;
773 if (event.key.keysym.sym == SDLK_CAPSLOCK)
775 if (!capsLockDebounce)
777 capsLock = !capsLock;
778 capsLockDebounce = true;
784 if (event.key.keysym.sym == SDLK_F12)
785 fullscreenDebounce = false;
786 if (event.key.keysym.sym == SDLK_CAPSLOCK)
787 capsLockDebounce = false;
789 // Paddle buttons 0 & 1
790 if (event.key.keysym.sym == SDLK_INSERT)
791 openAppleDown = false;
792 if (event.key.keysym.sym == SDLK_PAGEUP)
793 closedAppleDown = false;
795 // if (event.key.keysym.sym >= SDLK_a && event.key.keysym.sym <= SDLK_z)
799 case SDL_MOUSEBUTTONDOWN:
800 GUI::MouseDown(event.motion.x, event.motion.y, event.motion.state);
802 case SDL_MOUSEBUTTONUP:
803 GUI::MouseUp(event.motion.x, event.motion.y, event.motion.state);
805 case SDL_MOUSEMOTION:
806 GUI::MouseMove(event.motion.x, event.motion.y, event.motion.state);
808 case SDL_WINDOWEVENT:
809 if (event.window.event == SDL_WINDOWEVENT_LEAVE)
810 GUI::MouseMove(0, 0, 0);
818 // Handle power request from the GUI
819 if (powerStateChangeRequested)
821 if (GUI::powerOnState)
825 // Unlock the CPU thread...
826 SDL_SemPost(mainSem);
831 // Should lock until CPU thread is waiting...
832 SDL_SemWait(mainSem);
837 powerStateChangeRequested = false;
840 //#warning "!!! Taking MAJOR time hit with the video frame rendering !!!"
846 RenderScreenBuffer();
847 GUI::Render(sdlRenderer);
848 SDL_RenderPresent(sdlRenderer);
849 SetCallbackTime(FrameCallback, 16666.66666667);
851 #ifdef CPU_CLOCK_CHECKING
852 //We know it's stopped, so we can get away with this...
856 uint64_t clock = GetCurrentV65C02Clock();
857 //totalCPU += (uint32_t)(clock - lastClock);
859 printf("Executed %u cycles...\n", (uint32_t)(clock - lastClock));
866 // This is the problem: If you set the interval to 16, it runs faster than
867 // 1/60s per frame. If you set it to 17, it runs slower. What we need is to
868 // have it do 16 for one frame, then 17 for two others. Then it should average
869 // out to 1/60s per frame every 3 frames.
870 frameCount = (frameCount + 1) % 3;
871 uint32_t waitFrameTime = 17 - (frameCount == 0 ? 1 : 0);
873 // Wait for next frame...
874 while (SDL_GetTicks() - startTicks < waitFrameTime)
877 startTicks = SDL_GetTicks();
879 uint64_t cpuCycles = GetCurrentV65C02Clock();
880 uint32_t cyclesBurned = (uint32_t)(cpuCycles - lastCPUCycles);
881 WriteLog("FrameCallback: used %i cycles\n", cyclesBurned);
882 lastCPUCycles = cpuCycles
885 //let's wait, then signal...
886 //works longer, but then still falls behind...
887 #ifdef THREADED_65C02
889 SDL_CondSignal(cpuCond);//OK, let the CPU go another frame...
894 static void BlinkTimer(void)
897 SetCallbackTime(BlinkTimer, 250000); // Set up blinking at 1/4 sec intervals
902 Next problem is this: How to have events occur and synchronize with the rest
905 o Have the CPU thread manage the timer mechanism? (need to have a method of carrying
906 remainder CPU cycles over...)
908 One way would be to use a fractional accumulator, then subtract 1 every
909 time it overflows. Like so:
915 Execute6808(&soundCPU, time);
916 overflow += 0.289115646;