Featured

Coding for the Spectrum Next emulator CSpect

As you can see by my site, I have lots and lots of game development and programming experience https://luckyredfish.com/previous-works/, but I have little or no z80 experience. However, having learned many languages over the years I am sure Z80 is going to be a breeze.

Confession time, throughout my coding I will be using windows as the host system, the code that I post will compile on Linux and Mac but you will have to set up your development environment and choose your own editor.

Lets go!

Firstly, we need to set up a development environment to make our coding life as easy as possible, and having missed out on two Spectrum Nexts from eBay I am having to resort to using an emulator for now.

Emulation

You will need the CSpect emulator which can be downloaded from http://dailly.blogspot.com/.

Once downloaded you will need to extract the contents to a folder on your PC and because I do loads of development on different platforms, I like to keep everything for the platform local, therefore in this case I have a SpectrumNext folder on one of my drives and in there I have created a CSpect folder and I have extracted the CSpect zip into that folder.

In the CSpect folder is a “ReadMe.txt” file with further instructions such as the need to install the Open Audio Library (openAl32.dll) which can be downloaded from http://www.zxspectrumnext.online/. Also in the ReadMe.txt it states that you need a SD disk image from the same page under “distribution images”, the emulator will work without it but having the SD image will make your emulator look like the real Spectrum Next including the nice front end menu, the file browser, more code examples, docs, utilities and more.

Me I used the Win32DiskImager to write the image to a USB stick then just copied the contents of the USB to my SpectrumNext/Sd folder as well as copying the files “enNextZX.rom”, “enNxtmmc.rom” and the “cspect-next-XXgb.img” to the CSpect folder as per instructions. 

Now are we ready?

The CSpect folder contains the emulator along with some demos, source codes and the SNASM assembler which is a great assembler, unfortunately it needs more work to enable us to use it with the DeZog remote debugger but more on that below.

So for now to give the emulator a little test, just double click the “beast.bat” or the “parallax.bat” in the CSpect folder to run one of the demos.

Oh and the “mod_player.bat” runs an audio demo and the “NXtel.bat” is like a teletext demo if they are your thing.

You can also start the CSpect emulator from the command line, and for me using -tv switch to remove the horizontal fake TV lines was a must, so in a command prompt window,  navigate to the CSpect folder and start the emulator using the following line remembering to change the XX to match the disk image you downloaded earlier.

“CSpect.exe -w3 -zxnext -nextrom -tv -mmc=.\cspect-next-XXgb.img” 

If these have all gone well and you have seen all the Spectrum Next goodness on your PC monitor, it’s now time to get down to business of setting up your development environment. As mentioned before I like to keep everything local, which means my whole project, including the art, sounds and code, this makes it easier to back up all at once and to easy to find any assets or code.

Therefore, I created a project structure on one of my hard drives like this: –

Tools are normally not related to one particular project and may be shared over multiple projects. Therefore, they have their own folder on the root of the projects folder and contain such things as photoshop scripts, or even c++ utilities written to manipulate binary data, but more on that in later posts.

Notice that none of the paths have spaces in the names, this is to make life easier when creating batch files or reading directory structures in code. And also notice that the Assets folder contains a subfolder Renders etc, as the project develops each of this folder will contain assets and possibly other folders, each with the asset name as just to make it all easy to organize. And in case you are wondering renders in this project does not mean 3D renders although i will be experimenting with that in later posts, at the moment it means final exported, or composited images.

As i mentioned before we will be using the DeZog remote debugger in order to be able to debug from visual studio code and to make that work we can’t use the snasm assembler, therefore we will be using Sjasmplus.

Sjasmplus

Download the Sjasmplus assembler from here:-

 https://github.com/z00m128/sjasmplus  

Unzip it into a folder named “sjasmplus” again within in the SpectrumNext folder, we will make use of it in a while as we need some other bits and bobs first.

Now we have a compiler now we just need a debugger, and for this we will use DeZog. In Visual Studio Code simply install “DeZog” (maziac.dezog) from the Marketplace and while you are there , there are 3 other extensions that are not required to work with DeZog, but may help your coding experience.

asm-code-lens: Z80 assembler syntax highlighting completions, references, jump to label, renaming

z80-unit-tests: an extension to start/debug unit tests from a graphical UI

and 

z80-instruction-set: shows the opcode, affected flags and a description on hovering over a Z80 instruction.

For those that are interested here is the dev page!

https://github.com/maziac/DeZog

All can be installed from the market place. Also to connect CSpect to the DeZog debugger via a socket you will need the DeZog plug in for CSpect this can be found here

https://github.com/maziac/DeZogPlugin

Unzip and drop the “DeZogPlugin.dll.config” and the “DeZogPlugin.dll” into the root folder of CSpect!

The Code

As for the programming, my source files will be kept in a folder called “Source” again within the project folder, with the compiled results being placed in the “Output” folder and the project files being kept in the root of the project.

For this project I will be using Visual Studio Code as the Integrated Development Environment (IDE) which by the way is pronounced I D E and not ‘ide’ like I heard on you tube a short time ago.

While we are on the subject of programming I have noticed that some developers write multiple lines of z80 code on a single line, that is not my style, as my style is to try and comment my code as much as possible and to make it easy to read a year later when I want to make changes, therefore my code will be each line equals one instruction.

