Tag Archives: Cpp11

[ SDL2 – Part 11 ] Text styling

Text styles using SDL2_ttf


In the last post we looked at how to render text. Now let’s take this a step further and change the appearance of the font. There are two ways you can change how the font looks. Font style and font outline.

Fon styles


SDL TTF allows you to set the style of the font. It supports the following font styles

  • bold
  • italic
  • underlined
  • strikthrough

You can combine these in any way you like. We’ll start off with just setting a single font style at a time, and then move on to see how we can apply several of them at once.

Font styles


Settnig font styles in TTF is easy, it just requires a single function. The function let us you set one or more font styles. Let’s start off by looking at how to set just one font style

Setting the font style


We can set the font style using the following function

Arguments :

  •  TTF_Font *font – the font to set the style on
  • int style       – the style to set on the font

As you can see, the style parameter is an int and not an enum. I’ll get back to why that is later, but for now let’s look at the possible values for style, these are all self-explanatory so I won’t be adding a description.

  • TTF_STYLE_NORMAL
  • TTF_STYLE_BOLD
  • TTF_STYLE_ITALIC
  • TTF_STYLE_UNDERLINE
  • TTF_STYLE_STRIKETRHOUGH

Any text you render after setting this font style will have the new effect, but it won’t change any text you have written with a different style. So when you set the style to TTF_STYLE_BOLD, all text you render from that point and until you set a different style will be bold. And as long as you pass any of the above values to the function, the font will only have the one last style you set.

Let’s do a simple example

Any text rendered at this point will be normal with no font styles


Any text rendered at this point will be bold


Any text rendered at this point will be in italics, but not bold


Any text rendered at this point will be normal with no font styles


Any text rendered at this point will be underlined


As you can see, this is pretty straight forwards. So let’s make things a little bit trickier by setting multiple font styles at once. To do this, we must first look a bit at the binary number system

Binary numbers


In order to learn about how to combine these flags, we need to look at binary numbers first of all. If you don’t already know about binary numbers, you should take a look at the above link. It’s not crucial, but it is highly recommended to know a little about them. I might create a blog post about them at some point. For now, I’ll just talk a tiny bit about the binary number system. But as I said, I highly recommend understanding it fully to the point where you can convert back and forth between binary and decimal numbers

The binary number system


On a daily basis, we use the decimal number system. The binary numbers system is just a different way of representing numbers. Any numbers can be converted from any other number system. So you can convert binary numbers to decimal numbers ( and the other way around ).

A computer stores numbers as individual bits ( 0‘s and 1‘s ). They correspond to on / off or true / false.

Let’s take a look at an 8 bit binary number ( 1 byte )

1010 0101

As you can see, it has 8 digits. So that’s eight different flags. Each of these flags have two different possible values : 0 / 1 or false / true. So that’s 8 bools for the price of a single byte!

Bitwise operations


