Communication between Main Function and States - c++

I consider to build a game engine with the following design approach.
The principal characteristic is to create so called systems, which cover game menus and game levels. These systems are provided with objects like Window to draw, Input to fetch, Sound to play, and maybe Network to communicate with a server.
class System // abstract class
{
Window* Window;
Input* Input;
...
System(Window* Window, Input* Input, ...)
{
this->Window = Window;
this->Input= Input;
...
}
virtual Pause() = 0;
virtual Resume() = 0;
}
The main function handles the systems thus menus and levels. Say LevelOne is derived from System.
int main()
{
LevelOne Tutorial(&Window, &Input, ...);
Tutorial.Pause();
...
}
This way my code becomes structured and (in my opinion) easy to understand. But how could the main function communicate with the systems?
For example, how could the menu tell the main function that the user had selected a level, and which one? In order to let the main function delete the menu and create a new level object.

I think what you are trying to do here is organize a complete model-view-controller architecture, and the code you provided here is the model and controller portion of it. See some explanations on MVC on the web:
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html
If you have a single main() function trying to listen for messages from your subsystems and calling the appropriate actions as a result, you are trying to implement a single-threaded reactive message loop. You could consider running an ACE reactor that can listen for Qt GUI messages as well as others such as network events, then call your subsystems appropriately (though there may be some performance issues):
http://www.cs.wustl.edu/~schmidt/PDF/reactor-rules.pdf
I am not familiar with graphics engines for video game programming, but most graphics libraries offer a message loop for you during its initialization that doesn't require you to go through this kind of detail. All you typically have to do is create your graphics objects and register them with the main message loop of the library.
And I would recommend using a separate thread listening for network events compared to your message thread listening for graphics events. It separates the work out and helps to improve the performance of your graphics.

Related

Calling methods on an MFC UI class in a separate thread

I have two threads in my MFC application. One of them handles all Wnd stuff and the other some file management. Is it generally a good idea to call some methods on UI classes from other threads? Like for example to update some values the UI fields are showing to user. Or it is a bad practice and I have to send messages to the windows classes? If we try to use locks in UI threads, GUI will freeze frequently which is not really acceptable unless it is for a very trivial job. What is the best practice here? Should we solely use message passing mechanisms when dealing with UI?
There are also some methods on UI which don't involve data or variables. For example telling a window to maximize. Is it bad to call a public method in UI class in this case?
[EDIT]
I forgot to tell about my problem with sending messages. Your parameters a always two pointers and not easily customizable.
Primarily, UI is supposed too be light and responsive. To accomplish that, all the heavy duty works should be handled by a separate thread, wherein it can communicate with the main mfc UI thread using SendMessage().
Commands such as maximizing windows have fairly small overhead and can be accomplished in the UI thread itself. To simulate a long process, the UI can use an animated progress bar, for instance.
Decoupling UI from the program engine also will make your code more modular, reusable and the intent clearer.

Do people use classes as their "game loop?"

So I've been learning how to program so I can make games, and, therefor, I've been reading and watching many tutorials. Every once in a while, I'll come across code (c++) that uses a class to handle game events, but nobody has explained why they do this.
It also seems like some programming languages, like C#, automatically use a class for the program's "main."
So what I want to know is if I should be using a class for my game. Why and/or why not?
Here's an example of what this might look like:
class GAME
{
public:
void load_resources();
bool input();
void update();
void draw();
};
int main ()
{
GAME game;
while (!quit)
{
quit = game.input();
game.update();
game.draw();
}
return 0;
}
Thanks for reading.
In terms of game engine design we have something called a Scene system.
A scene normally hold all the GameObjects.
When you send the scene an event it should iterate on the gameObjects and update them all with events (update start end render postrender keyboard mouse scroll resize etch).
But in a much much simpler form of the system we at least want a game class so we can reload the level.
For example when the user enters the game it may take us a min to load all the models and textures and scripts from memory so we dont want it on our main loop we may want to load async and show a loading screen in this case we'll construct the game on another thread.
Or when the user wins and go to the next level we can unload the last level so we simply destroy the Game/Scene and create a new one of the new level.
In short: this kind of approach is used to define states of our application and manage them easily

wxWidgets (or even OOP GUI) Multiple Windows

