← C++

C++ · 08 / 24

A* routing and deterministic transport simulation

Understand grid-based path search and run the same simulation without its graphical interface.

  • Large
  • Advanced
  • 120 min

Prerequisites: Strings, vectors and standard algorithms, Headers, CMake and first unit tests

In this tutorial
  1. Build the complete core example
  2. Read the start, target and path
  3. Understand search ordering
  4. Consider time-based conflicts
  5. Run without a window
  6. Inspect the verification
  7. Verify the promises
  8. Exercise and solution
  9. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. Real core simulation through its outcome. The solution checks a longer detour, increased tick count and an unreachable destination.

For pathfinding, a grid becomes a graph. Each traversable cell is a node and each permitted move between neighbors is an edge. FactoryForge allows four movement directions without diagonal shortcuts. Every move costs one step.

A* combines the cost already incurred with an estimate of remaining distance. Manhattan distance, the sum of horizontal and vertical differences, is appropriate for this grid. Static routing answers whether two locations are connected. Multiple vehicles additionally need time-based rules because two geometrically valid paths may use the same place simultaneously.

Package contents and individual files

01Build the complete core example

Extract the learning package. The required FactoryForge sources are included under vendor from the linked pinned revision. Run cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug and cmake --build build. This standalone check does not require an additional full project download.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(SimulationLesson LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
get_filename_component(FACTORYFORGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/vendor/factory-forge" ABSOLUTE CACHE)
find_package(Threads REQUIRED)
add_executable(lesson main.cpp
  "${FACTORYFORGE_SOURCE_DIR}/src/core/project.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/pathfinder.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/puzzles.cpp"
  "${FACTORYFORGE_SOURCE_DIR}/src/core/simulation.cpp")
target_include_directories(lesson PRIVATE "${FACTORYFORGE_SOURCE_DIR}/include")
target_link_libraries(lesson PRIVATE Threads::Threads)

02Read the start, target and path

makePuzzle(0, true) creates the first puzzle’s reference solution. findPath starts at cell 1,3 and ends at 14,3. The returned vector includes both endpoints. Thirteen moves therefore produce fourteen path cells. Distinguish cell count from move count before comparing path length with elapsed steps.

main.cpp · cppOpen file
#include "factory/core/pathfinder.h"
#include "factory/core/puzzles.h"
#include "factory/core/simulation.h"
#include <iostream>
int main() {
  const auto project = factory::makePuzzle(0, true);
  const auto path = factory::findPath(project, {1, 3}, {14, 3});
  factory::Simulation simulation(project);
  while (simulation.snapshot().outcome == factory::Outcome::Running)
    simulation.step();
  std::cout << "path_cells=" << path.size() << '\n';
  std::cout << "delivered=" << simulation.snapshot().delivered << '\n';
  std::cout << "outcome="
            << (simulation.snapshot().outcome == factory::Outcome::Won ? "won"
                                                                       : "lost")
            << '\n';
}

Run / check

cmake -S . -B build -G Ninja -DFACTORYFORGE_SOURCE_DIR=/path/to/factory-forge
cmake --build build
./build/lesson

03Understand search ordering

pathfinder.cpp orders open candidates by path cost plus the Manhattan estimate. Reached states and predecessors allow reconstruction of the selected route. Stable tie breaking keeps choices reproducible. A blocked or disconnected destination produces no static path rather than a route through obstacles.

04Consider time-based conflicts

The fleet planner reserves cells and movement edges for twelve future ticks. Reverse-edge checks prevent vehicles passing through each other on the same connection. Unplanned vehicles conservatively hold their current cells and waiting vehicles gain priority. This bounded procedure is not a globally optimal fleet planner and narrow layouts can still block.

05Run without a window

The loop calls step while the outcome is Running. A logical tick represents 100 milliseconds. The console loop does not sleep for real time, so it computes the scenario faster. Delivery rules and the deadline remain identical. Execute the example and verify all three output lines.

Expected result

path_cells=14 delivered=3 outcome=won

06Inspect the verification

Real core simulation through its outcome. The solution checks a longer detour, increased tick count and an unreachable destination.Run python3 run_checks.py from the extracted package. Compare the test expectations with the exercise before opening the solution.

Expected result

The example and automated solution pass. The stated manual checks remain separate.

07Verify the promises

Core tests execute all five reference solutions and inspect each tick for distinct vehicle cells and the absence of reverse-edge collisions. Repeated runs must yield the same deliveries and tick counts. Faster or slower rendering does not alter the business sequence. The deadline counts logical steps rather than rendered frames.

Your exercise

Block the direct connection with a wall and build a detour. Compare path cells and delivery time. Then disconnect the destination completely and inspect static routing.

Show the solution and explanation

A connected detour produces a longer path vector and takes more steps. An isolated target produces an empty path. Keep valid start and target stations for a simulation run. The graphical editor reports missing connections during preflight. The core can retain unreachable orders as diagnostics until the deadline.

solution/main.cpp · cppOpen file
#include "factory/core/pathfinder.h"
#include "factory/core/puzzles.h"
#include "factory/core/simulation.h"
#include <cassert>
#include <iostream>
int main() {
  const auto project = factory::makePuzzle(0, true);
  const auto path = factory::findPath(project, {1, 3}, {14, 3});
  auto detour = project;
  detour.setTile({7, 3}, factory::Tile::Wall);
  for (int x = 6; x <= 8; ++x)
    detour.setTile({x, 2}, factory::Tile::Road);
  const auto longer = factory::findPath(detour, {1, 3}, {14, 3});
  assert(longer.size() > path.size());
  factory::Simulation slower(detour);
  while (slower.snapshot().outcome == factory::Outcome::Running)
    slower.step();
  assert(slower.snapshot().outcome == factory::Outcome::Won);
  for (const auto neighbor : detour.neighbors({14, 3}))
    detour.setTile(neighbor, factory::Tile::Wall);
  assert(factory::findPath(detour, {1, 3}, {14, 3}).empty());
  factory::Simulation simulation(project);
  while (simulation.snapshot().outcome == factory::Outcome::Running)
    simulation.step();
  assert(slower.snapshot().tick > simulation.snapshot().tick);
  std::cout << "path_cells=" << path.size() << '\n';
  std::cout << "delivered=" << simulation.snapshot().delivered << '\n';
  std::cout << "outcome="
            << (simulation.snapshot().outcome == factory::Outcome::Won ? "won"
                                                                       : "lost")
            << '\n';
}

Project context and sources

The first six examples are standalone teaching programs. Lessons 7 through 9 use the complete FactoryForge source snapshot. Code, exercises and verified simplifications are explained separately. The project page provides a source ZIP while the GitHub repository is not yet published.