Say now I have a base class, let's call it GameEngine. The GameEngine class inherited several functions from another class. Now I have several game states and I need to apply sub-class polymorphism to this problem: several game states all need to draw background of the game window. The point is, I must have only ONE class to initialise my game window. My problem is, when I need to change my game states from one to another, how can I do it? Essentially, how can I use different version of subclass function(say DrawBackground) from my superclass?
The code:
BaseEngine *gameEngine;
gameEngine = new MenuState(this);
iResult = gameEngine->Initialise(...); // To initialise the window
// I need to find a way to transfer my state from Menu to Play after the window is initialised
iResult = gameEngine->MainLoop(); // To refresh the window (in case of background changed)
gameEngine->Deinitialise();
So in the above code, I have a BaseEngine which can do several functions (draw something to the window). And I now have two game states, MenuState and PlayState. There is one virtual function in my BaseEngine called DrawBackground() and I need to redefine it(different behaviour) in my Menu and Play states. Now the point is only one state(whether Base, Menu or Play) can initialise the window. However I need it to use different version of my derived class (Menu and Play) to draw different background when state is changed.
It is not really clear what you are asking but it feels like what you want is strategy pattern (that is, in simple words, changing some internal object/algorithm that does the job).
When dealing with inheritance, you should follow the so-called is-a relationship (Wikipedia on Inheritance). In your question, GameEngine is not a state (specifically MenuState).
What you should actually do is to implement the states as a strategy for GameEngine (See Strategy Pattern on Wikipedia, some, including me, call it Policy Pattern which is more self explanatory I think). You could have several classes inheriting from, say BaseState, and you should set these states on GameEngine via something like GameEngine::setState(std::unique_ptr<BaseState> state). The GameEngine will act differently according to the strategy set on it. So in a simple case, we can say that GameEngine::MainLoop() will call the virtual BaseState::draw() function. So the data that gets drawn is simply controlled by the policy set on the GameEngine using GameEngine::setState().
To put it simply, move the behavior to the BaseState strategy and change the strategy to change the behavior.
Optionally you could use some event mechanism to change the strategy (state). There is Boost.Signal, Qt has its own and there are others but it is straightforward to implement one for simple needs, easier thanks to C++11.
Related
this is my first post and I really did a lot of research on the topic before posting here. But now I found several possible solutions and I'm just not sure what is the proper way.
Problem
We are currently developing a local coop game that is a mix of an action game for one player and a puzzle game for the second one. Our actual problem is the input that is currently handled by a player controller that casts on every action mapping delegate received to determine if the possessed Pawn is from type PlayerA or PlayerB to then call the right function.
Let me give you a specific example:
We have two action bindings for the Button B (XBox Controller) currently called "B"
When the delegate is called we cast the possessedPlayer to check whether it shall call PlayerA->Jump or PlayerB->Blink
I'm totally unhappy with the situation that I have to cast everytime we receive an Input just to check wether I have possessed action/puzzle char
Solutions
1) Create 2 PlayerControllers and swap them by using GameMode::SwapPlayerController(Old, New)
I found this function during research but I'm not happy with creating a Player with PlayerControllerA to immediately switch it to use PlayerControllerB,
2) Shift responsibility to the Charatcer class
Another thought would be to delegate the decision making to the Character class by passing down an enum value like E_BUTTON_B from the PlayerController to the Character. We could write a macro that creates this enum based on our input mappings and then delegate the decision to a generic Character->ProcessInput(EnumValue) function. I'm also not quite happy because then the PC does not make so much sense to me.
3) Cache the possessed Pawn to avoid the cast
Another idea would have been to cache the type of the possessed Character whenever the PC possesses a Pawn. This would get rid of the cast per input delegate call.
I would be very glad for advide and any hint how you folks solve such issues in your games. Our main goals are separation of concern, good maintainability and input rebinding.
Cheers and have a nice day,
Parzival
You can create structure like this (written in C++, but this approach could be easily implemented in Blueprints as well):
class MyGameBasePlayerController : public PlayerController
{
// TODO methods common for both controllers (for example Escape key handling)
}
Now specific controllers:
class PuzzlePlayerControler : public MyGameBasePlayerController
{
UPROPERTY(BlueprintReadWrite, Transient, Category = "MyCat"
PuzzleCharacter* puzzleChar;
// TODO handle specific actions for Puzzle chararacter and control handling.
// TODO override base methods / input bindings if necesary
virtual void Possess(APawn* pawn) override;
}
Same goes for ActionPlayerCharacter.
You need to decide, how your characters will differ. If they are same, you can use something like MyGameCharacter : public PlayerCharacter (or you can use broader class PlayerPawn) and your PlayerControllers will call appropriate methods. Then your stored reference to MyGameCharacter can be stored in MyGameBasePlayerController.
Or you can use inheritance as well, so you will have PuzzleCharacter : public MyGameCharacter and ActionCharacter : MyGameCharacter with some common base implementation and extending methods or use virtual method overriding.
Depending on your final structure, you can use overriden Possess method (UE Docs) to get actual pawn instance, cast it to appropriate class (for example PuzzleCharacter or PuzlePawn in PuzzlePlayerController) and store reference for later usage. Be aware that in this case you should implement Unpossess as well, so you can clear your stored reference and behave correctly in any given situation.
For my game, I use a State Pattern to handle my screens. The screen need to update and render each frame. And the game loop is in the Game class.
But I also need an update and render method in the Entity class. Should I use an interface in the Screen and Entity class (e.g. FrameProcess) ? Or can I leave it like this (see image)?
What is the best pratice in OOP ? Are there any pattern for that ?
Basic UML of this problem:
I would create pure virtual functions for update() and render() methods in the Entity class and let the classes that inherit from it define their own behaviour which will let the system behave in a polymorphic manner. Then in Game class or some other type of handler class call update() and draw() methods based on the current state of the system which decides it using the State pattern.
Btw, it tells more about State pattern and its example usage(s) in a very clear manner at http://gameprogrammingpatterns.com/state.html
It depends what you mean by "Entity" in this context. If an entity covers everything that is renderable AND updatable, creating a virtual function for both would be fine (If you plan on deriving other types of Entity like vehicles or weapons). If you have other renderable and updatable types other than Entity, an interface would be the better option in my opinion.
You might also be better off checking out https://gamedev.stackexchange.com/ for further Q&A on gamedev.
I'm wondering if there is some kind of logical programming pattern or structure that I should be using if sometimes during runtime a component should be used and other times not. The obvious simple solution is to just use if-else statements everywhere. I'm trying to avoid littering my code with if-else statements since once the component is toggled on, it will more than likely be on for a while and I wonder if its worth it to recheck if the same component is active all over the place when the answer will most likely not have changed between checks.
Thanks
A brief example of what I'm trying to avoid
class MainClass
{
public:
// constructors, destructors, etc
private:
ComponentClass m_TogglableComponent;
}
// somewhere else in the codebase
if (m_TogglableComponent.IsActive())
{
// do stuff
}
// somewhere totally different in the codebase
if (m_TogglableComponent.IsActive())
{
// do some different stuff
}
Looks like you're headed towards a feature toggle. This is a common occurrence when there's a piece of functionality that you need to be able to toggle on or off at run time. The key piece of insight with this approach is to use polymorphism instead of if/else statements, leveraging object oriented practices.
Martin Fowler details an approach here, as well as his rationale: http://martinfowler.com/articles/feature-toggles.html
But for a quick answer, instead of having state in your ComponentClass that tells observers whether it's active or not, you'll want to make a base class, AbstractComponentClass, and two base classes ActiveComponentClass and InactiveComponentClass. Bear in mind that m_TogglableComponent is currently an automatic member, and you'll need to make it a pointer under this new setup.
AbstractComponentClass will define pure virtual methods that both need to implement. In ActiveComponentClass you will put your normal functionality, as if it were enabled. In InactiveComponentClass you do as little as possible, enough to make the component invisible as far as MainClass is concerned. Void functions will do nothing and functions return values will return neutral values.
The last step is creating an instance of one of these two classes. This is where you bring in dependency injection. In your constructor to MainClass, you'll take a pointer of type AbstractComponentClass. From there on it doesn't care if it's Active or Inactive, it just calls the virtual functions. Whoever owns or controls MainClass is the one that injects the kind that you want, either active or inactive, which could be read by configuration or however else your system decides when to toggle.
If you need to change the behaviour at run time, you'll also need a setter method that takes another AbstractComponentClass pointer and replaces the one from the constructor.
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
I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.