Connecting C++ Model to Controller with Signals2 in Objective-C/C++ - c++

I'm developing a cross-platform C++ data model with almost 1,000 different kinds of data items (but < 100 different data structures/classes). To handle the Model to Controller messages (i.e. notification for the Controller that some data item has changed) I'm thinking about using boost:signals2. I think this will help create a unified Observer pattern that remains the same across different OS platforms. Initial implementation is on Mac OS / IOS, with subsequent UI developed on .net and unix.
Questions:
1) To set up observation of the data model, what type of object should a Controller connect to the signals2 object/slots? Should there be specific functions/methods/selectors in the Controller for EACH data item observed? Should these functions be C, C++, or Objective-C/C++ functions?
2) What level of granularity should a signal have? Should each item of data have its own? Or should the Model's management of related structures/records maintain a single signal for each type of structure/record? For example — should application preferences have ONE signal for all preferences data — passing information about what data item was changed?
3) Should the process of sending signals (or the slots receiving signals) be performed in a SEPARATE THREAD?
4) I understand Cocoa has its own system for Key-Value Observing. But would such a system be advantageous to COMBINE with the Model's signals2-based Observer paradigm — or just redundant?
UPDATE:
Regarding "granularity" of actual signal2 objects (not observers), I think having one per document and one for application prefs might be a good place to start. My document data already has a "key" concept, so it may be possible to generalize common UI cases where a UI component is tied to a specific item of model data.

There are quite a lot of facets to this question, so I'll tackle what I can.
Why do we want to be able to observe something in Objective-C and .NET?
I think it's instructive to think about why we'd want to observe a data-model in a 4th generation language? Aside from decoupling subsystems, we can also bind UI interface elements directly to the data model in some cases, avoiding the need to write a great deal of code in the controllers. This is possible in a WPF application built on .NET and in AppKit on MacOSX. There are fewer opportunities in UIKit on iOS.
Meta-model
The first obvious thing to point out is that two of the language run-times you want to target (Objective-C and .NET) provide language-level implementations of the observer pattern which are built around object properties. If you want to integrate them without writing thousands of lines of boiler-plate code, you will want to do this too.
This strongly suggests that all of your C++ model classes need to inherit from a meta-model that provides a generic property mechanism. Wrapped up with this will be an mechanism for observing them.
The alternative will be to generate an enormous quantity of boiler-plate setter/getters in C++, and binding objects to make use of them in .NET and Objective-C.
Adaptors
For both .NET and Objective-C you would design a generic adaptor class that uses reflection to do their dirty work. In the case of Objective-C you do this by overriding methods in NSObject to forward property sets/get messages onto the underlying model's property mechanism. I believe in .NET you can use reflection to inject properties corresponding to those in your model into the adaptors.
[Aside] IDL/ORM
Surely by the point you have a data model built on top of a meta-model, you might as well use some kind of IDL or ORM to describe and automatically generate the very large number of model classes? The huge number of classes you are dealing with also suggest this too.
Granularity of Observers
In terms of granularity, you could do either - it really depends on the way in which your data model changes and the UI needs to react to it. KVO in Objective-C is designed around changes to named properties on an object, but is restricted in that an observer has a single delegate method for all objects and properties it observes. This is, however, only an issue for your Objective-C UI components.
Integrating with this is definitely worthwhile unless you want to write masses of adaptor methods for value-changed events that bridge between C++ and Objective C: Remember that whilst there is toll-free interwork between C++ and Objective-C++, objective-C++ classes can't inherit interfaces C++ classes, not can you send a message to an objective-C object from C++ directly without a bridge and some nasty casting in an objective-C++ compilation unit.
With .NET you'd probably get into all kinds of similar machinations with an intermediate managed-C++ layer.
Threading
The only sane way to do this involving more than one thread is to queue signals for processing on the UI thread. After all, if generating signals in another thread you'll need to do this at some point later to update the UI. Using a separate thread for model and View/Controller portions of the app sounds like a recipe for dead-locks. It'll also be very hard to debug the source of a signal it it'll be long gone in another thread. Your life will be much easier keeping it all on one thread.

Related

JavaFX and Clojure: binding observables to immutable objects

I've been trying to figure out the approach to take to allow a JavaFX TableView (or any other JavaFX thing) to represent some Clojure data, and allow the user to manipulate the data through the GUI.
For this discussion, let's assume I have a list/vector of maps, ie something like
[{:col1 "happy1" :col2 "sad1"} {:col1 "happy2" :col2 "sad2"}] and I want it to display in a graphical table as follows:
mykey1 mykey2
------------------
happy1 sad1
happy2 sad2
Pretty straightforward. This has been done a gazillion times in the history of the world.
The problem is the TableView insists on taking an ObservableList, etc., which is inherently a mutable thing, as are all the Observables in JavaFX. This is great for keeping the table up to date, and in a mutable model, it's also great for allowing the user to directly manipulate the data via the GUI. I'm not an expert, but in this case it seems JavaFX wants the GUI object to actually contain the real data. This seems funny (not ha ha) to me. To maintain my own model and communicate between GUI and model via some API or interface also implies that I'm maintaining the data in two places: in my own model, and in the GUI. Is this the Correct Way of Doing Things? Maybe this is ok since the GUI only ever displays a small fraction of the total data, and it lets my model data just be normal model data, not an instance of some Java-derived type.
So this leads to the following three general questions when trying to put a GUI on a stateless/immutable model:
How can the model underneath be truly immutable if the GUI necessarily allows you to change things? I'm thinking specifically of some sort of design tool, editor, etc., where the user is explicitly changing things around. For example LightTable is an editor, yet the story is it is based on immutable data. How can this be? I'm not interested in FRP for this discussion.
Assuming at some level there is at least one Atom or other Clojure mutable type (ref/var/agent/etc) (whether it be a single Atom containing the entire in-memory design database, or whether the design database is an immutable list of mutable Atoms), which of the [MVP, MCP, MVVM, etc.] models is best for this type of creation?
JavaFX has littered the class hierarchy with every imaginable variation of Observable interface (http://docs.oracle.com/javafx/2/api/javafx/beans/Observable.html), with such gems as Observable[whatever]Value, including for example ObservableMap and ObservableMapValue, and then dozens upon dozens of implementing classes such as IntegerProperty and SimpleIntegerProperty... geez! wtf?. Assuming that I have to create some Clojure objects (defrecord, etc.) and implement some of the Observable interface methods on my mostly immutable objects, can I just stick with Observable, or must I implement each one down to the leaf node, ie ObservableIntegerValue, etc.?
What is the correct high level approach? Maintain a single top-level atom which is replaced every time the user changes a value? Maintain a thousand low-level atoms? Let my values live as JavaFX Observables, and forget about Clojure data structs? Implement my own set of Observables in Clojure using some reify/proxy/gen-class, but implement them as immutables that get replaced each time a change is made? Is there a need or place for Clojure's add-watch function? I'd very much prefer that my data just be normal data in Clojure, not a "type" or an implementation of an interface of anything. An Integer should be an Integer, etc.
thanks
I would add a watch to the atom, and then update your observable based on the diff.
http://clojuredocs.org/clojure.core/add-watch

What types of design patterns make events easier?

I'm working on a game and I'm finding myself having a ton of listeners.
For example, when the language of the game changes, the LanguageManager sends a languageChanged event which causes all interested gui elements to get the new text and redraw themselves. This means every interested gui element implements the LanguageListener class.
Another thing I find myself doing a lot is injecting dependencies. The GuiFactory needs to set fonts so it has a pointer to the FontManager (which holds an array of TTF fonts), it also has a GuiSkinManager so it can get Image* based on the skin of the game. Is this the right way to do this?
My main concern however is with the listeners and the massive amount of them; especially for the gui. The gui library im using is almost entirely listener driven. I can get away with ActionListeners most of the time but I still have nested ifs for if event.getSource() == button2 etc.
In general what type of design patterns are used to avoid these issues in large game projects that are much more complex than mine?
Thanks
Listeners are often used in huge applications as well. Don't be scared of them. I'm working with one of the biggest java app and I have seen tones of different listeners there, so it looks like that's the way to be.
For smaller applications Mediator could be way-around if you realy hate listening for events ;)
Instead of having one interface per event type containing a single callback (ie. LanguageListener), if you were to follow the Observer design pattern, you would have one interface xObserver with a callback for every kind of event.
class GuiElementObserver
{
public:
void LanguageChangedEvent(...) {}
void OtherEvent() {}
};
The default empty implementations allow you to redefine only the events you are interested in in the concrete classes.
Concerning dependencies, whenever I refactor code, I like to use the Single Responsibility Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle). You said that the GuiFactory needs to set fonts... But is it really the responsibility of a factory to set fonts?
If you limit the responsibilities of your classes to what they were originally meant to do, you should have leaner classes, cleaner code and fewer dependencies. In this case, maybe adding a font manager and moving the font related code there could be a solution.

