• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
iLoveGameProgramming

Structure of classes in good Game Engine?

46 posts in this topic

[quote name='Hodgman' timestamp='1340081228' post='4950487']
That's fine, each style to it's own, but this is still an arbitrary choice by the API designer to use a singleton as a restriction on the end-user developers usage. You could replace the UIApplication singleton by, inside main, making local variables for a window, an event queue, a URL fetcher, etc... and then having the choice weather to make them global variables (e.g. via a singleton) or not, ourselves (i.e. the end-user of the API).
[/quote]

I suppose your right that it's not a requirement that a singleton be used, but at the end of the day, it makes the API easier to use. I'm not saying singletons are the solution to every problem when it comes to needing dependencies throughout your application, but it does make sense from time to time. I am also of the belief that if you are trying so damn hard to not use a particular design pattern that you end up bending over backwards, you should probably take a step back and wonder if you aren't just being a bit evangelical and maybe just maybe that design pattern exists for a reason, and you should stop trying to fight its use in a legitimate use case. I doubt we will ever see eye to eye on this though, so I'm going to gracefully walk away and say, let's agree to disagree [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
1

Share this post


Link to post
Share on other sites
[quote name='krippy2k8' timestamp='1340090513' post='4950505']The main logging object handles adding file, line, function info, process and thread IDs, timestamps, possibly even call stacks when logging exceptions/errors, etc, to the message object[/quote]Do you need an object to do that? That's where the free-function comes in for me.[quote]I prefer a single logging object with multiple logging channels, where each channel can be of a different type. i.e. a FileLoggingChannel for writing to file, a ConsoleLoggingChannel for writing to the console, a SocketLoggingChannel for sending the logs over the network to an external logging application/server. Each channel type just implements a simple interface[/quote]I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:[code]class SocketLoggingChannel : NonCopyable
{
public:
SocketLoggingChannel(...);
~SocketLoggingChannel();
void log( const char* msg );
};

class ConsoleLoggingChannel: NonCopyable
{
public:
ConsoleLoggingChannel(...);
~ConsoleLoggingChannel();
void log( const char* msg );
};

cosnt char* FormatLogMessage(const char* fmt, ...);
typedef std::vector<std::function<void(const char*)>> ChannelVec;

#define Log(channels, fmt, ...) do { \
cosnt char* msg = FormatLogMessage(fmt, __VA_ARGS__); \
for (auto &c : channels){ \
c(msg); \
} \
} while(0) //[/code] Edited by Hodgman
0

Share this post


Link to post
Share on other sites
I am also in the no-need-for-classes camp.
You already have std::cout, std::cerr and std::clog. Why not use them for what they exist?

EDIT: well they are classes... :) Generally I meant don't overengineer something like that Edited by Madhed
0

Share this post


