Skip to content

sahmedhusain/flowgrid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FlowGrid

FlowGrid is a real-time Rust + SDL2 simulation of a four-way autonomous intersection. Instead of traffic lights, vehicles are coordinated by a reservation scheduler that assigns safe entry times into conflict zones so multiple directions can flow with minimal stopping.

Table of Contents

Overview

The simulation models a dense four-approach junction with 12 lane-route combinations (right, straight, left from each approach).

Core objective:

  • Maximize safe throughput without traffic lights.
  • Prevent collisions through conflict-zone reservations and same-lane headway control.
  • Track performance metrics (speed, completion time, waiting, close calls).

Key Features

  • Deterministic reservation-based scheduler over a conflict grid.
  • Fairness-aware priority model (wait time, delay, and queue depth).
  • Physics-based movement with acceleration/deceleration constraints.
  • Per-lane spacing enforcement to keep safe following distance.
  • Collision detection using oriented bounding boxes (OBB + SAT projection test).
  • Close-call tracking for near-miss analysis.
  • Interactive SDL2 visualization with:
    • Background texture support.
    • Procedural road rendering fallback.
    • Car texture sets by direction with generated fallback car sprites.
  • Post-run report window and crash-detected window.

How It Works

1) Route and Conflict Modeling

  • The map defines 12 fixed routes (4 approaches x 3 route kinds).
  • The intersection interior is sampled into a 6x6 conflict grid.
  • Each route stores conflict windows (distance intervals per zone) where occupancy matters.

2) Scheduling

  • Every frame, vehicles are ordered per lane by progress.
  • The scheduler computes earliest feasible entry times while enforcing:
    • Same-lane headway.
    • Cross-route zone non-overlap in time windows.
  • Priority is adjusted using aging/fairness weights so blocked queues are not starved.

3) Admission and Control

  • Near-entry candidates are admitted with additional safety checks.
  • Entry can be held, staged, or fast-released when safe.
  • Target speeds are adjusted for:
    • Lane leaders and gap safety.
    • Intersection conflict proximity.
    • Yield constraints and occupancy checks.

4) Motion, Safety, and Stats

  • Physics advances each vehicle with bounded acceleration/deceleration.
  • Waiting time accumulates when a vehicle is commanded to hold or blocked by limits.
  • Collisions are detected in real-time; on collision, simulation stops immediately.
  • Stats are continuously recorded and shown at exit.

Controls

  • Up Arrow: spawn from South approach.
  • Down Arrow: spawn from North approach.
  • Right Arrow: spawn from West approach.
  • Left Arrow: spawn from East approach.
  • R: toggle continuous random spawning.
  • Esc: stop simulation and open stats.

Notes:

  • Manual spawns are cooldown-limited per approach.
  • Random spawning is interval-based and capacity-aware.

Requirements

Rust

  • Rust toolchain with Cargo (stable, edition 2024 compatible).

Native Libraries

  • SDL2
  • SDL2_image

Install by platform:

Ubuntu/Debian:

sudo apt update
sudo apt install -y libsdl2-dev libsdl2-image-dev

Fedora:

sudo dnf install SDL2-devel SDL2_image-devel

Arch Linux:

sudo pacman -S sdl2 sdl2_image

macOS (Homebrew):

brew install sdl2 sdl2_image

On macOS, build.rs also checks common Homebrew library paths (/opt/homebrew/lib, /usr/local/lib) to improve dynamic linker discovery during builds.

Quick Start

1) Build

cargo build

2) Run

cargo run

3) Test

cargo test

The simulation runs in a window (1200x896). On exit, a statistics window is shown. If a collision occurs, the crash window is shown first.

Configuration

Primary tuning constants are in src/config.rs, including:

  • Geometry and window sizes.
  • Vehicle dimensions and safe spacing.
  • Speed levels and acceleration/deceleration limits.
  • Spawn timing, frame-time clamp, and capacity limits.
  • Reservation guard/occupancy margins and approach control distances.

Adjusting these values changes throughput, aggressiveness, and visual scale.

Assets

Expected runtime assets:

  • assets/background.png
  • assets/cars/car_north_<n>.png
  • assets/cars/car_south_<n>.png
  • assets/cars/car_east_<n>.png
  • assets/cars/car_west_<n>.png

Where <n> ranges from 0 up to configured model count (CAR_MODEL_COUNT).

Fallback behavior:

  • Missing background: procedural roads and markings are drawn.
  • Missing directional car textures: generated fallback car textures are used.

Project Structure

src/
  main.rs                      # binary entrypoint
  lib.rs                       # module exports
  app.rs                       # SDL lifecycle + main loop
  config.rs                    # simulation/render constants
  utils.rs                     # vector math and helpers
  input/
    controls.rs                # keyboard event mapping
    mod.rs
  rendering/
    assets.rs                  # load textures + fallback textures
    renderer.rs                # world and vehicle drawing
    stats_window.rs            # end-of-run statistics UI
    crash_detected_window.rs   # crash UI
    text.rs                    # bitmap-style text rendering
    mod.rs
  simulation/
    routing.rs                 # route geometry + conflict windows
    scheduler.rs               # reservation planning
    physics.rs                 # vehicle motion integration
    intersection.rs            # orchestration and control logic
    collision.rs               # SAT-based OBB collision checks
    spawner.rs                 # manual/random spawn policy
    stats.rs                   # metrics aggregation
    vehicle.rs                 # vehicle state model
    mod.rs

Statistics and Output

At shutdown, the app prints a console report and opens an on-screen stats window.

Tracked metrics:

  • Total spawned and total completed vehicles.
  • Active and peak active vehicles.
  • Max vehicles passed.
  • Min/max observed speed.
  • Min/max completion time.
  • Average completion time.
  • Average wait time.
  • Close-call count.

Completion time is measured from intersection detection to completion.

Troubleshooting

SDL2 Link/Runtime Errors

  • Verify SDL2 and SDL2_image are installed for your OS.
  • On macOS, confirm Homebrew libraries are present in /opt/homebrew/lib or /usr/local/lib.

Missing Sprites or Visuals

  • Check asset paths and filenames under assets/cars.
  • If assets are missing, fallback rendering should still allow the simulation to run.

Build Fails on Toolchain

  • Update Rust to a recent stable toolchain compatible with edition 2024.

Performance/Timing Feels Off

  • Review timing/physics constants in src/config.rs (FRAME_DT_CAP, speed levels, acceleration/deceleration, spacing).

Known Limitations

  • This is a single-intersection simulation (not a road network).
  • Route set is fixed at startup (no runtime editing).
  • No pedestrian or emergency-vehicle modeling.
  • Scheduling is deterministic but still heuristic-based under heavy congestion.

Authors

  • Salah Yuksel
  • Sayed Ahmed Husain
  • Qassim Aljaffer

License

Licensed under the terms in LICENSE.md.

About

A real-time Rust + SDL2 simulation of a four-way autonomous intersection using reservation-based scheduling.

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages