• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 06:32
CEST 12:32
KST 19:32
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL19] Finals Recap: Standing Tall9HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6
Community News
Weekly Cups (June 30 - July 6): Classic Doubles0[BSL20] Non-Korean Championship 4x BSL + 4x China7Flash Announces Hiatus From ASL63Weekly Cups (June 23-29): Reynor in world title form?13FEL Cracov 2025 (July 27) - $8000 live event22
StarCraft 2
General
Weekly Cups (June 30 - July 6): Classic Doubles Program: SC2 / XSplit / OBS Scene Switcher The SCII GOAT: A statistical Evaluation Statistics for vetoed/disliked maps Weekly Cups (June 23-29): Reynor in world title form?
Tourneys
RSL: Revival, a new crowdfunded tournament series FEL Cracov 2025 (July 27) - $8000 live event Sparkling Tuna Cup - Weekly Open Tournament WardiTV Mondays Korean Starcraft League Week 77
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma
Brood War
General
ASL20 Preliminary Maps SC uni coach streams logging into betting site Player “Jedi” cheat on CSL Flash Announces Hiatus From ASL BW General Discussion
Tourneys
[BSL20] Grand Finals - Sunday 20:00 CET [BSL20] Non-Korean Championship 4x BSL + 4x China CSL Xiamen International Invitational The Casual Games of the Week Thread
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Nintendo Switch Thread What do you want from future RTS games? Beyond All Reason
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Stop Killing Games - European Citizens Initiative Summer Games Done Quick 2024! Summer Games Done Quick 2025! Russo-Ukrainian War Thread
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion 2024 - 2025 Football Thread NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Blogs
Culture Clash in Video Games…
TrAiDoS
from making sc maps to makin…
Husyelt
Blog #2
tankgirl
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 669 users

Game Programming Primer

Forum Index > General Forum
Post a Reply
Normal
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2012-11-17 19:00:24
November 17 2012 02:42 GMT
#1

Game Programming Primer

By CecilSunkure




Game Programming Primer

Introduction

Goal of this Article

The Hobbyist

Professional Programming

Memory intensive

Computation intensive

Prerequisites

Variables, Keywords and Identifiers

Basic formatted input/output

Control structures

Arrays

Functions

Pointers

Structures

Classes

Quick Refresher

Stack and Heap

Bits and Bytes

Arrays

Second class type

Sizeof

Pointers

Address of

Indirection

Pass by value

References

Pointers and Arrays

Pointer arithmetic

Pointer to pointer

Preprocessor

#define

#include

#ifdef, #endif, #undef

Compiling and Linking

Code Organization for Large Projects

Coupling

Source files

Header files

Macros

Prototypes

Multiple Include protection

Circular inclusion

Forward Declarations

Extern

Data structures and program design

Linked lists

Ordered list

Array

std::vector

Hash table

Messaging

Game Engine Architecture

Overview

Systems

Main Loop

Display

Input

Memory Management

Object Management

Game logic

Physics

AI

Component Based Design

Component Based Game Objects

Factory

Data driven composition

Additional isolated topics

Finite State Machines

ActionList

Improved Messaging

Generic programming

Bitmasks

User Interface by Sean Reilly

Game User Interface

From Scratch

Preexisting Library

Editor User Interface

In-Game

External

External with Game Embedded

Serialization

Dump the Bytes

Streams

What to Serialize

Serializing Pointers

Optimization for C++ Games

Delayed Construction

Pre and Post Increment

Initializer List

Preallocate Objects

Reflection: Type MetaData

Example Engine

Introduction

Hello! My name is Randy Gaul, and I am a computer science student. I study at DigiPen Institute of Technology, and am majoring in Real-Time Interactive Simulation (a fancy way of saying game programming). I’d like to share my know-how in the ways of game programming as a profession for anyone interested in learning. I encourage anyone interested in programming or creating games, no matter how little knowledge you have in either topic, to check out this article.

Goal of this Article

Before my studies at university I had spent a good deal of time trying to learn what it is like to create a piece of useful software from scratch. I spent many hours studying the basics of programming such as control structures, program design and even abstract data types. I however was hardpressed to find any high-level information on how to piece together the smaller tools of programming in order to make a project of my own. This article aims at bridging the gap between the realm of a beginning programmer, straight into and through the intermediate level.

There will be very little actual code examples throughout the article, and this is intentional; by providing a higher level summary I can keep the article concise (I can’t write an entire novel inside of a KnowHow!). In doing so I can summarize and present many explanations and concepts that are essential to understand in order to progress as a programmer in a very clear and unified manner. I’d like for even non-programmers to be able to skim through the article and find interest in the ideas and concepts presented. In a way you can expect this entire article to be a firehose of information. If a reader hasn’t be introduced to many of the concepts presented here, he will surely return again and again as much information will not be fully gleaned in a single read-through.

The Hobbyist

There’s a type of game programming that can be done purely as a hobby. This usually involves a single person or a very small group of people developing a video game in their own spare time. Middleware is a term used to describe a tool that is used to create or connect a software project together. Middleware such as FMOD for a sound system, or Box2D for physics can be used to allow a developer to cut drastic chunks of work needed to get a project up and running. Hobbyists in the sense of what I’m trying to refer to don’t usually have professional level skills in game development, and simply create games for fun.

Tools for creating games in a manner like this are quite plentiful; here’s a few:

  1. Pygame
  2. Flash
  3. Game Maker
  4. XNA
  5. Other pre-created engines or libraries
  1. Unity
  2. Box2D
  3. SDL
  4. SFML

Tools like these can be wonderful for creating games, but this article isn’t dedicated to this area of game programming. I intend to write about how to start programming with the intentions of programming as a profession.

Professional Programming

As a professional programmer one should strive to understand as much as possible as to how a computer works, and how they can leverage a programming language to solve problems efficiently. As such, writing a game as a professional programmer revolves around the use of C/C++. This is because C++ lets you get as close to the hardware as realistically possible, thus granting lots of control over how the program runs; many things in C and C++ are hidden away from the developer and in turn makes them slower. Having slow code isn’t acceptable for high performance real-time applications such as games.

C++ is integral for anyone that wishes to have a career in the video games industry as a professional developer, especially if you want to have the best chances at success when you first start attempting to get a job as a game programmer.

Real-time applications, like video games, need to run in a highly efficient manner, and as such require skills of the programmer that may need be so important in other areas of Computer Science. As I myself am studying to become a professional software engineer, this Know-How is geared towards an audience interested in learning about game programming as a professional, not only as a hobbyist. For the rest of the article I will be referring to development of video games as a profession.

Memory intensive

Video games are very memory intensive. They can easily require a lot of memory, and as such will usually benefit from efficient use of memory. Efficient memory usage can let a game have more content and assets on the screen at a given time, or allow for more advanced features than the hardware would otherwise allow. For example the SNES had a very hard time scaling and rotating images in real-time with some of its hardware, and as such most snes games don’t do these two things. However with the addition of a specialized GPU chip in the SNES, some games were able to make interesting use of such a feature (Yoshi’s Island comes to mind). In order to get the most out of the limited powers of the SNES very tight memory management had to be employed.

So what is memory management? Memory management is the handling computer memory. This include allocation and deallocation. Many situations involving memory management become very non-trivial, and as such it’s an area of study that is crucial for anyone interested in professional software engineering, especially in game development.

Computation intensive

Besides being memory intensive, real-time simulations have the requirement of having very efficient algorithms and computations. In mathematics there’s no sense whatsoever of efficiency in solving problems, however each operation done on a computer has a cost. It’s up to the programmer to find the most efficient ways to solve problems. This efficiency requirement is due to video games needing to be run at a speed that is not only playable but fun.

Prerequisites

There’s some prerequisite knowledge required in order to apply the concepts presented within this article. However I’ve attempted to structure the article such that a lack of basic programming knowledge shouldn’t hinder the reader too much in understanding the overall ideas. I’ll quickly list off the various prerequisites required to to start actually applying the concepts yourself, and in the next section will provide a quick reference to understanding some of the “problem areas” a lot of programmers come across. Though I do cover some of the more advanced areas of basic programming, I will not be writing a comprehensive guide to learning C and C++.

Comprehensive books on both C and C++ are required for anyone interested in becoming a professional game programmer. Luckily I have two wonderful books that are pretty much my bibles when it comes to both C and C++. The first book is on C programming by C Programming: A Modern Approach, 2nd Edition.

Here’s a brief description of the book as seen on Amazon:

Professor King's spiral approach made it accessible to a broad range of readers, from beginners to more advanced students. With adoptions at over 225 colleges, the first edition was one of the leading C textbooks of the last ten years. The second edition maintains all the book's popular features and brings it up to date with coverage of the C99 standard. The new edition also adds a significant number of exercises and longer programming projects, and includes extensive revisions and updates. - Amazon.com

C Programming: A Modern Approach is definitely the best C book for learning all of the preliminaries shown in this entire article. This book also covers a lot of the topics in great detail from my A Quick Refresher section. Though I do link to many free alternatives, be warned that when I first started learning programming nothing could ever compare to this book.

The second book I have to recommend is C++ Primer Plus (5th Edition), the latest edition. Here’s an excerpt from Amazon.com about the book:

If you are new to C++ programming, C++ Primer Plus, Fifth Edition is a friendly and easy-to-use self-study guide. You will cover the latest and most useful language enhancements, the Standard Template Library and ways to streamline object-oriented programming with C++. This guide also illustrates how to handle input and output, make programs perform repetitive tasks, manipulate data, hide information, use functions and build flexible, easily modifiable programs. With the help of this book, you will:

  1. Learn C++ programming from the ground up.
  2. Learn through real-world, hands-on examples.
  3. Experiment with concepts, including classes, inheritance, templates and exceptions.
  4. Reinforce knowledge gained through end-of-chapter review questions and practice programming exercises.
  5. C++ Primer Plus, Fifth Edition makes learning and using important object-oriented programming concepts understandable. Choose this classic to learn the fundamentals and more of C++ programming.

Reading both of these books and studying them inside out is something any programmer needs to do if they wish to create their own game from scratch in C++. There’s just no replacement for lots of studying and lots of practice. This entire article isn’t intended to be a replacement for such studying, but merely a primer to. Get the books. Read the books. Study and breathe the books; they will provide with the foundation to carry your career for the rest of your life if you put in the effort to do so.

Variables, Keywords and Identifiers

Every programming language has both keywords and identifiers, and all programming languages I’ve used have some form of what a variable is, except for Assembly. An understanding of what each of these three things are and how they are used in programming should be researched and practiced.

Note: some languages have “typeless” variables, or variables without a specific type. Python and Lua both employ typeless variables, whereas C and C++ enforce strict typing. Strict typing, aka explicit typing, incurs less overhead upon the machine; converting from one data type to another often requires a modification of the bits of memory that a variable is represented. This modification of bits has some overhead.

Basic formatted input/output

Input and output to stdin, stdout, and file input/output should all be understood by the reader. These forms of input and output are useful for debugging, logging information, presenting information to users, storing data within files on-disk, and for retrieving data from files on disk. These topics are quite simple, and luckily many people for many years have written much documentation on them.

Some terms in which to start google searching related to this topic are: printf, cout, cin, scanf, fstream, stdio.h, iostream.

Control structures

A control structure is a bit of code helps determine what code will next be executed and when, once it itself is executed. There are a few different types of control structures that all programmers should know, and these control structures are generally features of most every programming language. Looping, and logical if, then else statements are control structures.

Arrays

An array is a chunk of variables stacked right next to each other in memory. A variable within an array is referred to as an element.. Each variable is of the same type of data, and so the offset of each element can be known given the size of the array in number of elements due to this. This allows random access to any part of an array, without needing to travel along the array to find a given value. The random access of arrays is what makes them so fast and efficient.

Functions

A function can be thought of as a type of control structure. A function is a chunk of code that be executed by a single piece of code somewhere else. For example mathematical equations can be thought of as functions: they take some form of input and present some form of output. A function in programming takes some information, runs operations, and then optionally returns information.

Pointers

A basic understanding of what a pointer is in C/C++ and how they can be used will not be explained here. There’s a never-ending supply of references for the basics of pointers online, and I’m sure many people have explained it as good as I ever can, or better.

In short, a pointer holds the memory address of a location in memory, and stores information about the type of data that resides at that location. This allows for the passing around of the location of data, rather than passing around and copying the data itself (as passing around data that is very large and copying it from one location to another has massive overhead).

Structures

A structure is a way storing pieces of data together within a single named package. This allows different types of data to be grouped together to form a new type of data.

Classes

Classes are a very large topic, so I’ll try my best to summarize what they are. A class in C++ is a structure with additional functionality. A class has language support for storing functions that modify itself, and in this way the data inside a structure will have clearly defined operations that it can perform upon itself. Class are a construct of Object Oriented programming.

Quick Refresher

This section is an attempt to clear up a lot of problem areas that myself and other programmers might have when just starting out in programming. These topics need to be understood in a strong manner in order to become an effective software engineer with C/C++.

When I was first beginning I never came across most of the information I’ll try to present here, however the information would have been very valuable given I had earlier access to it. Hopefully it can be of help for others in a similar situation.

Stack and Heap

For quite a while I didn’t have a solid concept of what the stack and heap are in C/C++. I feel it’s important to have a clear understanding of both, as knowing the differences between both is essential for basic memory management.

The stack is a location of memory assigned to a process (program running) when it starts. The stack is managed automatically, and is used to store things like global and local variables. Whenever a variable or array is declared within the scope of the program, it resides within the stack. Stack memory is very time-efficient to use, as it has been pre-allocated by the run-time upon program start.

The heap is memory is a large location of memory that dynamic memory can be requested from. A program can request any amount of memory from the operating system, and the OS will then search the heap for a chunk of empty memory of the specified size. In this way the memory that a program uses can change during run-time, whereas the stack is of a fixed size. Allocating dynamic memory requires the OS to search for an empty chunk, and this incurs a lot of overhead.

It should be noted that if a chunk of memory is allocated from the heap, it can act in a similar way to the stack. The programmer can allocate dynamic memory, and use it to provide smaller and more frequent allocations. These smaller and more frequent allocations require much less overhead than requesting them directly from the OS, as the programmer can make optimizations within their own dynamic stack that the run-time does not.

Bits and Bytes

All memory is in the form of bits. A bit stores one of two things: the number zero or one. A byte is a collection of 8 adjacent bites. By using each bit to count in binary, a range from 0 to 255 can be achieved with a single byte. An entire computer is composed of transistors and bits! There’s an immense amount of detail involved in how computers work on the machine level, so much so that I can’t write much about it right here right now. Luckily Charlze Petzold already has. Any programmer that wants to have a proper understanding of computers and computer hardware (which is anyone interested in game programming professionally) needs to read this book: Code: The Hidden Language of Computer Hardware and Software. This book was a required reading at my university, and the details of how a computer works from the ground up is something that allows me to feel very confident in my understanding of computer science.

Arrays

Rather than providing a comprehensive documentation of arrays, I’ll attempt to cover a few specific areas that are rather murky for early programmers.

Second class type

Arrays in C and C++ are second class data types. This means that they don’t have all the functionality of first class types such as ints or chars. This fact means there are some interesting behaviors of arrays.

Arrays cannot  be passed around from one location to another directly. If attempted, the name of an array will be converted to a pointer to the first element in the array. This incurs a loss of information, as a pointer stores information about location and type, whereas an array stores location of first element, type of the elements and number of elements. This “feature” of C and C++ can actually be viewed as a “language bug”.

Sizeof

The sizeof keyword is an operator. The way it works is very simple and a quick google search will give more information than ever needed on it. However when used with arrays it can be a little quirky.

An array in C and C++, as I said in the previous section, stores data about the size of each element, type of the element, location in memory and the number of elements. This allows the sizeof operator to intelligently calculate the number of bytes of memory of all the elements of an array combined. However this information can be lost if the array is converted to a pointer, and taking sizeof on a pointer is generally only 4 bytes of information.

Pointers

Address of

The & operator is called the reference operator. I however always refer to it as “the address of”. If you remember to call the & operator “the address of” it suddenly makes code very readable in a simple and intuitive way. Using the address of operator on something returns the address to the location in memory that the something resides within.

Indirection

The * operator is the indirection operator. When used on a pointer it retrieves the value at the address the pointer holds. Very simple. This operator is called the Dereference operator, though I like to read it as “the content of”, or “content at location”.

Pass by value

Whenever data is passed around there is overhead involved in copying data from one location to another. Data passed to a function incurs overhead. Instead of passing large pieces of data around themselves, passing a smaller pointer to that data will often be much faster, as copying 4 bytes of pointer data is very fast compared to a large piece of data. In this way the location of pieces of data can be used as “identifiers” to retrieve the data. You can think of this as passing around a key to a treasure chest. Whoever holds the key has access to the treasure inside, and it then becomes easy to transfer ownership of the treasure; you just pass around the key. However a chest full of treasure isn’t going to be passed around itself very often because of how heavy it is.

References

References are an addition introduced with C++. References confused me for the longest time, as I just couldn’t understand exactly how they are implemented. As it turns out references can be explained as pointers with a few rules.

Think of a reference as the exact same thing as a pointer: it holds a location in memory and type information of what resides at that location. However a reference is constant. A pointer’s address can be changed at any time (unless it is const), but a reference’s address will not be changed once it is initially set. Furthermore a reference cannot be uninitialized. When a reference is created it must also be immediately initialized.

Other than this the only difference between references and pointers (that I am aware of) is syntax rules.

Pointers and Arrays

An array’s name can be converted to a pointer implicitly to the first element implicitly within code. This means that at any time the name of an array can be treated the exact same as a pointer to the first element. This makes passing an array around impossible in C and C++; instead you must pass a pointer to an element in the array and perform pointer arithmetic to traverse all the other elements. This brings us to our next section.

Pointer arithmetic

Adding an integer to a pointer offsets that pointer by the number of bytes equal to to number being treated as the number of elements to offset. Example:

int a = 10;

int *p = a;

p += 5; // p now holds the address of a + 5 * sizeof( int )

In the above example p is offset by 5 times 4, which is 20 bytes. When you subtract two pointers from each other, the result is the number of elements between the two pointers, not the number of bytes.

Knowing these facts can let you loop through an array very easily with a single pointer, given you know how to stop your loop:

const char *words[] = { “This”, “is”, “an”, “array”, “of”, “words.”, 0 }

for(; *words; ++words)

  printf( “%s”, *words  );

// Output: This is an array of words.

The above code snippet prints the array of strings, and stops when it hits the last element of zero. This works in a very simple way. words is a pointer to an array of strings. Incrementing words with the preincrement operator results in offsetting the words pointer by the size of a char pointer. Dereferencing words will result in a const pointer to a character (also known as a string), and can be printed in printf as such. Once the content of words (*words) is at the last element, the result will be zero thus ending the for loop.

Pointer to pointer

Having a pointer to a pointer is valid C code. Doing such a thing is commonly useful when dealing with arrays. As I’ve said many times, the name of an array can be treated as identical to a pointer to the first element. So, if you need an array of arrays, you can use a pointer to a pointer. This is actually the technique used from the code snippet from the last section.

Preprocessor

The preprocessor is a part of the compiler the processes the text of source code into an intermediary format just before compilation. The preprocessor expands all macros, and operates on all preprocessor directives (which will be talked about momentarily). Understanding how the preprocessor works lets a programmer use it as a tool, and effective use of the preprocessor is something I wished I had learned when I first started programming.

#define

#define is a preprocessor directive. This means it’s a command that the preprocessor will come across and perform a particular operation upon. The #define directive allows the programmer to specify that a certain piece of text (technically a certain token, not piece of text, as a token is delimited by certain characters in C/C++ code like whitespace), no matter where it is placed within the code, will be replaced by a chunk of replacement code. This allows the programmer to tweak multiple locations of code by modifying a single entry point of the #define directive. Effective use of the #define directive makes modifying and maintaining code easier.

Here’s a quick example showing good use of the #define directive to create a preprocessor “variable”.

#define NUM_MAX 256

// Code snippet ...
int anArray[NUM_MAX] = { 0 };

PopulateArray( anArray, NUM_MAX );
// fill array with data

for(int i = 0; i < NUM_MAX; ++i)
{
 printf(
"%d\n", anArray[i] ); // print data in array
}

// Clear all data in the array
for(int i = 0; i < NUM_MAX; ++i)
{
 anArray[i] = 0;
}

Now the programmer can swap the value of the NUM_MAX macro whenever this value needs to be tweaked. This is much easier than modifying a bunch of code to tweak a single value by hand.

The #define directive can also be parameterized. See the appendix for additional information, within the The C-Style Macro section.

#include

The #include directive tells the preprocessor to take the entire contents of a file and do a literal copy/paste of the contents to the spot where the #include directive is located.

#ifdef, #endif, #undef

#ifdef is used to check and see if a particular definition created with the #define macro exists yet during the preprocessing stage. If the macro does not exist, all code between the #ifdef and matching #endif directive omitted.

This allows for inclusion protection. Refer to multiple include protection section for further details.

#undef can be used to undefine a previously defined definition. This is useful when some header file you have to use (perhaps Windows.h) defines something. If you really want to use that identifier you can actually just use #undef to free the identifier up for your own use.

Compiling and Linking

Compiling is an act a compiler does upon code. First C/C++ code is translated into assembly. From here it is then translated into machine code, and placed into an exe file.

Linking is an act the Linker performs (usually right after compiling). It takes the compiled machine code and hooks up all the function definitions to their references throughout the code. It also links all global variable declarations to their definitions. In short it replaces all references to “things” in your code with actual memory addresses. If a particular “thing” reference, such as a function or global variable does not have a matching definition, then the linker will output a specific linker error.

Understanding the difference between compiling and linking allows a programmer to have an easier time determining what errors a compiler or linking present mean, and in turn allows the programmer to more quickly find solutions to those errors.

Code Organization for Large Projects

Having proper code organization for really large projects is actually something I’ve just finally come to full-grips with. As a project gets larger and larger, having a strong sense of exactly how a program should be structured into multiple files will help save a lot of time.

Coupling

Coupling in computer science is the amount by which one section of code relies on another section of code in order to function properly. As a programmer you want to try to make sure that each individual function and set of functionality you write is as independent from everything else as possible.

Imagine you have three functions, and each one relies directly on the others. Assume they allow you to fly (somehow ). So you have three functions that let you fly, yay! However now lets assume you want your buddy to fly too. Well, your three functions are coupled to you and each other, but you buddy only needs two of those functions! Now you have to copy/paste and modify two of your functions to get your buddy too fly.

It would have been much more efficient if your flying functionality was written so that it could be reused in the future. If you as a programmer decouple the “flying” code from yourself and even decoupling the three flying functions from each other, you might have not needed to modify any code at all in order to get your buddy to fly.

Source files

Source files are either .C or .CPP files. Source files are where definitions go, and occasionally forward declarations (forward declarations are described a few sections below). Definitions for global variables, static variables, functions, and class functions (methods) go within .CPP files.

A single file should only contain definitions of functions that behave to solve a common task. As a rule of thumb no file should go over 2000 lines of code. Splitting functions into separate source files based on common behavior allows a developer to easily sift through files by name and find what function they are searching for. It also minimizes the amount of time a person must spend scrolling up and down a file in order to find a particular function.

In order for functions to call functions within other files, header files come into play.

Header files

A header file is used to declare various things such as functions, variables, classes, structures, etc. A header file should not ever contain any implementation (unless it is of templated code, which will be mentioned shortly). The purpose of a header file is to show how things are used. For example a header file can contain function prototypes that correspond to a particular C file. The header is then providing information that allows other source files to see what goes into a particular function, and what comes out. This allows other source files to use functions within another source file, without actually having direct access to that source. The Prototypes section of this article goes into this in more detail.


A header file is included into a source file with the #include preprocessor directive.

The same thing goes for class and structure declarations. A header file should contain a declaration of what a specific type of structure or class looks like, and the source file contains implementation of that particular data type.

Here’s a quick example of using header files to include other files into a source file.

// Header file #1
int Max( int a, int b );

// Header file #2
int Foo( float x );

// Source file #1
#include
"Header file #1"
#include
"Header file #2"

// Some code that does stuff
// ...
// ...

// Source file looks something like this after the
// preprocessor has its way with it:
int Max( int a, int b );
int Foo( float x );

// Some code that does stuff
// ...
// ...

Macros

Macros in C and C++ are usually placed into header files to allow multiple source files to make use of the macro without having the #define directive for the macro lay in multiple files. This means that any macros created should have very clear documentation on their use and purpose, all within the header file they reside. In this way you decouple your macros from specific source definitions whenever possible.

Prototypes

In order for a source file to be properly compiled all functions within the source file that are referred to must have either definitions for function prototypes within the source file, somewhere above where the function is referred to below.

It isn’t practical to put a function’s definition in more than one source file, so to allow functions to reside in separate source files, header files can contain function prototypes. A prototype for a function looks like this:

int Foo( int a );

In the example above a function is declared called Foo that takes an integer and returns an integer. If a source file has the prototype (aka declaration) of Foo, it can refer to Foo and even call it without actually knowing the definition of Foo. That’s because the code that uses Foo only goes about what goes in and what comes out (the return value and arguments).

Here’s a quick example showing how to use a function prototype in order to properly call it from an entirely different source file.

// Header file #1
int Max( int a, int b );

// Source file #1
int main( void )
{
 Max( 1, 2 );
// Causes a compile error
 
return 0;
}

// Source file #1
#include
"Header file #1"

int main( void )
{
 Max( 1, 2 );
// No errors here! We have the prototype
 
return 0;
}

Multiple Include protection

There’s an issue that can arise whenever a header file is included more than one time. Take a look at this example.

// Header file #1
struct SomeStructure
{
 
int x, y;
};

// Source file #1
#include
"Header file #1"

// No problems here!

int main( void )
{
 SomeStructure a;
 
return 0;
}

// Source file #2
#include
"Header file #1"
#include
"Header file #1"

// ERROR! Cannot declare structure type twice! SomeStructure is already defined in Source File #2

int main( void )
{
 SomeStructure a;
 
return 0;
}

As you can see, there’s a big issue when a header file is included multiple times. You might be thinking “well why would I ever include a header file twice?”, and this is a good question. The issue arises when two different source files include the same header. Both source files cannot both contain the declaration of the structure type as seen in the example. It can get particularly messy if header files are including other header files.

So how can this madness be stopped? With the use of #ifdef and #endif preprocessor directives. Take a look at this header file.

// This is a header file!

#ifndef HEADER_FILE
#define HEADER_FILE

// The usual header stuff
// ...
// ...

#endif // HEADER_FILE

As you can see, the contents of this header file will only be included a single time into a source file! They just happen to also be included into the first source file to include, and as such all source files compiled thereafter will have access to its contents. Usually the define of choice is related to the file name to ensure unique define protection identifiers.

Circular inclusion

Circular inclusion occurs when two or more header files both include each other. Imagine what would happen in this situation? Files would infinitely include one another. This classic problem can be very annoying to deal with. Circular inclusion usually gives you some very weird compiler errors, and can be very annoying to deal with. The best solution to circular inclusion is to avoid it altogether. Forward declarations and smart header file design are your weapons of choice. See the next section for details.

Forward Declarations

Forward declarations are an excellent way of mitigating file dependencies. Take a quick look at this short code example.

// Header file #1
class SomeClass
{
 
// stuff
 
// ...
};

// Header file #2
#include
"Header file #1"

class SomeOtherClass
{
 
public:
   SomeClass *p;
}

// Header file #2 - improved
class SomeClass;

class SomeOtherClass
{
 
public:
   SomeClass *p;
}

As you can see, SomeOtherClass only requires a pointer to SomeClass. As such, a declaration of SomeClass is sufficient to create a pointer to it; to point to an address the entire declaration of the SomeClass class isn’t required! This is perfect for reducing file dependencies.

Forward declarations of class and struct types should always be used in favor of file inclusion whenever possible.

Extern

Extern is something I wish I had known about long ago in my programming endeavors. Extern allows forward declarations of global variables within header files, without actually defining the variable. The variable definition can then reside within a specific source file. Extern can be thought of as allowing one source file to have proper access to a global variable within another source file. Here’s a quick example.

// Header file #1
extern int global;

// Source file #1
int global;

// Some code
// Probably use global within it
// ...

// Source file #2
#include
"Header file #1"

void Foo( void )
{
 ++global;
// we can access this global through the header!
}

Data structures and program design

There are a few data structures in particular that every game programmer should know about. I won’t be going very deeply into the details of how to implement each of the sections here, instead I’ll be focussing on a high-level summary followed by an important explanation of how and why they are useful, and how best to utilize each to solve particular problems.

Linked lists

To understand a linked list one must have an understanding of both structures and pointers, and ideally an understanding of classes as well.

A linked list is a container for abstract nodes. The length of the linked list is arbitrary, and each node contains some sort of data. The nodes are connected together with pointers. Inserting a new into a list is as simple as making a pointer in the last node point to the node to attach. Disconnecting a node from a list involves changing some pointer values.

[image loading]

Inserting and removing nodes from a linked list is extremely efficient as it involves merely a few pointer calculations. Searching through a list however is much slower, as the offsets and locations of each individual node are not known, and so direct random access as like in an array is not applicable.

So now what are linked lists useful for? This is a question that I had pondered for quite some time. Linked lists are useful whenever you have some form of data container that you need to constantly add new information to, and remove information from. Ideally you won’t need to search for particular individual or sets of nodes.

A great example of when to use a linked list is to store game objects. A game object usually doesn’t need to be searched for through a linked list (other methods such as a hash table can be used); it just needs to exist. Every game loop the linked list can be traversed, and update functionality can be called on each game object in linear fashion (though not in a particular order, unless the linked list is an ordered list). Game objects can be created on the fly easily, and little overhead is involved in insertion into a list. Game objects can also be easily removed from the list whenever needed.

Linked lists can also be perfect for some form of undo functionality. How do you think programs store information regarding the actions a user performs, in order to create some sort of undo button? A linked list can be perfect for this situation, and can be made to support an arbitrary amount of actions; this would be substantially more difficult to do with an array, as an array would require messy algorithms re-allocation once the array limit is reached. Each action can be stored as data within a single node. To perform undo, the inverse of each action can be performed while traversing the list in reverse order.

Ordered list

An ordered list is a linked list in which the nodes are ordered depending on what data they contain. To have a list be ordered one of two things must happen: an ordering algorithm is ran on the list; nodes are inserted into the list at the appropriate location. Often times a linked list doesn’t require an expensive sorting algorithm as nodes will never be moved around from one position in the list to another, and as such can simply be inserted into the correct location. If each node is placed into the correct location (perhaps by comparing integers of the node to place to each node in the list until a correct spot is found) then the list will always be in correct order. This allows the programmer to ensure that specific nodes are found first whenever traversing the list.

Imagine you have a list of game objects, and some of them need to be drawn. You traverse the list and once you find a game object that needs to be drawn, you order it to be drawn. Then you look at your screen to find that some objects are drawn over top of others. Blasphemy! An ordered list can easily solve this problem: as objects are inserted they can have a zOrder data member (just an integer), allowing them to be drawn before or after other objects. This is a form of zOrdering.

Array

An array is very useful for speed of access. An array provides random access to it’s elements by performing some pointer calculations; this provides a constant lookup time for arrays of arbitrary length. The only issue is that arrays must be indexed by an integer in order for the pointer calculations to work properly.

These properties make arrays ideal for storing data of known quantities that need to be constantly accessed. In a way an array provides strengths that are the weaknesses of the linked list, and vice versa.

An example of usage for an array is to store level files. A level file can be loaded from a file on disk, and before populating the level the dimensions of the level can be read from file. These dimensions can be used to create an array of a specific size, and then it can be populating with information from the file on disk. This array can then be accessed very efficiently to any position within it.

std::vector

The standard vector is a very useful all-purpose container that functions like an array. At its heart the vector actually is simply just an array, except the vector has a lot of member functions to perform operations on the array. The vector has the capability to grow and shrink, and automatically does so once it requires additional space to insert new data. Growing a vector is a bit simpler than shrinking one, but growing can be horrendously slow; to grow an array you must allocate new space, copy the old contents of the old array and place them within the new space, and then delete the old space. As you can see if growing and shrinking are common operations on some sort of data, an array or vector is probably not ideal.

Hash table

A hash table is a form of an array where a particular index maps to a specific element. The index can be an arbitrary type of data, not only an integer. This allows very convenient syntax such as:

IMAGE_MAP[“image name”]; // Retrieves an image by string identifier

In the example above the “image name” is what is called a key. A key in a hash table is an index that maps to a particular element in the array. The key itself is converted into an integer index using a special hash function.

Here’s an example (albeit simple) hash function for converting a string into an integer:

unsigned SimpleHash( const char *key, unsigned tableSize )

{

  unsigned hash;

  while(*key)

  {

    hash += *key;

    ++key;

  }

  return hash % tableSize;
}

Hash functions can be used to generate keys from any arbitrary data, not just strings.

With any hash table resolving collisions is important. When creating a hash table it is assumed that each individual key is unique. If you do not have some form of unique keys get some. If you cannot, then you cannot use a hash table. Although each key is unique it is not guaranteed that each key maps to a unique index. When two keys map to the same location this is called a collision. Taking care of this collision is what is called collision resolution.

There are two main forms of collision resolution: linear probing and chaining.

Hash tables are ideal for storing data just like an array, except when the index of a particular type of data isn’t a known integer. For example storing art assets for a particular project is a perfect time to use a hash table: art assets can then be retrieved with the hash function like so:

Asset *FindAsset( const char *key )

{

  unsigned index = StringHash( key );

  return ART_ASSETS[index];
}

A simple macro can be used instead of the function above:

#define FIND_ASSET( key ) \

  ART_ASSETS[ StringHash( (key) ) ]

I fell in love with hash tables for a particular project, and ended up using them great affect to name just about everything in this project: by utilizing an efficiently written hash table arrays can be indexed by string identifier instead of integer or enumeration. This allows a programmer to write rather readable code without magic numbers, without incurring much computational overhead. Here’s a link to the particular project.

Messaging

This section can very easily go on and on forever, so I’ll do my best to keep it concise. Messaging solves the problem of passing information around within your code in a loosely coupled manner.

The simplest form of messaging is a function call. By calling a function you pass it information through the function’s parameters, and it communicates back in the form of a return value. However in order to directly call a function you need that functions signature, which requires some sort of inclusion, perhaps a header file. By utilizing messaging one can cut into the amount of dependencies from one code section to another dramatically.

A message object is a single structure or class that holds a type identifier and some sort of data payload. The identifier lets any piece of code know what sort of message the message actually is. This lets code ignore messages that have identifiers it does not understand.

The simplest form of passing message objects around is with switches and enumerations. A message can be sent to a dispatcher, which consists of a switch statement that switches on the messages identifier (ID). If a matching ID is found, some form of action can be taken. If a matching ID is not found the message can safely be ignored. This means that new message types can be added at any time without conflicting with any pre-existing code, thus limiting upkeep cost of the messaging system to a minimum.

Game Engine Architecture

Game engine architecture (and project architecture in general) seems to be a commonly misunderstood and overlooked area of expertise. Before I talk about architecture I need to define what a game engine is. Simply put a game engine is a collection of functionality to allow a game to run. Game engines are not always general purpose, and much of the time game engines that focus on generalization lack what is needed to make a successful an immersive game. As such most game engines are very specific to the game that they are used to create. For example the Source engine by Valve is used (to my knowledge) for first person view games, namely shooters.

Now lets talk about architecture. Here is what architecture is defined as, as defined by my professor Chris Peters:

Architecture is the organizational structure of a system, including its decomposition into parts, their connectivity, interaction mechanisms, and the guiding principles and decisions that you use in the design of the system. - Chris Peters

What this is saying that good architecture makes it as easy and simple as possible to develop whatever type of functionality is required for your project. I bolded the word simple because it’s much too often overlooked. Architecture is simplicity. An overly complex solution is the sign of a bad architect! The best solution is often the simplest one.

A project’s architecture should aim to embrace change: the whole point of developing a project is to create a product. That product will often times change over the course of development, and so a strong architecture will embrace this change. I talked briefly about embracing change when mentioning messaging and in other topics such as coupling. In a way much of this article is actually about good architecture.

The best book for a beginning architect I can recommend isC++ For Game Programmers (Game Development Series) by Noel Llopis. This book covers a wonderful collection of topics, and can bring a standard newcomer to game programming who is familiar with the basics of C++ to a level of competency strong enough to create their own well-structured engine architecture. A must have for anyone interested in creating their own game engines in C++ from scratch (something ever CS student needs to do if they want the best chances at great game dev jobs straight from school).

Overview

Within the next few sections I’m going to attempt to bring everything together. How can all the previous information be used and connected together to form the architecture of game engine? I must inform the reader now that there is no single True Way to create a game engine. The methods proposed here but a single solution.

Systems

An engine is a collection of systems. Each system performs a specific type of task. There are two types of systems: Systems and Game Logic Systems. Systems deal with hardware related tasks or non-game logic tasks such as input, graphics, framerate control (timestep), memory management, audio management, and game state management. Game logic components include physics, AI, environment, other object interaction. This section will attempt to describe each briefly.

Main Loop

The main loop of a game is the loop that runs the rest of the game. I’ve seen some pretty crazy main loops in novice developers’ projects, and hopefully this section will help rid of some future ones.

For this section I will point the reader to a previously written article by myself. Feel free to refer to it as you wish. I won’t be going into implementation details like in the article, though I will describe the overall idea here.

Lets talk about the Game State Manager (GSM). A game state manager is a method of creating a highly organized main game loop, which is generalized to the point that it can apply to any situation without pre-runtime modification of code. The game should always be in a state during runtime. That state could be the main menu, a pause screen, or a specific level or scenario. A state is divided up into multiple categories, and these categories are generalized enough to apply to every state the game can be in.

Once a GSM is constructed the main loop should never need to be modified again. New states can be added at any time, and new states will not conflict with any previous written ones thus making for a highly decoupled and flexible design.

Display

The displaying of a project on a screen is handled by the Graphics system. A graphics systems should handle loading of all graphic related assets, store those assets in memory, and render them to the screen.

Some frameworks and/or libraries for graphics functionality is listed here (feel free to google them to find out more!):

  1. DirectX
  2. OpenGL
  3. SDL

It may be tempting to start your graphics system by reading an image from disk each time you want to draw it on screen. This is horribly slow as disk access is one of the slowest operations on a computer. Instead you’ll want to load any assets into memory, and then draw them from memory.

It’s important to realize that there should only be one instance of an asset in memory at any given time; there’s no reason to have two copies of identical data if all you’re doing is rendering it onto the screen (read access to the asset in memory). Thus, each object in your code should not store the entire asset’s data within itself. Instead you want to store a pointer (or handle) to an asset. This way all objects that require a particular image can all refer to the same image in memory, thus making efficient use of memory. An object can hand the graphics system it’s pointer and let the graphics system handle rendering it on screen. This is the overall idea of the basics a graphics system is required to perform.

Input

The input system should keep track of what sort of input is coming from the player. Reading input directly from hardware is a bad idea; instead you’ll want to have all input related requests be handled by the input manager. This allows code to be written with a single dependency on the input manager, rather than the hardware under which the code is running. The input manager can handle the specific details of gather input from various types of operating systems or hardware specifications.

The types of input an input management system should track include: keystrokes (key pressed and key released), mouse movement, mouse clicks, and a history of keys pressed.

Memory Management

Managing memory in a simple and intelligent manner can be a daunting task at first. However with a couple simple techniques the task itself can be whittled down into smaller easier to take care of pieces.

The type of memory management I’m referring to is that of dynamic memory management. Whenever memory is requested to place new data, this memory must be manually cleaned up by the developer. Knowing when and how to delete previously allocated data is important. For every allocation of memory there is a matching deallocation (or freeing) of said memory.

In order to match up deallocations to allocations, allocated memory requires an owner. Whenever memory is allocated the location of that dynamic memory needs to be stored somewhere, so that later on that location can be used to free the memory within it. Owners of allocated data need to store these addresses in some sort of container.

For a game engine it’s good practice to pretty much never use raw calls to new and delete, especially when creating entire game objects. Not only are new and delete (as well as malloc and free) too slow for many game requirements, they also provide no semblance of who owns the object and when it is to be deleted.

Object Management

In the game engine I’m currently developing, new and delete calls are almost exclusively reserved for the creation of game objects. The rest of the program’s memory is stored on the stack. All the major systems are stored on the stack. Game Objects in your engine should probably be the focal point of allocation and deallocation (aside from asset loading and unloading). This calls for some specialized code to handle the “owning” of game objects. This will be covered in greater detail within the Factory section of Component Based Design.

Game logic

Game logic systems are completely isolated from the other systems. Game logic systems are what construct the rules and interactions of your game, and should not be coupled whatsoever to tasks such as manually gathering input, or manually rendering images. The game logic systems should focus purely on their respective tasks in order to keep their code base as decoupled from other functionalities as possible, thusly encouraging code reuse, and clean/simple architecture.

Physics

The physics system handles all movement of game objects, as well as collision and collision resolution. Most every game has some form of physics simulation, even if it’s as simple as moving an image from one location to another over a span of time.

The best game physics book would be the orange one Real-Time Collision Detection. There are tons of algorithms that are really difficult if not impossible to find on the internet here. Also if you do manage find some on the internet they’re likely done wrong or inefficiently. Do yourself a favor and get the book.

Here’s a post I wrote a little while back on: Basic 2D Vector Physics. Here’s another one on: Basic 2D Collisions. If you’re interested in some implementation details of basic physics, these two articles are the ones for you. Once you wetted your feet be sure to grab the orange book mentioned above!

AI

Artificial intelligence is the application of algorithms and logic that give an illusion of intelligence through interactivity with the player. AI is usually performed within a game engine by a central Game Logic system. This game logic system provides functionality for individual game objects to draw upon and use to control their own behavior.

For example a game object might require a “patrolling” behavior in which it walks to the left, then walks to right, and repeats. The game object itself shouldn’t have any ad-hoc code that controls its movement. Instead think of the game object as a bucket of data. This bucket of data then hands its data to the AI system. The AI system can then determine from the information what actions to take. This allows the programmer to centralize all AI related behaviors into a generalized and centralized packet of code.

In our patrolling example, the game object can pass to the AI system its position and an identifier determining what behavior to execute (perhaps an enumeration or string ID). The AI system can then see the ID and know it matches to patrolling behavior, and then update the game object’s position appropriately.

Component Based Design

I’ve been alluding to component based design bit by bit for a while now. A colleague of mine wrote some excellent introductions to Component Based Design here, feel free to check them out. In short, objects should be containers of other objects. Contained objects are called components. What components and object contains defines what behaviors and properties the object exhibits. A game engine itself can be made to be a composition of systems (and should be). Component based design can also be referred to as a form of aggregation.

All the aforementioned systems can be contained within an array, and updated and enacted upon by the container as necessary. The container itself can be a small object called the Engine. The Engine can contain a method called MainLoop, and in the MainLoop it can properly update all systems accordingly. Upon construction of the Engine, all systems can be initialized. This sets up a clear hierarchy where the Engine “owns” or contains all systems, and thus the Engine object will take care of allocating and deallocating (if necessary), updating, and managing the various systems.

[image loading]

Component Based Game Objects

A game object should be a composition of components. Each component of an object allows the object to access new functionality, or store particular types of data. If a game object is thought of as a collection of components, suddenly we avoid the whole ugly idea of lame hierarchy trees using inheritance. The components themselves become highly reusable pockets of code that determine the behavior of the object that contains them.

Here’s an example of an ugly inheritance diagram:

[image loading]

The drawback of inheritance is as time goes on, it becomes extremely difficult to maintain decoupled code. Code starts traversing up the hierarchy as more and more derived objects require the same functionality.

Recommended books on the subject:

  1. Game Engine Architecture
  2. Game Programming Gems 4: A System for Managing Game Entities Game
  3. Game Programming Gems 5: Component Based Object Management
  4. Game Programming Gems 5: A Generic Component Library
  5. Game Programming Gems 6: Game Object Component System

Here is more detailed information about inheritance and component based design: Evolve your Heirarchy; Game Object Architecture: Aggregations vs Inheritance.

Factory

The factory is a system that manages the creation of other objects. Here’s an external link to a detailed description of the implementation of a factory. The factory is integral in a game engine; without a proper factory the creation of objects results in very coupled code and no clear owner of objects. The Factory itself abstracts the code to create objects by reversing the dependency of creation code to delegated creator objects. Instead of the factory including a bunch of files to create different types of objects, different types of objects can include the factory and tell it how to construct itself.

Data driven composition

Data driven composition is the idea that data (usually in files) can be used to determine the behavior of the game. For example a factory can be used to create game objects based off of a text file. Sets of text files can be used as blueprints for game object types, which is actually pretty simple if game objects are just compositions:

Here’s an example of a game object in text format from a project I’m currently working on.

GameObject
{
 ID
int 0
 active
bool 1
 components std::vector<Component*>
 {
   Transform
   {
     name std::string
"Transform"
     sX
float 32
     sY
float 32
     pX
float 0
     pY
float 0
     theta
float 0
   }
   Sprite
   {
     texture std::string
"someArtAsset.png"
   }
 }
}

The factory can create a game object of this type at any given time by a single call to the function CreateObject. CreateObject can be passed the filename of this text file, and then the factory can compose the game object on the fly from the specifications within the text file.

Entire level files can be created from these archetype (blueprint) files. Creating an object from information from a file on-disk can be referred to as serialization or deserialization. The power of the factory really comes to fruition when it’s used in conjunction with data from files. Being able to create an object from data within a text file abstracts data tweaking out from C++ code and into a simple file (binary or text). This file can be manually tweaked, or tweaked with tools, thus influencing how the program will run without writing any new code.

Additional isolated topics

Finite State Machines

The most common and simplest of all AI programming techniques is the finite state machine (FSM). A state machine is a way of creating a specific type of behavior based around organizing blocks of AI code into states. These states are generally very independent from one another, and an object with a FSM is always in one of the AI states. Swapping from state to state lets the object change its behavior, perhaps from walk left to jump right.

FSMs are generally used for very simplistic enemies, such as patrolling enemies in 2D action platformers.

[image loading]

Here’s an example FSM in C++ code.

void Enemy::Update( state State )
{
 
switch( State )
 {
 
case Attack:
   
if(FindPlayer( ))
     AttackPlayer( );
   
else
     enemyState = Patrol;
   
return;
   
 
case Patrol:
   PatrolWalk( );
   
if(FindPlayer( ))
     enemyState = Attack;
   
return;
   
 
case Die:
   DisplayDeath( );
   SetEnemyToInactive( );
   
return;
 }
}

In this example you can see that the enemy’s state will swap back and forth between patrolling and attacking the player continually, until the enemy’s state is somehow set to the Die state.

Finite state machines can be great for simple AI, though are very brittle. Adding a new state to a state machine often times requires refactoring of other pre-existing states, and state machines are usually very specific to the single object that they are intended to run on.

ActionList

Action lists are a different way of handling AI compared to that of state machines. The concept is that you have a linked list of actions to perform in sequence. There’s a single update function that updates the first action in the list. If this first action is “blocking”, then updating is stopped until the next call to update. If the first action is “non-blocking”, the next action in the list has update called on it, and so on. This way you can easily create complex behavior or algorithms on-the-fly, as opposed to writing brittle state machines, or some other method.

Here’s a long video on the details of implementing such a system. Here are the slides associated with the video. Lastly, here’s one more link on action list implementation details.

Improved Messaging

A more advanced form of messaging can map the message identifiers to specific operations to perform. This can be achieved with a hash table; a message’s ID can be hashed to an index rather than running a switch statement upon it.

Polling can be a big issue when using messages. For example say a game object needs to know when a particular key is pressed. This object might send a message to the input section of code within a project asking if this key is pressed, every single time the object itself is updated. This form of constantly checking the status of something is called a polling, and is very inefficient. An optimization to messaging is to allow some form of interrupt callback to be used whenever something happens.

Imagine polling as constantly asking if something has happened: “Did it happen yet? No. Did it happen yet? No. Did it happen yet? No”. This can be akin to kids in the backseat asking their parents “Are we there yet? Are we there yet?” It’s annoying. Instead the parents will say “We’ll let you know when we get there”. The same idea can be applied to messaging in the form of what is called listeners and subscribers.

In the parent child relationship in the car example, the children subscribe to the parents in order to hear about when they “get there”. In this way the children don’t do any actions at all until the parent informs them to.

To implement this in code an object will give the input access to itself, and the input section of code can then store that access information (perhaps the access information is an ID to the object, or a delegate to one of it’s methods) in a container. Then when the input recieves a keystroke it can traverse the container and inform everyone that “subscribed” that the key had been pressed. This a type of interrupt callback routine that can be known as the observer pattern.

Here’s a long video on the implementation details of messaging systems.

Generic programming

Generic programming is style of programming that is typeless, as in the type of data to be used is not determined at the time the code was written. In C++ this is achieved with templating. In C there’s a couple different methods for achieving generic programming.

Templating in C++ revolves around generating code around abstract types. A great example of an effective use of generic programming is in the implementation of abstract data types like linked lists or vectors. It would be horrendously annoying to write multiple definitions of linked lists revolving around supporting different types of data. Using templates you can let the compiler generate all the code for you.

Here’s a very simple example of a templated function used to find the smaller value between two parameters of type T. Every single time the Min function is used with a specific type for T the compiler’s templater will generate a new function specifically for use of Min with that type. The compiler will not generate any code from the Min function if it is never used. This way the code generated from templates is proportional to the amount of different types that require code generation from the template itself.

Bitmasks

A bitmask in C is usually used with an integer, and is a way of storing data into the separate bits. Bitfields can be achieved with structures, however I’ll be talking only about integer bitmasks.

By storing information into a particular bit, very efficient memory usage can be employed in order to store boolean properties within a single integer.

I won’t be doing an overview of the different bitwise operators, however an absolutely excellent chapter on low-level programming and the bitwise operators resides within: C Programming: A Modern Approach 2nd Ed.

Here’s a few common operations relating to bitmasks:

  1. Setting a bit
  1. number |= 1 << x;
  1. Clearing a bit
  1. number &= ~(1 << x);
  1. Toggling a bit
  1. number ^= 1 << x;
  1. Checking a bit
  1. bit = number & (1 << x);

By using these operations information can easily be stored and manipulated within an integer. Here’s a code example using a char instead of int (for brevity). As you can see creating combinations of bit properties is really simple from the programmer’s perspective.

User Interface by Sean Reilly

User Interface (UI) is the means by which the user and computer system interact. In games this is accomplished via the use of interactive on-screen elements such as menus and buttons, as well as visual indicators such as health bars, point/ammo displays and mini-maps.

Game User Interface

When it comes to creating a game user interface there are two main options: build a custom UI framework from scratch or use a preexisting library.

From Scratch

The key to creating a custom user interface library is keeping it simple. Remember, you are writing a game, not the next version of HTML. The majority of independent games get by using fixed size layouts with some images, text, and rectangular buttons. Even AAA games such as Diablo III get by with completely static UIs. At a minimum, all you need is the ability to detect whether or not the mouse cursor is within the bounds of an image or rectangle and call a function if the mouse is pressed.

Preexisting Library

If you are unsatisfied with the rigidity or lack of features a custom UI provides, the following is a list of user interface libraries which can be embedded into your game. Each of these libraries has varying levels of integration difficulty, but in exchange will provide you with the flexibility and customization needed to create a powerful and unique interface.

Preexisting UI Libraries:

Crazy Eddie's GUI (CEGUI)

LibRocket

Chromium Embedded Framework (CEF)

Editor User Interface

Creating a user interface for an editor is not the same as creating a user interface for a game. You should worry less about having something that looks nice, and more about having something familiar, robust, and easy to use. The three main types of game editors are in-game, external, and external with the game fully or partially embedded.

In-Game

An in-game editor is one which uses the your game's UI to create an on-screen editing environment.

Pros: Easy to implement. The editor can simply be a heavily modified game menu using your existing UI framework. It also becomes simple to ship the editor with the game as it is already integrated.

Cons: Inflexible. You will likely be limited in terms of editing tools and screen real estate. Chances are you will be using a static layout and tools will be hidden or cluttered around the screen.

In-Game Editor UI Library:

AntTweakBar

External

A tool which is completely independent from the game. It has no communication whatsoever and is used to create maps and other assets which are exported as files and loaded into the game.

Pros: Easy to work on while the game engine is still in development since it doesn't rely on the game itself. Can be written in any language.

Cons: No in-game editing or switching between play and edit modes. Cannot use engine libraries if the editor is written in a different language.

External with Game Embedded

A tool which shares engine libraries and is capable of running the game from within the editing environment. The Starcraft II and Torchlight editors are good examples of this approach.

Pros: Since you are using the game's engine, you gain the ability to quickly switch between edit and play modes. Additionally, sharing libraries between the editor and game provides the capability to trigger game events, instantiate objects, load levels, and do anything else that could normally be done in-game without having to duplicate any work.

Cons: Difficult to maintain. Any changes made to the game itself can adversely affect the editor and vise versa.

External UI Frameworks:

wxWidgets

Qt

Windows Forms

Windows Presentation Foundation

Serialization

Serializing an object is the act of placing information about the object into a file representation. Later an identical or similar object can be constructed from the information within the file, and this can be called deserialization. Serializing objects is a non-trivial matter, as explained momentarily.

Dump the Bytes

In order to get an object into a file, you may want to just simply dump all of its bytes straight into a file. This solution isn’t nearly good enough. What are the values of pointers going to mean on deserialization? How can you tell the difference in data from one type of object to another? What if an object on-creation needs to run its constructor? Not all objects are C-like structures that just hold data; they often need operations performed on them when they are constructed, and just simply loading/unloading bytes won’t perform these operations.

Streams

First we must talk about where to write and read data from. Streams are one solution and actually the only one I know of. A stream object is an object that can have data written and read from it. The standard library for C++ provides some excellent stream objects that will allow us to accomplish exactly what is needed, and I recommend using them. In particular fstream and stringstream were useful to me when I wrote serialization code recently.

By reading and writing to stream we introduce another level of indirection: first we manipulate a stream, and the stream manipulates a file. In this way the stream can be abstract. We can write our serialization code that writes to a stream of any kind, whether it be intended for a file or networking, or anything. The stream can handle the details of sending or storing data, and we don’t want to couple our serialization code to a specific type of I/O.

What to Serialize

As for what to serialize, only support the basic data types. Creating helper functions for serializing ints, floats, characters, booleans, strings, etc. is all the functionality you need to get started. Then by using the base serializers you can serialize more complex objects. Here’s some example code of one way to handle serializing the plain data types using template specialization:

// Serialize a non-specialised type.
template <typename TYPE>
void SerializePOD( streamType& stream, TYPE val )
{
 stream <<
"TYPE ";
 stream << val;
}

// Serialize specialized types to allow for proper name identifiers
template <>
void SerializePOD<float>( streamType& stream, float val )
{
 stream <<
"float ";
 stream << val;
}

template <>
void SerializePOD<int>( streamType& stream, int val )
{
 stream <<
"int ";
 stream << val;
}

A simple way to support serialization for more complex objects or classes is to have each class define their own serialize method. This way each class can have a customized serialization routine that writes to files only critical information. A key part in serialization is to make sure you only serialize what you need. For example in my current project we don’t serialize pointers at all (almost); it’s just not necessary for our design needs.

Once objects define their own serialize methods generic code can be written to handle serialization and deserialization of any object that supports serialization. Here’s a short example of what a serialized missile object may look like:

// Example of serialized object
Player Missile
int velocity 100
float scale 1.2
string texture
"Missile.png"
string LuaScript
"Follow.lua"

As you can tell serialized objects can be very simple, but the process of getting that information to and from files is rather non-trivial. Serialization can be as simple as you want it to be, and as complex as ever; try to choose what’s right for your project.

Finally you might wondering about the file format of the serialization itself. For large projects that require very fast serialization there’s often two file formats supported: text and binary. Binary serialization can be read and written very quickly compared to text, as in order to read and write text bytes must be translated (computed) to text format, which takes time. However text format is usually used for debug or developer builds, as it’s readable and tweakable by hand. Release builds can make use of an optimized binary format. If the serialization code was properly written, swapping formats could be about as simple as using a different type of stream or stream setting.

Serializing Pointers

As for serializing pointers, I’ll throw the description of the idea out very quickly and let the reader pick up the pieces. One way to tackle serialization of pointers is to use another level of indirection. First it’s assumed that all serialized pointers will point to serialized data (otherwise the data is lost on program end, defeating the purpose). When serializing a pointer use the address it holds and treat it as a unique identifier, also known as a key, that maps to a new location. This new location will be created on deserialization and all pointers will use their old address as a key to map to the new location. The data in the locations themselves will act as the “values” in a key to value table (or dictionary) that is stored in the serialized file.

To summarize: upon serialization all pointers you wish to serialize have the contents at their locations serialized in a table (perhaps a hash table), and the keys to each index in this table is the address the object resided in just before serialization. By using the address as a key it ensures that each entry into the table has a unique identifier. Upon deserialization the table is deserialized, and the old keys (old addresses) are then mapped to new memory locations of the newly constructed objects. Then all the other objects that refer to the table with address indices can be mapped to the new memory locations upon deserialization.

Optimization for C++ Games

There are a few different simple guidelines that one can follow to ensure their code isn’t running sub-optimally. I’ll point out the common low-hanging ones that I’m familiar with.

Delayed Construction

Don’t make something until you need it! Quite simple. If you have an algorithm that requires only one object at first, and then sometimes later one requires another don’t just construct both every time the code runs! Delay the construction of the second until it is needed. Here’s some unoptimized code:

void Func( int val )
{
 Object obj;
 
 
if(val == VALUE)
   
return;
 

  More code  
 ...
}

In the above example it’s fairly easy to see that the Object obj is being constructed at a time that doesn’t always require it to exist. Some of the time Func is executed the if statement will force the function to end before obj has a chance to ever be used. obj should be constructed at the last moment of where it is needed, this way its constructor will only be called when necessary.

Pre and Post Increment

Post increment should be avoided in favor of pre increment whenever possible. Post increment creates copies of user-defined types whereas post increment does not. Here’s an example in code to show the difference:

void Func( container& data )
{
 userDefined i = initVal;
 userDefined j = i++;
// Unnecessary copy created
}

void Func( container& data )
{
 userDefined i = initVal;
 userDefined j = ++i;
// No un-optimized copies being created
}

Initializer List

Using an initializer list, although awkward looking, is actually faster in C++03 than using code within a constructor to initialize values. This is due to how the compiler works. With an initializer list the compiler is able to reduce the amount of instructions necessary to set an object up, where if we place initialization code into the body of the constructor instead, assignment instructions must be called that might have been avoided if in the initializer list.

// Object construction and value initialization can happen at once here.
Object::Object( std::string& name,
int val ) : Name( name ), hp( val )
{
}

// Will require additional assignment operations after object construction.
Object::Object( std::string& name,
int val )
{
 Name = name;
 hp = val;
}

Preallocate Objects

A simple optimization to a game can be to pre-allocate an array of objects for use throughout the games duration. This is great for things like particle systems where object recycling comes in handy. Imagine a particle system spawning thousands of the same particle every second. If each object is allocated and deallocated individually the overhead incurred from memory handling will be overwhelming. A simple solution is to use a pre-allocated or stack array of particles. Whenever a new particle is needed an empty slot can be searched for and used. When a particle needs to be “deleted” it can be deactivated and its memory marked as “empty”. In this way no memory allocation or deallocation is being performed, instead memory is being efficiently reused.

A further optimization to pre-allocating arrays of objects like this is to keep track of which slots are open and empty so that no search for an empty slot needs to occur. This can reduce the amount of time spent searching for empty slots to be used for additional objects.

Of course the drawback to this method is that there are a limited number of slots available as the memory isn’t dynamic. There are ways around this limitation but are out of scope for this section.

