Free Programming Books

Free Programming Books

Guide to Scintifc Computing in C++The publisher Springer has made a whole raft of their books available as free downloads and this should last until the end of July. This includes a Guide to Scientific Programming in C++  and Systems Programming in Unix/Linux.

There’s also books on networking, cryptography and more.

Alternatively, if you fancy learning x86-64 Assembly Language Programming with Ubuntu then knock yourself out.  I used to write a lot of assembler (6502 and z80) a very long time ago. It’s a lot easier these days with debuggers.

 

Another mini project – a resource manager

Another mini project – a resource manager

Castle imageIn my ebook I talked about professional games using a resource manager. Games like Quake 2 use a .pak file which stores all images, levels etc. The first stage towards writing a resource manager is to have some way of compressing files. Most graphic file formats such as jpg, gif and png are already compressed. But other files like level files aren’t, typically text and so will compress well.

So a resource manager if it understands the type of resources it is handling can compress or not according to the file type. It will bundle everything into one archive file, and maintain a simple directory indicating where in the archive file each resource file starts, length and type.

However there is the issue of security. The idea of the resource manager is to protect your assets. I have two old games from the Dos days (bought recently on gog.com and playable in Windows)  and a quick glance in the games folder shows some interesting files! That’s one of them shown above. It’s parts of a castle. There are hundreds of graphic files just lying there in the open. They are in an older graphic format (.pcx) but SDL2_image can read those quite happily.

So not only should a resource manager protect your files, it should obscure them so anyone inspecting them with a binary file editor can’t easily spot them.

That brings me to the 2nd point about security. Your program has to be able to use the resources directly from the resource manager rather than say unpack them into a folder on disk. According to this stackexchange answer, SDL2 can do that, so something for me to experiment with.

So I’m starting on a simple and easy to use resource manager. It’ll be implemented as a simple library that provides access to images, text files etc. all loaded from a resource file. And there will be a standalone utility to add, delete and list files in that resource file.

 

A new mini game console

A new mini game console

playdatePlaydate sounds a tad dodgy but is actually a small handheld game console with a 2.7-inch, 400 × 240 screen (173 ppi) and costing $149. It’s due out sometime this year.

The reason I mention it is it runs games written in C (or Lua).  It also comes with 12 games. No mention of what’s inside it (RAM, CPU) though that’s described as ‘beefy’ but it has Wi-Fi, Bluetooth, USB-C, and a headphone jack.

That thing sticking out of the right is a hand crank. No, not for charging the battery but as a game input device. If you create a side-scroller game you can have it scroll one way by cranking in one direction and reverse it by cranking in the other way. Well that’s certainly original!

There will be a development kit available for it and you will be able to write programs for it though at the moment that looks as if its only on a Mac which is a bit of a shame. Oh I have a Mac but I much prefer my Windows PC or Ubuntu.

Compared to the massive screen sizes available on PCs, 400 x 240 sounds a bit small screen size. If you remember the CBM-64 from the 80s, it is exactly the same size as that screen and there were some great games out for it.

I’m excited about this because I believe it could be a renaissance for C Game programming.

My stab at encryption in C

My stab at encryption in C

Encryption
Image by Pete Linforth from Pixabay

This is a little bit off-topic for this blog but hey it’s my blog and it is C code and I will be publishing it in full.  It’s often said that programmers should not write their own encryption software because most programmers do not have the mathematical background.  And I confess that’s me…

However, I thought I’d publish it and put it out there and someone can look at it and say, oh that’s far too easy to break, or maybe not!

The other truism with writing encryption software is that it must not depend upon the algorithm being concealed; the key yes, the algorithm no. So here’s my algorithm.

Generate a 64 byte key. This key has one property, in that it contains each of the 64 numbers 0-63. The order is scrambled. So it might start 0,1,2 but after the bytes have been shuffled (like shuffling cards in a deck) then it might have 43,9,12 and so on.  Think of it as a single row with 64 columns. This 64 byte array must be written to disk. It’s a symmetric cipher, the same key is used to encrypt and decrypt.

Take the plain text and process it in blocks of 8 bytes at a time. Split those 8 bytes into 64 individual bits and write each bit to its own stream. So after processing 64 bytes, each stream has a single byte. Now write these 64 bytes to the file but index the column by the key i.e.

