Skip to content

MrDilaX/FiveM-NPC-Pathfinding

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FiveM Advanced NPC & Pathfinding Framework

Enterprise-grade NPC management system for FiveM with server-side A pathfinding, secure client-server architecture, and navmesh integration*

Version .NET FiveM License

Author: Alex SKYLINE
Compatibility: .NET Framework 4.5.2 / FiveM
Latest Version: 2.1.0


📖 Table of Contents


🎯 Overview

The FiveM Advanced NPC & Pathfinding Framework is a production-ready system designed for high-performance NPC management in FiveM servers. It combines sophisticated server-side pathfinding using the A* algorithm with a secure, optimized client-server architecture.

What Makes This Framework Unique?

  • Server-Side Intelligence: All pathfinding computations are executed on the server using optimized A* algorithm with spatial indexing
  • Navmesh Integration: Full support for custom navmesh data with efficient loading and querying
  • Zero Client Trust: Clients never access configuration files directly - all data is validated and distributed by the server
  • FiveM Optimized: Manual JSON parsing eliminates common Newtonsoft.Json initialization issues in FiveM environments
  • Modular Architecture: Clean separation of concerns with dependency injection patterns for easy maintenance and extension

Use Cases

  • Realistic NPC Populations: Create immersive environments with static and dynamic NPCs
  • Intelligent Navigation: NPCs navigate complex environments using server-calculated optimal paths
  • Dynamic Spawn Zones: Define multiple zones with custom NPC templates and spawn probabilities
  • Security-First Design: Prevent client-side manipulation of NPC configurations and behaviors

✨ Key Features

Pathfinding Engine

  • A Algorithm Implementation* with optimized priority queue
  • Spatial Indexing for O(1) nearest node lookups using grid-based partitioning
  • Wall Avoidance System with proximity cost penalties
  • Waypoint Generation for smooth path following
  • Performance Safeguards with iteration limits and time constraints
  • Navmesh Data Management with batch save/load operations

NPC Management

  • Static NPCs with fixed positions and scenarios
  • Dynamic Spawn Zones with radius-based spawning
  • Model Validation with existence checks and loading verification
  • Behavior Configuration (invincibility, freeze position, event blocking)
  • Real-time Updates for NPC state modifications
  • Automatic Cleanup on player disconnect

Client-Server Communication

  • Authentication System with token-based validation
  • Secure Configuration Broadcast with encrypted channels
  • Manual JSON Parsing to avoid FiveM compatibility issues
  • Message Validation with structure verification
  • Event-Driven Architecture for responsive communication
  • Heartbeat Monitoring for connection health

Development Experience

  • Comprehensive Logging with categorized severity levels
  • Modular Service Architecture for easy testing and extension
  • Dependency Injection patterns throughout codebase
  • Type-Safe Models for all data structures
  • Configuration Hot-Reload support (server restart required)
  • Detailed Error Messages for debugging

🏗️ Architecture

High-Level System Design

┌─────────────────────────────────────────────────────────────┐
│                        FiveM Server                          │
│  ┌────────────────────────────────────────────────────────┐ │
│  │              Server-Side Components                     │ │
│  │  ┌──────────────┐  ┌──────────────┐  ┌─────────────┐  │ │
│  │  │  Pathfinding │  │Configuration │  │    Auth     │  │ │
│  │  │   Service    │  │   Service    │  │  Service    │  │ │
│  │  └──────┬───────┘  └──────┬───────┘  └──────┬──────┘  │ │
│  │         │                  │                  │         │ │
│  │    ┌────▼──────────────────▼──────────────────▼─────┐  │ │
│  │    │           Server Script (ServerScript.cs)      │  │ │
│  │    └────────────────────┬──────────────────────────┘  │ │
│  └─────────────────────────┼─────────────────────────────┘ │
└────────────────────────────┼───────────────────────────────┘
                             │ Network Events
                             │ (TriggerClientEvent)
                             ▼
┌─────────────────────────────────────────────────────────────┐
│                      FiveM Clients                           │
│  ┌────────────────────────────────────────────────────────┐ │
│  │              Client-Side Components                     │ │
│  │  ┌──────────────┐  ┌──────────────┐  ┌─────────────┐  │ │
│  │  │     NPC      │  │   Network    │  │   Config    │  │ │
│  │  │   Manager    │  │   Service    │  │  Receiver   │  │ │
│  │  └──────┬───────┘  └──────┬───────┘  └──────┬──────┘  │ │
│  │         │                  │                  │         │ │
│  │    ┌────▼──────────────────▼──────────────────▼─────┐  │ │
│  │    │           Client Script (ClientScript.cs)      │  │ │
│  │    └────────────────────────────────────────────────┘  │ │
│  └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

Project Structure

FiveM-NPC-Pathfinding/
├── 📂 Server/                          # Server-side code (.NET 4.5.2)
│   ├── 📂 Services/
│   │   ├── AStarPathfindingService.cs          # A* pathfinding implementation
│   │   ├── NavmeshDataService.cs               # Navmesh load/save operations
│   │   ├── SpatialIndexService.cs              # Grid-based spatial indexing
│   │   ├── WallProximityService.cs             # Wall avoidance calculations
│   │   ├── WaypointGenerationService.cs        # Path smoothing
│   │   ├── ConfigurationService.cs             # JSON config management
│   │   ├── ConfigurationBroadcastService.cs    # Secure config distribution
│   │   ├── ClientAuthenticationService.cs      # Client validation
│   │   ├── PathfindingRequestHandler.cs        # Path request processing
│   │   └── LoggingService.cs                   # Structured logging
│   ├── 📂 Algorithms/
│   │   └── AStarAlgorithm.cs                   # Core A* algorithm logic
│   ├── 📂 Models/
│   │   ├── Node.cs                             # Navmesh node structure
│   │   ├── PathfindingConfig.cs                # Algorithm parameters
│   │   ├── PathfindingState.cs                 # Search state tracking
│   │   ├── OptimizedPathfindingState.cs        # Performance-optimized state
│   │   └── OptimizedPriorityQueue.cs           # Custom priority queue
│   ├── 📂 Converters/
│   │   ├── Vector3Converter.cs                 # JSON Vector3 serialization
│   │   └── TupleConverter.cs                   # JSON Tuple serialization
│   └── 📄 ServerScript.cs                      # Main server script
│
├── 📂 Client/                          # Client-side code (.NET 4.5.2)
│   ├── 📂 Services/
│   │   ├── NpcManagerService.cs                # NPC spawning and management
│   │   ├── NetworkService.cs                   # Server communication
│   │   ├── ConfigurationReceiver.cs            # Config data handling
│   │   └── LoggingService.cs                   # Client-side logging
│   ├── 📂 Models/
│   │   ├── ClientNpcData.cs                    # NPC data structure
│   │   └── NetworkMessage.cs                   # Network message format
│   ├── 📂 Handlers/
│   │   └── NpcEventHandler.cs                  # NPC event processing
│   └── 📄 ClientScript.cs                      # Main client script
│
├── 📂 config/                          # Configuration files
│   ├── 📄 setting.json                         # General settings
│   ├── 📄 npc_static.json                      # Static NPC definitions
│   └── 📄 spawnzone.json                       # Dynamic spawn zones
│
├── 📂 save/                            # Runtime data
│   └── navmesh_data_*.json                     # Generated navmesh files
│
├── 📄 fxmanifest.lua                   # FiveM resource manifest
├── 📄 NavMeshServer.csproj             # Server project file
├── 📄 NavMeshClient.csproj             # Client project file
└── 📄 README.md                        # This file

Key Architectural Patterns

1. Service-Oriented Architecture

All major functionality is encapsulated in dedicated services with single responsibilities:

  • Separation of Concerns: Each service handles one specific domain
  • Dependency Injection: Services are injected through constructors
  • Interface Segregation: Pathfinding uses IPathfindingService interface

2. FiveM-Compatible JSON Parsing

Manual JSON parsing eliminates TypeInitializationException common in FiveM:

// Manual JSON construction (NetworkService.cs)
var authData = $"{{\"clientId\":\"{clientId}\",\"timestamp\":\"{timestamp}\",\"version\":\"{version}\"}}";

// Manual JSON parsing with validation
private ClientNpcData ParseNpcDataFromJson(string json)
{
    // Extract values using string operations instead of JsonConvert
    // Robust against FiveM environment limitations
}

3. Optimized Priority Queue

Custom implementation for A* pathfinding that outperforms standard .NET collections:

// OptimizedPriorityQueue.cs - O(log n) operations
public class OptimizedPriorityQueue
{
    private List<(int nodeId, float priority)> _heap;
    
    public void Enqueue(int nodeId, float priority) { /* Min-heap insertion */ }
    public int Dequeue() { /* Extract minimum */ }
}

4. Thread-Safe Pathfinding

All pathfinding operations are protected with locks to prevent race conditions:

private static readonly object _pathfindingLock = new object();

public void HandlePathRequest(Player source, /* params */)
{
    lock (_pathfindingLock)
    {
        // Thread-safe path calculation
    }
}

🚀 Installation

Prerequisites

  • FiveM Server (latest build recommended)
  • .NET SDK 4.5.2 or higher
  • Visual Studio 2019+ or JetBrains Rider (for development)
  • Git (for version control)

Quick Start

1. Download and Build

# Clone the repository
git clone https://github.com/yourusername/fivem-npc-pathfinding.git
cd fivem-npc-pathfinding

# Build server-side DLL
dotnet build NavMeshServer.csproj -c Release

# Build client-side DLL
dotnet build NavMeshClient.csproj -c Release

2. Install to FiveM Server

# Copy entire folder to your FiveM resources directory
cp -r fivem-npc-pathfinding [FiveM-Server]/resources/

# Add to server.cfg
echo "ensure fivem-npc-pathfinding" >> server.cfg

3. Verify Installation

# Start your FiveM server
# Check console for:
[VitalityNPC_csharp] Server script initialization completed successfully
[VitalityNPC_csharp] Configuration ready for use

4. Required Files Check

Ensure these files exist in bin/Release/net452/ (or Debug for development):

✓ NavMeshServer.net.dll
✓ NavMeshClient.net.dll
✓ CitizenFX.Core.Server.dll
✓ CitizenFX.Core.Client.dll
✓ Newtonsoft.Json.dll
✓ Microsoft.CSharp.dll

Development Build

For active development with debugging enabled:

# Build in debug mode
dotnet build NavMeshServer.csproj
dotnet build NavMeshClient.csproj

# FiveM console commands
refresh
restart fivem-npc-pathfinding

⚙️ Configuration

General Settings (config/setting.json)