I'm kind of stuck on something; regarding spawning multiple forms in OOP.
The message loop most of the time is (wxWidget's case) window->show();
bool MyApp::OnInit()
{
MainWindow *oWindow = new MainWindow(wxT("My Window"));
oWindow->Show(true);
return true;
}
Others have oWindow->run(), but anyway my question is:
I've created a second thread with the exact same structure of the function above and called the message loop method. The problem is that the window appears and dissapears suddenly which doesn't make sense to me. If however I call:
MainWindow *oWindow = new MainWindow(wxT("My Window"));
oWindow->Show(true);
MainWindow *oWindow2 = new MainWindow(wxT("My Window"));
oWindow2->Show(true);
It will work, but I don't want that as I will need to keep track of the windows I create and have them on separate threads. What can I do?
You cannot run wxWidgets windows in anything other than the main thread.
"GUI calls, such as those to a wxWindow or wxBitmap are explicitly not safe at all in secondary threads and could end your application prematurely. This is due to several reasons, including the underlying native API and the fact that wxThread does not run a GUI event loop similar to other APIs as MFC."
http://docs.wxwidgets.org/2.8/wx_wxthread.html
BTW, I cannot imagine any situation where what you want to do is a good idea. There is never any need to tun windows in more than one thread.
A windows program is event-driven. You can as have as many top level windows as you want, but there should be just one event queue so that the events on two windows do not end up in contention for the same resource. This is why wxWidgets prevents you trying to create two threads both handling windows events.

Gtkmm: Adding Window at later time

Because I´m writting a "generic" application behaving completely different when facing other configurations, I´m forced to show gtk windows even if I dont yet know them at startup. There might also be the requirement that multiple windows need to be visisble (not modal dialogs but standalone windows) at the same time. But, it would be great if one can simply start one gtk event loop at startup.
Is is somehow possible to add windows to that loop after it has been started?
While I found the Gtk::Application class which seems to support exactly the indented behaviour I´m restricted to use the Gtk::Main class.
There's only a single Gtk::Main object allowed. Widgets should be created in the same thread the main event loop is being run in. To work around this limitation you need to develop a way to pass your window creation commands to the gtk thread.
The simplest way is to use Glib::Dispatcher
struct WindowBuilder {
/**/
Glib::Dispatcher* signal_create;
void create_window() {
//From main thread...
signal_create->emit();
}
}
void create_mainWnd() {
new Ui::MainWnd();
}
//From Gtk thread...
builder->signal_create->connect(sigc::ptr_fun(create_mainWnd));
Gtk::Main::run();
Glib::Dispatcher doesn't take any arguments with it, so next step is to figure out how to pass arguments around between threads.
For different types of windows you can just use different disptachers.
boost::asio::io_service can help you pass messages around.
while(!exit) {
io_service.reset();
io_service.poll();
while(Gtk::Main::events_pending())
Gtk::Main::iteration();
Sleep(0);
}

Making a GUI using Qt for a text-based game

Me and my fellow classmates decided to make a game over the summer. At first we decided to make it a text-based console app, but then I though that it would be possible to create a GUI for the game using Qt. I played around with it a bit, being able to create widgets and what-not, but was unable to do one thing. For an example, our game contains a Player class. I created a dummy player in the main.cpp and afterwards tried to make the players info to display on a label on a press of a button. After numerous attempts, the only way I was able to do it is by making the player in the mainwindow.cpp . Is there a way to display the info of a player made in the main.cpp? How would it be possible to make the data accessible by different windows, such as the battle window, inventory window, etc.
It's a good thing to let the main.cpp as lean as possible, it should not contain much code in your case.
If I understand correctly you have several windows (could be simple QWidgets with no parent or QMainWindows) running on the same QApplication and your want to share data between them ? Why not just share a Player pointer in both your windows ?
Your main.cpp will look like this:
QApplication app(argc,argv);
YourWindows1 mw1;
YourWindows2 mw2;
Player player;
mw1.setPlayer(&player);
mv2.setPlayer(&player);
mw1.show();
mw2.show();
app.exec();
A more fancy way, could be to use a singleton. This singleton could own and hold your Player instance, every windows can access this singleton statically anytime to fetch Player information. It could be something useful for you to learn.
NOTE: I don't see exactly what is the problem here, perhaps you could share more details about what's causing you trouble ...
In a typical Qt app, main.cpp is only there to start the single application UI object and then turn control over to Qt's event handler. It's possible to deviate from that model, but unless you're quite experienced with Qt it's not something that would be recommended.
I agree with the other posters in this thread in that your main function should be kept absolutely as lean as possible. You want it simply to spawn a new instance of your game, and the let the game loop or state control manager take care of the rest. It basically boils down to something like this:
class Game{
Game();
~Game();
int OnExecute();
};
int Game::OnExecute(){
while(running){
// do game stuff
}
return 0; // No errors, game closed correctly.
}
int main(int argc, char* argv[]){
Game myGame;
myGame.OnExecute();
}
All of your initialization methods/code is contained within the OnExecute function, prior to the game entering its main loop. Within that main while(running) loop, you put your calls to your per-frame Update and Rendering functions which control logic calculations like entity position, physics updating, AI updating, etc and then you render everything for that frame. This is obviously an ultra-simplistic strategy, but it definitely helped me grasp exactly how it is that game engines work.
Now, as far as Qt is concerned, I've tried exactly what you are trying and it is not easy. Qt, though it can be rigged to work for in-game interfaces and the like, seems to me to be primarily intended for use in applications more than games. It provides excellent functionality if you need simple forms and buttons in your program, but as far as custom-designed HUDs and such, you're going to want to look somewhere else in order to save yourself a great deal of hassle. There are, however, a huge number of extensible GUI libraries specifically meant for games. I would suggest looking for one based simply on OpenGL since most graphics/game engines are built upon it and would integrate quite nicely.