Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 18 Jan 2011
Offline Last Active Jun 03 2014 03:18 PM

#5134495 C++ Constructors vs. Init() Functions

Posted by on 25 February 2014 - 01:08 PM

The difference between them (obvious example inc!):

class MyClassCons
            Pointer* p = new Pointer();

class MyClassInit
        void Init()
            Pointer* p = new Pointer();

int main()
    MyClassConsc aClass;
    //p* already exists!

    MyClassInit bClass;
    //p* doesn't exist yet!

The problem with this is that sometimes p* could be a variable that depends on something ELSE to work.

Using a really bad example, say you put some OpenGL commands in your class' default constructor. Just by definining the class somewhere you'll get a runtime error because when the variable was created, right at the start of your program, the OpenGL context which is required before issuing glCommands wasn't active/didn't exist.


But you do could use Init(); since it would ONLY be called when you explicitly say so:

int main()
    MyClassInit aClass; //it's okay

    aClass.Init(); //okay, no runtime error

But you couldn't do the otherway around:

int main()

    MyClassCons aClass; //Still runtime error

Other than this situation (which I found to be sorta common), I think everything else is due preference...

#5133520 How to "reset" a singleton?

Posted by on 22 February 2014 - 06:55 AM

Rather than resetting a singleton and potentially breaking something that depends on it, it could be better to keep two of them - a previousState and a currentState.

Making your class able to deal with states changes like this so you won't have to worry about re-building the previous state if you're going back and wants things to be exactly as they were.


If that doesn't work for you, you can implement a function in the abstract class that the states resets themselves. So if the inherited states are very different in their core somehow they'll need to know how to reset.


But if I may suggest another approach... I would suggest to avoid using Singletons at all.

There's a bunch of topics on why they're bad (and the good bits as well) that you can look up, but generally, there's no reason at all to keep a singleton. With a good code design you shouldn't need to.

#5132840 Bones and Skeletons

Posted by on 19 February 2014 - 08:48 PM

Hmm I haven't used assimp either and I don't know much of DirectX, but I can tell you how I did my experimental bone animation project in OpenGL.


I also searched the internet but I never came across something that clicked "dang, that's it!" - something that occasionally happens when I search for more usual stuff.

Still, with the help of the folks here in GameDev and very few obscure sites I found around (unfortunately I don't have them anymore, but I'll try to type what I got of useful from them) I managed to get a bone animation sample running.


First is, don't do the animation in your code/program. It's much much much slower. I've read (and then tested) about doing it in the shader and it indeed works much better.

Think of your data:

class Model
        float* vertexes;
        float* bonesWeights;
        Matrix4x4* bonesTransformations;

If you calculate each bone's transformation and modify the vertex data, you'll face two problems:

- It's slow because you'll be doing one vertex at a time and then updating the data.

- Because you're updating the vertex data, you're wasting memory because each model on screen will need to have it's own vertex buffer. If you don't change it's data, then you can have only a single vertex buffer and multiple models using it.


So the best course would be to do the vertex transformation at the shader level. From what I've read, they're already more suited for multi-threading and so the calculations go much faster.

Anyway, as for how to do it... this is for OpenGL so I'm not sure how similar it might be for DirectX, but I think you can get the concept and apply it if you know your stuff with DX Shaders.


Besides the usual Vector3 vertex_position, Vector2 vertex_UV and Vector3 vertex_normal in the shader, you'll need two more: Vector4 bones_weights and Vector4 bones_indexes.

Also you'll need an uniform Matrix4x4 called bone_animation[32] (or 64).


This bone_animation will hold your bones' data so you're limited by up to 32 bones per model. You can increase it if you want but it'll just be a waste of space if you're not really using it.

Another limitation (sorta of) is that each vertex can only be affected by UP TO FOUR bones. That's why you're using Vector4's for bones indexes and weights. You can use another variable if you want or even multiple, but then you would need to make some more additions to the code that might slow down a bit... still, it's up to you and depending on your needs.


Shader code logic:

void main()
    //the vertex basic data here
    vec3 vertexPosition = vertex_position; 

    //checking first bone, applying it's weight
    //I'm getting the Matrix4x4 containing the bone data, getting the index of the first bone and multiplying by it's weight.
    vertexPosition = vertexPosition * (bone_animation[bone_indexes.x] * bone_weight.x);
    //Do this for all 4 possible bones affecting this vertex
    vertexPosition = vertexPosition * (bone_animation[bone_indexes.y] * bone_weight.y);
    vertexPosition = vertexPosition * (bone_animation[bone_indexes.z] * bone_weight.z);
    vertexPosition = vertexPosition * (bone_animation[bone_indexes.w] * bone_weight.w);

    //By here this vertex has been fully skinned, multiply it as usual for your MVP matrix and you're done
    gl_Position = objectTransformationMatrix * vertex_position;

Oh by using this you also need to make sure of a few things, that the ROOT bone (index 0) is an identity matrix or that you pass some index for an identity matrix when there's no more bones affecting that vertex (so it just multiply by 1).


With this, for each model you have on screen you'll need to keep and track only their bones_animation and upload it to the card every frame instead of modifying their vertex data. That's why it's faster too.

This is called shader skinning and I think you can find the sources where I got this from on google, though at the time I googled them I found very few on it (that I could understand at least).