for (i=0;i<64;i++)  
  write(file, data[key[i]]);  

So the first byte written would be data[43] then data[9], data[12] and so on.

So you say, that doesn’t sound very complicated. Are you sure it is encrypted?

Well consider our 64 byte key. There are 64! different ways of rearranging the 64 bytes. If I repeat some of my post from three days ago. “If you could do a million a second, it would take you 1.27×1083 seconds or 4.02×1075 years! Or to make it more meaningful it’s this large! 4.02,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 years. That’s approaching (but still far far off) the time for the heat death of the universe which is estimated at 10100!”

Now I don’t know what methods might be used to crack it. Plus if you have some super-dooper fast hardware that can brute force it, it must have some way of recognising that the decrypted data is correct. If before encrypting it, we do a round of obscuring text, maybe something as simple as xoring the text with a repeating set of values, it’s going to make things a wee bit harder.

I welcome any comments on this and as soon as I have finished testing my program, I’ll put the source code up on Github.

SDL. Surfaces or textures?

SDL. Surfaces or textures?

Screenshot from DominionsWhen I first started on the asteroids game, I did it as a set of tutorials on About.com. That was around 2011/2012 and back then I used SDL 1 which was all about surfaces not textures. When I picked up SDL coding again in 2018, it had progressed to SDL2 which uses textures.