Register Game Object Components in Game Subsystems? (Component-based Game Object design)

I'm creating a component-based game object system. Some tips:
GameObject is simply a list of Components.
There are GameSubsystems. For example, rendering, physics etc. Each GameSubsystem contains pointers to some of Components. GameSubsystem is a very powerful and flexible abstraction: it represents any slice (or aspect) of the game world.
There is a need in a mechanism of registering Components in GameSubsystems (when GameObject is created and composed). There are 4 approaches:
1: Chain of responsibility pattern. Every Component is offered to every GameSubsystem. GameSubsystem makes a decision which Components to register (and how to organize them). For example, GameSubsystemRender can register Renderable Components.
pro. Components know nothing about how they are used. Low coupling. A. We can add new GameSubsystem. For example, let's add GameSubsystemTitles that registers all ComponentTitle and guarantees that every title is unique and provides interface to quering objects by title. Of course, ComponentTitle should not be rewrited or inherited in this case. B. We can reorganize existing GameSubsystems. For example, GameSubsystemAudio, GameSubsystemRender, GameSubsystemParticleEmmiter can be merged into GameSubsystemSpatial (to place all audio, emmiter, render Components in the same hierarchy and use parent-relative transforms).
con. Every-to-every check. Very innefficient.
con. Subsystems know about Components.
2: Each Subsystem searches for Components of specific types.
pro. Better performance than in Approach 1.
con. Subsystems still know about Components.
3: Component registers itself in GameSubsystem(s). We know at compile-time that there is a GameSubsystemRenderer, so let's ComponentImageRender will call something like GameSubsystemRenderer::register(ComponentRenderBase*).
Observer pattern. Component subscribes to "update" event (sent by GameSubsystem(s)).
pro. Performance. No unnecessary checks as in Approach 1 and Approach 2.
con. Components are badly coupled with GameSubsystems.
4: Mediator pattern. GameState (that contains GameSubsystems) can implement registerComponent(Component*).
pro. Components and GameSubystems know nothing about each other.
con. In C++ it would look like ugly and slow typeid-switch.
Questions:
Which approach is better and mostly used in component-based design? What Practice says? Any suggestions about (data-driven) implementation of Approach 4?
Thank you.
Vote for the third approach.
I am currently working on component-based game object system and i clearly see some of additional advantages of this approach:
The Component is more and more self-sufficing subentity as it depends only on a set of available subsystems (i presume this set is fixed in your project).
Data-driven design is more applicable. Ideally, this way you may design a system where components are completely defined in the terms of data but not C++.
EDIT: One feature i thought about while working on CBGOS. Sometimes it is convenient to have ability to design and construct subsystemless passive components. When this is on your mind the fourth approach is the only way.
My approach was to implement the proxy pattern within each subsystem. As each subsystem is only interested in a subset of the total components each entity may contain, The proxy stores pointers to only the components the system cares about, eg, a motion system only cares about position and velocity, so it needs a proxy which stores two pointers, to those components. If the entity is missing one or more of those, then the subsystem will ignore it. If both components are present, then a proxy node is created and added to an internal collection. It is also useful for the proxy to store the unique identifier value for the entity, so that proxies may be added/removed in constant time from each subsystem, should it be necessary.
In such a way, should an entity be required to be removed from the engine, a single message containing the id of the entity can be sent to every subsystem. The proxy can then be removed from each subsystem collection independently.

