Shared single variable for list? - c++

This problem is a little difficult to describe, so bear with me if it isn't clear.
I want to implement a doubly-linked list with a single, universally accessible [to the items inside] Head, End and Iter pointers - this would greatly reduce memory overhead and processing/accessing times...
Static almost fulfills this role - except, it's shared by all classes of the same type - which what I don't want [as I might have multiple doubly-linked lists - I need one per list, not one per class]. So what I need is something similar to static, except it's localised to different declarations.
Head/Node methods become complicated (notably as it uses templates) and I want to avoid this at all costs. Head just ends up having duplicate functions of Node [so Node is accessible], which seems a waste and added complexity just to have three local-universal variables.
What I'd like is something similar to this:
class Test
{
private:
static Test *Head; //Single universal declaration!
static Test *End;
static Test *Iter;
//etc etc
};
Except...
Test A; //Set of 'static' variables 'unique' to A
Test B; //Set of 'static' variables 'unique' to B
I am willing to entertain any and all solutions to the problem, but please avoid complicated solutions - this is meant as an improvement and needs to be quick and simple to implement.
Additional Information [as requested]:
There isn't a 'problem' per se [aside in terms of avoiding overhead and design] - this is setting the frame-work/ground-work for several other classes/functions to build on. So the class needs to be able to handle multiple roles/variables/classes - for this, it has to be templated [although this isn't entirely relevant].
One [of many] of it's main roles is storing individual characters [loaded from files] in seperate Nodes. Given the size can vary, it has to be dynamic. However, as one of it's roles involve loading from files, it can't be an array [as reading the file to work out number of arguments, characters etc causes harddrive/access bottlenecks]. So...
...Singly-linked lists would allow a character to be [easily] added [to the list] on each pass that gets a character [and counted at the same time - solving two problems in one]. The problem is singly-linked lists are very hard to [safely] delete, and navigation is one way. Which is a problem as this hinders search functionality, and notably, the intended multipurpose role...
...So the conclusion is it has to be a doubly-linked list. I don't like the STL or standard lists as I have no idea of their efficiency or safety, or indeed, compatibility with additional features the class has to support. So it has to be a custom built D-L-List...
...However I previously (some time ago) implemented a Head/Node method - it worked. However it become complex and difficult to debug as Head and Node shared functions. This time around I just want a simple, single [Readable! It's going to be shared!] class that somehow sidesteps the almost 'beaucratic' nature of C++. That means no Head/Iter/End copying overhead (and all functions/variables/debugging required for it) and no Head system with it's duplication...
...Static is the closest I get. Perhaps there is a way that somehow, you have Class A that stores the three variables, and a Class B that stores the list - and both of them are aware of each other and are able to communicate via some method/function (no pointer storage!)...
...Something along those lines. I am pretty sure there is some hierarchy or sub-class or inheiretence trick that would pull this off, and I need someone who knows the finer arts better than I do to, refine my raw idea or something.

If static variables are not suitable, you have only one possibility - use instance variables.
If you want to share the variables between the items, put them in the list itself and maintain a pointer to the list in each item as follows:
class List
{
Item* head;
Item* end;
Item* iter;
};
class Item
{
List* list;
};

Make a List class (as already shown by vitaut, but add a makeEntry() function in which a reference to the List class can be passed. If List becomes more complicated, I would isolate these members to ListInfo, so the node only have access to them

Related

C++ member variable change listeners (100+ classes)

I am trying to make an architecture for a MMO game and I can't figure out how I can store as many variables as I need in GameObjects without having a lot of calls to send them on a wire at the same time I update them.
What I have now is:
Game::ChangePosition(Vector3 newPos) {
gameobject.ChangePosition(newPos);
SendOnWireNEWPOSITION(gameobject.id, newPos);
}
It makes the code rubbish, hard to maintain, understand, extend. So think of a Champion example:
I would have to make a lot of functions for each variable. And this is just the generalisation for this Champion, I might have have 1-2 other member variable for each Champion type/"class".
It would be perfect if I would be able to have OnPropertyChange from .NET or something similar. The architecture I am trying to guess would work nicely is if I had something similar to:
For HP: when I update it, automatically call SendFloatOnWire("HP", hp);
For Position: when I update it, automatically call SendVector3OnWire("Position", Position)
For Name: when I update it, automatically call SendSOnWire("Name", Name);
What are exactly SendFloatOnWire, SendVector3OnWire, SendSOnWire ? Functions that serialize those types in a char buffer.
OR METHOD 2 (Preffered), but might be expensive
Update Hp, Position normally and then every Network Thread tick scan all GameObject instances on the server for the changed variables and send those.
How would that be implemented on a high scale game server and what are my options? Any useful book for such cases?
Would macros turn out to be useful? I think I was explosed to some source code of something similar and I think it used macros.
Thank you in advance.
EDIT: I think I've found a solution, but I don't know how robust it actually is. I am going to have a go at it and see where I stand afterwards. https://developer.valvesoftware.com/wiki/Networking_Entities
On method 1:
Such an approach could be relatively "easy" to implement using a maps, that are accessed via getters/setters. The general idea would be something like:
class GameCharacter {
map<string, int> myints;
// same for doubles, floats, strings
public:
GameCharacter() {
myints["HP"]=100;
myints["FP"]=50;
}
int getInt(string fld) { return myints[fld]; };
void setInt(string fld, int val) { myints[fld]=val; sendIntOnWire(fld,val); }
};
Online demo
If you prefer to keep the properties in your class, you'd go for a map to pointers or member pointers instead of values. At construction you'd then initialize the map with the relevant pointers. If you decide to change the member variable you should however always go via the setter.
You could even go further and abstract your Champion by making it just a collection of properties and behaviors, that would be accessed via the map. This component architecture is exposed by Mike McShaffry in Game Coding Complete (a must read book for any game developer). There's a community site for the book with some source code to download. You may have a look at the actor.h and actor.cpp file. Nevertheless, I really recommend to read the full explanations in the book.
The advantage of componentization is that you could embed your network forwarding logic in the base class of all properties: this could simplify your code by an order of magnitude.
On method 2:
I think the base idea is perfectly suitable, except that a complete analysis (or worse, transmission) of all objects would be an overkill.
A nice alternative would be have a marker that is set when a change is done and is reset when the change is transmitted. If you transmit marked objects (and perhaps only marked properties of those), you would minimize workload of your synchronization thread, and reduce network overhead by pooling transmission of several changes affecting the same object.
Overall conclusion I arrived at: Having another call after I update the position, is not that bad. It is a line of code longer, but it is better for different motives:
It is explicit. You know exactly what's happening.
You don't slow down the code by making all kinds of hacks to get it working.
You don't use extra memory.
Methods I've tried:
Having maps for each type, as suggest by #Christophe. The major drawback of it was that it wasn't error prone. You could've had HP and Hp declared in the same map and it could've added another layer of problems and frustrations, such as declaring maps for each type and then preceding every variable with the mapname.
Using something SIMILAR to valve's engine: It created a separate class for each networking variable you wanted. Then, it used a template to wrap up the basic types you declared (int, float, bool) and also extended operators for that template. It used way too much memory and extra calls for basic functionality.
Using a data mapper that added pointers for each variable in the constructor, and then sent them with an offset. I left the project prematurely when I realised the code started to be confusing and hard to maintain.
Using a struct that is sent every time something changes, manually. This is easily done by using protobuf. Extending structs is also easy.
Every tick, generate a new struct with the data for the classes and send it. This keeps very important stuff always up to date, but eats a lot of bandwidth.
Use reflection with help from boost. It wasn't a great solution.
After all, I went with using a mix of 4, and 5. And now I am implementing it in my game. One huge advantage of protobuf is the capability of generating structs from a .proto file, while also offering serialisation for the struct for you. It is blazingly fast.
For those special named variables that appear in subclasses, I have another struct made. Alternatively, with help from protobuf I could have an array of properties that are as simple as: ENUM_KEY_BYTE VALUE. Where ENUM_KEY_BYTE is just a byte that references a enum to properties such as IS_FLYING, IS_UP, IS_POISONED, and VALUE is a string.
The most important thing I've learned from this is to have as much serialization as possible. It is better to use more CPU on both ends than to have more Input&Output.
If anyone has any questions, comment and I will do my best helping you out.
ioanb7

Best practice to set single/multiple members of a (property-) class

I have a class that contains some members that may be modified from external sources:
class CNode
{
protected:
// these members might be changed by users
std::string m_sName;
CState m_CurrentState;
CColor m_DiffuseColor;
};
The sample is simplified, it has more members in my code.
Now what would be the best practice to change
single
multiple (at once)
all members (at once)
of this class?
My code needs to handle all cases, though internally case 1. will be the usual case.
Most of the time it is applied to a single CNode but it might also be applied to an array of nodes.
I know two possible solutions that both don't really satisfy me:
set&get for every variable:
Pro:
Every variable is modifiable independently from other members.
Easy to set the same value for multiple CNodes.
Contra:
A lot of set&gets;
If a new variable is added, a new set&get needs to be added as well.
This would work best if one Variable is changed in many CNodes
Create a CProperties class that contains all modifiable variables:
Pro:
One set&get in the parent class - properties may be added/removed without needing to modify set&get.
This also reduces the amount of methods in my API that processes user input.
Contra:
setting individual variables requires getting the current CProperties, so the other values won't be modified.
This would work best if multiple/all variables are updated at once in a single CNode.
Like so:
class CProperties
{
// these members might be changed by users
std::string m_sName;
CState m_CurrentState;
CColor m_DiffuseColor;
}
class CNode
{
public:
const CProperties* GetProperties();
void SetProperties(CProperties*);
protected:
CProperties m_Properties;
}
This would be the most lazy version (by code creation effort) but also the most obnoxious version for me, since setting single variables requires getting the current properties first, modifying a single variable and then setting the complete properties class back to the node.
Especially in the modify-a-single-variable-in-multiple-CNodes-case this seems to be an awful solution.
Time of execution and (size) overhead is mostly irrelevant in my case. (Which would really be my only good argument against the lazy version)
Instead I'm looking for clean, understandable, usable code.
I could think of a third possible solution with a dynamic approach:
One set method has an object as parameter that may contain one or more values that need to be modified. The API then only has one set method that won't need any modification if the CProperties change. Instead a parsing method would be needed in the CNode class.
This parsing method would still need to be updated for every change in the CProperties, though I'm confident this should also be solvable with the compiler through templates.
My question is:
Are there any other possible solutions for my use case?
Which approach is the most sensible one?
You can add the logic of how to update and what to update into the class and only provide it with a source of information.
Look at how you build the properties object and transfer the logic into an update function that will reside in CNode.
If CNode needs external sources of information in order to perform the update then transfer them to the update function.
Preferably the number of arguments passed to the update function will be smaller than the number of fields in CNode.(Ideally zero or one)
CNode will only update the fields that have actually been modified.
No need for a multiple set functions, uniform way of updating class, no information getting lost between the cracks.

Switching between different types of pointers to objects

So far I have been using dynamic casting. But this comes with it's pros and cons. It seems that is a good thing NOT to use this too much. The examples on this topic, that I have found, are usually with classes that have little differences. But in my case, the "child" classes have very little similarities.
The code in this post is NOT from the project. It's only used for examples.
I am making a trading system for a game and there will be many more systems in the project. There are many different items that do many different things- equipment, modifications, resources. No matter how different they are, they all have a price and they can all be putted in an inventory, no matter what they are. But this is where are the similarities end, including the overridden methods.
Afterwards the different items are used in completely different ways. At first the different types of items were sorted in separate arrays of pointers from different types- one for the equipment, one for the modifications, e.t.c. To put something in an inventory I only use a single method- addToInventory(Item* item) . Since the item must be placed in the right array, I use dynamic casting- I convert Item* item to (for example) Equipment* equi, so I can add it to the Equipment array. I want to do it in the same method, because it's more intuitive and otherwise the different methods would have similar code.
addToInventory(Item* item)
{
if (item->type == 'e')
{
Equipment* newEquip = dynamic_cast<Equipment*>(item);
equipmentArr.add(newEquip);//thous arrays are dynamic- the reason I needed to make the conversion explained later
}
else if (item->type == 'm')
{
Modification* newMod = dynamic_cast<Modification*>(item);
modificationArr.add(newEquip);
}
//and so on...
}
Later I would want to add a modification to a piece of equipment- Weapon::addMod(Modification* mod) . And in this method I use other methods and variables that are found ONLY in the Weapon class.
addMod (Modification* mod)
{//all are found ONLY in class Weapon
mod[modCount] = mod; //an array of Modification* pointers
modCount++;
calcEfficiency();
}
But when I want to make the simple thing to print an inventory, I either have to copy-paste and edit some code for converting the pointers in the arrays, so I can pass them in the same printing method, or copy-paste and edit the same code for printing. There is a third option- to make the arrays to all arrays of pointers to Item objects. I tried the last option.
It got rid of the casting in addToInventory(Item* item), yay! But it caused the need to use casting EVERY time I need to call methods such as Weapon::addMod(Modification* mod) and in other places. Otherwise, I will need to put the casting within the method, but I want the method to explicitly take an Equipment* argument.
The project is still really early in development, so I don't know how much more I might need to use casting, so I can switch back and forth between different types of pointers when needed.
So, in a similar case, how should I switch between different types of pointers?
You may want to represent the traits (namely Equipment and Modification) of your (broad) Item implementations as pure virtual classes (i.e. interfaces). This way dynamic casting and dynamic cast checks for these interfaces is OK and will lower the noise to handle for actual implementations of Equipment and Modification.
Another way is to use the CRTP pattern and static_cast<Interface*> to have compile time checks for your interfaces.
Depends on your use case which way is more appropriate. As a rule of thumb:
Mostly static configuration => Do at compile time
More dynamic configuration (run time allocated instances) => Do at runtime

List design (Object oriented) suggestion needed

I'm trying to implement a generic class for lists for an embedded device using C++. Such a class will provide methods to update the list, sort the list, filter the list based on some user specified criteria, group the list based on some user specified criteria etc. But there are quite a few varieties of lists I want this generic class to support and each of these varieties can have different display aspects. Example: One variety of list can have strings and floating point numbers in each of its elements. Other variety could have a bitmap, string and special character in each of it's elements. etc.
I wrote down a class with the methods of interest (sort, group, etc). This class has an object of another class (say DisplayAspect) as its member. But the number of member variables and the type of each member variable of class DisplayAspect is unknown. What would be a better way to implement this?
Why not use the std::list, C++ provides that and it provides all the functionality you mentioned(It is templated class, So it supports all data types you can think of).
Also, there is no point reinventing the wheel as the code you write will almost will never be as efficient as std::list.
In case you still want to reinvent this wheel, You should write a template list class.
First, you should probably use std::list as your list, as others have stated. It seems to me that you are having problems more with what to put in the list, however, so I'm focusing on that part of the question.
Since you want to also store multiple bits of information in each element of the list, you will need to create multiple classes, one to store each combination. You don't describe why you are storing mutiple bits of information, but you'd want to use a logical name for each class. So if, for example, you were storing a name and a price (string and a double), you could give the class some name like Product.
You mention creating a class called DisplayAspect.
If this is because you want to have one piece of code print all of these lists, then you should use inheritance and polymorphism to accomplish this goal. One way to accomplish that is to make your DisplayAspect class an abstract class with the needed functions (printItem() for example) pure virtual and have each of the classes you created for the combinations of data be subclasses of this DisplayAspect class.
If, on the other hand, you created the DisplayAspect class so that you could reuse your list code, you should look into template classes. std::list is an example of a template class and it will hold any type you'd like to put into it and in that case, you could drop your DisplayAspect class.
Others (e.g., #Als) have already given the obvious, direct, answer to the question you asked. If you really want a linked list, they're undoubtedly correct: std::list is the obvious first choice.
I, however, am going to suggest that you probably don't want a linked list at all. A linked list is only rarely a useful data structure. Given what you've said you want (sorting, grouping), and especially your target (embedded system, so you probably don't have a lot of memory to waste) a linked list probably isn't a very good choice for what you're trying to do. At least right off, it sounds like something closer to an array probably makes a lot more sense.
If you end up (mistakenly) deciding that a linked list really is the right choice, there's a fair chance you only need a singly linked list though. For that, you might want to look at Boost Slist. While it's a little extra work to use (it's intrusive), this will generally have lower overhead, so it's at least not quite a poor of a choice as many generic linked lists.

Structure for hierarchal Component storage

I've been batting this problem around in my head for a few days now and haven't come to any satisfactory conclusions so I figured I would ask the SO crew for their opinion. For a game that I'm working on I'm using a Component Object Model as described here and here. It's actually going fairly well but my current storage solution is turning out to be limiting (I can only request components by their class name or an arbitrary "family" name). What I would like is the ability to request a given type and iterate through all components of that type or any type derived from it.
In considering this I've first implemented a simple RTTI scheme that stores the base class type through the derived type in that order. This means that the RTTI for, say, a sprite would be: component::renderable::sprite. This allows me to compare types easily to see if type A is derived from type B simply by comparing the all elements of B: i.e. component::renderable::sprite is derived from component::renderable but not component::timer. Simple, effective, and already implemented.
What I want now is a way to store the components in a way that represents that hierarchy. The first thing that comes to mind is a tree using the types as nodes, like so:
component
/ \
timer renderable
/ / \
shotTimer sprite particle
At each node I would store a list of all components of that type. That way requesting the "component::renderable" node will give me access to all renderable components regardless of derived type. The rub is that I want to be able to access those components with an iterator, so that I could do something like this:
for_each(renderable.begin(), renderable.end(), renderFunc);
and have that iterate over the entire tree from renderable down. I have this pretty much working using a really ugly map/vector/tree node structure and an custom forward iterator that tracks a node stack of where I've been. All the while implementing, though, I felt that there must be a better, clearer way... I just can't think of one :(
So the question is: Am I over-complicating this needlessly? Is there some obvious simplification I'm missing, or pre-existing structure I should be using? Or is this just inheritly a complex problem and I'm probably doing just fine already?
Thanks for any input you have!
You should think about how often you need to do the following:
traverse the tree
add/remove elements from the tree
how many objects do you need to keep track of
Which is more frequent will help determine the optimum solution
Perhaps instead of make a complex tree, just have a list of all types and add a pointer to the object for each type it is derived from. Something like this:
map<string,set<componenet *>> myTypeList
Then for an object that is of type component::renderable::sprite
myTypeList["component"].insert(&object);
myTypeList["renderable"].insert(&object);
myTypeList["sprite"].insert(&object);
By registering each obejct in multiple lists, it then becomes easy to do something to all object of a given type and subtypes
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(),renderFunc);
Note that std::set and my std::map construct may not be the optimum choice, depending on how you will use it.
Or perhaps a hybrid approach storing only the class heirarchy in the tree
map<string, set<string> > myTypeList;
map<string, set<component *> myObjectList;
myTypeList["component"].insert("component");
myTypeList["component"].insert("renderable");
myTypeList["component"].insert("sprite");
myTypeList["renderable"].insert("renderable");
myTypeList["renderable"].insert("sprite");
myTypeList["sprite"].insert("sprite");
// this isn't quite right, but you get the idea
struct doForList {
UnaryFunction f;
doForList(UnaryFunction f): func(f) {};
operator ()(string typename) {
for_each(myTypeList[typename].begin();myTypeList[typename].end(), func);
}
}
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(), doForList(myFunc))
The answer depends on the order you need them in. You pretty much have a choice of preorder, postorder, and inorder. Thus have obvious analogues in breadth first and depth first search, and in general you'll have trouble beating them.
Now, if you constraint the problem a litle, there are a number of old fashioned algorithms for storing trees of arbitrary data as arrays. We used them a lot in the FORTRAN days. One of them had the key trick being to store the children of A, say A2 and A3, at index(A)*2,index(A)*2+1. The problem is that if your tree is sparse you waste space, and the size of your tree is limited by the array size. But, if I remember this right, you get the elements in breadth-first order by simple DO loop.
Have a look at Knuth Volume 3, there is a TON of that stuff in there.
If you want to see code for an existing implementation, the Game Programming Gems 5 article referenced in the Cowboy Programming page comes with a somewhat stripped down version of the code we used for our component system (I did a fair chunk of the design and implementation of the system described in that article).
I'd need to go back and recheck the code, which I can't do right now, we didn't represent things in a hierarchy in the way you show. Although components lived in a class hierarchy in code, the runtime representation was a flat list. Components just declared a list of interfaces that they implemented. The user could query for interfaces or concrete types.
So, in your example, Sprite and Particle would declare that they implemented the RENDERABLE interface, and if we wanted to do something to all renderables, we'd just loop through the list of active components and check each one. Not terribly efficient on the face of it, but it was fine in practice. The main reason it wasn't an issue was that it actually turns out to not be a very common operation. Things like renderables, for example, added themselves to the render scene at creation, so the global scene manager maintained its own list of renderable objects and never needed to query the component system for them. Similarly with phyics and collision components and that sort of thing.