Hey,
I could use some of your input on a problem I'm having (I'm using Java).
I'm writing a Node class which keeps track of the transformation of objects in my game world. This class contains position, rotation and scale fields for getting and setting the objects transformation and a transformation matrix for quick and easy calculations.
The problem lies in the fact that this matrix must be updated to match the current transformation every frame, but only when necessary. If the transformation of the node has not changed I would like not to recalculate the transformation matrix. As scene's in my game consist of a mixure of static and dynamic objects I feel such a optimisation can be worthwhile.
Well... in C++ this would easily be solved by a construction like:
class Node
{
private:
Vector position;
bool isDirty;
public:
void setPosition(const Vector& p)
{
position = p;
isDirty = true;
}
void move(const Vector& p)
{
position += p;
isDirty = true;
}
const Vector& getPosition() const
{
return position;
}
void update()
{
if (isDirty)
recalculate();
}
}
However in Java you can't have const references thus making it possible to do: node.getPosition().set(0, 0). This makes the approach using a isDirty flag quite inpractical. Now I'm looking into other solutions:
- Still use the isDirty flag and let the getPosition() method set the isDirty flag to true aswell. This would work and is quite easy but would also lead to some unnecessary recalculation of the transformation matrix.
- Use the implementation as above and make it a rule not to modify the value returned by getPosition. This could also work but is not at all safe and will lead to untraceable bugs if you forget the rule.
- Store the previous transformation state of the node and do a comparison with the current one to see if recalculation is needed. I'm not really a fan of this solution as it makes the Node class quite a lot bigger and introduces a lot of 'epsilon comparisons' to the update method.
- Store a hashcode of the previous transformation state and compare this to the hashcode of the current transformation. I'm not sure about this one either. It introduces extra calculation in cases where the transformation matrix needs to be updated and there is a risk of a 'hashcode collision' which would lead to completely untraceable bugs (I have no idea what the chance on this is though)
- Just recalculate the transformation matrix every frame.
I was hoping you guys might have an other solution or have some opinions about the solutions I came up with.
Thanks in advance.