John Carmack take on C code arrangements

John Carmack take on C code arrangements

 

Quake 2 Intro
Screenshot from Quake 2

John Carmack is a major games developer involved with DOOM, Quake and many other titles. Recently some past things he wrote were published and its interesting particular about inlined code.

You can read the piece here, but I’ll just copy a little bit out. Which of these three coding styles do you prefer?

------- style A:
 
void MinorFunction1( void ) {
}
 
void MinorFunction2( void ) {
}
 
void MinorFunction3( void ) {
}
 
void MajorFunction( void ) {
        MinorFunction1();
        MinorFunction2();
        MinorFunction3();
}
 
--------- style B:
 void MajorFunction( void ) {
        MinorFunction1();
        MinorFunction2();
        MinorFunction3();
}
 
void MinorFunction1( void ) {
}
 
void MinorFunction2( void ) {
}
 
void MinorFunction3( void ) {
}
  
---------- style C:
 
void MajorFunction( void ) {
        // MinorFunction1
 
        // MinorFunction2
 
        // MinorFunction3
 
}

If you look at the source of Asteroids, you’d probably notice I’m more of an A or B person. I do like readability. Though if you looked back at the assembler code I wrote 30 odd years ago, it was not very modular. I used functions very rarely back then. In those days, you had to do a lot of tricks like unrolling loops to get that extra bit of performance. Now, it’s not quite as important and I’m happy to make it readable.

Timing of SDL vs TTF fonts

Timing of SDL vs TTF fonts

TimingsSo I got round to writing that SDL vs TTF timing comparison. However I had to make a few assumptions. The program was written for Windows but easily converts to Linux (apart from the timing code but I did that back in March for Linux) is about 250 lines long. I’ve uploaded it to GitHub, and the zip file contains not only the VS 2019 project and source but all the SDL2 dlls plus a free font MONOFONT.TTF (renamed to font.ttf) and test.png which is the bitmap font as a .png file.

Note you’ll have to edit the sdlttf.c file and change the paths to load the font .png and ttf files in lines 96 and 97.

I’d never used SDL_ttf before though it worked out easy enough. There are three levels of TTF – fast, not so fast and slow but pretty. I went for the fastest setting. The SDL text is in red and the TTF in yellow and are roughly the same height about 30 points.

If you read the caption you’ll see that my bitmap font drawing (I call it SDL) is nearly 14 x slower than TTF. In my code I prerendered the phrase “Sphinx of black quartz, judge my vow” which has all 26 letters a-z but is shorter than standard phrase “the lazy quick fox…”.

SDL_ttf renders the phrase into a surface which is a memory structure in RAM. Calling SDL_CreateTextureFromSurface (line 188) creates a texture from this (it copies the bitmap from RAM to VRAM) and so in my program I was just blitting this texture to the screen. The SDL printing in the print function (Line 157) gets each character, and calls printch (line 143) which works out where in the textFont texture that character and blits it. I’m guessing the overhead of blitting individual characters is what makes it so much slower.

So for fixed phrases where you can prerender the surface and texture, SDL_ttf is way faster and more flexible with colour and to a certain extent size. Colour is set at runtime while size is set when you prerender the font into the surface. If you want different sizes then you need multiple surfaces and corresponding textures for each size. Things like say a score would be a bit slower because it would need to be rendered each time and copied to a texture or prerender all 10 digits and have a texture for each and draw it much like the print method does.

The program is a little rough in places; it was thrown together over three nights.

Learning C and SDL

Learning C and SDL

Learning
Image by Gerd Altmann from Pixabay

I frequent the Reddit C subreddit and Quora.com and quite often see people asking what they should learn first. So I’ve updated the C tutorials page (link at top) with details of future tutorials as well as a new one on functions. This includes the entire course (though some are not yet written).  It has more details about each lesson and shows the whole course,

There’s considerable overlap with material in my first EBook though that was for Windows only and this is for Windows, Linux and Raspberry Pi. The Pi of course is Linux with some hardware specific stuff and I’ll include links back to previous blog entries which have explained how to get and display the Pi’s temperature in a C program or use game pads.

Unlike other C courses it will include SDL2 code and how to use it. I think C + SDL2 is a great way to make 2D games, and is probably the easiest and simplest to learn.

 

Could Flash make a comeback?

Could Flash make a comeback?

Ruffle Flash EmulatorBack in the day (2011) I did a bit of Flash game development. It was a curious technology compared to what I was used to. It was originally a way of scripting graphics and other media but really took off when ActionScript, a programming language very much based on JavaScript was introduced.

Unfortunately the twin combination of insecurities in the Flash player’s on PC and refusal by Apple to allow it on iPhones killed it. It took a few years to die and HTML5/JavaScript became a slightly inferior replacement. There were 100s if not thousands of Flash games on websites like Kongregate.com. There are still many games there and on other similar aggregator sites.