You can get Visual Studio Code from here https://code.visualstudio.com/

Once you have downloaded and installed Visual Studio Code, open your project folder from the File Menu by selecting Open Folder, then choose your project folder in my case it is located at

 F:\SpectrumNext\Projects\MyGameName 

but yours may be different. You should now see your project folder and its subfolders and files on the left-hand side of Visual Studio Code.

Now pressing ctrl + shift + B will build your code, however because we do not have any code of projects set up this will bring up the build menu at the top, so from this menu select “no build tasks to run …”and then select “Others …” at the bottom of that menu.

This will create a new build task file for your project from the default template, creating a new tasks.json looking like this:-

{
        // See https://go.microsoft.com/fwlink/?LinkId=733558
        // for the documentation about the tasks.json format
        "version": "2.0.0",
        "tasks": [
                {
                        "label": "echo",
                        "type": "shell",
                        "command": "echo Hello",
                        "problemMatcher": [],
                        "group": {
                                "kind": "build",
                                "isDefault": true
                        }
                }
        ]
}

Unfortunately Microsoft do not program on the Spectrum next so their template is not what we need, but that’s easily fixed.

We need to modify the tasks.json first, which is is a simple change for the assembler and its arguments, but we all know you will just copy and paste the whole thing, so here are the new contents of the tasks.json file :-

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
                {
    // use the sjasmplus assembler
            "label": "sjasmplus",
            "type": "shell",
    // the command to the assembler and its path has changed
    // and the argument to create a listing file is added
            "command": "F:\SpectrumNext\sjasmplus\sjasmplus.exe", 
            "args": [
                "--lst=${fileDirname}/${fileBasenameNoExtension}.lst",
                "${file}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Next, we need something to compile, so make a file called borders.asm in your Source folder and copy and paste this code into it.

This is my first z80 ever.

// as pointed out by Peter Ped Helcmanovsky, the OPT switches 
// must be indented so please copy this comment as well, which will
// have the correct formatting, also click the Raw button to get plain ascii.
// no copyright patricia dot curtis at luckyredfish.com


                OPT     --zxnext    
                DEVICE  ZXSPECTRUMNEXT                               // tell the assembler we want it for Spectrum Next
                ORG     0x8000
StackEnd:
                ds      127 
StackStart:     db      0        
//              org StackStart
StartAddress   
MainLoop:       ld      a,0                     // black border
                out     ($fe),a        

// Here DE counts down and D and E are OR-ed to check if the loop has completed.

                ld      de,1000                 // loop for 1000 times just wasting cycles
Loop1:          dec     de                      // take 1 off the 1000
                ld      a,d                     // move it to a register we can or with
                or      e                       // or with e to set the flags
                jp      nz,Loop1 

                ld      a,1                    // change this for different colours
                out     ($fe),a         
                
// do another loop wasting more cycles , this time larger band                
                ld      de,2000
Loop2:          dec     de
                ld      a,d
                or      e
                jp      nz,Loop2
// do the whole thing black and blue again and again
                jp      MainLoop
//end start 
// now we save the compiled file so we can either run it or debug it

                SAVENEX OPEN "Output\\borders.nex", StartAddress
                SAVENEX CORE 3, 0, 0                                // Next core 3.0.0 required as minimum
                SAVENEX CFG  0
                SAVENEX AUTO
                SAVENEX CLOSE   

Launch.json

The last part now is the launcher, so make a new file in the root of your project called launch.json and paste this code into it.

{
        "version": "0.2.0",
        "configurations": [
            {
                "type": "dezog",
                "request": "launch",
                "name": "Z80 Debugger",                
                "remoteType": "cspect",      
	// connect to the CSpect emulator via TCIP          
                "cspect": 
                {
                        "hostname": "localhost",
                        "port": 11000
                },
	// for when my next arrives i hope this works
                "zxnext": 
                {
                        "baudrate": 230400,
                        "port": "/dev/tty.usbserial"
                },
                "rootFolder": "${fileDirname}",
                "listFiles": [
                  {
                      "path": "${fileDirname}/${fileBasenameNoExtension}.lst",
                      "useFiles": true,
                      "asm": "F:\\SpectrumNext\\sjasmplus\\sjasmplus.exe",
                      "mainFile": "${fileDirname}/${fileBasenameNoExtension}.asm"
                  }
                ],
                "disassemblerArgs": {
                    "esxdosRst": true
                },
                "load": "Output/${fileBasenameNoExtension}.nex",
                "skipInterrupt": false,
                "startAutomatically": false
            }
        ]
    }

Alexey Glider has pointed out some changes, which I can not test at the present with my set up so please check the comments for his changes!

Yay, that was a bit long wasnt it, but hey, so now you should just have to open the CSpect emulator, and this time with the -remote switch set, remembering to change the XX for your image size.

CSpect.exe -w3 -zxnext -nextrom -tv -16bit -s28 -remote -mmc=.\cspect-next-XXgb.img

Then with the borders.asm file selected (focused and clicked on), then press ctrl+shift+B to build your code and then either click run or press ctrl+shift+d to open the debugger menu and then press the little green arrow start debugging your code.

Part two can be found here

Please let me know how you get on!