Now, this is the basic idea... you can get it a little bit faster if you change your data a bit. Instead of storing your bones transformations as matrices and uploading a float * 16 per animated model every frame, you can store only a vector3 and a vector4 and apply quaternion math to skin a vertex. You'll be uploading then float * 7 per model every frame then, and the shader will calculate everything else.

I couldn't which is faster on the shader (I haven't looked on debugging shaders yet), so it could be faster or slower... anyway, the idea is to use quaternion * vertex math to figure a vertex's rotated point and then translate it by the bone translation.


The shader code would be:

//uniform mat4 boneAnimation[32]; 
//mat4 containing all the bone transformations, unused for now

uniform vec3 boneTranslation[32]; //Only the translations of each bone
uniform vec4 boneRotation[32]; //And their rotations in quaternion form

//This is the function that will do the quaternion * vector3
void applySkin(in vec3 vertexPosition, in vec3 boneTranslation, in vec4 boneRotation, in float boneWeight, out vec3 updatedVertexPosition)
    vec3 cross;
    cross.x = (boneRotation.y * vertexPosition.z - vertexPosition.y * boneRotation.z) * 2;
    cross.y = (boneRotation.z * vertexPosition.x - vertexPosition.z * boneRotation.x) * 2;
    cross.z = (boneRotation.x * vertexPosition.y - vertexPosition.x * boneRotation.y) * 2;

    vec3 crossQuat;
    crossQuat.x = boneRotation.y * cross.z - cross.y * boneRotation.z;
    crossQuat.y = boneRotation.z * cross.x - cross.z * boneRotation.x;
    crossQuat.z = boneRotation.x * cross.y - cross.x * boneRotation.y;

    cross.x = cross.x * boneRotation.w;
    cross.y = cross.y * boneRotation.w;
    cross.z = cross.z * boneRotation.w;

    updatedVertexPosition = vertexPosition + ((cross + crossQuat + boneTranslation) * boneWeight);

void main()
    //same logic, multiply the vertex per all 4 possible bones affecting it
    //by the way if you want more than 4 here is where you'll have to adapt it and add another variable somewhere
    vec3 skinnedVertex;

    applySkin(vertex_position, boneTranslation[bone_indexes.x], boneRotation[bone_indexes.x], bone_weight.x, skinnedVertex);
    applySkin(vertex_position, boneTranslation[bone_indexes.y], boneRotation[bone_indexes.y], bone_weight.y, skinnedVertex);
    applySkin(vertex_position, boneTranslation[bone_indexes.z], boneRotation[bone_indexes.z], bone_weight.z, skinnedVertex);
    applySkin(vertex_position, boneTranslation[bone_indexes.w], boneRotation[bone_indexes.w], bone_weight.w, skinnedVertex);

    gl_Position = objectMVP * skinnedVertex;

This way you'll only need to worry about getting the data in the right format before, translations and rotations per bone and upload it every frame.

#5132550 Game Engine Code Design

Posted by on 18 February 2014 - 11:33 PM

Hmm I'm not sure if that's a suitable title for this topic, but here goes...


I'm coding a Game Engine and there's various parts of it that I come up with doubts and questions if I'm doing the right thing, and I'd like to ask for opinions and suggestions for these.

I'll post the problems I have, the solutions I've thought of, and I'd like to discuss them if there's a better way or something like that. So I'd like to ask how you would do it and why.


1. The Scene Draw and Object Hierarchy

Explanation: I have a Scene class that has various vectors for all the types of objects in my game, I separated them to make it faster for iterating and to avoid using interfaces in my objects.

class Scene
        void Draw();
        vector<Image*> _images;
        vector<Model*> _models;
        vector<Text*> _texts;

All objects have two Orientation classes that holds it's current position/rotation/etc and it's previous. At each Draw() call, I interpolate with these.

To support hierarchy, I have this in my objects:

class Model
        SceneObject* parentObject;
        Orientation currentOrientation;
        Orientation previousOrientation;

Here, SceneObject is a struct that holds pointers to an object's Orientation (both of them, current and previous), just so I could do this:

void Scene::Draw(float& interpolation)
    //Calculate each object's matrix using a recursive function to calculate it's parent's first.
    //Set a flag to define it's been calculated already so it doesn't calculate again in case of multiple children
    for(unsigned int i = 0; i < _images.size(); i++)
        if(_images[i]->isOrientationCalculated == false)
            CalculateOrientation(_images[i], interpolation);

    //Draw each one of them and reset the flag for the next frame
    for(unsigned int i = 0; i < _images.size(); i++)
        _images[i]->isOrientationCalculated = false;

Matrix4x4 CalculateOrientation(Image* image, float& interpolation)
    if(image->parentObject != 0)
        return CalculateOrientation(image->parentObject, interpolation) * Interpolate(image->currentOrientation, image->previousOrientation, interpolation);

    if(image->isOrientationCalculated == true)
        return image->objectMatrix;
        image->isOrientationCalculated = true;
        return image->objectMatrix = Interpolate(image->currentOrientation, image->previousOrientation, interpolation);

Problem: Only children keeps tracks of their parents so parents don't know if they have children or not. I've thought of making it the other way around, of having parents keeping track of their children, but after coding it I noticed the code was nearly the same, since they're all in a single vector I'd have to keep a flag for each object to set if they've been calculated already or not so I don't calculate children's matrices twice.


Because of this, or rather, any way I'd choose to do (parent->children or children->parent) I would need to add the code above and it's making my Draw() function much slower, and I was trying to leave this as clean as possible.