But a lot of developers really enjoyed creating Flash games and there have been a few open source emulators. None in C, but at least one in C/C++ and more recently Ruffle (in Rust).  The image is a screenshot from one of the demo games.

What’s different now apart from still not running on mobile is that the “Flash” players are more secure and in this case use WebAssembly for browsers. WebAssembly is seen as the future of browser games and whether it’s by compilin g C/C++ or Rust programs directly into WebAssembly or by using Flash games and animations transformed via programs like Ruffle into WebAssembly, I suspect that the browser will become an increasingly important platform for WebAssembly games.

Talking of which as well as Emscriptem for turning C/C++ with SDL) into WebAssembly there is also Cheerp, an open source and commercial C/C++ compiler that produces WebAssemb;y. I really have no excuse for not producing a WebAssembly version of Asteroids!

The joys of SSL certs

The joys of SSL certs

Certificate ass u meThere’s a saying “Don’t assume- it makes an ass of U and me“, and I er fell foul of this a month ago. A couple of months ago I setup a cheap VPS. It was one of those that you pay every month. What I didn’t realise was you are explicitly meant to renew the hosting every month and they send you an email with a link. Of course what did I do?, I er forgot to renew it. Annoyingly, I’d installed Virtualmin, redirected a domain and bought a cheap SSL certificate. All lost.

Now I actually did something right and there’s a lesson here. When you setup a SSL certificate, you create a CSR (Certificate Signing Request) and a Private key. You upload the CSR, pay your money (£20 for four years) and get a certificate back. The hosting companies I’ve used provide a SCR creation facility and somewhere to paste the private key and certificate when you get it. Then you click a button and your website now has a working SSL. It couldn’t be easier.

So luckily for me I had made a backup copy of my private key and was able to download the certificate. I’ve setup a completely new VPS, redirected the domain and very nervously pasted in the cert and private key. It worked. I had been bothered that the CSR was generated on a different server but it doesn’t seem to matter. So long as you have the private key the certificate works on a different server.

 

Drawing  dungeon rooms using characters

Drawing dungeon rooms using characters

Some roguelike roomsThe final game will use graphics but those graphics will be based on characters, so I’ve started off by drawing a room or two using the provided extended ASCII characters.

Here for example is an 8 x 8 cell room with four inner columns and four possible doors. I’ve used spaces in one and full stops in the other to see which looks better. I think I prefer full stops as you can count them but it’s not a big difference.

╔════╬═╗  ╔════╬═╗  /----\
║      ║  ║......║  |....|
║ ╬  ╬ ║  ║.╬..╬.║  #....|
╬      ╬  ╬......╬  |....|
║      ║  ║......║  \.||./
║ ╬  ╬ ║  ║.╬..╬.║
║      ║  ║......║
╚═╬════╝  ╚═╬════╝

The 3rd room is smaller and roughly octagonal though not as nice looking. I used the normal ASCII characters for that with the two slashes ( / and \ ) as well as # for a vertical wall door and two | for a double door. Here’s a corridor that goes round two corners and then meets another one.

═══     ╔════╦══
   ╚════╝    ║

There are plenty of ASCII character charts and I used this one which describes all the graphical chars making it easy, albeit a bit tedious to draw these in any text editor. There are single box characters as well as the double ones I’ve used. The ╬ character has proved very versatile as it provides not only columns but doors in both horizontal and vertical walls.

It’s noticeable that despite this room being square, it looks rectangular thanks to characters being taller than wide. Also in WordPress, the gaps between lines are more noticeable as gaps whereas in Notepad++ (the editor I used to create these) as shown in the image at the top, these gaps are absent.

How to make a game with QR codes

How to make a game with QR codes

Example.com QR codeThis follows on from yesterday’s post about creating QR Codes. How about creating a web game similar to the Choose Your own Adventure type games but with a difference? I did think about implementing this as a proof of concept and may yet still but ideas are worthless until executed so I’m happy to put this out there. Here are a few notes on a proposed web QR game.

  1. You can get open source QR generators for PHP, C#, probably most programming languages.
  2. The web pages show one or more QR codes with a title on them. These are actions and by opening the URL (say in a QR reading mobile app) the action applies. Eg Go West into a room, open a chest etc.
  3. If you use an 8 character parameter to the URL that gives you something like 2.8 trillion different destinations. eg example.com/r/h65tr321.  The idea is that the web application generates a page from this parameter. If the parameter has been spoofed then you fall into a bottomless cavern, get eaten by an Ice Worm etc and start again. These parameters are generated anew for each game.
  4. You can add extra information such as carrying items with extra characters. Unlike web games, there only way to pass information is via the url. So the URL might now be example.com/r/h65tr321a6. (the QR code shown is for this url) The page would still be created from h65tr321 but the a6 might mean you are carrying say a sword and key. If you add on a character to the query for each item, you can have 36 different types of item using a-z and 0-9.
  5. The whole adventure is created as a list of rooms, each with a description. A random eight character code is generated for each room. That’s where the h65tr321 comes from. At the start this list of rooms is read into the web application.
  6. Puzzles are of the blocker type. To open a door that lets you escape you need to be carrying a key but that’s in a chest protected by a Dragon. You can fight the Dragon but only if you have the sword and the Dragon will always kill you unless you are carrying a potion of extra hit points. So first you have to explore the rooms, going from room to room and picking up items. But you can only carry three items at a time. You can either use or drop an item which stays in the room where you dropped it.
  7. Every room you enter when carrying items displays each items with a use and a drop QR code.
  8. Other ideas include a time element that reduces each time you move rooms/do an action. You only get so long to escape but a potion that can be used once adds more time.

