Monday, April 1, 2013

Simple Gravity for your 3D game

Beginners out there are often making a really simple game and don't always need a physics engine. If you want to try out some basic gravity for your game, then something like this might work for you.

Any object in your 3D world is going to need a 3D position (a point, often represented by a vector class). Applying gravity to your 3D objects is actually really simple, assuming you're not trying planetary physics around a sphere (or a gravity well of some kind). Each frame during an update cycle you just add gravity to the velocity of your objects. And later in the update cycle you move all of your objects based on their velocity. Here's some C++ pseudocode of how this might work:

#include <vector>

class Object
{
public:
    Object();

    Vector3 m_position;
    Vector3 m_velocity;
    Matrix3 m_rotation;
    float   m_elasticity;
};

class SceneManager
{
public:
    void update(float timeDelta);

private:
    std::vector<Object> m_objects;
}

void SceneManager::update(float timeDelta)
{
    // Be careful here, I'll explain why after the code snippet
    for ( unsigned int i = 0; i < m_objects.size(); ++i )
    {
        applyGravity(m_objects[i]);

        updatePosition(m_objects[i]);
    }
}

void applyGravity(float timeDelta, Object& obj)
{
    static Vector3 gravity(0.0f, -9.8f, 0.0f);

    // Factor time when adding gravity, because 9.8m/s is a speed, and speed requires time
    obj.m_velocity += (timeDelta * gravity);
}

void updatePosition(Object& obj)
{
    obj.m_position += obj.m_velocity;
}
Be careful when looping through your game's object list and making changes, if your change of position does something like cause a collision with another object, and you are handling that immediately, you could wind up making changes to your list of objects while you're in the middle of iterating through them. The above sample will work, but if your 'applyGravity' and 'updatePosition' methods don't end up getting inlined then you're going to be incurring two function calls for every object in your scene. If those methods don't get inlined then I would recommend passing your entire list of objects that you want updated to the function and let the function loop through them and make the updates. It would like something like this:
void SceneManager::update(float timeDelta)
{
    applyGravity(m_objects);
    updatePosition(m_objects);
}

void applyGravity(float timeDelta, std::vector<Object>& objs)
{
    // A hard-coded gravity, you might want to have this somewhere convenient
    // where it can be changed at run-time. Depends on what you're trying to do.
    static const Vector3 gravity(0.0f, -9.8f, 0.0f);

    const float gravityThisFrame = (timeDelta * gravity);

    for ( unsigned int i = 0; i < objs.size(); ++i )
    {
        objs[i].m_velocity += gravityThisFrame;
    }
}

void updatePosition(std::vector<Object>& objs)
{
    for ( unsigned int i = 0; i < objs.size(); ++i )
    {
        objs[i].m_position += objs[i].m_velocity;
    }
}
Once you have gravity your next concern will probably be some kind of collision detection with the ground. How you do that will be determined by your game, but once you've detected a collision with the ground, a simple way to handle the bounce is to flip the velocity and reduce it by some amount. The more you reduce the velocity the less bouncy your object is.
void handleGroundCollision(Object& obj)
{
    objs[i].m_velocity.y *= -objs[i].m_elasticity.y;
}
The above method assumes your gravity is in the direction of the -Y axis. If you have a gravity going in a different direction then you may need to do a bit more of a complex calculation to bounce your object. The following method will handle basic collisions with any stationary object. In this case you need to pass the normal of the surface the object is hitting, if that is flat ground and your 'up' axis is +Y then the surface normal is Vector3(0.0f, 1.0f, 0.0f). Make sure your surface normal is normalized/unitized before using it in this method.
void Vector3::reflect( const Vector3& normal, float elasticity )
{
    const float dotProductTimesTwo = Dot(normal) * 2.0f; 
    x -= dotProductTimesTwo * normal.x * elasticity;
    y -= dotProductTimesTwo * normal.y * elasticity;
    z -= dotProductTimesTwo * normal.z * elasticity;
}

// Or if you don't have your own Vector class, use this:
void reflect( Vector3& velocity, const Vector3& normal, float elasticity )
{
    const float dotProductTimesTwo = Dot(normal) * 2.0f;
    velocity -= ((dotProductTimesTwo * normal) * elasticity);
}