{
  "debug": true,                    // Enable verbose logging
  "maxNpcs": 50,                    // Maximum NPCs per client
  "spawnDistance": 100.0,           // Spawn radius in meters
  "refreshInterval": 5000,          // Update interval in ms
  "enableStaticNpcs": true,         // Enable static NPC system
  "enableDynamicNpcs": true,        // Enable dynamic spawn zones
  "modelLoadTimeout": 5000,         // Model loading timeout (ms)
  "maxAuthAttempts": 3,             // Max authentication retries
  "sessionDuration": 3600           // Session lifetime (seconds)
}

Static NPCs (config/npc_static.json)

Define NPCs with fixed positions and behaviors:

{
  "npcs": [
    {
      "id": 1,
      "name": "Reception Desk Clerk",
      "model": "a_m_m_business_01",
      "position": {
        "x": -1006.1578,
        "y": -2782.7275,
        "z": 21.3617
      },
      "heading": 80.0,
      "scenario": "WORLD_HUMAN_STAND_IMPATIENT",
      "behavior": {
        "isInvincible": true,        // Cannot be killed
        "freezePosition": true,       // Cannot move from position
        "blockEvents": true,          // Ignore game events
        "useScenario": true,          // Play animation scenario
        "canWander": false,           // Allow random movement
        "wanderRadius": 5.0,          // Wander distance (if enabled)
        "wanderInterval": 60000       // Time between wanders (ms)
      }
    }
  ]
}

Available NPC Scenarios

Common GTA V scenarios for realistic NPC behavior:

  • WORLD_HUMAN_STAND_IMPATIENT - Standing impatiently
  • WORLD_HUMAN_GUARD_STAND - Security guard stance
  • WORLD_HUMAN_CLIPBOARD - Holding clipboard
  • WORLD_HUMAN_STAND_MOBILE - Using mobile phone
  • WORLD_HUMAN_SMOKING - Smoking cigarette
  • WORLD_HUMAN_LEANING - Leaning against wall
  • WORLD_HUMAN_TOURIST_MAP - Looking at map
  • WORLD_HUMAN_AA_COFFEE - Drinking coffee

Dynamic Spawn Zones (config/spawnzone.json)

Create areas where NPCs spawn dynamically:

{
  "spawnZones": [
    {
      "id": 1,
      "name": "Downtown Business District",
      "center": {
        "x": -1000.0,
        "y": -2800.0,
        "z": 20.0
      },
      "radius": 200.0,              // Zone radius in meters
      "maxNpcs": 15,                // Max NPCs in this zone
      "isActive": true,             // Enable/disable zone
      "priority": 1,                // Spawn priority (1 = highest)
      "npcTemplates": [
        {
          "model": "a_m_m_business_01",
          "name": "Business Worker",
          "scenario": "WORLD_HUMAN_STAND_MOBILE",
          "spawnChance": 0.6        // 60% spawn probability
        },
        {
          "model": "a_f_m_business_02",
          "name": "Business Woman",
          "scenario": "WORLD_HUMAN_CLIPBOARD",
          "spawnChance": 0.4        // 40% spawn probability
        }
      ]
    }
  ]
}

Behavior Parameters Reference

Parameter Type Description Default
isInvincible boolean NPC cannot take damage false
freezePosition boolean NPC stays at spawn point false
blockEvents boolean NPC ignores game events false
useScenario boolean Play specified scenario animation false
canWander boolean Allow random movement false
wanderRadius float Maximum wander distance (meters) 0.0
wanderInterval integer Time between wanders (milliseconds) 0

📡 API Documentation

Server Events (Received from Client)

Authentication & Configuration

npc:requestAuthentication

-- Client sends authentication request
TriggerServerEvent("npc:requestAuthentication", authDataJson)

-- Parameters:
--   authDataJson (string): JSON with clientId, timestamp, version

npc:requestConfiguration

-- Client requests specific configuration
TriggerServerEvent("npc:requestConfiguration", requestDataJson)

-- Parameters:
--   requestDataJson (string): JSON with configType, authToken

Pathfinding Operations

navmesh:requestPath

-- Request server-side pathfinding calculation
TriggerServerEvent("navmesh:requestPath", 
    startX, startY, startZ,    -- Start position
    endX, endY, endZ,          -- End position
    requestId                  -- Unique request identifier
)

navmesh:requestLoadZone

-- Load navmesh data for current zone
TriggerServerEvent("navmesh:requestLoadZone")

navmesh:startBatchSave

-- Begin batch navmesh save operation
TriggerServerEvent("navmesh:startBatchSave", totalChunks)

navmesh:saveZoneChunk

-- Save a chunk of navmesh data
TriggerServerEvent("navmesh:saveZoneChunk", chunkData)

navmesh:endBatchSave

-- Complete batch save operation
TriggerServerEvent("navmesh:endBatchSave")

Client Events (Received from Server)

Authentication & Security

npc:authenticationToken

-- Receive authentication token from server
RegisterNetEvent("npc:authenticationToken")
AddEventHandler("npc:authenticationToken", function(token)
    -- Store token for subsequent requests
end)

npc:connectionValidated

-- Connection validation status
RegisterNetEvent("npc:connectionValidated")
AddEventHandler("npc:connectionValidated", function(isValid)
    -- Handle validation result
end)

Configuration Management

npc:configurationData

-- Receive configuration data
RegisterNetEvent("npc:configurationData")
AddEventHandler("npc:configurationData", function(configType, configDataJson)
    -- Process configuration (npc_static, spawnzone, setting)
end)

npc:configurationUpdate

-- Receive real-time configuration updates
RegisterNetEvent("npc:configurationUpdate")
AddEventHandler("npc:configurationUpdate", function(configType, updateDataJson)
    -- Apply configuration changes
end)

