C++ Class Access Management - c++

I'm developing a game using OpenGL. I have a Game class that contains all the environment variables (by environment, I mean things like gravity or tile sets). There's only one Game object. I also have another class called Entity, which contains properties to display objects on the screen.
I'm finding myself needing access to more and more Game variables in my Entity class. At the moment i'm just using parameters to pass data into each function, but I'm considering just passing a pointer to the Game class? Is there anything wrong with that? Is there a better way?

I think this is good practice. It is good idea to replace a group of parameters with a parameter object.
Just make sure that Game remains cohesive. The variables contained within Game should be related.

Make Entity a Friend of the Game class.
Please see
http://msdn.microsoft.com/en-us/library/465sdshe.aspx
Note: If this is ever done in C#, there isn't a friend keyword or exact equivalent.

Related

How to access non-static Qt Ui function from a static member function of a different class?

So me and my friends are developing Connect4 in C++. At first we elaborated the logic behind the game in a Visual Studio Console Application. We came up with 3 classes, "Logic", "GameUi" (That name is probably not suitable) and "Gui". (I should mention that all members off these classes are static members - so no instances)
Once the logic worked it was my job to tranfer it to Qt. And here's the problem:
So basically once the player has done an input (aka. The Player has chosen a column in which he wants to throw the slice (?) in) the Logic class processes this input and updates the vector in which we store the field. After this Logic calls the GamUi class, which should then call a function in the Gui class (Note that the Gui class is now the Qt class). The Problem with that is that I can't call a non-static function in the Qt class to change the Ui from a static function from a different class.
At first I thought about making the Ui public, which is according to the internet not a good programming exercise.
Thank you very much in advance
Ps: Please don't judge me for my non-native-speaker-english and my not very good c++ skills.
Assuming GUI is a singleton, you might code a static GUI::instance() method that returns a pointer to itself. Call it from anywhere and you have your pointer. Better yet, [inherit from QObject and] use signals and slots.

Using singletons inside a factory class (C++)

