Thursday, 28 January 2016

Low-Level Programming_Post13

Low-Level Programming: Post 13 28/01/2016

January 28th 2016 is the date of the fourteenth lesson on Low-Level Programming.

After clearing up last weeks confusion regarding missing a post on a lesson, everything should be back to normal for the next few weeks.

In this week's lesson, we were taught about Const Correctness & Networking. Below are the main points from the lesson...

  • Const Correctness: What is it and how does it work?
  • Const & Non-Const Functions: How do const and non-const functions work in tandem.
  • Networking: What are data packets and how do we send/receive them?
Const

Constness
  • Const Correctness: Const correctness is fundamentally based on treating data and objects as constant unless we intend to modify it’s value.
  • Semantics: Const allows you to specify a semantic constraint – a particular object should not be modified. Compilers will obey this constraint.
  • Meaning: Const tells both the compiler and programmers that a value should remain invariant. Whenever that’s the case, you should say so i.e. const.
  • Scope: 
  1. Outside of classes; Static at file, function or block scope.
  2. Inside of classes; Both static and non static data members
  • Const Pointers: It is possible to have constant pointers to data, pointer to constant data or even a constant pointer to a constant data address.
  • Syntax: If the word const appears to the left of * it’s constant data, else it’s a constant pointer.
  • Iterators: As covered previously, iterators are just abstracted pointers to data. This means it’s constness is similar to that of pointers.
  • Const Iterator: An iterator that can’t point to a different memory address.
  • Iterator to Const Data: An iterator that can point to any memory address but not amend data.
  • Parameters: When passing user defined types into functions, always use the const declaration where possible.
  • Benefits:
  1. Tells the programmer that the data won’t be modified.
  2. Stops accidental errors such as ‘=‘ when you meant “==“.
  3. Const “may” improve performance with ROM caching.
  • Member Functions: Const member functions identify which functions can be called on const objects.
  • Clarity: They show a clear interface for the class’s interaction with const objects.
  • Const Objects: You can’t work with const objects in non-const functions.
  • Overloading: A member function can be overloaded by it’s constness.
Bitwise Constness
  • Bitwise: A member function is only const if it doesn't modify any of the object’s data members, excluding static variables. i.e. it doesn't modify any of the ‘bits’.
  • Violations: Just look for assignments to data members. Bitwise is C++’s definition of constness. A member function can’t modify any of the nonstatic members.
  • Issue: Functions that aren't const can sometimes pass the bitwise test.
Logical Constness
  • Logical: A const member function might modify some of the bits in it’s object, but only in way clients can’t detect.
  • Example: Caching a value is an interesting process. The cache may be read-only but it needs to be generated first. It would make sense for us to calculate the cache on first run of the function; but it will fail bitwise constant.
  • Mutable: Mutable allows us to evade the limitations of a const variable. Mutable variables can be changed in either const or non-const functions.
Duplication
  • Multiple Functions: The problem with const functions can be code duplication. You can end up duplicating identical code for both const and the non-const function.
  • Approach: We could instead, call the const version of the function, cast away the “constness” of the object and return it from the non-const version.
ConsteXPR
  • Compile Time: Even const variables aren't necessarily created at compile-time even though their value is known. Instead space may be allocated at run-time.
  • Constant Expression: We can actually declare a variable as a constant expression which is evaluated at compile-time. It can therefore be used as constants to determine array sizes etc.
After going over a few of the points in the lesson, it was time for a mini-practical session. Once again, we had to take what we had learnt from the current lesson. The guide from the practical was as followed...

  1. Create a class called GameObjects that stores a vector of GameObject.
  2. Create two functions (one const) that return the GameObject at pos [i] as a reference.
  3. Create a function in GameObject that takes another GameObject& as const.
  4. Return true if the object being tested has more health than the other.
  5. Create a function that takes two GameObjects& as const and returns the one with least health.
I found this particular task fairly tricky, due to my lack of knowledge in this area. I had only managed to complete task 1 and added the code snippets provided from the lesson slides. When the answer was revealed to us about 15 minutes later however, it made some sense to me as to where I went wrong.

Networking

Networking
  • Communications: Networking covers the concept of using multiple hosts/nodes to share data with each other. They can keep each other updated on any game logic changes.
  • Ease: Actually getting computers to talk to each other is a fairly easy task, but making sense of the bits sent/received isn’t.
Interwebs
  • Transport: The internet works by encoding packets of data and transporting them across the internet. A session can be thought of the mechanism for allowing the two to communicate.
  • Host Layers: Host layers are concerned with software, where the media layers are focused on the physical hardware responsible for transmitting data i.e. bits.
Protocols
  • Protocols: The internet sends data via protocols. Two of the most common in games is UDP and TCP/IP. They both allow data to be sent over the internet. But offer radically different approaches to how they accomplish this.
  • TCP (1): Transport Control Protocol; Creates a connection via two hosts. TCP is a guaranteed full duplex protocol. The connection is reliable and ordered.
  • UDP (1): User Datagram Protocol; Data is simply sent as packets. The receiver listens for these packets. Does not guarantee delivery of data.
  • TCP (2): Forms the backbone of the internet. It’s a reliable connection based protocols. I t forms a connection between two nodes.
  • Reliability: TCP provides reliable and guaranteed delivery of data.
  • Ordered: The data sent by TCP will be received in the same order.
  • Performance (1): All this extra error checking involves the receiver acknowledging receipt of complete and non-corrupt packets. i.e. ACK. Corrupt packets causes a queue to resolve the out of order issues.
  • IP: IP sits beneath the TCP stack. There is no concept of connections, packets are just passed from one computer to the next.
  • Duration: IP passes the data between nodes, but the route is unknown.
  • Recipent: There’s no guarantee that the packet is ever received by the intended host.
  • Routing: IP will do it’s best to get data from a to b via any possible route necessary. This means data can arrive out of order if the 2nd packet takes a different route to the 1st. It’s like a postal system.
  • UDP (2): Just like TCP it’s built on top of IP. However, it doesn’t provide layers of complexity and features. It’s a thin wrapper over the IP protocol.
  • Delivery: There’s no guarantee of delivery, nor attempt to confirm it.
  • Split: If the data get’s split into multiple packets, you won’t know.
  • Performance (2): Because it’s lightweight it’s quick but the lack of guaranteed delivery, or the ordering of packets make’s it an unreliable connection protocol.
TCP Vs UDP


  • TCP Innards: TCP is a stream protocol, you just write bytes to a stream formed by the connection. TCP breaks your stream of data into packets before sending them via the IP protocol.
  • Queues: This actually means there needs to be a queue for sending and buffer for receiving.
  • Delay: This process causes a delay, we can disable it, but TCP is still slow.
  • Guidance: Never use TCP for time critical applications. Real-time requirements dictate the usage of UDP. The truth is probably UDP and TCP connections should be used in tandem. Send real-time data via UDP, everything else by TCP.
