Game development - Update method and State pattern - c++

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.

Related

UE4 - C++: How to design a local coop game where characters have different input schemes?

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.

Use different subclass functions from base class

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.

C++: Designing a component-based entity system - advanced problems

In my game engine, that is written in C++, I've moved away from the classical hierarchical entity system and build up a component-based one. It works roughly in this way:
An entity is merely a container for components. Some example components are: Point, Sprite, Physics, Emitter.
Each entity can hold at most one component of each type. Some component depend on another, like Physics and Sprite depend on Point, because they need a position and angle delivered by it.
So everything works fine with the component system, but now I have trouble implementing more specialized entities, like:
A camera, which needs additional functions to handle movement and zoom
A player, which needs support to receive input from the user and move
Now, I could easily solve this with inheritance. Just derive the camera from the entity and add the additional zoom functions and members. But this simply feels wrong.
My question:
How can I solve the problem of specialized entities with a component system in C++?
You seem to be doubting the IS-A relationship here. So why not make it a HAS-A relationship? Instead of being an entity, the camera and the player could be objects that have an entity (or a reference to the entity), but exist outside of your component-system. That way, you can easily keep the uniformity and orthogonality of your component system.
This also fits nicely with the meaning of those two examples (camera/player) as 'glue' objects. The player glues the entity system to the input system and acts as a controller. The camera glues the entity system to the renderer and acts as a kind of observer.
What about just creating components that enable that behavior? For example, an InputComponent could handle input from the player. Then your design remains the same, and a player is just an entity which allows input from a keyboard, rather than input from an AI controller.
Components based system usually have a general method allowing to send "messages" to entities, like a function send(string message_type, void* data). The entity then pass it to all its components and only some of them will react to it. For example, your component Point could react to send("move", &direction). Or you could introduce a moveable component to have more control. Same thing for your camera, add a component view and make it handle "zoom" message.
This modular design already allow to define different types of cameras (like a fixed one not having the moveable component), reuse some component for other stuff (another type of entity may use a "view") and you can also gain flexibility by having various components handling each message differently.
Of course, some optimization tricks could be needed, especially for frequently used messages.
How about giving each entity some restrictions to what kind of components it may hold (and maybe also what it should hold), and loosening those restrictictions when you derive from that entity. For example by adding a virtual function that verifies whether a certain component can be added to the entity.
A common solution is to use the visitor pattern. Basically, you'll have your entity being "visited" by a Visitor class. Inside your entity, you'd have :
void onVisitTime(Visitor* v)
{
// for each myComponent...
v->visit(myComponent);
// end for each
}
And then, you'd have, in the Visitor class :
void visit(PointComponent* p);
void visit(CameraComponent* c);
Be aware that it's a bit of violation of OOP (data-manipulation being handled outside the object, since the visitor will handle it). And visitors tend to become over-complicated, so it's a not-so-great solution.

Is creating a base class for all applications of a particular type good design?

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.

How to restructure this code hierarchy (relating to the Law of Demeter)

I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body
class Body
from which I'll be deriving various implementations of a physics simulation. My game object class then looks like
class GameObject {
public:
// ...
private:
Body *m_pBody;
};
and I can plug in whatever implementation I need for that particular game. But I may need access to all of the Body functions when I've only got a GameObject. So I've found myself writing tons of things like
Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); }
I'm tempted to scratch all of them and just do stuff like
pObject->GetBody()->GetPosition();
but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.
The idea of the law of Demeter is that your GameObject isn't supposed to have functions like GetPosition(). Instead it's supposed to have MoveForward(int) or TurnLeft() functions that may call GetPosition() (along with other functions) internally. Essentially they translate one interface into another.
If your logic requires a GetPosition() function, then it makes sense turn that into an interface a la Ates Goral. Otherwise you'll need to rethink why you're grabbing so deeply into an object to call methods on its subobjects.
One approach you could take is to split the Body interface into multiple interfaces, each with a different purpose and give GameObject ownership of only the interfaces that it would have to expose.
class Positionable;
class Movable;
class Collidable;
//etc.
The concrete Body implementations would probably implement all interfaces but a GameObject that only needs to expose its position would only reference (through dependency injection) a Positionable interface:
class BodyA : public Positionable, Movable, Collidable {
// ...
};
class GameObjectA {
private:
Positionable *m_p;
public:
GameObjectA(Positionable *p) { m_p = p; }
Positionable *getPosition() { return m_p; }
};
BodyA bodyA;
GameObjectA objA(&bodyA);
objA->getPosition()->getX();
Game hierarchies should not involve a lot of inheritance. I can't point you to any web pages, but that is the feeling I've gather from the several sources, most notably the game gem series.
You can have hierarchies like ship->tie_fighter, ship->x_wing. But not PlaysSound->tie_fighter. Your tie_fighter class should be composed of the objects it needs to represent itself. A physics part, a graphics part, etc. You should provide a minimal interface for interacting with your game objects. Implement as much physics logic in the engine or in the physic piece.
With this approach your game objects become collections of more basic game components.
All that said, you will want to be able to set a game objects physical state during game events. So you'll end up with problem you described for setting the various pieces of state. It's just icky but that is best solution I've found so far.
I've recently tried to make higher level state functions, using ideas from Box2D. Have a function SetXForm for setting positions etc. Another for SetDXForm for velocities and angular velocity. These functions take proxy objects as parameters that represent the various parts of the physical state. Using methods like these you could reduce the number of methods you'd need to set state but in the end you'd probably still end up implementing the finer grained ones, and the proxy objects would be more work than you would save by skipping out on a few methods.
So, I didn't help that much. This was more a rebuttal of the previous answer.
In summary, I would recommend you stick with the many method approach. There may not always be a simple one to 1 relationship between game objects and physic objects. We ran into that where it was much simpler to have one game object represent all of the particles from an explosion. If we had given in and just exposed a body pointer, we would not have been able to simplify the problem.
Do I understand correctly that you're separating the physics of something from it's game representation?
i.e, would you see something like this:
class CompanionCube
{
private:
Body* m_pPhysicsBody;
};
?
If so, that smells wrong to me. Technically your 'GameObject' is a physics object, so it should derive from Body.
It sounds like you're planning on swapping physics models around and that's why you're attempting to do it via aggregation, and if that's the case, I'd ask: "Do you plan on swapping physics types at runtime, or compile time?".
If compile time is your answer, I'd derive your game objects from Body, and make Body a typedef to whichever physics body you want to have be the default.
If it's runtime, you'd have to write a 'Body' class that does that switching internally, which might not be a bad idea if your goal is to play around with different physics.
Alternatively, you'll probably find you'll have different 'parent' classes for Body depending on the type of game object (water, rigid body, etc), so you could just make that explicit in your derivation.
Anyhow, I'll stop rambling since this answer is based on a lot of guesswork. ;) Let me know if I'm off base, and I'll delete my answer.