Setting your object's elasticity to 0.0f would mean that it would not bounce at all. A value of 1.0f would mean a perfect bounce, which would have no loss of energy on the bounce. Any value higher than 1.0f would cause the ball to move with a higher velocity than when it bounced. Usually you're going to want something between 0.0f and 1.0f, feel free to experiment with it a bit.

One more optimization consideration to make with this. If you have a lot of objects it can become more and more expensive to loop through them all each frame. If you separate your object list, or have another one for only the objects that can be moved or affected by gravity, then that will limit how many objects you're having to loop through each frame. Additionally if you have some more advanced detection methods you may know when an object is at rest due to it sitting on top of another object, if that is the case you may not need to apply gravity to it. Be careful with that optimization though, if gets tricky if you start mucking around with the direction of gravity.

Wednesday, March 27, 2013

Code structure: Cleanliness and efficiency

There are many ways to help make your code more readable, less bug-prone, and even more efficient. These are ignored by so many people whose code I've seen that I've decided to post about it. To many of you this stuff may be considered common sense, and that's a good thing.

Early out with conditionals when appropriate. This prevents your conditionals from nesting.


Bad:
void processMapNodes()
{
    if ( !map.hasBeenProcessed() )
    {
        map.process();

        // Other stuff here

        map.setProcessed(true);
    }
}
Good:
void processMapNodes()
{
    if ( map.hasBeenProcessed() )
    {
        return;
    }

    map.process();

    // Other stuff here

    map.setProcessed(true);
}

Early out with for loops. If you have to loop to find something, break out as soon as you've found it.


Bad:
void removeMapNodeByName(const std::string& name)
{
    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() == name )
        {
            // Possibly some stuff here

            map_nodes.erase( map_nodes.begin() + i );
        }
    }
}
Better:
void removeMapNodeByName(const std::string& name)
{
    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() == name )
        {
            // Possibly some stuff here

            map_nodes.erase( map_nodes.begin() + i );
    
            // We've found what we're looking for, so we break and stop looping
            break;
        }
    }
}
Best: (Use a conditional to continue as soon as possible)
void removeMapNodeByName(const std::string& name)
{
    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() != name )
        {
            continue;
        }

        // Possibly some stuff here

        map_nodes.erase( map_nodes.begin() + i );
        break;
    }
}

Some of these examples are just to give you an idea of how to break out of code as soon as possible, but sometimes you can get even more efficient. In the example above we're simply going through a vector of data and looking for a match and then removing it. If what you're doing is really that trivial then you can use the standard library remove_if algorithm to do that for you. There are good examples of that, here, and here.

Don't nest your conditionals unnecessarily


Bad: Here we have nested conditionals, it starts to get messy
void foo(Bar* pBar)
{
    if ( pBar )
    {
        if ( pBar->hasData() )
        {
            Data* pData = pBar->getData();
            
            for ( int i = 0; i < pData->size(); ++i )
            {
                if ( pData[i].needsProcessing() )
                {
                    pData[i].process();
                }
            }
        }
    }
}
Good: We unnest our if statements and leave the for loop as soon as possible.
void foo(Bar* pBar)
{
    if ( !pBar || !pBar->hasData() )
    {
        return;
    }
     
    Data* pData = pBar->getData();
            
    for ( int i = 0; i < pData->size(); ++i )
    {
        if ( !pData[i].needsProcessing() )
        {
            continue;
        }

        // Do a bunch of stuff here

        pData[i].process();
    }
}

Create data only once it's needed

Bad: We're creating 'node_pos' at a point before we might exit the function early. This is wasteful and unnecessary.
void moveToMapNode(const std::string& name)
{
    Vector3 node_pos;

    if ( map_nodes.empty() )
    {
        return;
    }

    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() != name )
        {
            continue;
        }

        node_pos = map_nodes[i].getPosition();
        break;
    }

    player.setPosition( node_pos );
}
Better: We create node_pos after any point were we could leave the function early, so we're never creating it when it might not be needed.
void moveToMapNode(const std::string& name)
{
    if ( map_nodes.empty() )
    {
        return;
    }

    Vector3 node_pos;

    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() != name )
        {
            continue;
        }

        node_pos = map_nodes[i].getPosition();
        break;
    }

    player.setPosition( node_pos );
}
Best: We don't need to create a named variable 'node_pos', and it doesn't need to be used in as large of a scope as it was, we can use the position we get directly within the for loop.
void moveToMapNode(const std::string& name)
{
    if ( map_nodes.empty() )
    {
        return;
    }

    for ( int i = 0; i < map_nodes.size(); ++i )
    {
        if ( map_nodes[i].getName() != name )
        {
            continue;
        }

        // This is still fairly clear, even though we have a function call within a function call.
        // I wouldn't recommend nesting function calls any deeper than this, or debugging them 
        // and their return values can get messy if you end up with any bugs.
        player.setPosition( map_nodes[i].getPosition() );
        break;
    }
}