Reflection: Type MetaData

I was slightly hesitant in including this section because of how vast of a topic it is. I decided to include it in that I’ll compromise by mainly describing what reflection in C++ is, while linking to other external sources for implementation details.

Reflection (aka MetaData) in a programming language grants the programmer access to the various types of data being manipulated in a program. By having access to this information very generic code can be written, and often times entire tools can be generated for user-defined types, simply by inserting a newly created user defined type into a reflection system.

In my current project as I write this I’m using a MetaData system that allows for the following interesting features:

  1. Variant and RefVariant objects
  1. Variant is an object that holds MetaData information and a void *
  2. Refvariant is a Variant that performs shallow copies on the void *
  1. Automated serialization
  2. Automated Lua object binding
  3. Automated Lua function binding
  4. Advanced debugging information and type checking

A MetaData system can also allow for:

  1. Simple factories for object creation
  2. Versionable serialization
  3. Simple editor support
  1. Automatically generated property grids
  1. More I don’t know about!

Hopefully you’ve been convinced that a strong MetaData system can provide some valuable features. So how does it work? The implementations I’m familiar with involve either manually entering in type data, or with some sort of code preprocessor that scans C++ code before compilation and inserts data into some sort of database.

As for the preprocessor approach, I’ve heard of the awesome clReflect library. clReflect scans your code and generates a database of MetaData that can be accessed during run-time.

The other type of approach is through template metaprogramming. Through the use of templates one can construct their own database of information upon program start, where much of the bulk-work is achieved during compile time. Some implementations I know are my very own series of articles, the articles be Sean Middleditch, a library made by Wang Qi called cpgf, and lastly a few articles from a couple wonderful books.

There are two articles I’ve read that deal with reflection and both of them use the templated approach. I’d suggest researching into both of them if you’re considering writing or using any sort of MetaData system in C++.

  1. Game Programming Gems 5 Chapter 1.4
  2. Game Engine Games 2 Chapter 25

With all that hype about C++ MetaData systems, how about we take a look at some? I’ll try sharing some code I’ve written myself with my own reflection system:

template <typename TYPE>
void SerializePOD( std::stringstream& stream, RefVariant var )
{
 stream << var.GetMeta( )->Name( ) <<
" ";
 stream << var.GetValue<TYPE>( ) << std::endl;
}

You can see in the example above that the crux of the implementation is the RefVariant. The RefVariant holds a MetaData object that contains a lot of useful information about the type present within the Variant object. You can see that by using the MetaData within the RefVariant I’m able to print out the type of the data in string format, and retrieve its value within templated code.

This next bit of code is going to be a little longer. This is a function I’ve written that uses RefVaraints to deserialize any type of class or structure recursively:

RefVariant TextSerializer::Deserialize( const MetaData *meta )
{
 
if(!meta) // meta can be null, and is on first call
   meta = RetrieveTypeFromFile( );
 RefVariant var( meta, meta->New( ) );

 
int startLevel = level;

 
do
 {
   
const Member *mem = RetrieveMemberTypeFromFile( &(meta->members), startLevel );
   
if(mem)
   {
     RefVariant member;
     
if(mem->Meta( )->HasMembers( ))
       member = mem->Meta( )->Deserialize( );
     
else
       member = mem->Meta( )->Deserialize( mem->Meta( ) );
     member.GetMeta( )->Copy( PtrAdd( var.GetData( ), mem->offset ), member.GetData( ) );
     member.Delete( );
   }
 }
while(level > startLevel);

 
return var;
}

You can see here that this code is very generic; it will work for any type of class or structure registered within the MetaData system! It works by traversing a data table that represents a class type, where that data table stores other data tables that represent the class members. The MetaData information allows for generic Copy, Deserialize, offset locations, Delete, and other useful functionality that allow generic code like above.

Hopefully by now you’re interested in learning more about reflection within C++, and if you are interested feel free to check out any of the various resources I’ve discussed within this section.

Example Engine

At the end of the day it would be wonderful to provide some sort of example code for people to see with their own eyes. Luckily I have a pretty simple project called AsciiEngine. You can read all about it in the link here. AsciiEngine is a game engine written in C (sorry not C++!) for Windows XP, Vista, and Win7 that allows the user to easily create and display images within a Windows console. The engine also automates the tedious task of customizing aspects of the console, such as a font or palette color.

Take a look at some of the features of AsciiEngine that you might be able to learn something from (it might seem like a lot, but I’m just good at making it sound better than it is haha):

  1. Complete game loop
  1. Game loop integrated into Game State Manager via function pointers
  1. Game State Manager
  1. Allows for easy management/creation/deletion of game states
  1. Functioning framerate controller
  1. Allows the setting of framerate with a #define macro
  2. Prevents large timesteps from passing through the program with a cap
  1. Various console related functions for easy customization of the console window
  2. Complete graphics functions set for drawing 2D images
  3. Input template complete for simple keystroke detection and mouse event handling
  1. Easily customizeable to include more functionality
  1. Complete and very simple PRNG
  2. Simple image format that allows for variable size
  3. Integrated hash table for storing images
  1. Allows for an optimized lookup, e.g.: TableLookup( “ImageName” )
  2. Extremely simple creation/deletion of images
  1. Implementation of my simple 2D collision library
  2. Implementation of my simple 2D vector library
  3. Highly organised object manager using the factory pattern
  1. Allows for easy creation/handling/deletion of game objects
  2. Incredibly simple to create new object types
  1. Implemented my Tile mapping — Binary Collision library
  2. Image editor
  3. File output
  4. Automatic image file loading and parsing
  5. Messaging system Object to object + global messaging system
  6. Component base game object system (now renamed to game entity)
  7. New button class for easy UI creation
  8. Integration of generic Hash Table and Linked Lists
  9. Simple serialization and deserialization support.




Brought to you by the TL Knowhow Team
Written by: CecilSunkure
+
genesis_crimsonheart
Profile Blog Joined September 2011
United States81 Posts
November 17 2012 03:49 GMT
#2
SO MUCH WRITING!!!!!!!!!!!!!!!!!!!
Infinite in mystery is the gift of the Goddess.
SeeDLiNg
Profile Joined January 2010
United States690 Posts
November 17 2012 04:46 GMT
#3
This is amazing o.o I know what I'm doing for the next few days XD
PassiveAce
Profile Blog Joined February 2011
United States18076 Posts
November 17 2012 04:47 GMT
#4
There's a typo at the top, "progamming"

Amazing guide.
Call me Marge Simpson cuz I love you homie
HawaiianPig
Profile Blog Joined July 2008
Canada5155 Posts
Last Edited: 2012-11-17 05:03:00
November 17 2012 04:58 GMT
#5
Cool article!
AdministratorNot actually Hawaiian.
Redmark
Profile Joined March 2010
Canada2129 Posts
November 17 2012 05:01 GMT
#6
Not gonna lie, didn't even realize this subforum existed. Maybe have it be an optional block on the left, like Blogs?
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 17 2012 05:13 GMT
#7
On November 17 2012 14:01 Redmark wrote:
Not gonna lie, didn't even realize this subforum existed. Maybe have it be an optional block on the left, like Blogs?

There is a block

+ Show Spoiler [Screenshot] +
[image loading]
Lmui
Profile Joined November 2010
Canada6213 Posts
November 17 2012 05:22 GMT
#8
Damn nice article!

I'm in computer engineering so I'm obligated to know everything up until the game engine architecture section but it looks like most of those concepts are pretty close to what you do to design hardware as well. Looks like I'm halfway to knowing how to make a game already =P
Redmark
Profile Joined March 2010
Canada2129 Posts
November 17 2012 05:29 GMT
#9
On November 17 2012 14:13 CecilSunkure wrote:
Show nested quote +
On November 17 2012 14:01 Redmark wrote:
Not gonna lie, didn't even realize this subforum existed. Maybe have it be an optional block on the left, like Blogs?

There is a block

+ Show Spoiler [Screenshot] +
[image loading]

Oh, jokes on me, I turned off Blogs. Surprisingly low traffic then, I wonder why.
vaderseven
Profile Joined September 2008
United States2556 Posts
November 17 2012 05:43 GMT
#10
O_O

This and the unpublished guide of a certain matchup by a certain monk are the best guides on TL.
Chronos.
Profile Joined February 2012
United States805 Posts
November 17 2012 06:20 GMT
#11
This is a very neat article, I'm definitely gonna give this a closer look later!

I took a computer technology vocational program in high-school and did some minor game programming for my senior project, and now I'm going to college for computer science. I'm still very interested in game programming and have a lot of ideas floating around, so when I get a chance (maybe between semesters) I'll probably put some serious work into this.

Thanks!
Alethios
Profile Blog Joined December 2007
New Zealand2765 Posts
November 17 2012 06:42 GMT
#12
Holy fuck.
When you arise in the morning, think of what a precious privilege it is to be alive - to breathe, to think, to enjoy, to love.
Tchado
Profile Blog Joined January 2011
Jordan1831 Posts
November 17 2012 08:09 GMT
#13
Damn ! Excellent article.

This brought back so many memories from college , and why I quit programming after my graduation project and vowed never write a single line of code again , I still maintain it was a good call.
Isualin
Profile Joined March 2011
Germany1903 Posts
November 17 2012 09:28 GMT
#14
really useful guide. thanks so much!
| INnoVation | The literal god TY | ByuNjwa | LRSL when? |
Teoita
Profile Blog Joined January 2011
Italy12246 Posts
November 17 2012 09:29 GMT
#15
Awesome guide man
ModeratorProtoss all-ins are like a wok. You can throw whatever you want in there and it will turn out alright.
Hemania
Profile Joined June 2012
1 Post
November 17 2012 09:49 GMT
#16
I would like to thank you for a really nice write about the basic programming guidelines!

I'm study Computer Science myself, and what you wrote is a incredible accurate overview of what you will need to know to program an engine.

Well done!
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
November 17 2012 12:29 GMT
#17
I do have my issues with this, as expected. Now I didn't really read through all of it in detail, but I tried to make sure I didn't miss anything. So I will just hint at a few things...

You can't tell people that low level code optimization is important without telling them about profiling. Optimizing the 99% of non-critical code in your application will not do you any good. It will do you lots of harm though, and not just because the development time increases tenfold.

Don't recommend macros in C++ for anything aside from include protection. Macros are evil. C++ has plenty of ways to avoid macros smoothly and efficiently. Google's coding guidelines even suggest that you wouldn't ever use a macro.
If you have a good reason to disagree with the above, please tell me. Thank you.
MilesTeg
Profile Joined September 2010
France1271 Posts
November 17 2012 15:34 GMT
#18
This. Is. Awesome! Thanks!
Munk-E
Profile Blog Joined July 2010
United States672 Posts
November 17 2012 17:14 GMT
#19
Damn, cecil. nice.

Now all i have to do is got off my butt and actually try it (or I guess, on my butt)
You recognise me because of my signature!
1handsomE
Profile Blog Joined July 2011
United States199 Posts
November 17 2012 17:16 GMT
#20
That's like 2 years of comp sci in an essay!!!! Noobs might want to take it slow, but this is good introduction.
MarineKing / Jaedong / DeMusliM / SeleCT / Maru hwaiting!
PassiveAce
Profile Blog Joined February 2011
United States18076 Posts
Last Edited: 2012-11-17 17:37:25
November 17 2012 17:35 GMT
#21
many things in C and C++ are hidden away from the developer and in turn makes them slower. Having slow code isn’t acceptable for high performance real-time applications such as games.

Hey Cecil, is this a typo also? the sentence seems contradictory in relation to the rest of the paragraph. This sentence comes from the "goals of the article" section at the top.

once again, this guide is truly incredible, thanks for taking the time to writing it : )))
Call me Marge Simpson cuz I love you homie
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 17 2012 17:42 GMT
#22
On November 18 2012 02:35 PassiveAce wrote:
Show nested quote +
many things in C and C++ are hidden away from the developer and in turn makes them slower. Having slow code isn’t acceptable for high performance real-time applications such as games.

Hey Cecil, is this a typo also? the sentence seems contradictory in relation to the rest of the paragraph. This sentence comes from the "goals of the article" section at the top.

once again, this guide is truly incredible, thanks for taking the time to writing it : )))

Haha yes definitely a typo, thanks for pointing it out. Should say something like "many things in interpreted and other high level languages", not C and C++.
Gorlin
Profile Joined November 2010
United States2753 Posts
November 17 2012 17:50 GMT
#23
Sweet, thanks a ton for this!
akarin
Profile Joined February 2011
Ireland42 Posts
November 17 2012 19:43 GMT
#24
This looks so sweet! I'm really looking forward to reading this later, I have just scanned through it. As a nooby CS student (we covered arrays last week ^^) I am wondering is java used (much) in programming games?

Thanks for writing this Cecil!
jca2 *
Profile Joined March 2006
France52 Posts
November 17 2012 19:56 GMT
#25
Very good article. I dont know if i missed it but I didnt see anything about "interfaces" which in C++ are based on abstract classes. It's a very powerfull mechanism that allows a binary to interact with another binary without any implementation knowledge, just a few abstract classes defined in .h files. Which in turn allows for real Component oriented design (infrastructures like COM, CORBA, ActiveX, etc).
APM? Never heard of it...
NeWeNiyaLord
Profile Blog Joined September 2010
Norway2474 Posts
November 17 2012 20:35 GMT
#26
As an aspiring Developer I really appreaciate the effort you've done into this post. When I get time to study it I surely will! Thx Cecil!
This is where we begin. Show your true self, Battosai.
DodgySmalls
Profile Joined June 2012
Canada158 Posts
Last Edited: 2012-11-17 22:12:45
November 17 2012 22:06 GMT
#27
I'll bookmark this and use it along side other references to try to get a "fresh" perspective when I have a problem.

Pretty awesome amount of content in this, given that it's relatively short and covers so many topics.

edit:
I guess I'd also like to ask what are everyone's thoughts on java? I've seen some examples of how inefficient java can be in comparison to some c code, and it is true that you are denied quite a lot of low level access (pointers anyone? )

I feel like it's a decent medium for a hobbyist, like myself, but I really don't have any argument for why I enjoy coding in Java over c++.
Please remove nyx assassin
ibutoss
Profile Blog Joined June 2005
Australia341 Posts
November 17 2012 22:45 GMT
#28
I like this article. It is well written and even if I'm not that interested in writing a game I found it a useful refresh on many of the concepts I studied at uni but haven't really been exposed to since.

Thanks for writing it! I enjoyed reading it.
Nada got Yooned
Cyx.
Profile Joined November 2010
Canada806 Posts
November 17 2012 22:46 GMT
#29
As someone else who's in a software engineering program hoping to go into game programming, this is really awesome! A lot of the stuff I work in on my second-year courses is exactly the kind of stuff you're talking about which is really helpful.

One thing though - in your section about game engine architecture you use the Source engine as an example of an engine specific to first-person shooters, when in reality Dota 2 (and every other Valve game since HL2 I think) is built on the Source engine. I'm a bit of a Valve fanboy =P
Bombadil819
Profile Joined November 2011
United States45 Posts
November 17 2012 23:25 GMT
#30
Nice article. Also worth mentioning Panda3D and Torque3D as other options for prebuilt game engines. Especially now that T3D is MIT licensed and on Github.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2012-11-17 23:51:50
November 17 2012 23:49 GMT
#31
On November 18 2012 04:43 akarin wrote:
This looks so sweet! I'm really looking forward to reading this later, I have just scanned through it. As a nooby CS student (we covered arrays last week ^^) I am wondering is java used (much) in programming games?

Thanks for writing this Cecil!

Sorry, Java isn't used really at all (as far as I know) professionally. I'm always hearing about how people are being interviewed for full-time positions around here (cough cough Microsoft) and are always declined; they don't really know what's going on. I'm sure there's a lot of Java jobs out there, but the kind I'm aiming at are not.

On November 18 2012 07:06 DodgySmalls wrote:
I'll bookmark this and use it along side other references to try to get a "fresh" perspective when I have a problem.

Pretty awesome amount of content in this, given that it's relatively short and covers so many topics.

edit:
I guess I'd also like to ask what are everyone's thoughts on java? I've seen some examples of how inefficient java can be in comparison to some c code, and it is true that you are denied quite a lot of low level access (pointers anyone? )

I feel like it's a decent medium for a hobbyist, like myself, but I really don't have any argument for why I enjoy coding in Java over c++.

I don't use Java, but what all my superiors tell me is that it isn't nearly enough to cut it whenever you have a product that requires heavy optimization.

See for reference: http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html
cowsrule
Profile Joined February 2010
United States80 Posts
Last Edited: 2012-11-18 00:29:10
November 18 2012 00:25 GMT
#32
Nice article! Glad to see people documenting their learning progress and sharing their expreience with others.

Sidenote: '#pragma once' is awesome not those crazy header guards .

On November 18 2012 08:49 CecilSunkure wrote:
Show nested quote +
On November 18 2012 04:43 akarin wrote:
This looks so sweet! I'm really looking forward to reading this later, I have just scanned through it. As a nooby CS student (we covered arrays last week ^^) I am wondering is java used (much) in programming games?

Thanks for writing this Cecil!

Sorry, Java isn't used really at all (as far as I know) professionally. I'm always hearing about how people are being interviewed for full-time positions around here (cough cough Microsoft) and are always declined; they don't really know what's going on. I'm sure there's a lot of Java jobs out there, but the kind I'm aiming at are not.

Show nested quote +
On November 18 2012 07:06 DodgySmalls wrote:
I'll bookmark this and use it along side other references to try to get a "fresh" perspective when I have a problem.

Pretty awesome amount of content in this, given that it's relatively short and covers so many topics.

edit:
I guess I'd also like to ask what are everyone's thoughts on java? I've seen some examples of how inefficient java can be in comparison to some c code, and it is true that you are denied quite a lot of low level access (pointers anyone? )

I feel like it's a decent medium for a hobbyist, like myself, but I really don't have any argument for why I enjoy coding in Java over c++.

I don't use Java, but what all my superiors tell me is that it isn't nearly enough to cut it whenever you have a product that requires heavy optimization.

See for reference: http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html


Learning java is great, just don't stop there. Once you learn one language (which you CAN use to make games, just possibly not super-awesome AAA titles), it becomes easier to learn a second language.

Android development is java, so there are at least some games written in java. I believe the ever-popular Runescape is also written in java. Most AAA titles for the PC are written in C++ however.
thedeadhaji *
Profile Blog Joined January 2006
39489 Posts
November 18 2012 00:35 GMT
#33
On November 18 2012 02:42 CecilSunkure wrote:
Show nested quote +
On November 18 2012 02:35 PassiveAce wrote:
many things in C and C++ are hidden away from the developer and in turn makes them slower. Having slow code isn’t acceptable for high performance real-time applications such as games.

Hey Cecil, is this a typo also? the sentence seems contradictory in relation to the rest of the paragraph. This sentence comes from the "goals of the article" section at the top.

once again, this guide is truly incredible, thanks for taking the time to writing it : )))

Haha yes definitely a typo, thanks for pointing it out. Should say something like "many things in interpreted and other high level languages", not C and C++.


C hides a lot of stuff away from the developer compared to assembly!
(just this week, we actually had to implement something in Assembly since C was too slow, lol -- this was for an embedded systems environment tho)
Bombadil819
Profile Joined November 2011
United States45 Posts
November 18 2012 00:45 GMT
#34
On November 18 2012 08:49 CecilSunkure wrote:
Show nested quote +
On November 18 2012 04:43 akarin wrote:
This looks so sweet! I'm really looking forward to reading this later, I have just scanned through it. As a nooby CS student (we covered arrays last week ^^) I am wondering is java used (much) in programming games?

Thanks for writing this Cecil!

Sorry, Java isn't used really at all (as far as I know) professionally. I'm always hearing about how people are being interviewed for full-time positions around here (cough cough Microsoft) and are always declined; they don't really know what's going on. I'm sure there's a lot of Java jobs out there, but the kind I'm aiming at are not.

Show nested quote +
On November 18 2012 07:06 DodgySmalls wrote:
I'll bookmark this and use it along side other references to try to get a "fresh" perspective when I have a problem.