As you can use any app to scan a QR code and jump to the url, it would be a bit tedious to play but might make for an educational project for teenagers or schoolkids.

It should be possible to build an app might be able to detect the QR codes automatically and display just the link text. Again like QR generators code there are open source packages for reading QR codes.

 

 

Such simplicity- online QR generator

Such simplicity- online QR generator

QR code for Learncgames.comSometimes you come across a design that is sheer simplicity, could not be easier to use and it just works. That QR code you will not be surprised takes you to this very website!

The website that I got it from is simpleqr.xyz. Just paste or type in your URL and a QR code appears before your eyes.

This is slightly off-topic for this site and no its not an advert – just a recommendation of a useful website. The thing is QR codes are quite complex (understatement).  This is quite a nice visual description.

This however is a very detailed explanation of how to create a QR code in 10 steps and I wouldn’t be surprised if its the method used in simpleqr.xyz.

I remember seeing this explanation a few months ago and no I don’t have a perfect memory. Instead, many of the websites I’ve found are through hacker news. Even better though is this search engine that searches hacker news. I used it to find that QR website.

There are innumerable free QR apps on smartphones so good ahead and verify the QR code!

There’s an elegance about QR codes though it’s not exactly steganography (hiding data or images inside something else) but the fact that you can’t understand it without an app is quite clever. I had an idea once of making a Choose your own Adventure EBook using QR Codes to navigate around a website.

Text and URLs

QR codes can hold a lot of information. Would you believe it if I told you that the QR below has all this blog text (about 230 words) up to the Text and URLs title at the start of this paragraph? Try it!

Also I compressed the PNG file but it still works perfectly. Here’s a screenshot of the QR app that scanned it.

Blog entry QR code

iPhone QR Scan

 

 

 

A first-person-shooter in 32KB

A first-person-shooter in 32KB

Anarch FPSDon’t expect this to be Call of Duty standard but then those games typically have a 50GB or higher footprint on disk. Anarch comes with 10 levels, 6 weapons, 7 enemy types and 3 ammo types and runs in 200 KB of disk space and runs in 32KB RAM. It’s 100% C but doesn’t use any FPU, GPU or file I/O. It’s old skool 90s style.

If you’ve played original Doom you’ll have an idea what it’s like.

Interestingly, the creator has put everything, source code, graphics etc into the public domain which is a very philanthropic gesture. So if you want to understand how to write a FPS (first-person-shooter) in C, take a look. You can even play it in a browser.

I’ve added this to the C Code links page (on the top menu).

 

Back on the Raspberry Pi

Back on the Raspberry Pi

Pi Asteroids DevelopmentIt has been a few months since I last used it and as you’d expect, it took a little bit of time and effort to get things back to what they were.

I’m pretty good about backing things up and it took about 30 minutes to burn a new SD Card, update it, install VS Code and the C/C++ extension, then copy my asteroids version over. I use WinSCP so had to enable SSH on the PI. It’s disabled by default but just tick a checkbox on the interface tab of the Preferences->Configuration menu.

Even then it didn’t compile. Of course I had to reinstall the dev versions of SDL, SDL_image, SDL_mixer and SDL_ttf and the clang compiler. Still it didn’t compile. I had created a Projects folder and created an Asteroids folder underneath that. I also had the Vs Code JSON files that you need for compiling C/C++. the main one of which is tasks.json. Those were in a folder .vscode which I had backed up but I’d copied it over into the wrong location. You want it located inside your VS Code folder.

This makes sense. If you have say five different projects then you are going to have a different build, link stuff per project. So you’ll have a unique .vscode in each folder. When you want to switch projects, you just close the Folder in the VS Code File menu and open it in the folder for the project that you next want to work on.

Mind you it still wouldn’t compile. It turned out my tasks.json has clang-6 in it. When I did a clang –version on it, it told me it was clang 7.0.1. So I upped it to clang-7 in tasks.json and that fixed it. It all compiled and ran.

Once you’ve done this a time or two it becomes 2nd nature but I can understand novices frustration; there are a lot of moving parts that all have to be right before you can even write and run C code. It’s not like other programming languages are really any better though. If you have setup virtual environments in Python and installed Python modules, you’ll know what it can be like.