samp.directory
← Scripts et bibliothèques

Hutman4kov/DayZ-SAMP-Project-v2.0

DayZ survival gamemode for SA-MP with fully rewritten NPC AI (navmesh navigation, player-grade bot collision, smart zombies & marauders) + Linux port. v2.0

Gamemode★ 1mis à jour août 2026BSD-3-ClausePawn
Ouvrir sur GitHub

README.md

DayZ S.A.M.P Project v2.0

A DayZ survival gamemode for SA-MP (San Andreas Multiplayer) with fully rewritten NPC AI — real navmesh navigation, player-grade bot collision, smart zombies & marauders, plus a complete Linux port.

Survival-режим DayZ для SA-MP с полностью переписанным ИИ NPC: настоящая навигация по навмешу, физическая коллизия ботов «как у игрока», умные зомби и мародёры и полноценный порт на Linux.

Languages / Языки: English · Русский

⚠️ Heads-up: This repository contains the source code (Pawn gamemode + filterscripts + includes). The compiled server, plugins (.dll/.so), and the navmesh data files (~1.3 GB) are distributed in the Releases as a downloadable archive. Production secrets (DB password, RCON password) and the player database dump have been removed — see Setup.


English

About

This project is based on the original DayZ S.A.M.P Project by ZombiedEronix (released as open source in 2023). Over ~2 months the NPC stack was rebuilt from the ground up:

  • The NPC AI (zombies and marauders) was completely rewritten.
  • Added real navmesh navigation (Recast/Detour).
  • Added player-grade physical collision for bots (swept-capsule).
  • Built a full self-contained Linux port.

In the original, NPCs existed but their AI was broken — zombies phased through fences and walls, got stuck, teleport-"hopped" across the map and ignored world geometry. In this build NPCs get real navigation and real collision, so they behave like proper enemies.

Honest note: this is a technically hard problem and not everything can be made 100% perfect. Occasional bot-behaviour defects and rare bugs are possible, but the build squeezes out as much as possible and is still being improved.

What's new in v2.0

NPC AI & navigation
  • Real navmesh navigation (Recast/Detour): a navigation mesh built for the whole map (full_sa.navmesh, 4489 tiles, ~125 MB), driven by a dedicated dayz_navmesh plugin. Bots route around buildings, fences and obstacles instead of walking straight through them. The original had no navmesh at all.
  • Player-grade physical collision: a continuous swept-capsule (convexSweepTest via Bullet/ColAndreas) was added to a fork of FCNPC. The bot collides with the world by its body and cannot slip through a thin fence or wall between movement frames. Includes collide-and-slide along walls. Toggles: /sweep on|off, /sweepstats.
  • Precise navmesh carving for fences & building walls: impassable strips are carved for every fence so bots go around; building walls are sealed while doorways stay open so NPCs can enter.
  • Smart horde navigation (flow-field): the dayz_pathfind plugin builds a gradient field per player so the horde spreads and flows around buildings instead of piling against a wall.
  • Spatial index (dayz_spatial): fast nearest-target / nearest-bot lookup via spatial hashing — no full object scan every frame.
  • Unified AI core (dayz_ai): on Windows the three AI plugins (spatial, pathfind, marauder_ng) are merged into one dayz_ai.dll; on Linux they ship as three separate modules.
Zombies
  • On-demand spawning around players: zombies appear only near real players. By day a city keeps ~7 zombies at 100–190 m, scattered. When a player leaves, stragglers are removed and the group respawns around the new location. No players → no zombies, so the server doesn't waste resources.
  • Sound + sight aggro with stealth: every action makes its own noise radius — gunshot ~900 m, vehicle ~120 m, running ~50 m, while quiet walking/crouching is nearly silent. A noisy player is seen up to 250 m in line of sight. Sneak quietly and you can slip past.
  • Two zombie types + FSM logic: normal (runs) and sprinter. Behaviour is a finite state machine: IDLE, ALERT, CHASE, ATTACK, plus OBSERVE and WATCHING (when the player is on a roof, bots circle below).
  • Day/night cycle + night "stalkers": nights get genuinely brutal. 13 zombies come for the player — 4 normal and 9 "stalkers" (fast and very tanky, ~6 headshots or ~60 body shots). At night all infected notice the player up to 700 m vs 120 m by day. Stalkers retreat at dawn. Night is the real danger.
  • Playable zombie: dying to a zombie or infection respawns you as a controllable zombie (random skin, bite infection, ~2-storey jump, red overlay; ~3–4 headshots to kill). Spawns at the death spot; NPC zombies leave their own kind alone.
Marauders
  • Three factions: bandits, survivors and military (BANDIT / SURVIVOR / MILITARY), each with its own behaviour. FSM: PATROL, ALERT, ENGAGE, INVESTIGATE, FLEE. They occupy ~20 map points (1–4 each): military at Area 51 (armoured, M4), groups in San Fierro, Grove Street, near LSPD, LS hospital, Las Venturas and 8 towns (Angel Pine, Dillimore, Montgomery, Blueberry, Palomino Creek, Bayside, El Quebrados, Fort Carson). While no player is within ~700 m, a point sleeps.
  • Navmesh navigation (MarDrive): they route over the mesh anchored to their patrol point, go around structures and hold their zone.
  • Cover map: under fire or at low HP a marauder finds the nearest cover (ai_cover_map.bin) and fires from behind it.
  • Squads & revenge: they come out in pairs. Kill one and the partner plus allies within ~200 m converge, investigate and start hunting the shooter — the group reacts to losses rather than acting like loners.
New gameplay systems
  • Visual body armor: worn armor shows as a tactical vest (model 19142) — appears with armor, disappears without it. Works on any skin, for players and marauders.
  • Crafting (/craft): "ingredient + ingredient = result" recipes. E.g. bandage + antibiotic = first-aid kit, 2 shotgun shells = Desert Eagle round, 2 wooden walls = a large wall. The original had no crafting.
  • Extended bandaging (4 new meds): tourniquet slows bleeding, clean cloth stops it cleanly, dirty cloth stops it but with an 80% infection chance, gauze (hospital loot) stops it fully. All tied into the wound/infection system.
  • Item trading (/trade): /trade [ID] [item] [qty] hands items to a nearby player (≤5 m) with a dialog confirmation.
  • Sleep (/sleep): lies the character down for 60 s, restoring HP. Safe-only — won't let you sleep near zombies, in water, in a car, while bleeding or with a heavy infection.
  • Quest bonus items: besides money, NPC quests grant an item set per stage (kits, ammo, water…). If the backpack is full, the bonus drops to the ground nearby.
  • Clan box (/klanbox): a clan member places a storage crate (costs a wooden wall + tools). It binds to the clan by password, is shared by members and persists in the database.
  • Weather events — cold waves: a cold wave occasionally arrives (with an on-screen warning); body temperature drops and you must warm up by a fire or in a vehicle.
Fixes (bugs & security)
  • Closed multiple SQL injections (escaping + moving queries to async).
  • Closed remote overflows via network packets (RPC sscanf overflow).
  • Removed money "printers" (negative item deletion).
  • Closed array out-of-bounds (inventory, dialog lists, chat reads, random indices).
  • Added access guards to griefer/admin commands; anti-cheat re-enables after /god-off.
  • Fixed jerry-can refuelling (tank tops up to full).
  • Fixed kill-credit (guards for suicide and disconnect).
  • Removed zombie phasing and sticking — no teleport hops, no fence "gluing", no walking through walls.
Optimization
  • Per-frame cache of player positions — no repeated native calls in the zombie tick.
  • Flow-field updates via a "dirty list" of cells instead of clearing the whole field each round.
  • Spatial hashing — nearest lookups in ~O(1), no full NPC scan.
  • FCNPC collision optimized: a chest-point pre-check yields ~5× fewer heavy ray checks.
  • Tuned nav tick rate (NavDrive 100 ms) — smooth movement without load spikes.
  • Spawn scales with population: zombies-per-player are capped by a fair share (MAX_BOTS / player count), so load is predictable at 20–50 players.
  • Profiler wired in (HTML gamemode profiling).
  • Removed always-spinning idle NPCs — no CPU spent where there are no players.
Plugins & technical

New AI stack vs the original:

  • dayz_navmesh — navmesh navigation (Detour)
  • dayz_ai — unified AI core (spatial + pathfind + marauder_ng; separate on Linux)
  • dayz_spatial — spatial index
  • dayz_pathfind — horde navigation (flow-field)
  • dayz_marauder_ng — marauder logic
  • FCNPC (custom fork) — bot controller (collide-slide, swept-capsule, hardening)
  • profiler, YSF, rustext — service plugins

Base official plugins (as in the original): ColAndreas, mysql, streamer, sscanf, pawncmd (Pawn.CMD), pawnraknet, crashdetect. 13 plugins load in total. Removed as unneeded: FCNPC-DL, MapAndreas, sattp, discord-connector.

Linux port: a full self-contained Linux package, plugins rebuilt for 32-bit SA-MP (ELF32, static linking), with a detailed install guide and MD5 checksums. Runs on both Windows and Linux.

Base survival systems (from the original, preserved)

Inventory (with item trading & dropping, backpack slots) · world loot & item spawning · hunger, thirst, temperature, blood, armor · diseases & infection · anomalies · vehicles (fuel, tires, durability, repair) · password-protected storage boxes · campfires, jerry-cans, medicine · weapons, ammo, equipment · admin command panel · radio, chat, reports, private messages.

Setup / Настройка

This repo holds the source only. To run a server you need the binaries/plugins/maps from the Release archive.

  1. Download the full server archive from Releases and unpack it.
  2. MySQL: create a database and import the schema. Then fill in your credentials in gamemodes/dayz/secrets.inc:
    #define SQL_HOST   "127.0.0.1"
    #define SQL_USER   "YOUR_DB_USER"
    #define SQL_DB     "YOUR_DB_NAME"
    #define SQL_PASS   "YOUR_DB_PASSWORD"
    

    The production credentials and the player-database dump were removed before publishing. secrets.inc is shipped with placeholders.

  3. server.cfg: set your own rcon_password (it ships as CHANGE_ME).
  4. Compile the gamemode:
    ./pawno/pawncc.exe -i"./pawno/include" -i"./gamemodes" "./gamemodes/dayz.pwn" -o"./gamemodes/dayz.amx"
    
    Expected: 0 errors, a few cosmetic warnings.
  5. Start the server (samp-server.exe, or heal_and_start.ps1 which re-bakes the navmesh from learned hotspots before starting). On Linux see linux/INSTALL_LINUX.txt.

⚠️ Source encoding: dayz.pwn and all gamemodes/dayz/*.inc are stored in CP1251 (Windows-1251), not UTF-8. Edit them with a byte-preserving method (not a naive UTF-8 editor) or you'll corrupt the Russian strings.

Credits

  • Original: ZombiedEronix — DayZ S.A.M.P Project (open-sourced in 2023).
  • v2.0 (2026): X666Murzikov — rewrote the NPC AI (navmesh, collision, zombies & marauders), optimization, new systems, Linux port.

License

Includes the SA-MP server LICENSE (Copyright © 2016 BlueG, BSD-style). Third-party plugins retain their own licenses. This gamemode is shared in the same open-source spirit as the original.


Русский

О проекте

За основу взята оригинальная сборка DayZ S.A.M.P Project от ZombiedEronix (выложена в OpenSource в 2023). За ~2 месяца стек NPC переделан с нуля:

  • ИИ NPC (зомби и мародёры) полностью переписан.
  • Добавлена настоящая навигация по навмешу (Recast/Detour).
  • Добавлена физическая коллизия ботов «как у игрока» (swept-capsule).
  • Сделан полноценный самодостаточный порт на Linux.

В оригинале NPC были, но их ИИ был сломан — зомби проходили сквозь заборы и стены, застревали, телепортами «прыгали» по карте и игнорировали геометрию мира. В этой сборке NPC получили реальную навигацию и реальную коллизию, поэтому ведут себя как полноценные противники.

Сразу честно: задача технически тяжёлая, всё на 100% реализовать как хотелось бы нельзя. Возможны отдельные дефекты и редкие баги в поведении ботов, но я выжал из неё максимум и продолжаю дорабатывать.

Что нового в v2.0

ИИ и навигация NPC
  • Настоящая навигация по навмешу (Recast/Detour): построена навигационная сетка на всю карту (full_sa.navmesh, 4489 тайлов, ~125 МБ), за неё отвечает отдельный плагин dayz_navmesh. Боты строят маршрут по сетке и обходят здания, заборы и препятствия, а не идут по прямой сквозь дома. В оригинале навмеша не было вообще.
  • Физическая коллизия ботов «как у игрока»: в форк FCNPC добавлена непрерывная капсульная развёртка (swept-capsule, convexSweepTest через Bullet/ColAndreas). Бот упирается в мир телом и не проходит сквозь тонкий забор или стену между кадрами движения. Сделано скольжение вдоль стены (collide-and-slide). Команды: /sweep on|off, /sweepstats.
  • Точная резка навмеша под заборы и стены зданий: для всех заборов прорезаны непроходимые полосы — боты обходят забор. Стены зданий запечатаны, но дверные проёмы открыты, чтобы NPC заходили внутрь.
  • Умная навигация орды (flow-field): плагин dayz_pathfind строит поле-градиент на каждого игрока, орда растекается и обходит здания, а не сбивается в кучу у стены.
  • Пространственный индекс (dayz_spatial): быстрый поиск ближайших целей и ботов через пространственное хеширование, без перебора всех объектов на каждый кадр.
  • Единое ядро ИИ (dayz_ai): на Windows три AI-плагина (spatial, pathfind, marauder_ng) объединены в один dayz_ai.dll, на Linux идут тремя отдельными модулями.
Зомби
  • Спавн «по требованию» вокруг игроков: зомби появляются только рядом с реальными игроками. Днём в городе держится ~7 зомби на дистанции 100–190 м, вразброс. Когда игрок уходит, отставшие убираются, а группа спавнится вокруг нового места. Без игроков зомби нет, сервер не тратит ресурсы впустую.
  • Аггро по звуку и зрению со стелсом: каждое действие создаёт свой радиус шума — выстрел ~900 м, транспорт ~120 м, бег ~50 м, а тихая ходьба и присед почти бесшумны. Шумного игрока зомби видят до 250 м по прямой видимости. Крадёшься тихо — можно пройти мимо.
  • Два вида зомби и FSM-логика: обычный (бежит) и бегун (спринт). Поведение на конечном автомате: IDLE, ALERT, CHASE, ATTACK, плюс OBSERVE и WATCHING (когда игрок на крыше, бот ходит внизу).
  • Смена дня и ночи и ночные «сталкеры»: ночью становится по-настоящему жарко. На игрока выходит 13 зомби, из них 4 обычных и 9 «сталкеров» — быстрых и очень живучих (~6 выстрелов в голову или ~60 в тело). Ночью все заражённые замечают игрока до 700 м против 120 м днём. На рассвете сталкеры отступают. Ночь — самое опасное время.
  • Играбельный зомби: при смерти от зомби или инфекции игрок возрождается управляемым зомби (случайный скин, заражение укусом, высокий прыжок ~2 этажа, красный оверлей; в голову ~3–4 выстрела). Спавн на месте смерти, NPC-зомби своего не трогают.
Мародёры
  • Три фракции: бандиты, выжившие и военные (BANDIT / SURVIVOR / MILITARY), у каждой своё поведение. FSM: PATROL, ALERT, ENGAGE, INVESTIGATE, FLEE. Стоят по ~20 точкам карты (по 1–4 на точку): военные на Зоне 51 (в броне и с M4), группы в Сан-Фиерро, на Грув-Стрит, у LSPD, у больницы Лос-Сантоса, в Лас-Вентурасе и по 8 посёлкам (Эйнджел-Пайн, Диллимор, Монтгомери, Блюберри, Паломино-Крик, Бэйсайд, Эль-Кебрадос, Форт-Карсон). Пока игрока нет рядом (~700 м), точка спит.
  • Навигация по навмешу (MarDrive): строят маршрут по сетке с привязкой к точке патруля, обходят строения и держатся своей зоны.
  • Карта укрытий: под огнём и при падении HP мародёр находит ближайшее укрытие (ai_cover_map.bin) и ведёт огонь из-за него.
  • Отряды и месть за своих: выходят парами. Убьёшь одного — напарник и союзники в ~200 м идут к месту, осматривают и начинают искать стрелка. Группа реагирует на потери, а не действует как одиночки.
Новые геймплейные системы
  • Визуальный бронежилет: надетая броня показывается тактическим жилетом (модель 19142), появляется при наличии брони и пропадает без неё. Работает на любом скине, и у игроков, и у мародёров.
  • Крафт (/craft): рецепты «ингредиент + ингредиент = результат». Например, бинт + антибиотик = аптечка, 2 патрона дробовика = патрон Desert Eagle, 2 деревянные стенки = большая стенка. В оригинале крафта не было.
  • Расширенная перевязка (4 новых медикамента): жгут замедляет кровь, чистая ткань останавливает без последствий, грязная ткань останавливает но с 80% шансом инфекции, марля (больничный лут) останавливает полностью. Всё завязано на систему ран и инфекции.
  • Передача предметов (/trade): /trade [ID] [предмет] [кол-во] передаёт вещи соседу (до 5 м) с подтверждением через диалог.
  • Сон (/sleep): укладывает персонажа спать на 60 секунд с восстановлением HP. Только в безопасности — не даст лечь рядом с зомби, в воде, в машине, при кровотечении или тяжёлой инфекции.
  • Бонус-предметы за квесты: кроме денег, за NPC-квесты дают набор предметов под каждый этап (аптечки, патроны, вода и т.д.). Если в рюкзаке нет места, бонус падает на землю рядом.
  • Клан-бокс (/klanbox): участник клана ставит ящик-хранилище (расходует деревянную стенку + инструменты). Бокс привязывается к клану по паролю, доступен всем членам и сохраняется в базе.
  • Погодные события — холодные волны: иногда приходит холодная волна (с предупреждением на экране), температура тела падает, и чтобы не замёрзнуть, надо греться у костра или в транспорте.
Что исправлено (баги и безопасность)
  • Закрыл множественные SQL-инъекции (экранирование + перевод запросов на асинхронные).
  • Закрыл удалённые переполнения через сетевые пакеты (RPC sscanf overflow).
  • Убрал «печатные станки» денег (отрицательное удаление предметов).
  • Закрыл выходы за границы массивов (инвентарь, списки в диалогах, чтение чата, индексы random).
  • Поставил гарды доступа на грифер-команды и админ-функции, анти-чит снова включается после /god-off.
  • Починил заправку канистрой (бак дозаправляется до полного).
  • Починил зачёт убийства (гарды на самоубийство и дисконнект).
  • Убрал фазу и застревание зомби — нет прыжков-телепортов, «прилипания» к заборам и прохода сквозь стены.
Оптимизация
  • Кэш позиций игроков раз в кадр — нет повторных нативных вызовов в тике зомби.
  • Flow-field обновляется по «грязному списку» ячеек, а не чистит всё поле каждый раунд.
  • Пространственное хеширование — поиск ближайших почти за O(1), без перебора всех NPC.
  • Оптимизирована коллизия FCNPC: предпроверка по грудной точке даёт примерно в 5 раз меньше тяжёлых лучевых проверок.
  • Подобрана частота навигационного тика (NavDrive 100 мс) — ход плавный, без скачков нагрузки.
  • Спавн масштабируется под онлайн: число зомби на игрока режется по честной доле (потолок MAX_BOTS делится на число игроков), нагрузка предсказуема на 20–50 игроков.
  • Подключён профайлер (HTML-профилирование геймода).
  • Убраны лишние «постоянно крутящиеся» NPC — сервер не тратит CPU там, где нет игроков.
Плагины и техническое

Lire la suite sur GitHub

Cette page est construite à partir de ce que GitHub publie sur le dépôt. samp.directory n’héberge pas le code. Signaler un problème avec cette fiche

Hutman4kov/DayZ-SAMP-Project-v2.0 : Gamemode SA-MP | samp.directory