Sort your conditionals such that the cheapest ones are evaluated first, or the one most likely to evaluate positively is evaluated first.

Bad: We're calling the more expensive function first. Both functions in the conditional must be true for us to continue, so we should be calling the cheap function first, and if it returns false there is no need to call the expensive function.
void someFcn()
{
    if ( isExpensiveFcnTrue() && isCheapFcnTrue() )
    {
        // Do stuff here
    }
}
Good: We're calling the least expensive function first.
void someFcn()
{
    if ( isCheapFcnTrue() && isExpensiveFcnTrue() )
    {
        // Do stuff here
    }
}
Bad: We're placing the cheaper methods first, however, if they're functions that are true most of the time then we're still likely to have to evaluate all of the functions, even the expensive one that is usually false.
void someFcn()
{
    if ( cheapFcnThatUsuallyReturnsTrue() 
      && someOtherCheapFcnThatsUsuallyTrue() 
      && moderatelyExpensiveButUsuallyFalse() )
    {
        // Do stuff here
    }
}
Good: We call the more expensive method first, because it usually returns false, allowing us to skip the calls to the less expensive functions that usually return true. Basically your goal is to pay the lowest overall cost in your conditional statement, sometimes that will be calling cheaper methods first to avoid having to call expensive ones, if all of the functions stand similar chances of returning positive values, and sometimes you'll want to call more expensive ones first if it means you can save yourself numerous calls to other methods afterward. You'll need to make a judgement call based on the expense of the methods and what allows you to bail out as early as possible.
void someFcn()
{
    if ( moderatelyExpensiveButUsuallyFalse() 
      && cheapFcnThatUsuallyReturnsTrue() 
      && someOtherCheapFcnThatsUsuallyTrue() )
    {
        // Do stuff here
    }
}
If you're using || in your conditional, then you want to evaluate to true as soon as you can in your conditional, if you have && then you want to evaluate to false as soon as possible. Whatever the logic you're using, you want to do the least amount of work as possible to terminate the conditional check early and/or cheaply. This isn't only the most efficient, but it can make it easier to debug as you're not having to step through as much code when you exit early.

Cache results from an expensive algorithm or method that you might be calling more than once.

The compiler cannot optimize out multiple calls to the same function, unless those functions are purely constant expressions, so it's up to you to do it.

Bad: Here we're calling numCompletedNodes() more than once.
void displayCompletedNodeCount()
{
    // Let's pretend that 'numCompletedNodes()' has a big O of N*log(n) each time it's called.

    // If the player has completed any nodes in the map
    if ( numCompletedNodes() > 0 )
    {
        // We update the UI to display the number of completed nodes
        ui_interface->updateNodeCount( numCompletedNodes() );
    }
}

Better: We cache the number of nodes so we don't have to call the function each time we use it.
void displayCompletedNodeCount()
{
    // Let's pretend that 'numCompletedNodes()' has a big O of N*log(n) each time it's called.

    const unsigned int num_completed_nodes = numCompletedNodes();

    // If the player has completed any nodes in the map
    if ( num_completed_nodes > 0 )
    {
        // We update the UI to display the number of completed nodes
        ui_interface->updateNodeCount( num_completed_nodes );
    }
}

Best: If you really want to be more efficient, in this example it would probably be best to make sure that the numCompletedNodes() function is cheaper to call. Just from the example we can probably assume that it has to go through the map of nodes and calculate for each one if the player has completed it. That is probably information that could be stored on each node, which would bring the big O down to O(n). And you could go further and have a variable that keeps track of the completed node count as it changes, and then it would bring the cost down to O(1) (constant).

Tuesday, March 26, 2013