NPC Management

npc:spawnCommand

-- Spawn NPC command
RegisterNetEvent("npc:spawnCommand")
AddEventHandler("npc:spawnCommand", function(npcDataJson)
    -- Parse and spawn NPC
end)

npc:updateCommand

-- Update existing NPC
RegisterNetEvent("npc:updateCommand")
AddEventHandler("npc:updateCommand", function(npcDataJson)
    -- Update NPC state
end)

npc:removeCommand

-- Remove NPC by ID
RegisterNetEvent("npc:removeCommand")
AddEventHandler("npc:removeCommand", function(npcId)
    -- Delete NPC entity
end)

C# Service APIs

Server-Side Pathfinding Service

public interface IPathfindingService
{
    bool IsReady { get; }
    void LoadNavmesh();
    List<Vector3> FindPath(Vector3 start, Vector3 end);
}

// Usage example
var path = _pathfindingService.FindPath(startPos, endPos);
if (path != null && path.Count > 0)
{
    // Use path waypoints
}

Client-Side NPC Manager

public class NpcManagerService
{
    public bool SpawnNpc(ClientNpcData npcData);
    public bool UpdateNpc(ClientNpcData npcData);
    public bool RemoveNpc(int npcId);
    public ClientNpcData GetNpc(int npcId);
    public List<ClientNpcData> GetAllNpcs();
}

// Usage example
var success = _npcManager.SpawnNpc(new ClientNpcData
{
    Id = 1,
    Name = "Security Guard",
    Model = "s_m_m_security_01",
    Position = new Vector3(100.0f, 200.0f, 20.0f),
    Heading = 90.0f
});

🔒 Security

Authentication Flow

sequenceDiagram
    participant C as Client
    participant S as Server
    
    C->>S: npc:requestAuthentication
    Note over C,S: {clientId, timestamp, version}
    S->>S: Generate SHA256 Token
    S->>C: npc:authenticationToken
    Note over S,C: Base64 encoded token
    S->>C: npc:connectionValidated(true)
    S->>C: npc:configurationData
    Note over S,C: Secured config with integrity hash
Loading

Security Features

Token-Based Authentication

  • SHA256 hashed authentication tokens
  • Unique client identification
  • Session management with automatic cleanup

Message Integrity Validation

  • SHA256 hash verification on all messages
  • Timestamp-based replay attack prevention
  • Structured message format validation

Zero Client Trust Architecture

  • Configuration files only accessible server-side
  • All NPC data validated before distribution
  • Client cannot modify server state directly

Session Management

  • Automatic session cleanup on player disconnect
  • Configurable session duration
  • Maximum authentication attempt limits

Message Format

Server Messages (Newtonsoft.Json format)

{
  "Data": { /* payload */ },
  "MessageType": "npc_static",
  "Timestamp": "2025-10-12T12:00:00.000Z",
  "MessageId": "unique-guid",
  "MessageHash": "sha256-integrity-hash"
}

Client Messages (Manual format)

{
  "data": { /* payload */ },
  "authToken": "authentication-token",
  "timestamp": "2025-10-12T12:00:00.000Z",
  "messageId": "unique-guid",
  "messageHash": "sha256-integrity-hash"
}

🎯 Performance

Optimization Techniques

1. Spatial Indexing

Grid-based spatial partitioning for O(1) nearest node queries:

Traditional Search: O(n) - Check all nodes
Spatial Index: O(1) - Direct grid cell lookup
Result: 100x-1000x faster for large navmeshes

2. Optimized A* Implementation

  • Custom priority queue with O(log n) operations
  • Early termination on unreachable paths
  • Configurable iteration and time limits

3. Model Loading Strategy

// Optimized model loading with validation
1. Check if model exists in game files
2. Validate model hash
3. Request with extended timeout
4. Monitor loading with exponential backoff
5. Automatic cleanup on failure

4. Memory Management

  • Node connection caching
  • Spatial grid reuse
  • Automatic navmesh cleanup
  • Client-side NPC dictionary management

Performance Metrics

Operation Time Notes
Navmesh Load ~500-2000ms Depends on file size
Path Calculation <50ms Typical 100-node path
NPC Spawn ~100-500ms Includes model loading
Spatial Query <1ms O(1) grid lookup
Authentication <10ms Token generation

Scalability

  • Supports 1000+ navmesh nodes with minimal performance impact
  • 50+ concurrent NPCs per client (configurable)
  • Multiple spawn zones with independent management
  • Thread-safe pathfinding for concurrent requests

📊 Logging System

Log Format

[YYYY-MM-DD HH:mm:ss.fff] [ResourceName] [ClientID] [LEVEL] [Component] Message

Log Levels

Level Usage Example
INFO General information NPC Manager service initialized
SUCCESS Successful operations NPC spawned successfully
WARNING Non-critical issues Model loading timeout, retrying
ERROR Errors with stack traces Failed to parse JSON: {exception}
SECURITY Security events Client authenticated with token
NETWORK_IN Incoming network data Configuration data received
NETWORK_OUT Outgoing network data Authentication request sent
CONFIGURATION Config status Setting.json loaded successfully
DEBUG Debug information Pathfinding iteration 150/1000

Example Log Output

[2025-10-12 14:30:15.234] [VitalityNPC_csharp] [Server] [INFO] [ServerScript] Initializing server script
[2025-10-12 14:30:15.456] [VitalityNPC_csharp] [Server] [CONFIGURATION] [ConfigurationService] setting.json loaded (6 properties)
[2025-10-12 14:30:15.789] [VitalityNPC_Client] [Client_12345] [SECURITY] [NetworkService] Authentication request sent
[2025-10-12 14:30:15.890] [VitalityNPC_csharp] [Server] [SECURITY] [AuthService] Client authenticated: Client_12345
[2025-10-12 14:30:16.012] [VitalityNPC_Client] [Client_12345] [SUCCESS] [NpcManager] NPC 'Security Guard' spawned

🛠️ Troubleshooting

Common Issues and Solutions

1. TypeInitializationException - Newtonsoft.Json

Error:

The type initializer for 'Newtonsoft.Json.Serialization.DefaultSerializationBinder' threw an exception

Cause: FiveM environment doesn't properly initialize some .NET reflection features required by Newtonsoft.Json

Solution: ✅ This framework uses manual JSON parsing to avoid this issue completely

  • Network messages: Manual string construction
  • NPC data: Custom parsing without JsonConvert
  • Configuration: Direct string manipulation

2. Model Loading Failures

Error:

[ERROR] Failed to load NPC model after 50 attempts: a_m_m_business_01

Possible Causes:

  • Model name typo in configuration
  • Model not available in GTA V
  • Server performance issues

Solutions:

// 1. Verify model exists
// Use https://wiki.rage.mp/index.php?title=Peds for valid model names

// 2. Increase timeout in setting.json
{
  "modelLoadTimeout": 10000  // Increase from 5000 to 10000ms
}

// 3. Check console for specific errors
[INFO] [NpcManagerService] Requesting model: a_m_m_business_01 (Hash: 123456789)

3. Authentication Failures

Error:

[ERROR] [NetworkService] Authentication failed: timeout

Solutions:

  1. Check server is running and resource loaded
  2. Verify network events are registered
  3. Check F8 console for error messages
  4. Restart resource: restart fivem-npc-pathfinding

4. NPCs Not Spawning

Checklist:

  • ✅ Static NPCs enabled in setting.json ("enableStaticNpcs": true)
  • ✅ Valid model names in npc_static.json
  • ✅ Client authenticated with server
  • ✅ No errors in F8 console
  • ✅ Player within spawn distance (if configured)

Debug Steps:

# 1. Enable debug logging
# In setting.json: "debug": true

# 2. Check server console for:
[CONFIGURATION] npc_static.json loaded successfully

# 3. Check client console (F8) for:
[SUCCESS] NPC spawned successfully

# 4. If nothing appears, check authentication:
[SECURITY] Client authenticated with token

5. Pathfinding Not Working

Error:

[A*] Could not find nearest nodes

Cause: Navmesh data not loaded

Solution:

# 1. Generate navmesh data (if not exists)
TriggerServerEvent("navmesh:requestLoadZone")

# 2. Check save folder for navmesh files
ls save/navmesh_data_*.json

# 3. Verify navmesh loaded in console
[PATHFINDING] Successfully loaded 5000 nodes in 1500ms

6. High Memory Usage

Symptoms:

  • Server slowdown after extended runtime
  • Increasing memory usage

Solutions:

// 1. Reduce max NPCs in setting.json
{
  "maxNpcs": 25  // Reduce from 50
}

// 2. Decrease spawn zones
// Remove or disable unused zones in spawnzone.json

// 3. Implement automatic cleanup
// NPCs are automatically cleaned up on player disconnect

7. DLL Not Found Errors

Error:

Could not load file or assembly 'NavMeshServer.net.dll'

Solutions:

  1. Verify build completed:

    dotnet build NavMeshServer.csproj
    dotnet build NavMeshClient.csproj
  2. Check file locations:

    ✓ bin/Debug/net452/NavMeshServer.net.dll
    ✓ bin/Debug/net452/NavMeshClient.net.dll
    
  3. Verify fxmanifest.lua:

    server_script 'bin/Debug/net452/NavMeshServer.net.dll'
    client_script 'bin/Debug/net452/NavMeshClient.net.dll'
  4. Refresh and restart:

    refresh
    restart fivem-npc-pathfinding

Message Format Validation

The system supports two message formats for maximum compatibility:

Server Messages (Newtonsoft.Json format)

{
  "Data": { /* payload */ },
  "MessageType": "npc_static",
  "Timestamp": "2025-10-12T12:00:00.000Z",
  "MessageId": "unique-guid",
  "MessageHash": "sha256-integrity-hash"
}

Client Messages (Manual format)

{
  "data": { /* payload */ },
  "authToken": "authentication-token",
  "timestamp": "2025-10-12T12:00:00.000Z",
  "messageId": "guid-unique",
  "messageHash": "sha256-integrity-hash"
}

🔧 Advanced Configuration

Performance Tuning

Pathfinding Parameters

Edit Server/Models/PathfindingConfig.cs:

public static class PathfindingConfig
{
    public const int MAX_ITERATIONS = 1000;           // Max A* iterations
    public const int MAX_PROCESSING_TIME_MS = 100;    // Max calculation time
    public const int YIELD_EVERY_N_ITERATIONS = 100;  // Thread yield frequency
    public const float WALL_PROXIMITY_THRESHOLD = 2.0f; // Wall avoidance distance
    public const float WALL_AVOIDANCE_COST = 2.0f;    // Wall proximity penalty
}

