- Joined
- Aug 6, 2011
- Messages
- 405
- Reaction score
- 3
- Points
- 18
Ok, after a (longish) break, I'm looking back over the code.
On the interface design end, I need to finish off "snapping" for vessel stacks. On that end, I noticed this horrendous function I wrote. I need some help refactoring it, if possible.
I'm no expert on algorithimic complexiety, but there are four for loops in there, which (might) mean that it runs in n^4 time. This function is called every time a stack is moved, and although it hasn't been a problem so far in my testing, it would surely crash if Dantassii got ahold if it :facepalm:
Here's what each level does, in order:
On the interface design end, I need to finish off "snapping" for vessel stacks. On that end, I noticed this horrendous function I wrote. I need some help refactoring it, if possible.
Code:
void VesselStack::checkForSnapping(std::vector<VesselSceneNode*>& vessels, bool dock)
{
//loop over each node
for (unsigned int nodeNum = 0; nodeNum < nodes.size(); nodeNum++)
{
//loop over empty docking ports on this node
for (unsigned int i = 0; i < nodes[nodeNum]->dockingPorts.size(); i++)
{
if (nodes[nodeNum]->dockingPorts[i].docked == false)
{
//now, loop over the OTHER vessels (not equal to this node)
//and see if it is close to another port's empty docking ports
for (unsigned int j = 0; j < vessels.size(); j++)
{
//make sure this vessel isn't in our stack
if (std::find(nodes.begin(), nodes.end(), vessels[j]) == nodes.end())
{
//check it's docking ports
for (unsigned int k = 0; k < vessels[j]->dockingPorts.size(); k++)
{
//check if it is not docked, and they are within a certain distance
if (!vessels[j]->dockingPorts[k].docked &&
((nodes[nodeNum]->getAbsolutePosition() + nodes[nodeNum]->returnRotatedVector(nodes[nodeNum]->dockingPorts[i].position)) -
(vessels[j]->getAbsolutePosition() + vessels[j]->returnRotatedVector(vessels[j]->dockingPorts[k].position))
).getLengthSQ() < 16)
{
//snap it if dock=false, dock if dock=true
if (!dock)
nodes[nodeNum]->snap(nodes[nodeNum]->dockingPorts[i], vessels[j]->dockingPorts[k]);
else
nodes[nodeNum]->dock(nodes[nodeNum]->dockingPorts[i], vessels[j]->dockingPorts[k]);
}
}
}
}
}
}
}
}
I'm no expert on algorithimic complexiety, but there are four for loops in there, which (might) mean that it runs in n^4 time. This function is called every time a stack is moved, and although it hasn't been a problem so far in my testing, it would surely crash if Dantassii got ahold if it :facepalm:
Here's what each level does, in order:
- For each individual vessel in the current VesselStack
- For each docking port on that vessel
- Check if the current docking port is free
- If so, for each vessel currently "in use" (in the scene)
- Check if each other vessel is not in our VesselStack (this prevents infinite docking loops)
- For each docking port in each vessel, not in our stack, see if it is empty, and within the "snapping" radius.
- Choose to dock or snap