So how do we use these 8 booleans? As you know, we have the following boolean operations in C++:

  • and ( && )
  • or ( ||

These work on an entire variable. An int, for instance will be false if its value is 0, otherwise its true.

But there are similar operations that does this on all bits of a variable. These are called bitwise operations, simply because they operate on a simple byte. To do a bitwise operation, we need two variables of equal size ( same number of digits ), for instance two bytes. The result of a bitwise operation is a third variable of the same size. So if we do a bitwise operation between two bytes, we get a third byte back as a result.

Let’s create two bytes, we’ll use these for a few examples

Byte 1 : 0101 0011 ( 64 + 16 + 2 + 1 = 85 )
Byte 2 : 0110 0010 ( 32 + 64 + 2 = 98 )

We’ll be referring to each digit as a position. So the digits in the first position is 0 in both or bytes. In the second position it’s 1 in both bytes and in the third it’s 0 in the first byte and 1 in the second byte.

Bitwise OR


A bitwise OR operation means we look at all positions as check if either of them is 1 if so, we set the digit in that position to 0. If no digit in that position is 1, we set it to 0

The operator for bitwise OR in C++ is | ( just one |, not two )

Here is a simple example of bitwise OR between two bytes

0101 0011
OR
0110 0010
=
0111 0011

Bitwise AND


In a bitwise AND operation, we look at each position and see if both of them are 1. If so, we set the digit in that position to 1, otherwise we set it to 0. So in OR we set it to 1 if any of the two is 1, here we only set it to 1 if both are 1.

The operator for bitwise AND in C++ is & ( just one &, not two )

Here’s the a simple example :

0101 0011
AND
0110 0010
=
0100 0010

Bitwise XOR


XOR or exclusive OR is slightly less known than OR and AND. In an XOR operation, we check if the two values are different. So this is equivalent to != in C++.

  • ( true  != false ) = true
  • ( true  != true  ) = false
  • ( false != true  ) = true
  • ( false != false ) = false

Simply put, an XOR operation is true if the two parts are different. So in a bitwise XOR operation, we look at each position and see if the two digits are different. If so we set the digit at that position to 1, otherwise we set it to 0.

The operator for bitwise XOR in C++ is !=

Here is an example :

0101 0011
XOR
0110 0010
=
0011 0001

Bitwise NOT


We also have the a bitwise version of the NOT opeartion this is done by using the ~ operator in C++. If we used ! we would get the result of NOT on the entire variable, not the individual bits which is what we want. This operation only takes a single element and flips all bits ( turns 1‘s into 0‘s and 0‘s into 1‘s. ). Let’s test it on our two bytes

The operator for bitwise NOT in C++ is !

Byte 1 :

NOT 0101 0011
=   1010 1100

Byte 2 :

NOT 0110 0010
=   1001 1101

Setting and checking individual bits


So now that we know how to do bitwise operations, we need a way of checking and setting the individual bits. This is done simply by using OR, AND and XOR. Before we take a look at how to do this, let’s define a few values to check.

Remember that the different font styles are ints? This is because they are used to perform bitwise operations to set and unset different bits. Here they are again, this time with their values. For simplicity, I’ll only list the last four bits ( the others are always 0 ). The values are in decimal with the binary representation in parenthesis

  • TTF_STYLE_NORMAL = 0 ( 0000 )
  • TTF_STYLE_BOLD = 1 ( 0001 )
  • TTF_STYLE_ITALIC = 2 ( 0010 )
  • TTF_STYLE_UNDERLINE = 4 ( 0100 )
  • TTF_STYLE_STRIKETRHOUGH = 8 ( 1000 )

As you can see, they all have only one ( or zero ) bit set. This means we can use AND, OR or XOR on just one bit.

Setting a bit


To set a bit ( without affect any other bit ) we use the ORoperation. So say that we have four bits set to 0, 0000 and we want to set the bit for bold on it ( 0001 ). In other words, we want the result 0001. What we do is : that we take our original 4 bits ( 0001 ) and set it to the original 4 bits ( 0001 ) OR‘ed with the bitmask for bold ( 0001 ) :

0000
OR
0001
( value of TTF_STYLE_BOLD )
=
0001

Simple as that! This woks for any of the other flags in the same way. They all will end up setting one bit.

Note that this will not change any other bits. If we try set the italics font style on the above variable we get :

0001
OR
0010
( value of TTF_STYLE_ITALIC )
=
0011 ( TTF_STYLE_BOLD and TTF_STYLE_ITALIC set )

Let’s make a simple function that adds a style to a mask.

Unsetting a bit


Sometimes we want to unset a bit. Say for instance we want to remove the italics from the font above. How do we do that without affection the other values? This is a bit more complex, because it requires two operations. What we are trying to do is the following :

Say we have a bitmask ( 0000 1011 ) and we want to unset the bit for bold text, but leave the rest unchanged. So we need to be able to go :

From 1011 to 1010

To do this, we need to use an AND operation. This is because we can’t turn of a bit using OR, and XOR would only flip it back and forth between 0 and 1

But we can’t use AND with the flag we want to unset alone, because that would keep the flag at 1 and change every other to 0!

0000 0101
AND
0000 0001
=
0000 0001

This is the opposite of what we want! Wait? Opposite you say? Well how about we use the NOT operator here to get the opposite result? This works perfectly, because NOT 0000 0001 is 1111 1110. And, as we saw earlier, doing AND 1 won’t change the element we’re AND‘ing with. So we get :

0000 0101
AND
1111 1110
=
0000 0100

Success! Only the bit we were trying to unset has changed. So let’s make a function that does this for us :

Checking a bit


To check a bit, we also need to use the bitwise AND operation. And since we are only checking and not setting, we don’t have to store the value anywhere which means we don’t have to worry about changing anything.

To check a bitmask, simply do an AND operation with the value you want to check for ( in this case, any of the TTF_STYLE_.... values ). So, to check if a text is bold, we do an AND between our mask and TTF_STYLE_BOLD :

0011 ( our bit mask, TTF_STYLE_BOLD and TTF_STYLE_ITALIC set )
AND
0001
=
0001

As you can see, we only check the bit that’s set in our variable ( TTF_STYLE_ITALIC set ) the others will be 0 no matter what our mask is. The value 0001 is not 0, and thus this evaluates to true and we now know that the font is bold.

If our mask didn’t have the bold bit set ( only the italic one ), our mask would be 0010. An AND between 0010 AND 0001 is false ( they have no bit set to 1 in common ) and the result is 0 aka false.

So let’s create a function for that too!

Conclusion


With a little knowledge about binary numbers and bitwise operations, we can easily set, add, remove and check various font styles in SDL_TTF.

Since it does involve a little low level code, I made a simple class that does the apparitions for us in a more intuitive way. I strongly suggest using this opposed to “raw” TTF_Fount*


Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com
Share

[ C++11 – Part 2 ] Timing

std::chrono


Today, we’ll learn how to use the chrono library. It’s used for timing functionality. It supports a variety of different operations and can be quite daunting in the beginning. The library contains several new types, but I’ll try to explain all of them shortly. But first a few practical tips that will make using std::chrono easier.

using std::chrono


For working with chrono I suggest writing using namespace std::chrono somewhere your code ( preferably at the top ). This means you don’t have to write std::chron:: in front of everything.

Is easier to read than :

Usually, using namespace statements are discouraged to avoid name collisions, but since we are writing std::chrono we could only get name collisions with items in the std::chrono library, which is less likely to happens.

Includes


To make sure everything compiles as it should, please add the headers and using to the top of your file :

About this part


I also want to point out that this guide is rather comprehensive. This is because it’s a good idea to have deep understanding how the various components of the chrono library works. Just writing this guide helped me to understand a lot of it. My hope is that it will help you too.

If you want more information, you can look at the en.cppreference documentation for chrono. This resource covers most, if not all of the features in C++11 with detailed information and good examples. It’s very useful for learning and as a reference.

Overview


Here is a quick overview of the chrono library.

I will now go over each of these components, starting with the basic one, ratio

ratio


The ratio is actually not a direct part of chrono but it’s very useful for working with chrono and just useful in general. A ratio is just that, a ratio or a fraction if you will. For example the ratio between a minute and a second is 60 / 1 since you need 60 seconds to make a minute. ration is defined in it’s own header file, simply called ratio

Definition


The class is templated. The definition looks like the following :

Even though this is a templated class, which can be complicated and hard to understand, the template arguments are quite straight forwards.

Template arguments :

  • Num  – the numerator, or simply the top part of a fraction
  • Denom  -is the denomerator or bottom part of fraction

These two numbers forms a fractions :

Num / Denom

Usually these numbers are dividable by 10, so you end up with numbers like 1000 or 0.001

Both variables are of the type std::intmax_t, which means they are the biggest possible type of signed int available, usually at least 64 bits. For example int64_t.

Predefined ratios


In the chrono library ticks are stored in fractions of second. A few examples :

  • A second : ratio < 1 /1 >
    • A second is 1 / 1 of a second.
    • Can also be written as std::ratio< 1 > since the denomerator defaults to 1
  • A millisecond : ratio < 1 /1000 >
    • A millisecond is 1 / 1000 of a second
  • A minute : ratio< 60 /1 >
    • A minute is 60 / 1 seconds.
    • Can also be written as ratio< 60 > since the denomerator defaults to 1

Resource on ratios


As a part of the ratio header, there’s a lot of predefined ratios ( milli, nano, kilo, mega, … ). Because ratio is not directly a part of the chrono library ( it has other uses than just chrono ), there is no predefined values for minutes, hours, etc. There’s just the ones based on the standard units that’s used for distance or weight. You can refer to either of these using the std:: prefix. Since the ratios are not part of the chrono library, it’s just std:: and not std::chrono::.

For a full list of the predefined values, take a look at the documentation.

duration


duration( or std::chrono::duration ) is one of the basic classes of the chrono library. As the name suggests, it stores a time duration. Or a distance between to points in time if you like.

Member variables


It’s quite simple in its structure, it only has two member variables :

  • rep
    • an arithmetic type ( basically any unit that can hold a number ) that stores the number of ticks ( number of seconds, minutes, years, etc.. ).
  • period
    • a ration containing the type of unit rep stores. In effects this means “how many seconds/minutes/years,… is one tick.”

Constructing a duration


The creation of a duration is a bit complex as it involves two template arguments that sets representation type and a ratio plus the constructor.

teamplate arguments


The actual templated part looks like this :

Template parameters :

  • rep – the type to hold the ticks
    • Typically int or double
  • ratio – the type units used by duration
    • Covered above

The ratio defaults to 1 / 1, meaning seconds. The number of ticks the duration should use are sent to the constructor in the ordinary way using the parenthesis after the variable name.

To create a duration for containing seconds, you can do :

This creates a duration for holding seconds.

Other ratios


To create different durations we can use the ratio like above.  For example 10 millisecond becomes :

We can simplify this by using the predefined ratios already in C++11 :

Okay, but what about 10 minutes? This is quite similar to the above :

We do std::ratio< 60, 1 > because a minute is 60 / 1 seconds which or simply 60 seconds. But we can’t simply this like above because there is not predefined ratio for minutes. The predefined ratios are all “clean” ratios like 1 / 100, 1000 / 1, 1 / 10, 10 / 1, etc…

Predefined durations


But there is another, even simpler way! Just like in ratio there are predefined values in duration And they’re very simple to use.

So say you wanted a duration of 10 milliseconds :

Or 10 minues :

Constructor


The duration has three major constructors

  • Default, empty constructor
    • Looks something like this : duration( )
    • Initializes the duration
  • Constructor with rep variable
    • Looks something like this : duration( rep ) where red can be int, doube or similar
    • Sets the internal tick variable to the variable passed in constructor
    • This is the one we’ve used up until now
  • Construct for other duration
    • Looks something like this : duration( duration )
    • Sets the internal tick variable based on the passed duration
    • The = operator works in the same way
From rep type

Takes a value ( rep ) as argument and sets the ticks of the duration to it.

From other duration type

Takes a duration as argument and sets the ticks of the duration to it. Will convert between the two types of duration based on the ration. This means that if you pass a minutes duration to a seconds duration, you will get the number of minutes * 60 ( because there are 60 seconds in a minute.

Example

This creates a 10 second duration

Duration functions


Duration has a few functions, but I’ll just cover two of them now

  • count
    • Returns the number of ticks
  • duration_cast 
    • Converts a duration of duration into another.

count


This function simply returns the number of ticks. So for our 10 millisecond example, this will be 10.

Code example :

Output :

duration_cast


When we’re working with two different types of durations things can get a bit weird. A simple example : what’s 3 minutes minus 36 seconds. The answer is quite simple for a human to figure out. But the results in your program needs to be a duration but which unit? Since 3:24 can’t be expressed exactly in minutes, we need to change either the 3 minutes to seconds, or the 36 seconds to minutes. Here’s where duration_cast<> comes in.

This simply casts our 3 minutes into 180 seconds. After doing that, we can simply do :

And we’ll get the result in seconds ( 144. ) If you had converted this to minutes, it would take the whole minutes and strip the seconds. Meaning you would end up with 2

Floating points


Up until now, we’ve only used integer values for representing ticks. This means we can only represent whole tick. So a duration of seconds using an int to represent ticks means it can only represent whole seconds. Consider the following code :

This will fail ( won’t compile ) because you loose precision. You could use a duration_cast to fix this, but you’ll loose the precision and end up with 0duration_cast is way of telling the compiler “yeah, I know this will loose precision, just do it!”

So instead we can create a duration of seconds represented as a double :

Output :

Count : 0.016

This is not the same as the predefined duration seconds because all the predefined durations uses int.

Unlike the previous example, this won’t fail because you don’t loose precision. In fact, you could change the ratio to store years :

This will convert the 16 ms to years. If you did yearsAsDouble.count()
you would get roughly 5.07356672 × 10^-9 ( 0.00000000507356672 ) years.

Clocks


Clocks are just objects that is used for finding the current time. They are static, which means that there will only be one of each clock type. There is also just one member function ( also static member function, now() . The function now() returns the current time as time_point. I will cover time_points later.

Clock also have a tick rate which state how accurate they are. For instance : a clock has a tick rate of seconds, it can’t be used to measure milliseconds. The tick rates are represented as ratios.

Clock types


There are three available clocks in the chrono library.

  • system_clock
    • Full name : std::chrono::system_clock
    • The wall clock, use this if you just want to know the current time and date
    • This clock may be adjusted by either daylight saving time ( DST ) or leap seconds.
    • Can be mapped to C-style points and can therefore be easily printed.
  •  steady_clock
    • Full name : std::chrono::steady_clock
    • This clock is monotonic, this means will never be adjusted, so it’ll never be affected by things like DST and leap seconds
    • Best suited for measuring intervals
  •  high_resolution_clock
    • Full name : std::chrono::high_resolution_clock
    • Shortest tick available ( will be updated most often )
    • Might be alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.
      • This means it’s not guaranteed to be monotonic like steady_clock
    • Use this for benchmarking

That’s really all you need to know about clocks, but in the next part we’ll be exploring them more.

time_point


time_point<( or std::chrono::time_point) is the central class of the chrono library. I’ll spare the implementation details for now and just say that it contains various information about the current point it in time.

Construction


The constructor for a time point looks something like this :

As you can see, its a templated class that takes both a clock, and a duration. The duration is the duration the time_point uses. This defaults to the duration of the clock ( as you can see from the typename Clock::duration part. )

Simplified constructor


Luckily though don’t have to specify either of the arguments. So a really simple way to construct a time_point is :

You can use stady_clock or system_clock instead of high_resolution_clock.

This is equal to writing :

A bit more complex, but it means the exact same time : a time_point that uses a high_resolution_clock and has the same duration as the high_resolution_clock. I see no reason to use this method as opposed to the simpler one, but I want to explain the template arguments as well as I can.

Using custom ratio


But what if we wanted to specify our own duration? Well then we have to set the second template argument as well. Say we wanted to specify milliseconds as our duration time unit. Remember that duration has predefined constants for this.

This means we can simply do :

Full constructor


Now let’s do something even worse. Say we wanted a time_point that uses half minutes ( 30 seconds ) as the time units. I have no idea why anyone would want this, but it’s just a ( somewhat contrived ) example. As with some other examples, I do not encourage writing code like this. It’s horribly hard to read and very hard to understand unless you know the different part of the chrono libraries. Okay, here we go :

Yup, that’s a template argument, inside a template argument, inside a template argument! Don’t write code like this! If you need a specific time ratio, at least put the ratio and duration in separate objects ( I’ve shown you how to use the constructors above. ) Also make sure they’re well named like ratio30sec and duration30sec. That should give the reader at least a small hope at knowing what’s going on.

I added this example because if you understand this constructor and how it works, you understand the major parts of std::chrono

Initialization


As stated above, the static member function of clocks, now() returns a time_point of the current point in time.

That means we can just use auto to create a time_point too!

Simple as that, we’ve created a time point. The type of this object will be exactly the same as

Only it’s even simpler, and we’ve initialized it to the current point in time at the same time!

Difference between two time_points


And finally we can do some actual timing! Time points supports arithmetic operations. This means you can say time_point_x - time_point_y. This will result in a duration But what is the kind of duration. Seconds? Milliseconds? Years? Actually there is no one answer, it’s implementation defined. But the result is almost certain to be less than one second.

Since we can’t know what the resulting value is, we have two options. Say we have the following code :

And wanted to know the result of t1 - t2 Our two options are :

  1. Use auto
      • Nice and simple
      • But we can’t control the type of result.
  2. Use duration_cast
      • Takes the result of t2 - t1 and casts it into a duration of milliseconds and uses it to set result
      • This is a bit harder, but now we have full control over the type of duration.
      • If you want higher precision, you can use microseconds or nanoseconds
      • If you want higher precision, you can use microseconds or nanoseconds

Delta timer


So now let’s use all this knowledge and make a delta timer. A delta timer is used in games to tell the difference between two frames. The code is relatively simple and will show one ( of many ) ways to use the chrono library.

Notes


  1. Get the current time
    • We need this to calculate the difference in the next step
  2. Take the dif and store it in a duration
    • Stored in seconds ( since it’s the default )
    • Represented as double
  3. Reset time_prev
    • We need this point because we always need to know the time_point of the previous frame
  4. Return the results
    • Finally we return the time since last frame as fractions of a second
    • Can be a very small value like 0.000000001 ( 1ns )

A note about time units


This section just describes my reasoning for using seconds stored as double. It’s very focused around game programming and not crucial to understanding chrono.

I choose to use seconds as double here because double allows higher accuracy than int. And even though the game will almost certainly use less than 1 second on one frame, using seconds over milliseconds as time units means that the number will always be on the form 0.x. It also ensure that the delta won’t be exactly 0.

If the delta is 0 on one frame, no movement would happen ( I will get into this in the next SDL2 part ). If it only happens in one frame, the effect might not be that bad. But if it happens 100 frames in a row, that would be 100 frames without movements. And that would be bad!

So, in my opinion, it’s better to always have a delta of 0.x as it ensure that there will always be at least a tiny fraction of movement. The fact that the delta is a small number can be countered by multiplying with a great number in the function that calculates movement ( we’ll see this in the next SDL2 part too! )

Conclusion


The chrono library is very useful and makes it easy to deal with timing. It enables high precision timing, and makes it easy to find difference between two points in time. There are also other libraries that uses chrono like the threading library. I might write about the threading library later. There is also a post about timing in games coming up soon ( as mentioned in the above post. )


Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com
Share

[ C++11 – Part 1 ] Enum class

Introduction to the series


I thought I’d start of by talking about my favorite thing that’s new about C++11 standard. C++11 has a lot of useful new features : auto, initializer lists, lambda, shared_ptr, unique_ptr, move semantics, etc. Some of these are quite comprehensive and complicated, and I’m still working on understanding all of them. But this one is actually quite simple.

About enum classes


Enum classes are basically enumerations that can’t implicitly be converted to integer types. So basically you can’t write :

Why is this such a good thing?


First of all it helps code clarity. A simple question : Say you have an enum of card suits, which would you prefer?

Using and enforcing enum classes means you’ll instantly know what the value is, so you’ll never have to find the actual definition of the enum and look up what the different int values does.

So it helps code clairty. Is that all?


No! There are more serious issues. Say you have the following code

This might look okay, they both set the card to Suit::Clover. But here comes the big issue. Someone changes the order of the elements in Suit.

What’s the issue?


It might seem a very subtle change. But you let’s say you implemented reset method a long time ago. It’s been working fine ever since, and you’ve completely forgotten that it uses and integer value to set suit. It’ll now do something different from the constructor! So you end up with cards being different when you reset them from when you create them. And issues like this can be very confusing and hard to debug.

This is just a minimal example to showcase the issue. But this can happen just as easily in huge projects where the enum is used hundreds of places. Debugging such issues will waste a huge amount of time and cause a whole lot of pain and agony. All because of using an integer to assign an enum! Using enum class prevents these issues.

Conclusion


Use enum classes! It might be a bit annoying having to write the full enumeration name sometimes. But it’s a lot better than spending hours upon hours debugging when someone changes the order of the enumeration items or adds a new value in front of others!


Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com
Share