Mixing component based design and the model-view(-controller) pattern

'm developing a 2D game and I want separate the game engine from the graphics.
I decided to use the model-view pattern in the following way: the game engine owns game's entities (EnemyModel, BulletModel, ExplosionModel) which implement interfaces (Enemy, Bullet, Explosion).
The View receives events when entities are created, getting the pointer to the interface: in this way the View can only use the interface methods (i.e. ask for informations to perform the drawing) and cannot change the object state. The View has its onw classes (EnemyView, BulletView, ExplosionView) which own pointers to the interfaces.
(There is also an event-base pattern involved so that the Model can notify the View about entity changes, since a pure query approach is impraticable but I wont' discuss it here).
*Model classes use a compile-time component approach: they use the boost::fusion library to store different state componets, like PositionComponent, HealthComponent and so on.
At present moment the View isn't aware of the component based design but only of the model-view part: to get the position of an enemy it calls the Enemy::get_xy() method. The EnemyModel, which implements the interface, forwards this call to the PositionComponent and returns the result.
Since the bullet has position too, I have to add the get_xy method to Bullet too. BulletModel uses then the same implementation as the EnemyModel class (i.e. it forwards the call).
This approch then leads to have a lot of duplicate code: interfaces have a lot of similar methods and *Model classes are full of forward-methods.
So I have basically two options:
1) Expose the compoment based design so that each component has an interface as well: the View can use this interface to directly query the component. It keeps the View and the Model separated, only at a component level instead of a entity level.
2) Abandon the model-view part and go for pure component based design: the View is just a component (the RenderableComponent part) which has basically full access to the game engine.
Based on your experience which approach would be best?
I'll give my two cents worth. From the problem you're describing, it seems to me that you need an abstract class that will do the operations that are common amongst all of your classes (like the get_xy, which should apply to bullet, enemy, explosion, etc.). This class is a game entity that does the basic grunt work. Inheriting classes can override it if they want.
This abstract class should be the core of all your interfaces (luckily you're in C++ where there is no physical difference between a class, and abstract class and an interface). Thus the Views will know about the specific interfaces, and still have the generic entity methods.
A rule of thumb I have for design - if more than one class has the same data members or methods, it should probably be a single class from which they inherit.
Anyway, exposing the internal structure of your Model classes is not a good idea. Say you'll want to replace boost with something else? You'd have to re-write the entire program, not just the relevant parts.
MVC isn't easy for games as when the game becomes larger (including menu, enemies, levels, GUI...) and transitions, it'll break.
Component or entity-system are pretty good for games.
As a simpler case for you, you may consider using a HMVC. You'll still have issues with transitions, but at least your code will be grouped together in a more clean manner. You probably want your tank's code (rendering and logic) to get close together.
There have been presentation architectures designed especially for agent-based systems, such as Presentation-Abstraction-Control. The hard part in designing such a system is that you ultimately end up hardwiring sequences of collaborations between the agents.
You can do this, but don't use OO inheritance to model the message passing hierarchy. You will regret it. If you think about it, you are really not interested in using the OO inheritance relationship, since the interfaces defined are really just a "Record of functions" that the object can respond to. In that case, you are better off formally modeling your communication protocol.
If you have questions, please ask -- this is not an obvious solution and easy to get wrong.

What's a pattern for getting two "deep" parts of a multi-threaded program talking to each other?

I have this general problem in design, refactoring or "triage":
I have an existing multi-threaded C++ application which searches for data using a number of plugin libraries. With the current search interface, a given plugin receives a search string and a pointer to a QList object. Running on a different thread, the plugin goes out and searches various data sources (locally and on the web) and adds the objects of interest to the list. When the plugin returns, the main program, still on the separate thread, adds this data to the local data store (with further processing), guarding this insertion point using a mutex. Thus each plugin can return data asynchronously.
The QT-base plugin library is based on message passing. There are a fair number of plugins which are already written and tested for the application and they work fairly well.
I would like to write some more plugins and leverage the existing application.
The problem is that the new plugins will need more information from the application. They will to need intermittent access to the local data store itself as they search. So to get this, they would need direct or indirect access both the hash array storing the data and the mutex which guards multiple access to the store. I assume the access would be encapsulated by adding an extra method in a "catalog" object.
I can see three ways to write these new plugins.
When loading a plugin, pass them
a pointer to my "catalog" at the
start. This becomes an extra,
"invisible" interface for the new
plugins. This seems quick, easy,
completely wrong according to OO but
I can't see what the future problems would be.
Add a method/message to the
existing interface so I have a
second function which could be
called for the new plugin libraries,
the message would pass a pointer to
the catalog to the plugins. This
would be easy for the plugins but it
would complicate my main code and
seems generally bad.
Redesign the plugin interface.
This seems "best" according to OO,
could have other added benefits but
would require all sorts of
rewriting.
So, my questions are
A. Can anyone tell me the concrete dangers of option 1?
B. Is there a known pattern that fits this kind of problem?
Edit1:
A typical function for calling the plugin routines looks like:
elsewhere(spec){
QList<CatItem> results;
plugins->getResult(spec, &results);
use_list(results);
}
...
void PluginHandler::getResults(QString* spec, QList<CatItem>* results)
{
if (id->count() == 0) return;
foreach(PluginInfo info, plugins) {
if (info.loaded)
info.obj->msg(MSG_GET_RESULTS, (void*) spec, (void*) results);
}
}
It's a repeated through-out the code. I'd rather extend it than break it.
Why is it "completely wrong according to OO"? If your plugin needs access to that object, and it doesn't violate any abstraction you want to preserve, it is the correct solution.
To me it seems like you blew your abstractions the moment you decided that your plugin needs access to the list itself. You just blew up your entire application's architecture. Are you sure you need access to the actual list itself? Why? What do you need from it? Can that information be provided in a more sensible way? One which doesn't 1) increase contention over a shared resource (and increase the risk of subtle multithreading bugs like race conditions and deadlocks), and 2) doesn't undermine the architecture of the rest of the app (which specifically preserves a separation between the list and its clients, to allow asynchronicity)
If you think it's bad OO, then it is because of what you're fundamentally trying to do (violate the basic architecture of your application), not how you're doing it.
Well, option 1 is option 3, in the end. You are redesigning your plugin API to receive extra data from the main app.
It's a simple redesign that, as long as the 'catalog' is well implemented and hide every implementation detail of your hash and mutex backing store, is not bad, and can serve the purpose well enough IMO.
Now if the catalog leaks implementation details then you would better use messages to query the store, receiving responses with the needed data.
Sorry, I just re-read your question 3 times and I think my answer may have been too simple.
Is your "Catalog" an independent object? If not, you could wrap it as it's own object. The Catalog should be completely safe (including threadsafe)--or better yet immutable.
With this done, it would be perfectly valid OO to pass your catalog to the new plugins. If you are worried about passing them through many layers, you can create a factory for the catalog.
Sorry if I'm still misunderstanding something, but I don't see anything wrong with this approach. If your catalog is an object outside your control, however, such as a database object or collection then you really HAVE to encapsulate it in something you can control with a nice, clean interface.
If your Catalog is used by many pieces across your program, you might look at a factory (which, at it's simplest degrades to a Singleton). Using a factory you should be able to summon your Catalog with a Catalog.getType("Clothes"); or whatever. That way you are giving out the same object to everyone who wants one without passing it around.
(this is very similar to a singleton, by the way, but coding it as a factory reminds you that there will almost certainly be more than one--also remember to allow a Catalog.setType("Clothes", ...); for testing.