Do you think this could be done in a better way? How?


2. Text Rendering and Effects

Explanation: I have a Text class that I use Bitmap Fonts with, and I have to use a function SetText(string) to set it's text value.

At first I would save buffer all the characters, and draw them with different positions depending on the text (moving a certain width/height every character/line break).

I thought it was too slow, so I made the SetText(string) function and what it does is, I count the characters, create a new buffer and a single object with all the vertex/uv data for that string, and draw it. It was much (very much!) faster than before.


Problem: Now with this new way of rendering the text, I can't use a basic effect I had before on texts, the one that displays text as if it's been typing (like a character per second). With all the characters in different buffers, I just had to count the string and display until a currentCharacter variable, which increased by 1 per second/timing.


Now since I have the entire string in a single object, I'm having to recreate the object, calculate all the positions/vertex/uv data again, and display, and then this isn't really all that fast as before. Still faster than having multiple buffers though.


Is there a better way to do this?


3. Input Class and Game Commands

Explanation: I don't have an Input class yet, for now, I'm coding on Windows only and I know how to get keyboard and mouse input. I want the Input class to be oblivious of the input or system, so I can make it cross platform and depending on the system, I only point/fill the Input class variables for the game to use.

 ________                                   _______     ________
| System |---(unique input code/message)---| Input |---| Engine |
|________|                                 |_______|   |________|
                                                      \ (configures/add it's specific game commands)
                                                        \ ______
                                                         | Game |

So a game A could add a specific command for Directional Keys and give it the type of float or bool.

It's game code would only worry about checking these specific commands:

if(_input.IsPressed("MOVE_LEFT")) //MOVE_LEFT command created

So far this is simple to do...

Problem: Can I make a code to change the state of the Game's commands with it being unaware of the actual input? Like as if it doesn't care if it's keyboard, joystick, mouse or even touchscreen?

Seeing as how I check for an input on Windows:

        case WM_KEYDOWN:
            myGame->inputClass.Pressed(wParam, true);        

    return DefWindowProc(hWnd, uMsg, wParam, lParam);

I'm "locked" in the sense that I must have wParam defined to a command, and I don't want to have a game command locked to a specific charCode like that if possible.

I've thought of making a Keyboard, Mouse, Joystick class and look for a way to make they work in every platform I'd want to code in, but that wouldn't change much since I would still be locking the commands for the specific codes... but at least I would be sure to work in any platform.


Is there any way to do this? If not I'll probably stick to creating and setting codes for every platform/input type, though it's not much work, but I'd like to achieve something more... automatic.


Hmm typing this last one made me realize that it seems something stupid to ask... it doesn't seem possible to have an input like that, I'll leave it like this though since I'd like to discuss how input classes are made.

#5132202 How can i create normal textures with code?

Posted by on 17 February 2014 - 07:41 PM



It is possible in the sense that can be done, but I don't think it's feasible because the whole point of having a normal texture is because the code can't figure how to do itself...


Check this image. There's a perfect example in the middle of the texture of something that is bumped out but it doesn't appear so from the texture, so only something human looking at it could figure it out.


So if you do it programatically, I think at best (easily) you could do the texture the wrong way, which would be simply by making another texture in black/white shades.

But still, if you can figure some algorithm to make the code "realize" where it is supposed to have height differences... or if you just want to try it out, you can do a simple one using C++ and Bitmaps.


All images in their raw form are bytes that are usually in the format RGB or RGBA.

You can check for various libs (free) for loading images from various formats (such as stb_image, really easy to set up and use) into an array of unsigned char*, and then... well, you can parse each "pixel" by getting the format of it and doing whatever algorithm you want to.

unsigned char* imageBytes = new unsigned char[imageTotalByteSize];

//fill the variable either loading yourself or using a lib

for(unsigned long i = 0; i < imageTotalByteSize; i++)
    imageBytes[0] = 0; //number from 0~255 representing the first pixel's Red channel
    imageBytes[1] = 0; //number from 0~255 representing the first pixel's Blue channel
    imageBytes[2] = 0; //number from 0~255 representing the first pixel's Green channel

    //Do whatever you want with the first pixel - I just set it to black

//Actually you might want to check it depending on the loader you use, some of them invert the image (meaning you start at the bottom) or some might even load it without doing any sorting (so BMPs would be at BGR format instead of RGB)

I'm guessing you could read the entire image, and check if the pixel's darker than a certain amount (all three values < 75) or just take the average of the three or something so it makes a black/white one.


Then you either write over these values or write in another array of the same size. But that's still not yet done, the array is only some data in the memory not the actual image file.

Now you have to save that data into an image file of your own, and I'm not sure how you can do it but surely there's a lib for that. If you don't want to take your time setting it up, check the BMP's file format, it's really easy and fast to make your own (because it's uncompressed, so you only have to worry about the headers, which is setting the right width/height, bits, etc) and then writing it to a binary file, name it "myImage.bmp" and that's it...

#5131745 Why C++?

Posted by on 16 February 2014 - 11:09 AM

 So I dabble with programming, and I know some C++, C# and a little about java/javascript and HTML, and while searching around I frequently found people that say that "real game programmers" use C++ for game programming. However from what I gather even if that seems to be true, there are a lot of other programming languages, perhaps even more suitable for game programming.


  So then I happened upon somewhat of a dumb but meaningful question:

         Why C++?

