
Sign up to save your podcasts
Or


EasyAsm. Dan’s MEGA65 Digest for August 2024.
There’s tons of new stuff for you to download and try this month! kibo has launched a new implementation of a classic graphic adventure game engine capable of playing Maniac Mansion. The group Megastyle has released several new MEGA65 titles. And I’m launching a project of my own: an on-device assembly language programming tool for the MEGA65, called EasyAsm.
Much to discuss, let’s get started!
Maniac Mansion, running on a MEGA65 with kibo’s SCUMM v2 player.
You can now play the LucasArts graphic adventure-comedy game Maniac Mansion directly on your MEGA65!
kibo made a new implementation of the SCUMM v2 game engine for the MEGA65 capable of playing the classic game, which he calls “MegaSPUTM.” This hugely impressive project uses the game data files from the Amiga version, and supports full color graphics, digitized sound, and multiple input devices.
To play Maniac Mansion, you need to acquire the original game data files. If you own the disks, you can use Amiga disk management tools to extract the .LFL files. MegaSPUTM works with both the English and German versions of the data files.
The full procedure takes a few minutes. I got it up and running like so:
Now on the MEGA65, MOUNT and BOOT the mm1.d81 disk image. Crank those speakers, and use a joystick or a mouse!
The original Maniac Mansion game included a printed booklet entitled “Nuke’m Alarms Owner’s Disarmament Quick Reference Guide,” which was needed early in the game. Similar to SCUMM VM and Disney’s own re-release of Maniac Mansion, this is not needed when playing the game with MegaSPUTM.
C programmers, don’t miss the source code, which is chock full of examples of how to do common and interesting things on the MEGA65 in C.
kibo’s original Maniac Mansion game disks, with which his engine was tested.
Mega Invaders, from Megastyle.
The group Megastyle has not one, not two, but three releases for the MEGA65 this month!
Mega Invaders (itch.io link), an homage to Space Invaders, is a MEGA65 original with all of the nostalgic arcade game graphics and sounds you crave. Be sure to switch to PAL video mode before running the game. Joystick in port 2.
Omega Race (itch.io link) is a direct port of the VIC-20 space war game to the MEGA65. Nearly all of the VIC-20 code is intact, with only small patches required to get it to run.
In Skramble, also a VIC-20 port, you fly over a landscape, destroying enemies. Check out the blog article about the original game for the impressive technical details of how an unexpanded VIC could render such large levels.
Don’t miss all the great C64 and Amiga titles in Megastyle’s catalog. Their Empire Strikes Back remake is one of my all-time C64 faves.
Snake65, by piramania.
Snake65 by piramania is a modern take on a classic. It features six levels of challenging snake gameplay and charming music, and is written entirely in BASIC 65. Use W, A, S, and D on the keyboard as controls.
Mondrian Simulator, by Drex.
Mondrian Simulator, by Drex, is a MEGA65 demo that generates artwork in the style of abstract artist Piet Mondrian. Press S to start a meditative slideshow.
The MEGA65 project includes a collection of command-line tools for development and testing, using a JTAG adapter to remotely control a MEGA65 from a PC. These tools have recently acquired new features for transferring files, ROMs, and programs over Ethernet, as well as a revised tool for core management. The M65Connect desktop application uses these tools behind the scenes, and I use these tools regularly as part of a cross-development workflow.
You can now download a formal release package of the latest command-line toolkit, version 1.0. Get it for Windows, macOS, and Linux. The tools in this package:
Mac users, remember to remove the “quarantine” attribute of the tools before using them: xattr -d com.apple.quarantine m65.osx
Looking for alternate cores available for the MEGA65? Boris Schneider-Johne has taken over maintaining the cores list from sy2002, and it now has an easy-to-remember address. Visit cores.mega65.org to be redirected to the new list. Thanks to Boris for preparing and maintaining this documentation!
MEGA65 booth display banner, draped over my couch.
A quick update on those September conferences in the USA: I still plan to be at the Vintage Computer Festival Midwest, September 7-8 in Schaumburg, Illinois. For the first time in the show’s history, VCFMW received more talk proposals than available slots, and my proposal was not selected this year. I’m grateful that they have a presentation track at all, with a full-time volunteer staff to make quality recordings for YouTube. I have confirmed that we’ll have a table—and we might even have a real Commodore 65 next to the MEGA65!
I splurged on getting some fun booth display items printed professionally, something I’ve always wanted to try. The cloth banner and table signage turned out very nicely. I also placed a bulk order of 45GS02 CPU quick reference mousepads.
I, my MEGA65, and my mousepads will also be at the Portland Retro Gaming Expo, September 28-29 in Portland, Oregon. Come say hi, if you can!
EasyAsm is a new assembly language programming tool for the MEGA65. EasyAsm runs entirely on the computer, with no need for a separate PC. It is designed to work with the existing MEGA65 environment, to give you as much control and understanding of the computer as possible, and to take advantage of the MEGA65’s existing programming workflow. EasyAsm provides a powerful subset of the syntax and features of the Acme cross-assembler, so that you can use it with the assembly language programming examples in the documentation and in this Digest, as well as for larger programs.
I was inspired to write EasyAsm while playing with vintage on-device assemblers for the Commodore 64. Many of these used the C64’s built-in BASIC line editor for entering assembly language source code, giving the programmer a familiar environment for managing code without the overhead of a proprietary text editor application or file management system. I realized that not only was this possible on the MEGA65, the MEGA65 could do it better and more intuitively thanks to its powerful memory management architecture, and a little-known feature of BASIC 65: Edit mode.
Save your work to disk, early and often.
Writing a program for a microcomputer using the microcomputer itself comes with the inherent risk that a bug in your program will interfere with your programming environment. EasyAsm preserves your source code in memory while you are testing your program, but this cannot be guaranteed to work if the program does something unexpected.
By design, EasyAsm does not force you to save your work to disk before testing your program. Please remember to do this yourself.
With this announcement, I am releasing the first version of EasyAsm, which I’m calling “version 0.1.” I have tested it to the best of my ability, but it may still have bugs, including bugs that may lose data. If you find any bugs, please report them!
To start an EasyAsm session, mount and boot the EASYASM.D81 disk image:
This loads EasyAsm into memory, then returns to a blinking cursor. This is still your usual command prompt, but something is different: instead of the cursor blinking below the word READY, it blinks below the word OK. This is how you know the MEGA65 is in Edit mode.
Try entering the following program at the OK prompt. To enter the blank line on line 20, type 20 then press Shift + Space, then press Return.
Type LIST to see the listing.
Before doing anything else, save this source file to disk:
Next, press the Help key to open the EasyAsm menu.
Select option #1: Assemble and Test. (Press the 1 key.) EasyAsm assembles the program, then runs it. In this case, the program you entered does two things: it changes the color of the border (inc $d020), then ends the program (rts).
Type LIST again. The source code is in memory, and you can continue to make changes to the program.
Let’s make a small improvement. The register at hexadecimal address $D020 controls the border color, but this is not obvious from the program listing. It’d be better to assign a label to this value, so it’s easier to see what’s going on. Insert the label definition with line 25, and replace line 30:
Save the source file to disk again, this time using the @ symbol to tell DSAVE to replace the existing file.
Press Help then 1 to assemble and run the program again, to confirm that it still works.
Edit mode is very similar to the usual BASIC mode. You can type any BASIC command at the prompt, and it’ll do it right away. The main difference is that when you type a numbered line, instead of treating it as BASIC code, Edit mode treats it as PETSCII text. The DSAVE and DLOAD commands also have special behavior in Edit mode, operating on sequential files (type SEQ) instead of program files (type PRG). You can use Edit mode to write any kind of text file, like a (very) simple word processor. With EasyAsm, you can use it to write assembly language programs.
Editing works just like in BASIC. When you enter a new line, the program updates based on the line number, either inserting the line in sequence or replacing an existing line of that number. To delete a line, enter just the number, then press Return. All of the built-in tools for line editing, such as the AUTO and RENUMBER commands, are available in Edit mode. See the User’s Guide for information about these commands.
Type DIR to see the list of files on the disk. Notice that the SIMPLE.S file you created is of type SEQ.
Type NEW to clear program memory. Type LIST again to confirm that the source code is no longer in memory. Then re-load the source file:
Type LIST. The source file is the same—but the line numbers have changed!
This is a notable difference between Edit mode and BASIC mode: Edit mode does not include the line numbers when it saves the file. This is usually what you want when editing a text file, and for EasyAsm, the line numbers don’t affect how the program is assembled. However, it does mean that if you try to organize your code using groups of line numbers like you might in a large BASIC program, that organization effort is not saved between sessions.
You’ll want to get familiar with the RENUMBER command, which can insert a range of unused line numbers in the middle of your source code. For example, to renumber all lines from 1030 onward so that they start at number 2000 counting by 10s, thereby leaving a gap of available line numbers between 1030 and 2000:
EasyAsm enables Edit mode automatically when you boot the disk. To disable Edit mode and return to BASIC mode, use this command: EDIT OFF To re-enable Edit mode: EDIT ON
Remember that when you’re in BASIC mode, the prompt says “READY,” and when you’re in Edit mode, the prompt says “OK.” Take care to notice which mode you are in before typing in lines of a program, and before loading or saving source files. If you type a line of assembly language source while in BASIC mode, it will attempt to interpret the line as BASIC code, and produce incorrect results. And if you try to DSAVE the source file while in BASIC mode, it’ll save as a PRG file.
With the SIMPLE program’s source code in memory, press Help to open the EasyAsm menu. Now select option #2: Assemble to Disk. EasyAsm assembles the program, but instead of running it, it creates a new PRG file on disk, named "SIMPLE". You specify the name of the program file using the !to directive in the code.
Type DIR to see the SIMPLE program file of type PRG alongside the SIMPLE.S source file of type SEQ.
I like to use a .S suffix for source code filenames, then omit the suffix for the program name. Take care to not use the same name for the source file and the program file, so that EasyAsm does not overwrite your source file with the program file.
Let’s try out the new program. Switch back to BASIC mode, then load and run the SIMPLE program, like any other program:
The program changes the border color, then exits.
In a previous Digest, we used the Acme cross-assembler to make a program like this, using a lengthy preamble to produce a runnable program:
This would work in EasyAsm just as well: EasyAsm supports the cbm output type similar to Acme. But EasyAsm has a feature that makes this easier. When you tell the !to directive to make a runnable file, EasyAsm generates this preamble for you, including setting the program counter. In fact, this cbm listing and the runnable version you typed produce exactly the same output.
The PRG file contains your program and only your program. Give it to your friends so they too can change the colors of their borders!
When you assemble-and-test your assembly language program, EasyAsm attempts to recreate the memory layout that your program will see when it runs from disk. To do this, it first copies your source code out of program memory, so it can replace it with the assembled program for testing. EasyAsm watches for the program to exit using the rts instruction, then copies the source file back into program memory so you can continue to edit it.
That’s nice, but it’s not always possible—or even desired. A typical machine code program never exits. A broken machine code program might get stuck before it can exit.
Try entering a slightly different program:
Assemble and run the program. This program changes the border color repeatedly, in an infinite loop. It does not exit.
To interrupt this program and return to BASIC, hold Run/Stop and press Restore. The program stops, and the MEGA65 Monitor starts. Type X then press Return to exit the Monitor and return to the OK prompt.
Now type LIST.
Uh oh, there’s something wrong with the first line! EasyAsm did not see the program exit with the rts instruction, so it didn’t get a chance to restore the source file. The assembled instructions are still in program memory, having overwritten the source.
When this happens—and it will happen often—use menu option #9 to tell EasyAsm to bring back the source file. Press Help, then press 9. Type LIST again to see the restored source.
EasyAsm tries to maintain a minimal memory footprint while you are editing your source code, and while your program is running. This allows you to use all the tools at your disposal for editing, and allows your program to use most of the computer, while still retaining a useful on-device workflow.
Of course, EasyAsm has to live somewhere. This is what EasyAsm needs:
EasyAsm will refuse to assemble to addresses $1E00-$1EFF when assembling to memory, or when assembling a runnable program to disk (because the bootstrap routine may use it in the future). This restriction does not apply when assembling to disk in cbm mode.
If your program needs to use $1E00-$1EFF for its own purposes, that’s entirely fine. Just be aware that it will interfere with the EasyAsm workflow.
I’m fairly confident that I could have used this initial version of EasyAsm to write many of the programs I’ve written for the MEGA65 so far. There are a few features I want to add to really make it feel like a complete assembler:
I have a roadmap of other feature ideas that I’m considering, though they’ll take more substantial work and I want to see if anyone actually uses EasyAsm first. 😇 To me, the most important of these would be macros, a feature of Acme and other assemblers that makes programs easier to write, test, and manage. It’s possible to write substantial programs without macros—the MEGA65 ROM source has no macros in it at all—but macros are a powerful way to organize code, reuse common structures, and mitigate some of the fragility of the low-level language.
As clever as Edit mode is, it would be nice to have a more modern IDE-like text editor as an option. Personally, I’d love the experience of building a nice text editor, and I want to try it someday. I intentionally designed EasyAsm so that it could be integrated into other projects, so anyone else’s programming tools could use it.
I wrote EasyAsm from scratch in pure assembly language. I learned a lot about assembly language from this experience, and will be milking this for content writing about this in future episodes of the Digest.
I included a few sample programs on the D81 disk image based on previous Digest and blog articles. Try loading their source files and assembling them. The longest file on the disk right now is my assembly language implementation of Robot Finds Kitten, 35 KB of source that assembles in six seconds.
Want to see continued development of EasyAsm, or my other projects like this Digest? Please consider becoming a patron. Visit: ko-fi.com/dddaaannn
I hope you try EasyAsm, and I hope it makes it easier to get started with assembly language programming. Let me know how it goes!
— Dan
Let’s paint! Dan’s MEGA65 Digest for July 2024.
I feel like painting today. Let’s paint!
Oh, uh, but first…
My talk at Pacific Commodore Expo Northwest
My talk about the MEGA65 at Pacific Commodore Expo Northwest 2024, Lessons from My First Two Years with the MEGA65, is now on YouTube. My thanks to Robert Bernardo for producing the event, to Stephen Jones and SDF.org for sponsoring, and to everyone who attended. We had three MEGA65s on the floor this year, including a live unboxing of a freshly delivered unit!
Vintage Computer Festival Midwest.
I’m working up plans to be at the Vintage Computer Festival Midwest, September 7-8, 2024, at the Schaumburg Convention Center in Schaumburg, Illinois near Chicago. This large show attracts enthusiasts from all over the USA and Canada, and is a regular pilgrimage for collectors, computer clubs, YouTubers, and makers of modern retro computers and peripherals. Admission is free.
This year, I’ll be collaborating with Jim Happel (jim_64) on a MEGA65 table. I’ve also applied for a speaking slot to deliver a revised version of the “Lessons from…” talk, though those won’t be announced until next month, so, fingers crossed. 🤞
The Portland Retro Gaming Expo.
My MEGA65 and I will be at the Portland Retro Gaming Expo, September 27-29, 2024, in Portland, Oregon, USA. PRGE is one of the largest vintage video gaming shows in the Pacific Northwest, and this year they’re doing a home computing exhibition. Come for the interactive volunteer-run computer exhibits, then stay for the weekend of talks, playable arcade games, and the vendor floor. I’m not doing a talk at this one, but I’ll have my own table in the home computing area.
PRGE is a ticketed event at the Oregon Convention Center. If you’re visiting from out of town, get your hotel rooms reserved early—and make sure to leave time to explore Portland!
The Commodore 64 core for the MEGA65
The C64 core for the MEGA65, one of the best things you can do for your favorite computer, has a new update. Version 5.1 adds support for the R6 mainboard, the board in all MEGA65s being delivered this year, and can take advantage of the R6 board’s bidirectional expansion port lines for Kung Fu Flash, MSSIAH, and freezer cartridge support. This update also includes improvements for all mainboards, including the ability to share the MEGA65’s Real-Time Clock with GEOS, using an appropriate driver.
Don’t forget that the MEGA65 has a new feature that can select the C64 core automatically when a C64 cartridge is installed. If your MEGA65 was delivered this year, your firmware is already up to date with this feature. If you have an older MEGA65, you can update to the v0.96 release in “slot 0” to get this feature. See the User’s Guide, 2nd edition, for upgrade instructions.
See the C64 core release notes for details on all of the changes.
retroCombs MEGA65 User’s Guide video series.
retroCombs is producing a video series based on the MEGA65 User’s Guide, 2nd edition. Steven is going chapter by chapter, reviewing the material, and presenting it in an entertaining and easy-to-understand fashion. It’s the perfect video companion to the Guide, and a useful resource in its own right, with additional tips not mentioned in the book. Steven just released the video for chapter 4, and intends to complete the series for the entire book.
Subscribe to retroCombs to make sure you don’t miss a video!
I need a canvas to paint on. Something 320 pixels wide and 200 pixels tall is good enough to start. I just want to use the 32 built-in colors for now, so a bit depth of 5 is plenty. (Five binary bits can express up to 32 values: 2 x 2 x 2 x 2 x 2 = 32.) I’ll use screen number 0.
Yes, that’s fine. I can’t see what I’m typing now because the text is behind the painting, but I can hold Run/Stop and tap Restore to get back to the text screen.
Blank canvases are intimidating. Whenever I buy a new notebook, I always scribble nonsense on the first page, so I’m not afraid to make mistakes on the other pages. I’ll take a swipe with some white paint (color 1).
I can specify locations on the canvas using numbers, one for the distance in pixels across from the left (the X coordinate), and one for the distance down from the top (the Y coordinate). With a 320 x 200 screen, coordinate X=0 Y=0 is the top-left corner, and X=319 Y=199 is the bottom-right corner. I drew my line from the position X=20 Y=30 to X=300 Y=180.
The 32 colors of the built-in palette are listed in the MEGA65 User’s Guide, 2nd edition, appendix E. The first 16 of these are also written on the fronts of the number keys on the keyboard from 1 to 8, in two rows: colors 0 through 7 are the top row (“Blk” through “Yel”), and colors 8 through 15 are the bottom row (“Orng” through “L Gry”).
I need to switch back to the canvas to see my white line. I’ll set my screen 0 to be both the canvas I’m drawing on and the canvas I’m looking at.
I notice that typing SCREEN 0,320,200,5 again will not switch back to the existing canvas, it’ll open a new blank one. Here’s a way to clear an already-opened canvas, by filling it with color #6 (blue):
Flipping back and forth between the text screen and the canvas is a bit cumbersome. I think I’ll put all of my painting commands into a BASIC program. This way, the MEGA65 can recreate my picture by following my painting instructions, and I can save my program to a floppy disk.
I can press Run/Stop + Restore to get back to text mode, make changes to the program, and RUN it again to see the result.
If I wanted to give this program to someone else, they might enjoy being able to exit back to text mode by pressing a key. Here’s a simple way to do that:
In addition to lines, BASIC has commands for drawing dots, and drawing shapes of several kinds, both filled and unfilled. I’m just messing around, changing the numbers to see how they change the picture.
Of course, the User’s Guide has more information on how these commands work, including some additional interesting features.
Here is a simple picture I made.
Wherever there’s a number in a computer program, there could also be some computation that produces a number. This can turn math formulas, variables, and flow control structures into their own kind of computational paintbrush.
I want to try a simple grid pattern with regularly spaced lines. Instead of writing out all of the coordinates for each line, I’ll have the MEGA65 figure it out for me.
I can tell the computer how to calculate a number. Or, I can just let the computer pick a number at random. The computer can use its own imagination to paint a picture, in accordance with my instructions. (well actually computers don’t have imaginations and random numbers aren’t really random and whatever it’s fun)
BASIC 65 has some mathematical functions that can help paint interesting pictures, if I can remember enough geometry.
Those symbols on line 70 are the Greek letter pi (π), which I typed with Shift + up-arrow. In BASIC 65, this is the geometric constant pi, defined as the circumference of a circle divided by its diameter. Someone check my math.
I keep my MEGA65 on my desk and sometimes just use it as a simple calculator, typing a question mark ? followed by an arithmetic expression at the READY. prompt to get a quick answer. I wonder if I could make the MEGA65 into a graphing calculator.
Huh… That’s interesting…
I think I got the gist of this right. The first few lines define the function to be plotted, and the domain (XL to XH) and range (YL to YH) to use for the graph.
The subroutine starting on line 1000 scales a value V to screen coordinate C within value range (L,H) scaled by SC. For example, to convert an X value to a horizontal screen coordinate, I set V to the X value, L to XL, H to XH, and SC to 320 (the pixel width of the screen). The subroutine returns with C set to the horizontal screen coordinate.
I use this subroutine for every such conversion. Importantly, I need to invert the vertical coordinate that comes back from this, because math graphs go up as Y values increase, but screen coordinates go down. So PX = C, and PY = SC-C.
To keep this simple, I only draw a zero-axis if the zero is within the range/domain, and I don’t bother with tick marks. I use the CHAR command to print the range/domain values close to the zero-axis lines, if appropriate, making sure they stay on screen.
To draw the function itself, I calculate a starting point based on its value for the leftmost point on the screen, FN Y(XL), then loop over 160 evenly spaced points between XL and XH. For each iteration, I draw a line from the previous point to the next. PX/NX and PY/NY are the previous and next horizontal and vertical screen coordinates.
Real graphing calculators are pretty sophisticated. They need to be to produce something useful under all circumstances. For example, I just allow a graph that goes off the top or bottom of the screen to squash up against the edge. The LINE command doesn’t mind receiving fractional coordinates, but it will complain if I give it values outside of the screen. This could be improved by calculating exactly where the graph crosses the edge. But I’m painting here, not building something useful.
Also my sine graphs have a bit of a cowlick in some spots, for some reason. I’m guessing this is hitting up against the range limits of BASIC 65 floating point numbers. Math is hard. 🤷 Moving on…
Painting with code is fun, but this computer can do more than use hand-entered numbers or numbers derived from math and randomness. I can also write a program that changes numbers interactively based on keys I press on the keyboard. Here’s the simplest version of this idea:
This operates similarly to our Robot Finds Kitten experiment from a while back. The program maintains a cursor position in the X and Y variables. It waits for a keypress, then compares it to the PETSCII codes for the cursor keys. After it confirms the cursor position won’t leave the screen, it changes the cursor position, then draws a dot. I can move the dot around the screen, and it leaves a trail, like an Etch-a-Sketch.
I could also make this controllable with a joystick, with almost no changes:
Whoa! Uh, slow down there, partner:
This only supports four directions of movement, and actually feels like it sticks when I accidentally press the joystick in a diagonal direction. The JOY() function returns different values for diagonals. (See the User’s Guide.) This should work.
It’d be nice if I had more control over the paintbrush behavior. Maybe if it doesn’t draw unless I press the button?
JOY() returns a value 0 through 8 representing the joystick direction, plus 128 if the fire button is pressed. I’m using a bitwise AND both to test the button on its own, and to erase the button part of the value for the rest of the comparisons.
OK that works, but now I can’t really see what I’m doing. Before, it was always drawing, so I could usually see where it will draw next when I move. Now it’s only drawing when the button is pressed. I need some kind of cursor on the display that doesn’t draw into the image itself.
On Commodores, that’s what sprites are for. We covered sprites, yeah? I’m just going to use the built-in arrow sprite for now:
Remember that the sprite coordinate system is not the same as the screen coordinate system inside the border. The upper corner for a sprite is X=24, Y=50, so I need to add these values to the MOVSPR command.
That’s pretty good… Looks like there might be a bug in sprite coordinates over bitplanes. We’ll have to look into that.
That arrow cursor reminds me, I could also write this to use the mouse. This simplifies the code quite a bit because the KERNAL does its own range checking on the mouse position. My program just needs to read the mouse position, check for the button press, and draw a dot there if it is pressed. I still need to offset the mouse coordinates when I draw, this time in the other direction because X and Y are set to sprite coordinates by the RMOUSE command.
That’s neat! The dots are a bit spread apart though. I wonder if I can combine this with the technique in the graphing calculator to get a smoother line while the button is pressed.
Hmmm…
Maybe…
And what about…
Oh, here’s an idea…
That was fun!
Did I forget to include screenshots of my paintings? Ah, well. I suppose you can always just type these in and see what happens.
If you liked this one, please consider supporting the Digest with a contribution. I hope to continue making more of these, and your support goes a long way to making that possible. Visit: ko-fi.com/dddaaannn.
Happy painting! See you next month.
— Dan
KERNAL of Truth. Dan’s MEGA65 Digest for June 2024.
The Summer of MEGA65 begins! The latest delivery batch is in progress, and many preorder holders are receiving their new favorite computer.
If you’re new to this Digest, welcome! Here you’ll find news about the MEGA65 and community projects, and interactive feature articles of things you can try for yourself. Read the Digest while next to your MEGA65 and PC for the best experience.
Also, every Digest has a read-aloud audio edition. Click the audio player at the top of the email or website, or subscribe to “Dan’s MEGA65 Digest” in your podcast player. I don’t know how many people listen to it, but I enjoy making it.
In this Digest, we’ll start taking a look at the MEGA65 KERNAL, the main operating system of the computer. We’ll build off of last month’s discussion of interrupts and the CPU memory map, and try writing a MEGA65 version of a classic KERNAL extension: a desktop time-of-day clock.
Let’s get started!
MEGA65s being tested, courtesy Trenz Electronic
MEGA65 home computers are now arriving with their new owners! Trenz Electronic has begun sending out the third manufacturing batch, and will continue to fulfill pre-orders steadily. Congrats and welcome to everyone receiving a new bundle of joy!
Back in January, we were able to confirm with Trenz that this manufacturing batch will be large enough to cover all preorders placed up to that point. I continue to use that as a conservative estimate. New preorders placed in the last few months may need to wait a bit longer—or maybe not. For all we know, Trenz may be able to make quick work of another batch and get everyone taken care of. Rest assured that everyone involved in this project wants you to have a MEGA65 as soon as possible.
Of course, you can still order the MEGA65 if you haven’t already. Tell your friends!
Pacific Commodore Expo Northwest.
If you’re near Seattle, Washington, USA this month, I will be presenting the MEGA65 at the Pacific Commodore Expo Northwest, June 22-23, 2024. Admission is free. The space is cozy and filled with Commodores, and this year we have access to additional space for presentations. I’ll have my MEGA65 at a table all weekend for people to try.
I gave a talk on the MEGA65 at last year’s PaCommEx NW that went reasonably well, despite being hastily planned. Here’s hoping that I’ll have this year’s talk figured out in time. 😬
The Silent Enigma, by Gurce
The Silent Enigma is a new demo by Gurce, based on the song by Anathema. Gurce wrote the demo in BASIC 65 with the Eleven IDE, with assembly language helper routines in Mega Assembler and Acme, and an extended version of grim-fandango’s MEGAPLOT library.
The current version of the demo requires customized versions of the MEGA65 core and ROM to run on MEGA65 hardware. Gurce discovered a need for a new feature of the KERNAL for combining BASIC and machine code routines, and also discovered a core bug while getting it to work. We’re working on getting these improvements into the core platform. In the meantime, Gurce is distributing modified core and ROM files with the demo.
Check out retroComb’s video debuting The Silent Enigma, along with an interview with Gurce. And don’t miss the Eleven and assembly language source files included on the disk!
Lala the Magical (preview) for the MEGA65, by Majikeyric
Majikeyric is previewing a new game for the MEGA65! Lala the Magical (preview) is an adorable puzzle platformer, with parallax scrolling areas and tons of enemies and collectibles. It’s based on the PC DOS game by the Mojon Twins.
In the ancient ruins (province of Badajoz) lives Lala with her teacher. She is learning magic but still has a long way to go.
“Tell me about the Sky Palace” – asks Lala, and her teacher tells her again about the three Power Gems hidden inside. “I’d love to see them”, but Lala’s teacher would say no… “It’s too dangerous, and powerful magic is required to traverse the palace”.
You can play the preview with a joystick. Sound, music, and polish are in progress. I’m looking forward to the final product!
Wonder Boy, arcade core by muse
muse continues his series of arcade cores with Wonder Boy. This colorful side-runner will have you running, jumping, and even skateboarding across the landscape, collecting fruit and dodging creatures.
This core is available for both R3 (2022) and R6 (2024) MEGA65s. Be sure to use the correct version for your system, and follow the installation instructions.
Arcade cores use the MEGA65’s FPGA to fully recreate arcade game chipsets with a high degree of accuracy. Thanks to muse for his continued dedication to the arcade core library!
In computer architecture, the kernel is the center of a computer’s operating system. It manages access to hardware such as the keyboard, storage devices, and peripherals, as well as other common facilities. Programs—including the rest of the operating system—access these facilities by interacting with the kernel.
The Commodore KERNAL has played this role in Commodore 8-bit computers all the way back to the Commodore PET. The proper name, spelled with an “A” and all uppercase, is credited to an honest misspelling of the word “kernel” by developer Robert Russell that made its way into the VIC-20 programmer’s manual. While the KERNAL has evolved substantially across the line all the way up to the Commodore 65, its role in the computer and many of its key features and interfaces have remained largely the same since 1977.
In total, a Commodore computer’s operating system consists of the KERNAL, the BASIC interpreter, and the screen editor. The machine code for the operating system is etched into a ROM chip, wired to be the first thing the CPU sees when it wakes up. If the KERNAL detects that a C64-style cartridge is connected, it passes control to the cartridge. Otherwise, the KERNAL starts the screen editor, from which the user can load and run programs, type other commands, or start programming in BASIC. These three components tend to share some responsibilities, and the distinctions between them can be a bit blurry in some places, but that’s the general idea.
(There’s an interesting historical exception to the start-up procedure. The Commodore 64 was designed with support for cartridges made for the Commodore MAX, aka “Ultimax” or “VC-10.” An Ultimax cartridge connects directly to the 6510 chip’s I/O lines in a way that causes the CPU to go directly to the cartridge for its first instructions. The Ultimax did not have its own operating system: it relied on the connected cartridge for everything.)
There are three main ways the KERNAL participates in the execution of programs: KERNAL subroutine calls, the KERNAL IRQ handler, and vectors.
A program can call subroutines in the KERNAL code to perform tasks and interact with the KERNAL’s systems. Here’s a simple machine code program that writes a short message to the screen by calling the KERNAL subroutine BSOUT:
The BSOUT routine writes a single character to the current output device, which by default is the screen editor. The program sets the accumulator to the character to be written as a PETSCII code, then calls BSOUT with the JSR instruction to address $FFD2. The subroutine does all of the work to write the character, then returns.
The screen editor does a lot of work here. It maintains a text cursor—the same one that you type with at the READY prompt—that has a position on the screen, and a draw state including the text color and other attributes. When it receives a character from the program via BSOUT, the screen editor figures out what changes to make to screen and character attribute memory, moves the cursor position, and scrolls the screen up if the text runs off the bottom. (Other PETSCII codes change the draw state or cursor position in other ways.)
The screen editor is a full-fledged built-in application that behaves like an input/output terminal. Your program writes to and reads from this terminal using KERNAL subroutines.
$FFD2 is not actually the memory location of the BSOUT subroutine. Instead, the KERNAL keeps a JMP instruction at that address that goes to the actual subroutine code. Each KERNAL subroutine available to programs has one of these, in a fixed memory location called a jump table.
The jump table provides a critical layer of compatibility across different versions of the KERNAL. Your program needs an explicit address to where it can jump, to invoke the subroutine. When the KERNAL developers inevitably need to relocate the subroutine code to a different address in a new version of the operating system, they can just update the address in the jump table, and your program (and everyone else’s) will continue to run correctly because the jump table itself doesn’t move.
I recently added an appendix to the MEGA65 Compendium describing all of the KERNAL subroutines and how to use them, including jump table addresses, CPU register arguments, and example programs. Check it out, and let me know what you think!
As we covered in detail in last month’s Digest, you can program the VIC video chip to tell the CPU when its raster beam is at a given vertical location on the screen. This triggers an interrupt that causes the CPU to call a special kind of subroutine known as an interrupt handler. A typical use of the vertical raster beam interrupt is to have a chunk of program code that gets called many times per second at regular intervals. This allows the program to be organized as if it is two programs running side by side: a main program that runs normally, and a short secondary program kicked along by the interrupt.
The KERNAL uses this raster interrupt in this way. It installs an interrupt handler that pays regular attention to KERNAL subsystems while the user’s program is running. The KERNAL IRQ handler drives behaviors of the screen editor such as blinking the cursor and checking for special keyboard combinations like Mega + Shift, and behaviors of BASIC such as sprite move animations (from the MOVSPR command) and music playback (from the PLAY command).
Most programs can just take for granted that the KERNAL is doing its own thing with the raster IRQ. As we saw last month, only one IRQ handler can be installed at a time, so a program that wants to take over the IRQ handler must disable the KERNAL. But the KERNAL has a way it can share its IRQ handler with a program, so they can both play…
The KERNAL generously offers programs the ability to replace or extend some of the KERNAL’s own subroutines. In these cases, when the KERNAL wants to call one of its own subroutines, it looks up the address in a table. This table is initialized to the address of the KERNAL’s version of the subroutine, so without changes, everything behaves normally. A program can replace that address with an address of its own, so the KERNAL calls the program’s routine instead. This indirect address is called a vector, because of how it points to where the KERNAL will go.
A program can replace a KERNAL routine by re-pointing a vector, but this is a heavy task in most cases. Much more common is to extend the existing KERNAL routine with additional functionality. It works like this:
Now when the KERNAL calls the vector, control goes to the custom routine. The custom routine does some custom things, then jumps to the KERNAL’s original routine. The KERNAL routine still does the heavy lifting, and the custom routine just adds a bit of extra functionality.
This is how the KERNAL can share its IRQ handler. In the middle of the KERNAL’s IRQ handler, it calls a vector that points right back at the rest of the IRQ handler. A program can use the vector to insert its own routine that gets called as part of the KERNAL’s raster IRQ. This way, the program can combine the KERNAL IRQ and its custom IRQ routine, all running alongside its main program code.
Custom vectors remain installed when your program returns to BASIC. This allows a program to extend KERNAL behaviors used by BASIC and the screen editor. The custom IRQ vector is especially fun for this. A game written in BASIC can invoke a small amount of machine code to install an IRQ vector that plays a SID music file, and this music plays in the background while BASIC runs the rest of the game. You could even listen to SID music while writing your BASIC program, with the playback routine running alongside the screen editor!
Note that Run/Stop + Restore will reset KERNAL vectors. There are ways to prevent this, but we won’t cover them here for now. In general, this is a good thing, so you can get the system back to normal when a bug in a vector routine gets out of control.
The KERNAL keeps its vector table in its own private memory location. To read from or write to the vector table, a program calls a KERNAL subroutine that copies the table to or from the program’s memory. The full procedure for installing an extension vector routine is:
Some Commodore programmers are accustomed to reading and writing custom vector addresses directly from internal KERNAL memory, without using the VECTOR routine. For the MEGA65, it is important for programs to use the VECTOR accessor routine, and to not depend on the internal KERNAL memory address. Just like how the jump table protects your program from KERNAL subroutines jiggling around between ROM versions, the VECTOR accessor protects your program from the KERNAL vector table jiggling in the same way.
We’ll try an example below. See the entry for VECTOR in the “KERNAL Jump Table” appendix of the Compendium for a complete explanation, along with a description of the vector table.
Last month, we briefly considered the CPU memory map, just enough to understand that the KERNAL assigns itself into the $E000-$FFFF address range so it can take over the IRQ handler address stored at $FFFE-$FFFF. We ditched the KERNAL by zeroing out the memory map, so all 16-bit addresses referred to RAM in the MEGA65’s first (well, zeroth) 64K memory bank.
I will continue to avoid a complete description of the MAP register—see the “Memory” chapter of the Compendium for that—but it’s worth knowing a bit more about how the KERNAL uses MAP when integrating with it using jump table entries and vectors.
Recall that the CPU sees 64KB of memory at a time, using 16-bit addresses $0000 to $FFFF. The MEGA65 has a much larger 28-bit address space, $000.0000 to $FFF.FFFF. The memory map assigns 8KB regions of the 16-bit space to parts of the 28-bit space, and a program can reconfigure this map with the CPU instructions map and eom.
There are actually a few ways the CPU can read and write memory using full 28-bit addresses without changing the map. Crucially, the CPU can only execute machine code instructions via 16-bit addresses. In other words, to execute code somewhere in the MEGA65’s memory, the memory map must have an 8KB region mapped to that location. Instructions like JMP use the 16-bit address into the memory map to find that code.
When the MEGA65 starts, it runs BASIC, the screen editor, and the KERNAL all together to power the familiar READY prompt, blinking cursor, program line editor, and library of BASIC commands. The operating system code that powers all of this lives in bank 3. There’s a lot of it, so in this mode, most of the memory map points to bank 3. Specifically, $2000 to $BFFF refer to $3.2000 to $3.BFFF, and $E000 to $FFFF refer to $3.E000 to $3.FFFF.
If the operating system is hogging most of the 16-bit addresses, where does our program code live? The KERNAL has two tricks up its sleeve, one for BASIC, and one for machine code.
A BASIC program lives in RAM in bank 0, starting at address $0.2001. The BASIC interpreter uses the CPU’s ability to read from 28-bit addresses to access BASIC program code. The machine code for the interpreter lives in memory starting at $3.2000, and is mapped in to 16-bit addresses starting at $2000. The interpreter itself reads the BASIC code from MEGA65 RAM directly using 28-bit addresses starting at $0.2000. (You’ll get used to it.)
A typical standalone assembly language program, the kind we start with the RUN command, starts with a short BASIC program that consists of a SYS command and the address of the beginning of the machine code, such as $2014. The machine code lives right next to the BASIC starter code, in bank 0 from $0.2014 onward. The CPU can’t execute this machine code when the BASIC memory map is active. So how does SYS get to it?
The answer: SYS changes the map. In the new map, only $E000 to $FFFF are mapped to $3.E000 to $3.FFFF. This is the KERNAL, without the BASIC interpreter or the screen editor.
In both maps, the unmapped region $C000 to $DFFF connects to I/O registers and whatnot, using features of the memory system that we won’t discuss here. See the “Memory” chapter for details.
Understanding how the KERNAL uses the memory map is important when writing software that depends on the KERNAL.
If your machine code program is a game or demo that doesn’t need the KERNAL for anything, it can map out the KERNAL, take over the interrupt handlers, and run the whole show. The tradeoff is, if you want to do something like read a file from disk, you’ll have to provide your own driver routines that interface directly with hardware registers.
If your program calls KERNAL subroutines, or if it installs vectors but does not return to BASIC, the SYS map will work just fine. The KERNAL routines live in $E000 to $FFFF, and this is present in both the BASIC map and the SYS map. The KERNAL’s internal memory is in the $0000-$15FF region, in bank 0.
If your program installs vector routines then returns to BASIC, those routines must live in a region that’s accessible from the BASIC map, not just the SYS map. This means your vector routines must live within $1600 to $1EFF.
The vector routines themselves can do something fancy like disable interrupts, change the map, do something with code elsewhere in memory, then restore the map and re-enable interrupts before continuing on. See that “Memory” chapter again if you want to try to figure that out.
It’s 10 o’clock at night, the kids and spouse have gone to bed, and you finally have a bit of time to play with your MEGA65. You flip through the User’s Guide, scroll through some old Digests, and decide to try a little BASIC program. You type a few lines, run the program, get a satisfying result, then write some more code. Everything is going great. Then you look up and it’s 3 o’clock in the morning! And you have an important work meeting in five hours! If only you had a little clock display in the corner of the MEGA65’s screen, you wouldn’t be in this mess.
Let’s try extending the KERNAL with an IRQ routine that prints the current time of day in the corner of the screen. This program has two parts: an installer that sets up the IRQ vector to point to a clock printing routine, and the clock routine itself.
To keep the memory management simple, we will assemble everything starting at address $1600, leaving out the BASIC preamble of a traditional program assembled to $2001. This complicates the user instructions a bit: the user must load the program with the BLOAD command, and start it with SYS $1600. But this turns out to be somewhat convenient. If the user resets the KERNAL vectors with Run/Stop + Restore, they can re-install the clock by running SYS $1600 again.
Here’s the full listing:
Things to notice:
* = $1600 : The installer assembles to address $1600, with the IRQ routine immediately following. The assembler creates the file clock.prg with this starting address. The user can load it with BLOAD "CLOCK". Note that DLOAD "CLOCK" will not load it to the correct address and should not be used.
sta custom_irq_return+1 : The jmp $0000 instruction at the end of the custom IRQ routine assembles to three bytes, one for the jmp instruction and two for the address. The installer copies the original KERNAL IRQ vector to the address portion of this instruction.
$0ffd7110 : The Real-Time Clock can be read from hardware registers starting at $0FFD7110. There are six byte registers: seconds, minutes, hours, day-date, month, year (from the year 2000). Each value is a two-digit Binary Coded Decimal (BCD), where each 4-bit nibble represents one decimal digit. This might seem like a crazy way to store a number, but it’s quite useful when the end goal is to display it as a decimal number. To read the left digit alone, shift right four times: lsr…. To read the right digit alone, mask out the upper four bits: and #$0f.
and #$7f : The hours value needs its top bit masked out for some reason.
adcq scrnptr : The address of screen memory where the clock should be drawn is calculated by adding 72 to the starting address of screen memory, read from the VIC SCRNPTR register ($D060-$D063). This is a 28-byte pointer, and using the Q virtual register to calculate column 72 allows this to support any text screen configuration, including 80x50 mode. Of course, on a 40x25 screen, an offset of 72 would put it on the second row. This could be improved by detecting the screen width. See the SCRORG KERNAL routine for one way to do this.
sta attrmem+72,x : To make the clock stand out, it is drawn with character attributes for reverse mode and a white color. The VIC makes the first 2KB of attribute memory visible at $D800, which is sufficient to reach the top half of the screen. See the “Memory” chapter for an explanation of attribute memory. (Naturally, the “72” in this statement would also have to change to support the clock on the first row in 40-column mode.)
Here’s a pre-assembled version of the clock program if you want to play with it:
A reminder of the instructions:
Did you enjoy this Digest? Consider supporting the Digest with money! Visit: ko-fi.com/dddaaannn
Oh, and be sure to send me a photo of your MEGA65 set-up! I might feature it in a future issue.
Cheers!
— Dan
Racing the Beam. Dan’s MEGA65 Digest for May 2024.
At least once before in this Digest I’ve said something about how there’s a way to write a program to perform precisely timed actions, but the actual technique would have to wait until a future issue. In this issue, we’ll start looking into this, with a focus on synchronizing a program with a particularly useful hardware feature: the raster beam.
To do this effectively, we’ll introduce an important programming paradigm supported directly by a feature of the CPU, called interrupts. To get that to work, we’ll also take a brief look at how to uninstall the KERNAL operating system by changing the system’s memory map.
Trenz Electronic is busily assembling new MEGA65s, still on track for delivering the next batch in the next few weeks. The Discord and Forum64 board have been quieter than usual, with everyone starting new projects or resting up from previous ones. I can’t wait for the rush of new people joining and asking questions!
If you have a project in progress that you’d like to see featured in the Digest, let me know! You can also announce your project in the #announcements channel on the Discord, and upload your work in progress to Filehost for others to try. Beginners welcome! Some of the coolest stuff we’ve seen for the MEGA65 has been written in BASIC by people like you just trying things out.
Every computer contains a component that generates a clock signal, a fast and precisely timed electronic pulse that drives the digital devices in the computer. Like turning the crank of a music box, these pulses advance the internal mechanisms of each device through their various stages to perform computations, and to generate signals of their own. The clock signal also synchronizes the devices with each other, so they can communicate with one another over their electronic connections.
MEGA65 programs can take advantage of three specific devices driven by the system clock to execute code with precise timing: the CPU, the VIC video chip, and the CIA chip.
The CPU uses the clock signal to perform the machine code instructions of a program. Each instruction requires a certain number of cycles to perform, where each cycle takes a fixed amount of time based on the clock. For example, the lda #$ff instruction, which loads the byte value $ff from the program code into the accumulator register, takes two CPU cycles to complete. The cycle cost of an instruction depends on the instruction and addressing mode, but it’s typically between 1 and 6 cycles, and as many as 14 cycles for fancier operations like the 45GS02 Q-register instructions.
In its default MEGA65 mode, the MEGA65 CPU performs instructions at 40.5 million cycles per second, or 40.5 megahertz (MHz). The MEGA65 can also underclock its cycle rate to emulate a Commodore 64 (1 MHz), Commodore 128 (2 MHz), or Commodore 65 (3.5 MHz).
In theory, you can analyze the duration of a section of machine code by looking up the cycle costs of each instruction and adding them together. Commodore 64 programmers sometimes do this to optimize small sections of code, especially for advanced video effects that require precise coordination between the 1 MHz CPU and the VIC video chip. This is less necessary with the MEGA65’s 40.5 MHz CPU, which outpaces most of the signal frequencies that a program might care about.
A program can pause for a period of time by executing instructions and ignoring the results, simply to burn through cycles. This could be a series of instructions in memory, a loop with a counter, or a loop that exits when a hardware register changes. This technique is known as busy-waiting because the CPU can’t stop executing instructions: it has to twiddle its thumbs to keep busy—and also to figure out when to stop waiting and continue the program.
Try these examples of busy-waiting in BASIC:
The VIC video chip uses the system clock to generate a video signal with the precise timing expected by the display hardware. Such protocols are derived from old cathode-ray tube (CRT) displays that draw the entire screen with a beam of electrons. This raster beam sweeps across the screen in a fixed pattern of horizontal rows, or raster lines, from left to right, top to bottom. The video signal controls the intensity of the beam, and the beam leaves pixels in its wake that form the complete image. Once it reaches the bottom, the beam returns to the top of the screen, and the process repeats, many times per second.
The MEGA65 connects to modern VGA analog or HDMI digital displays. Internally, it attempts to recreate the display parameters of one of two vintage analog video modes, either PAL or NTSC, so that vintage software that depends on these parameters will run properly. The PAL video mode draws 312 raster lines 50 times per second, also known as a refresh rate of 50 Hz. NTSC draws 262 lines 60 times per second, or a refresh rate of 60 Hz. A full image consists of two interlaced sets of lines, so the actual image size and frame rate is twice as many lines and half the frequency: PAL video is 625 lines tall with a frame rate of 25 Hz.
Synchronizing a program’s behavior with the raster beam is a powerful way to perform advanced visual effects. By changing VIC control parameters at specific times during the drawing of the screen, a program can break away from some of the VIC’s numerical limitations. This is the basis for one of the most coveted of Commodore graphical techniques, called sprite multiplexing, where the VIC’s eight hardware sprites are reused in different parts of a single screen.
The Complex Interface Adapter (CIA) chip is a multi-purpose chip that manages device and serial communications, and also has a high-precision countdown timer feature. Each CIA chip contains two timers, and the MEGA65 (like the Commodore 64) has two CIA chips, each wired up a bit differently. The CIA counts pulses at a rate of 1 MHz, and your program can set a timer interval up to 65,535 of these pulses, for a delay of up to approximately 0.065 seconds. For example, to set a timer for 1/60th of a second, your program would set the timer value to 16,666.
We’ll save a complete discussion of the CIA chip for another time. For now, suffice it to say that you can use both busy-waiting and interrupt-based techniques with the CIA high-precision timers.
There are two other kinds of clock that are worth knowing about, but are less useful for high-precision timing. Each CIA chip contains a time-of-day (TOD) clock that counts tenths of seconds, seconds, minutes, and hours, up to a 24-hour period. In the Commodore 64, this clock powers the TI and TI$ BASIC variables, and is reset to midnight when the computer is switched off. The MEGA65 contains a separate battery-backed Real-Time Clock (RTC) chip that can remember the time of day and calendar date even when power is disconnected. BASIC 65 uses the RTC chip for the TI$ and DT$ variables, and it uses the CIA TOD clock for the TI variable.
Just to complete the picture, here’s a simple BASIC program that busy-waits on the TI special variable for three seconds. Notice that the TI variable’s value changes over time, even though the BASIC program itself isn’t changing it.
The VIC video chip generates a signal for the raster beam to draw onto the display, expecting the raster beam to follow a fixed pattern on a regular interval. The VIC keeps track of where the raster beam is located, and a program can access this information by reading a hardware register.
One way to synchronize a program’s behavior with the VIC’s raster beam is to busy-wait on its location. You can do this from BASIC 65, with the VSYNC command:
VSYNC pauses the BASIC program and busy-waits for the raster beam to reach a given vertical position (or raster line). The vertical position number can be between 0 and 311 in PAL video mode, or 6 and 261 in NTSC mode, where smaller numbers are further up the screen. Try adjusting the numbers on lines 20 and 40 in this example program. (Beware that there’s currently a bug that causes VSYNC to hang with a value less than 6 in NTSC mode.)
Here is an equivalent program in assembly language. Because the raster beam vertical position can be larger than 255, it takes up more than one byte of space across two register addresses. Bit 7 of register $D011 is high (1) if the raster beam is beyond line 255.
$D011/$D012 are the VIC-II raster position registers. Indeed, this example will work on a Commodore 64 as well as the MEGA65. The MEGA65’s VIC-IV is also capable of doubling the vertical resolution of the screen, a mode known as “V400,” which uses twice as many raster lines. You can see this mode in action by activating the 80x50 text mode: press Esc then 5. (Press Esc then 8 to return to 80x25 text mode.) In V400 mode, the $D011/$D012 VIC-II registers and the VSYNC command continue to use the raster position as if it were in the non-doubled mode, so the bottommost VIC-II raster position in PAL video mode is still “312,” even if V400 is active. If you want the actual mode-specific VIC-IV raster position, an 11-bit value, see the FNRASTERLSB register at $D052 (lower 8 bits) and FNRASTERMSB at $D053.0-2 (upper 3 bits).
Note that while the raster vertical position corresponds to pixel Y-coordinates, the beam starts well above the top edge of the usual background area inside the colored border—because the raster beam also draws the border! The outermost raster positions are outside of the visible area.
The ability to synchronize our program with the raster beam gives us a clever way to visualize the duration of a section of program code—using the border color! Try this:
This program allocates an array of 30 numbers, then fills it with the Fibonacci sequence. To see this in action, run the program, then type: PRINT FB(5)
We can get a sense of how fast this code runs using a combination of VSYNC and BORDER, like so:
The Fibonacci code is the same, but now it runs repeatedly in a loop. For each repetition, the program changes the border color to black, synchronizes to raster line 100, changes the border to white, then performs the Fibonacci fill. When control loops back to line 30, the border is changed back to black. In other words, the border is only white for the time it takes to fill the array. The height of the white bars in the border represent how far the raster beam travels during the fill operation. The VSYNC command makes sure this happens when the raster beam is at the same spot on the screen every time, to hold the white bars steady.
Try changing N in line 10 to another number, such as N=5 or N=40. This changes the size of the array, and therefore changes the amount of time it takes to fill it with Fibonacci numbers.
Caution: This next step causes the screen to flicker. Change line 10 to N=80, then run the program. Press Run/Stop to stop the flickering.
Why does the screen flicker when N=80? Here’s what’s happening:
Visualizing code duration using the border color is especially helpful when writing games and demos. To animate graphics smoothly, a game must update all of the screen data in less than the time it takes to draw a single screen, so the updated data is ready for the next pass of the raster beam. If the border flickers, it means the computation is taking up more than one screen’s worth of raster travel, and the programmer has some work to do.
A typical machine code program is a sequence of instructions performed one at a time by the CPU in the order the instructions are given. Branching instructions can change the flow of control to other instructions in memory, but otherwise the CPU just marches down the list.
An interrupt is an event in a computer that needs immediate attention from the software. The event can come from a peripheral, such as a key press or incoming serial communication, or an internal programmable device that isn’t the CPU, such as the VIC or CIA chip. (As a special case, an interrupt event can also be triggered directly by the software with the brk instruction, but we’ll ignore this for now.)
When an interrupt occurs, the CPU completes the current instruction (however many cycles are remaining), stops executing the program, then calls a software routine called an interrupt handler. A typical interrupt handler does a small amount of work to respond to the event, then resumes the main program where it left off.
Interrupts allow a program’s code to be organized as if it were two programs: a main program that runs as if it is unaware that special events are occurring, and a short program that runs whenever a special event occurs. Without interrupts, a program would have to be written in such a way as to check for the special condition periodically, in between doing everything else it needs to do. This can delay the program’s ability to respond to the event, or even cause it to miss the event entirely.
Here’s a quick demonstration in BASIC of what could go wrong in this scenario. The program loop does some “work” that takes time, in this case an empty loop, but imagine it’s doing something important. Once the program has a free moment, it checks to see if the fire button of the joystick in port 1 is pressed; if not, it goes and does some more work. It’s pretty difficult to get this program’s attention with the fire button. Only by holding the button down will it eventually notice and respond.
You can imagine a hypothetical computer that triggers an interrupt when the fire button is pressed, halting the “work” to respond immediately. Because interrupts are built into the hardware, only a few kinds of events are wired into the CPU interrupt system. A typical program would use one of the timing sources (VIC or CIA) to trigger an interrupt at fixed intervals many times a second, and the interrupt handler would check for things like joystick input and react accordingly. This is how the KERNAL moves sprites or plays music concurrently with a BASIC program, or blinks the cursor while waiting for keyboard input at the READY. prompt. The steady drumbeat of interrupts allows the program (or the KERNAL) to respond to user input quickly, and progress animation and music smoothly.
Custom interrupt handlers are exclusively the domain of machine code programs. While BASIC programs benefit from how the KERNAL uses interrupts, they can’t use interrupts directly. In most cases, the best a BASIC game program can do is keep the game loop logic short and fast, so it can respond to joystick input as soon as possible. So maybe don’t loop 50,000 times between checks for the fire button.
BASIC 65’s sprite COLLISION feature behaves like an interrupt handler, but it’s actually implemented by the BASIC interpreter, not the CPU’s interrupt system: the interpreter just checks for sprite collisions before executing each BASIC statement.
The 6502 family of CPUs supports two kinds of interrupt: an interrupt request (IRQ), and a non-maskable interrupt (NMI). Some events trigger IRQs, and others trigger NMIs.
The difference between IRQs and NMIs is that certain CPU operations can temporarily disable IRQs, and a program can disable and re-enable IRQs as needed, while NMIs cannot be disabled. Disabling IRQs is like putting a “Do Not Disturb” sign on a hotel room door: it says that the main program is working on something that should not be interrupted, and interrupt requests should be ignored for the time being. NMIs are more like a hotel fire alarm: they must be handled immediately, no matter what. Both kinds of interrupt are necessary for a fully functioning system, but most programs can get away with only dealing with IRQs.
The following are possible sources of IRQ interrupts in the C64 and MEGA65:
The following are possible sources of NMI interrupts in the C64 and MEGA65:
Yes, pressing the Restore key triggers the NMI handler! This is how Run/Stop + Restore works: the KERNAL’s NMI handler tests whether both keys are pressed, then resets BASIC and declines to continue the interrupted program. This works even if the program has disabled IRQs.
The CPU supports one interrupt handler for IRQs and one handler for NMIs. It’s up to the handler code to figure out the specific cause of the interrupt, and react appropriately.
The address of each interrupt handler is stored as two bytes, in little-endian order (low byte first), at a fixed 16-bit address: the IRQ handler address is stored at $FFFE-$FFFF, and the NMI handler address is stored at $FFFA-$FFFB. The MEGA65’s default memory map installs KERNAL ROM code in this location, and the KERNAL uses its own interrupt handlers, so you can’t just POKE new addresses here. One way that a program can install custom interrupt handlers is to uninstall the KERNAL, by changing the memory map.
It is possible to leave the KERNAL in place and ask it to call custom code during its own IRQ handler. We’re still formalizing and documenting KERNAL integration techniques, so this is best left alone for now when writing MEGA65 programs. This is probably the most popular KERNAL integration technique on the C64, so we’ll try to finish this soon. (Hint: use the “VECTOR” KERNAL routine.)
For the rest of this Digest, we’ll focus on the raster beam IRQ, and assume that the program will uninstall the KERNAL to install its own handler. We’ll save other interrupt types for another time.
When the CPU encounters an IRQ, it finishes the current instruction, then pushes the 16-bit address of the next instruction onto the stack (two bytes). It also pushes the CPU flags onto the stack, as a single byte. It then disables IRQs, then jumps to the address stored in the IRQ vector.
The first thing the interrupt handler needs to do is preserve any additional CPU state that might get clobbered by the rest of the handler. The main program expects everything about the CPU to be just as it left it, including the values in other registers. For example, if the handler needs to use the accumulator (and it probably does), it needs to push the previous accumulator value to the stack beforehand, and restore it afterward.
For most kinds of IRQ interrupt, the device that triggers the interrupt stays in the “interrupt” state until it is told that the interrupt is handled. The program must interact with the device via a hardware register to acknowledge the interrupt, so that it doesn’t re-trigger once the interrupt handler resumes the program. Remember that an IRQ can have multiple causes, so if your program enables more than one cause, it will need to determine the cause and handle it appropriately.
When the interrupt handler is complete, it calls the rti instruction to resume the paused program. This restores the CPU flags and next code address from the stack (thereby re-enabling interrupts), and continues where it left off. This is kind of like how jsr jumps to a subroutine and rts returns from it, with minor differences. For example, normal subroutines don’t stash and restore the CPU flags.
The CPU keeps track of whether IRQs should be handled or ignored using the “IRQs disabled” CPU status flag (I). To disable IRQs, a program calls the sei instruction (“set IRQ disabled”). To re-enable IRQs, a program calls the cli instruction (“clear IRQ disabled”). I know, this set/clear definition feels like a double-negative; just think of how interrupts being enabled is the default case (0 or clear), and being disabled is the special case (1 or set).
The CPU will automatically disable IRQs when calling either the IRQ or NMI interrupt handler, so an IRQ handler can’t re-trigger while it is executing, nor can a handler be interrupted by something else. Interrupts get re-enabled automatically when the rti instruction restores the previous status flags from the stack. It’s possible to get fancy with this, and some advanced techniques make unusual exits from the interrupt handler or manipulate the stack.
Interrupts are also disabled automatically while updating the 45GS02 memory map registers. This is important because memory map adjustments require several instructions, and interrupting these instructions could be disastrous if the incomplete memory map leaves either the interrupt handler code or handler vectors in an inconsistent state.
This is an important hint for how a program and its interrupt handlers can communicate with each other. If the main program is updating the state of the system, and it’d be bad if the interrupt handler sees the state only partially updated, the main program should disable interrupts (sei), update the state, then re-enable interrupts (cli). Remember: with interrupts enabled, the handler could be called between any two instructions, including between an lda and an sta. Modern-day programmers might compare disabling interrupts to a “global lock” on memory and CPU state, albeit a simple one.
Let’s try disabling the KERNAL and setting up our own interrupt handler. This requires a few steps.
We’re not going to cover memory mapping in detail in this issue. To learn more about it, download the latest version of The MEGA65 Compendium and check out the “Memory” chapter. For now, we just need to know a few things:
The MEGA65 KERNAL ROM code lives in the 28-bit address space from $2.0000 to $3.FFFF. While the KERNAL is running, it switches between a few memory maps to do various things. Most importantly, when interrupts are enabled, the 28-bit addresses $3.E000 to $3.FFFF are mapped to 16-bit addresses $E000 to $FFFF, which includes the IRQ and NMI vectors as well as the handler routines that they point to.
To take this over for our own purposes, we need to reset the memory map so that $E000 to $FFFF points to RAM at $0.E000 to $0.FFFF. The memory map consists of eight bytes of information. Without going into detail, we can accomplish our task by setting four of these bytes to zero. To do this, set the A, X, Y, and Z registers to zero, then use the map instruction, followed by the eom (“End Of Map”) instruction:
The map instruction transfers A, X, Y, and Z to the first four bytes of the MAP register. Simultaneously, the map instruction also disables IRQs (similar to sei). After the first map and before the eom, the program can call map a second time to set the second four bytes of the MAP register if needed, or otherwise set up any additional state needed by IRQ handlers in the new memory map. The eom instruction signifies that the MAP setting is complete, and re-enables IRQs.
The map and eom instructions are specific to the 65CE02 CPU on which the 45GS02 is based, so you’ll want to use an assembler that supports them, like Acme assembler. If your assembler of choice only supports CPUs up to the 65C02, you can use the aug instruction for map, and nop for eom. If your assembler only supports 6502 instructions, get a better assembler.
The KERNAL keeps the VIC raster interrupt active for its own purposes, so we need to either disable this or set it up the way we want. In general, it’s a best practice to disable all sources of interrupt that your program doesn’t recognize when installing custom interrupt handlers.
Let’s use the gap between map and eom to install our own interrupt handlers, and disable the KERNAL’s raster interrupt. Even though we’re not discussing NMIs for now, we need an NMI handler because we’re replacing all of the KERNAL’s handlers. (We’ll look at a more thorough way to do this another time.)
The VIC chip can trigger an IRQ when the raster beam is at a requested position. Setting this up requires two simple steps.
First, the program must tell the VIC what raster position to use. As with the BASIC 65 VSYNC command, the range of this value depends on the video mode: 0 to 311 for PAL, and 6 to 261 for NTSC. The program sets the desired location with the lower eight bits in register $D012, and the ninth bit as bit 7 of register $D011.
Astute readers may notice that this is the same register we used to read the raster position for busy-waiting! The VIC is clever enough to re-use this register location in this way: when you read the register, it returns the current raster position. When you write to the register, you set the raster interrupt position.
The second step is to set a flag that says the program wants the VIC to trigger the raster IRQ. Set bit 0 of register $d01a to 1 to enable the raster IRQ.
Within the IRQ handler, you can confirm that it was the raster IRQ that triggered the interrupt by testing bit 0 of register $D019. To acknowledge the interrupt and prevent the IRQ handler from re-triggering, write a 1 to this bit. This is another register that has unusual read and write behavior: reading it tests the IRQ trigger status, and writing a 1 to a bit “unlatches” the trigger.
I promised to limit this discussion to raster interrupts, but it won’t take more than two sentences to discuss the VIC-II’s other interrupt capabilities. The VIC can also trigger an IRQ when a sprite collides with the background, or with another sprite. To use these, simply use bits 1 and 2, respectively, of the $d019 and $d01a registers. Oh, and the VIC also uses an IRQ for managing input from a light pen, but I don’t have one of those so I can’t tell you anything about it.
As mentioned earlier, the VIC-IV uses twice as many raster lines in V400 mode as otherwise, but maintains the non-doubled raster line count in the $D011/$D012 registers. The raster vertical position IRQ uses the same value range, regardless of the V400 mode. There is not currently a way to set a more precise raster IRQ in V400 mode.
In the time that it takes the raster beam to draw a single line, a 1 MHz Commodore 64 can execute about 64 cycles worth of instructions. (Check my math: PAL draws 312 lines 50 times per second; the C64 executes 1 million CPU cycles per second; 1,000,000 / (312 x 50) = 64.1. NTSC draws 262 lines 60 times per second; 1,000,000 / (262 x 60) = 63.6.) Just eyeballing the IRQ handler I wrote above, which doesn’t even do anything useful, it looks like I’ve already spent 26 cycles. A typical C64 interrupt handler will not complete until the raster beam is on the next line.
With high-speed C64 graphics programming, if each CPU cycle represents 1/64th of a line, every cycle matters, and getting the code to synchronize with the raster beam position can be challenging. Remember how I said that when the CPU receives the interrupt request from the VIC, it finishes the current instruction before calling the handler? The current instruction could have several cycles remaining, and the raster beam will have advanced across the screen for some distance before the handler is called. Moreover, the interrupt could be happening at any time during any instruction, so the runoff is likely to vary every time. On a C64, a simple raster IRQ handler that changes the background color results in a flickering fringe at the transition point. C64 programmers can use complex techniques to synchronize the CPU with the raster beam, typically by setting a raster interrupt just before the line that is needed, then performing tests and busy-waiting for very specific amounts of time to account for minute differences between C64 models and other conditions.
The MEGA65 doesn’t have that problem. At 40.5 MHz, the MEGA65 executes approximately 2,600 cycles per raster line, or less than a pixel per CPU instruction. In most cases, the small amount of cycle slop just before the interrupt handler is called won’t impact a program. A bit of fringing can still appear if you’re changing the border color, because the border is so close to the beginning of the raster line. In this case, just be sure to change the border color as early as possible in the handler routine.
Also note that if the interrupt handler exits before the beam has left the line that caused the IRQ to trigger, the VIC won’t re-trigger the IRQ for the same line. The VIC only triggers a vertical raster interrupt at the beginning (left-most position) of the line.
If you want the raster IRQ to trigger once per frame in the same location, you can just leave the IRQ mask bit set, and leave the raster location registers alone. This is handy for simple game loops that stay in sync with the screen refresh.
Earlier, we were discussing special effects like multi-color borders and sprite multiplexing that involve changing VIC parameters at multiple raster positions. To do this with interrupts, you set the next raster position within the interrupt handler. After the handler returns, the VIC is ready to trigger it again at the new position. Of course, this means that your handler must test which position triggered the interrupt. It can do so by reading the raster position, as before.
Another option is for the interrupt handler to also update the IRQ handler vector address to point to a different routine to be called for the next raster interrupt. This avoids having to test the raster position. As long as all of the raster handlers correctly advance the raster interrupt position and handler address, you can set up distinct handlers for each raster position.
Here’s an example of using the first technique to draw the white border bar from 100 to 200:
The traditional VIC-II raster position register and corresponding IRQ trigger are based on the vertical position of the beam, how far up or down the beam is. If you’re careful to consider the video mode, you can think of this as a raster Y coordinate, in correspondence with the VIC screen coordinates.
The MEGA65’s VIC-IV has an extra trick up its sleeve: it also reports and can trigger the IRQ on the raster horizontal position, as a raster X coordinate. This works similarly to the VIC-II vertical position: you can read the X position from a register, write an X position to this register to set the IRQ trigger, and enable and acknowledge the IRQ by setting bits in other registers.
To protect backwards compatibility, this IRQ is behind a master switch for all MEGA65-specific IRQ triggers that is off by default. To unlock new MEGA65 IRQs (currently just this one), set $D07A bit 6. The X position is a 13-bit value, readable at $D050 (lower eight bits) and $D051.0-5 (upper five bits). You write the IRQ trigger position to the same register. To enable the raster X IRQ, set bit 4 of $D01A. To acknowledge the raster X IRQ in the request handler, write a 1 to bit 4 of $D019.
This IRQ will trigger whenever the raster beam reaches the requested horizontal position, once for every raster line when this is enabled. To target a specific raster X-Y coordinate, leave the horizontal IRQ disabled, trigger a vertical IRQ for the Y coordinate, then in that handler, enable the horizontal IRQ for the X coordinate and return. The next interrupt will be at the requested position on the line. Remember that the beam travels while the handler is executing, so keep it tight.
Let’s end with a musical experiment!
SID files are the Commodore community’s method of creating and preserving music designed to be played by a Commodore 64 through its SID sound chip. Perhaps surprisingly, a typical SID file isn’t just data about the musical notes to be played, like a piano roll for a player piano. Instead, it contains 6502 machine code—the player mechanism itself! (I guess the SID is the piano? You get it.)
The playback code consists of two subroutines. One subroutine initializes the SID chip, and is expected to be called once before starting the song. The other subroutine plays the actual music, and is expected to be called many times per second, with precise timing. This makes it easy for a game or demo to play the SID file simply by loading it into memory, calling the initialization routine, then calling the playback subroutine from an interrupt handler. The music plays concurrently with whatever else the program does.
The complete SID file specification has matured over multiple generations to cover many interesting cases. For our simple experiment, we can note just a few things: the file header tells us where in memory to load the file, and also provides the addresses of the initialization routine and the playback routine in memory when loaded appropriately. SID files expect a C64 memory map, so getting arbitrary SIDs to play on the MEGA65 can be tricky. (When you play a SID via M65Connect—did you know you can play SIDs via M65Connect?—it uploads a tiny player routine that runs in GO64 mode, which gets around this issue.)
Here’s an easy one to try that works with the MEGA65 memory map:
If we open Frogger.sid in a hex editor and compare it to the SID file format spec, we can see:
It seems like we should be able to load this file starting at address $5000 - $7C = $4F84, then call the subroutines at $5000 and $59F0 appropriately. Let’s forget about interrupts for a second and try this in BASIC!
This program loads the SID file such that the data region starts at $5000, calls the initialization routine, then runs the main loop in lines 30-70. The loop uses VSYNC in two ways: it makes sure that we’re calling the play routine as often as the screen updates, and it uses the border timing trick to see how long the playback routine takes to execute. If you want to use this tune in a BASIC game, the white bar tells you how much runtime is available for game logic and graphics.
Maybe this tune sounds familiar! And if you’re in PAL mode, maybe it sounds a bit too slow. If your display supports it, open the Freezer (hold Restore for one second then release), press V to switch video modes, then press F3, then re-run the program to hear the difference. The song plays as originally intended in the NTSC video mode, which updates the screen 60 times per second, and slower in the PAL video mode, at 50 times per second.
Music playing at the wrong speed is very familiar to Commodore enthusiasts sharing game software between the USA and Europe, where the two different video standards were used. Many C64 games use the raster interrupt for every aspect of their game loop including music playback, because it’s much more convenient to use a single interrupt for all timing purposes than to try to accommodate different intervals for graphics and music. One fix for this would be to use both a raster IRQ (50 Hz or 60 Hz, depending on video mode) and a CIA timer IRQ (set to 60 Hz), and write the interrupt handler to detect which device triggered the IRQ and perform either graphics or sound updates accordingly.
If you’d like to try playing this SID file from assembly language, I recommend using the feature of your assembler to include frogger.sid as binary data into your program, then have the program start by copying the data into the correct memory location. Everything else should look similar to the interrupt handling code from earlier. In a later Digest, we’ll revisit the subject of interrupts, and look at how to use the CIA chip to play music correctly in either video mode.
By this time next month, new MEGA65s may be on their way to their new homes! Huge thanks to everyone who has been reading this Digest in anticipation of future ownership. The new User’s Guide contains everything you need to get started, and don’t miss my MEGA65 Welcome Guide with photos and additional tips. Join the Discord and let us know it arrived safely, and don’t forget to register for ownership status in both the Discord and on Filehost.
Everything I do for the MEGA65 project, including this Digest, is made possible by supporters like you! If you’d like to support the Digest, visit: ko-fi.com/dddaaannn.
Happy computing!
— Dan
The Justified Ancients of Mu Mu. Dan’s MEGA65 Digest for March 2024.
[Did you know: All issues of the Digest have an audio version! Search for “Dan’s MEGA65 Digest” in your favorite podcast app, or check out the audio player at the top of each issue. — Dan]
There are two methods for making sound and music with the MEGA65, as it is currently implemented. The first method is the four SID chips, programmable devices that generate waveforms with requested parameters using analog electronic components. We took a dive into the SID chips back in—November 2022?? How long have I been doing this?? …
The MEGA65 can produce sound another way. Pulse-Code Modulation (PCM) describes a waveform as a sequence of values over time, literally the shape of the desired waveform as a series of high and low numbers, as if drawn on a graph. The computer feeds these numbers into a device called a Digital-Analog Converter (DAC) that produces the waveform in that shape, as if rapidly changing the position of a speaker membrane according to each value. The MEGA65 has four DACs, and these waveforms are mixed with the rest of the audio system to produce the stereo audio output of the computer.
With PCM, a computer can reproduce real-world sounds captured by a microphone, such as human speech or musical instruments. Today, we take this extremely for granted: modern computers generate pretty much all sound using PCM waveforms. We used to call this “digitized sound,” in contrast with “synthesized sound.” Now we just call it “sound.” While PCM gives a computer program much more control over the generated sound, the trade-off is memory: relative to the memory sizes of 1980’s computers, PCM sound data takes a huge amount of space, depending on the length and quality of the sounds.
In this issue, we’ll look at how to control the MEGA65’s DACs to play digitized sound, as well as techniques for wrangling sound data for use in your programs. As usual, we’ll spend a bit too much time nerding out on theory and file formats.
Are you ready? Here we go.
Bomb’em All, by btoschi
Bomb’em All by btoschi, an explosive action game for two to four players. Drop bombs, pick up items, and break through walls while trying to trap your opponents in the blast zone. The game supports the Four Fun joystick adapter for four joysticks, or can be played with a mix of joystick and keyboard controls.
BASIC Star Galactica, by jim_64
BASIC Star Galactica by jim_64, a space battle adventure. Destroy the Cylons and protect the fleet—and the future of humanity. Don’t miss the downloadable, printable disk label and manual.
The MEGA65 Z-code Text Adventure Collection Pack #4, edited by fredrikr
fredrikr has prepared the fourth in his series of text adventure game bundles for the MEGA65, featuring modern classics from the interactive fiction community. This pack includes a variety of games released from 1995 to 2023, all playable on the MEGA65 thanks to the Ozmoo Z-machine player. (See the Digest from October 2022 for more on Ozmoo and MEGA65 adventure gaming.)
Ghosts’n Goblins, arcade core by muse
Another arcade core from muse! In Ghosts’n Goblins (1985), you are brave knight Sir Arthur, on a quest to save the Princess Prin-Prin. Don your armor—and take care not to lose it—while fighting waves of zombies, giants, demons, and other monsters. This classic from Capcom is considered one of the best video games of all time—and one of the most difficult. As with the other arcade cores, you will need to find the game ROM online, and follow the instructions to install it.
Stranded, by Magnus Heidenborn
In Stranded, a graphical adventure game by Magnus Heidenborn, your boat has crashed and washed ashore a deserted island. Magnus wrote Stranded for the Commodore 64, specifically the modern TheC64 clone. Gurce ported it to the MEGA65, and added original music. I especially appreciate the novel keyboard-based linear travel and exploration mechanic, which works around common issues with point-and-click adventure games. Check it out!
The latest expansion board prototype, from Paul
Paul is making progress on the MEGA65 expansion board project. As we reviewed in a previous issue, this project intends to produce an internal hardware expansion that adds component video output, a Commodore user port, a tape port, and a port for the never-released 1565 external floppy drive that was originally intended for the Commodore 65. The goal is for these expansion boards to be made entirely out of printed circuit boards (PCBs) and common components with open source designs, so anyone can order and assemble one from any PCB fabricator.
The latest prototype includes a way to connect an ESP32 wireless Internet module (!), and routes a path for the optional JTAG adapter to a firmly mounted microUSB port accessible through the back of the computer. It also completes the 1565 disk drive port. Hopefully someday we’ll be able to make a modern recreation 1565 drive with a plastic case that matches the MEGA65.
Here is a visual representation of the waveform of the first few notes of “3 am Eternal” by The KLF, performed by soul singer P. P. Arnold:
Storing and replicating this waveform exactly as it was performed would require a device and a storage medium that could capture the infinitesimal changes of air pressure in the listener’s ear over time. Digital storage media is neither infinite nor infinitesimal, so we have to make some tradeoffs when digitizing audio. How can we represent this waveform as a collection of numbers, then use those numbers to reproduce an approximation of the waveform on a loudspeaker?
Pulse-code modulation describes the height of a waveform measured periodically, or sampled, over time. We can’t measure every infinitesimal point in time, so we have to choose a sample rate that says how often we take a sample. For audio, a typical sample rate is on the order of kilohertz, or thousands of times per second. A smooth curve in the original waveform is approximated by a stair-step pattern in the digitized waveform.
The sample rate for digital audio is a lot like the screen resolution of a digital image. The actual image of an object as seen by the eye could have infinitesimal detail, but to capture it and represent it on a screen, it must be digitized into pixels. The smaller and closer together the pixels, the more detail can be captured and represented. You can think of sample rate as the “horizontal resolution” of the waveform.
We can’t measure the height of each waveform sample infinitesimally either, so this too needs a digital compromise. For example, we could store each sample as 8 bits (one byte) of data. This would give us 256 possible values for the sample. If the measured sample is between two adjacent values, it gets rounded—or quantized—to the closest value. The number of storage bits per sample is the bit depth of the sample (or sample depth). You can think of bit depth as the “vertical resolution” of the waveform.
Sample depth can also be understood by analogy with digital images. Each pixel of an image is stored with a digital value that represents its color. The number of possible colors it can use is limited by the bit depth of the color value. Naturally, the more colors the computer can use for a pixel, the more accurately it can represent the original image.
Conceptually, an audio waveform is a variance in the regular air pressure of a silent room, wiggling positive and negative in a pattern until stabilizing back to zero. You can see the middle line on these waveform diagrams where this level lies. Based on this, waveform samples could be represented as a signed number, with some negative numbers and some positive numbers around a baseline of zero. Or, it could be represented as an unsigned number, where the baseline is the middle value of a range of positive numbers.
A signed 16-bit sample has a range of -32,768 to +32,767. It is usually stored as a two’s complement value, $8000 (-32,768) up to $FFFF (-1), then $0000 (0) up to $7FFF (32,767). An unsigned 8-bit sample has a range of 0 to 255, where 128 is the baseline of the waveform. It is stored simply as its byte value, $00 (0) to $FF (255). If you’re messing with sample data, you need to know both its bit depth and whether it is signed or unsigned to interpret it correctly.
Both sample rate and bit depth explain how the amount of data relates to the quality of the reproduction of the original sound. The faster we sample, the more samples we collect, and the more accurate the data is to the original sound. The higher the bit depth of the sample, the more memory is required for each sample, and the more accurate the sample is to the waveform.
Before there were large hard drives, fast Internet transmission speeds, and data compression algorithms tuned for audio, digital music could only be practically distributed on optical fixed-storage compact discs (or “CDs,” as we called them). We purchased these discs at retail establishments with names such as “Tower Records,” and ordered them from printed catalogs to be delivered to our home via postal service from Columbia House at an introductory cost of 10 discs for 1 penny. A typical audio CD stored 74 minutes of uncompressed stereo sound data, using a sample rate of 44.1 kHz and a depth of 16 bits.
We can calculate the amount of sample data on an audio CD with a simple multiplication: 74 minutes x 60 seconds per minute x 44,100 samples per second x 2 bytes per sample x one sample for each stereo channel (2) = 783,216,000 bytes, or almost 747 MiB. Old-timers may remember that a CD-ROM, which uses the same type of disc for storing computer files, has a capacity of 650 MiB. CD-ROMs use the rest of the space for error correction and addressing, so computers can find files and make sure they read them correctly. When an audio CD player reads a sample incorrectly, it just pretends nothing happened and keeps going, so it can use more space for samples.
For perspective, at CD quality, the MEGA65’s 8 megabytes of Attic RAM can contain 45 seconds of audio. As we’ll soon see, we’re actually limited to 64 kilobytes at a time, which would last us 0.35 seconds at 44.1 kHz 16-bit. We’ll need to make some tradeoffs in quality and duration to make practical use of digitized sound.
The following are the durations of 64 kilobytes of sample data at various sample rates and bit depths:
Imagine we had a way to control the speaker membrane directly from a MEGA65 program using a hardware register. What would the program have to do to play back a short digitized sound? The program would write each PCM sample to the register, and it would have to do it at a consistent rate that matches the sample rate. If the sound was digitized at 8 kHz, this program would have to write sample data to the register 8,000 times per second, at even intervals. This is entirely possible with a 40 MHz CPU, but getting the timing right would be a significant programming challenge, especially if the program does other things besides play the sound.
Thankfully, the MEGA65 can help us with this. Reading a series of values from one memory location and writing them to another is the bread and butter of the Direct Memory Access (DMA) chip, a purpose-built chip in the Commodore 65 that the development team called “DMAgic.” DMA is typically used to copy one region of memory to another location very quickly, or fill a region with a value. Normally it does this as quickly as possible. The MEGA65 has enhanced DMAgic with a mechanism for playing audio samples to the DAC at a programmable sample rate, controlled with hardware registers. Your program can even do other things while the sample is playing: playback happens concurrently with program execution.
Because sample timing is managed for us by audio DMA, we don’t need to worry about our program being fast or accurately timed. You can even use audio DMA from BASIC!
For audio DMA to work its “DMAgic,” a few things must be true:
At first glance, this seems a bit limiting, but it’s actually quite powerful with a few tricks. For example, while sample data must be in the first 384 KB of main memory during playback, your program can store its samples in the 8 MB of Attic RAM, then use a DMA copy operation to install it in main memory to be played.
4-bit samples are stored in an interesting way: the DMA must advance through memory by at least one byte per sample, so 4-bit samples use either the top four bits or the bottom four bits of each byte, and you tell audio DMA which bits to use when you play the sound. This means you can have two 4-bit sounds stored in the same bytes, one in the top bits and another in the bottom bits.
When you play a sound, you can tell audio DMA to stop at the end, or loop back to the beginning automatically and continue playing. Looping is great for short repeating waveforms, or long repeating patterns like drum beats or atmospheric sounds.
With a bit of cleverness, you can play sample data larger than 64 KB by taking advantage of the looping feature. Your program can copy new sample data into the memory region as the sound is being played, so when the playhead loops back to the beginning, it starts playing the new data.
Your program specifies the sample rate to use the play the samples. If you want the samples to sound like the original recording, you play the samples at the rate they were digitized. You can also play the samples at a slower or faster rate to change the pitch and speed of the sample, like spinning a record player at a faster or slower speed. —Oh, uh, records were another way to distribute music before CDs, as analog waveforms etched into grooves on vinyl discs. Sounds were reproduced mechanically by vibrating a needle called a stylus, by running it across the etched groove at a steady speed. Because retro is cool, vinyl album sales have seen a rapid resurgence recently that is expected to grow in 2024, while sales of CDs have dropped in favor of online music streaming.
Before we figure out how we get recorded sound data into the MEGA65, let’s try out the audio DMA system with some made-up numbers. We’ll use BASIC here, but the procedure is the same in assembly language: we’re just writing to memory and registers. (Try porting this example to assembly language!)
To start, let’s draw a simple “sawtooth” waveform into some memory. This will just be the numbers 0 to 255 across 256 bytes of memory, which we will play looped.
Each of the four audio DMA channels has 16 bytes of registers. Channel 0’s registers are at addresses $D720 to $D72F, channel 1’s are at $D730 to $D73F, channel 2’s are at $D740 to $D74F, and channel 3’s are at $D750 to $D75F. I’ll refer to each register by its offset $0 through $F. Just know that the registers have the same layout for all four channels.
Switch off channel 0 while we’re setting it up, by writing a 0 to register $0:
The audio DMA system must be enabled before it can be used. This is a global setting, address $D711 bit 7:
The starting address of the sample is a 24-bit value, across registers $1 to $3. We also want to set the channel 0 playhead, a 24-bit value across registers $A to $C. (Remember, these are all Little Endian.) The starting address is used for looping: when the playhead reaches the end, it’ll jump back to the start address.
The end of the sample is stored as a 16-bit value equal to the lower 16 bits of the last address, in registers $7 to $8. In our case, the end address is $5.00FF, so the register value is $00FF.
Each audio DMA channel gets two volume settings, with the ability to pan the channel’s output to the Left DAC or the Right DAC in different proportions.
Channels 0 and 1 are considered “left” channels, and channels 2 and 3 are considered “right” channels. The $9 register in each channel’s register bank sets the volume of the signal that it outputs to its device, either the Left DAC or the Right DAC. The register value is between 0 and 255, with 255 being the loudest.
Another set of volume registers allow for each channel to also output to the opposing DAC. Registers $D71C and $D71D set the output of channels 0 and 1, respectively, to the Right DAC. Registers $D71E and $D71F set the output of channels 2 and 3, respectively, to the Left DAC.
This can get a little confusing because the user can subsequently pan the Left DAC or the Right DAC using the Audio & Volume tool in the Freezer, and can even flip the stereo field entirely. If you want to experiment with this, I recommend opening the Freezer tool and setting the “Left Digi” volume up in the left output channel and all the way down in the right output channel, and the “Right Digi” volume down in the left and up in the right, so you can hear clearly through stereo speakers which DAC is being used.
Let’s just set channel 0 to output evenly to both DACs for now. This sawtooth wave is a bit obnoxious, so I’m using a low volume level:
Headphone warning: If you are listening to your MEGA65 with headphones connected directly to the 3.5mm jack, I recommend reducing the master volume in the Audio & Volume tool while you are testing digital audio samples. Incorrect sample data or erroneous register values could cause unexpectedly loud sounds. I prefer to use a set of speakers with an independent volume knob set to a low setting. (Headphones tend not to have their own volume control.)
The sample rate (frequency) is stored as a 24-bit value in registers $4 to $6. This one is a bit weird, but it’ll make sense, I promise.
The value is the 24-bit proportional value of the frequency relative to the CPU speed. For example, if the sample rate is 16 kHz, then the register value is 16 kHz divided by 40 MHz (a ratio), multiplied by 2 to the 24th power minus 1 (the largest 24-bit value). Watch those units when doing the math! The CPU is much faster than the sample rate, so you should get a very small ratio.
Here are the register values for some useful sample rates, pre-calculated for your convenience:
For our experiment, we actually want to do something special with the frequency. We have a very short sawtooth waveform, capable of playing a musical note. The middle “A” key on a piano would play this pattern 440 times per second (440 Hz). We have 256 samples, so to achieve a middle A pitch, we need a sample rate of 440 x 256 = 112640 Hz = 112.64 kHz. Proportional to the 40 MHz CPU speed, the 24-bit value is: 47,244 decimal, or $00B88C (that’s “zero zero Baker eight eight Charlie”).
Someone check my math.
Finally, we can trigger the sample, with a few last settings in register $0. This register uses the following bits as flags:
Run this to hear the tone. It’s a bit obnoxious, so press a key to switch it off. If you accidentally press Run/Stop with the sound still playing, use POKE $D720,0 to disable the sound.
You can experiment with different waveforms by writing different values to $5.0000-$5.00FF. Try these:
This little experiment to play triangle, sawtooth, and sine waveforms is fun, but not particularly impressive considering that the SID chips can already generate these waveforms on their own. To unleash the true power of audio DMA, we need PCM sample data for more interesting sounds. The MEGA65 does not have a built-in audio digitizer (at least not yet), so we must turn to our trusty modern computers.
There are many ways to record, produce, or otherwise acquire sound files with a modern computer and an Internet connection. Your computer’s operating system probably includes a free sound recording or editing program, and so does your mobile phone. Sound editing software like Audacity is free, and you can also download free sound files from FreeSound.org. Whatever software you’re using, be sure to edit your sound file to trim it to just the length you want your MEGA65 program to play.
Our goal is to convert the sound file to raw PCM sample data at an appropriate sample rate, and at a bit depth supported by the MEGA65 audio DMA. Audacity can do all of this in a single export step:
Remember that sample rate and bit depth affect data size and sound quality, so choose wisely.
Other modern sound production software may not have all of the same export options. Some of the more expensive software packages on my computer can’t believe I would ever want to export at a sample rate lower than 44.1 kHz. If your software doesn’t export raw PCM sample data, or doesn’t offer the desired sample rate or bit depth, export a .wav file with high quality settings, then use Audacity for the final conversion to raw PCM data with the desired parameters.
It’s important to use the highest quality settings for every processing step until the last one. Because each digital audio file is an approximation of the original waveform, the conversion tool has to use some math to assume the gaps between the samples when converting from one sample rate to another. The more data that goes into that process, the better.
While preparing this Digest, I had occasional issues with Audacity trying to boost the volume of my samples, causing clipping of the signal in some cases that added loud pops to the final sound effect. Notably, this clipping only happened on real hardware and not in Xemu, so be sure to test your samples.
Audacity is fine, but I like command line tools so I can automate build workflows. The tool for this is ffmpeg, an essential free media conversion tool for video and audio. It’s similar to how we used ImageMagick to convert still images back in a previous Digest. ffmpeg is available for all platforms. On a Mac using Homebrew, install this with: brew install ffmpeg
ffmpeg accepts most audio files as input, including .wav files. Specify the input file with the -i parameter. It’ll detect everything it needs to know about the input data from the file itself.
For the output file, we want something special, so we need to tell it what we want. The -f option selects the bit rate, selected from this list:
To convert the file to a different sample rate, use the -ar option, and provide the value in Hertz. To convert a stereo sound to monophonic, specify -ac 1.
You now have a raw PCM data file. Assuming it’s small enough, you can now copy this to a D81 disk image, and transfer the disk image to your MEGA65. See a previous Digest for more information on how to manage files and disk images.
The BASIC program above can be modified to play an arbitrary sample file. Replace line 10 with a BLOAD command that loads your sample file to address $50000:
You will need to adjust the sample length (line 60) and the sample rate (line 80) as appropriate for your data. You might want to remove the loop flag ($40) from the playback command (line 90). Only include the “unsigned” flag ($20 on line 90) if the sample data is unsigned.
Can you hear the sound, but it’s noisy or crackling? Double-check the “unsigned” bit. Using the unsigned bit when the sample data is signed (and vice versa) will cause transitions from negative to positive values to pop, in a bad way.
None of the audio processing programs I tried offer export of 4-bit samples. How can we make 4-bit samples, to take advantage of this feature of audio DMA?
Compared to something as complex as re-sampling at different sample rates, converting from an unsigned 8-bit sample to an unsigned 4-bit sample is simple. We just lop off the lower four bits, equivalent to dividing by 16. Here’s a simple Python program that does this:
This takes the file klf_8b.raw containing unsigned 8-bit samples and produces the file klf_4b.raw containing unsigned 4-bit samples, with each sample in the lower four bits. We can modify our playback program to use this by setting the appropriate flags in the $0 register:
Audio DMA requires that each sample be at separate memory locations, so merely converting a sample from 8-bit to 4-bit doesn’t actually save any space. The space savings comes from storing two 4-bit samples on top of each other, and telling audio DMA to play either the bottom four bits or the top four bits. We can modify this Python script to store two samples together in this way:
This takes the two 8-bit sample files klf_8b.raw and rockyou_8b.raw, converts them both to 4-bit, then writes them to a single file klf_4b.raw with klf in the lower bits and rockyou in the upper bits.
To tell the playback program which sample to play, set bits 1 and 0 of $D720 accordingly:
I have a vivid memory of hearing The KLF’s “3 a.m. Eternal” played on my childhood Amiga 500. Like the MEGA65, the Amiga can play short digitized sounds over four audio DACs. Most Amiga owners didn’t have enough memory to store several minutes of digitized sound, so another kind of music was born. A MOD file encodes music as short digitized sounds played in a pattern of frequencies and timings, saving memory by re-using samples throughout the song. The KLF’s music was largely sample-based and repetitive to begin with, and they even produced some of it on home computers like the Apple II and Atari ST. MOD files can come close to reproducing the original songs within the memory limitations of a vintage computer.
Your MEGA65 includes a MOD player on the Intro Disk, called “Manche,” that uses audio DMA to play sound samples. I found one person’s attempt at a MOD of “3 a.m. Eternal” and was able to play it in Manche on my MEGA65. I can’t say this particular MOD is my favorite remix, but it’s been fun to revive this memory.
Here are a few MOD arrangements of KLF songs for you to enjoy:
Put these in the root of your SD card, then start Intro Disk #1. Open the Music menu, select Manche, and press Return to run the program. Within Manche, press F1, type one of the filenames, then press Return to load the file. Press Space to start playback.
I also made this demonstration disk with the waveform generator program from this issue, as well as a program demonstrating the same sound at different sample rates and bit depths.
This Digest is made possible with support from justified ancients, like you! To contribute, visit ko-fi.com/dddaaannn.
See you next month!
— Dan
Sprite Attack. Dan’s MEGA65 Digest for February 2024.
Spaceships. Aliens. Marios. Goombas. Bullets. Fireballs. Mouse pointers, text cursors. Any of these could be a sprite, a feature of a computer graphics system dedicated to things that move. The sprite capabilities of the Commodore 64’s VIC-II chip super-charged video games and user interfaces beyond a single screenful of character text or a bitmap image. The MEGA65 includes support for VIC-II hardware sprites, and has sprite-related BASIC commands that make them easy to use in your programs.
In this Digest, we’ll review the VIC-II sprite system’s capabilities, try out the sprite features added to Commodore BASIC for the C128, C65, and MEGA65, and step through a development workflow for using sprites in BASIC games. And we’ll try putting these pieces together to make a simple arcade game.
But first…
The MEGA65 User’s Guide, 2nd edition.
You can now buy a spiral-bound printed copy of the MEGA65 User’s Guide, 2nd edition!
This new edition has been updated substantially from the 1st edition printing from two years ago. It covers the upcoming v0.96 release, with instructions for new features like Ethernet file transfer, and revised information on important topics like upgrading the firmware and using disks. The BASIC reference has been updated with corrections, polish, and material on new features. And there are handy new appendices on screen codes and system colors.
Whether you have the 1st edition and want to upgrade, or don’t yet have a MEGA65 and just want a useful book to go with Xemu, getting the 2nd edition in print is a great way to enhance your MEGA65 experience.
I wrote a FAQ with more information, including what’s happening with the manuals bundled with new MEGA65s. Let me know if you have any questions.
The v0.96 release package has been in public testing for a month, and we’ve been chasing down issues and polishing it up for factory installation on all of the new MEGA65s. This process should be complete a week or so after you read this. Many thanks to everyone who has contributed to the testing effort!
What happens next: the v0.96 release package will be made official and sent to Trenz for the factory installation on new machines. It will be declared the new stable release for R3A and R6 mainboards, and made available on Filehost. Everyone with the “retail” MEGA65 will be encouraged to upgrade.
DevKit and Nexys board owners will need to wait, just a bit. In order to meet the assembly schedule, we have had to defer preparing new cores for these boards until after this release. The plan is to immediately start work on these deferred tasks, and issue a v0.97 update within a couple of months that includes support for these boards. You’re always welcome to help test along the way, just be aware of known issues with slot 0 flashing on the older boards.
Upgrade party at lydon’s place! 🎉
The new Intro Disk main menu
Gurce has put a ton of work into preparing the new software bundle for the SD card that will ship with the new MEGAs. Current owners are familiar with the “Intro Disk” menu that starts when you first switch on the computer, as well as other bonus goodies that come on the pre-installed memory card. The new bundle includes all of that and much more, a total of 191 (one hundred and ninety one!) menu entries. And that’s not even counting the disk menus themselves, with useful information and musical accompaniment. This compilation starts all new MEGA65 owners off with plenty to do on their first day. Huge thanks to Gurce for his meticulous work on this project, and of course to everyone who has written software for the MEGA65.
You can download the new software bundle on Filehost. (There’s a separate download for registered owners with a more complete version of GEOS.) If you don’t yet have a MEGA65, you can try it out in Xemu—or save it as a surprise for when your MEGA65 arrives!
Rocket Delivery Service, by fredrikr
Don’t miss these new titles on Filehost:
Rocket Delivery Service, by fredrikr, a new game for one or two players. Navigate your rocket man to pick up and deliver packages, for cash! Each player can use a joystick, or player one can use the keyboard while player two uses a joystick. Written entirely in BASIC!
MJoergen and sy2002 are updating their vintage platform cores for use on the new R6 mainboard. The ZX Spectrum core v1.2 is now available, and there is a beta test version of the C64 core v5.1 (link goes to Discord) to be released soon. The C64 core update also includes a few fixes for all mainboards, and support for using the MEGA65’s Real-Time Clock with the Commodore 64 version of GEOS.
muse has yet another arcade core, and he keeps picking my favorites! Elevator Action (1983), a spy thriller set in a multi-level top secret facility. Infiltrate the building from the roof, avoid the armed goons, collect the secret files, and escape through the parking garage. As with the other arcade cores, you must locate the arcade ROMs yourself, so be sure to follow the installation instructions. Hold the button to jump.
Amiga fans: geehaf has published an ADF disk image utility that can use the MEGA65’s physical floppy drive to make Amiga disks from ADF files, and vice versa. This is a beta release of the tool, so take care to back up important data.
The hardware sprites of the VIC-II chip should be familiar to anyone who has written a program for the Commodore 64. The Commodore 64 Users Guide that came with the machine included a chapter on sprite graphics with a type-in demo. C64 programmers may also remember drawing out pictures on graph paper, hand-coding them into decimal numbers, typing them into DATA statements, and messing about with dozens of arcane POKE statements. In later computers and later versions of BASIC, Commodore added a BASIC sprite subsystem with access to most of the VIC-II’s sprite features, driven by a new set of commands. No POKE-ing necessary.
From here on, when I say “sprites,” I’m referring to the built-in sprite features of the VIC-II chip that have carried forward from the Commodore 64 to the MEGA65. Experienced game programmers would want me to point out that the general term “sprite” could apply to any kind of moveable graphics object, and there are, in fact, other ways to accomplish sprite-like effects on the MEGA65. We’ll have to cover those in later issues of the Digest.
The best way to get to know Commodore sprites is to try out the commands! The new v0.96 release version of the MEGA65 ROM includes pre-defined sprite images for a mouse pointer and a simple line pattern, so you can get started without drawing any graphics. If you’re using the previous release, you can still switch on the sprites, you’ll just see a blob of pixels that represents uninitialized memory contents.
The VIC chip can keep track of up to eight sprites at a time, numbered 0 through 7. Each sprite has a set of modes and flags, including a flag to enable or disable the sprite. You manage these flags with the SPRITE command.
To turn on sprite 0:
Nothing appears to happen because the sprite starts located off the screen. Let’s move it roughly to the middle of the screen so we can see it (X=160, Y=120):
While many of BASIC 65’s sprite commands originate with BASIC 7 and the Commodore 128, there are subtle differences. For example, on the C128, sprites are numbered 1 through 8. I won’t describe every difference here, just be aware that they’re not exactly the same on both computers.
In the default sprite mode (sometimes called “high resolution” mode), each sprite is 24 pixels wide and 21 pixels high, using a single sprite-assignable color for each “on” pixel (bit 1) and treating each “off” pixel (bit 0) as transparent. This is encoded as three bytes per row (8 bits per byte x 3 bytes = 24 pixels), for a total of 63 bytes (21 rows x 3 bytes per row) per sprite image.
You can set the color of a sprite with the SPRITE command. You can omit any argument you don’t want to change by specifying just a comma. The color value refers to the palette entry, in this case the default system palette. To turn sprite 0 red (palette entry 2):
On the MEGA65, you can change the system palette using the PALETTE COLOR command. Each palette entry can be any of 4096 possible colors, with a red, green, and blue component each between 0 and 15. This changes the palette entry for all uses of the color on the screen, not just sprites. To replace the red color at entry 2 with a bright green:
To restore the default palette:
If you’re willing to use a lower sprite resolution of 12 double-wide pixels per row instead of 24 single-wide pixels, you can set a sprite to multi-color mode, for two more additional colors. The two new colors must be shared by all sprites that are in multi-color mode. In this mode, sprite pixels are encoded as bit pairs: 00 for transparent, 10 for the sprite color, and 01 and 11 for the two shared colors.
Let’s try setting sprite 0 to multi-color mode, using a value of 1 for the seventh argument to SPRITE:
If you’re using a ROM beta version, the default mouse pointer image of sprite 0 might not look that impressive in multi-color mode. Try enabling sprite 1 and moving it to the middle of the screen, then put it in multicolor mode. The default image of sprite 1 is designed to illustrate multicolor mode, with a repeating pattern of 00, 01, 10, and 11 bit pairs. (If you’re using release v0.95’s ROM 920377 or earlier, you’re in luck: the garbage data that’s usually there typically has an interesting combination of bit pairs.)
To set the two shared colors for the multicolor sprites, use the SPRCOLOR command, with the two palette entry numbers:
Each sprite can be displayed normal size, double width, double height, or both double width and double height. The double modes don’t give you more pixels: instead, they stretch the existing sprite design in the requested dimension.
These modes can be selected per sprite, and are the fifth and sixth arguments to the SPRITE command, respectively. Try the combinations of 0 and 1 for these arguments:
Each sprite can be set to appear above the character or bitmap layer, or below it. When above, you can see the character or bitmap through the sprite’s transparent pixels.
Use the cursor keys to move the text cursor to where the sprite is on the screen, then type some characters underneath it. On a blank line, set the fourth argument to SPRITE to 0 or 1, and see what happens:
When sprites overlap each other, lower numbered sprites are always in front of higher numbered sprites. This order cannot be changed. Use SPRITE to make sure two sprites are active, then use MOVSPR to locate them so that their images overlap.
Overlapping sprites is a common way to draw a high resolution graphics object using more than one color: just use more than one sprite to represent the object, and allow pixels of lower sprites to shine through the transparent pixels of upper sprites.
A sprite can be located at any pixel location on the screen. A sprite’s location is specified as coordinates on the screen, where the sprite’s top-left corner is placed at that location. Coordinates extend to locations under the screen border, and a sprite that overlaps the border will be obscured. This allows a sprite to glide off the screen smoothly until it disappears. (Note that double-width sprites won’t fit completely under the left border.)
To place a sprite exactly in the top-left corner of the screen just inside the border, set its coordinates to X=24 Y=50. If a sprite is in its normal display mode (with its double-width double-height features turned off), you can place the sprite’s bottom-right corner exactly at the bottom-right corner of the screen with coordinates X=321 Y=229.
The VIC-II sprite coordinate system is independent of the resolution of the underlying screen mode. The MEGA65’s default 80-column text screen is actually 640 pixels wide. VIC-II sprite coordinates refer to the same locations regardless of the MEGA65 screen resolution. If you switch to the 40-column text mode, the sprites will remain where they are.
Sprite coordinates are the same for both NTSC and PAL video modes. Even though these modes use different dimensions for the full screen, the dimensions inside the border are the same.
We’ve already seen how the MOVSPR command can set a sprite to specific coordinates. This command has several other useful features. To move a sprite to a relative distance from its current location, use a + or - and an offset for the coordinate value (X, then Y):
The MOVSPR command can animate the movement of a sprite at a given speed. This animation happens asynchronously to BASIC program execution, similar to the PLAY command for music: the animation occurs in the background while the rest of your code continues to run. To move a sprite from one coordinate pair to another, use the TO keyword, and provide a speed as a number of pixels per frame. Remember that PAL mode refreshes 50 frames per second, while NTSC mode refreshes 60 frames per second, so the movement speed differs based on video mode.
Note that the sprite needs to hit the end coordinate almost exactly for the sprite to stop. If the speed is not a multiple of the differences between the starting and ending coordinates, the sprite might overshoot its destination and wrap around the screen until it finally lands where it was told. If there’s a chance of this, you may need to resort to a loop that tests RSPPOS() and stops the sprite with another MOVSPR command when it is close enough.
A sprite can be set to move continuously, with no fixed end coordinate. To do this, provide an angle as a number of degrees, with 0 degrees being “up” and proceeding clockwise, so 90 is right, 180 is down, and so forth. Follow this with a # symbol and the speed.
The sprite will continue to move at this angle and speed until you set its speed to 0 with another MOVSPR command, or until you switch it off with the SPRITE command.
When a moving sprite leaves the screen, it will continue to move until its position wraps around to the other side of the screen. If you want to test the position of the moving sprite, such as to stop its motion after it is off screen, use the RSPPOS() function. This takes the sprite number, and an argument identifying the parameter to return: 0 for the X position, 1 for the Y position, 2 for the speed.
Here’s a short program that starts the sprite moving to the right, then stops it either when a key is pressed or the sprite leaves the screen:
The VIC chip can report when two sprites have non-transparent pixels on top of each other, or on top of the character or bitmap layer. Your program can use this to detect collisions between sprites, or between a sprite and the background, such as to know when a player’s bullet hits an alien ship, or when the player’s ship crashes into a mountain.
BASIC 7 on the Commdoore 128 introduced an interesting mechanism for handling sprite collisions. To tell BASIC that you care about sprite collisions, you use the COLLISION command to indicate the type of collision (1 = sprite on sprite, 2 = sprite on background), followed by a line number of your BASIC program. At some later point, when the VIC detects the requested collision type, BASIC will stop whatever it is doing and jump to the given line number as if it were a GOSUB subroutine. Your code at this line number should do whatever it needs to do to react to the collision, then use the RETURN command to resume where the program left off.
Your handler subroutine is called for any collision of the requested type. Your code will need to use other tests to determine which collision took place. The BUMP() function reports which sprites were involved in a collision since the last call to BUMP(). You can also use the RSPPOS() function to test individual sprite locations to further determine where the collision took place. See the User’s Guide for information on these functions.
Try to guess what this program does, then type it in and run it:
The VIC’s built-in collision detection is not always the most reliable way to detect game events. Depending on the shapes of your sprites and other factors, you may prefer a different method to detect collisions, such as by testing sprite positions relative to a hitbox. To do this, instead of a COLLISION handler, you’d make repeated tests of RSPPOS() in your game’s main loop.
Another caveat: There is a known issue with the VIC-IV core where sprite collisions are not detected with bitmap graphics (the BASIC 65 SCREEN system). Collisions are limited to sprite-to-sprite and sprite-to-text for now. Of course, there’s quite a bit you can do graphically in text mode using PETSCII graphics, and custom character sets with the CHARDEF command.
If you grew up with a Commodore 64, these sprite features probably feel quite familiar. The C128 sprite commands, and the C65 and MEGA65 additions, are handy, but the sprites themselves mostly look like they did on the VIC-II.
For the VIC-III video chip in the Commodore 65, Commodore added no new features to sprites. Sprite colors use the VIC-III system palette, and you can adjust the colors of the system palette to any of 4096 possible colors. Otherwise, they’re basically the same as they’ve always been.
The MEGA65’s VIC-IV adds advanced sprite features, such as a full-color mode with actual-size pixels, four palette banks, a 64-pixel width monochromatic mode, variable pixel height, and high resolution sprites that use the actual pixel width and coordinate system of a 640-wide (80-column) display. BASIC 65 does not yet support any of these features with the BASIC sprite commands. You can adjust VIC-IV registers directly with POKE statements, but this may interfere with the behavior of the BASIC commands. I’m currently working to extend BASIC 65 with official support for VIC-IV sprite features, so stay tuned for updates!
Playing with the built-in sprites is fun and all, but for our own programs, we obviously want to draw our own sprite images.
Did you know that the Commodore 128 has a built-in sprite editor? The C128’s SPRDEF command opens a sprite editor that directly manipulates the BASIC sprite image data in memory. For whatever reason, Commodore removed SPRDEF for BASIC 10. The good news is, the MEGA65 has its own sprite editor, “SpritEd,” built into the Freezer.
Hold Restore for one second then release to open the Freezer, then press S to start the sprite editor. This utility edits sprite image data at the BASIC sprite locations in memory.
A word of warning. SpritEd is currently unfinished software. Up to platform release v0.95, SpritEd crashes the machine if you press the Up Arrow key. I discovered this while writing this article, and I committed a fix to prevent this that will be in release v0.96. I recommend upgrading to release v0.96 before doing any serious work in SpritEd.
SpritEd is missing a bunch of its intended features, such as the ability to load and save images to disk. Even without these features, it is about as useful as the C128’s SPRDEF tool, and can edit sprite image data in memory. We’ll see how to get sprite image data from memory into your program in the next section.
Press the Help key for a list of keyboard controls. Briefly, these are as follows:
SpritEd supports drawing with a mouse connected to port 1. I discovered a small bug where the mouse can’t draw in the rightmost column, which should be easy to fix in a future version.
To exit SpritEd, press F11 to make sure the current sprite is saved to memory, then press F3 to exit back to the Freezer menu. Each sprite image is saved to memory automatically when you flip between the sprites, so F11 is only necessary on the current sprite, if it was modified. (That feels like something else we can improve pretty easily. Just know that’s how it works for now.)
The gorgeous sprite graphics we created in SpritEd are now in memory, but they’ll disappear forever if we don’t get them out of memory and onto disk. BASIC 65 makes this easy: SPRITE SAVE "filename" saves all eight sprite images to a file on disk. SPRITE LOAD "filename" loads them back in.
This provides a POKE-free workflow for managing sprites for BASIC programs:
For a game like Space Invaders, a ship can be a single sprite image whose only animation is to move around the screen, such as with the MOVSPR command. For a game like Pac Man, the player sprite should open and close its mouth, which means updating the sprite’s image data. We can’t exactly load a new Pac Man from disk each time he opens and closes his mouth, so we need another way to update sprite data within the program.
The SPRSAV command copies sprite data between sprite slots and BASIC string variables. It takes two arguments: the source and the destination. One or both of these can be a number between 0 and 7 to refer to the sprite image. If the other is a named string variable, the variable is used as either the source or destination.
For example, to copy the image data from sprite 2 to the string variable C$:
To copy that image to sprite 5:
Combined with SPRITE LOAD, you can use SPRSAV to load all of your sprite patterns into string variables, then store them back into sprite slots during game play as needed.
You can also use string variables and SPRSAV along with disk operations as an alternative to SPRITE LOAD. For example, you can store more than eight patterns in a single file. Each pattern is 64 bytes in length. See any good reference on disk commands for more information.
Sprite Attack is a simple game I wrote to demonstrate how the sprite features can be used together. Get it here:
Try it out with a joystick in port 2. It’s written entirely in BASIC, so type LIST to see the program listing. A few notes:
I used SpritEd to draw eight multicolor sprites: the player’s spaceship, the player missiles, the space alien death ray, four frames of an explosion animation, and the space alien itself. I exited SpritEd and the Freezer, then used the command SPRITE SAVE "SPRATK.DAT" to save the sprite data to disk. The program starts by loading this file with SPRITE LOAD.
I keep the player’s X position in a variable so I can fine-tune the speed that the player moves. Pixel locations are always integers, but sometimes you want a sprite to move in non-integer increments, such as 1.8 pixels per frame. The variable holds the non-integer location, and this value is rounded to the nearest pixel when I pass it to the MOVSPR command.
The game loop tests for joystick movement, adjusts the variable, and updates the player location with MOVSPR. Because the player only moves left and right, I use +0 as the Y coordinate argument to MOVSPR so that I don’t have to remember the ship’s vertical position after initializing it.
I use the VSYNC command to synchronize gameplay with the frame rate. This makes it easier to tune the movement speeds, and it prevents the sprites from “tearing” by making sure the location doesn’t change while the sprite is being drawn.
Player missiles use the movement animation system. The RSPPOS() with a second argument of 2 returns the current speed of a sprite, so I can test whether the missiles are moving. If the button is pressed and the missiles aren’t moving, I set their position to just above the player ship and set them moving in an upward motion, then I activate the missiles sprite. I also test once per loop if the missiles have gone off the top of the screen, and if so, I stop their motion by setting their speed to zero.
The alien also uses movement animation. If the space alien is ever stationary (speed is 0), the program chooses a new random location, and calls MOVSPR with the current location as the origin and the random location as the destination. This gives the alien an evasive behavior that still gives the player a chance to target it with missiles.
A collision handler detects when the missiles are in contact with the alien. When the alien is hit, the routine moves the explosion sprite to the alien’s location, disables the missiles sprite, then moves the alien sprite to another random starting point above the screen. It plays out the explosion animation using SPRSAV to copy in the explosion patterns we saved into string variables earlier, pausing between each frame. This causes all gameplay to pause while the explosion finishes. A more sophisticated game would handle explosion animations in the main game loop, so other events like player movement can take place during the animation.
This game is a little unfair—to the alien. Try extending this program to have the alien shoot back at the player, using its death ray in sprite 2.
VIC hardware sprites and the BASIC 65 sprite commands are a fun and easy way to code video game graphics. Combine them with PETSCII graphics to draw level maps, backgrounds, and informational displays, and you have all of the elements of a great looking game. Be sure to share your games with other MEGA65 owners by uploading them to Filehost!
There are some advanced sprite techniques I wanted to mention here, but they’ll have to wait for another issue. You can help make more issues possible by supporting the Digest on Ko-Fi.
As always, happy coding!
— Dan
The New Hotness. Dan’s MEGA65 Digest for January 2024.
It’s time! We have a shipping schedule for the next batch of MEGA65 computers, and a candidate for the next platform release. Everyone is invited to help with testing, so let’s get to it!
Trenz Electronic has announced that the next batch of MEGA65 computers will ship on June 1st, 2024.
We currently expect that all preorders up to this point will be included in this batch. If you need to make adjustments to your preorder before then, contact [email protected].
Once we clear the preorders, remaining stock will become available for purchase in the Trenz Electronic store, while supplies last.
Please bear with us while we work through any last minute issues that might change these estimates. And thank you so much for your patience! I can’t wait for you to receive your MEGA65!
To make the new delivery schedule, we need to hand over the gold masters of the next release of the MEGA65 firmware and system software, as well as the updated User’s Guide, to Trenz Electronic by January 31st. Release v0.96 of the firmware, ROM, and system software will be installed at the factory on all MEGA65s about to ship. Of course, it will also be available as a free upgrade for all existing MEGA65s. This next release has a ton of new features and bug fixes—and we need testers!
If you have a MEGA65, you can install the release candidate on your machine to help test. If you don’t have a MEGA65 yet, you can still help by testing the new version of the ROM with an updated version of the Xemu emulator.
To begin, be sure to back up your SD card, or use an alternate SD card, before proceeding with testing. I usually just move the SD card to my PC, then copy all of the files from the SD card into a folder on my desktop. This doesn’t back up the configuration or Freeze states, but personally I don’t keep important freeze states around long term. Alternatively, you could also use a disk imaging utility to back up both the hidden configuration partition and the files partition.
If you’re using a fresh SD card for testing, remember to prepare the card first using the MEGA65’s SD Card Utility. Insert the card in your MEGA65, hold the Alt key while switching on the computer, then select the utility from the menu and follow the prompts. This erases all data on the card.
Here’s how to get the files for the release candidate:
Unpack the mega65r3-r-0.96-build-5.7z archive. Transfer the .cor file to the root of your SD card. Open the sdcard-files folder, and copy its contents (.M65 files) to the root of the SD card as well.
Rename 920391.bin to mega65.rom, and transfer it to the root of your SD card.
Install the SD card in your MEGA65. With the power switched off, hold No Scroll then switch on the computer. This opens the core selection menu. Hold the Ctrl key and press a number to select an appropriate core slot for the new core, then follow the prompts to select the .cor file and flash the core. See the User’s Guide for more information about upgrading cores.
I recommend keeping both the release candidate and the previous stable release installed during testing. If you find any issues with the release candidate, it will be important to determine if those issues also exist with the previous stable release, or if they are new issues introduced by a recent change.
Choose one or the other to be the default for your computer. Flash the core you wish to be the default to core slot 1, and name the default ROM as mega65.rom on the SD card. For the non-default release, flash the core to slot 2, and name the ROM file as mega652.rom. To start the non-default release (whichever one you chose), hold No Scroll while switching on the computer to open the core selection menu, then press and hold the number 2 until you see the READY. prompt (and probably a bunch of 2’s). This selects core slot 2 and also selects mega652.rom.
There’s one tricky bit with a dual installation: you can only have one set of system software on the SD card. I have not had any issues running the new system software with the previous stable core and ROM, so my recommendation is to go ahead and use the release candidate system software as the system files on your SD card.
It’s important to note that the release candidate ROM only works with the release candidate core. If you accidentally select the release candidate ROM (version 920391) and the previous stable release core, typing won’t work correctly and you’ll see the cursor disappear. If this happens, switch off the computer, hold No Scroll while switching it back on, then select a matching core and ROM. You can use the previous ROM (version 920377) with the new core, just not the other way around.
You can confirm that you’re running the release that you intend with the new MEGAINFO utility. Open the Freezer—hold the Restore key for a second, then release—then press the Help key. This is a feature of the new system software, and it works with either release as long as the new release’s system software is on the SD card.
If you do not have a MEGA65, you can still help test the ROM in the Xemu emulator. Get these files:
Run xmega65, and when prompted for a ROM, use the new ROM.
Just as the release candidate ROM (version 920391) depends on the release candidate core, it also depends on the “next” version of Xemu. If you try to use the new ROM with the previous stable version of Xemu, you will notice problems with typing.
This release is the culmination of 15 months of improvements and fixes across the board. Changes to the ROM are listed in the ROM change log. Changes to the core are numerous and we’re still assembling the core change log, but here are a few notable features:
In addition to testing new features, we want to know about anything that worked in the last stable release and appears to have stopped working in the new release candidate (called “regressions” in software engineering parlance). This includes, but is not limited to:
There are two ways to report any bugs you find. We have an active thread on the Discord for collecting release candidate bugs. Look for the platform-testing forum. Alternatively, you can file issues directly to the Github repo for the core, the repo for the ROM, or the repo for the User’s Guide. If you’re not sure where the bug goes, file it in the core repo, and we’ll triage.
If you find something that doesn’t look right, try to reproduce it in the previous release. File a bug either way, and make sure to note whether this only happens in the release candidate, or if it happens in both versions.
Many thanks to everyone who is available to test! We’re on a tight schedule, so anything you can do before the end of January would be a huge help.
Every MEGA65 includes a printed version of the MEGA65 User’s Guide, a book that includes set-up instructions, common procedures, an introduction to BASIC programming, and a BASIC command reference. We printed a large quantity of the 1st edition, and everyone who has received a MEGA65 so far has this edition. We can’t afford not to use the remaining stock, so we will be including copies of the 1st edition with some MEGA65s that will ship in June.
The User’s Guide has been revised with new material on new features like Ethernet file transfer, and a renewed focus on non-developer activities like using virtual disk images and upgrading the firmware. The entire Guide has been polished with corrections, and the BASIC reference has been updated to include the most recently added features. We’re calling this the “2nd edition,” and we will be printing new Guides to include with MEGA65s after the stock of the 1st edition is depleted.
Do you want a printed copy of the 2nd edition? I know I do! I’m working on setting up the User’s Guide, 2nd edition with a print-on-demand service, so anyone who wants an updated printed Guide can get one. Whether you have the 1st edition and want to upgrade, or you’re just enjoying Xemu and want a book to go with it, you’ll be able to order a copy.
I’ll share the link to the purchase page in the next issue of this Digest. We’re using the release testing period to catch any last minute bugs in the Guide, and to make sure it matches the new slot 0 flashing procedure when it is finished. In the meantime, you can always download the latest draft PDF of The MEGA65 User’s Guide. (And report bugs!)
YouTuber David Murray, aka “The 8-Bit Guy,” made a video about the Commodore 65 last December, borrowing Bo Zimmerman’s vintage C65 prototype to try it out. At the end of the video, David mentioned the MEGA65, mostly to say that he knew about the project but didn’t know anything about it. There were multiple attempts to get a review unit to David that fizzled out for one reason or another. When I saw that, I thought to myself, what can I do to help? I suppose I could… just go down to Texas and bring my MEGA65 with me. So I did!
Behold, the 8-Bit Guy’s video about the MEGA65, with special guest, me!
David is a co-founder of the Commander X16 project, a retro fantasy hardware project with similar interests to the MEGA65. Based on the 65C02 CPU, the X16 has a Commodore-like architecture and uses a Commodore-derived KERNAL and BASIC, while updating other aspects of the design to use readily available components and interfaces. Check out the X16 FAQ for details, and give the in-browser emulator a try.
Many thanks to David for hosting me and for appreciating the MEGA65. Thanks also to my Ko-fi supporters and to the MEGA65 team who helped make this possible.
Yes, your support of this Digest on Ko-fi is already making new things happen! If you would like to support the Digest and my involvement with the MEGA65 team, please visit: ko-fi.com/dddaaannn
Back again next month with more news, and more fun things to do with your favorite computer. Cheers!
— Dan
robotfindskitten, part 3. Dan’s MEGA65 Digest for December 2023.
Our robotfindskitten adventure continues! In part 1, we introduced the robotfindskitten experience, and described tools and techniques for building an rfk game in BASIC 65. In part 2, we started building a similar toolkit in assembly language, starting with KERNAL routines, memory access techniques, and screen memory registers. This month, we complete the toolkit, and I present my own attempt at an assembly language version of the game.
But first, a whole bunch of new stuff!
A test unit of the R5 main board.
The new R5 main board test units have arrived and Paul has started the “bring-up” process, adapting the FPGA core to the design changes. With some minor corrections to the assembly, this should resemble the main boards that will ship with new MEGA65s going forward, including all pending pre-orders. Many thanks to Paul, Trenz Electronic, and the hardware testing team for the work they are doing.
Unicode title screen.
deathy has another new game release! In Unicone, you are chasing a unicorn that poops ice cream. Move your ice cream cone left and right to catch falling ice cream scoops dropped by the unicorn. A fun game in the tradition of Kaboom! (or its lesser known ancestor, Avalanche), Unicone features high resolution graphics, sampled sounds, a wide variety of control schemes, and a unique ice cream balancing mechanic for extra challenge in later levels. Download Unicode from Filehost.
Want to see how it works? deathy has generously released the C source code to Unicone using an open source license, and the assets using a Creative Commons license. The code builds with the Calypsi C cross-compiler, a modern retro development suite by hth313 that recently added support for the MEGA65’s 45GS02 CPU. Check it out!
The Ghosts of Blackwood Manor, by Stefan Vogt
Stefan Vogt, the author of the adventure games Hibernated and The Curse of Rabenstein, has a new adventure out for multiple platforms including the MEGA65. The Ghosts of Blackwood Manor is an interactive horror game with three possible outcomes, and each outcome fills out the story.
And of course, Ghosts is getting another gorgeous boxed release from poly.play! Pre-order the boxed release, and get it digitally right now for a donation of your choice.
Way of the Imploding Foot, a game in progress by Gurce and the MEGA65 community
Gurce has been doing a series of live stream development vlogs coding a game from scratch in BASIC 65, using the Eleven programming environment. The game, currently titled “Way of the Imploding Foot” (or just “MegaFoot” for short), is a side-view fighting game, featuring low resolution block character graphics, animated fighting characters, and parallax scrolling.
MegaFoot source code, in the Eleven IDE
You can start with episode 1, and subscribe to find out about new live streams. Also check out the Github repository for the game, or just try the latest D81 disk image. When browsing the repo, be sure to locate the .ELPC files (such as FOOT.ELPC), which contain the code in Eleven syntax viewable as a text file on a PC.
Gurce is welcoming contributions on this project! If you’d like to try implementing a feature in BASIC using Eleven, let Gurce know on the Discord.
One section of the newly remodeled MEGA65 Discord.
The MEGA65 Discord is the MEGA65 community’s real-time meeting spot, a great place to ask questions, show off your projects, and meet other MEGA65 enthusiasts. Thanks to MEGA65 Discord moderator KiDra, the Discord now has a fresh new structure and some really cool new features! Here are just a few highlights:
We will continue to evolve and improve the Discord based on the needs of the community. If you have any feedback or questions on the new layout and features, feel free to discuss it in the #mega65 channel, or contact anyone on the admin team. Thanks again to KiDra for setting all of this up!
Bad Basic65 Apple Demo, by Nobato.
As a follow-up to MEGApple, MirageBD’s high fidelity Bad Apple demo for the MEGA65, Nobato has a new version, this time in BASIC65! Bad Basic65 Apple Demo comes on multiple D81 disk images and can swap disks automatically from the SD card. The music is an original SID arrangement, using BASIC65 PLAY statements.
Boot B65APPL1.D81 to start. It takes a few minutes to load and decompress data into upper RAM—this is all in BASIC, remember—but once it begins, it runs smoothly, start to finish.
Don’t miss the Little Bad Basic65 Apple bonus disk, also included in the archive!
It’s a mousepad! It’s a quick reference! It’s a mousepad and a quick reference!
A couple of weeks ago, I mentioned that I designed a 45GS02 assembly language quick reference, and you can purchase this design as a mousepad or a poster. Many thanks to everyone who has ordered a mousepad or poster so far! Proceeds go to supporting this Digest and my other work on the MEGA65 project.
I especially like how the mousepad turned out. It’s fun to look at, I can keep it on my desk as a mousepad, and it’s actually useful as a quick reference for MEGA65 assembly language programming. I just used it a couple of days ago to remind myself how the stack-related instructions work.
I’m using Zazzle to make and distribute these. They ship worldwide, and the shipping rates seem reasonable, only about 10 euros to ship the mousepad to Germany. I’ve had one report that there were technical issues trying to pay with PayPal. They also support credit cards. If you have issues, let me know, and I can try to figure it out.
The mousepad is a perfect companion for our robotfindskitten project. Speaking of which…
To complete our robotfindskitten program in assembly language, we need to accept keyboard input, generate random numbers, de-duplicate choices, pause to animate the (very simple) ending sequence, and select from the list of item descriptions.
A common way for a program to accept keyboard input is another KERNAL routine, getin at $FFE4. This loads a PETSCII code into the Accumulator if a key has been pressed, or 0 if not. This isn’t necessarily the best method for using the keyboard as a game controller, because it includes typing features like key repeat. But it’s easy to use, and for rfk, the built-in key repeat is reasonable behavior.
In older versions of the ROM, the getin routine uses CIA registers to scan the keyboard. With the latest beta test version of the core and ROM that I mentioned last month, getin uses a new typing event queue implemented in hardware for greater accuracy. Your program will get the same result from either version: the pre-conditions and post-conditions of getin have not changed.
A program that doesn’t use the KERNAL can access the new hardware registers directly, or can implement its own keyboard scanner based on the CIA chips. See a Commodore 64 reference for information on how to do that.
getin also supports features like the function key macros and input redirection, which don’t apply to a game but could come in handy for other types of programs. getin and chrout are both part of the KERNAL’s input-output system, of which the screen and keyboard are only two possible devices.
We need a way to select randomized locations and appearances for the items. In BASIC, we used the RND() function for this purpose. What can we do from assembly language?
The MEGA65 has a dedicated hardware register that produces random values. To use it, a program must loop to wait for a “not ready” flag to clear, then read the generated random number from a register. The act of reading the number restarts the process, setting the “not ready” flag while it works on a new number. Internally, the number generator is using a fluctuating oscillator to generate values, and it needs a brief amount of time between reads to produce good results.
Important note: If you test your software in the Xemu emulator, be sure to use the “next” branch release. As of this writing, the random number register implementation is not in the latest stable release, and the ready-wait loop will never exit.
The distribution of values returned by this register is even across all possible byte values 0 to 255. Because this distribution is over a range sized by a power of two, you can reduce the range to a smaller power of two by ignoring some of the bits. For example, to get a random value from an even distribution of 0 to 63, use the and instruction to set the upper two bits to 0:
If the range size is not a power of two, it is feasible to simply “re-roll” for a number within the desired range. This causes all picks outside the range to be distributed evenly across the desired range, so it does not skew the results. Of course, this can take an arbitrary number of tries to roll a value in range, so you can speed this up by combining both techniques: get a number 0 to 255, zero out the unused bits, then test whether the result is in range and re-roll if not.
To get a random number larger than 255, fetch two random numbers and treat them as a single 16-bit number. You can use similar techniques to narrow the range.
Another option is to implement a pseudorandom number generator in your own code. Such algorithms range in power and complexity and can be difficult to get right, but applications like simple games can often get by with something as simple as a linear-feedback shift register (LFSR). Pseudorandom number algorithms generate a sequence of numbers based a starting number, known as the seed. It can be an advantage during testing to use a known seed to get a predictable result. For the final program, you can use another source of randomness, such as the hardware random number register, to determine the seed.
If you’d like to try this, read the Wikipedia page on LFSRs carefully. See also this video from Retro Game Mechanics Explained on how the game Super Mario Bros. 3 nerfs its card shuffling algorithm by misusing an LFSR, apparently accidentally.
When we discussed random selection in BASIC last month, we put in some extra effort to store all previous choices in an array, and re-rolled the dice when we accidentally chose an already-selected character, location, or description. This ensured that no two items would be placed on the same location, which would not only appear as fewer items on the screen but might cause the kitten to be hidden by another item. Depending on how it was implemented, the robot might touch the location and only see the Non-Kitten Item even if the kitten was also at the same location. Ensuring diverse characters and descriptions also maintains variety in the gameplay, to avoid the disappointment of seeing the same description more than once in a game.
The assembly language version of this isn’t different, it’s just a bit more cumbersome than in BASIC. I allocated some array-like memory within the program’s memory space for this purpose, like so:
(Alternatively I could have put this on the base page, or elsewhere between $1700 and $19FF, which is available for program use.)
I wrote three assembly language routines that detect whether the value at position X is equal to the value at any position 0 through X-1, the idea being that as I fill the array from position 0 upward, I can check each item against the previous items. I needed three routines because each value is stored in a different way: characters are stored as one-byte screen codes, descriptions are stored as two-byte addresses (which we’ll see more of later in this article), and coordinates are stored as coordinate pairs in two separate lists.
Here’s the simplest of the three routines I came up with that checks for duplicate screen codes:
A few notes:
These routines were challenging to get right! The algorithm isn’t complicated, but one errant instruction can cause all kinds of havoc. I found it useful to insert a brk instruction early in my program so that it would open the MEGA65 Monitor. From here, I would test these routines by writing values into the arrays, setting the registers, calling the routines, and inspecting the Carry flag.
To do this, I needed to determine the raw addresses of the routines and the arrays assigned by the assembler. You can tell Acme to generate a report of all of the addresses it used throughout the program, using the -r command line argument:
The monitor commands r and m inspect registers and memory, respectively. To update values, you can move the cursor up to the lines that these commands print, change a value, then press Return. (Remember that addresses and values are in hexadecimal.) To call a subroutine, use the j command. See my tutorial on the MEGA65 Monitor, as well as appendix M of the manual, for more information.
There are two more cases of bad item placement worth considering, at least briefly.
The robot also appears on the playfield along with the items. We need to make sure that an item doesn’t land on the robot’s starting position. My solution is crude but effective: I put the robot in the upper left corner of the playfield, then limit item placement to be within a one-tile border. This way, there is never an item where the robot starts, and the robot can move unimpeded around the entire edge of the playfield.
With items placed entirely at random within the border, it is possible, however unlikely, that four items might surround a fifth item. And if that fifth item is the kitten, then the robot will never be able to find it! Tragedy! I admit, I did not bother to solve for this edge case in my implementations, but it’s worth thinking about how this might be solved. One way is to test a chosen item location for surrounding items, and re-roll if a bad case is noticed. A complete solution would have to handle extremely unlikely cases like 19 items forming a wall around the kitten, and would probably involve path finding algorithms or other magicks.
A simpler solution is to only place items on odd numbered rows and columns. For example, within an 80-column width, pick a number from 0 to 38, double it, then add one. This produces a column coordinate from 1 to 77 and guarantees at least a one-space gap between items. Do the same for the row coordinate, and the robot is assured a clear path to every item.
One of the responsibilities of the CIA chips is to keep track of time. For coarse-grained timing, the CIA has a built-in “time of day” clock that counts up by tenths of a second. If your main loop executes faster than ten times per second, you can count upwards by tenths of a second simply by testing for when register $DC08 changes. The bottom four bits are a “binary-coded decimal” value between 0 and 9, representing the tenths-of-seconds value of the CIA’s clock. This can be a bit crude because you might be testing the register just before it ticks, so the actual delay might be off by as much as one tenth of a second.
You can achieve a more precise wait loop delay using a feature of the VIC video chip. The VIC uses a finely-tuned high speed mechanism to describe the entire screen to a connected display many times per second, one line at a time from top to bottom, known as the raster scan. The current raster line number is stored in the RC register, as nine bits: bits 0 through 7 are at address $D012, and bit 8 of the number is stored as bit 7 at address $D011. In the same way that you can wait for the CIA TOD tenths register to change, you can wait for these register values to change for much shorter durations.
The tricky bit (because there’s always a tricky bit) is that the number of raster lines and the rate at which the screen is drawn differs depending on the video mode of the MEGA65. Back in the day, PAL and NTSC were competing standards for analog video signals, used for both transmission and rendering on cathode ray tube (CRT) displays. Commodore sold computers with different VIC chips in different regions to be compatible with the technical standard used in the region for televisions. As a result, Commodore games that used raster-based timing ran differently depending on which VIC chip was in the machine. A game might animate slower or faster than was intended, or it might play music at a different speed. In other cases, a game would only function correctly with one kind of VIC chip, and just trip over itself when running with mismatched VIC timing.
The MEGA65’s VIC-IV chip can generate PAL-like or NTSC-like video signals, as separate modes. Some MEGA65 owners are using displays (vintage or modern) that only support one of the modes. I asked everyone about their display modes in the 2023 survey, and 81% of the MEGA65 owners that responded have their video mode set to PAL by default, vs. 18% set to NTSC. Modern digital displays can often support both modes, but only 56% of owners were confident that their display could do this. A program can force the MEGA65 into one mode or the other using registers, but it’s best to leave it in the mode selected by the user in the configuration or Freezer menu.
The upshot is this:
The actual image size is twice this many lines, fully refreshed at half these rates. The full image is drawn interlaced, with odd lines and even lines alternating with each refresh. 50 Hz or 60 Hz is the refresh rate; 25 Hz or 30 Hz is the frame rate.
It is possible for a program to achieve precision timing independently of video mode using the CIA chips and a system feature known as interrupt handling. Interrupts can also be used for raster-based timing. High speed games are most likely to use raster-based interrupts for timing because it makes it easier to control screen updates, and they will either live with the consequences of the different video modes, or use sophisticated techniques to work around them. Interrupts are a big topic, so we’ll leave that for another Digest.
robotfindskitten doesn’t need precise timing for anything, so raster timing is overkill in this case. I use CIA TOD tenths to add a simple delay to my found-kitten experience, and otherwise rely exclusively on keyboard events (and delays introduced by the key repeat handler) to drive the gameplay logic.
We’re almost done! We have all the tools we need to display messages, choose and place items, animate the robot, move the robot based on keyboard input, and check for item interactions and the win condition. We just need a way to store, select, and display the 400+ possible item descriptions.
We’ve already seen how to add the bytes of a text message to the program in Acme, and to assign a label to its address:
What we need is a way to select from a table of messages by an index. For my robotfindskitten implementation, I used a Python script that reads the NKI descriptions from a text file, and generates !pet directives for all of them, with labels such as i1, i2, and so on. The script also generates an address look-up table with all of the generated labels in it. This puts the starting address of each description into memory at regular two-byte intervals. The program can find the description for a given index by multiplying the index by two (the asl instruction will do the trick), adding it to the address of the lookup table (nki_table), then reading the description start address from that location. Each description ends with a 0 byte, so the message printing routine knows where to stop.
Here’s the full procedure for assigning a unique description to a Non-Kitten Item, using the techniques we’ve discussed:
Using tools and scripts to generate data embedded in a machine code program like this is an essential skill, especially for games. Some assemblers have powerful directives that make embedding and manipulating data easy, such as Acme’s !binary directive that pulls in binary data from a file. Kick Assembler’s inline scripting capabilities are especially impressive. I find it useful to know a modern scripting language like Python so I can write my own data conversion tools that generate either assembly code or binary data that can be embedded in my programs.
If you don’t want to write your own scripts to generate the NKI description table, you can borrow the source code for my version, linked below.
Here are my final versions of robotfindskitten for the MEGA65, in both BASIC and assembly language:
I don’t claim that either of these are the best possible versions of this program. If you find ways that either of these can be improved, or if you have used different designs or techniques in your program, please let me know!
Whew! That’s a whirlwind of programming topics for three Digest issues. Hopefully this is enough for you to get started writing a robotfindskitten of your own, or extending these ideas to making other kinds of games. For example, you could add a system of walls or a maze generator to make locating items more challenging. Or, you could add other non-player robots that move when the player does, attempting to interfere with the search. Maybe when a non-player robot encounters an item, the item gets relocated on the playfield! It’d be a much less zen experience, but more like a game.
Huge thanks to everyone who has jumped in to support the Digest on Ko-fi so far! We’re off to a good start to funding the Digest through 2024. If you would like to become a supporter, visit: https://ko-fi.com/dddaaannn
See you next year!
— Dan
robotfindskitten, part 2. Dan’s MEGA65 Digest for November 2023.
Last month’s Digest introduced robotfindskitten, a programming exercise that unites several major concepts of game programming: updating the display, reading user input, generating random values, timing events, and including and manipulating large amounts of static game data. I offered examples of each of these tasks in BASIC 65, and proposed that these could be used to make a robotfindskitten experience for the MEGA65.
In this issue, I want to start reviewing these topics again in assembly language. Without BASIC’s help, the program will need to turn to hardware registers and low-level programming techniques to achieve similar effects. Some of these topics are too large for a single newsletter, so we’ll take this in two parts. I’ll try to keep things simple by limiting this to just the needs of a robotfindskitten program. Applications that require higher speed or more memory may need more sophisticated techniques.
This month’s Digest will focus on using the KERNAL, printing messages, and drawing characters to the screen—barely scratching the surface of the MEGA65’s graphics capabilities. Next month, we’ll finish robotfindskitten in assembly language with random values, user input, item descriptions, and a simple animation delay.
The work continues to finalize the new R5 main board hardware for the next delivery batch of computers. Getting the test hardware has taken longer than anticipated, and we are now expecting manufacturing lead times to put the batch #3 delivery in early 2024.
Importantly, the team has decided to proceed with the full verification process for the new design, and not skip any steps just to accelerate the schedule. The MEGA65 is manufactured in small volumes in a not-for-profit operation, so we can’t afford to rush the process and risk having to re-make and replace hardware. We want every computer delivered to be as high in quality as possible.
Some pre-orders have been pending for a very long time now, and we thank you for your patience! If you have a pending pre-order and need to make changes, contact Trenz Electronic customer support.
Tristam Island for the MEGA65.
Tristam Island, by Hugo Labrande, is a new text adventure game for multiple platforms, including the MEGA65. You can get the deluxe boxed edition, from publisher poly.play for 35 EUR. The deluxe edition includes the game on 3.5" floppy disk and on microSD card, a hint book, immersive props such as a rock sample and a postcard, and more. You can also get the digital-only edition for $3.99 USD.
Thanks to Hugo for the great game and for supporting the MEGA65, and to poly.play for publishing fun collectible boxed software for our favorite platform!
The ZX Spectrum.
Did you know that you can turn your MEGA65 into a ZX Spectrum? You can, with the ZX Spectrum core! This core just received a major overhaul to use the MiSTer2MEGA65 framework, and now works with modern displays.
Download the ZX Spectrum core from Filehost, then follow these detailed instructions for set-up and enjoyment. The core expects certain files in specific locations on the SD card, and uses ESXDOS v0.8.8 (not v0.8.9) for SD card access. It can load .tap and .trd files.
Once again thanks to sy2002 and MJoergen for their amazing work on setting up the MEGA65 for retro core success!
muse continues the great work of porting arcade game cores to the MEGA65. Bombjack (1984) (installation instructions) and Bosconian (1981) (installation isntructions) are both available.
The complete list of alternate cores for the MEGA65 so far:
Ports and enhancements by MJoergen and sy2002:
Ports and enhancements by muse (shoestring):
Along with a MEGA65 development core in slot 1 and a factory-installed stable core in slot 0, that’s more cores than there are core slots on a MEGA65! Just keep the .cor files on your SD card and flash them as needed.
Jim Happel (jim_64) at Commodore Retro eXpo 2023
MEGA65 enthusiasts have been giving talks at computer conferences this year, and several of them now have video online. Check these out!
If you have given a presentation on the MEGA65, even just to your local computer club, and there’s video online, please let me know so I can feature it here!
Let’s take a look at how you might implement robotfindskitten in MEGA65 assembly language. This month will focus on using the KERNAL API and manipulating the display. Next month, we’ll cover the remaining topics to get a robotfindskitten program working, similar to what we did in BASIC last month.
As before, I’ll be using the Acme assembler. Here’s a reminder of the starter code for an assembly language program that assembles to a PRG file that can be loaded and run. The !8 ... values describe a BASIC bootstrap program that invokes the first assembly language instruction.
Every Commodore computer has a built-in operating system powered by machine code etched into the computer’s Read Only Memory (ROM). You see this code running as soon as you turn on the computer: the READY prompt, the blinking cursor, and the BASIC interpreter and all of the BASIC commands are all built-in code. Included in this code is a collection of machine code routines and subsystems for accessing hardware such as the keyboard, screen, and disk drives. In computer architecture terms, these routines are known as the kernel, the centerpiece of the system used by other components. Commodore employee Robert Russell originally misspelled the word “kernel” as “KERNAL” in the documentation, and this became a nickname for the software. For the sake of tradition, I’ll continue to refer to the Commodore kernel as the KERNAL, using uppercase letters.
A program can call KERNAL routines by way of a jump table, a list of jmp instructions built into the ROM at a fixed memory location. Each jmp instruction redirects to the actual location of the routine elsewhere in memory. The jump table exists to give programmers peace of mind that each jmp instruction will stay at a consistent address for all future revisions of the KERNAL. When changes in the KERNAL code inevitably push an internal routine to a new location, the jump table is updated accordingly, so programs that use the routine continue to function without needing an update.
Here’s a useful example. The KERNAL maintains a system for printing PETSCII codes to the screen. As we’ve seen before, these codes manipulate a cursor that determines the location of the next printable character, and maintains other properties such as the text color and display attributes. The BASIC PRINT command uses this system to display strings of codes and characters. Machine code programs can also access this system using a routine called chrout (also called bsout in some documentation), available via the jump table entry at $FFD2.
The chrout routine has a pre-condition that the PETSCII code to print is in the accumulator (CPU register “A”). The effect of calling the routine is to print the PETSCII code at the current cursor position. If the code is a printable character, it plots the character, moves the cursor, and performs other effects like scrolling the display as needed. If the code is some other PETSCII code, such as code 147 to clear the screen and move the cursor to the top-left corner, that code takes effect.
The jump table is part of the Application Programming Interface, or API, of the KERNAL. The API definition also includes the pre-conditions and post-conditions of each routine, and other important behavioral characteristics about what the routine does. All KERNAL jump table entries designed for the C64 and C128 are valid on the MEGA65—with some changes. While neither the C65 nor the MEGA65 have introduced new table entries, future versions of the MEGA65 ROM could extend the table further without changing any of the existing entries.
It’s important to remember that the MEGA65 ROM is an active construction zone, and only some of the KERNAL APIs borrowed from previous Commodores are considered officially supported for now. Some things that C64 programmers may be used to aren’t official APIs, even if they appear to function today. When the dust has settled on the major bug fixes, the MEGA65 team will formalize more of the KERNAL API surface, adding documentation about supported features to the manuals and building automated tests to ensure that the APIs work properly. The KERNAL jump table is officially supported, as are certain specific facts about the memory layout, such as $2001 being the start address for BASIC programs.
Once a machine code program is running, it is not obligated to use the KERNAL. In fact, many games and larger utilities jettison the KERNAL entirely, installing custom interrupt handler routines, defining a custom memory map, and manipulating the computer entirely through hardware registers. For such a program, the only API surface is the hardware itself, and there is no need to integrate with the KERNAL except to launch the program. If the program does use KERNAL routines and systems, it must honor the KERNAL’s documented pre-conditions, and stay out of its way.
The following code uses the KERNAL chrout routine to clear the screen and print a short message:
This example uses the “X indexing” addressing mode to access characters in the message stored in program memory. lda message,x takes the address of the message, via the assembler symbol message, and adds the value in the X register to it. The X register is one byte, with a range of possible values of 0 to 255. This limits the length of the message to 254 PETSCII codes and one 0 byte to indicate the end of the message.
There’s another way to print short messages, using another KERNAL routine. The primm routine at $FF7D will print a null-terminated message, with the message bytes immediately following the jsr instruction. It’s like having a PRINT command for assembly language!
It seems like a magic trick for the message bytes to be sitting in the middle of the code like this. How does the CPU know to skip over the message to the next instruction? The primm routine is quite clever. When the CPU encounters a jsr instruction, it remembers the address just after the instruction, so it can pick up where it left off when the subroutine exits with the rts instruction. The primm routine assumes that this address is the starting byte for the message and starts printing. When primm finds the 0, it updates the return address to just after the 0, then issues the rts. The CPU is blissfully unaware that primm has been messing with the return address and proceeds to execute the rest of the program. Pretty slick!
Note that primm is also limited to messages of 254 characters. To print a longer message, we need a different strategy.
In the code above, message is a symbol whose value is determined by the assembler and inserted into the code where the word appears. Wouldn’t it be great if we could update the value of the message symbol as the program executes, like a variable? The value of message is written into the machine code, and this code is just bytes in memory. One option is to update the address bytes within the code by writing to the appropriate memory locations, then execute the code. This technique, known as self-modifying code, is quite common, and not that difficult with a bit of care.
The following routine accepts the low byte and high byte of the message address in the Y and Z registers, and prints the message until it encounters a 0 byte. It relies on the knowledge that the lda $0000,x instruction assembles to three bytes: one for the instruction code, and two for the address. It uses the X register as before, but this time it tests whether X wraps around from 255 to 0, then increments the high byte of the address and continues printing. This gives us a maximum message length of 65,535 characters, which is more than enough.
Another useful KERNAL routine for printing is the plot routine, at $FFF0. plot can do two things: it can either move the cursor to given coordinates, or it can report the coordinates of the cursor’s location. You use the carry flag to choose between the two actions. To move the cursor, clear the carry flag (clc), then set the X register to the row number and the Y register to the column number.
To ask plot to report the current location, set the carry flag (sec) before calling it. Instead of changing the cursor position, plot will overwrite the values in the X and Y registers with the current cursor location.
A word of caution: When the KERNAL print system prints a character in the bottom-right corner of the screen, it assumes that more text needs to appear on the following line, and scrolls the text display to make room. When plotting characters for game graphics, this probably isn’t what you want. A simple albeit unsatisfying way to avoid this issue is to never print a character in the bottom-right corner.
Also notice that X and Y refer to the CPU registers, but not the names of the coordinate axes! The X register stores the row number, as in the coordinate position along the vertical axis. The Y register stores the column number, along the horizontal axis. This is how Commodore designed it originally, and it hasn’t changed in decades. Below, I offer a different way to plot characters, and I use X for the horizontal and Y for the vertical, which is swapped from how plot does it.
You could make a robotfindskitten game using just the KERNAL print system: use plot and chrout with PETSCII codes to draw items, and erase and draw the robot character as it moves across the screen. Most games don’t use the KERNAL print system to plot characters at all. Instead, they write directly to screen memory, color memory, and registers in the VIC-IV chip. This avoids issues like the KERNAL scrolling the text display, at the expense of doing other things manually, such as calculating memory locations for screen coordinates, and managing character attributes and colors.
If your program uses the KERNAL print routines, it’s best to let the KERNAL manage screen memory as much as possible. The KERNAL uses internal variables to keep track of some screen properties, and these need to be consistent with its own understanding of the state of the video hardware. If you change the screen mode or relocate screen memory via VIC-IV registers without telling the KERNAL, actions performed by PETSCII codes, such as clearing the screen, may not function correctly.
Handling screen memory is an essential skill for assembly language programmers. It’s also a deep topic. So let’s limit this discussion of screen memory to a few salient facts. To tell the KERNAL to set the screen mode to 80 x 25 text, print the Escape + 8 key sequence with chrout, as if you were typing it at the READY prompt:
If you’re not using the KERNAL, you can select the screen mode with flag registers at location $D031. To get 80 x 25, clear the V400 register (bit 3) and set the H640 register (bit 7). Without the KERNAL, you will need to write your own message printing routines that write directly to screen memory; you can’t use chrout.
The starting address of screen memory is in a VIC-IV register known as SCRNPTR, a 28-bit value stored at $D060-$D063, least significant byte first. The KERNAL will set this when you print the escape sequence for the screen mode. If you’re not using the KERNAL, you can set this to any address you like in the first 384K of memory by writing its address into the registers.
The KERNAL’s preferred memory location for a 40 x 25 or 80 x 25 screen is address $0800. Strictly speaking, this is not a documented fact: a program that relies on the KERNAL’s setting must read it from SCRNPTR, and never assume its value. For propriety, the examples below will read the SCRNPTR value instead of assuming it, but—at least for now—I’m also relying on the fact that the address is within bank 0 (addresses $0000 to $FFFF) so we can use 16-bit addressing modes and don’t have to worry about accessing upper memory. Note that this won’t work with 80 x 50 text mode, because the KERNAL relocates screen memory to bank 1 for this mode.
As with BASIC’s T@&() special array, screen memory contains screen codes that represent the characters in the character set. The codes are organized in columns then rows, from top-left to bottom-right: the first 80 bytes are the top row, the next 80 bytes are the next row, and so on, for 80 x 25 = 2,000 bytes.
The following example uses the self-modifying code technique to store a value in screen memory. The sta instruction can only operate on 16-bit addresses, so it uses the lower two bytes of SCRNPTR, and assumes the upper bytes are zero (an address in bank 0).
In the regular text mode, color memory stores the foreground color and attributes for each character on the screen, organized in the same way. One way to access color memory is starting at address $D800.
There’s one issue, though. By default, only the first 1K of color memory is visible here, from $D800 to $DBFF. That’s not enough for all 2,000 characters of a 80 x 25 display! This is solved by yet another of the MEGA65’s many modes. The CRAM2K register, bit 0 of $D030, swaps the registers from $DC00 to $DFFF with the remaining color memory. To do this, it hides other hardware registers normally at those locations, such as the CIA chip registers. The KERNAL expects to see the registers here and not color memory, so you must clear the bit before calling KERNAL routines. (The KERNAL IRQ is smart enough to stash and restore your CRAM2K setting, so you do not need to disable interrupts. That’s a topic for another time.)
Given screen coordinates of column X and row Y, the offset into screen memory for that coordinate is Y times 80, plus X. The CPU doesn’t have an instruction that can multiple any two numbers, but it does have a quick and easy way to multiply a number by two: it can shift the bits of a number to the left, using the Arithmetic Shift Left instruction (asl). If it’s not clear that shifting the bits of a number to the left multiply it by two, write out a binary number, then write a zero at the end. For example, the binary number %0110 is 2 + 4 = 6 in decimal. Write a zero at the end, and it becomes %01100, which is 4 + 8 = 12 in decimal. Just as writing a zero at the end of a decimal (base ten) number multiplies the number by ten, writing a zero at the end of a binary (base two) number multiplies it by two.
Using a combination of left-shift and addition operations, we can calculate the screen memory address for a given set of coordinates in three steps:
To update color memory, the only difference in this routine would be to use a different base address, and set CRAM2K while updating memory. I added a do_plot label above so I could share the common code between the two routines.
Each machine code instruction that accesses memory can operate in one or more addressing modes, ways for the CPU to figure out what address to use. We’ve seen three addressing modes in the examples so far:
Immediate mode: use the value given in the instruction. This example loads the number 7 from the instruction into the accumulator:
Absolute mode: use the 16-bit address given in the instruction. This example loads the value stored at address $20CF into the accumulator:
Absolute X-indexed mode: take the given 16-bit address, then add the value from the X register to it, and use that as the address. This example sets the X register to $2F, then loads the value stored at the address calculated as $20CF plus the value in the X register ($20CF + $2F = $20FE) into the accumulator:
The X register can contain a value from 0 to 255, which limits the range of the X-indexed addressing mode. Earlier, I used self-modifying code to get around this problem, allowing for performing calculations on the entire address. The following example rewrites the 16-bit address portion of an instruction that’s using absolute mode addressing, then executes the modified instruction:
Writing the address directly into an instruction like this is only really practical if only one instruction needs the address, and the modifying code knows exactly which address to modify. In many cases, it’d be better if we could store the address in one memory location like a variable, then tell the instructions where to find it.
Base Page Indirect Addressing mode can do exactly that. This example stores a 16-bit address at memory location $10-$11, then accesses it using the Y register as an index:
So why didn’t I do this earlier? Well, there’s a catch: the address must be written to the base page, a region of 256 bytes that gets special treatment. Commodore 64 programmers know this as the zero page, within the addresses $0000 to $00FF. The CPU uses special forms of its instructions to access these addresses faster and with more compact code than absolute 16-bit addresses, so the base page is a great place to put variables. It’s so useful, in fact, that the KERNAL claims all of the zero page for its own use. If your program uses the KERNAL, you must protect the zero page so that it’s the way the KERNAL left it by the time you call a KERNAL routine.
With the original 6502 CPU, the base page is always at address $0000 (hence the name “zero page”). The 65CE02 CPU (on which the MEGA65’s 45GS02 is based) adds a feature that lets you use any 256-byte page of the first 64K of memory as the base page. The B register holds the top two nibbles (two hexadecimal digits) of the address of the base page. Your program can stake out its own base page and set the B register to that location to use it. I recommend page B = $16 ($1600 to $16FF), which is reserved for use by your program.
You must change B back to $00 before calling a KERNAL routine. The base page being set to $00 is a pre-condition of all KERNAL routines. (The B register is preserved along with other registers during interrupt handling, so you don’t have to worry about confusing the KERNAL IRQ.)
To set the B register, put the desired value in the accumulator, then use the tab instruction (Transfer A to B). If you need to read the B register, transfer it back to the accumulator first, with tba. The requirement to go through A to set or read B sometimes requires a bit of register wrangling.
Another register consideration to keep in mind: Base Page Indirect Addressing always uses an index register. The lda instruction supports using the Y or Z registers as indexes for this mode. If you just want to use the address directly, you must set the index register to 0.
Here’s another version of the long message printer using Base Page Indirect addressing, preserving the zero page for the KERNAL and using page $16 for the program’s base page. Try to follow which register has which value:
This is not necessarily better than the earlier version using self-modifying code, especially with all the register flipping required. But it illustrates the use of base page variables as address pointers.
The 45GS02 CPU has another Base Page Indirect addressing mode, and it’s super useful: 32-bit Base Page Indirect Addressing lets you use a 32-bit address instead of a 16-bit address. With the Acme assembler in MEGA65 mode, this is indicated using square brackets instead of parentheses. Only the Z register is supported as the index in this mode.
Notice that other addressing modes do not support 32-bit addresses, so we can’t use the self-modifying code method to access upper memory, at least not in the same way. We can adapt the second version of the printing routine to be able to print long messages from anywhere in the MEGA65’s memory with minimal changes, but we can’t adapt the first version as easily.
Earlier, I made a potentially unsafe assumption that the KERNAL used an address between $0000 and $FFFF for SCRNPTR in 80 x 25 mode, and I just ignored the upper bytes of the SCRNPTR address. With 32-bit base page indirect addressing, I don’t have to do that: I can just copy the entire address from SCRNPTR to a four-byte base page variable, then use 32-bit indirect addressing to access screen memory.
Incidentally, upper memory addresses $1.F800 through $1.FFFF are another way to access the first 2K of color memory, with no need to set the CRAM2K flag. In my implementation of robotfindskitten, I use base page $16 for variable storage, and base page indirect addressing for plotting characters with the full four-byte SCRNPTR address and for plotting colors to 1.F800. I set the B register to $16 at the beginning of the program, and wrap my KERNAL calls to set B to $00 before the call and set it back to $16 afterward.
As you can see, there are multiple ways to accomplish certain tasks. For high speed applications, you may need to make your choices based on the amount of CPU time each operation takes, measured in CPU cycles. Instruction cycle counts are listed in the manual. robotfindskitten is not speed critical, so I just went with what made my code easiest for me to understand.
That’s a good start. With the KERNAL output routines and screen memory access, we have the tools to replicate BASIC’s PRINT, T@&(), and C@&() facilities in assembly language. Next month, we’ll look at another important KERNAL facility for accepting keyboard input, and some snazzy MEGA65 hardware features for generating random numbers and measuring time. We’ll close by designing data structures to access all of the item descriptions, and prevent two items from landing on the same place on the screen.
For comparison and enjoyment, here’s my BASIC version of robotfindskitten. It’s faithful to Leonard Richardson’s version, which is not particularly creative of me, but hopefully it serves as a useful reference implementation.
Happy coding! See you next month.
— Dan
robotfindskitten, part 1. Dan’s MEGA65 Digest for October 2023.
A new month, a new feature, a new game, a new demo, and a coding exercise that really brings the room together. Let’s dig in!
My new Linux PC for building MEGA65 cores.
We’re getting closer to having a complete release candidate, with features being finalized and bug fixes piling in. There’s one new feature that’s near and dear to my heart, and I’m thrilled to be able to share it with anyone up for early beta testing.
The very first thing I noticed when I got my MEGA65 is how the typing experience felt nostalgic. Even with the new mechanical key switches and the 40 MHz CPU, the ability for the computer to recognize key presses felt exactly like a Commodore 64 did back in the day: sluggish and imprecise. I like nostalgia as much as anybody, but I type much faster today than I did when I was nine years old. I wished my MEGA65 could handle fast typing more like a modern computer, so I could enjoy on-device composition without slowing myself down. It was one of the first feature requests that I filed with the MEGA65 team.
Paul and company started working on an idea for fast typing, and an early version of the chipset support required made it into the core last year. The feature wasn’t wired up to the KERNAL ROM, and only a few built-in applications used it. I brought it up again with the team this summer, and we had many design discussions and tried several ideas. I learned a bit of FPGA coding, and even built a high-speed Linux PC just to build and test new cores and ROMs.
I’m proud to present the all-new MEGA65 hardware-accelerated keyboard scanner. Using the latest development core and ROM beta release, you can now enjoy a typing experience that is more accurate and more reliable for fast typists throughout the BASIC screen editor and many applications. These changes will be in the v0.96 release, and you can test it today and file any bugs you find. I also wrote a test plan and detailed description of how it works.
I plastered this all over the instructions, but I’ll repeat it here: the latest ROM beta versions (920387 or later) require the latest development core. If you use the newer ROM with an older core, typing won’t work. You can safely use older ROMs with the newer core, so you can revert to the legacy keyboard scanner at any time if you encounter any issues just by going back to an older ROM (920386 or earlier). Also, the latest ROM betas will not work with the Xemu emulator until emulation for the new core feature has been added (hopefully soon), so stick with 920386 or earlier in Xemu for now.
For me, the difference with the enhanced typing quality is like night and day. On-device programming and other typing applications are much more usable, and I just enjoy using the computer much more, confident that I won’t have to struggle with missed keystrokes. Try it out, and let me know what you think!
Classy, by deathy.
Classy, by deathy, is a new match-3 game for the MEGA65. Careful with this one: it’s addictive! A joystick in either port or the keyboard sets you on your tile swapping journey. If the game is still running, it means you still have moves remaining. Keep looking!
MEGApple, by MirageBD.
The MEGA65 gets its Bad Apple!!
MEGApple is MirageBD’s MEGA65 version of the popular demo challenge: recreate the shadow-art music video of the Japanese pop song, “Bad Apple!!” The original video was a collaboration of animators on the Japanese website Nico Nico Douga, based on the pop remix by nomico of a track from the video game Touhou Fantasy Land: Lotus Land Story. Over a decade later, it persists as a popular meme to recreate the music video in unusual media, including (but not limited to) retro computers.
To run MEGApple, download and expand the archive, then copy the files to the root of your SD card. Start your MEGA65, then type: MOUNT "MEGAPPLE.D81":RUN "*" The program on the D81 disk image loads the data from the other larger files.
Xevious (1982).
muse has a new arcade cabinet core for us! Xevious (1982) and Super Xevious (1984) are early vertical scrolling shooter games by Namco. Fly your Solvalou starship over the planet’s surface to stop the Xevious forces by both land and sky. muse’s version supports a one-button joystick with a clever adaptation: press the button quickly to shoot at airborne enemies, and hold the button to drop bombs on turrets.
As with the Galaga core, the installation instructions include searching for and downloading the original Xevious ROM files, running a Python script to validate the files and prepare a folder that you copy to your MEGA65’s SD card with the path /arcade/xevious, then installing the core in an available core slot. See the Discord announcement for additional notes.
“Yet another zen simulation.”
In robotfindskitten, you are a robot, who finds a kitten.
robotfindskitten was originally written by Leonard Richardson in 1997 for DOS, as his submission to the robotfindskitten contest put on by the webzine “Nerth Pork.” It took first prize. There were no other entries, but there didn’t need to be. The theme had found its perfect expression on the first try.
In the decades that followed, many have made their own versions of the simulation, on many interactive platforms. And now, it is your turn.
Richardson’s version depicts the robot with a single colored ASCII character on a monospaced field that spans the screen. The field is populated sparsely with other colored ASCII characters that represent many Non-Kitten Items (NKIs), and one kitten. To the robot, all items, including the kitten, appear as random colored characters. The operator uses cursor keys to move the robot around the field. When the robot comes into contact with an item, a message is printed describing the item. If the item is the kitten, the experience ends in joyful celebration.
You can play robotfindskitten in your browser. Or, you can install a version for a modern terminal for Linux (sudo apt install robotfindskitten) or macOS (brew install robotfindskitten) or many other platforms. (Some versions are survived only by their archived screenshots.) Or you can build the Linux version from source. Or you can check out the Ultimate robotfindskitten Fan Site, by Leonard himself.
Or you can make your own. Here are some techniques that you might use to rise to this challenge in BASIC 65. Next month, we’ll look at how to do similar things in assembly language.
You will need to control what is displayed on the screen, so the operator can see the robot and the items.
To clear the screen of all text, you can use the SCNCLR command. To set the color of text to be printed (from 0 to 31): COLOR number. Similarly, to change the color of the border or background: BORDER number or BACKGROUND number. To set the position of where the next text will be printed: CURSOR column, row. To print a string of text at the current cursor position: PRINT string.
One word of caution with PRINT: if the string you are printing extends beyond the right edge of the screen, the screen below that point will scroll down by one line. This probably isn’t what you want in this exercise, so take care with the length and position of your strings.
To plot a single character at a set of coordinates, you can assign the screen code of the character to the T@& array, and its color to the C@& array. These are two dimensional arrays, with the first index referring to the column and the second index referring to the row. T@&(0,0)=1 plots the letter A to the leftmost topmost position. (1 is the screen code for the A character. Notice that screen codes are not PETSCII codes.) C@&(0,0)=5 paints it green. You can read screen codes and colors from these arrays as well: IF T@&(0,0)=1 THEN ... and so forth.
Recall that PETSCII codes in strings give you further control of the display via the PRINT command. PRINT CHR$(14) switches the display to the lowercase character set. Be aware that not all PETSCII graphics characters are available in the lowercase set.
Here is a short program that clears the screen, switches to lowercase, and plots all of the available screen codes:
To accept keyboard input, use either GET variable or GETKEY variable. These both take a variable name as their parameter. Given a string variable (such as A$), the key being pressed is loaded into the variable as a single-character string. Given a number variable (such as A), it is loaded as a PETSCII code. GETKEY pauses until a key is pressed. GET will not wait: if no key is pressed, it assigns an empty string or a zero, and moves on. If you want GET or GETKEY to provide the PETSCII code as a number, be sure to use a byte type variable, so that the number is in the range 0 to 255: GET K&.
Alternatively, you can accept joystick input using the JOY() function. The function takes the port number as an argument (1 or 2), and returns a number 0 through 8 indicating the state of the joystick. 0 says the joystick is centered. All other numbers indicate a direction, starting with 1 for “up” and going clockwise: 2 for “up-right,” 3 for “right,” and so forth.
The items are assigned random characters, colors, and positions, so you’ll need a way to generate randomness. The RND() function generates numbers using a pseudo-random number generation algorithm. The function takes an argument that determines the “seed” for the algorithm. For most purposes, an argument of 1 suffices: RND(1). The function evaluates to a random fractional number between 0 and 1. To generate numbers within a range of integers, multiply the result by the size of the range, then take the INT() of the result to lop off the fractional part. INT(RND(1)*80) generates a random integer between 0 and 79.
If you want the range of possible values to start at a value other than zero, do the inner multiplication by the size of the range, then add the starting value. INT(RND(1)*77)+1 generates a random integer between 1 and 77.
The following program plots randomly colored random characters when one of the cursor keys is pressed. See if you can figure out what the variables CL, CH, RL, and RH do.
Like the Commodore 64, a positive argument generates a new number based on the previously generated number. Unlike the Commodore 64, the algorithm is initially seeded from the MEGA65’s Real-Time Clock during boot, so you are unlikely to see the same sequence twice with RND(1).
Tip: For RFK, you probably want to prevent randomly selected values from repeating. A simple way to avoid this is to keep track of previously selected values, such as in an array, and scan the array each time a new value is chosen. If it’s in the array, restart the process to pick another value. Once a unique value is found, add it to the end of the array. In my version, I used this technique to avoid two items from appearing at the same location, and to ensure that each item uses a unique PETSCII character and a unique description.
To animate the joyful celebration at the end, you’ll need a way to pause between frames of an animation. The SLEEP seconds command pauses the program for the given number of seconds. The number can be fractional.
Each Non-Kitten Item in robotfindskitten gets assigned a description at random when the item is created. One way to put a large list of descriptions in a BASIC program is with DATA statements. These statements don’t do anything when encountered by control flow. Instead, they make values available to the READ statement, which finds the next unread value and puts it in a variable.
A traditional BASIC technique is to read the number of elements from the first DATA statement, DIMension an array of that size, then READ that many elements into the array. The program can then access any string from the array by its number index. This is a bit wasteful. It keeps two copies of the list in memory: one in the BASIC program listing, and another in variable memory. It also introduces a delay at the beginning of the program to load all of the elements into the array. The primary advantage is that each element can be accessed instantly by index.
In BASIC 65 (and BASIC 7 for the Commodore 128), there’s a better way: use sequential line numbers for the DATA statements, then use the RESTORE command to set the READ pointer to a given line number. RESTORE accepts a number expression for the line number, so you can select a string programmatically by number.
A DATA statement has a special syntax to allow for string values that contain almost any character: values are separated with commas, and a value that starts with a double-quote contains every character (including commas) up to the next double-quote. This requires special handling if you want a string value to contain a double-quote character. Because NKI descriptions only use letters, numbers, and punctuation, one solution is to use a special character as a substitute for double-quotes, then replace it in code:
You can use the original list of 406 NKI descriptions, or write your own. The truly patient can type all of these into DATA statements by hand, a zen experience of its own. Or you can use one of these that I made for you:
Your program will have at least a few phases of operation, such as one to decide on the locations and appearances of the items, and another where the player is moving the robot. Each phase will be a section of lines in your program. BASIC executes lines in a given section to produce the experience of that phase. To transition from one phase to another, the program directs BASIC to GOTO a line in the appropriate section.
I based my RFK experience on Richardson’s version, which can be described as four phases:
My program code also ends with the NKI descriptions as a fifth section of data statements. Control never reaches this section, because DATA statements do not need to be performed like other commands. (The READ statement in an earlier section accesses this data.)
One of the best things about BASIC is how it makes it easy to write and test each section separately. To start a section from the READY. prompt, provide the first line number to the RUN command:
You can temporarily add a STOP statement in the program to cause execution to return to the READY. prompt at that point. You can use commands to inspect the state of program variables, such as: ?NK$ When you are ready to resume execution of the program, type the CONT command. You can even assign new values to variables while paused, and it’ll use the new values when you continue the program. Don’t forget to remove the STOP statements when you no longer need them.
As amusing as it would be for everyone to upload their RFK experiences to Filehost, that might not be the most polite use of the site. Let’s do this instead: send me a photo or screenshot of your robotfindskitten experience. I will try to feature a selection of submitted photos in an upcoming issue of the Digest.
If you have any questions about BASIC programming or would like to discuss the exercise, let’s meet up in the #basic channel of the Discord chat. I’m usually there.
Next month, I’ll share my BASIC RFK implementation, and we’ll look at similar tools for making an RFK game in assembly language. See you then!
— Dan
From the publisher's feed