Recommendations:

  • High-traffic servers: Reduce MAX_ITERATIONS to 500
  • Complex navmesh: Increase MAX_PROCESSING_TIME_MS to 200
  • Performance issues: Increase YIELD_EVERY_N_ITERATIONS to 50

Spatial Index Optimization

Edit Server/Services/SpatialIndexService.cs:

public SpatialIndexService(List<Node> nodes, float gridSize = 50.0f)

Grid Size Guidelines:

  • Dense urban areas: 25.0f (smaller cells, more precision)
  • Open areas: 100.0f (larger cells, better performance)
  • Mixed environments: 50.0f (default, balanced)

Custom NPC Behaviors

Creating Wandering NPCs

{
  "id": 5,
  "name": "Wandering Civilian",
  "model": "a_m_m_tourist_01",
  "position": {"x": 100.0, "y": 200.0, "z": 20.0},
  "heading": 0.0,
  "scenario": "WORLD_HUMAN_TOURIST_MAP",
  "behavior": {
    "isInvincible": true,
    "freezePosition": false,
    "blockEvents": true,
    "useScenario": false,
    "canWander": true,
    "wanderRadius": 50.0,      // 50 meter radius
    "wanderInterval": 30000     // Move every 30 seconds
  }
}

Creating Interactive NPCs

{
  "id": 6,
  "name": "Shop Keeper",
  "model": "s_m_m_autoshop_01",
  "position": {"x": 150.0, "y": 250.0, "z": 20.0},
  "heading": 90.0,
  "scenario": "WORLD_HUMAN_STAND_IMPATIENT",
  "behavior": {
    "isInvincible": true,
    "freezePosition": true,
    "blockEvents": false,      // Allow interactions
    "useScenario": true,
    "canWander": false
  }
}

Environment-Specific Configurations

Development Environment

{
  "debug": true,
  "maxNpcs": 10,
  "spawnDistance": 50.0,
  "refreshInterval": 2000,
  "enableStaticNpcs": true,
  "enableDynamicNpcs": false,
  "modelLoadTimeout": 10000
}

Production Environment

{
  "debug": false,
  "maxNpcs": 50,
  "spawnDistance": 100.0,
  "refreshInterval": 5000,
  "enableStaticNpcs": true,
  "enableDynamicNpcs": true,
  "modelLoadTimeout": 5000
}

🤝 Contributing

We welcome contributions to improve this framework!

Development Setup

  1. Fork and clone the repository

    git clone https://github.com/yourusername/fivem-npc-pathfinding.git
    cd fivem-npc-pathfinding
  2. Create a feature branch

    git checkout -b feature/your-feature-name
  3. Make your changes

    • Follow existing code style
    • Add XML documentation for public methods
    • Update README if adding new features
  4. Test thoroughly

    • Build both server and client projects
    • Test in FiveM development environment
    • Check F8 console for errors
  5. Submit pull request

    • Describe your changes clearly
    • Reference any related issues
    • Include screenshots if UI changes

Code Style Guidelines

  • Naming: PascalCase for classes/methods, camelCase for variables
  • Documentation: XML docs for all public APIs
  • Logging: Use appropriate log levels
  • Error Handling: Try-catch with detailed error messages
  • Thread Safety: Use locks for shared resources

Areas for Contribution

  • 🎯 Additional pathfinding algorithms (Dijkstra, Jump Point Search)
  • 🤖 Advanced NPC behaviors (patrol routes, reactions)
  • 🗺️ Navmesh generation tools
  • 📊 Performance monitoring dashboard
  • 🌐 Multi-language support
  • 📝 Documentation improvements

📚 Additional Resources

Documentation

Related Projects

  • FiveM Docs: Official FiveM documentation
  • CFX Forums: Community support and discussions
  • GTA V Modding: Resources for GTA V development

Support


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License

Copyright (c) 2025 Alex SKYLINE

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

🙏 Acknowledgments

  • FiveM Team for the excellent multiplayer framework
  • CitizenFX Collective for C# scripting support
  • GTA V Modding Community for resources and documentation
  • Contributors who helped improve this project

📞 Contact

Author: Alex SKYLINE
Version: 2.1.0
Last Updated: October 2025

For questions, suggestions, or support:

  • Open an issue on GitHub
  • Join our Discord community
  • Check the documentation wiki

⭐ If this project helped you, please consider giving it a star! ⭐

Made with ❤️ for the FiveM community

🔝 Back to Top

| `ConfigurationBroadcastService` | `Server/Services/ConfigurationBroadcastService.cs` | Diffusion sécurisée | Support multi-format + validation | | `AStarPathfindingService` | `Server/Services/AStarPathfindingService.cs` | Pathfinding optimisé | Algorithme A* avec spatial indexing | | `NavmeshDataService` | `Server/Services/NavmeshDataService.cs` | Gestion navmesh | Chargement/sauvegarde par chunks |

Services Client (Refactorisés pour FiveM)

Service Fichier Responsabilités Améliorations v2.1.0
LoggingService Client/Services/LoggingService.cs Logging client avec IDs uniques Sync avec logging serveur
NetworkService Client/Services/NetworkService.cs Communication sécurisée Parsing JSON manuel + validation bidirectionnelle
NpcManagerService Client/Services/NpcManagerService.cs Gestion complète des NPCs Chargement modèles optimisé + validation avancée
ConfigurationReceiver Client/Services/ConfigurationReceiver.cs Réception de configurations Extraction JSON manuelle + processing automatique

Gestionnaires Client