Pretty awesome amount of content in this, given that it's relatively short and covers so many topics.

edit:
I guess I'd also like to ask what are everyone's thoughts on java? I've seen some examples of how inefficient java can be in comparison to some c code, and it is true that you are denied quite a lot of low level access (pointers anyone? )

I feel like it's a decent medium for a hobbyist, like myself, but I really don't have any argument for why I enjoy coding in Java over c++.

I don't use Java, but what all my superiors tell me is that it isn't nearly enough to cut it whenever you have a product that requires heavy optimization.

See for reference: http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html


Java sees HEAVY use in certain industry, and is capable of being highly performant when the code is written by someone who knows what they're doing. That doesn't mean it's a good intro language, or that it's the right tool for every job. Or that the language design is particularly elegant. But Java-bashing is a popular hobby for not terribly good reasons.
Greem
Profile Blog Joined September 2010
730 Posts
November 18 2012 01:31 GMT
#35
On my to read list ! thx a lot for a such a good work!
youtube.com/N0rthernL1ght
RayzorFlash
Profile Joined December 2010
Canada253 Posts
November 18 2012 06:24 GMT
#36
Bookmarked and saved! The Quick Refresher stuff is SO IMPORTANT and so amazingly well put together. A lot of the fundamentals in there is what people in the industry REALLY look for when hiring and during interviews. This is an amazing review sheet to use before an interview. Thanks a lot!!! :D
jobebob
Profile Joined April 2011
30 Posts
November 18 2012 06:59 GMT
#37
Wow, so much info. This is a good overview of many important concepts in programming.

You should add some info about using revision control systems. These systems are the foundation to managing a project between a group of people, and every programmer needs to learn how to use them.

Git is pretty famous and a really nice system. Github is massive.

Valve uses a system called perforce, which is basically a rev system for more than just code. We used it to store textures, vertex files and all the other things the artists make.

Some more design patterns would be cool too. I find the "Strategy" pattern is really well suited for making a simple game.
Nightsz
Profile Blog Joined February 2011
Canada398 Posts
November 18 2012 07:39 GMT
#38
i will read this one day >.>

BLinD-RawR
Profile Blog Joined April 2010
ALLEYCAT BLUES50114 Posts
November 18 2012 11:10 GMT
#39
holy hell yes, This is so useful for me I will read,reread this a lot as I progress on my own.
Brood War EICWoo Jung Ho, never forget.| Twitter: @BLinDRawR
TL+ Member
uZr
Profile Joined April 2011
20 Posts
November 18 2012 12:00 GMT
#40
That's some insane amount of work you put in there, congrats !

However some things are just bugging me.

Arrays cannot be passed around from one location to another directly. If attempted, the name of an array will be converted to a pointer to the first element in the array. This incurs a loss of information, as a pointer stores information about location and type, whereas an array stores location of first element, type of the elements and number of elements. This “feature” of C and C++ can actually be viewed as a “language bug”.

What do you mean by "name of an array will be converted to a pointer" ? Strictly speaking those two things are just the same: pointers. the name[idx] syntax is just some syntaxical sugar over doing *(name+idx). Furthermore the "size of the array" is never stored anywhere in C. You can write it explicitly when allocating on the stack, but it will eventually get lost when compiled, and the compiler won't give you any warning if you access out of bounds entries.
Here's an example:

#include <stdio.h>

int main()
{
int array[] = {1,2,3,4,5};

printf("array[3] = %d | *(array+3) = %d\n",
array[3], *(array+3));

return 0;
}

Running

test % gcc test.c -o test
test % ./test

then outputs

array[3] = 4 | *(array+3) = 4

When asking gcc to output it as assembly (gcc -S -m32 test.c) we get (some parts have been cut) :

_main:
pushl %ebp
movl %esp, %ebp
pushl %esi
subl $52, %esp
call L1$pb
L1$pb:
popl %eax
movl _C.0.1863-L1$pb(%eax), %ecx
movl %ecx, -32(%ebp)
movl (_C.0.1863-L1$pb)+4(%eax), %ecx
movl %ecx, -28(%ebp)
movl (_C.0.1863-L1$pb)+8(%eax), %ecx
movl %ecx, -24(%ebp)
movl (_C.0.1863-L1$pb)+12(%eax), %ecx
movl %ecx, -20(%ebp)
movl (_C.0.1863-L1$pb)+16(%eax), %ecx
movl %ecx, -16(%ebp)
movl -20(%ebp), %ecx
movl -20(%ebp), %edx
movl %esp, %esi
movl %ecx, 8(%esi)
movl %edx, 4(%esi)
leal L_.str-L1$pb(%eax), %eax
movl %eax, (%esi)
call _printf
movl $0, -12(%ebp)
movl -12(%ebp), %eax
movl %eax, -8(%ebp)
movl -8(%ebp), %eax
addl $52, %esp
popl %esi
popl %ebp
ret

Notice how our array entries get accessed:

movl -20(%ebp), %ecx
movl -20(%ebp), %edx
. (then get pushed on the stack later on etc).
As you can see there, both times it is accessed in the same way.

Arrays are just there to lighten up the syntax.

For example, you could want to iterate over a null-terminated char array this way:

void iterate_and_do_nothing(char *str)
{
int i;
while (str[i]) {
++i;
}
}

That's valid, yet on this one the interrest of using an array-type approach is limited ...
simpler
Profile Blog Joined August 2010
Sweden49 Posts
November 18 2012 12:21 GMT
#41
Really solid article, good job!
Fandango
Profile Joined October 2011
291 Posts
November 18 2012 13:34 GMT
#42
On November 18 2012 15:24 RayzorFlash wrote:
Bookmarked and saved! The Quick Refresher stuff is SO IMPORTANT and so amazingly well put together. A lot of the fundamentals in there is what people in the industry REALLY look for when hiring and during interviews. This is an amazing review sheet to use before an interview. Thanks a lot!!! :D


It really isn't, it's more the stuff you're expected to know in the same way you're expected to know how to type. Most questionnaire type things on stuff like that are just there to catch people who literally know nothing and forgetting how a hashmap is stored internally is not going to stop you from getting the job if you get most of the other stuff right. Good interviewers who want good hires will generally place a lot of emphasis on a pre-interview programming test as well as asking you about situations you most likely have not dealt with to see your problem solving ability.

Software engineering whether it's games or anything else is 80% problem solving using as elegant solutions as you can come up with, it's not about writing constantly heavily optimised code all the time, even on AAA projects. It's about finding solutions to problems that don't end up causing more problems, whether that's a performance problem or a dependency issue or whatever. You learn how to do this mostly from experience, you can know what code pattern X is, but unless you know the situations where it's an actual benefit instead of a theorhetical one it's largely irrelevant knowledge.

You learn to make games by making games, you don't learn to make games by making game engines that you think are so elegantly designed that in theory anyone could make any game ever on it, because you don't know yet what the real issues are going to be. It's the most common habit of the student games programmer where they're so obsessed with doing things 'properly' by their own definition of whatever that may be, that they never run into the real problems they'll actually have to deal with.
nimdil
Profile Blog Joined January 2011
Poland3748 Posts
November 18 2012 13:36 GMT
#43
On November 18 2012 02:16 1handsomE wrote:
That's like 2 years of comp sci in an essay!!!! Noobs might want to take it slow, but this is good introduction.

You meant newbs, Noobs won't bother. Also not exactyl justified because to actually apply all the information presented here you have to have a LOT of comp sci knowledge not mentioned directly here. But nicely put indeed.

Radiated11
Profile Joined December 2011
United States32 Posts
November 18 2012 15:17 GMT
#44
Sweet write up! I'm going into computer science in college next year and I will definitely give this a read!
moxley
Profile Joined May 2010
United States65 Posts
November 18 2012 15:18 GMT
#45
While C++ is absolutely favored for high performance platform-specific programs like games, you shouldn't dismiss java as a language for aspiring software engineers. Many people start out wanting to be a "game programmer" but when you look outside that narrow field you'll realize that java is huge in enterprise web applications which make up a large majority of the market for software engineering.
kYem
Profile Blog Joined March 2010
United Kingdom412 Posts
November 18 2012 15:52 GMT
#46
I'm learning Java right, however i would love to learn c++ as well, just wondering how similar these to language are or how hard it's compared to Java.

As moxley said, i do feel Java has a lot bigger market share, so it's very good investment as you can find a well paid job, while it would be very difficult to get one for c++ in a software company.

Maybe someone did a switch from Java to c++ and can share their experiences.
Hell
iamke55
Profile Blog Joined April 2004
United States2806 Posts
November 18 2012 16:21 GMT
#47
On November 18 2012 21:00 uZr wrote:
That's some insane amount of work you put in there, congrats !

However some things are just bugging me.

Show nested quote +
Arrays cannot be passed around from one location to another directly. If attempted, the name of an array will be converted to a pointer to the first element in the array. This incurs a loss of information, as a pointer stores information about location and type, whereas an array stores location of first element, type of the elements and number of elements. This “feature” of C and C++ can actually be viewed as a “language bug”.

What do you mean by "name of an array will be converted to a pointer" ? Strictly speaking those two things are just the same: pointers. the name[idx] syntax is just some syntaxical sugar over doing *(name+idx). Furthermore the "size of the array" is never stored anywhere in C. You can write it explicitly when allocating on the stack, but it will eventually get lost when compiled, and the compiler won't give you any warning if you access out of bounds entries.

What he means is something that will rarely ever come into effect, but nonetheless is true. To see the difference between an array name and a pointer to the first element, run this test program.


#include <stdio.h>

void arrDecay(char array[]);

int main(int argc, char *argv[])
{
char *a = "A test string to compare arrays and pointers";
char b[]= "A test string to compare arrays and pointers";
printf("Size of a:%d\n",sizeof(a));
printf("Size of b:%d\n",sizeof(b));
arrDecay(b);
return 0;
}

void arrDecay(char array[])
{
printf("Size of b after decay:%d\n",sizeof(array));
};


b should have a size of the number of characters plus the null at the end, while a's size is the number of bytes a pointer uses. If you pass the array name as a function argument, it is cast to a pointer.
During practice session, I discovered very good build against zerg. -Bisu[Shield]
iaretehnoob
Profile Joined June 2004
Sweden741 Posts
Last Edited: 2012-11-18 17:10:19
November 18 2012 17:07 GMT
#48
On November 18 2012 21:00 uZr wrote:
What do you mean by "name of an array will be converted to a pointer" ? Strictly speaking those two things are just the same: pointers. [...] Furthermore the "size of the array" is never stored anywhere in C. You can write it explicitly when allocating on the stack, but it will eventually get lost when compiled, and the compiler won't give you any warning if you access out of bounds entries.
Here's an example:

#include <stdio.h>

int main()
{
int array[] = {1,2,3,4,5};

printf("array[3] = %d | *(array+3) = %d\n",
array[3], *(array+3));

return 0;
}



The size of the array is "stored" in the source code you wrote, e.g. it is available to the compiler, hence the difference between sizeof(array) and sizeof((int*)array) and in C++11 the ability to use static arrays with range-based for (and STL algorithms by using begin()/end()).
Then there's std::array as a wrapper around plain arrays, which should be preferable in most situations, even if I haven't gotten used to it myself yet.

edit: does this still count as ninja'd? :S
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
Last Edited: 2012-11-18 18:30:48
November 18 2012 18:21 GMT
#49
On November 19 2012 00:18 moxley wrote:
While C++ is absolutely favored for high performance platform-specific programs like games, you shouldn't dismiss java as a language for aspiring software engineers. Many people start out wanting to be a "game programmer" but when you look outside that narrow field you'll realize that java is huge in enterprise web applications which make up a large majority of the market for software engineering.

Thank you for the comment. I don't mean to entirely dismiss Java outside of the field I've been writing about, but really just meant to express what I've learned in regards to it and game programming professionally.

On November 19 2012 01:21 iamke55 wrote:
Show nested quote +
On November 18 2012 21:00 uZr wrote:
That's some insane amount of work you put in there, congrats !

However some things are just bugging me.

Arrays cannot be passed around from one location to another directly. If attempted, the name of an array will be converted to a pointer to the first element in the array. This incurs a loss of information, as a pointer stores information about location and type, whereas an array stores location of first element, type of the elements and number of elements. This “feature” of C and C++ can actually be viewed as a “language bug”.

What do you mean by "name of an array will be converted to a pointer" ? Strictly speaking those two things are just the same: pointers. the name[idx] syntax is just some syntaxical sugar over doing *(name+idx). Furthermore the "size of the array" is never stored anywhere in C. You can write it explicitly when allocating on the stack, but it will eventually get lost when compiled, and the compiler won't give you any warning if you access out of bounds entries.

What he means is something that will rarely ever come into effect, but nonetheless is true. To see the difference between an array name and a pointer to the first element, run this test program.


#include <stdio.h>

void arrDecay(char array[]);

int main(int argc, char *argv[])
{
char *a = "A test string to compare arrays and pointers";
char b[]= "A test string to compare arrays and pointers";
printf("Size of a:%d\n",sizeof(a));
printf("Size of b:%d\n",sizeof(b));
arrDecay(b);
return 0;
}

void arrDecay(char array[])
{
printf("Size of b after decay:%d\n",sizeof(array));
};


b should have a size of the number of characters plus the null at the end, while a's size is the number of bytes a pointer uses. If you pass the array name as a function argument, it is cast to a pointer.

Thanks for explaining that ke.

On November 19 2012 00:52 kYem wrote:
I'm learning Java right, however i would love to learn c++ as well, just wondering how similar these to language are or how hard it's compared to Java.

As moxley said, i do feel Java has a lot bigger market share, so it's very good investment as you can find a well paid job, while it would be very difficult to get one for c++ in a software company.

Maybe someone did a switch from Java to c++ and can share their experiences.

I wish I could tell you specifics, but I can just tell you sort of second hand experience I've had. I've used quite a few languages with garbage collection and no real sense of memory management. All in all, I feel with using languages like these you learn how the most basics of programming works. You can learn how to use abstract data types, can learn about algorithms and design patterns, can learn a little bit about how to write efficient code, but won't really truly understand what's going on under the hood. There's no concept of where in memory things are, how long things exist for, what sort of caching impact your memory access is incurring, or anything of the like. When using a higher level language you can learn about lower level details in theory, but with C or C++ (or even assembly if you have the luck of finding courses offered in it) you can learn first-hand directly about these things.

This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

Thanks to everyone else! Glad you all like the article
uZr
Profile Joined April 2011
20 Posts
Last Edited: 2012-11-18 20:01:37
November 18 2012 19:57 GMT
#50
On November 19 2012 01:21 iamke55 wrote:
What he means is something that will rarely ever come into effect, but nonetheless is true. To see the difference between an array name and a pointer to the first element, run this test program.

b should have a size of the number of characters plus the null at the end, while a's size is the number of bytes a pointer uses. If you pass the array name as a function argument, it is cast to a pointer.

Thanks for the heads up, I had not thought about that particular case, when it indeed makes much more sense And that's indeed something I use with array of variable size once in a while (which does not work when you're forced to restrict to ANSI C for some work ^^).
Never thought of it like it was phrased by OP though, but that's indeed probably the best way to write that. (English isn't the language in which I learnt programming at first, which sometimes cause me to misunderstand some specific terms).
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2012-11-18 22:12:38
November 18 2012 22:05 GMT
#51
On November 19 2012 03:21 CecilSunkure wrote:
This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

It's the other way round. Starting with C++ is like starting with learning elaborate build orders, while starting with higher level languages is like learning how to control your units (how to use the existing units/classes, instead of how to produce these classes/units in detail).

In programming, the people who are sought after are those who can finish a given task quickly using robust code, using whatever means is appropriate. Nobody cares if you know every single detail of all the machines your code might ever run on as long as your code solves the given task (that includes a certain level of performance), is produced quickly (= reduced cost) and robust (= reduced cost in the long run).

Highly optimized C++ code is often fragile and costly to produce (especially if you aren't really(!) good with templates). That's why you use high level constructs in C++ pretty much everywhere except for the critical code parts. But since you do that anyways, you might as well start with something like C# instead, because it's very much like using high level constructs in C++, except easier and more robust.


Oh and of course there is a concept of memory management in these languages. The general workings of these garbage collectors are no secrets. You should be roughly aware of how your garbage collector works. C++ doesn't force you to learn about the details of new/delete either (and the new algorithm can hardly be called simple, plus it's OS dependant).
If you have a good reason to disagree with the above, please tell me. Thank you.
nimdil
Profile Blog Joined January 2011
Poland3748 Posts
November 19 2012 01:03 GMT
#52
On November 19 2012 00:52 kYem wrote:
I'm learning Java right, however i would love to learn c++ as well, just wondering how similar these to language are or how hard it's compared to Java.

As moxley said, i do feel Java has a lot bigger market share, so it's very good investment as you can find a well paid job, while it would be very difficult to get one for c++ in a software company.

Maybe someone did a switch from Java to c++ and can share their experiences.

Java is defeinitely the biggest language in business/enterprise/corporate environment. Unofrtunately Java is also bloated pain in the ass :/ I'd choose C# over Java anytime I can use Windows platform.
Kerm
Profile Joined April 2010
France467 Posts
Last Edited: 2012-11-19 16:39:28
November 19 2012 16:38 GMT
#53
On November 19 2012 07:05 spinesheath wrote:
Show nested quote +
On November 19 2012 03:21 CecilSunkure wrote:
This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

It's the other way round. Starting with C++ is like starting with learning elaborate build orders, while starting with higher level languages is like learning how to control your units (how to use the existing units/classes, instead of how to produce these classes/units in detail).

In programming, the people who are sought after are those who can finish a given task quickly using robust code, using whatever means is appropriate. Nobody cares if you know every single detail of all the machines your code might ever run on as long as your code solves the given task (that includes a certain level of performance), is produced quickly (= reduced cost) and robust (= reduced cost in the long run).

Highly optimized C++ code is often fragile and costly to produce (especially if you aren't really(!) good with templates). That's why you use high level constructs in C++ pretty much everywhere except for the critical code parts. But since you do that anyways, you might as well start with something like C# instead, because it's very much like using high level constructs in C++, except easier and more robust.


Oh and of course there is a concept of memory management in these languages. The general workings of these garbage collectors are no secrets. You should be roughly aware of how your garbage collector works. C++ doesn't force you to learn about the details of new/delete either (and the new algorithm can hardly be called simple, plus it's OS dependant).


Cecil is right. As far as game programming is concerned, at least for Console/PC high-end titles, C++ is the way to go. If you want to break into that part of the industry, you are wasting your time if you're not gearing toward being excellent at C++.