Link to post
Share on other sites
Whether your logger needs to be a separate class or not really depends on if it needs to keep any data. For example a logging system I worked with had the ability to work in combination with the scripting language by capturing all log messages send during the execution of a certain function, making debugging scripts a lot faster as you could visualize where something went wrong. While this did really improve debugging (specially for scripting languages where you can't put breakpoints), in your case I don't think you will need things like that yet. Specially for simple applicatins, simple error output works fine. And if your functions don't need to touch member variables you should make them static, and if your class only has statics they don't need to be in a class.

As for singletons: I have been them being used to death in engines. It's really fun to see the engine being initialized before you even loaded the application because someone is calling the singleton from a static initializer. Even nicer is to clean up the memory on shutdown, you have to explicitly destroy the singleton, only to have somebody still requesting it again, crashing the whole thing to the desktop. But even without these extreme cases, it still is confusing as you don't really know when something is initialized, the flow of your application becomes hidden, which can introduce all kind of hard to debug bugs. Anyway, after having seen this abuse, I kind of decided to avoid them wherever I could. Yeah, you might need to pass some objects around through the constructor more then you want, specially for people with an alergic reaction to constructors. But it does make the flow of your application more clear and helps to reduce bugs because you are forced to initialize things in order or you will not be able to pass a reference to the depending class.
0

Share this post


Link to post
Share on other sites
I guess hating on globals is the cool thing to do here. LOL

Standard function call is the way to go. Hell you can even use your Logger class if you want. Except you keep that hidden.

[source lang="cpp"]//basic example yo.
void logMessage(string message) {
static Logger log;

//post log message here using log object.
log.log(message);

}[/source]

This is only really required if Logger keeps any state, such as the file its logging to among other things. Edited by sss_abaker
0

Share this post


Link to post
Share on other sites
[quote name='Cygon' timestamp='1340101692' post='4950531'][list]
[*]Forfeit logging altogether. I've done this in my code. I'm going all-out with assertions for pedantically checking internal states and exceptions for any usage error. Since the point of logging is to help you find the cause of errors quickly, by not letting any inconsistency, bad return code or missing capability slip under the carpet you remove the need for logging.
[/list]
[/quote]
This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY. There's no combing through log files to find out why your geometry isn't showing up. Simply add an Assert. You can easily remove asserts from release code when you know your stuff works, by using #define.
0

Share this post


Link to post
Share on other sites
Logging is one of the few singletons I have in my game engine, for the simple reason I haven't figured out a sane way to replace it with a non-singleton.
0

Share this post


Link to post
Share on other sites
I usually have a function for logging, but I can see the appeal of passing a pointer/reference to a logger to a constructor, because it allows the user of the class to provide any logger they want (a null logger, a logger that prints out to a file, a logger that prints out to stdout, a logger that verifies that the log agrees with some expected text...). This is particularly useful for regression testing.

If you have 38 minutes to burn, consider watching [url="http://www.youtube.com/watch?v=4F72VULWFvc"]this video[/url].

What I remember from watching it many months ago is that he proposes using polymorphism instead of if statements. The idea is to have two types of code:[list=1]
[*]The core objects, which make use of pointers to base classes for anything they need (the talk uses Java, so the language is a bit different).
[*]The initialization code, which hooks together the core objects.
[/list]
His point is that most if statements in code of type 1 can be beneficially replaced with a polymorphic call, the main benefit being ease of testing.

I am not sure how much I buy this method of development, but I would love to try it sometime. Edited by alvaro
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1340117183' post='4950589']
Do you need an object to do that? That's where the free-function comes in for me.
[/quote]

No, not necessarily.

[quote name='Hodgman' timestamp='1340117183' post='4950589']
I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:
[/quote]

That's actually very similar to how I used to do it, until I discovered that it's useful to be able to do more than just call "log" from user code. In particular invoking the open and close methods (more importantly the close method) on my logging channels from the logger object, using named channels, dynamically setting named properties on logging channels from configuration dialogs, enumerating channels, dynamically remove channles, etc. The interface that I use isn't exactly as simple as what I posted, but basically all that is necessary to implement is the log method unless the channel wants to expose properties, open/close, or a handful of other functionality. A series of function objects could do the same thing, but that gets quickly gets messy and harder to maintain.
0

Share this post


Link to post
Share on other sites
I found this to be a good read: [url="http://accu.org/index.php/journals/246"]http://accu.org/index.php/journals/246[/url]

I haven't personally implemented it, but he addresses several pros/cons in detail.
0

Share this post


Link to post
Share on other sites
Why the hell are people so terrified of namespaces?

[CODE]
//SysLogger.h
namespace SysLogger {
extern int loggedItems;
int initialize(char* somedata, int someother);
void logSomething(char* herpderp);
};
[/CODE]

[CODE]
//SysLogger.cpp
#include "SysLogger.h"

int SysLogger::loggedItems = 0;
static int fd = -1;

static int miscHelperFunction() {
return foo;
}

int SysLogger::initialize(char* somedata, int someother) {
herpderpSystem = new Foo;
fd = herpderpSystem->makeLogFile();
return 4;
}

void SysLogger::logSomething(char* herpderp) {
loggit(fd, herpderp);
++loggedItems;
}
[/CODE] Edited by Khatharr
1

Share this post


Link to post
Share on other sites
[quote name='sss_abaker' timestamp='1340134846' post='4950694']
This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY.
[/quote]

No they don't. They may stop and tell you that you have a bug, but unless your bugs are extremely well behaved and occur directly at the assert site, they can't tell you anything about why you have a bug or where it's at.
0

Share this post


Link to post
Share on other sites
[quote name='krippy2k8' timestamp='1340249621' post='4951200']
[quote name='sss_abaker' timestamp='1340134846' post='4950694']
This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY.
[/quote]

No they don't. They may stop and tell you that you have a bug, but unless your bugs are extremely well behaved and occur directly at the assert site, they can't tell you anything about why you have a bug or where it's at.
[/quote]

This is partially true. Asserts make sense and should be used extensively. The reason that an assertion fails however can be hidden somewhere else in the code, it could even have happened several frames ago. Also asserts are usually removed from release code which simply crashes the program for your customers without any information. IMHO log files are invaluable tools for bug fixing after release.
0

Share this post


Link to post
Share on other sites
Boy am I gonna be yelled at...

Are you adamant you will only have one logger?
Being so it should be available from pretty much everywhere?
Passing around references seems pointless?

So... why not static?

I think you should avoid to overdesign, the simplest solution is usually the best one, if it gets the job done and doesn't impact your development speed, go for it.
1

Share this post


Link to post
Share on other sites
I found the service locator pattern (as described here http://gameprogrammingpatterns.com/service-locator.html) a good alternative to the singleton. Its still very global but not that restrictive anymore.
0

Share this post


Link to post
Share on other sites
I am not a huge fan of globals but when I am forced to use them, I usually do. The way I indicate if I should use them or not, is if they are used by the whole application and if they are dependencies. If they depend on a class, or a class depends on it, then I will not use it. A good example would be a logger. It does not require anything from other classes, it just holds a few functions and outputs information to a file/console. I most likely wouldn't even make it a class, it would just be a few static functions that I would call. At most, it would probably be two or three global variables.
There is a time where using globals too much can make it a pain to debug, but for a simple logger, it won't be too difficult to debug, especially when it's purpose is to help you debug :P
0

Share this post


Link to post
Share on other sites
[quote name='mancubit' timestamp='1340288607' post='4951351']
I found the service locator pattern (as described here [url="http://gameprogrammingpatterns.com/service-locator.html"]http://gameprogrammi...ce-locator.html[/url]) a good alternative to the singleton. Its still very global but not that restrictive anymore.
[/quote]
Looks rather useful, and not just as a static variable.
0

Share this post


Link to post
Share on other sites
Cygon mentioned it as a anti-pattern though..

[quote name='Cygon' timestamp='1340101692' post='4950531']
[list]
[*]Passing some semi-global application class around is just hugely increasing dependencies since now you don't know which objects a class will look up through the application class (the service locator anti-pattern).
[/list]
[/quote]
0

Share this post


Link to post
Share on other sites
Seriously, it's just for logging. Don't overengineer and overthink the solution. A thread-safe and simple function is generally sufficient. If you want to log to different outputs (file, network), use FILE structure or std::ostream.

[code]MyLogger::log(std::ostream& stream, const std::string& what);[/code]

Done.
0

Share this post


Link to post
Share on other sites
yes logging is one thing, but the discussion is also valid for other stuff..
0

Share this post


Link to post
Share on other sites
For higher level objects or systems, dependency injection is always an option.

http://martinfowler.com/articles/injection.html
1

Share this post


Link to post
Share on other sites
[quote name='mancubit' timestamp='1340288607' post='4951351']
I found the service locator pattern (as described here [url="http://gameprogrammingpatterns.com/service-locator.html"]http://gameprogrammi...ce-locator.html[/url]) a good alternative to the singleton. Its still very global but not that restrictive anymore.
[/quote]

[quote name='Nanook' timestamp='1340319700' post='4951534']
Cygon mentioned it as a anti-pattern though..

[quote name='Cygon' timestamp='1340101692' post='4950531'][list]
[*]Passing some semi-global application class around is just hugely increasing dependencies since now you don't know which objects a class will look up through the application class (the service locator anti-pattern).
[/list]
[/quote]
[/quote]

I had to laugh :)

Yep, it's widely considered an anti-pattern because the service locator is the equivalent of handing your classes a big box of other objects and letting them go shopping in it.

The dependencies are turned completely opaque since all you see from the outside is a constructor taking a [font=courier new,courier,monospace](ServiceLocator &)[/font] -- you have to rely on the documentation or consult the code to find out what dependencies a class really has. And those may change at any time. Missing dependencies (common scenario: component X adds a new dependency) result in an error at runtime if and when the code consuming the dependency is reached because the compiler can't determine if the service locator will have the required service when it is looked up. Such classes also become dependent on the service locator implementation (whereas dependency injection can happen without the knowledge of the partaking classes, see [url="https://github.com/phs/sauce"]sauce[/url] for an example).
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0