What makes C++ the favorite/mainstream language in game programming, when other languages such as C# or javascript are easier? Is it just because C++ has been around longer? Does it offer more control over some aspects of data-storage and such? Does it simply have more support?


Thank you in advance for answering.


Languages have "levels" which imply their "distance" from the hardware.

Programming in Assembly for example, you'd be really close to machine code, messing with how the hardware really works, so there's a lot more work to be done.

Higher level languages such as C# or Java have gone through tons of layers of code already, simplifying everything.


For example, creating a string in C# would be as simple as:

string myString = "someString";

In C, without the help of any libraries, you'd have to deal with an array of single characters:

char myString[20];
myString[0] = 's';
myString[1] = 'o';
myString[2] = 'm';
myString[3] = 'e';

(There's easier ways to initialize the variable, but the work is basically the above code)


So, the higher the language level, simpler the code management. But exactly because of this, you lose some "control" of what really happens.

For example videogames. Unlike desktop PCs, they have specific hardware set: Memory X, CPU Y.

When programming a game for a videogame you have to be aware of how much memory and CPU you have available and work with it.


In Javascript, you create variables, use them and that's it.

In C# and Java too, because they have something called "garbage collectors".

So what would happen if you keep constantly creating more and more variables and you reach the limit memory available? Crash. No more space for variables means no more variables, so expect something to crash.


In C++ and below, you can control when to delete a variable from memory, so you can make sure you'll have enough memory to continue your program.

"Garbage Collectors" in Java/C# free the memory when they detect that a variable isn't being used anymore. How do they detect it? This means there's another program running besides it checking for all variables you're creating and constantly checking them to see if they're okay to delete. This program is obviously consuming resources (CPU and Memory) as well, so that's why these languages are considered "heavier" on performance.


So, in general, the higher the language level, the heavier it is on performance because of all the things it is already doing to simplify the programmer's work.

When you want games to be as fast as possible, pushing the hardware to the limits, you don't want anything else doing (unnecessary) work for you.


Another thing about languages is that, the closer it is to the hardware (so the lower it's level), the easier it is to port to different machines.

All machines work in the same way in the lowest level possible: machine code.

The higher the level of the language, more layers it has been gone through, so more limitations it has.


For example Javascript, you must have a browser to run a javascript code (windows can work around it as well).

Or C#/Java, you must have their frameworks installed to run them (.NET and JVM), otherwise they just won't run.


So they're limited by whatever layers precede them. In comparison, an Assembly code could be run nearly anywhere - it's just a matter of how.


Taking all of these in consideration, you can figure why C/C++ is the language of choice for game programming.

It's not hard (harder than languages higher than it, obviously, but much much much easier than Assembly and lower languages), provides much control, and works nearly everywhere (where it doesn't is because the manufacturer is lazy), making your code much more portable.


But don't forget the famous "use the right tool for the job" quote. It'd be a waste of time to program in Assembly for a Windows Game just as it would be unproductive to program a game for PS3 using Javascript (not to mention the work it'd be just to have Javascript useable in the machine).

#5131393 Game Engine, Implementing Physics (Code Layout)

Posted by on 14 February 2014 - 03:17 PM



I've been coding a game engine for a while and now I'm trying to implement physics on it.

The engine has a SCENE class that holds various arrays of objects (Image, Text, Model, etc) that will be draw.

void GameEngine::Update()
    while(_timeModule.NeedsUpdate()) //Fixed Time Step
        _currentState->Update(); //Updates the Game's state

void Scene::Draw(Camera& camera, float& interpolation)
    for(unsigned int i = 0; i < _objects.size(); i++)
        _objects[i]->Draw(camera, interpolation);

How can I implement the Physics code in this layout? What's the best way/consensus on how it's done?


I've been thinking in three ways:


#1: All Objects in the Scene

void GameEngine::Update()
    while(_timeModule.NeedsUpdate()) //Fixed Time Step
        _scene->Update(); //I'll call this method here

void Scene::Update()
    for(unsigned int i = 0; i < _objects.size(); i++)
        if(_objects[i]->PhysicsComponent.isEnabled == true) //Checking if I want physics on this object
            //Do whatever Physics code I want to do on them, based on their physicsComponent properties
            //I have access to the object's properties here, such as Position, Rotation etc so I can add Speed and such and compute

For this first option, I'm guessing it would be hard to code some specific changes or event calling (like when a collision happens) back to the object.

Also, using the Scene to loop through the objects... not sure if it's a good idea.


#2: Per Object

class MyCharacter
        void Update(); //Physics here
        Image* characterSprite;

void Scene::Update()
    for(unsigned int i = 0; i < _objects.size(); i++)

For this second option, the Scene would call each object's Update() function so I can code specific stuff in there. I'm thinking of adding some basic general physics functions such as gravity so I don't have to type it for every object, but just call the function inside their Update() function.

For now this is the most... reasonable option I've thought of.


#3: Totally New Class

void GameEngine::Update()
    while(_timeModule.NeedsUpdate()) //Fixed Time Step

void PhysicsClass::Update()
    for(unsigned int i = 0; i < _objects.size(); i++)
        //Apply physics

void MyGameCode::Start()
    Image* someImage = new Image();
    //Load, etc

    gameEngine.Scene.Add(someImage); //adding to the scene so it'll be draw
    gameEngine.Physics.Add(someImage); //adding to the physics array so it'll be computed

For this third option I don't think it's bad, but it's just like the first option as it's hard to call back the object when, for example, a collision happens.

For example I'd tag the object with collision and a bullet hits it, I have no idea how I could call a specific function when that happens to their "parent" object.


What would be a good way to implement this?

#5098624 Pro and Cons to building a game engine

Posted by on 03 October 2013 - 04:34 PM

I agree with wintertime, I never developed a game (not even a simple one) but I still wanted to make an engine of my own (mostly for curiosity).


There were countless time I was lost like "what should I do next?". Even reading topics and books about it, there were plenty of things that I read and thought "do I really need this? What is this for?"


In the end, I decided to change the perspective and decided to code a prototype game instead, and then make the engine. I've read about how to manage states and such, and typed:

void InitialState::Initialize()
    //Image* myLogoImage
    myLogoImage = Resources.Load<Image>("LOGO");
void InitialState::Update()
    if(counter > Time.Seconds(3))
        State.NextState(new MainMenuState());

I wanted a code that would show my logo for 3 seconds, then disappear, and go to the MainMenu state.


From there, I started to code what things had to be done so the code above would work the way I wanted. First how to load the image, manage the resource, then display it, sort it in the scene, etc


I think this makes it easier for you to figure what do you need exactly and what you want your engine to do.

#5095862 Shader Skinning Questions

Posted by on 21 September 2013 - 11:19 PM

I'm creating my shader skinning for animation and although I've got the basic stuff up, I don't know how to get the values required to actually test it out.


I've got this in my vertex shader:


layout (location = 1) in vec3 vertexPosition;
layout (location = 2) in vec3 vertexNormal;
layout (location = 3) in vec2 vertexUV;
layout (location = 4) in vec4 boneIndexes;
layout (location = 5) in vec4 boneWeights;
uniform mat4 transformationMatrix;
uniform mat4 skeletonMatrix[64];
void main()
    gl_Position = transformationMatrix * (skeletonMatrix[int(boneIndexes.x)] * boneWeights.x) * vertexPosition;


My questions are:


1. Is there anywhere that I can learn how to produce the bones matrices? For now I'm passing an identity matrix but it obviously doesn't do anything, and I don't understand the concept of it yet. 

For example, I have two Quads with two bones, and the middle vertex in the middle have a 50% weight for each bone. What I don't understand is, I have the bone's position, rotation as a quaternion, and what kind of matrix should I set to get the proper transformation? Applying it as I apply my regular transformation matrix makes the vertex transform around the center origin, and not my bone's, so rotations/translations everything is messed.


2. Is there a way I can use this shader as a "general" model shader? I'm worried that, if I make a shader for some special effect for models, I'll have to duplicate it just because this one is used for animated models. Something that wouldn't affect performance (much) and would be ignored if boneIndexes/boneWeights aren't passed by.


3. Could you suggest any sources on this topic that you consider good? I've found some but either they're too advanced for me (and briefly speaks about stuff which I'm supposed to understand already, but I don't, so I get lost) or they're very abstract ("you pass the bone matrix, multiply it by the weight and that's it").


Any tips/infos for someone beginning this topic are very appreciated!

#5093651 A Resource manager design.

Posted by on 12 September 2013 - 01:55 PM

I recently finished my Resource Module as well, I'm going to post the design here so you can get your own thoughts of it.

It's very similar to yours too.


Resource Classes:

First, I have these [Basic Types]: MeshClass, MaterialClass, TextureClass, and anything else that I might add.

They contain only the resource data of how a Mesh if defined, the values of a Material, the Texture image, etc


Then I have the [Info Types]: ImageClass, ModelClass, and still adding new stuff.

These don't contain any data except the IDs/Names of what compose a Image or a Model.


Each one of the above have their own functions to load and save their data.

So I can create new Texture objects from BMPs, PNGs or anything else, and I save them in a format of my own.


And finally, the actual resource classes of: SpriteImage, Model, etc

An Image has an imageClass variable that describes what composes it: a TextureClass, a Material and a Canvas.


Resource Cache:

This class accepts any template, gives it an int for ID and a string for name, and puts it in a vector.

Actually I have two vectors in this one, one for headers, another one for objects.


When I open a resource file in my format from, I read only the headers and save them in the vector.

Then when a resource is requested, I'm surely to return a pointer to the resource, and I go through these steps:

- First, look in the loadedResources vector. If the requested ID/name is already there, return it.

- If not, look in the headerResources vector. I'll find the header based on ID/name, if not I'll throw an error to my error module and return 0;

- If I found the header, I'll create a new object of the requested type, call it's LoadFromResource() function, add to my loadedResources vector, and return it's pointer.


I also left an AddResource() function if I want to load outside the resource manager for some (weird) reason, so it can start to manage it.


It'll free the memory/destroy the objects when it goes out of scope, so I don't have about leaks (I just have to properly delete stuff I allocated in these objects).


Also, this class has a Save() function that will loop through all loaded objects and save it to a file by calling each of the object's SaveToResource() function.

This is so I can get a single file with all resources of the same type, organized with headers, for easier loading the next time.

It also have the Load() (obviously) to accompany it...


Resource Manager:

Then I have this Resources class that has a bunch of template functions, and it's the class that knows how to load each type of resource.


For example, when I call Resources.Load<Image>("imageName"); it'll need to know how an image is loaded:

- First, look in the ResourceCache<ImageClass> to get that particular image's texture, material and canvas size.

- Then load every one of the resources that compose it from the other (Basic Types) ResourceCaches: Texture, Material, Canvas (this one actually I don't keep track, I create a new one everytime a new image is loaded so I can change it without worrying about messing with other images).


I had a hard time coming up with something to handle composite resources, and that's what I came up with.

For example, I might want to have two of the same 3D Model but with a different texture each, so I also had to keep track of each of these models remembering which texture/mesh they had.


For the case that I want a new copy of something that will be changed (such as material), I just create a new one in the Resources's Load function:


template <> Image* Load(int imageID)
    Image* image = new Image();
    image->_imageInfo = _imageInfoVector.GetResource(imageID);
    //imageInfo contains everything about this image
    if(image->_imageInfo != 0)
        image->Texture = _textures.GetResource(image->_imageInfo.textureID);
        //Texture shares the same pointer since I won't change them per image
        image->Material = new Material(_materials.GetResource(image->_imageInfo.materialID));
        //But I will for the material, so I create a new one, and I copy it through a constructor overload
        //So I can change this image's material without it affecting any other images
        //Whatever else my image will have
   return image;


Hope this help give you some ideas on how to design yours.

#5093636 Which Technology to use for my next game ?

Posted by on 12 September 2013 - 01:20 PM

OpenGL/DirectX are two different things.


OpenGL is an open specification for graphics, DirectX is a all-in-one library that handles everything. Direct3D is the one that handles graphics.


A long time ago, every graphics manufacturer used to display graphics their way.

So, in order to draw anything on screen you had to know how to display what you wanted on that particular graphic card. I think there were libraries and/or even Windows managed to handle a bit itself, but things were different from card to card.


It was annoying to have a game work properly only on graphic cards X and Y, but not on Z (does anyone remember those damned Voodoo cards?).


So they had a very bright idea of getting a foundation in which all of these manufacturers would work: OpenGL.

Regardless of how their cards use the data and draw on screen, they would all follow the same rules: To draw a triangle, they need X, Y and Z.

So if all the manufacturers follow this (actually I think this goes to whoever writes their drivers), developers don't have to worry anymore about which card it is, they can be sure that by sending XY and Z, a triangle is sure to show on screen.


So all cards, of probably nearly everything that isn't fully proprietary (like if you made a device yourself and came up with everything from scratch), supports OpenGL.

As more cards are developed, OpenGL evolves and supports even more stuff.

But basically, OpenGL is a collection of functions/variables to access your card's functions, regardless of manufacturer.


Direct3D, which I have little to no experience (yet) with, does the same thing (access your card's functions) but it's hidden through a layer (library) from Microsoft.


By having this layer they're free to add any cool stuff they want on top of it, like "write TRIANGLE and a triangle shows automatically on screen!".

They're still doing the same thing you would have to do with OpenGL, it's just that they have a function on top of it to shorten the calls.


So I think that by using Direct3D you're limiting your game/engine to Microsoft platforms, but you get some things done already.

By using OpenGL your game/engine is more portable to any platform you choose, but it's like doing everything from scratch.


I think these discussions of "OpenGL or Direct3D?" are mostly pointless if you think of them this way, there's benefits and cons to each, it's just a matter of what do you want to do.


Do you want to flip a bool and have some cool feature ready at the cost of being limited to Microsoft/Windows?

Do you want to program every little detail and code these features yourself to be able to port your game/app anywhere?


(Feel free to correct me if I said anything wrong)

#5091390 Why are static variables bad?

Posted by on 03 September 2013 - 01:19 PM

I've read a few threads here that people advise against static variables, and the argument is usually because anything global is bad, but besides this, why are static variables considered bad?


Do they perform badly or something like that?


I'm asking because I've got my engine structure with modules, and I'm using static variables for each module so my base classes can access it.


class GameEngine
            resourceModule = &_resourceModule;
        static ResourceModule* resourceModule;
        ResourceModule _resourceModule;


#include "GameEngine.h"
void Image::Load(string imageName)
    //Texture2D* _texture;
    _texture = GameEngine::resourceModule->GetLoadedTexture(imageName);


Images are meant to be used like this:


void SomeGameFunction()
    Image* newImage = new Image();


I'm currently doing some encapsulation and blocking accesses to base classes that I don't want exposed, so other programmers don't ever access a "Texture2D" class for example, and when I looked to these static variables I thought they might be an issue but I couldn't find of any good solutions for it, that is, if they require a solution...


So I remembered the topics against static variables I thought I should ask, why are static variables considered bad?

#5090519 Moving a single object around in 2D

Posted by on 30 August 2013 - 09:35 PM

An easy way to deal with position and rotation and everything else related to transforms is to use a matrix to represent an object's transformations.


So you can have a class with your object's data (in the case, a single Quad + Texture) in it's original state, and when you're about to draw it, you use glLoadMatrix(matrix) and all it's transformations will be done.


Also, a suggestion, do some research about VBOs, what you're doing is called "Immediate Mode" and is pretty outdated and usually bad on performance.

#5083902 General Engine Optimizations

Posted by on 07 August 2013 - 10:57 AM

I'm coding my first Engine and I'm unexperienced in both game programming and C++, so I'd like to ask about general optimizations and methods.


First, I'm going to develop games with a group of friends, and I decided to work in the engine, so my goal is to keep things as simple as possible for them and whoever else codes the game itself.

For example, I don't want to tell the game programmer "to create an object, you need to first load the object from the resource manager, call the object manager, load it to the graphic card, position it's orientation, then add it to the sceneGraph".

Instead, I'd like to keep it as simple as:


//Game Programming
GameStaticObject* playerHouse = new GameStaticObject();
playerHouse->Load("House1"); //done!


I'm going to be the only one coding the engine, so I'd like to hide how it's working and keep things simple, so when programming the game whoever does it doesn't need to know how the engine is doing it, but instead focus on creating the game.


So far my main layout looks like this:


                                 |    GameEngine     |
                                 |  .GraphicsModule  |
                                 |  .OSModule        |
                                 |  .SoundModule     |
                                 |  .NetworkModule   |
                                 |  .ResourceModule  |
                                 |  .InputModule     |
                                 |                   |
                                 |  .GameTime        |
                                 |  .GameConfig      |
                                 |  .GameScene       |
                                 |  .GameState       |
                                 |  .GameErrors      |
                                 |                   |
                                 |  .SetKey()        |
                                 |  .SetButton()     |
                                 |  .SetMouseMove()  |
                                 |  .Update()        |
                                 |  .Render()        |
 __________________      ________________      ________________      _______________________
|  GraphicsModule  |    |    OSModule    |    |  OtherModules  |    |      GameObjects      |
|  .Init()         |    |  .Init()       |    |  .Init()       |    |  //Not really a class,|
|  .Uninit();      |    |  .Uninit()     |    |  .Uninit()     |    |  //I'm just grouping  |
|                  |    |                |    |________________|    |  //them all here      | 
|  #ifdef OGL/DX   |    |  #ifdef iOS/Win|                          |  - GameTime           |
|  .gfxAPI         |    |  .osAPI        |                          |  - GameConfig         |
|__________________|    |________________|                          |  - GameScene          |
                                                                    |  - GameState          |
                                                                    |  - GameErrors         |
                                   *And the Game Class*
                                 |         Game         |
                                 |  .GameEngine         |
                                 |  .Init()             |
                                 |  .Uninit()           |


The GameEngine class have methods such as SetKey and Update so the Game class call them and don't have to worry about using the inputModule/graphicModule and figuring how it works, the class just focus on populating the data to the scene and updating the objects, and the engine deals with updating the states and rendering.


The Game Time and Main Game Loop


I've read about time in various sources and I think I got the concept of how I should implement it, but I'm not really sure if it's correctly implemented because I that got me really confused.

#include <chrono>
class GameTime
        void ResetTimers();
        bool UpdateGame();
        float GetInterpolation();
        __int64 GetRealTime(); 
        __int64 _currentRealTime;
        __int64 _currentGameTime;
        __int64 _nextGameUpdateTime;
        int _updatesPerSecond, _maxFrameSkip, _timeResolution;
        int _currentFrameSkipCounter;
        float _interpolation;
    //Defining default values
    _updatesPerSecond = 25;
    _timeResolution = 1000 / _updatesPerSecond;
    _maxFrameSkip = 5;
    _nextGameUpdateTime = GetRealTime();
    _currentRealTime = _currentGameTime = 0;
    _currentFrameSkipCounter = 0;
//This is called once per logical update
void GameTime::ResetTimers()
   _currentRealTime = GetRealTime();
   _currentFrameSkipCounter = 0;
//This returns if the game logic should be updated or not, it's called right after ResetTimers()
bool GameTime::UpdateGame()
    if( (_currentRealTime - _nextGameUpdateTime > _timeResolution) && (_currentFrameSkipCounter < _maxFrameSkip) )
        _currentGameTime += _timeResolution;
        _nextGameUpdate += _timeResolution;
        return true;   
        _interpolation = (_currentRealTime + _timeResolution - _nextGameUpdate) / (float)_timeResolution;
        return false;    
__int64 GameTime::GetRealTime()
    return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
//And my main game loop is this:
void GameEngine::Update()
    while(_gameTime.UpdateGame()) //Update the game until _nextGameUpdateTime > _currentRealTime
       //Get the inputState from the last request to this current one
       InputState inputState = inputModule.GetInputState(_gameTime.GetCurrentGameTime());
    //Get the "left over time" and send to render
void GameEngine::Render(float interpolation)
    //render here


Did I got the concept right?

After reading this post (http://lspiroengine.com/?p=378) I think I got the concept, but I'm not sure if it's correctly implemented.


The Input State


class InputModule
        void SetKey(int keyCode, bool keyStatus);
        void SetButton(int buttonCode, bool buttonStatus);
        void SetMouseMove(int positionX, int positionY);
        void SetWheel(int wheelMove);
        //Those functions above will fill the _inputQueue vector with timestamps
        InputState* GetInputState(__int64 currentRequest);
        InputState _inputState;
        vector<Input*> _inputQueue;
        __int64 previousRequest;
void InputModule::SetKey(int keyCode, bool keyStatus)
    Input* newInput = new Input();
    newInput->inputType = InputType::Keyboard;
    newInput->inputCode = keyCode;
    newInput->inputStatus = keyStatus;
    newInput->inputTime = Engine::_time->GetRealTime();
//Same for all other inputs
InputState* GetInputState(__int64 currentRequest)
    if(_inputQueue.size() > 0)
        while(_inputQueue[0]->inputTime <= currentRequest)
                case InputType::Keyboard:
                    _inputState.keyboard[_inputQueue[0]->inputCode].keyStatus = _inputQueue[0]->inputStatus;
                case InputType::Mouse:
                    _inputState.mouse[_inputQueue[0]->inputCode].buttonStatus = _inputQueue[0]->inputStatus;
                case InputType::MouseMove:
                    _inputState.mouse.positionX = _inputQueue[0]->positionX;
                    _inputState.mouse.positionY = _inputQueue[0]->positionY;
            //Input processed, removing it from the queue
            delete _inputQueue[0]; //memory
            _inputQueue.erase(_inputQueue.begin()); //queue
            if(_inputQueue.size() == 0) { break; }; //breaking if it's empty
    return &_inputState;


Keyboard is an array of 256 elements with a single bool variable for the key status, same for mouse, but mouse is only 16 elements.

So I return an InputState with the bools true/false depending on whether the key were pressed until the requestedTime. I'm not sure if I need to keep track of the lastRequestedTime, so the variable is still there until I figure it out.


ClearState() iterates over the 256 keyboard array and 16 mouse array and sets all the bool values to false. I think there should be a better way to clear (maybe deleting the state and creating a new one is faster?) but I still can't test it.


The GameScene


class SceneObject
        GameObject* objectPointer; 
        //The game object also has a pointer to it's own SceneObject
        //So if it gets a child, it's easy to find and add
        SceneObject* previousObject;
        SceneObject* nextObject;
        SceneObject* parentObject;
class GameScene
         //functions to add and remove sceneObjects, same as linked lists
         void Add(SceneObject* sceneObject);
         void Remove(SceneObject* sceneObject);
         SceneObject* sceneObjectList;
         SceneObject* currentObject;
void GameScene::Add(SceneObject* sceneObject)
    currentObject = sceneObjectList;
    while(currentObject->nextObject != 0)
    { currentObject = currentObject->nextObject; }
    currentObject->nextObject = sceneObject;
    sceneObject->previousObject = currentObject;
void GameScene::Remove(SceneObject* sceneObject)
    if(sceneObject->nextObject == 0 && sceneObject->previousObject != 0)
        sceneObject->previousObject->nextObject = 0;
    else if(sceneObject->nextObject != 0 && sceneObject->previousObject == 0)
        sceneObject->nextObject->previousObject = 0;
    else if(sceneObject->nextObject != 0 && sceneObject->previousObject != 0)
        sceneObject->previousObject->nextObject = sceneObject->nextObject;
        sceneObject->nextObject->previousObject = sceneObject->previousObject;
    delete sceneObject;


To add an object as child of another, I do this:


GameObject* myParentObject = new GameObject();
GameObject* myChildObject = new GameObject();
myChildObject->sceneObject->parentObject = myParentObject->sceneObject;


And for transformations I do this:


SceneObject* myCurrentSceneObjectTransformation = myCurrentObject->sceneObject;
while(myCurrentSceneObjectTransformation->parentObject != 0)
    //get the transformation mat4 from the object->gameObject and multiply to my currentObj
    myCurrentSceneObjectTransformation = myCurrentSceneObjectTransformation->parentObject;


I think this is a bad way to do it... anything recursive like this during the game loop looks like a bad idea to me, but I'm not sure and I couldn't think of other alternatives.


The Game Model


class BaseModel
        void Load(char* assetName);
        static ResourceModule* resourceModule;
        static GraphicModule* graphicModule;
class GameModel : public BaseModel
void GameEngine::Initialize()
    //Setting the addresses that the model will use
    BaseModel::_resourceModule = &_resourceModule;
    BaseModel::_graphicModule = &_graphicModule;
void BaseModel::Load(char* assetName)
    ResourceObject* resObject;
    if(resourceModule->IsLoaded(assetName)) //if the data is already in the vector<Objects> in the resourceModule
        resObject = resourceModule->GetAssetData(assetName);
        ifstream fileReader = resourceModule->GetPointer(assetName);
        resObject = new ResourceObject();
        //fill resObject from the stream
    //fill this obj according to resObject
    vertexBufferObject.vertexes = new float[x];
    //model ready for rendering
    //Thinking if I should add an instance to the sceneGraph already


This way I want to get to this:


GameModel* newModel = new GameModel();
newModel->Load("assetName"); //object ready to use/display ingame


This is what I got so far... do you have any suggestions or optimizations, or even alternatives for what I'm doing?

I'm unexperienced with C++ so I think there should have plenty of bad practices there too, and any advice is really appreciated.

#5046069 Why is my Rotation not centered?

Posted by on 23 March 2013 - 04:36 PM

After much reading, trial and error, I managed to get the following code:

void Game::Draw()
    mat4 mProjection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
    mat4 mView = glm::lookAt(cameraPosition, cameraTarget, headsUp);

    mat4 mModel = mat4(1.0f);
    quat qModelRotation = quat(vec3(object.rotationX, object.rotationY, object.rotationZ)); //values are in degrees 0~360 already
    mat4 mModelRotation = mat4_cast(qModelRotation); //quat to mat4
    mModel = mModel * mModelRotation; //applying the rotation to my model
    //mModel = mModel * mModelTranslation * mModelRotation; //this if I put translation as well

    mat4 MVP = mProjection * mView * mModel;
    //send MVP to the shader, where gl_Position = vertex * MVP;

The object's rotating fine on the Z-axis, around it's center, but in the X and Y axis it's rotating around one of it's edges, why?

My object's a cube with values from -1 to 1 only.


I've been suggested to translate to the origin, rotating, and then translating, but I'm multiplying the rotation with the model without any translation and it's center is still off.