IP Addresses
  • Hosts: Every networked PC has TCP/IP installed which provides an IP. The IP address uniquely identifies the PC’s ‘address’.
  • Classes: Some ranges of IP addresses are for private use only and the others for public i.e. internet.
  • Routing: A series of routers are responsible for forwarding packets to these IP addresses. Consider your IP address as your mailbox, with IP responsible for delivering items.
  • TCP Innards: The IPv4 address is a 4-byte number. IP addresses are normally in decimal format. It’s formed of two parts. The network ID and host ID.
  • LAN: Local area networks sit behind a router, that serves data from and to the internet.
DNS
  • Domain Name System: Clearly, even though every host has an IP address, we don’t browse the web using those IP’s. Instead we resolve an alias that points to that IP.
  • Resolve: The DNS servers around the world are responsible for converting a human readable name to an IP address.
  • Abstraction: It’s clear that this layer of abstraction is of benefit. Imagine trying to remember the IP addresses of all your favourite sites?
Once the theoretical side of the lesson ended, we moved onto the main practical of the lesson. Our task was to create our own Chat Server using Visual Studio 2013. Although my set-up was when following the instructions was fine, it came up with compiler errors nevertheless. There were also sections in the code where we would need our own input to make it work. Sadly, before I started to try and fix the errors, I ran out of time in the lesson.

Friday, 22 January 2016

Low-Level Programming_Post12

Low-Level Programming: Post 12 21/01/2016

January 21st 2016 is the date of the thirteenth lesson on Low-Level Programming.

The reason as to why I skipped a post last time out on December 10th 2015, since that was the date of the twelfth lesson on Low-Level Programming, was due to the extremely low attendance in that lesson, which was most likely due to the coursework deadline for this course being on the same day. This resulted in the lesson being cancelled and we were sent on our ways.

Below are the points as to what we were taught in the lesson...


  • Template Functions/Classes: How to implement template functions and template classes.
  • Generics: Templates, what are they and how do they work?
  • Compiler Directives: How to implement template functions and template classes.
Directives

Directives
  • Compiler Instruction: Directives are designed to dictate the compiler’s behaviour and do not form part of the language’s syntax.
  • C++: C and C++ support a simple macro pre-processor. Lines which start with the # symbol indicate a directive.
  • Directive: They are responsible for ‘directing’ the compilation process.
Pre-Processor
  • Pre-Processor (1): The pre-processor is responsible for substituting these expressions into text that alters the source code that’s about to be compiled.
  • Abilities (1): They can replace tokens in the text, insert the content of other files into the source file or even remove lines of code that may otherwise had been compiled.
  • Placement (1): Pre-processor directives can appear anywhere in a source file, but they apply only to the remainder of the source file.
  • Supported #: The following pre-processor directives are supported; #define, #error, #import, #undef, #elif, #if, #include, #using, #else, #ifdef, #line, #endif, #ifndef, #pragma.
  • #Define/#Undef: Used to define or un-define a pre-processor tag.
  • #Include: Includes the source from another file.
  • #Pragma: Allows machine/OS specific code which retains overall compatibility.
  • #If/#Else/#Elif: IF / ELSE style clauses for the pre-processor.
  • #Ifdef: Checks to see if a tag is defined.
  • #Error: Emits a user-error at compile time and fails compilation process.
  • Pre-Processor (2): The pre-processor is responsible for substituting these expressions into text that alters the source code that’s about to be compiled.
  • Abilities (2): They can replace tokens in the text, insert the content of other files into the source file or even remove lines of code that may otherwise had been compiled.
  • Placement (2): Pre-processor directives can appear anywhere in a source file, but they apply only to the remainder of the source file.
Some Guidance...
  • Pre-Processor: Do not use #defines. They are text substitution and complicate debugging.
  • Macros: Do not use macros, they start with #define and often lead to complicated bugs.
  • Platform: Do use them for platform specific code.
Templates

Generics
  • Templates: As discussed previously it’s possible to write code that operates independently of the type it’s working with.
  • Blueprint: A template acts as a blueprint for creating a generic class of function. The STL is based around this principle.
  • Type Safe: Even though this is generic programming, the type safety is maintained when using templated code.
Template Code
  • Duplication: Function templates allow the creation of functions that can adapt to the type or class being worked with, without repeating the code for each type.
  • Parameters: This is achieved through the use of template parameters. These are special types of parameter, but the class can use them like any regular parameter.
  • Compile-Time: As discussed last year, it’s important to understand that the template code is evaluated at compile time.
  • Function Templates/Declaration: There are two ways of declaring a template function, the difference is the keyword. There are semantically identical.
  • Syntax: Functions are one of the most common usages in generic programming i.e. the idea that a function can use the same code on any given type.
  • Interface: When we use templates the interface is implicit. The templated object’s interaction determines it’s interface even though it’s type is unknown.
Classes
  • Template Classes: Just like templates, it’s possible to create templated classes. The typename defined can then be used throughout the class’s functions and variables.
  • Member Definitions: The advantage of the template class over template function is due to the fact member variables can be stored in the class of type T.
  • Type Specification: When using a class that utilise templates, it becomes necessary to provide the type we want to use with the class via the <> brackets.
After the first few slides, we were given a practical task. It was essentially what we had just learnt in the lesson. The stages in the practical were as followed...

1. Create a function called min that takes a template argument named T
2. The function will need to take two args of type T
3. Set the return type as type T
4. Return the result of the two args added together.
5. Test by printing to result to the console.
6. Create a function called max that determines the greater of the two.
7. Create a function called create that returns a newly allocated block of said type. Hint: the function does not require any parameters.

Unfortunately, due to not having enough experience and knowledge in this field, I didn't get very far in the task. Although I managed to add up the args together and show it, it was via a different method.

After a 5 minute break, we resumed the theoretical side of the lesson.

Varadic Templates
  • Arguments: Wouldn’t it be good if; templates could take a variable number of arguments.
  • C++11: C++ 11 standard provides the ability to use variadic templates, which allows this. Logic is resolved at compile-time.
Explicit Interfaces
  • Generic Code: Using templated functions allow the usage of the same code regardless of the types being used.
  • Specialization: Occasionally, it becomes necessary to handle certain types in an alternative way. We can explicitly define this in the codebase, thus creating an explicit specialization.
  • Partial or Full: If a class template is specialized by a subset of it’s parameters it’s partial otherwise it’s known as full specialization.
Inheritance
  • Template Classes: A template class that inherits from another template class. Inheritance from a template class. A template class that inherits from a non-template class. A template class that uses multiple inheritance.
  • Member Definitions: The advantage of the template class over template function is due to the fact member variables can be stored in the class of type T.
  • When using a class that utilise templates, it becomes necessary to provide the type we want to use with the class via the <> brackets.