Djikstra's Algorithm: Finding the Shortest Path

For those that are unfamiliar, Djikstra's Algorithm is used to find the guaranteed shortest path between two points in a graph (as opposed to A* which will take an educated guess, but is more efficient). For the second time in as many years I've found myself needing a shortest path algorithm in a game project. The last one that I wrote was before my blog existed and I never published it, and since then I've lost access to the code base it was published in. This time I'm a bit more pressed for time and didn't want to write my own from scratch so I decided to grab one from online and fix it up a bit.


It has several issues with it that I needed to solve:
  • The algorithm itself and several methods related to it were not encapsulated, which is messy. At the least they should be in their own file.
  • Any nodes and edges that were created had to be deleted by the user otherwise the program would leak memory.
  • The code assumes all edges were bi-directional, I need to handle the possibility of a directional edge.
  • Querying the node graph would remove the nodes from the graph, making it so that if you wanted to query again you had to recreate the graph.
  • The code didn't handle the case in which there wasn't a possible path between two nodes
  • There were several inefficiencies.
The changes I made were:
  • Encapsulated the algorithm, and the containers for the nodes and edges into a Graph class.
  • The Graph class destructor made sure to clean up the nodes and edges to prevent memory leaks.
  • Made edges directional while still allowing for bi-directional connections.
  • Allowing the Graph class to not remove nodes while calculating the shortest path, so the user can query the graph as often as they'd like without recreating it.
  • Made a user-friendly method to allow the user to get a path between any two nodes.
  • Corrected inefficiencies.
For the code containing all of my changes, (click here). I go over the changes in more detail at the end of this post.

In the example code, here is the graph:

Notice that the edges between A and B, and E and F, are uni-directional, you cannot move from B to A, or F to E. In a shortest path algorithm, each node connection (edge) has a weight rather than a distance, this is because we're really not looking for the path of least distance, but the path that can be traversed the fastest, so we may want to factor in things along the path that may slow down the traveller. For example, the connection between B and E, and B and D are of different distances, but both have a weight of 4. Maybe the path between B and E is a smooth concrete path, but from B to D is a swampy path that is hard to traverse.

Given the weights that we've given to each edge, denoted by the numbers near each edge, the shortest path from A to F is: A->B->E->F. Because some edges are uni-directional, the shortest path from F to A is: F->D->B->E->C->A (in fact, that's the only path from F to A). We can also start on nodes besides A and F. For example, the shortest path from C to D is: C->E->F->D.

Below here you'll find the code, organized into main.cpp and three classes. Graph is the class that contains the algorithm and stores Nodes and Edges. And a class for Node, and a class for Edge.

First let's look at main.cpp so we can see how the graph is created and utilized:

#include <iostream>

#include "graph.h"
#include "node.h"

// NOTE: Credit for the original code for this implementation of 
// Djikstra's Algorithm goes to:
// http://www.reviewmylife.co.uk/blog/2008/07/15/dijkstras-algorithm-code-in-c/
// I've modified it to suit my needs.

void outputPath(std::vector<node> path)
{
    for ( long i = (path.size() - 1); i >= 0; --i )
    {
        std::cout << path[i]->getID() << " ";
    }
    
    std::cout << std::endl;
}

int main(int argc, const char * argv[])
{
    Graph graph;
    
    // Create and name our nodes
    Node* a = graph.createNode('a');
    Node* b = graph.createNode('b');
    Node* c = graph.createNode('c');
    Node* d = graph.createNode('d');
    Node* e = graph.createNode('e');
    Node* f = graph.createNode('f');
    
    // Create some edges
    graph.createEdge(a, b, 5);
    graph.createEdge(a, c, 4);
    graph.createEdge(b, d, 4);
    graph.createEdge(b, e, 4);
    graph.createEdge(c, e, 6);
    graph.createEdge(d, f, 3);
    graph.createEdge(e, f, 2);
    
    // Create some edges so we can get from 'f' to 'a'
    graph.createEdge(f, d, 3);
    graph.createEdge(d, b, 4);
    graph.createEdge(e, c, 6);
    graph.createEdge(c, a, 4);
 
    std::vector<node> path;

    // Go from 'c' to 'f'
    graph.getPathFromStartNodeToFinishNode(c, f, path);
    outputPath(path);
    
    // Go from 'a' to 'f'
    graph.getPathFromStartNodeToFinishNode(a, f, path);
    outputPath(path);
    
    // Go from 'f' to 'a'
    graph.getPathFromStartNodeToFinishNode(f, a, path);
    outputPath(path);
    
    return 0;
}

