A comprehensive MATLAB-based traffic simulation that models intelligent vehicle behavior on realistic road networks with advanced decision-making algorithms and physics-based vehicle dynamics.
This simulation system demonstrates autonomous vehicle navigation through complex traffic scenarios using hierarchical behavior planning, trajectory optimization, and realistic vehicle dynamics. The system supports multiple vehicle types, environmental hazards, and real-time performance monitoring.
Behavior Planning (behaviorPlanner.m)
- Implements rule-based decision hierarchy for autonomous vehicles
- Processes perception data to generate high-level driving goals
- Supports behaviors: KEEP_LANE, FOLLOW, LANE_CHANGE_LEFT/RIGHT, STOP
- Priority system: Emergency avoidance → Car following → Lane changes
Vehicle Control (trajectoryController.m)
- Hybrid control system combining Pure Pursuit and Stanley controllers
- PID-based speed control with adaptive cruise capabilities
- Speed-dependent steering limits for stability
- Separate control modes for different driving scenarios
Vehicle Dynamics (vehicleDynamics.m)
- Kinematic bicycle model for realistic vehicle motion
- Physics-based position and heading updates
- Vehicle-specific parameters (wheelbase, max speed, steering limits)
- Supports both cars and motorcycles with different characteristics
Scenario Generation (createTestScenario.m)
- Parametric road geometry generation with smooth curves
- Multi-lane road networks with proper lane markings
- Configurable spawn and exit points
- Support for OpenStreetMap integration
Traffic Management (spawnTraffic.m)
- Dynamic vehicle generation with configurable mix ratios
- Vehicle-specific properties (dimensions, dynamics, behavior)
- Intelligent spacing to prevent spawn conflicts
- Lane assignment and initial state configuration
Main Loop (run_sim.m)
- Discrete-time simulation with configurable timestep (default: 0.1s)
- Multi-agent perception system (50m detection range)
- Collision detection and safety monitoring
- Real-time visualization and metrics collection
Environmental Assets
- Static obstacles: potholes, barricades
- Dynamic hazards: moving animals with random walk behavior
- Vehicle response varies by obstacle type (slow down vs. avoid)
- Pure Pursuit: Smooth path following with dynamic lookahead
- Stanley Controller: Cross-track error correction for precise lane keeping
- PID Control: Speed regulation with integral windup protection
- Adaptive Cruise: Distance-based following with comfort constraints
- Cars: 4.5m length, 1.8m width, 50 km/h max speed, 2.5m wheelbase
- Bikes: 2.0m length, 0.6m width, 25 km/h max speed, 1.5m wheelbase
- Individual behavioral parameters (aggressiveness, gap preferences)
- 360-degree vehicle detection within 50-meter radius
- Object classification (vehicles vs. static obstacles)
- Relative position and velocity estimation
- Lane assignment for detected objects
- MATLAB R2020b or later
- Simulink (optional, for model-based development)
- Computer Vision Toolbox (recommended)
- Automated Driving Toolbox (optional, for enhanced features)
% Clone repository and add paths
addpath('lib', 'utils', 'sim', 'examples');
% Run basic simulation
results = run_sim();
% Run with custom parameters
options = struct('numVehicles', 30, 'simTime', 120, 'visualize', true);
results = run_sim(options);options = struct(...
'numVehicles', 20, ... % Initial vehicle count
'simTime', 60, ... % Simulation duration (seconds)
'dt', 0.1, ... % Timestep (seconds)
'visualize', true, ... % Real-time visualization
'exportMetrics', true); % CSV exportRun the comprehensive test suite:
test_simulation % Runs component tests and integration validationTests include:
- Scenario generation validation
- Vehicle spawning verification
- Behavior planning unit tests
- Controller stability checks
- Performance benchmarking
- Color-coded vehicle states (blue: normal, yellow: following, orange: stopping)
- Vehicle ID and speed displays
- Interactive zoom and pan controls
- Road geometry with proper lane markings
- Environmental hazard visualization
- Travel time statistics
- Collision detection and counting
- Vehicle throughput analysis
- Speed distribution tracking
- CSV export for post-processing
- Multiple road geometries (straight, curved, intersection)
- Variable vehicle mix ratios
- Adjustable traffic density
- Environmental hazard placement
- OpenStreetMap integration support
- Max Acceleration: 3.0 m/s² (cars), 2.0 m/s² (bikes)
- Max Deceleration: -8.0 m/s² (cars), -6.0 m/s² (bikes)
- Steering Limits: Speed-dependent (π/9 to π/4 radians)
- Reaction Time: 0.5s (cars), 0.3s (bikes)
- Following Distance: 2-second rule + minimum gap
- Lane Change Threshold: 30-50% speed benefit
- Emergency Distance: 15m obstacle detection
- Perception Range: 50m detection radius
Results structure contains:
avgTravelTime: Mean journey completion timenumCollisions: Total collision eventsnumVehiclesCompleted: Vehicles reaching exit pointstimeHistory: Simulation timelineactiveVehicles: Vehicle count over time
- Extend behavior modes in
behaviorPlanner.m - Implement corresponding control logic in
trajectoryController.m - Update visualization color coding
- Add test cases
- Modify
createTestScenario.mfor custom geometry - Define waypoints using parametric equations
- Set appropriate spawn/exit points
- Configure world boundaries
- Parse OpenStreetMap XML data
- Extract highway segments and convert coordinates
- Generate lane-level representations
- Implement intersection handling
- Supports 50+ vehicles in real-time on modern hardware
- Visualization update frequency affects performance
- Collision detection scales O(n²) with vehicle count
- Memory usage approximately 10MB per 100 vehicles
High Collision Counts: Increase vehicle spacing or reduce spawn rate Slow Performance: Reduce visualization frequency or vehicle count Vehicles Not Moving: Check initial speed assignment and road geometry Visualization Issues: Ensure proper graphics drivers and MATLAB version
This project is designed for educational and research purposes. Commercial use requires appropriate licensing of MATLAB and associated toolboxes.