After finishing the theoretical side of the lesson, we moved onto another practical session. This time, we had to create a UML diagram showing all the classes and their relationship to each other in the form of the game Snake, which was one of the parts of the assignment we were tasked to do.

I listed down all the features in the Snake game, such as the player, the walls, the points and so on and then extended it by adding the variables in each of their respective classes. I didn't have enough time left to connect them together, however.

Thursday, 3 December 2015

Low-Level Programming_Post11

Low-Level Programming: Post 11 03/12/2015

December 3rd 2015 is the date of the eleventh lesson on Low-Level Programming.

In a case similar to last week, we started the lesson showing, from the bullet points, what we were going to learn in the lesson. The reason as to why I stated that this lesson is very similar to last week's lesson is that, although there were some bullet points, there wasn't a lot that we were going to be taught today.

Below are the bullet points and what we covered in the lesson today...

  • Operator Overloading: What is Operator Overloading and how can it benefit us?
  • Function Pointers: How do we utilize function pointers?
  • Delegate Functions: What's a delegate function and how do we use them?
Overloading
  • Functions: It's possible to overload functions, we do this by altering the parameters on the function signature.
  • Operators: All objects and classes have a number of operators. These range from constructors through to less than or equality comparisons.
  • Overloading: The compiler where possible will generate simple operator functions. However, these can be overridden or overloaded.
  • Syntax: Overloaded operators are functions and like a normal function, they have return types and parameters.
  • Copying: One example of using operator overloading is when a class allocates memory on the heap.
  • Assignment: When the object is assigned, there's a need to ensure we do need a deep copy of all those heap values and not point to the same ones.
  • Casting: By overloading the construction operators, we can enable implicit and explicit conversions between differing types.
  • Conversions: Before making conversions between different types, it's important to make sure the conversion is logical as to avoid confusion.
  • Equality: One of the most common usages of operator overloading is the equality operation ==. We overload the room equality to do a string comparison on it's description.
  • < Operator: Remember that the STL uses the less than operator for maintaining it's sort order when using associative containers.
  • Operator += & -=: Depending on an object's definition and structure, it may be valid for it's value to increase or decrease.
  • Restrictions: The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?: (ternary conditional) cannot be overloaded.
  • Non-Existent Operators: New operators such as **, <>, or &| cannot be created.
  • Common Functionality: The overload of operator -> must either return a raw pointer or return an object (by reference or by value), for which operator -> is in turn overloaded.
  • Precedence: It is not possible to change the precedence, grouping, or number of operands or operators.
  • Short Circuiting: The overloads of operators &&, ||, and , lose their special properties: short-circuit evaluation and sequencing.
Function Pointers
  • Functions: The function identifier is a constant pointer to a function. The pointer holds the address in memory where the code for the function resides.
  • Dereference(): When the function is called via the () operator, execution jumps to the address of the function via it's constant pointer.
  • Syntax: Knowing this, it becomes possible to store the address of a function in a variable, but it's a pretty hideous syntax.
  • Parentheses: They're important due to precedence rules in the language. In this case it would be seen as a function that returns a pointer to an integer.
  • Ptrs to functions: Storing pointers to functions mean we have to dereference the pointer. There are two ways of doing this: Implicit calls and Explicit calls.
  • Callback Functions: Passing a function pointer through to another function is possible. It just needs to be added as an argument to the function signature.
  • Decltype: Evaluates the type of an expression. We can use this to cheat on our declaration of function pointers as a type.
  • Compiler: The compiler evaluates the expression for you and substitutes it's reference when compiling.
  • Auto Keyword: When storing a Ptr to a function inside the code base, it's preferable to use the auto keyword to prevent the convoluted syntax involved.
  • Decltype of Auto: It's even possible to decltype an auto defined variable. However, this may make it less clear when reviewing the code.
  • Factories: We can make use of function pointers when creating a factory class.
  • Each class has a lookup ID that's stored in the pair. The second part stores the function pointer that's responsible for creation.
  • Pointers: Assuming the signature of all the action handling functions were the same, why not use function pointers instead.
  • Predicates: Predicates are another example of function pointers and are used throughout the STL and it's containers and algorithms.
  • Static Predicates: By implementing a static predicate inside a class, it can be provided to the algorithms.
  • Lambda Functions: Lambda or local functions can be used, again these are passed through as a function pointer to the algorithm being utilized.
  • Classes: It's possible to have a pointer to a member function. In order to use these, we need an object and some new syntax.
  • This Pointer: In essence, in order for member functions to be accessed via pointers, they need access to the pointer.
  • Normal Pointer: A normal pointer can only store one address. This is why it's not possible to have a direct pointer to an object and the function.