Handler Fichier Responsabilités Améliorations v2.1.0
NpcEventHandler Client/Handlers/NpcEventHandler.cs Events de gestion NPC Parsing NPC manuel + validation complète

📊 CONFIGURATION AVANCÉE

config/npc_static.json - Structure Complète

{
  "npcs": [
    {
      "id": 1,
      "name": "Reception Desk Clerk",
      "model": "a_m_m_business_01",
      "position": {
        "x": -1006.1578,
        "y": -2782.7275,
        "z": 21.3617
      },
      "heading": 80.0,
      "scenario": "WORLD_HUMAN_STAND_IMPATIENT",
      "behavior": {
        "isInvincible": true,
        "freezePosition": true,
        "blockEvents": true,
        "useScenario": true,
        "canWander": false,
        "wanderRadius": 5.0,
        "wanderInterval": 60000
      }
    },
    {
      "id": 3,
      "name": "Information Assistant",
      "model": "a_f_m_business_02",
      "position": {
        "x": -1000.0,
        "y": -2785.0,
        "z": 21.3617
      },
      "heading": 270.0,
      "scenario": "WORLD_HUMAN_CLIPBOARD",
      "behavior": {
        "isInvincible": true,
        "freezePosition": false,
        "blockEvents": true,
        "useScenario": true,
        "canWander": true,
        "wanderRadius": 5.0,
        "wanderInterval": 60000
      }
    }
  ]
}

Paramètres de Comportement NPC

Paramètre Type Description Valeur par défaut
isInvincible boolean Rend le NPC invulnérable aux dégâts false
freezePosition boolean Empêche le NPC de bouger de sa position false
blockEvents boolean Bloque les événements externes sur le NPC false
useScenario boolean Active l'utilisation du scénario spécifié false
canWander boolean Permet au NPC de se déplacer aléatoirement false
wanderRadius float Rayon de déplacement en mètres 0.0
wanderInterval int Intervalle entre déplacements (ms) 0

config/setting.json - Paramètres Système

{
  "debug": true,
  "maxNpcs": 50,
  "spawnDistance": 100.0,
  "refreshInterval": 5000,
  "enableStaticNpcs": true,
  "enableDynamicNpcs": true,
  "modelLoadTimeout": 5000,
  "maxAuthAttempts": 3,
  "sessionDuration": 3600
}

config/spawnzone.json - Zones de Spawn Dynamiques

{
  "spawnZones": [
    {
      "id": 1,
      "name": "Downtown Business District",
      "center": { "x": -1000.0, "y": -2800.0, "z": 20.0 },
      "radius": 200.0,
      "maxNpcs": 15,
      "isActive": true,
      "priority": 1,
      "npcTemplates": [
        {
          "model": "a_m_m_business_01",
          "name": "Business Worker",
          "scenario": "WORLD_HUMAN_STAND_MOBILE",
          "spawnChance": 0.6
        }
      ]
    }
  ]
}

📝 LOGGING ENRICHI

Format des logs standardisé

[YYYY-MM-DD HH:mm:ss.fff] [ResourceName] [ClientID] [LEVEL] [Component] Message

Niveaux de logs spécialisés

  • INFO - Informations générales
  • SUCCESS - Opérations réussies (spawn NPCs, authentification)
  • WARNING - Avertissements (modèles non trouvés, timeouts)
  • ERROR - Erreurs avec stack traces complètes
  • SECURITY - Événements de sécurité (authentification, sessions)
  • NETWORK_IN/OUT - Communication réseau détaillée
  • CONFIGURATION - Status des configurations chargées
  • DEBUG - Messages de débogage (build debug uniquement)

Exemples de logs v2.1.0

[2025-07-07 12:45:00.503] [VitalityNPC_Client] [Client_61480] [SECURITY] [NetworkService] Client-server secure connection established
[2025-07-07 12:45:00.515] [VitalityNPC_Client] [Client_61480] [NETWORK_IN] [ConfigurationReceiver] Configuration data received: npc_static
[2025-07-07 12:45:00.518] [VitalityNPC_Client] [Client_61480] [INFO] [NpcManagerService] Requesting model: a_m_m_business_01 (Hash: 123456789)
[2025-07-07 12:45:00.647] [VitalityNPC_Client] [Client_61480] [SUCCESS] [NpcManagerService] NPC 'Reception Desk Clerk' (ID: 1) spawned successfully
[2025-07-07 12:45:00.648] [VitalityNPC_Client] [Client_61480] [SUCCESS] [ConfigurationReceiver] Static NPC configuration processed: 5 NPCs

🔗 DÉPENDANCES ET COMPATIBILITÉ

Serveur (NavMeshServer.csproj)

<PackageReference Include="CitizenFX.Core.Server" Version="1.0.*" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />

Client (NavMeshClient.csproj)

<PackageReference Include="CitizenFX.Core.Client" Version="1.0.*" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />

Versions Testées et Compatibles

  • .NET Framework 4.5.2 (requis pour FiveM)
  • FiveM Latest (testé sur builds récents)
  • GTA V (tous les modèles de NPCs standards)
  • ⚠️ Newtonsoft.Json 11.0.2 (version fixe pour compatibilité FiveM)

🚀 DÉVELOPPEMENT

Commandes de build optimisées

# Build complet avec nettoyage
dotnet clean && dotnet build NavMeshServer.csproj && dotnet build NavMeshClient.csproj

# Build release optimisé pour production
dotnet build -c Release NavMeshServer.csproj
dotnet build -c Release NavMeshClient.csproj

# Déploiement FiveM automatique
refresh && start VitalityNPC_csharp

Architecture modulaire v2.1.0

  • Injection de dépendances : Services chaînés avec logging intégré
  • Parsing JSON manuel : Indépendance complète de Newtonsoft.Json côté parsing
  • Gestion d'erreurs robuste : Try-catch avec logging détaillé
  • Documentation XML : Complète sur toutes les méthodes publiques
  • Compatibilité FiveM : Tests complets des méthodes synchrones

🛠️ TROUBLESHOOTING FIVEM

Erreurs Courantes et Solutions

1. TypeInitializationException avec Newtonsoft.Json

Error: The type initializer for 'Newtonsoft.Json.Serialization.DefaultSerializationBinder' threw an exception

Solution : Le système utilise maintenant un parsing JSON manuel. Cette erreur ne devrait plus se produire.

2. BadImageFormatException avec async/await

Error: Cannot load method from token 0x0a0000d3 for call at 0x00c0

Solution : Toutes les méthodes async ont été remplacées par des versions synchrones FiveM-compatibles.

3. Échec de chargement des modèles NPCs

Error: Failed to load NPC model: a_m_m_tourist_01

Solutions :

  • Vérifier que le modèle existe dans GTA V avec API.IsModelInCdimage()
  • Augmenter le timeout de chargement dans setting.json
  • Utiliser des modèles de NPCs standards

4. Problèmes d'authentification

Error: Client authentication failed

Solutions :

  • Vérifier la synchronisation d'horloge serveur/client
  • Contrôler les timestamps dans les logs
  • Redémarrer la ressource si les sessions sont corrompues

Validation de l'Installation

# 1. Vérifier la compilation
dotnet build NavMeshServer.csproj
dotnet build NavMeshClient.csproj

# 2. Vérifier les DLL générées
ls -la bin/Debug/net452/

# 3. Tester dans FiveM
refresh
start VitalityNPC_csharp

# 4. Vérifier les logs
# Rechercher : "VitalityNPC_csharp server script initialization completed"
# Rechercher : "Client-server secure connection established"

📈 CHANGELOG VERSION 2.1.0

🔧 Corrections Majeures

  • Résolution TypeInitializationException : Parsing JSON manuel dans NetworkService, ConfigurationReceiver, NpcEventHandler
  • Élimination BadImageFormatException : Remplacement async/await par méthodes synchrones
  • Chargement modèles optimisé : Validation avancée avec IsModelInCdimage() et timing amélioré
  • Communication bidirectionnelle : Support format serveur (Newtonsoft) et client (manuel)

✨ Nouvelles Fonctionnalités

  • Parsing JSON manuel sécurisé : Indépendance complète de JsonConvert côté client
  • Validation multi-format : Détection automatique format serveur vs client
  • Logging spécialisé : Niveaux NETWORK, SECURITY, CONFIGURATION
  • Gestion de sessions robuste : Cleanup automatique et refresh tokens

🏗️ Améliorations Architecturales

  • Services refactorisés : NetworkService, NpcManagerService, ConfigurationReceiver
  • Extraction NPCs automatique : Parsing manuel des configurations complexes
  • Validation comportements : Support complet wandering et scenarios
  • Documentation enrichie : Guide troubleshooting et exemples détaillés

🔒 Sécurité Renforcée

  • Messages bidirectionnels : Validation serveur ↔ client avec hash SHA256
  • Sessions authentifiées : Tokens sécurisés avec expiration automatique
  • Audit logging : Traçabilité complète des opérations sensibles

⚠️ NOTES IMPORTANTES

Sécurité et Architecture

  1. Client passif : Le client ne peut jamais accéder directement aux fichiers de configuration
  2. Parsing manuel : Évite les problèmes d'initialisation Newtonsoft.Json dans FiveM
  3. Communication sécurisée : Tous les messages utilisent SHA256 pour l'intégrité
  4. Sessions temporaires : Nettoyage automatique lors des déconnexions

Performance et Stabilité

  1. Chargement asynchrone : Models NPCs chargés avec validation et timeout
  2. Communication optimisée : Messages compacts avec validation bidirectionnelle
  3. Gestion mémoire : Cleanup automatique des sessions et NPCs
  4. Logging intelligent : Niveaux spécialisés pour debugging FiveM

Compatibilité

  1. FiveM natif : Architecture testée avec les dernières versions FiveM
  2. .NET Framework 4.5.2 : Compatibilité garantie avec l'environnement FiveM
  3. Modèles GTA V : Support de tous les modèles standards du jeu
  4. Extensibilité : Architecture modulaire facilement extensible

📞 SUPPORT TECHNIQUE

Diagnostic de Problèmes

  1. Vérifier les logs : Rechercher les erreurs dans les niveaux ERROR et SECURITY
  2. Tester l'authentification : Vérifier la séquence d'authentification complète
  3. Valider les modèles : Contrôler l'existence des modèles NPCs avec IsModelInCdimage
  4. Vérifier la compilation : S'assurer que les deux DLL sont présentes et à jour

Ressources de Debugging

  • Logs détaillés avec composants et timestamps
  • Validation de structure des messages en temps réel
  • Monitoring des sessions d'authentification
  • Traces complètes du chargement des modèles NPCs

Cette architecture v2.1.0 garantit une compatibilité FiveM native, une communication sécurisée optimisée et une gestion NPCs robuste sans les problèmes de dépendances qui affectaient les versions précédentes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 99.8%
  • Lua 0.2%