And below you'll find the three class .h/.cpp files.

graph.h
#pragma once

#include <vector>

class Node;
class Edge;

class Graph
{
public:
    Graph() {}
    ~Graph();
    
    Node* createNode(char id);
    Edge* createEdge(Node* node1, Node* node2, const int weight);
    void removeEdge(Edge* edge);
    
    void getPathFromStartNodeToFinishNode(Node* node1, Node* node2, std::vector<node>& path);

private:
    void processGraph();
    Node* extractSmallest(std::vector<node>& nodes);
    
private:
    std::vector<node> m_nodes;
    std::vector<edge> m_edges;
};

graph.cpp
#include "graph.h"
#include "node.h"
#include "edge.h"

#include <iostream>

Graph::~Graph()
{
    for ( int i = 0; i < m_nodes.size(); ++i )
    {
        delete m_nodes[i];
    }
    
    for ( int i = 0; i < m_edges.size(); ++i )
    {
        delete m_edges[i];
    }
}

Node* Graph::createNode(char id)
{
    Node* new_node = new Node(id);
    
    m_nodes.push_back(new_node);
    
    return new_node;
}

Edge* Graph::createEdge(Node* node1, Node* node2, const int weight)
{
    // Yes, we intentionally reverse the node order here
    Edge* new_edge = new Edge(node2, node1, weight);
    
    m_edges.push_back(new_edge);
    
    return new_edge;
}

void Graph::removeEdge(Edge* edge)
{
    std::vector<edge>::iterator it = m_edges.begin();
    for ( ; it < m_edges.end(); ++it)
    {
        if (*it == edge)
        {
     m_edges.erase(it);
     return;
        }
    }
}

void Graph::getPathFromStartNodeToFinishNode(Node* start, Node* finish, std::vector<node>& path)
{
    path.clear();
    
    // Clear any existing node information
    for ( int i = 0; i < m_nodes.size(); ++i )
    {
        m_nodes[i]->setDistanceFromStart(INT_MAX);
        m_nodes[i]->setPreviousNode(NULL);
    }
    
    start->setDistanceFromStart(0);
    
    processGraph();
    
    Node* previous = finish;

    while (previous)
    {
        path.push_back(previous);
        
        previous = previous->getPreviousNode();
    }
    
    if ( path.size() == 1 )
    {
        path.clear();
    }
}

void Graph::processGraph()
{
    // Create a copy of the nodes.
    std::vector<node> nodes = m_nodes;
    
    while (nodes.size() > 0)
    {
 Node* smallest = extractSmallest(nodes);
        
        std::vector<node> out_nodes;
        smallest->adjacentRemainingNodes(nodes, m_edges, out_nodes);
        
 const size_t size = out_nodes.size();
 for (int i = 0; i < size; ++i)
 {
     Node* adjacent = out_nodes[i];
            
     const int distance_to_node = adjacent->distanceToNode(m_edges, smallest);
            if ( distance_to_node == -1 )
            {
                continue;
            }
            
            const int total_distance = distance_to_node + smallest->getDistanceFromStart();   
     if ( total_distance < adjacent->getDistanceFromStart() )
     {
         adjacent->setDistanceFromStart(total_distance);
         adjacent->setPreviousNode(smallest);
     }
 }
    }
}

Node* Graph::extractSmallest(std::vector&ltnode&gt& nodes)
{
    if ( nodes.empty() )
    {
        return NULL;
    }
    
    int smallest_position = 0;
    
    Node* smallest = nodes[0];
    for ( int i = 1; i < nodes.size(); ++i )
    {
        Node* current = nodes[i];
        
        if ( current->getDistanceFromStart() < smallest->getDistanceFromStart() )
        {
            smallest = current;
            smallest_position = i;
        }
    }
    
    nodes.erase(nodes.begin() + smallest_position);
    
    return smallest;
}

node.h
#pragma once

#include <vector>

class Edge;