What you are explaining probably makes sense for general sofware engineering, but game programming is different.
What i know is that I know nothing - [http://twitter.com/UncleKerm]
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2012-11-19 20:44:33
November 19 2012 20:43 GMT
#54
On November 20 2012 01:38 Kerm wrote:
Show nested quote +
On November 19 2012 07:05 spinesheath wrote:
On November 19 2012 03:21 CecilSunkure wrote:
This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

It's the other way round. Starting with C++ is like starting with learning elaborate build orders, while starting with higher level languages is like learning how to control your units (how to use the existing units/classes, instead of how to produce these classes/units in detail).

In programming, the people who are sought after are those who can finish a given task quickly using robust code, using whatever means is appropriate. Nobody cares if you know every single detail of all the machines your code might ever run on as long as your code solves the given task (that includes a certain level of performance), is produced quickly (= reduced cost) and robust (= reduced cost in the long run).

Highly optimized C++ code is often fragile and costly to produce (especially if you aren't really(!) good with templates). That's why you use high level constructs in C++ pretty much everywhere except for the critical code parts. But since you do that anyways, you might as well start with something like C# instead, because it's very much like using high level constructs in C++, except easier and more robust.


Oh and of course there is a concept of memory management in these languages. The general workings of these garbage collectors are no secrets. You should be roughly aware of how your garbage collector works. C++ doesn't force you to learn about the details of new/delete either (and the new algorithm can hardly be called simple, plus it's OS dependant).


Cecil is right. As far as game programming is concerned, at least for Console/PC high-end titles, C++ is the way to go. If you want to break into that part of the industry, you are wasting your time if you're not gearing toward being excellent at C++.

What you are explaining probably makes sense for general sofware engineering, but game programming is different.

I'm saying C# will teach you how to program properly in C++, except that you can focus on one aspect (algorithms, software engineering/architecture) without having to fight with all the problems C++ throws at beginners. The step from C# to C++ is rather easy assuming you learnt C# properly. You pick a book like The C++ Programming Language which covers all the technical language details and you're set.

It's divide and conquer applied to learning C++.
If you have a good reason to disagree with the above, please tell me. Thank you.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 19 2012 20:49 GMT
#55
On November 20 2012 05:43 spinesheath wrote:
Show nested quote +
On November 20 2012 01:38 Kerm wrote:
On November 19 2012 07:05 spinesheath wrote:
On November 19 2012 03:21 CecilSunkure wrote:
This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

It's the other way round. Starting with C++ is like starting with learning elaborate build orders, while starting with higher level languages is like learning how to control your units (how to use the existing units/classes, instead of how to produce these classes/units in detail).

In programming, the people who are sought after are those who can finish a given task quickly using robust code, using whatever means is appropriate. Nobody cares if you know every single detail of all the machines your code might ever run on as long as your code solves the given task (that includes a certain level of performance), is produced quickly (= reduced cost) and robust (= reduced cost in the long run).

Highly optimized C++ code is often fragile and costly to produce (especially if you aren't really(!) good with templates). That's why you use high level constructs in C++ pretty much everywhere except for the critical code parts. But since you do that anyways, you might as well start with something like C# instead, because it's very much like using high level constructs in C++, except easier and more robust.


Oh and of course there is a concept of memory management in these languages. The general workings of these garbage collectors are no secrets. You should be roughly aware of how your garbage collector works. C++ doesn't force you to learn about the details of new/delete either (and the new algorithm can hardly be called simple, plus it's OS dependant).


Cecil is right. As far as game programming is concerned, at least for Console/PC high-end titles, C++ is the way to go. If you want to break into that part of the industry, you are wasting your time if you're not gearing toward being excellent at C++.

What you are explaining probably makes sense for general sofware engineering, but game programming is different.

I'm saying C# will teach you how to program properly in C++, except that you can focus on one aspect (algorithms, software engineering/architecture) without having to fight with all the problems C++ throws at beginners. The step from C# to C++ is rather easy assuming you learnt C# properly. You pick a book like The C++ Programming Language which covers all the technical language details and you're set.

It's divide and conquer applied to learning C++.

Although it sounds like it would work theoretically, I don't really have any experience with anyone learning C++ by learning another language and I can't really judge it for myself. I do know that the people I'm around graduate and are very successful, and they learned C, then C++.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
November 19 2012 21:00 GMT
#56
On November 20 2012 05:49 CecilSunkure wrote:
Show nested quote +
On November 20 2012 05:43 spinesheath wrote:
On November 20 2012 01:38 Kerm wrote:
On November 19 2012 07:05 spinesheath wrote:
On November 19 2012 03:21 CecilSunkure wrote:
This really is just shooting in the dark, but it feels like learning with Java in a lax curriculum compared to learning in C/C++ in a rigorous curriculum is like playing SC2 without learning how to make efficient use of your mouse and keyboard. Sure there's tons and tons of people in bronze up through low master who can "get by" and do fairly well without using more than one hotkey while flailing their mouse around widely. But the people who are really sought after are the ones who have mastered the fundamentals of their keyboard, mouse, and playing mechanics because these are the people that can really spend their time focusing on implementing strategies to defeat their opponents.

It's the other way round. Starting with C++ is like starting with learning elaborate build orders, while starting with higher level languages is like learning how to control your units (how to use the existing units/classes, instead of how to produce these classes/units in detail).

In programming, the people who are sought after are those who can finish a given task quickly using robust code, using whatever means is appropriate. Nobody cares if you know every single detail of all the machines your code might ever run on as long as your code solves the given task (that includes a certain level of performance), is produced quickly (= reduced cost) and robust (= reduced cost in the long run).

Highly optimized C++ code is often fragile and costly to produce (especially if you aren't really(!) good with templates). That's why you use high level constructs in C++ pretty much everywhere except for the critical code parts. But since you do that anyways, you might as well start with something like C# instead, because it's very much like using high level constructs in C++, except easier and more robust.


Oh and of course there is a concept of memory management in these languages. The general workings of these garbage collectors are no secrets. You should be roughly aware of how your garbage collector works. C++ doesn't force you to learn about the details of new/delete either (and the new algorithm can hardly be called simple, plus it's OS dependant).


Cecil is right. As far as game programming is concerned, at least for Console/PC high-end titles, C++ is the way to go. If you want to break into that part of the industry, you are wasting your time if you're not gearing toward being excellent at C++.

What you are explaining probably makes sense for general sofware engineering, but game programming is different.

I'm saying C# will teach you how to program properly in C++, except that you can focus on one aspect (algorithms, software engineering/architecture) without having to fight with all the problems C++ throws at beginners. The step from C# to C++ is rather easy assuming you learnt C# properly. You pick a book like The C++ Programming Language which covers all the technical language details and you're set.

It's divide and conquer applied to learning C++.

Although it sounds like it would work theoretically, I don't really have any experience with anyone learning C++ by learning another language and I can't really judge it for myself. I do know that the people I'm around graduate and are very successful, and they learned C, then C++.

I have never seen anyone start with C/C++ and get good with it reasonably fast and without producing really awful code until some magical turning point. Me included. C++ is so deep, and if you don't even know how to properly design a program yet it's overwhelming.
If you have a good reason to disagree with the above, please tell me. Thank you.
Sapp
Profile Joined March 2011
Poland173 Posts
November 19 2012 21:05 GMT
#57
fuck me... /O.O\
Quote? O.o?
skorched
Profile Joined October 2010
United States81 Posts
November 20 2012 05:43 GMT
#58
Awesome writeup Cecil! Also pretty useful if you want to be a hacker/pentester! A lil off subject but your dt expand is still working great on the ladder. XD
I love the sound of Medivacs getting feedbacked.
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
Last Edited: 2012-11-20 08:48:54
November 20 2012 08:48 GMT
#59
Learning C and C++ after you know another programming language isn't all that hard. You already know the basics of programming (control structures, functions, handling variables) so you can focus on the new stuff, such as pointers and memory management. It's a challenge, but it's a fun one. I would definitely recommend people who are studying other languages to learn those languages first, then dwelve into C/C++ when done, if still interested.

Thing is though, C/C++ development is becoming more and more of a niche. Like Cecil is saying, in progessional game development, for AAA titles etc, C/C++ is definitely the way to go. That's not to say you need to know C/C++ to work profesionally as a game programmer, pretty much all smartphone games and pretty much all Xbox Live Arcade games etc are coded using more highlevel languages like C#, Objective-C and Java.
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2012-11-20 21:42:22
November 20 2012 19:57 GMT
#60
If you're talking about just getting a job out of college, your experience in one language or another really isn't going to mean shit. It's kind of blunt, but the programming you do in Uni is completely different compared to the programming you do in industry. If you're still in Uni, don't get hung up on one language or another - get a solid foundation in algorithms and data structures, and write lots of random code in whatever language(s), enough to be comfortable.

The point is, if you're just starting out in industry, your previous experience in a given language isn't going to even come close to preparing you for the volume of random weird shit that's going to come crawling out of the woodwork to bite you in the ass. You can only learn that stuff when you're hammering away at it for 50+ hours a week on the job. If you started with Java in Uni and are now doing enterprise c++, it's not that much different from starting with c++ in Uni and doing enterprise c++.

The more important part is to be really enthusiastic about it, and be willing to learn whatever is thrown at you as quickly as possible. That's the really good part of the OP; it's something someone can easily use to get more excited about programming in general.
Who after all is today speaking about the destruction of the Armenians?
Deezl
Profile Blog Joined November 2010
United States355 Posts
November 21 2012 03:14 GMT
#61
If you're ever interested in a job in technical writing, let a brotha know.
Three hundred lives of men I have walked this world, and now I have no time.
Ender2701
Profile Blog Joined January 2012
United States581 Posts
November 21 2012 04:29 GMT
#62
Wow really nice article! Definitely will recommend to any friends that are interested into getting into industry game programming. I learned a bit from the generic coding in C article and I've been doing game development in C++/C for several years
]343[
Profile Blog Joined May 2008
United States10328 Posts
November 22 2012 05:00 GMT
#63
Wow, all I need to do is learn graphics and find a physics engine, and I can write my own games too!

Nice guide
Writer
4tre55
Profile Joined June 2011
Germany330 Posts
November 22 2012 10:44 GMT
#64
Just bought "Code" because of your guide an it's an amazing book, thanks a lot for the recomandation.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 22 2012 19:09 GMT
#65
On November 22 2012 19:44 4tre55 wrote:
Just bought "Code" because of your guide an it's an amazing book, thanks a lot for the recomandation.

Very awesome! I loved that book, read it twice.
kollin
Profile Blog Joined March 2011
United Kingdom8380 Posts
November 22 2012 20:30 GMT
#66
Out of interest, Cecil, what compiler do you use for coding? Having trouble finding the 'right' one :/
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 22 2012 20:34 GMT
#67
On November 23 2012 05:30 kollin wrote:
Out of interest, Cecil, what compiler do you use for coding? Having trouble finding the 'right' one :/

I like gcc/g++ and VS 2010. I'd recommend VS Express 2010.
kollin
Profile Blog Joined March 2011
United Kingdom8380 Posts
November 22 2012 20:53 GMT
#68
On November 23 2012 05:34 CecilSunkure wrote:
Show nested quote +
On November 23 2012 05:30 kollin wrote:
Out of interest, Cecil, what compiler do you use for coding? Having trouble finding the 'right' one :/

I like gcc/g++ and VS 2010. I'd recommend VS Express 2010.


Alright thanks, I took a look at VS 2008 I think, but some of the UI felt a bit weird to what I'd used before, but I'll definitely check out both those recommendations! :D
Chronopolis
Profile Joined April 2009
Canada1484 Posts
Last Edited: 2012-11-23 06:43:32
November 23 2012 06:42 GMT
#69
O ..................... O

_______________
|.........................|
|.........................|
|.........................|
|.........................|
|.........................|
| ______________|

Too long, will read.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
November 23 2012 15:48 GMT
#70
On November 23 2012 05:30 kollin wrote:
Out of interest, Cecil, what compiler do you use for coding? Having trouble finding the 'right' one :/

You don't use a compiler for coding, you use a text editor or an integrated development environment (IDE) which usually consists of a text editor, a compiler and lots of other helpful tools. Visual Studio is an IDE, gcc/g++ is just a compiler. If you're more of a linux/command line guy, vim with the right plugins is supposed to be good. For typical Windows users, Visual Studio is very good.
Afaik Eclipse is somewhat popular too, and I often use it when I am working on a Linux system, but I find it to be just an inferior version of Visual Studio (I'm not exactly good with the command line style editors).

For C/C++ you usually don't really need a fancy IDE though as long as you have syntax checking and code completion.
If you have a good reason to disagree with the above, please tell me. Thank you.
Arnstein
Profile Blog Joined May 2010
Norway3381 Posts
November 23 2012 18:38 GMT
#71
What a shitty text...............JUST KIDDING, THIS WAS FUCKING AMAZING!!! Thanks a LOT!!!
rsol in response to the dragoon voice being heard in SCII: dragoon ai reaches new lows: wanders into wrong game
Spikeke
Profile Joined October 2010
Canada106 Posts
November 23 2012 18:44 GMT
#72
Covered more general programming than actual game programming, but it was still a good refresher. For those who think this is a lot... This isn't even scratching the surface. That's one thing I enjoy about game development though, it's like a never ending rabbit hole. Always something new to learn or new tech to play with.
Lorizean
Profile Blog Joined March 2011
Germany1330 Posts
November 25 2012 18:39 GMT
#73
On November 23 2012 04:09 CecilSunkure wrote:
Show nested quote +
On November 22 2012 19:44 4tre55 wrote:
Just bought "Code" because of your guide an it's an amazing book, thanks a lot for the recomandation.

Very awesome! I loved that book, read it twice.


Haha, I bought it too and it is pretty amazing indeed.

About the compilers: you will want to use gcc (g++) on gnu/linux. For Windows you have a choice between the microsoft compiler included in visual studio or MingW (a gcc port for windows).
Or you can use the Intel compiler (parallel xe) on both platforms.
Microsoft and Intel cost money though, but you can get free access as a student or for non-commercial use.

As for IDE i quite liked codeblocks (linux+windows, option to come coupled with mingW/gcc) or you can use visual studio for the microsoft/intel compilers.
Personally I use vim with g++ on linux and I can say that learning to use vim was very worth it, but it takes time to get used to it. So if you just want to code some small c++ program its probably not worth your while to learn it.
Ender2701
Profile Blog Joined January 2012
United States581 Posts
Last Edited: 2012-11-26 06:38:26
November 26 2012 06:38 GMT
#74
On November 26 2012 03:39 Lorizean wrote:
Show nested quote +
On November 23 2012 04:09 CecilSunkure wrote:
On November 22 2012 19:44 4tre55 wrote:
Just bought "Code" because of your guide an it's an amazing book, thanks a lot for the recomandation.

Very awesome! I loved that book, read it twice.


Haha, I bought it too and it is pretty amazing indeed.

About the compilers: you will want to use gcc (g++) on gnu/linux. For Windows you have a choice between the microsoft compiler included in visual studio or MingW (a gcc port for windows).
Or you can use the Intel compiler (parallel xe) on both platforms.
Microsoft and Intel cost money though, but you can get free access as a student or for non-commercial use.

As for IDE i quite liked codeblocks (linux+windows, option to come coupled with mingW/gcc) or you can use visual studio for the microsoft/intel compilers.
Personally I use vim with g++ on linux and I can say that learning to use vim was very worth it, but it takes time to get used to it. So if you just want to code some small c++ program its probably not worth your while to learn it.


If you're coding on linux, I'd suggest emacs and g++, but since you're doing game programming you're probably using Windows. If you're going to use Windows, I'd suggest Visual Studio and Visual Assist X. Visual Assist X is probably the greatest IDE add on I've ever used, really good for large C++ projects, I used it when I was doing game programming for First Playable and it was awesome.

No matter what I'd suggest learning + using emacs hotkeys. It makes editing text so much faster. The only downside is that you'll constantly be frustrated when other things don't have emacs hotkeys and you accidentally open 10 new windows.
iaretehnoob
Profile Joined June 2004
Sweden741 Posts
November 26 2012 13:49 GMT
#75
And if you get Visual Studio, get VS 2012 (unless you're stuck on Win XP). C++11 support should be enough to convince anyone. Also syntax-highlighting/intellisense seems to have improved at some point, I remember VA X being somewhat of a must have in the past, but I haven't missed it in the last few months.

Clang is another good compiler choice, competing with gcc, just really not as widespread.
Random()
Profile Blog Joined August 2004
Kyrgyz Republic1462 Posts
Last Edited: 2012-11-30 19:01:36
November 27 2012 18:43 GMT
#76
While this is a great article, I think you are overemphasizing the "internals" of game programming. Those parts that work with the hardware and all the low-level implementation details are, of course, quite important, but in all honesty they have little to do with your actual game.

When you look at it this way, then game development (as in implementing the actual gameplay mechanics) is very often done in a higher-level language. People use all sorts of languages (Python, Lua, Java, C#, ...) to abstract themselves away from the engine internals and the horrors of C++, and that is a very good thing. Writing good C++ programs is extremely difficult, and even the state-of-the-art engines written by the most talented programmers in the world are ridden with bugs. C++ programs written by average programmers are a minefield.

So unless you are determined to be a very technical sort of developer, working on the engine, I don't agree that you HAVE to use C++ for game development, in fact I would argue that you should try to avoid it at all if that is possible within your workflow.

Also, you write "there are a few different simple guidelines that one can follow to ensure their code isn’t running sub-optimally" as if running sub-optimal code is something to be ashamed of. Saying such things, especially to new programmers, is a recipe for disaster. Premature optimization is the root of all evil, and for whatever reason many people really seem to like spending their effort "optimizing" absolutely unimportant stuff which they don't even know to be the bottleneck, while at the same time their program is not working correctly overall.

EDIT: please take this as my personal rambling and wishful thinking. Reality is, as people have pointed out, that you will be most likely expected to know C++ if you are going to apply for a game programming job.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 27 2012 20:29 GMT
#77
On November 28 2012 03:43 Random() wrote:
While this is a great article, I think you are overemphasizing the "internals" of game programming. Those parts that work with the hardware and all the low-level implementation details are, of course, quite important, but in all honesty they have little to do with your actual game.

When you look at it this way, then game development (as in implementing the actual gameplay mechanics) is very often done in a higher-level language. People use all sorts of languages (Python, Lua, Java, C#, ...) to abstract themselves away from the engine internals and the horrors of C++, and that is a very good thing. Writing good C++ programs is extremely difficult, and even the state-of-the-art engines written by the most talented programmers in the world are ridden with bugs. C++ programs written by average programmers are a minefield.

So unless you are determined to be a very technical sort of developer, working on the engine, I don't agree that you HAVE to use C++ for game development, in fact I would argue that you should try to avoid it at all if that is possible within your workflow.

Also, you write "there are a few different simple guidelines that one can follow to ensure their code isn’t running sub-optimally" as if running sub-optimal code is something to be ashamed of. Saying such things, especially to new programmers, is a recipe for disaster. Premature optimization is the root of all evil, and for whatever reason many people really seem to like spending their effort "optimizing" absolutely unimportant stuff which they don't even know to be the bottleneck, while at the same time their program is not working correctly overall.

I can understand why you'd want to shy from encouraging C++, but if you want a job being very good at C++ is the best way I know of. Sure, the everyday workflow of the position you might get may or may not be using C++, but that's besides the point if you want the best chances of hire. Just go check out all the various game programming or software engineering positions offered from studios; pretty much every one requires excellent C++ skills.

As for optimization, I only talked about delayed construction and said not to pass-by-value. These are the sort of things I learned my first semester working in C. They aren't really something you can get lost in while programming in a bad way as you'll be learning fundamentals essential to programming in general.
ClysmiC
Profile Blog Joined December 2010
United States2192 Posts
November 28 2012 04:35 GMT
#78
This is AWESOME. I'm learning Java right now, but I took a little detour learning some C++ and this will definitely help. Can't wait to read this over the next few days. Looks like a great write-up!
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2012-11-28 16:56:57
November 28 2012 16:56 GMT
#79
On November 28 2012 05:29 CecilSunkure wrote:
As for optimization, I only talked about delayed construction and said not to pass-by-value. These are the sort of things I learned my first semester working in C. They aren't really something you can get lost in while programming in a bad way as you'll be learning fundamentals essential to programming in general.

Not using pass by value to improve speed is a trap too. Sometimes you want to pass by value, sometimes you don't.
See: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/


Generally you never even want to think of optimization until after you ran a detailed performance analysis. Before that point all your efforts should be spent on producing simple, readable, understandable, reusable, testable and maintainable code.
If you have a good reason to disagree with the above, please tell me. Thank you.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
November 28 2012 18:48 GMT
#80
On November 29 2012 01:56 spinesheath wrote:
Show nested quote +
On November 28 2012 05:29 CecilSunkure wrote:
As for optimization, I only talked about delayed construction and said not to pass-by-value. These are the sort of things I learned my first semester working in C. They aren't really something you can get lost in while programming in a bad way as you'll be learning fundamentals essential to programming in general.

Not using pass by value to improve speed is a trap too. Sometimes you want to pass by value, sometimes you don't.
See: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/


Generally you never even want to think of optimization until after you ran a detailed performance analysis. Before that point all your efforts should be spent on producing simple, readable, understandable, reusable, testable and maintainable code.

You know, intentionally setting up RVO is in and of itself programming while being mindful of optimizations. Some optimization really is just low hanging fruit you can be sure of.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
November 28 2012 21:10 GMT
#81
On November 29 2012 03:48 CecilSunkure wrote:
Show nested quote +
On November 29 2012 01:56 spinesheath wrote:
On November 28 2012 05:29 CecilSunkure wrote:
As for optimization, I only talked about delayed construction and said not to pass-by-value. These are the sort of things I learned my first semester working in C. They aren't really something you can get lost in while programming in a bad way as you'll be learning fundamentals essential to programming in general.

Not using pass by value to improve speed is a trap too. Sometimes you want to pass by value, sometimes you don't.
See: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/


Generally you never even want to think of optimization until after you ran a detailed performance analysis. Before that point all your efforts should be spent on producing simple, readable, understandable, reusable, testable and maintainable code.

You know, intentionally setting up RVO is in and of itself programming while being mindful of optimizations. Some optimization really is just low hanging fruit you can be sure of.

It's stuff that you'll do automatically more and more as you gain experience, but it still has pretty much zero impact on performance for the vast majority of code. You will still need to optimize bottlenecks, and only those matter.

For example, I always write ++i instead of i++ unless I specifically need i++ (and even then I prefer to split the statement into two lines because it's easier to read/understand and maintain), but it never makes a difference with most of it being optimized by the compiler, and the rest simply not being in a critical section.

All I'm saying is: The optimizations without drawbacks are nice and all, but it's not something one should prioritize (especially beginners!). Optimize bottlenecks after performance analysis. Saves time, money, and your sanity.
If you have a good reason to disagree with the above, please tell me. Thank you.
Ender2701
Profile Blog Joined January 2012
United States581 Posts
November 29 2012 07:59 GMT
#82
On November 28 2012 03:43 Random() wrote:
While this is a great article, I think you are overemphasizing the "internals" of game programming. Those parts that work with the hardware and all the low-level implementation details are, of course, quite important, but in all honesty they have little to do with your actual game.

When you look at it this way, then game development (as in implementing the actual gameplay mechanics) is very often done in a higher-level language. People use all sorts of languages (Python, Lua, Java, C#, ...) to abstract themselves away from the engine internals and the horrors of C++, and that is a very good thing. Writing good C++ programs is extremely difficult, and even the state-of-the-art engines written by the most talented programmers in the world are ridden with bugs. C++ programs written by average programmers are a minefield.

So unless you are determined to be a very technical sort of developer, working on the engine, I don't agree that you HAVE to use C++ for game development, in fact I would argue that you should try to avoid it at all if that is possible within your workflow.

Also, you write "there are a few different simple guidelines that one can follow to ensure their code isn’t running sub-optimally" as if running sub-optimal code is something to be ashamed of. Saying such things, especially to new programmers, is a recipe for disaster. Premature optimization is the root of all evil, and for whatever reason many people really seem to like spending their effort "optimizing" absolutely unimportant stuff which they don't even know to be the bottleneck, while at the same time their program is not working correctly overall.


As far as I know most big name games are done in C++. It's actually not bad if you follow good coding practices and code reviews. Starcraft II for instance is primarily C++, and I also know for sure that every game that comes out of http://www.vvisions.com/ and http://www.1stplayable.com/. At the very least, games on console will likely remain primarily in C++ due to the limited hardware specs.
Kerm
Profile Joined April 2010
France467 Posts
Last Edited: 2012-11-29 14:49:59
November 29 2012 14:47 GMT
#83
On November 28 2012 03:43 Random() wrote:
While this is a great article, I think you are overemphasizing the "internals" of game programming. Those parts that work with the hardware and all the low-level implementation details are, of course, quite important, but in all honesty they have little to do with your actual game.

When you look at it this way, then game development (as in implementing the actual gameplay mechanics) is very often done in a higher-level language. People use all sorts of languages (Python, Lua, Java, C#, ...) to abstract themselves away from the engine internals and the horrors of C++, and that is a very good thing. Writing good C++ programs is extremely difficult, and even the state-of-the-art engines written by the most talented programmers in the world are ridden with bugs. C++ programs written by average programmers are a minefield.

So unless you are determined to be a very technical sort of developer, working on the engine, I don't agree that you HAVE to use C++ for game development, in fact I would argue that you should try to avoid it at all if that is possible within your workflow.

[...]


This is just plain wrong. Game programmers do work on C++ too, and although their are more concerned with iterating fast on a feature so that the game designer is happy than with raw performance (as are engine programmers), they need to be excellent at C++. Just read any gameplay programmer job offer (see http://www.gamasutra.com/jobs/board.php?category=16 for instance) you will see than "strong C++ skills" are a pre requisite in 95% of the cases.

Please do avoid to misinform people around here, that are not necessarily schooled with the inner working of the game industry.


[Edit: Ooops actually Cecil already answered pretty much the same thing, sorry about that]
What i know is that I know nothing - [http://twitter.com/UncleKerm]
bbm
Profile Joined April 2011
United Kingdom1320 Posts
November 29 2012 15:39 GMT
#84
Not bad (though rushes through a bit quickly but whatever)

as a note, there's no good reason I can think of to use #define for global ints and things. Use enums or const variables.

You can't for example call the following code snippet:

#define NUM_MAX 256
//...
SomeFunction(&NUM_MAX);

But you can do

const int NUM_MAX = 256;
//...
SomeFunction(&NUM_MAX);



not to mention better error checking and reporting with const vars, and problems if you define the same thing twice.

The only time I'd use #define is when creating some kind of debug and i might want to use ugly macros like __LINE__. something like this:


#define ERROR(x) \
do { \
std::cerr << "ERROR: \"" << x << "\" - Line: " << __LINE__ << ", File: " << __FILE__ << "." << std::endl; \
}while(0)


Or of course if you have a bunch of different flags, you should probably use an enum instead for better type safety and less confusion in parameters and such.
By.Sun or By.Rain, he always delivers
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
November 29 2012 15:50 GMT
#85
Macros are for actual preprocessor operations like include guards and stuff where you select some code based on the architecture you're compiling for (note: use this very sparingly) or debugging (although you should use a logger for that). In some rare occasions you might want to use it to greatly improve readability (for example Typelists). Macros as a replacement for functions, constants, inlining or templates are bad.
If you have a good reason to disagree with the above, please tell me. Thank you.
Random()
Profile Blog Joined August 2004
Kyrgyz Republic1462 Posts
Last Edited: 2012-11-30 17:15:40
November 30 2012 17:09 GMT
#86
On November 29 2012 23:47 Kerm wrote:
Show nested quote +
On November 28 2012 03:43 Random() wrote:
While this is a great article, I think you are overemphasizing the "internals" of game programming. Those parts that work with the hardware and all the low-level implementation details are, of course, quite important, but in all honesty they have little to do with your actual game.

When you look at it this way, then game development (as in implementing the actual gameplay mechanics) is very often done in a higher-level language. People use all sorts of languages (Python, Lua, Java, C#, ...) to abstract themselves away from the engine internals and the horrors of C++, and that is a very good thing. Writing good C++ programs is extremely difficult, and even the state-of-the-art engines written by the most talented programmers in the world are ridden with bugs. C++ programs written by average programmers are a minefield.

So unless you are determined to be a very technical sort of developer, working on the engine, I don't agree that you HAVE to use C++ for game development, in fact I would argue that you should try to avoid it at all if that is possible within your workflow.

[...]


This is just plain wrong. Game programmers do work on C++ too, and although their are more concerned with iterating fast on a feature so that the game designer is happy than with raw performance (as are engine programmers), they need to be excellent at C++. Just read any gameplay programmer job offer (see http://www.gamasutra.com/jobs/board.php?category=16 for instance) you will see than "strong C++ skills" are a pre requisite in 95% of the cases.

Please do avoid to misinform people around here, that are not necessarily schooled with the inner working of the game industry.


[Edit: Ooops actually Cecil already answered pretty much the same thing, sorry about that]


EDIT: Nevermind.
zak_attack
Profile Joined November 2012
Wales6 Posts
November 30 2012 19:14 GMT
#87
yeh man nice thread i have a Bsc in computer game development
'I am the punishment of God...If you had not committed great sins, God would not have sent a punishment like me upon you.
LunaSaint
Profile Blog Joined April 2011
United Kingdom620 Posts
December 03 2012 03:08 GMT
#88
Yikes. This is impressive.

I've dabbled in Python and C++, but I'm still a complete novice. Brilliant stuff.
dae
Profile Joined June 2010
Canada1600 Posts
December 03 2012 23:07 GMT
#89
Wow.. this is like the entire contents of first and 2nd year CSC in one spot. Amazing.
Incze
Profile Blog Joined December 2011
Romania2058 Posts
December 04 2012 17:28 GMT
#90
Posts like your help give me motivation to pursue programming. I'm actually going to buy those books.
Thanks a lot!
Religion: Buckethead
ShadowWolf
Profile Joined March 2010
United States197 Posts
December 06 2012 16:02 GMT
#91
Tons of people use Java all the time - there are plenty of hobbyist games built in Java. I absolutely think making a few smaller games in e.g. Python or Java is a great idea. Arguably, while you're learning, the python/java implementation can be faster than your C++ implementation as long as you do things somewhat reasonably. You will be a far better programmer (especially in C++) by experiencing what other languages can do for you. Even getting in to some functional concepts is powerful because a lot of those ideas fit really well in to building parallelizable systems.

Plus, let's face it, there's a really solid chance most people in this thread won't enjoy doing gamedev for a living. It's a very taxing, very difficult, and very competitive industry with low pay and horrific hours. Very rewarding if you're the type of person who likes making games, but, as someone who is strong in C++, I can assure you having a C++ background isn't really an ultra-desired skill set right now. You can make do (and good money) but your industries are limited (basically you can kiss startups goodbye).

Arrays cannot be passed around from one location to another directly. If attempted, the name of an array will be converted to a pointer to the first element in the array. This incurs a loss of information, as a pointer stores information about location and type, whereas an array stores location of first element, type of the elements and number of elements. This “feature” of C and C++ can actually be viewed as a “language bug”.


In C++, references to arrays are not decayed when passed. This allows you to eliminate this decay at no cost with a parameter that looks similar to the below. Just a sample from an implementation of one of those internet question things, but demonstrates the prototype:
template <size_t Sz>
Node* TreeFromSortedArray(int (&arrayList)[Sz], int start, int end)

With this, sizeof does work correctly (which means you can use _countof or ARRAY_SIZE). You can even replace int with a template if you wanted and that works, too.

I'd probably suggest striking the optimization section entirely; I agree with everything in it but I think it would be stronger in a "Coding for the future" type of section. i.e. postfix/prefix - I use the prefix operator too but it hasn't reasonably mattered in years and I've literally never had a line of code's speed increased by any measurable factor by a postfix ++ operator even in the one situation I can think of where it create unnecessary copies, delayed construction is more just a code organization thing - it can be the right answer in some situations but only if you've done the necessary legwork (profiling and analysis) to know why. And so on with the remaining things. They're all great suggestions but also they're all premature optimizations. More important is focusing on complexity (avoiding n^2 or worse - especially in a loop), profiling, and timing. Every foray in to game making I've made usually involves a section where I forget I only have like 15ms or something to complete the game loop.

Overall it's a great article. I liked the sections on design patterns and data structures. I definitely feel like the #1 mistake I see at work is people overlooking both of those things.
MChrome
Profile Joined May 2011
Netherlands201 Posts
December 07 2012 10:36 GMT
#92
One thing... Do you need to learn C and C++ side by side or is learning just C++ enough?
If you do things right, people won't be sure you've done anything at all.
iaretehnoob
Profile Joined June 2004
Sweden741 Posts
December 07 2012 17:45 GMT
#93
I would advice learning either C or C++, not the abomination that is C/C++ or C with classes.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
December 07 2012 17:58 GMT
#94
Just learn C++. C is used only in some rare and very specific circumstances nowadays.
If you have a good reason to disagree with the above, please tell me. Thank you.
LTY
Profile Joined November 2012
United States223 Posts
December 08 2012 18:14 GMT
#95
oh my, i'm working on whac a mole program in java, i'm totally lost now..
Known as Miso or LTY
Azerbaijan
Profile Blog Joined January 2010
United States660 Posts
December 10 2012 09:58 GMT
#96
I have Visual Studio 2012 and I can't figure out how to set it up for C programming. Options for C++ and C# are pretty obvious but allegedly I can use it for plan C ( I think). I was using codeblocks on my old computer, which I liked a lot, but I have a class that is using C# and I would like to us VS for both languages if I can.
e-Goh
Profile Joined January 2012
New Zealand18 Posts
December 10 2012 14:00 GMT
#97
On December 10 2012 18:58 Azerbaijan wrote:
I have Visual Studio 2012 and I can't figure out how to set it up for C programming. Options for C++ and C# are pretty obvious but allegedly I can use it for plan C ( I think). I was using codeblocks on my old computer, which I liked a lot, but I have a class that is using C# and I would like to us VS for both languages if I can.


Create a C++ console project, and code away in C. You may get warnings for including C headers like <stdio.h> instead of their C++ counterparts <cstdio>, but it won't be a big deal for the foreseeable future.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
December 10 2012 21:31 GMT
#98
On December 10 2012 18:58 Azerbaijan wrote:
I have Visual Studio 2012 and I can't figure out how to set it up for C programming. Options for C++ and C# are pretty obvious but allegedly I can use it for plan C ( I think). I was using codeblocks on my old computer, which I liked a lot, but I have a class that is using C# and I would like to us VS for both languages if I can.

Just create your file as a .c file.
Azerbaijan
Profile Blog Joined January 2010
United States660 Posts
December 10 2012 22:06 GMT
#99
Ah, thanks. And thanks for the article; I'm hoping to pick up the C and C++ books for christmas and I've just grabbed the Code one from the library. Should keep me busy for a while.
3FFA
Profile Blog Joined February 2010
United States3931 Posts
Last Edited: 2012-12-11 22:49:52
December 11 2012 21:48 GMT
#100
CecilSunkure just curious, what compilers do you use to program with and what compilers have you used to program with in the past? Any short reviews you would be willing to give of a few?

edit: Also, when reading through this I noticed this odd sentence
In the first sentence about Heap:
The heap is memory is a large location of memory that dynamic memory can be requested from.
"As long as it comes from a pure place and from a honest place, you know, you can write whatever you want."
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
December 12 2012 00:01 GMT
#101
On December 12 2012 06:48 3FFA wrote:
CecilSunkure just curious, what compilers do you use to program with and what compilers have you used to program with in the past? Any short reviews you would be willing to give of a few?

edit: Also, when reading through this I noticed this odd sentence
Show nested quote +
In the first sentence about Heap:
The heap is memory is a large location of memory that dynamic memory can be requested from.

I've used GCC, g++, borland and Microsoft's compiler. I like Visual Studio the most for actually writing code. I like g++ as a compiler the most because it supports a lot of c++11 features that Microsoft does not.

As for what you should use, I'd recommend using Microsoft Visual Studio Express.

And why is that sentence odd? Makes sense to me
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
December 12 2012 09:45 GMT
#102
"heap is memory is"
If you have a good reason to disagree with the above, please tell me. Thank you.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
December 12 2012 21:45 GMT
#103
On December 12 2012 18:45 spinesheath wrote:
"heap is memory is"

Oooh I see it now.
3FFA
Profile Blog Joined February 2010
United States3931 Posts
December 13 2012 22:11 GMT
#104
On December 13 2012 06:45 CecilSunkure wrote:
Show nested quote +
On December 12 2012 18:45 spinesheath wrote:
"heap is memory is"

Oooh I see it now.

Would you mind editing that then? o.O
"As long as it comes from a pure place and from a honest place, you know, you can write whatever you want."
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
December 13 2012 23:49 GMT
#105
On December 14 2012 07:11 3FFA wrote:
Show nested quote +
On December 13 2012 06:45 CecilSunkure wrote:
On December 12 2012 18:45 spinesheath wrote:
"heap is memory is"

Oooh I see it now.

Would you mind editing that then? o.O

I don't have html privileges for TL. I'll be putting an updated version on my personal site though
Mahanaim
Profile Joined December 2012
Korea (South)1002 Posts
December 22 2012 12:46 GMT
#106
Got to appreciate Blizzard even more now
Celebrating Starcraft since... a long time ago.
RGnt
Profile Blog Joined January 2011
Finland100 Posts
January 02 2013 22:09 GMT
#107
Okey, 3 great things coming together here. . . Teamliquid, Gamedev and Cecilsunkure. And funniest thing is, I got to this article through tutsplus article.
Nhatn: my guide names » i just think about what i want to do to ur children » np
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
January 03 2013 06:38 GMT
#108
On January 03 2013 07:09 RGnt wrote:
Okey, 3 great things coming together here. . . Teamliquid, Gamedev and Cecilsunkure. And funniest thing is, I got to this article through tutsplus article.

O.o interesting can you link that?
Recognizable
Profile Blog Joined December 2011
Netherlands1552 Posts
January 03 2013 11:32 GMT
#109
Bookmarked. Once I have a thorough understanding of Python(first language) i'll give give C/C++ a shot.
RGnt
Profile Blog Joined January 2011
Finland100 Posts
Last Edited: 2013-01-05 03:36:04
January 04 2013 00:37 GMT
#110
Here you go: http://gamedev.tutsplus.com/articles/roundups/fantastic-gamedev-tutorials-from-across-the-web/

edit:
For learning resources I would highly recommend Stanford lecture material from:
http://cslibrary.stanford.edu/
and http://www-cs-faculty.stanford.edu/~eroberts/courses/cs106b/
Nhatn: my guide names » i just think about what i want to do to ur children » np
DisaFear
Profile Blog Joined September 2010
Australia4074 Posts
January 06 2013 12:08 GMT
#111
It's like a book, except free! Nicely done
How devious | http://anartisticanswer.blogspot.com.au/
Zeke50100
Profile Blog Joined February 2010
United States2220 Posts
January 06 2013 17:55 GMT
#112
It's interesting that this is listed on that site as a "game development tutorial"; I find this much less to be a tutorial on game development, and much more a simple collection of "things to know and remember". The title itself is "Primer", which I think is fitting enough - a tutorial, I feel, would have to be something much more specific (perhaps concerning the structure of an engine, component-based systems, threading discourses, and so on) in greater detail - but I digress

Anyway, this is excellent for what it is. One thing I think people should remember, if they're trying to do any kind of graphical display, is hardware acceleration. Software rendering is painfully slow T_T
RGnt
Profile Blog Joined January 2011
Finland100 Posts
January 06 2013 21:55 GMT
#113
On January 07 2013 02:55 Zeke50100 wrote:
Anyway, this is excellent for what it is. One thing I think people should remember, if they're trying to do any kind of graphical display, is hardware acceleration. Software rendering is painfully slow T_T


There's a bloody good reason to learn from ground up software rendering 1st. You learn the math behind the magic, which is way more important than to learn "specific" hardware accelerated api
Nhatn: my guide names » i just think about what i want to do to ur children » np
snakeeyez
Profile Joined May 2011
United States1231 Posts
January 06 2013 23:42 GMT
#114
Game programming is too complicated and hard you can get a much easier job doing pretty much anything else and get paid as much or more anyways. More money in other businesses then in making games generally speaking there always exceptions.
Zeke50100
Profile Blog Joined February 2010
United States2220 Posts
January 07 2013 01:49 GMT
#115
On January 07 2013 06:55 RGnt wrote:
Show nested quote +
On January 07 2013 02:55 Zeke50100 wrote:
Anyway, this is excellent for what it is. One thing I think people should remember, if they're trying to do any kind of graphical display, is hardware acceleration. Software rendering is painfully slow T_T


There's a bloody good reason to learn from ground up software rendering 1st. You learn the math behind the magic, which is way more important than to learn "specific" hardware accelerated api


I wouldn't say hardware accelerated OpenGL is a "specific" API. Software rendering only gets you so far, and it is much simpler and far less powerful than hardware accelerated graphics. I'm not quite sure where you're doing hardware acceleration without learning the math behind it. Transformations and whatnot don't happen on their own.
Vorenius
Profile Blog Joined December 2010
Denmark1979 Posts
January 09 2013 21:06 GMT
#116
On January 07 2013 08:42 snakeeyez wrote:
Game programming is too complicated and hard you can get a much easier job doing pretty much anything else and get paid as much or more anyways. More money in other businesses then in making games generally speaking there always exceptions.

I don't think anyone has ever gotten in to game programming for the money though and there are certainly no one here that has sugested that would be a good idea. Just like you don't become a Starcraft pro for the money (unless you're Stephano of course).
pigmanbear
Profile Blog Joined August 2011
Angola2010 Posts
January 15 2013 05:04 GMT
#117
Minecraft is written in Java (I'm not a Java developer). All sorts of games are written in Java. Don't want to burst anybody's bubble but this is written by an amateur for amateurs, and there's a lot more to programming, games or otherwise, than the low-level things covered in this article.

The big thing you need to know when programming anything graphical (like most games) is MATH. The language details are the easy part.
h3r1n6
Profile Blog Joined September 2007
Iceland2039 Posts
Last Edited: 2013-01-15 15:28:37
January 15 2013 15:28 GMT
#118
From the op:

Tools like these can be wonderful for creating games, but this article isn’t dedicated to this area of game programming. I intend to write about how to start programming with the intentions of programming as a profession.


C++ is integral for anyone that wishes to have a career in the video games industry as a professional developer, especially if you want to have the best chances at success when you first start attempting to get a job as a game programmer.


And that holds true. If you want to work in the games industry, you learn C++ and that what the op is aimed at. I personally wouldn't make a case for learning C++ otherwise, but it's just the way it is. I also wouldn't pursue a job as game developer. I feel people romaticise that somewhat and there is too much competition compared to other branches of software development.
IMLyte
Profile Joined November 2010
Canada714 Posts
January 16 2013 10:53 GMT
#119
This is amazing, TL needs to do more about getting these knowhow's more exposure, I barely caught this.
I'ma show you how great I am ~ Muhammed Ali
Naeth
Profile Joined July 2011
Germany25 Posts
Last Edited: 2013-01-17 16:55:46
January 17 2013 16:28 GMT
#120
On December 08 2012 02:58 spinesheath wrote:
Just learn C++. C is used only in some rare and very specific circumstances nowadays.


This is not really true. It is certainly valid in game programming and similar high-level, high-complexity programming endeavours. Moreover, having learned C++ you won't have too hard a time understanding C, so "just learn C++" is sound advice.

But C is still used all over the place, mostly for academic or low-level purposes like kernel programming, drivers or any number of obscure CASs. Heck, people still use FORTRAN...

Edit: Pondering whether my stated uses of C would qualify as "rare and very specific" circumstances, I decided to restate my point: Among all languages C may have a rather low market share today, but compared to just C++ the difference is not as big as one might think. Googling for some numbers on that statement I was surprised to find that the difference is even smaller than I assumed, see this article (10/2011). Of course, there are no really reliable numbers. Plus it's not even clear what we are trying to measure here. How is "market share" defined for programming languages? :S
Nonetheless, the graphic is interesting – especially the "job postings" bar.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
January 17 2013 16:51 GMT
#121
On January 18 2013 01:28 Naeth wrote:
Show nested quote +
On December 08 2012 02:58 spinesheath wrote:
Just learn C++. C is used only in some rare and very specific circumstances nowadays.


This is not really true. It is certainly valid in game programming and similar high-level, high-complexity programming endeavours. Moreover, having learned C++ you won't have too hard a time understanding C, so "just learn C++" is sound advice.

But C is still used all over the place, mostly for academic or low-level purposes like kernel programming, drivers or any number of obscure CASs. Heck, people still use FORTRAN...

Things like kernel programming and drivers fall under "rare circumstances" in my book. These things don't make up a huge percentage of code produced these days. You also aren't very likely to get a job in that field unless you have significant programming experience.
If you have a good reason to disagree with the above, please tell me. Thank you.
Naeth
Profile Joined July 2011
Germany25 Posts
January 17 2013 17:22 GMT
#122
Yes, this is mostly open source and academic stuff. No standard programming job. Also the classification as rare circumstances is fair enough, see my edit on the previous page.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
January 17 2013 18:52 GMT
#123
Well, sure, C is still used a lot, but it's mainly because people have to work with existing C code. New C projects are the rare ones.
If you have a good reason to disagree with the above, please tell me. Thank you.
finkelboy
Profile Joined December 2008
Italy372 Posts
January 18 2013 16:23 GMT
#124
Wow, really really useful, thanks a lot for your effort
Ma jae yoon, what else? By.hero next bonjwa
RGnt
Profile Blog Joined January 2011
Finland100 Posts
January 19 2013 21:12 GMT
#125
I love how EVERY time people get hung up on language choices. C/C++ are pretty much the "standards" currently in the industry. Also, what I've found is that languages like C tends to keep programmers "honest" and teach the subtle art of actually managing the smallest detail in their code.
Personally I used to hate Java, (ironically I fell in love with C# from the get go) but I was "forced" to pick it up for UNI and now I pretty much prefer to use it for almost anything. Personally I did learn programming on C64 Basic and machine language, that was fun. . . And to this day I value the lessons I learned from the "low level" programming and am often able to do stuff more efficiently with higher level languages just because I know what happens under the hood.

So to point, forget the language and learn the art of programming, study the math and understand the algorithms
Nhatn: my guide names » i just think about what i want to do to ur children » np
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
January 19 2013 22:51 GMT
#126
On January 20 2013 06:12 RGnt wrote:
I love how EVERY time people get hung up on language choices. C/C++ are pretty much the "standards" currently in the industry. Also, what I've found is that languages like C tends to keep programmers "honest" and teach the subtle art of actually managing the smallest detail in their code.
Personally I used to hate Java, (ironically I fell in love with C# from the get go) but I was "forced" to pick it up for UNI and now I pretty much prefer to use it for almost anything. Personally I did learn programming on C64 Basic and machine language, that was fun. . . And to this day I value the lessons I learned from the "low level" programming and am often able to do stuff more efficiently with higher level languages just because I know what happens under the hood.

So to point, forget the language and learn the art of programming, study the math and understand the algorithms

The more details you have to manage, the more mistakes you WILL make. There is a reason the programming world has moved to higher level languages over time. When C came out (a high level language at the time), a lot of people said it's no good, proper programming can only be done in ASM. You know how that one ended.

Learning how to program properly is important, but knowledge of low level programming is actually not required for that; the same principles can be applied at all levels of abstraction.
If you have a good reason to disagree with the above, please tell me. Thank you.
Spyridon
Profile Joined April 2010
United States997 Posts
Last Edited: 2013-01-26 05:09:36
January 26 2013 05:07 GMT
#127
On January 18 2013 01:28 Naeth wrote:
Show nested quote +
On December 08 2012 02:58 spinesheath wrote:
Just learn C++. C is used only in some rare and very specific circumstances nowadays.


This is not really true. It is certainly valid in game programming and similar high-level, high-complexity programming endeavours. Moreover, having learned C++ you won't have too hard a time understanding C, so "just learn C++" is sound advice.

But C is still used all over the place, mostly for academic or low-level purposes like kernel programming, drivers or any number of obscure CASs. Heck, people still use FORTRAN...

Edit: Pondering whether my stated uses of C would qualify as "rare and very specific" circumstances, I decided to restate my point: Among all languages C may have a rather low market share today, but compared to just C++ the difference is not as big as one might think. Googling for some numbers on that statement I was surprised to find that the difference is even smaller than I assumed, see this article (10/2011). Of course, there are no really reliable numbers. Plus it's not even clear what we are trying to measure here. How is "market share" defined for programming languages? :S
Nonetheless, the graphic is interesting – especially the "job postings" bar.


It's "somewhat" true.

A lot of people in this topic are talking as from the perspective of a "game developer" as a developer building a full game engine for a game from scratch, but honestly that's not really commonplace in todays industry.

Today being a "game developer" could mean so many multitudes of different jobs, with more of them NOT about programming than the ones that are.

So the statement of "Just learn C++. C is used only in some rare and very specific circumstances nowadays." is sometimes true, but very misleading. If you are going to be a professional game developer (assuming not for your own development team) you will be joining a team that often has an engine of choice already. Contrary to popular belief, these days the engine for most games are NOT made specifically for the game. Most game development companies already have either game engines they already licensed, or they have one that their company designed specifically for the game itself. This means the language you have to know is mostly dependent on the engine you are using, and often times it's not C++, since in a professional atmosphere time = money and you want to develop in as little time as possible. Many times you need to learn a language specific to the engine itself.

Also it's not common knowledge that one of the most common jobs for game programmers these days are actually tool programmers, rather than programmers of the actual game. And its these peoples job to make editors for the game for the other "programmers" to design the gameplay itself. In terms of Starcraft, think of it as you were the person to make the Galaxy editor. Once the editor is done, the further programming work is just functions that are not already available in the editor that someone on the team needs.

Basically any game that's designed with a potential sequel in mind (most games these days) require tool programmers who are adept in the specific engine, rather than broad C++ programmers, since they make sequels much more profitable since you only need new media and minimal amounts of work on everything else. Even if you are an expert in C++ on a C++ based engine, there will still be a longer learning curve than someone who is adept in the engine and only mediocre in their C++ knowledge.

Also, if you want a job in the game industry you need to have a more specific specialty nowdays. You may be a graphics programmer specialized in shaders, you may be an engine programmer (but there arent as many of these as there used to be anymore), you may be the already mentioned tool programmer, you may specialize in optimization and trying to understand and smooth out the complexities of the game engine, you may be a network programmer, or you may specialize in adding and/or balancing game logic to an already existing game stage/level/world and do a very minimal amount of programming (which actually is the job many of the programmers who design the combat systems in games).

So to sum things up, C++ "helps" to know, or at least be familiar with, but it's a bit misleading to say C++ is used more than any other language. C/C#/various scripting languages are actually coming up in the world since tool programmers are becoming more mainstream. I wouldn't advise specializing in a specific programming language though.

My advice to anyone who wants to be a game designer? Do a little shopping on various engines and learn a few of them. You will need to learn a couple different languages based on the engine you join, and it would be good to make sure one of them is C++ focused, but also learn some that are not. You will see the things they have in common with each other, and you will also be able to easily pinpoint the strengths and weaknesses of each language. But more importantly you will learn how to program specific to game development, and learn how real development works in an existing game engine. Once you do this you will probably find what specialty you like and this will enable you to be able to find out what role you would try to find in a professional development team. Furthermore, if you decide you actually want to be an engine programmer, you won't be able to create a very good engine without knowing where the bar is set for a game engine. Once you know the in's an out's of different engines, you will know what you feel you could improve on in your own engine, as well have a long list of your favorite features you encountered in each of the engines you used in the process.
IRL_Sinister
Profile Blog Joined May 2011
Ireland621 Posts
February 12 2013 02:29 GMT
#128
Not into programming or game development at all but this was a great article, thank you.
CecilSunkure
Profile Blog Joined May 2010
United States2829 Posts
February 18 2013 23:00 GMT
#129
On February 12 2013 11:29 IRL_Sinister wrote:
Not into programming or game development at all but this was a great article, thank you.

Awe thanks! That's great to hear
Kerm
Profile Joined April 2010
France467 Posts
March 05 2013 15:36 GMT
#130
On January 26 2013 14:07 Spyridon wrote:
Show nested quote +
On January 18 2013 01:28 Naeth wrote:
On December 08 2012 02:58 spinesheath wrote:
Just learn C++. C is used only in some rare and very specific circumstances nowadays.


This is not really true. It is certainly valid in game programming and similar high-level, high-complexity programming endeavours. Moreover, having learned C++ you won't have too hard a time understanding C, so "just learn C++" is sound advice.

But C is still used all over the place, mostly for academic or low-level purposes like kernel programming, drivers or any number of obscure CASs. Heck, people still use FORTRAN...

Edit: Pondering whether my stated uses of C would qualify as "rare and very specific" circumstances, I decided to restate my point: Among all languages C may have a rather low market share today, but compared to just C++ the difference is not as big as one might think. Googling for some numbers on that statement I was surprised to find that the difference is even smaller than I assumed, see this article (10/2011). Of course, there are no really reliable numbers. Plus it's not even clear what we are trying to measure here. How is "market share" defined for programming languages? :S
Nonetheless, the graphic is interesting – especially the "job postings" bar.


It's "somewhat" true.

A lot of people in this topic are talking as from the perspective of a "game developer" as a developer building a full game engine for a game from scratch, but honestly that's not really commonplace in todays industry.

Today being a "game developer" could mean so many multitudes of different jobs, with more of them NOT about programming than the ones that are.

So the statement of "Just learn C++. C is used only in some rare and very specific circumstances nowadays." is sometimes true, but very misleading. If you are going to be a professional game developer (assuming not for your own development team) you will be joining a team that often has an engine of choice already. Contrary to popular belief, these days the engine for most games are NOT made specifically for the game. Most game development companies already have either game engines they already licensed, or they have one that their company designed specifically for the game itself. This means the language you have to know is mostly dependent on the engine you are using, and often times it's not C++, since in a professional atmosphere time = money and you want to develop in as little time as possible. Many times you need to learn a language specific to the engine itself.

Also it's not common knowledge that one of the most common jobs for game programmers these days are actually tool programmers, rather than programmers of the actual game. And its these peoples job to make editors for the game for the other "programmers" to design the gameplay itself. In terms of Starcraft, think of it as you were the person to make the Galaxy editor. Once the editor is done, the further programming work is just functions that are not already available in the editor that someone on the team needs.

Basically any game that's designed with a potential sequel in mind (most games these days) require tool programmers who are adept in the specific engine, rather than broad C++ programmers, since they make sequels much more profitable since you only need new media and minimal amounts of work on everything else. Even if you are an expert in C++ on a C++ based engine, there will still be a longer learning curve than someone who is adept in the engine and only mediocre in their C++ knowledge.

Also, if you want a job in the game industry you need to have a more specific specialty nowdays. You may be a graphics programmer specialized in shaders, you may be an engine programmer (but there arent as many of these as there used to be anymore), you may be the already mentioned tool programmer, you may specialize in optimization and trying to understand and smooth out the complexities of the game engine, you may be a network programmer, or you may specialize in adding and/or balancing game logic to an already existing game stage/level/world and do a very minimal amount of programming (which actually is the job many of the programmers who design the combat systems in games).

So to sum things up, C++ "helps" to know, or at least be familiar with, but it's a bit misleading to say C++ is used more than any other language. C/C#/various scripting languages are actually coming up in the world since tool programmers are becoming more mainstream. I wouldn't advise specializing in a specific programming language though.

My advice to anyone who wants to be a game designer? Do a little shopping on various engines and learn a few of them. You will need to learn a couple different languages based on the engine you join, and it would be good to make sure one of them is C++ focused, but also learn some that are not. You will see the things they have in common with each other, and you will also be able to easily pinpoint the strengths and weaknesses of each language. But more importantly you will learn how to program specific to game development, and learn how real development works in an existing game engine. Once you do this you will probably find what specialty you like and this will enable you to be able to find out what role you would try to find in a professional development team. Furthermore, if you decide you actually want to be an engine programmer, you won't be able to create a very good engine without knowing where the bar is set for a game engine. Once you know the in's an out's of different engines, you will know what you feel you could improve on in your own engine, as well have a long list of your favorite features you encountered in each of the engines you used in the process.


Depends on the platform.
Go to Gamasutra jobs offers regarding programming for AAA companies (i.e : working on mainstream high profile console/PC games), pretty much every one of them reads "Strong C++ skill required".
What i know is that I know nothing - [http://twitter.com/UncleKerm]
vitruvia
Profile Joined June 2009
Canada235 Posts
April 22 2013 04:56 GMT
#131
2 really successful indie games are made by xna - bastion and terraria.
i'm just wondering if the makers of those games have to pay special licensing fee to microsoft for using xna as their framework.
Since the game is for profit and i assume the majority of the game is completed in xna since it wasn't mentioned other wise.
what quote?
drjones
Profile Joined March 2014
1 Post
March 06 2014 04:51 GMT
#132
Just wanted to say thanks for the tips, following your education has reminded me of a lot of stuff I have not used for quite a while.

Also, to beat a long dead horse, in defense of C:

Think about how many computers you own. One, two, maybe a laptop in addition? But really you own many more. If you have a car you own many separate computers inside it. Your TV, DVD, etc all are full of processors in some cases more than one. And now we want our fridge etc. to talk to our phones or the internet adding more chips. Someone has to write all the code that goes in those processors. And they need it to be fast and efficient. Depending on the application a cheaper chip with more processing or memory constraints might save hundreds on every unit sold. There are embedded applications that have fancy OS layers or that are built in object oriented languages but the bulk of the work I have seen is straight up C. Since the code you are writing needs to execute perfectly, hundreds of times a second for up to 50 years there is little room for tricky implementations that save a few lines of text but are twenty times harder for other engineers to understand.

I studied C++, and many other languages in school and was able to shift to C pretty easily, the important thing is learning concepts behind the syntax, keeping your code readable, maintainable and well architected.

Not to be a downer but I'd have a backup plan. I have several friends who work on AAA titles that are some of the top grossing in history on the art side and they make modest livings and have seen most of their coworkers and occasionally themselves laid off. Replaced by unpayed interns or outsourced. This can happen in any industry but games like movies have a lot of talented people fighting for a few jobs which means employers can really treat ya like crap without a second thought. Go for your dream but don't be so focused that you can't do something boring as well to pay the rent.
LaNague
Profile Blog Joined April 2010
Germany9118 Posts
Last Edited: 2014-03-06 22:53:11
March 06 2014 22:52 GMT
#133
xna is free as far as i know.

Microsoft sells their visual studio ultimate license and gives me a whole lot of tools to play with without bothering me for money, at least thats the deal i think i have with them.




Also, these languages are made to be understood by humans, if you want to learn C++, just do it, its not hard, even as a first language.

C# is another good one, its very productive.
If you go to a university, they make you lean java anyways, i dont know what is it with academics and their java.
Normal
Please log in or register to reply.
Live Events Refresh
Next event in 28m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Creator 99
StarCraft: Brood War
Hyuk 759
Pusan 491
Soma 457
Stork 309
Jaedong 205
ZerO 170
Sharp 160
Larva 134
sorry 129
sSak 98
[ Show more ]
Soulkey 98
Shine 65
yabsab 51
Aegong 39
Snow 39
Free 27
zelot 26
JulyZerg 25
Mind 24
IntoTheRainbow 10
ivOry 3
Dota 2
XcaliburYe567
XaKoH 528
syndereN92
Counter-Strike
shoxiejesuss689
x6flipin409
allub120
Super Smash Bros
Mew2King243
Other Games
Pyrionflax314
crisheroes257
SortOf150
rGuardiaN49
ZerO(Twitch)17
Organizations
Other Games
gamesdonequick28834
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 13 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota2227
League of Legends
• HappyZerGling100
Other Games
• WagamamaTV166
Upcoming Events
Wardi Open
28m
Replay Cast
13h 28m
Sparkling Tuna Cup
23h 28m
WardiTV European League
1d 5h
MaNa vs sebesdes
Mixu vs Fjant
ByuN vs HeRoMaRinE
ShoWTimE vs goblin
Gerald vs Babymarine
Krystianer vs YoungYakov
PiGosaur Monday
1d 13h
The PondCast
1d 23h
WardiTV European League
2 days
Jumy vs NightPhoenix
Percival vs Nicoract
ArT vs HiGhDrA
MaxPax vs Harstem
Scarlett vs Shameless
SKillous vs uThermal
uThermal 2v2 Circuit
2 days
Replay Cast
2 days
RSL Revival
2 days
ByuN vs SHIN
Clem vs Reynor
[ Show More ]
Replay Cast
3 days
RSL Revival
3 days
Classic vs Cure
FEL
4 days
RSL Revival
4 days
FEL
5 days
FEL
5 days
Sparkling Tuna Cup
5 days
RSL Revival
5 days
FEL
6 days
Liquipedia Results

Completed

BSL Season 20
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL 2v2 Season 3
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Jiahua Invitational
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025

Upcoming

2025 ACS Season 2: Qualifier
CSLPRO Last Chance 2025
CSL Xiamen Invitational
2025 ACS Season 2
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.