Month: December 2020

SDL-TTF now on Raspberry Pi

SDL-TTF now on Raspberry Pi

Raspberry Pi screenshotI eventually got the Windows SDL vs TTF comparison program converted to run on Raspberry-pi, after wrestling with VS Code’s Folder. Get it wrong and you can waste hours trying to get it to compile and link. I originally set the Folder (VS Code’s way of managing projects) to the pi/Projects folder (which contained both asteroids and sdlttf folders) but eventually I sussed it and set sdlttf as my Folder.  The login user is pi and so the pi folder is my home folder. I created the Projects folder under it.

This time the home brewed print routine (print) took 28x as long as the SDL_ttf compared to 14x on Windows. I used the same text.png and font.ttf files. The times are in the Window caption and read (for those with poor contrast) sdl: 35538.574 ttf: 1235.630. These times are the microsecond times to draw the strings 100x.

Changes were fairly minimal. I changed the fopen_s to fopen (used for error logging and changed the paths to the two font files. The other change was in the timing which used the Linux versions of hr_time.h/.c and called the diff() function instead of GetElapsedTime().

I’ve zipped up the source file (sdlttf.c) plus timing files and JSON config files for VS Code in the sdlttf_pi.zip file and put it in the LearnConLinux repository on GitHub.

Note I created a projects folder then sdlttf under that. The paths in tasks.json reflect this. To build this you’ll need libsdl2-dev,libsdl2_image_dev and libsdl2-ttf-dev installed. I used clang version 7 (the default installed on pi when you do sudo apt install clang) but I imagine gcc should also build it without any problems.

This matches my conclusions from running the virtually identical Windows version. The sdlttf way is way faster for prerendered strings than my print routine which just blits the characters out of the font bitmap one by one.

 

PagedOut a technical programming magazine

PagedOut a technical programming magazine

PagedOut Issue 1 frontcoverIt’s not often that I recommend somebody else but when I see something that I think deserves it, I’m happy to. PagedOut is a free experimental (one article == one page) technical magazine about programming (especially programming tricks!), hacking, security hacking, retro computers, modern computers, electronics, demoscene, and other similar topics. That’s their description! It’s published by Gynvael Coldwind, an IT Security engineer at Google.

It isn’t game related and not totally C oriented. In fact there are currently only two issues out, downloadable as PDFs and the second one has half a dozen C articles but the first issue has none.  There’s a bit of C++, Python, Go and some other stuff including assembly and the content varies enormously and is mostly Linux oriented but there is a bit Windows as well.

The big thing is that each article is just one page long. That’s by design. They accept submissions from anyone, subject to their standards and review but it must fit in one page.

I’ve always had a bit of a hacker mentality going back to when I crashed a mainframe (twice) at University. I didn’t mean to honest….  Being naturally inquisitive I think has helped me as a professional programmer.

 

Networking fun with my Pi

Networking fun with my Pi

Networking
Image by Free-Photos from Pixabay

I lost my main internet for a week due to a power cut that left my main router in a funny state. It had to be factory reset then WiFi SSDs and passwords were reset. My office internet comes down a very long ethernet cable via two switches and a router. I had problems with my router and it got factory reset. Unfortunately I didn’t set this network up and didn’t realise that the network had two routers each doing DHCP and consequently it took a week to get things right. At one point I;d do a ping from my desktop PC and the answer would come back as IPV6, It was totally ignoring IPV4 requests, pings to domains with the -4 parameter were unreachable. Not a fun week.

My Pi which plugs into one of the switches and my desktop PC which also plugs onto the same switch would not talk. Both could see the internet but my Pi could not see Microsoft servers. I’d tried everything, even giving it a permanent IP rather than a DHCP but that can cause issues if the DHCP issues an IP address the same.

I do rather a lot with my PC and the Pi and having them networked is much more convenient than not. I use WinSCP for copying files and Putty if I need to connect in.

In the end, I bottled out and burnt the Raspberry Pi OS on a SD Card and booted from that. One hour later I’d installed all 295 updates and then installed VS Code.

 

An uncensored alternative to GitHub

An uncensored alternative to GitHub

Digital cash
Image by WorldSpectrum from Pixabay

I use GitHub a lot, I’ll be the first to admit it but there have been recent cases where GitHub has censored projects because of the US DMCA law ((I’m in the UK so different laws apply here but GitHub is in the US and being owned by Microsoft is not going to ignore the law) so radicle offers a er radical alternative.

It uses Peer to Peer thus avoiding needing servers which can be seized.  People share a bit of their bandwidth and storage and act as anonymous servers; I suspect you don’t see or have any access to stuff stored on your computer. It uses digital cash so those with lot of bandwidth and storage can do more hosting and receive payment from those who are using it.  I’ve seen Ethereum mentioned for 2021 but I think it uses Electron having looked at the community pages.

Slightly ironically, the project is currently hosted on GitHub!  

Am I going to switch to it? Not yet but in the future, who knows?

Fun with optimisation in C

Fun with optimisation in C

Inner cogs
Image by ar130405 from Pixabay

Bit twiddling with C is quite a common thing but sometimes it can be hard to understand something quite simple.  Here’s a line of code. Can you say what it does? Note that a,b and c are all ints.

c = b ^ ((a ^ b) & -(a < b));

Or how about this which looks quite similar

c = a ^ ((a ^ b) & -(a < b));

The first line puts the minimum of a and b into c, while the second line puts the max of a and b. Both came from a page of bit twiddling hacks by Sean Eron Anderson at Stanford university. The significant thing about these is not that they provide two clever if incomprehensible ways of calculating min and max but they do it without branches.

If you look at the source of min and max in stdlib.h they are defined like this:

#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))

Because modern CPUs use instruction caches (pipelines), they try to keep them full through a technique called branch prediction. If a branch happens then the CPU has to read instructions from the wherever the branch goes to and this causes a pipeline stall which slightly slows down processing. So branchless min and max should run faster than branching code, at least in theory.

I tried it on Windows using a small Visual C++ (Well C) program doing the four in a loop 10 million times. I also ran it in 32-bit and 64-bit.  All runs were done in release mode which lets the compiler optimise.

Curiously the 32-bit took almost no time at all while the 64-bit took a lot lot longer. There wasn’t much difference between branchless and branch. Possibly the code is too small and the benefits of branchless are less significant because the instructions fall inside the instruction cache for 32-bit while 64-bit may be too big and so is affected by instruction cache misses.

This is the 32-bit time.

fastMin 0.0000000
fastMax 0.1000000
Min 0.1000000
Max 0.1000000

And this is the 64-bit. Quite a lot of difference!

fastMin 1757.6000000
fastMax 1677.9000000
Min 2039.4000000
Max 2134.4000000

This is the code which compiles in Visual C++. You can get the hr_time timing code (for WIndows) from the sdlttf.zip file. I increment and decrement a and b to stop the compiler possibly spotting that the values would be invariant otherwise and doing too-clever optimisation stuff.

#include <math.h>
#include <stdio.h>
#include "hr_time.h"

#define NUMLOOPS 10000000
	int a = 1000;
	int b = 67;
	int c;
	double t;
	stopWatch s;

int main() {

	startTimer(&s);
	for (int i = 0; i < NUMLOOPS; i++) {
		a++;
		b++;
		c = b ^ ((a ^ b) & -(a < b));
	}
	stopTimer(&s);
	t = getElapsedTime(&s) * 1000000.0;
	printf( "fastMin %8.7f\n", t);
	startTimer(&s);
	for (int i = 0; i < NUMLOOPS; i++) {
		a--;
		b--;
		c = a ^ ((a ^ b) & -(a < b));
	}
	stopTimer(&s);
	t = getElapsedTime(&s) * 1000000.0;
	printf("fastMax %8.7f\n", t);
	startTimer(&s);
	for (int i = 0; i < NUMLOOPS; i++) {
		a++;
		b++;
		c = min(a, b);
	}
	stopTimer(&s);
	t = getElapsedTime(&s) * 1000000.0;
	printf("Min %8.7f\n", t);
	startTimer(&s);
	for (int i = 0; i < NUMLOOPS; i++) {
		a--;
		b--;
		c = max(a, b);
	}
	stopTimer(&s);
	t = getElapsedTime(&s) * 1000000.0;
	printf("Max %8.7f\n", t);
}

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.