I am working on developing a game engine using DirectX 11 and C++ (using the default Visual Studio template) and I have some questions that I cannot find answers to online.
So there are three main components for the game, the actual game class, a renderer and a logic class. The game class would look like this
class Game {
Game();
~Game();
Logic* m_Logic;
Renderer* m_Renderer
}
(If you are curious, I am doing this for two reasons, 1. to play around with classes, I've done it the conventional way before so I want to try something else and see if it has any real benifits. 2. so that the code for both are completely abstracted from eachother)
My question here is if it is a bad idea to make the two subclasses into singletons (given the game class is). I understand when and why one might use them, but considering that there will only ever be a single instance within the game class, would this work fine? What if the game class wasn't a singleton, and could instead run multiple copies at the same time (thus allowing for running multiple games at the same time, once again out of curiosities sake)
NOTE: Since everyone keeps pointing this out. I know they aren't a good idea. This is a test/experiment. I am having my fun programming. Let me have my fun :P
EXAMPLE: An example of why I might want a renderer to be a singleton when the game class can have multiple instances. Since the renderer will be identical between different instances of the game, there is no need for there to be multiple instances of it. Think of it as a container of all the functions that just takes the various variables stored in the game class and does the things to it to output to screen. Same goes for the logic class.
Some would say that "Singletons are never a good idea", but this statement is not held by engineers behind many popular game engines to this day. I will advise you to minimize their use everywhere possible, but there will be situations that they are well-suited for. In fact, "Game Engine Architecture" written by Jason Gregory over at Naughty Dog has a whole section on their uses. I will give an example that I kind of regard as a hybrid approach.
If you read through the code base of Unreal Engine (or at least use the engine), you will find something along the lines of:
extern class UEngine * GEngine
UEngine is actually the base class of all Engine implementations (and there are multiple as there is a need for different variants). During startup, the launcher determines which variant it needs to load and then proceeds to construct a single instance that the entire system will then use. This is similar to your approach, but rather than making multiple Singletons, you can have a global reference to your Game object that gets set once during initialization:
extern std::unique_ptr<Game> game; // Global game reference in some .h file
(in .cpp)
std::unique_ptr<Game> game;
int main(int numArgs, char ** args) {
game = std::make_unique<Game>( ... ); // Initialize game exactly once!!
...
}
This approach allows you to do some interesting things, especially if you make Game an interface like the engineers behind Unreal Engine decided to do and then have multiple implementations depending on the need behind it.
Should each object that Game maintains be a Singleton? I would not think so as it actually limits what you can do later. Game needs to at least support the following:
Creation, start up and shut down of things like Logic and Renderer, in the correct order (it owns all of these objects it creates, so all code that interfaces with Game inevitably interacts with them!)
Ability to retrieve references to things like Logic and Renderer, or whenever possible keep them hidden but provide a limited interface to gain access to their functionality
Since Game is now your only/one of your only global variables, it becomes the gateway into your engine environment and thus you can do a lot of stuff to encapsulate the components that it maintains rather than making many singleton objects
I consider this a better approach than making all of your core classes singletons.

Making a simple particle system

I had a question regarding the way I am designing my particle system.
Right now I have a class P, which stores all the information about a particle such as speed, position, direction, type, etc. I also have a main file I will be drawing these particles, updating and instantiating them in. I want to create a list of these particles using the c++ std list library, so initially I did
std::list<P> listOfParticles;
in the main file. Here is the problem. By doing this I will essentially be forced to make my update and draw functions in the main file. I feel like this is bad practice, and that everything to do with the particle should be kept in one class, but I am unsure where to go from here in terms of best practice. Would it be a good idea to just create a list of particles in the class P where I am defining what a particle is? I feel like this isn't a smart idea though..
If anyone could guide me in the right direction I would really appreciate it.
"By doing this I will essentially be forced to make my update and draw functions in the main file"
No one is stopping you from putting declarations/definitions of class members in same/different .h/.cpp files.
EDIT:-
That's what I said, better it would be if you make this List a member of some other class where you would put all functions to manipulate this list.
Your list of particles most probably deserves its own class, let C, that will handle storage, initial spatial distribution, temporal updates... i.e. all global operations on the particle cloud. If you are sure that you will ever handle a single list, you can make it a static member.
The class that represents the individual particles (P) can be nested into (C) if there is no need to see it from outside. It will encapsulate particle data and possibly also model pairwise interaction with another particle and other single-particle operations.

Mutual inclusion with singleton

I currently have a problem with mutual inclusion in a project of mine (C++).
Normally, if I had a mutual inclusion problem, I'd easily solve it by either forward declaration or redesigning the classes a bit. But this time, I'm stuck:
I have a class called Game, which creates and launches core game systems, where one of these is called GraphicsSystem.
In the Game constructor, a GraphicsSystem object is dynamically created and stored in a GraphicsSystem* pointer. Looks like this:
Game::Game ()
{
gfxSys = new GraphicsSystem(80, new Camera());
}
Now my GraphicsSystem class needs to access a Game class's method at one point to get the player object, which is stored within the Game object. The respective part looks like this (Game is btw a singleton!):
void GraphicsSystem::handleFrame ()
{
ElementList elements = Game::instance()->getPlayer()->getEnvironment()->getElements();
}
Now I tried forward declaration in both directions already, but that wouldn't satisfy the compiler. I could of course also just put the player pointer into the graphics system, but I really don't want to do that, since he doesn't belong there.
Is there any way to resolve this without me having to change the design too much? I'm really stumped right now, so I hope you guys can help me.
I'm using Visual Studio 2010 (Visual C++).
Thank you in advance!
Chris
Forward declare GraphicsSystem in Game.h. Include Game.h in GraphicsSystem.h if it needs it. Include Game.h and GraphicsSystem.h in Game.cpp. Include Game.h and GraphicsSystem.h in GraphicsSystem.cpp.
That should work based off the code you posted.
There are two main ways to break circular dependencies in C++.
1) Create a 'interface' class which lists the methods implemented by your real class and which your real class inherits from. Then you can include that instead of the declaration of the real class.
2) Pimpl - a class holds an opaque pointer to its real data, solving the problem of having to include declarations for the types of member variables.
I know this is going to sound dodgy, but have you considered holding a global reference to the initialized Game class?
I know globals are evil and so on and so forth, and I'm sure lots of people are going to rage, but in my personal experience I have succumb to Singletonitis with the Game class (among others) and found that sometimes it just simply isn't necessary.
The biggest question you need to ask yourself is "Who are you trying to protect your Game object from? and is there any reason why you need to request an instance each time you need the game class? I'm pretty sure that if your Game object wasn't initialized, you wouldn't be doing much else in your engine anyway.
Hope this might help you think about things in a different way, even though it's not answering your question directly.

c++ GUI Events/Messaging Design

So, I'm making a simple game using DirectX 9 and C++. I looked at the SDK's GUI, but I think I can implement something simpler.
All I want are windows, labels, buttons, textboxes, and checkboxes.
I've created a base class GUIObject, that all inherit from. It includes basics like size and focus and whatnot. Then the derived classes, GUILabel for example, all define render(), update() and whatnot.
My question is how to handle events, like clicks? I had it working with GUILabel::Click() defining every possibility based on the current instance's text member value. It felt wrong and I realized that every single label that needed to be clicked would have to be defined in the GUILabel class. I'd like to move that to each game state's code.
So, I briefly tried making the GUILabel::Click() take a function pointer as an argument. But then I realized I needed to have the state's class member method as static (not really possible, unless everything in it is static as well, right?) or also pass it a GUIObject class as well. Is that the way to go?
Could I define a derivation of GUILabel (or button, or whatnot) within a game state and just override whichever actions I needed? And then do that for whatever controls I need in that state?
What is the proper way to implement event handling?
You might want to look into using a signaling library such as boost::signals to allow you the flexibility of defining the interface between your GUI objects and the underlying events that each callback will trigger. It can also come in handy for the reverse relationship where you need GUI elements such as status indicators, etc. to respond to underlying events.
For callbacks/click events i would go with boost::function/boost::bind.
In my GUI framework I used to have two different abstract classes InputHandler and Renderable for handling touches and rendering. This leads to a design where components which don't need to be clickable (like UILabel) wont need to implement useless methods.
HTH,
Alex