class Node
{
public:
    Node(char id) :
        id(id)
        , m_previous(NULL)
        , m_distance_from_start(INT_MAX)
    {
    }
    
    char getID() const                          { return id; }
    
    void setPreviousNode(Node* node)            { m_previous = node; }
    Node* getPreviousNode() const               { return m_previous; }
    
    void setDistanceFromStart(int distance)     { m_distance_from_start = distance; }
    int getDistanceFromStart() const            { return m_distance_from_start; }
    
    Node* extractSmallest(std::vector<node>& nodes);
    
    void adjacentRemainingNodes(const std::vector<node>& nodes, const std::vector<edge>& edges,
                                std::vector<node>& out_nodes) const;
    
    int distanceToNode(const std::vector<edge>& edges, const Node* other_node) const;
    
    bool contains(const std::vector<node>& nodes, const Node* node) const;
    
private:
    char    id;
    Node*   m_previous;
    int     m_distance_from_start;
};



node.cpp
#include "node.h"
#include "edge.h"

void Node::adjacentRemainingNodes(const std::vector<node>& nodes, const std::vector<edge>& edges,
                                  std::vector<node>& out_nodes) const
{
    const size_t size = edges.size();
    
    for(int i = 0; i < size; ++i)
    {
        const Edge* edge = edges[i];
        Node* adjacent = NULL;
        if (edge->first() == this)
        {
            adjacent = edge->second();
        }
        else if (edge->second() == this)
        {
            adjacent = edge->first();
        }
        
        if (adjacent && contains(nodes, adjacent))
        {
            out_nodes.push_back(adjacent);
        }
    }
}

int Node::distanceToNode(const std::vector<edge>& edges, const Node* other_node) const
{
    const size_t size = edges.size();
    for(int i = 0; i < size; ++i)
    {
        const Edge* edge = edges[i];
        if ( edge->connects(this, other_node) )
        {
            return edge->getDistance();
        }
    }

    // Happens if two nodes do not connect or the connection is directed in the opposite direction
    return -1;
}

bool Node::contains(const std::vector<node>& nodes, const Node* node) const
{
    for(int i = 0; i < nodes.size(); ++i)
    {
        if (node == nodes[i])
        {
            return true;
        }
    }
    
    return false;
}

edge.h
#pragma once

#include <vector>

class Node;

class Edge
{
public:
    Edge(Node* node1, Node* node2, int distance) :
        m_node1(node1)
      , m_node2(node2)
      , m_distance(distance)
    {
        // Assert that node1 and node2 aren't null and that distance is a positive value
    }
    
    Node* first() const           { return m_node1; }
    Node* second() const          { return m_node2; }
    int getDistance() const       { return m_distance; }
    
    bool connects(const Node* node1, const Node* node2) const;
    
private:
    Node* m_node1;
    Node* m_node2;
    int m_distance;
};

edge.cpp
#include "edge.h"
#include "node.h"

bool Edge::connects(const Node* node1, const Node* node2) const
{
    return ( (node1 == m_node1) && (node2 == m_node2) );
}

The Changes

The Graph class destructor made sure to clean up the nodes and edges to prevent memory leaks.
The original required you to keep track of all of your own pointers to nodes and edges and delete them.

Graph::~Graph()
{
    for ( int i = 0; i < m_nodes.size(); ++i )
    {
        delete m_nodes[i];
    }
    
    for ( int i = 0; i < m_edges.size(); ++i )
    {
        delete m_edges[i];
    }
}

Made edges directional while still allowing for bi-directional connections.
The original 'connects' method checked if the edge went in either direction, which made it so you could not have uni-directional edges.

#include "edge.h"
#include "node.h"

bool Edge::connects(const Node* node1, const Node* node2) const
{
    return ( (node1 == m_node1) && (node2 == m_node2) );
}