As I understand it, a surface is a structure in RAM while a texture is a structure in VRAM ( the memory in the GPU(. That makes it much faster copying pixels from VRAM to VRAM than from RAM to VRAM.

But I found it much easier to read pixels from a surface than from a texture. Chapter 38 in my e-book has a mask utility. It loads the images from disk into a surface then reads the pixels and creates the masks from that. Masks are used in collision detection. I had previously thought you couldn’t read from a texture.

However after reading this article, which writes directly to the pixels in a texture, it makes me think that reading from them should be possible. I will give it a go just because I’ve not seen it done anywhere.

Picture is from the game Dominions, created with SDL.

A useful function to know- atexit

A useful function to know- atexit

Warning signs
Image by Annalise Batista from Pixabay

This is in C, but applies to C++ as well and is part of stdlib. Perhaps you’ve written a program and when it exits, you want it run some final code. The typical use case for this is releasing resources such as memory allocations and closing files. If you are doing networking then it might also be closing network handles.

Then you need atexit(). You pass in the name of void function. When it finishes, it jumps to that function and runs it. Here’s some code to show it in use.

void ExitFunction(void) {
    printf("Exited");
}    

int atv = atexit(ExitFunction);

As good programming practice, you should check that value to make sure it’s 0. If it isn’t then your exit handler failed to register. I’m not sure what would cause that (overzealous antivirus software?)

You might notice that the ExitFunction has a (void) parameter rather than (). The two are the same but atexit() has been told to expect void parameters and will be disappointed should you fail to comply. Not disappointed enough to give you an error but you will incur a warning and you know how I hate to see those.

The reason why I hate warnings is that not all warnings are equal. This one is trivial and could be ignored, but others aren’t and really need dealing with. So I go for zero tolerance to warnings. Some compilers like gcc have a setting to tell the compiler to treat all warnings as errors.

C is top programming language in Tiobe?

C is top programming language in Tiobe?

Technology
Image by ar130405 from Pixabay

The Tiobe index is a popular and much quoted and updated monthly list of programming languages sorted by popularity. And in May 2020, it lists C as the top language.

Now call me cynical; I do like C (kind of obvious- duh!) but I do have my misgivings about this index. For one, other programming language popularity measures usually disagree with it but are more consistent. Here are some. Most other articles seem to quote from these particularly the StackOverflow developer survey.

RedMonk – C is ninth.

Reddit’s programming language sub-reddits. C is ninth on here.

PyPl – how often language tutorials are searched on Google.  C does not appear at all!

StackOverflow developer survey 2019. C is eleventh in their listed technologies.

Github Octoverse. You have to scroll down to Top languages. C is ninth.

Codingame 2020 Survey. You have to scroll down. C is 6th in most loved and most known (5th in most dreaded!)

Now each of these measures different things so they are never going to be that consistent but coming ninth in three different surveys is pretty telling, with one eleventh and one sixth.  So when you see things like Tiobe, please take this with a pinch of salt.

More on generating random numbers

More on generating random numbers

Two dice
Image by Clker-Free-Vector-Images from Pixabay

The very first program I wrote in any programming language was sometime in October 1976. It was in BASIC and it had this line or something very similar. Even then I was into random numbers. I know, uppercase!

LET DIEROLL = RANDOM(6)+1

I’ve been writing small utility that I’ll publish in a few days. It’s 100% in C and I decided instead of using srand(time(null)) for generating random numbers, I’d use something with a bit more oomph. That something is a library called sodium. Using it for just generating random numbers is a bit overkill. But it has the benefit that the random numbers are good enough random to be used in cryptographic code. Not all random number generators are good enough. This one is.

And it’s easy enough and adds just one dll, or you can compile it statically. I’ll do that once I figure it exactly which Visual Studio settings to change.

It takes just one include –

#include <sodium.h>

Then one call to initialise it.

 int i = sodium_init();
 if (i<0 ) {
   error("Unable to initialise sodium library. Error = ",inttoa(i) );
 }

After that you can call one of several functions. Here’s an example from my code. It fills a 64 byte key with the numbers 0-63 but shuffled like cards.


    typedef char key[64];
    key _key;
    uint32_t ival;
    int i,index1,index2;
    for (i = 0; i < 63; i++) {
        _key[i] = i;
    }
    for (i = 0; i < 1000; i++) {
        do {
            index1 = randombytes_uniform(64);
            index2 = randombytes_uniform(64);
        } while (index1 == index2);
        ival = _key[index2]; // swap two indices
        _key[index2] = _key[index1];
        _key[index1] = ival;
    }

The do loop (how often do you actually see those used in code!) generates two indexes in the range 0-63, making sure that they are not the same. It then swaps the two values at those indexes, and does this 1,000 times. It’s very similar to card deck shuffling code.

Do you know how long it would take you to work through all the combinations of 64 numbers this way? IF you could do a million a second, it would take you 1.27×1083 seconds or 4.02×1075 years! Or to make it more meaningful it’s this large! 4.02,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000. That’s approaching (but still far far off) the time for the heat death of the universe which is estimated at 10100!

The Joys of C++

The Joys of C++

Maze
Image by Arek Socha from Pixabay

My progress on the C++ asteroids game took a little detour down a one way street. The problem I hit was until then I thought I was being clever by passing in a reference to another class in the constructor. That worked fine until I started implementing array classes.

The issue I got was using my constructor meant that the default constructor was deleted. This happens in any class where you add your own constructor as all the special functions are deleted. You then have to add your own Move or Copy assignments if you are doing things that invoke them. Like iterating through an array (or vector in my case). Although I use Bullet and Asteroid classes, I manage  collections of them through an Asteroids and a Bullets class.

Plus I’d decided that vector class wasn’t perhaps the best class to use. This thing runs at 60 fps, so adding and deleting elements from a vector seems a bit wasteful. Instead by using a std::array, and constructing all elements in it when the managing class is instantiated, all I have to do is scan for the first element with an active flag set false. (all are set false when constructed), set a few fields for velocity and position and there it is on screen.

Is this premature optimisation? I don’t think so. One of the things that programmers are told NOT to do!

So I have cleaned up my constructors now. They are parameterless and no special functions are deleted. It’s this kind of stuff that can do your head in and one of the reasons why I think C++ is considered a harder language to master.  I’m certainly a long long way from that.

The maze? Just a metaphor for C++ programming!

Want to learn C by doing projects?

Want to learn C by doing projects?

chess
Image by FelixMittermeier from Pixabay

This site on Github has lots of interesting projects that will help you improve your C programming ability.

Whether it’s  a chess engine, a sudoku solver, space invaders clone,  tic-tac-toe (noughts and crosses for us Brits!), Othello, program a text adventure plus a lot of non games stuff as well.

I’ve added this to the C code Links page.

 

Or do you fancy learning how to write your own virtual Machine in C? Authors Justin Meiners and Ryan Pendleton have crafted a 14 part tutorial that will teach you how to write a VM that can run assembly language programs.