Functors
  • Functors: Function objects or functionals are object + (). A functor is an object that can be used with () in the same way a function is called.
  • Functions: This includes normal functions, pointers to functions and class objects where the () operator is overloaded.
    • STL: The STL makes extensive usage of function objects, the most obvious example is when a predicate is required.
    • An Object or a Function: It's an object that acts as a function. One of the best usages of a functor is the storage of state.
    • Struct: Define a struct that we will use as a function.
    • Overload the (): Overload the () operator, this way we can call the class as a function and it will perform the code in the () operator.
    • State: This struct is no state. We could easily add member variables to it, if they would help in the function's processing.

    Thursday, 26 November 2015

    Low-Level Programming_Post10

    Low-Level Programming: Post 10 26/11/2015

    November 26th 2015 is the date of the tenth lesson on Low-Level Programming.

    Keeping with tradition, we were shown an overview of what we were going to learn today. From the bullet points, we were only going to be learning about three (more) types of patterns. Below are the bullet points in more detail...

    • Observer Pattern: What is it and how does it work?
    • Component Pattern: What is it and how does it work?
    • Type Pattern: What is it and how does it work?
    Before we began looking at the patterns, we were given a practical task. The task was to create two Pseudocodes, one for the 'Factory' that creates the GameObjects, which should have consisted of the Player, Three enemies and a Boss, and the other for an Object Pool that creates the enemies. It was a simple task, simply creating a class for, except the player, the enemies. We decided to make a separate pool for the boss as well.

    After the 15 minute practical session, we moved onto the lesson slides again, resuming with learning about Observer Patterns.

    Observer: Define a one-to-many dependency between objects so that when one object updates, others are aware
    • Java & C#: Model-View-Controller architecture utilizes the observer pattern and is built into Java and C# even supports it via the event keyword.
    • Announcement: In this pattern, one part of the code-base will announce an event, this event can be processed elsewhere.
    • Coupling: An event based system allows us to reduce the level of complexity.
    • Achievements: The achievement system used in games is event triggered, rather than pollute the code where the event happens, we notify observers.
    • Register: It's now possible to register observers with our observable object.
    • Events: The observable objects can then send events to all it's observers without any understanding of it's intention. We've maintained low coupling.
    • Performance: We're simply iterating through a list of observers and calling a virtual function to handle the event.
    • Dereferencing: There's an obvious overhead associated with virtual function calls, but it's fairly minimal, especially as we don't need to "poll" or couple.
    • Observers: Care needs to be taken as the thread is paused whilst processing the observers update functions.
    • Allocations: Best practices dictate we reduce the number of allocations during game time, in this case add observers at load time.
    • Linked List: Instead of using a vector of pointers, it's possible to create a linked list using observer nodes, with each one pointing to the next.
    • Multiple Observer: Using a linked list, we can only have the observer itself observing a single object at any given time.
    • Nodes: To circumvent this problem, we can use the concept of a node, which has a link to the next node and a pointer to the observer.
    • Pool: The nodes can then be pooled together, saving on allocations and deallocations. Remember to give them a bool flag for reusage.
    Component: Allows a single entity to span multiple domains without coupling the domains to each other
    • Game Objects: In games, it's not uncommon that objects need to interact with the rendering, update and input systems i.e. multiple domains.
    • Coupling: In a traditional update method, it soon becomes obvious that code between the domains is coupled, with the coder needing an understanding of each component.
    • Divide and Conquer: Let's resolve the issue by dividing the domains in to their own respective managed components.
    • Candidates:
    1. An Input Component.
    2. An Audio Component.
    3. A Rendering Component.
    • Result: The three components are decoupled and can be managed independently. Though it's likely they will need some awareness of each other.
    • Reusable: Components are now reusable and we can prevent objects from having complex inheritance structures.
    • Decoration: Decorations i.e. static objects with no dynamic updates are now composed of graphic components.
    • Composition: Prefer composition over inheritance.
    • Domains: This illustrates the definition in which it's stated that a single entity i.e. zombie spans multiple domains and remains decoupled.
    • Large Classes: When the functionality in a class is becoming large and complex, it may be a good time to implement components to reduce it.
    • Decoupling: If there's a desire to keep a class loosely coupled, then the component design pattern allows this.
    • Common Functionality: If a variety of objects are utilizing similar functionality but inheritance doesn't fit correctly, again components can be used.
    • Complexity: Utilising this design pattern makes the object more complex. It has a number of components, all of which need initialising.
    • Communication: Another consideration is cross-communication between the domains, how do you tie them together if they need each other.
    Type: Allows the flexible creation of new 'classes' by creating a single class, each instance represents a different type
    • Inheritance: When designing classes of objects, there is the desire to create subclasses for each kind of similar object.
    • Breeds: Using the Dungeon Death game as an example; last week I mentioned three enemies, most likely only different in base attributes.
    • Subclass: Each subclass has more health than the other, due to the enemies' increased perception of strength.
    • Additional Enemies: For every additional enemy, we end up writing short and annoying classes that only consist of a few lines.
    • Inheritance: Inheritance works in this example, but it means we end up with all these small classes, but there's another option.
    • Composition: Each monster class or enemy has a breed object. The breed object determines how a monster attacks or it's health.
    • Challenges: The ability to override functions to determine behaviour are now not possible, instead the type data is attached to the class.
    • Behaviour: Type patterns are good for defining the data relevant to an instance but are more difficult to encompass different behaviours at different times.
    • States: We could store a state in the type data and then act differently depending on the value stored in the state.
    • Data Files: With more complex solutions, behaviours can be constructed from data files. This way, the behaviour is completely removed from the code base.
    • Type: The breed object molds or defines a monster's type, hence the name of the pattern i.e. type.
    • Instances: Instances of the monsters which use the same breed object are conceptually identical and will act in the same way.
    • Data: The instances store the data required per breed; this is what get's altered when the monster takes damage.
    • Usages:
    1. You don't know what types you will need up front, just that you require multiple types.
    2. You want to be able to modify and add new types without having to change code.
    After the end of the rather short lectural side of the lesson, we were shown some questions that other people on the course asked about the assignment. Two of the three questions were about some of the rules in the BlackJack game, in which the tutor said we didn't NEED to implement it, but implementing it would get us higher marks. The other question was about the documentation needed for the assignment. It says that it should cover our design decisions and utilise UML, Pseudocode and diagrams where necessary, basically saying why we design the game(s) like we did and how to implement it.

    After that, we then moved onto the second practical of the lesson. Carrying on from the first practical earlier on, we had to implement the Pseudocode from earlier, as in, creating the classes for the enemies. Sadly, we only managed to create the classes and ran out of time to do any more work on it.

    Friday, 20 November 2015

    Low-Level Programming_Post9

    Low-Level Programming: Post 9 19/11/2015

    November 19th 2015 is the date of the ninth lesson on Low-Level Programming.

    As per usual, at the start of the lecture, we were shown some bullet points on what we were going to learn today. Below are the all the points from the lesson...

    • Design Patterns: Design Patterns continued, round up of previous lesson.
    • Creational Patterns: The Factory and Singleton Patterns.
    • Sequencing Patterns: Facade, Game Loop and Update Patterns.
    • Object Pooling: Object Pooling, Implementations, Advantages and Disadvantages.
    Unlike in most previous lessons, I am going to do a recap of Design Patterns from last week. This is due to the Design Patterns and the newer patterns mentioned above being linked together. Before we went into any detail on the Design Pattern, we were shown/told of a book that could help us in the module. The book was called 'Game Programming Patterns' by Robert Nystrom and published by Genever Benning. It covers all of what we were going to learn in the lesson on patterns and there was also an online version of the book.

    Design Patterns (Recap)
    • Tool: Design Patterns are a powerful tool for software development, but they are not prescriptive specifications.
    • Concepts: They prevent us conceptual ways of modelling behaviour that we might want inside our software.
    • Misuse: Incorrectly using design patterns for a given situation will over-complicate your code and make it more difficult to maintain.
    • OOP: Object Oriented Design collates a collection of concepts and references them under a single paradigm
    • Appropriate Usage: Apply patterns appropriately, don't attempt to find a problem that requires a patterned solution.
    • Gang Of Four: The Gang Of Four have set out a series of patterns, which most modern day ones are based on, but their prose can be inaccessible.
    Singleton Pattern: Ensure a class has only one instance, and provide a global point of access to it.
    • Single Instance: The first point to note is that a singleton is designed to enforce only a single instance of an object.
    • Global Access: The second is that using a singleton requires a global point of access. This in turn means the object itself is global and global is bad.
    • Consideration: The following three criteria;
    1. Ownership of the instance is unknown.
    2. Lazy initialisation is desirable.
    3. Global Access is not provided elsewhere.
    • Static: Singletons make use of the static keyword and manage their own instance to make sure it's only constructed once.
    • Overuse: The singleton's pattern is one of the most disliked because it breaks rules regarding global variables.
    • Laziness: There are very few occasions when passing the object around the game world is not possible, making it global is lazy.
    Implementation
    1. Define a static attribute 'instance'.
    2. Define a static get function.
    3. Lazy initialise the object i.e. on first usage.
    4. Define constructors/destructors as private.
    5. Access is controlled via the get function.
    • Instance: Lazy initialisation means the object/data in the class is only created when needed. Ironically, we may want to control when.
    • Runtime: It's created at runtime, where a static class could be used instead and they aren't dependent on runtime scenarios.
    • Static Initialisation: The compiler initialises static variables before the program runs, which means we can't guarantee the order they've initialised.
    • Subclass: You can subclass a singleton object. This helps with cross-platform implementation, where the interface can be platform agnostic.
    • Patterns: Patterns such as Abstract Factory, Builder and Prototype often use the singleton pattern. So do state machines.
    • Single Instance: Singletons are overused, they should only be used when we only need a single instance that has global access.
    Single Pattern (Bad)
    • Globals: Global variables are bad. They make it harder to reason code as well as encourage higher levels of coupling. Then there's threads.
    • Two Problems Solved: It solves two problems (not one).
    1. The Single Only Instance.
    2. The Global Access.
    • Lazy Initialisation: Whilst one of it's greatest advantages, using singletons restrict how and when we control allocations. This could lead to poor performances. 
    • Classes: Often developers can get carried away with the creation of manager classes, are they really needed? Could it not reside in the class?
    • Limit Classes: To limit a class to a single instance we can use a static bool to determine if the class has already been initialised.
    Singleton Pattern
    • Static Class: As mentioned, a static boolean sits on the class. The first time it's accessed and constructed, the boolean is set to true.
    • Access: With this implementation, it's important to note that you will need to keep a variable or pointer to the one instantiated class object so you can utilise it throughout the codebase.
    • Parameters: Well designed software will allow us to flow data and objects between functions and classes, we should look to pass it in, rather than access it globally.
    After looking through some of the lesson slides, we were then given an unexpected practical session. For this task, we had to design the DungeonDeath's game level layout. This included 10 bottom floors and 5 top floors. We also had to design various enemies and a boss enemy in the game, with them having different variables/values (health, damage etc). We also had to design where to place them in the game. I decided that out of the 5 enemies (including the boss) in the floor(s), three of them would be optional fights, but if the player defeats them, they get an item(s) to help fight against the boss.

    Factory Pattern: Define an interface for creating an object, but let subclasses decide which class to instantiate
    • Factory: A factory relates to a class or a function whom's job it is to create objects of a derived class, often returning a reference to the base.
    • Instantiation: Factory method allows the base class to define all common and basic behaviours i.e. it's interface and delegates creation to subclasses.
    • Runtime Support: Factory methods are useful when it's not known what objects are required. Potentially we load the objects from a file and use an ID to create the correct subclass.
    • Allocation: Our factory's method can use special allocators during construction as well as taking ownership of the object.
    • Storage: A factory class can also manage the objects internally, storing them in a container and returning a reference to the new objects.
    • Game Objects: Implementing the previous factory requires the addition of a new type and a new switch statement for each new class added.
    • Factory: It's possible to edit the factory, so that a lookup value can be used to determine the object to be created. After which, for new classes we just need to register it in the factory.
    • Inheritance: Factory implementations are used with inheritance, unlike prototyping (another design pattern).
    • Sub-Classing: Prototyping does not require sub-classing but factories do, conversely they don't use initialise functions.
    • Approaches: There are multiple other approaches. We can use abstract factories or even generic programming to reduce the verbosity of types.
    • Return Type: The factory method is capable of returning the same instance more than once, or in this case, a subclass rather than the exact return type.
    Facade Pattern: A facade is an object that provides a simplified interface to a larger body of code
    • Simplification: The facade pattern is designed to simplify interactions with complex parts of the codebase.
    • Understanding: It is often true that in order for us to accomplish our goal, we don't need to understand what's happening in great depth i.e. system("cls").
    • Implementation: The facade creates a single-class controller that hides the implementation details of the underlying code.
    • Libraries: Libraries are a prime example of a facade. They provide complex functionality through a clearly defined interface.
    • Duplication: If the same code is being duplicated, or the same behaviour, then combining then into a controller class is sensible i.e. a facade.
    • Layers: Remember the layers in an engine, with the platform layer handling all the platform specific calls, through a single API call.
    • When: 
    1. A simple interface is required to access a complex system.
    2. The abstractions and implementations of a subsystem are tightly coupled.
    3. A system is very complex or difficult to understand.
    • Interaction: The facade abstracts packages 1,2,3 from the rest of the application and the clients use the facade class to interact with these resources.
    Game Loops: Decouple the progression of game time from user input and processor speed
    • Loops: Games require feedback loops. If the user inputs an action, we expect a reaction. In order to do this, a loop is created.
    • Modern Day: Even after all these years, games and applications often utilise the humble loop to pool for user input and then react to it.
    • Constant Updates: With games, there is a desire to keep updating and rendering whilst we await user input. The game shouldn't pause but continue to process in the mean time.
    • Input: Game loops fundamentally (threading aside) always check for user input every tick before processing all the game logic.
    • Speed: Our loop is designed to continuously run and not block, therefore our game world is alive and evolves every update or 'tick'.
    • FPS: How quickly or how often the update loop is run can be described, somewhat crudely as the measurement of frames per second.
    • Responsiveness: The FPS controls how smoothly the game input processes input and how quickly it reflects changes on the screen.
    • Hardware/Software: The speed of our loop is a combination of hardware and software. The faster the hardware, the quicker it can process data.
    • Traditional Usage: When working with known hardware configurations, it was easier for the developers to know how long the loop was.
    • Modern Day Loops: These days, it's up to the developer to control the ticks or updates and make sure the game responds accordingly, regardless of hardware.
    • Core: Game Loops are core to all games development. Even if we have an event based system, there's still a loop processing in the background.
    • Fixed Time Steps: Even though we've now slowed the processing time of our game loop, we have a problem when the target FPS isn't met.
    • Performance: Slow down will negatively effect the game's experience, so there's now a requirement to handle updates passes on time passed.
    • The Problem:
    1. Each update advances game time by X.
    2. The time taken to process the update (If two steps take longer than one step etc).
    • A New Problem?: Now, we know the game will run smoothly and advance using the calculated time-step, unfortunately, if two machines have a differing number of updates, we have an issue.
    • Render Async: It is possible to use a fixed time-step for the update game loop, but allow rendering to happen independently of updates.
    • Frame Delta: Conceptually, the frame delta is tracked and added to a counter, when the counter reaches our desired MS, we update the game world.
    • Rendering: If the rendering takes longer than our desired update time, we run the update multiple times until we've caught up on the lag.
    • Rendering Updates: It's possible to render between updates, which can cause judder. We can use interpolation in the render process.
    • Interpolation: The amount interpolated shows how far between two frames the object should be moved. If there's no lag, we need no interpolation.
    Update Pattern: Simulate a collection of independent object by telling each to process one frame of behaviour at a time
    • Updating the Game World: Quite frankly, it's unlikely that the game won't have living breathing objects in it. For each object, we need to update or animate it.
    • The Game Loop: The game loop seems like a sensible place to process the game objects that need updating. This way, they update every tick.
    • Maintainability: Very quickly, the loop becomes bloated and difficult to maintain. Sure, a function could still be written for each type of object update.
    • Pattern: The update pattern is simply a layer of abstraction. Instead of processing updates of objects in the loop, we delegate this to the objects.
    • Succinct Loop: Allows us to keep the game loop succinct and much easier to manage, regardless of the number of objects we add.
    • Living Worlds: Not every game entity or world requires a real-time update function. Think of turn-based games, they react to a players move.
    • Ordering: Most games and their entities are often interdependent on each other i.e. with this in mind, the order they are updated in has consequences.
    • A before B: A will see B's current state, but B will see A's newly updated state. There's a disconnect here that needs to be acknowledged.
    • Updating Lists: If there are changes made to the game entities listed in the container, make sure not to miss any or delete needed ones.
    • Inheritance: In modern day development, massive levels of inheritance are shunned away from. Be careful to consider this when using update.
    • Composition: If we prefer composition over inheritance, we can reduce the level of derived classes and create update functionality on the classes' parts.
    • Dormant Objects: Give thought to how you might manage objects that don't need updating.
    Object Pooling: Improve performance and memory use by reusing objects from a fixed pool instead
    • Memory Fragmentation: Memory Fragmentation is often the primary reason for object pools. They provide contiguous heap of memory.
    • Instantiation and Destruction: Additionally, there's a cost associated with the creation and destruction of objects in our game. Object Pooling allows us to control it.
    • Heap: As discussed in prior lectures, memory fragmentation causes slower performance but also strangles the available memory.
    • Solution: Object Pooling: Grab the biggest chunk of memory we need and don't free it until the level or game ends.
    • Runtime: Define a pool class that maintains a collection of reusable objects. Each object needs a flag to determine if it's 'alive'.
    • Allocation: When the pool is created, all the objects are initialized up front and marked as 'not alive'.
    • New Objects: When a new objects is required, one is found that is currently 'not alive', reset and then set as 'alive'.
    • Vectors: As discussed in prior posts, vectors give us a chunk of contiguous memory on the heap and are quick to iterate.
    • When:
    1. You need to frequently create and destroy objects.
    2. Objects stored in the pool are of a similar size.
    3. Allocation objects on the heap is slow, or could lead to excessive fragmentation.
    4. The resource being acquired is an expensive operation and a cache is more suited.
    • Free List: An alternative to searching through the list to find a free object might be to have a second list or use a sorted associative container.
    • Properties: Are there other fields or properties that can be used to see if the object's in use, saving on the additional boolean.
    • Coupling: The objects being pooled are often aware of the fact, so we could make the constructor private and force the pool to instantiate them.
    • Initialisation: Either the data needed to setup the object has to be passed through to the pool manager, or the pool manager can return it.

    Thursday, 12 November 2015

    Low-Level Programming_Post8

    Low-Level Programming: Post 8 12/11/2015


    November 12th 2015 is the date of the eighth lesson on Low-Level Programming.

    Before the lesson officially began, we were informed of a new approach to have we would have our break (time off). Instead of having a full 15 minutes break after the lectural side of the lesson like we would normally do, instead, we had two 5 minute breaks and one 10 minute break. This was perhaps due to having nearly two hours of consistent teaching to take in, whereas in the new method, we had to take in around half an hour each, which I felt was better, as we could also look back at potential notes taken and take it in generally.

    After becoming aware of the new break system, the lesson officially began. As per usual, we began with being shown the points that we were going to learn today and the components/features that come with them. The main points are as follows...
    • Big 'O' Notation: How we define and describe complexity of algorithms.
    • Design Patterns: What are they & Examples.
    • Auto: The Auto keyword and how it works and when to use it.
    • Windows.h: Do not use (in assignments) and how we can sleep a thread instead, poll for input and clear the screen.
    Big 'O' Notation ('O' stands for Order)
    • Complexity: Refers to how the number of inputs impact the processing time.
    • Algorithms: Focuses on Algorithms.
    • Models: There are mathematical models and computing science, plus various others.
    • Symbolism: Big O Notation is used to describe the asymptotic behaviour of functions i.e. how fast a function grows or shrinks.
    • Letter O: The letter O is used because the rate of growth of a function is called it's order.
    • Orders: When we examine our algorithms we can describe the growth rate of our function in "order of".
    • T(n) = 0(n^2): In this instance our function T grows at the order of n^2 i.e. the growth rate for each input for this function is exponential.
    • Computing Science: When we talk about Big O in computing science, we're referring to how complexity scales depending on the number of inputs.
    • Arrays: For example searching through an array has a complexity that's linear, as we need to potentially check all items stored in it; O(n).
    Orders of Magnitude
    • Magnitude: In asymptotic analysis, we focus on the order of magnitude of a algorithm rather than the actual values themselves.
    • Abstract: Conceptually the amount of time of processing an algorithm takes is unknown, but orders allow us to show how it scales.
    • Big O: Big O notation is the way we express orders of magnitude when discussing the complexity of an algorithms for n items.
    • Traditional Usage: When two values are within an order of  magnitude of 1, they're within a factor of 10 i.e. 10 and 20 but not 10 and 200.
    • Notation: In Big O, the n defines the order, the higher the order of n, the more aggressively the complexity of the algorithm scales.
    • Algorithms: Often, you'll see references to algorithms when discussing a function's complexity.
    Algorithms
    • Meaning: It's a set of rules that govern a series of calculation of problem-solving solutions. Sometimes it's abstractly considered a recipe.
    • Computing: Simply, we can think of each line, operation or function in our program as an algorithm. Rules to tell a computer what to do.
    • Unambiguous: Algorithms are unambiguous, each step does not lend itself to interpretation i.e. Add X to Y and return the result.
    Constant Expression
    • Constant Expression: How do we represent a function or algorithm that regardless of the number of inputs provides us with a constant level of complexity?
    • Element Access: Accessing an element directly in a vector has constant complexity; it's irrespective of the number of elements contained in it.
    • Time Taken: The time taken to retrieve the element has no relationship with the number of items in the array, hence, it's constant Big O notation.
    Linear
    • Linear Expression: How do we represent a function or algorithm that's complexity increases in line with the number of items being processed.
    • Linear Searching: Searching through a vector is an example of linear complexity. For every item added, we need to then potentially loop through it.
    • Time Taken: The time taken to retrieve the element has no relationship with the number of items in the array, hence, it's constant Big O notation.
    Polynomial
    • Polynomial: How do we represent a function or algorithm that's complexity is directly proportional to the square of the size of the input set.
    • Selection Sort: A very simple and easy way to implement algorithms that sort numbers by their lowest value has an exponential complexity.
    • Complexity Growth: The deeper nested the algorithm, the higher the polynomial degree i.e. n^2, n^3, n^4 etc.
    Exponential Big O
    • Exponential: An algorithm whose growth doubles with each addition to the input set. The growth curve is shallow and then rises rapidly.
    • Recursion: Recursive functions that need to traverse through a series of data inputs, cause a doubling of processing for each additional input.
    Logarithmic
    • Logarithmic: The opposite of exponents. This time, the larger the input set, the smaller increase in the algorithms processing time.
    • Associative Containers: Last week, we spoke about how sets and maps use forms of binary searches to locate the item in the container.
    • Complexity Growth: Looking at the graph we can clearly see that working with a bigger data set has significantly less impact than other algorithms.
    STL Search Algorithms
    • Linear: Standard search used when traversing containers using find.
    • Binary Tree: How does Binary Tree searching differ?
    • Red Black Tree: Associative Containers.
    Linear Search
    • Find: One of the most used algorithms in the STL is std::find or std::find_if, both of which are linear in complexity.
    • Distance: It is can be thought of as up to linear complexity for the distance of the container being searched (first to last).
    • Best Case: In the best case scenario, the first element we check is the one we want, which would imply a constant complexity, but we Big O deals with the largest case.
    Binary Tree Search
    • Associative Containers: The containers such as set and map provide an alternative search algorithm based on binary tree searches. The key in the container is stored.
    • Logarithmic: When we look at the complexity, we find it's logarithmic in nature.
    • Linked Lists: They work similar to linked lists but provide the efficiency of search in an ordered array. Each node points to the nodes left and right.
    Verb Tree
    • Finding a Verb: To find the verb 'up', we traverse the tree, simplifying the search domain until we converge on our solution.
    Red Black Tree Search
    • Balanced Binary Tree: Red Black Trees are a form of self balancing binary search trees designed to help the tree maintain it's logarithmic nature.
    • Node Colours: Each node in the tree is coloured, either red or black, whilst preserving the mantra, that the deepest node is not longer than twice the shortest.
    • Leaf Nodes: All nil nodes at the end of the tree will be coloured black and both children of a red should always be black.
    • Height: Every path from a node n to a descendent leaf has the same number of black nodes. The black height is denoted as bh(n).
    • T(n) = 0(log(n)): These properties or rules guarantee that the tree has a height of O(log(n)), since the order is a function of the tree's height.
    • Root Node: The root of the tree is always black, with no adjacent red nodes in the tree allowed.
    • Black Heights: With these rules in place, the root is at least h/2(each red node requires two black nodes). A subtree node has at least 2^bh(v) - 1 nodes.
    Design Patterns
    • Software Architecture: How we design our systems and engines.
    • Patterns: What are Patterns?
    • State Pattern: What's the State Pattern?
    Software Architecture
    • Good Design: Good design can encompass many ideals and concepts, but normally illustrates itself when adding new functionality is seamless.
    • OOP: Fundamentally, this is why OOP design continues to be the standard when building your codebase.
    • Coupling: Remember, if you can't understand one part of a program without understanding another, you have coupling.
    • Performance: All of our design decisions to make code more manageable aren't free.
    • Balance: We want a nicely designed codebase which is easy to understand, debug and extend over it's life time, but also quick.
    • Design Patterns: Design patterns are all about helping us to provide sensible interface and solutions to meet our desirable software architecture.
    State Pattern
    • State Machines: As discussed last week, objects in the game world including the game itself can be broken down to it's constituent states.
    • Usage: When managing the game state for your object is becoming convoluted, now's a good time to use the state pattern.
    Multiple States
    • Concurrent States: You may find that an object in your game, has multiple states unrelated to each other, or require loose coupling.
    • Hierarchical States: It's inevitable that after implementing a number of states that there will be common behaviours between some of them.
    Pushdown Automata
    • Stack: It sometimes makes sense to record a series of states that have happened in order, for this we can emulate the stack principle.
    • Convenience: When transitioning between the character's state, it makes sense that we might want to revert to the last state before the current.
    • Multiple States: Store a current and a stack of previous states.
    States
    • Limited: States are considered fairly limited. For more complex AI solutions, we have behaviour trees, neural nets and pathfinding algorithms.
    • Behaviour Changes: If the object being modelled behaviour changes with respective to some internal state, then states are still valid.
    • Distinct Options: The object can be easily categorized into one of several small distinct states.
    • Input Response: The entity responds to a series of inputs and/or events over time. i.e. input handling, menu screens, pausing text etc.
    Factory Patterns
    • Constructor of Objects: A factory is exactly that; it produces or in this case constructs object's of our choosing. Very common in games.
    • Workings: Very simply, you ask the factory for an object of type X and it constructs it and returns a reference of the newly constructed object.
    • Similar Classes: Often our factory will look after the construction of a multiple of classes, that share the same base class.
    • Parameters: In order to construct the objects, the factory either needs to have sane construction defaults or allow the user to specify them.
    • Storage: Whilst the factory is busy constructing objects, it can use specific pools and even allocate them to a central storage location.
    • Return Type: Depending on the type of storage used and whom owns responsibility for the destruction of the object, you may get the actual object or a reference to it instead.
    In one of the main points, I mentioned that we were told NOT to use the Windows.h file in our assignments. I will now display a guidance as to why we shouldn't use it and similar methods...
    • It bloats your codebase and pollutes namespaces ,defines etc (Lean and Mean config is available).
    • Using the functionality included will tie your program into a single platform, you lose the benefit or portability.
    • Stay away from the use of system commands (system ("pause") etc).
    We were, however, given other features and methods that we could use in our assignments to help us.

    C++11: Sleeping a Thread!
    • Sleep Function: Instead of using the system function provided by windows to sleep, let's utilise the new standards version.
    • Thread: We in effect stall the thread for a given amount of time. Once the time has elapsed, the thread resumes.
    • Literals: C++14 even allows us to specify literals to determine the sleep unit.
    Storing Inputs
    • Windows.h: Windows provides some convenient ways of polling for input, but how can we implement our own 'portable' alternatives.
    • Polling: Instead of running a function that handles the check and the actions, we could store the inputs status in an 'input' class or similar.
    Cleaning the Console
    • System: We could use system commands to do this for us, but i've made a point of disallowing them (slow and non-portable).
    • Alternative: Quite simply, why not just print a series of new lines to the screen, not the most graceful solution, but effective.
    • Platform Independent Code: Or we could attempt to write two different versions of console clearing modes depending on the platform we're running on.
    C++11: Auto
    • Type Inference: C++11 introduces the Auto keyword. This keyword lets the compiler auto-deduce the type.
    • Shorthand: Provides us with the ability to declare variables efficiently and more quickly. i.e. iterators are longhanded, auto resolves this.
    • Usability: Only use auto when the type inference is obvious and it doesn't obfuscate the codebase.

    Friday, 6 November 2015

    Low-Level Programming_Post7

    Low-Level Programming: Post 7 05/11/15

    November 5th 2015 is the date of the seventh lesson on Low-Level Programming.

    At the beginning of the lecture, we were given/shown, as per usual, an overview on the lecture for today. The following bullet points covered what content we were going to be shown today and what we would take away from it.
    • Pointers and Containers: Raw and Smart Pointers and their usage in Containers.
    • Containers: Sets, Maps, Multi-Sets, and Multi-Maps.
    • Algorithms: Find, Find_if and Binary Predicates.
    • State Systems: Game States and how a system might compose of them.
    Unlike some of the previous lessons, there wasn't anything particularly 'unique' at the beginning (such as an assignment overview, Dev blogs reviewing and how it's marked etc). Instead we went straight into the lesson for the day.

    On the first bullet and it's contents, we learnt about Pointers and Containers. We have already gone into some depth on Pointers before and it's varieties (Smart_Ptrs, Unique_Ptrs, Shared_Ptrs and Weak_Ptrs). However, unlike in previous blog posts where I move onto the next point, I am going to make an exception to this one, since it also goes into containers, vectors and how they seem to link together.

    Vectors and Ptrs
    • Containers: It's acceptable and common to have containers of pointers. These can be traditional raw, unique or smart.
    • Considerations: With a Vector, the pointers are stored contiguously in memory.
    • Heap: They're on the heap, but the default allocator has made the decision on their location.
    • Cleanup: The Vector will free the memory it's allocated for the array contents, but any manual heap allocations need to be freed by you.
    • Elements: When you don't want to store copies of an object's array or pointers are a good choice.
    Vectors and Unique_Ptrs
    • Unique Ptrs: Storing a vector of unique ptrs allows us to resolve the deallocation issues.
    • Ownership: Remember the pointer is unique and will remove the data on the heap regardless of any other pointers or refs.
    • Memory Location: Much the same as raw pointers, we just have the wrapper that provides us with deallocation.
    Vectors and Shared_Ptrs
    • Shared Ptrs: Sometimes we might want to store a container of reference counted ptrs.
    • Shared Ownership: Multiple reference to the same data can be controlled.
    • Central Storage: It's possible to return a shared pointer that can be used elsewhere in the game, but also stored in a central container.
    Associative Containers
    • Associative: At the moment the container types we've been looking at are all unsorted with no association between the data orders.
    • Key Values: The key which stores the associated value is used to maintain the sort appropriate to the container.
    • Elements: The key values are how we can look up the elements in the container.
    Set
    • Sets: Containers that store unique elements following a specific order.
    • Unique: Sets only allow one entry per unique key.
    • Key: The value of the object being inserted into the container also dictates the unique key.
    • Sorted: The items are sorted using a comparison object, by default this is the less than operation.
    • Insertions: Sets are good at insertions, regardless of the location the new object is being added, unlike vectors and deques.
    • Binary Search Tree: Underlying principles are based on binary search trees.
    Set Vs Vector
    • Ordered: A set will always retain it's order, a vector will need to be sorted to guarantee it's order.
    • Vector Sort: Sorting a vector can be slow, especially if you need to repeat the process on a frequent basis.
    • Proportional: The time it takes an item to insert into a vector is proportional to the number of items in it. The set is proportional to the log.
    • Initialisation: If you add all the items upfront and then sort one, the performance is negated.
    • Iteration: Faster on a vector than on a set.
    • Set Overhead: Needs to store additional information for tree traversal. Insertions only faster if you're not inserting to the end of a vector.
    Find
    • STL: There's an algorithm include that's part of the STL and allows a linear search of a container.
    • Sets: In associative container like sets, they include their own find algorithm that performs logarithmically instead.
    • Usage: You can use either the associative container version of the STL version depending on your requirements. 
    • Binary Search: If you have a sorted vector, you can perform a binary search using lower or upper bounds.
    Find_If
    • STL: Much like remove_if which requires a predicate you can use a find_if which needs a unary predicate.
    • Boolean: It takes a single parameter and returns a boolean to determine whether the element should be selected/highlighted.
    • Usage: The associative container does not provide this function, it's in the algorithms section.
    Map
    • Indexed Key: Our lookup key is separate from the value stored in the array.
    • Pairs: They use pairs, which has two members, first and second. The first is the key.
    • Set Overhead: Fast insertions and logarithmic lookup times and like set, unique values must be used.
    Multi-Set
    • Sets: Work the same as a set. The difference is that the key does not need to be unique, we can have duplicates.
    • Vector Sort: Sorting a vector can be slow, especially if you need to repeat the process on a frequent basis.
    • Search Trees: Again, often implement as binary search trees.
    • Binary Predicate: We can provide a custom sort predicate that will take both objects and perform a comparison.
    • Function Ptr: Basically, you're passing a pointer to the specialised sort function.
    • Operator Overload: Alternatively we can provide an operator overloaded function that provides a custom sort.
    • Clarity: Using the operator overloader could be considered clearer than passing a function pointer through and is automagically called.
    Multi-Map
    • Multiple Keys: The Multi-Map allows a separate lookup value to the element. With a Multi-Map duplicate, keys are now supported.
    • Usage: If you need to store multiple instances of objects but need to look them up by a key value, then this is the container. Caches which use hashes are one example.
    State
    • Game: In most games, the logic being process is dependent on the current state of the game. (Running -> Jump Button -> Jumping -> Reach apex of jump -> Falling etc).
    • Game Loop: On simple games, you often find that all the logic may be in a single loop i.e. the game loop.
    • Modular: If instead we look at our games as a series of states, we can more easily control what's been updated or checked every update.
    • Specialised: Using states allows us to keep the logic required for updating our objects more succinct and specialised.
    • State Machines: Conceptually the idea of differeing states and transitioning between them is handled by our state machine.
    State Behaviours
    • State-Dependent Behaviour: State machines can be used in any part of our game, where the design lends itself well to processing the logic in a series of states.
    At the end of the Straight-forward lectural side of the lesson (and once the 15 min break finished), the practical side of the lesson began. The practical once again saw us try and work on the DungeonDeath game. Since I wasn't working alone on the game this week, we had an attempt to change the player to have a unique_ptr, which I think we succeeded at. We were also about to attempt to move the static array of rooms into vectors of levels, but we ran out of time.