And here we handle the case where we don't get a valid distance from a distance check, which can happen if there is no possible path.
void Graph::processGraph()
{
    // Create a copy of the nodes.
    std::vector<Node*> nodes = m_nodes;
    
    while (nodes.size() > 0)
    {
        Node* smallest = extractSmallest(nodes);
        
        std::vector out_nodes;
        smallest->adjacentRemainingNodes(nodes, m_edges, out_nodes);
        
        const size_t size = out_nodes.size();
        for (int i = 0; i < size; ++i)
        {
     Node* adjacent = out_nodes[i];
            
            // We get the distance, if it's -1 then we know there is no possible path between the two nodes
     const int distance_to_node = adjacent->distanceToNode(m_edges, smallest);
            if ( distance_to_node == -1 )
            {
                continue;
            }
            
            const int total_distance = distance_to_node + smallest->getDistanceFromStart();   
     if ( total_distance < adjacent->getDistanceFromStart() )
     {
         adjacent->setDistanceFromStart(total_distance);
         adjacent->setPreviousNode(smallest);
     }
        }
    }
}

Allowing the Graph class to not remove nodes while calculating the shortest path, so the user can query the graph as often as they'd like without recreating it.
The key change from the original is that we make a copy of the list of nodes. The copies list is then whittled away by this function and then goes out of scope, the original would alter the 'm_nodes' list, thus requiring the user to recreate it after each time they queried for a new path.

void Graph::processGraph()
{
    // Create a copy of the nodes.
    std::vector<node> nodes = m_nodes;
    
    // ... Rest of function ...
}

Made a user-friendly method to allow the user to get a path between any two nodes.
The original required you to recreate the entire graph, and then manually set the distance on the start node to 0, and then run the algorithm. I don't have the graph nodes deleted after they process so here I clear out changes the nodes might be storing, then set the distance on the start node, then iterate through the nodes and save out the path. If the path only ends up with the last node in it then we know that there is no path to the start node.

void Graph::getPathFromStartNodeToFinishNode(Node* start, Node* finish, std::vector<node>& path)
{
    path.clear();
    
    // Clear any existing node information
    for ( int i = 0; i < m_nodes.size(); ++i )
    {
        m_nodes[i]->setDistanceFromStart(INT_MAX);
        m_nodes[i]->setPreviousNode(NULL);
    }
    
    start->setDistanceFromStart(0);
    
    processGraph();
    
    Node* previous = finish;

    while (previous)
    {
        path.push_back(previous);
        
        previous = previous->getPreviousNode();
    }
    
    if ( path.size() == 1 )
    {
        path.clear();
    }
}

Corrected inefficiencies
There were several places in the original code sample that included the use of std::vector's 'at' method. This method is around 5-10x slower than using the [] operator. 'at' performs a range check, which is unnecessary if your code is setup to prevent indices from going out of range. Additionally there were places where entire containers were being created on the heap (using 'new'), and then deleted within the same scope. These have been changed to use the stack instead, which is generally much more efficient.

As an example, here was the original method:
void Dijkstras()
{
    while (nodes.size() > 0)
    {
        Node* smallest = ExtractSmallest(nodes);
        vector<node>* adjacentNodes = 
            AdjacentRemainingNodes(smallest);

        const int size = adjacentNodes->size();
        for (int i=0; i<size; ++i)
        {
            Node* adjacent = adjacentNodes->at(i);
            int distance = Distance(smallest, adjacent) + smallest->distanceFromStart;
   
            if (distance < adjacent->distanceFromStart)
            {
                adjacent->distanceFromStart = distance;
                adjacent->previous = smallest;
            }    
        }
        delete adjacentNodes;
    }
}

And here you can see that we're creating a vector on the stack and passing it by reference to the 'adjacentRemainingNodes' method. Because it's not being created on the heap we also don't have to worry about deleting a pointer that was created by another method:

void Graph::processGraph()
{
    // Create a copy of the nodes.
    std::vector<Node*> nodes = m_nodes;
    
    while (nodes.size() > 0)
    {
        Node* smallest = extractSmallest(nodes);
        
        std::vector<node> out_nodes;
        smallest->adjacentRemainingNodes(nodes, m_edges, out_nodes);
        
        const size_t size = out_nodes.size();
        for (int i = 0; i < size; ++i)
        {
            Node* adjacent = out_nodes[i];
            
            const int distance_to_node = adjacent->distanceToNode(m_edges, smallest);
            if ( distance_to_node == -1 )
            {
                continue;
            }
            
            const int total_distance = distance_to_node + smallest->getDistanceFromStart();   
            if ( total_distance < adjacent->getDistanceFromStart() )
            {
                adjacent->setDistanceFromStart(total_distance);
                adjacent->setPreviousNode(smallest);
            }
        }
    }
}