diff --git a/CLAUDE.md b/CLAUDE.md
index d87af13..04d747f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -21,13 +21,17 @@ renderer, camera, sprites), `Input`, `Audio`, `Assets` (runtime loading, no cont
pipeline), `Assets.Generator` (Roslyn source generator for typed asset handles),
`Atlases` (texture-atlas builder + runtime loader; CLI wrapper in `tools/MrGameEng.AtlasTool`),
`Tilemaps` (code-built tile grids rendered through the batcher; `scene.UseTilemaps()`
-after `UseRenderer2D()`), `UI` (Myra integration: `scene.UseUI()` after `UseRenderer2D()`),
+after `UseRenderer2D()`), `Pathfinding` (grid A*/Dijkstra/BFS and flow fields over a
+game-implemented `IPathGrid`; Core-only, owns no world data), `Collisions` (`Collider`
+component, spatial hash rebuilt per tick, pairs/queries/raycast; `scene.UseCollisions()`
+after movement systems), `UI` (Myra integration: `scene.UseUI()` after `UseRenderer2D()`),
`DevConsole` (in-game console capturing `Core.Log`; `scene.UseDevConsole()` last in OnLoad).
Dependency rule: every module may depend only on `Core`; `Core` depends only on
MonoGame and Friflo.Engine.ECS. `Assets.Generator` is a netstandard2.0 analyzer.
Documented exceptions: Myra renders with its own SpriteBatch internally; `Atlases`
depends on `Graphics` (Texture2DRegion) and `Assets` (loader registration);
-`Tilemaps` depends on `Graphics` (regions, layers, renderer).
+`Tilemaps` depends on `Graphics` (regions, layers, renderer);
+`Collisions` depends on `Graphics` (Transform2D, RectF).
## Commands
diff --git a/MrGameEng.sln b/MrGameEng.sln
index 50ca30d..fc2374f 100644
--- a/MrGameEng.sln
+++ b/MrGameEng.sln
@@ -49,6 +49,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Tilemaps", "src\M
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Tilemaps.Tests", "tests\MrGameEng.Tilemaps.Tests\MrGameEng.Tilemaps.Tests.csproj", "{10B318BB-BB00-4A9D-8AF3-D36C570B6286}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Pathfinding", "src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj", "{84064C54-688F-4A58-9EC6-BFD478816306}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Collisions", "src\MrGameEng.Collisions\MrGameEng.Collisions.csproj", "{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Pathfinding.Tests", "tests\MrGameEng.Pathfinding.Tests\MrGameEng.Pathfinding.Tests.csproj", "{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Collisions.Tests", "tests\MrGameEng.Collisions.Tests\MrGameEng.Collisions.Tests.csproj", "{B8C132F5-C4C8-4931-B0CE-885811F44DB0}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -287,6 +295,54 @@ Global
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x64.Build.0 = Release|Any CPU
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x86.ActiveCfg = Release|Any CPU
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x86.Build.0 = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x64.Build.0 = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x86.Build.0 = Debug|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|Any CPU.Build.0 = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|x64.ActiveCfg = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|x64.Build.0 = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|x86.ActiveCfg = Release|Any CPU
+ {84064C54-688F-4A58-9EC6-BFD478816306}.Release|x86.Build.0 = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x64.Build.0 = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x86.Build.0 = Debug|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x64.ActiveCfg = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x64.Build.0 = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x86.ActiveCfg = Release|Any CPU
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x86.Build.0 = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x64.Build.0 = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x86.Build.0 = Debug|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x64.ActiveCfg = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x64.Build.0 = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x86.ActiveCfg = Release|Any CPU
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x86.Build.0 = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x64.Build.0 = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x86.Build.0 = Debug|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x64.ActiveCfg = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x64.Build.0 = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x86.ActiveCfg = Release|Any CPU
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -311,5 +367,9 @@ Global
{1951D50B-122A-45B5-9356-F186A3CBC974} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
{10B318BB-BB00-4A9D-8AF3-D36C570B6286} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
+ {84064C54-688F-4A58-9EC6-BFD478816306} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {E069CBFD-F4FA-4400-84AE-090F9B81BDFC} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
+ {B8C132F5-C4C8-4931-B0CE-885811F44DB0} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
diff --git a/docs/architecture.md b/docs/architecture.md
index 368e12d..ae9612d 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -35,6 +35,8 @@
| `MrGameEng.Assets.Generator` | Roslyn incremental source generator: классы с типизированными хендлами ресурсов |
| `MrGameEng.Atlases` | Текстурные атласы: офлайн-сборка из дерева картинок (`AtlasBuilder`) и рантайм-загрузка (`TextureAtlas`); CLI — `tools/MrGameEng.AtlasTool` |
| `MrGameEng.Tilemaps` | Тайловые карты, создаваемые кодом: `TileGrid` + `TileSet` + компонент `Tilemap`, отрисовка видимых клеток через батчер |
+| `MrGameEng.Pathfinding` | Поиск пути по гриду: A*, Dijkstra, BFS и flow fields для толп; чистая логика без зависимостей |
+| `MrGameEng.Collisions` | Определение столкновений: компонент `Collider`, spatial hash, пары/запросы/raycast |
| `MrGameEng.UI` | Игровой UI на [Myra](https://github.com/rds1983/Myra): `Desktop` на сцену, виджеты, скининг |
| `MrGameEng.DevConsole` | Ингейм-консоль разработчика: логи `Log`, команды, история, автодополнение |
@@ -183,6 +185,41 @@ CLI-обёртка: `dotnet run --project tools/MrGameEng.AtlasTool -- <исто
от экрана, а не от размера грида. Тайлы батчатся со спрайтами по обычному порядку
слой → depth → текстура: пол из одной текстуры атласа — один draw call.
+## Поиск пути
+
+`MrGameEng.Pathfinding` — алгоритмы поиска пути по гриду; зависит только от Core
+и не владеет данными мира — игра реализует `IPathGrid` (Width/Height,
+`IsPassable`, `Cost ≥ 1`) поверх своего рельефа или `TileGrid`.
+
+- `GridPathfinder.FindPath(start, goal, path, algorithm)` — **A\*** (octile/Manhattan
+ эвристика), **Dijkstra** (с учётом цены клеток) и **BFS** (быстрейший для
+ равномерных гридов, цену игнорирует). Связность 4 или 8; диагонали никогда
+ не срезают углы.
+- `FlowFieldBuilder.Build(goals, field)` — multi-source Dijkstra строит **flow field**:
+ дистанция + нормализованное направление на клетку. Толпа любого размера дальше
+ стоит O(1) на агента в кадр — основной инструмент для масс агентов (LittleSim).
+- Оптимизация под ECS: все буферы созданы один раз под размер грида и
+ инвалидируются generation-штампом — повторные запросы не аллоцируют и не чистят
+ массивы. Один экземпляр на систему; результаты детерминированы.
+
+## Коллизии
+
+`MrGameEng.Collisions` — определение столкновений (без разрешения физики — она в бэклоге):
+
+- Компонент `Collider` (`struct : IComponent`): круг или AABB (без вращения),
+ `Offset`, битовые маски `Layer`/`CollidesWith` (пара регистрируется, только если
+ маски согласны в обе стороны). Создание через `Collider.Circle(r)` / `Collider.Box(w,h)`.
+- `CollisionWorld` — uniform spatial hash на плоских массивах (головы бакетов +
+ связные списки индексов), **перестраивается с нуля каждый тик** за O(n): для
+ движущихся сущностей это дешевле инкрементальных обновлений. Ноль аллокаций
+ после прогрева; порядок пар детерминирован (порядок чанков Friflo).
+- `scene.UseCollisions(cellSize)` добавляет `CollisionSystem` — регистрируй её
+ **после** систем движения; системы, читающие `world.Pairs`, — после неё.
+- Запросы для игровых систем: `Pairs` (пересекающиеся пары кадра),
+ `QueryAabb(rect, span)`, `Raycast(from, to, mask)` (ближайшее попадание).
+- `cellSize` подбирается под типичный размер коллайдера; крупные коллайдеры
+ занимают несколько ячеек — корректность не страдает, страдает константа.
+
## Рендеринг
`SpriteBatch` в движке **не используется** — в `MrGameEng.Graphics` свой батчер,
diff --git a/samples/MrGameEng.Sample/MrGameEng.Sample.csproj b/samples/MrGameEng.Sample/MrGameEng.Sample.csproj
index c75a03f..7565eca 100644
--- a/samples/MrGameEng.Sample/MrGameEng.Sample.csproj
+++ b/samples/MrGameEng.Sample/MrGameEng.Sample.csproj
@@ -13,6 +13,8 @@
+
+
audio.Play(beep));
+ console.Register("path", "switch to the pathfinding & collisions demo", (_, _) =>
+ {
+ if (!Context.Scenes.IsTransitioning)
+ {
+ Context.Scenes.Switch(new PathfindingScene(), Transition.Fade(0.6f));
+ }
+ });
console.Register("atlas", "list texture atlas regions", (c, _) =>
{
c.WriteLine($"atlas '{atlas.Name}': {atlas.Pages.Count} page(s), {atlas.Regions.Count} region(s)");
diff --git a/samples/MrGameEng.Sample/Scenes/PathfindingScene.cs b/samples/MrGameEng.Sample/Scenes/PathfindingScene.cs
new file mode 100644
index 0000000..3baa2c3
--- /dev/null
+++ b/samples/MrGameEng.Sample/Scenes/PathfindingScene.cs
@@ -0,0 +1,284 @@
+using Friflo.Engine.ECS;
+using Friflo.Engine.ECS.Systems;
+using Microsoft.Xna.Framework;
+using MrGameEng.Assets;
+using MrGameEng.Collisions;
+using MrGameEng.Core;
+using MrGameEng.DevConsole;
+using MrGameEng.Graphics;
+using MrGameEng.Input;
+using MrGameEng.Pathfinding;
+using MrGameEng.UI;
+
+namespace MrGameEng.Sample.Scenes;
+
+///
+/// Демо поиска пути и коллизий: ЛКМ ставит цель — толпа агентов стекается к ней по
+/// flow field, жёлтым подсвечен A*-путь из левого верхнего угла, столкнувшиеся агенты
+/// вспыхивают красным. Tab/'main' — назад.
+///
+public sealed class PathfindingScene : Scene
+{
+ private const int CellsX = 64;
+ private const int CellsY = 36;
+ private const int CellSize = 20;
+ private const int AgentCount = 250;
+ private static readonly Point AStarStart = new(1, 1);
+
+ private readonly WallGrid _grid = new(CellsX, CellsY, seed: 99);
+ private readonly FlowField _field = new();
+ private readonly List _path = [];
+ private readonly List _pathMarkers = [];
+ private FlowFieldBuilder _builder = null!;
+ private GridPathfinder _pathfinder = null!;
+ private Texture2DRegion _white = null!;
+ private Entity _goalMarker;
+
+ /// Состояние агента: время красной вспышки после столкновения.
+ private struct AgentState : IComponent
+ {
+ public float Flash;
+ }
+
+ protected override void OnLoad()
+ {
+ var assets = Context.Services.GetOrDefault() ?? Context.UseAssets();
+ var input = this.UseInput();
+ var actions = SampleInput.CreateActions(input);
+ var renderer = this.UseRenderer2D(new Renderer2DOptions { VirtualResolution = new Point(1280, 720) });
+ SampleLayers.EnsureRegistered(renderer);
+
+ var shapesTexture = assets.Load(GameAssets.Textures.Shapes);
+ _white = new Texture2DRegion(shapesTexture, new Rectangle(40, 41, 14, 14)); // жёлтый квадрат как "белый" регион
+ _builder = new FlowFieldBuilder(_grid);
+ _pathfinder = new GridPathfinder(_grid);
+
+ // Стены.
+ for (var y = 0; y < CellsY; y++)
+ {
+ for (var x = 0; x < CellsX; x++)
+ {
+ if (!_grid.IsPassable(x, y))
+ {
+ var sprite = new Sprite(_white) { Color = new Color(70, 74, 84), Depth = 0f };
+ Store.CreateEntity(CellTransform(x, y), sprite);
+ }
+ }
+ }
+
+ // Агенты на проходимых клетках.
+ var random = new Random(7);
+ for (var i = 0; i < AgentCount; i++)
+ {
+ var cell = RandomPassableCell(random);
+ var sprite = new Sprite(_white) { Color = new Color(120, 180, 255), Depth = 1f };
+ sprite.CenterOrigin();
+ Store.CreateEntity(
+ new Transform2D(CellCenter(cell), scale: new Vector2(0.45f)),
+ sprite,
+ new AgentState(),
+ Collider.Circle(4f));
+ }
+
+ // Маркер цели.
+ var goalSprite = new Sprite(_white) { Color = new Color(80, 220, 120), Depth = 0.6f };
+ _goalMarker = Store.CreateEntity(CellTransform(0, 0), goalSprite);
+
+ var world = this.UseCollisions(cellSize: 16f);
+
+ UpdateSystems.Add(new ClickTargetSystem(this, input, renderer));
+ UpdateSystems.Add(new AgentSteerSystem(this));
+ UpdateSystems.Add(new CollisionFlashSystem(world));
+ UpdateSystems.Add(new FlashDecaySystem());
+ UpdateSystems.Add(new SceneHotkeysSystem(Context, actions, () => new MainScene(), Transition.Fade(0.6f)));
+
+ var desktop = this.UseUI();
+ var label = new Myra.Graphics2D.UI.Label
+ {
+ Text = "ЛКМ — цель: толпа идёт по flow field, жёлтое — путь A*.\nСтолкновения агентов подсвечиваются красным. Tab — назад.",
+ };
+ desktop.Root = new Myra.Graphics2D.UI.VerticalStackPanel { Left = 12, Top = 12 };
+ ((Myra.Graphics2D.UI.VerticalStackPanel)desktop.Root).Widgets.Add(label);
+
+ this.UseDevConsole();
+
+ SetGoal(new Point(CellsX / 2, CellsY / 2));
+ }
+
+ private void SetGoal(Point goal)
+ {
+ if (!_grid.IsPassable(goal.X, goal.Y))
+ {
+ return;
+ }
+
+ _builder.Build([goal], _field);
+ _goalMarker.GetComponent().Position = CellTopLeft(goal);
+
+ foreach (var marker in _pathMarkers)
+ {
+ marker.DeleteEntity();
+ }
+
+ _pathMarkers.Clear();
+ if (_pathfinder.FindPath(AStarStart, goal, _path))
+ {
+ foreach (var cell in _path)
+ {
+ var sprite = new Sprite(_white) { Color = new Color(240, 210, 60) * 0.55f, Depth = 0.5f };
+ _pathMarkers.Add(Store.CreateEntity(CellTransform(cell.X, cell.Y), sprite));
+ }
+ }
+ }
+
+ private static Transform2D CellTransform(int x, int y) =>
+ new(CellTopLeft(new Point(x, y)), scale: new Vector2(CellSize / 14f));
+
+ private static Vector2 CellTopLeft(Point cell) => new(cell.X * CellSize, cell.Y * CellSize);
+
+ private static Vector2 CellCenter(Point cell) =>
+ new(cell.X * CellSize + CellSize / 2f, cell.Y * CellSize + CellSize / 2f);
+
+ private Point RandomPassableCell(Random random)
+ {
+ while (true)
+ {
+ var cell = new Point(random.Next(CellsX), random.Next(CellsY));
+ if (_grid.IsPassable(cell.X, cell.Y))
+ {
+ return cell;
+ }
+ }
+ }
+
+ /// Случайные прямоугольные стены; старт A* и центр всегда свободны.
+ private sealed class WallGrid : IPathGrid
+ {
+ private readonly bool[,] _walls;
+
+ public WallGrid(int width, int height, int seed)
+ {
+ Width = width;
+ Height = height;
+ _walls = new bool[width, height];
+ var random = new Random(seed);
+ for (var i = 0; i < 70; i++)
+ {
+ var w = random.Next(1, 7);
+ var h = random.Next(1, 7);
+ var x0 = random.Next(width - w);
+ var y0 = random.Next(height - h);
+ for (var y = y0; y < y0 + h; y++)
+ {
+ for (var x = x0; x < x0 + w; x++)
+ {
+ _walls[x, y] = true;
+ }
+ }
+ }
+
+ for (var y = 0; y < 3; y++)
+ {
+ for (var x = 0; x < 3; x++)
+ {
+ _walls[AStarStart.X + x, AStarStart.Y + y] = false;
+ _walls[width / 2 + x - 1, height / 2 + y - 1] = false;
+ }
+ }
+ }
+
+ public int Width { get; }
+
+ public int Height { get; }
+
+ public bool IsPassable(int x, int y) => !_walls[x, y];
+
+ public float Cost(int x, int y) => 1f;
+ }
+
+ private sealed class ClickTargetSystem(PathfindingScene scene, InputManager input, Renderer2D renderer) : BaseSystem
+ {
+ protected override void OnUpdateGroup()
+ {
+ if (!input.IsMousePressed(MouseButton.Left))
+ {
+ return;
+ }
+
+ var world = renderer.ScreenToWorld(input.MousePosition.ToVector2());
+ var cell = new Point((int)(world.X / CellSize), (int)(world.Y / CellSize));
+ if (cell.X >= 0 && cell.X < CellsX && cell.Y >= 0 && cell.Y < CellsY)
+ {
+ scene.SetGoal(cell);
+ }
+ }
+ }
+
+ private sealed class AgentSteerSystem(PathfindingScene scene) : QuerySystem
+ {
+ private const float Speed = 70f;
+
+ protected override void OnUpdate()
+ {
+ var delta = Tick.deltaTime;
+ var field = scene._field;
+ foreach (var (transforms, _, _) in Query.Chunks)
+ {
+ var t = transforms.Span;
+ for (var i = 0; i < t.Length; i++)
+ {
+ ref var position = ref t[i].Position;
+ var cx = Math.Clamp((int)(position.X / CellSize), 0, CellsX - 1);
+ var cy = Math.Clamp((int)(position.Y / CellSize), 0, CellsY - 1);
+ if (!field.IsReachable(cx, cy) || field.DistanceAt(cx, cy) <= 0.6f)
+ {
+ continue; // недостижимо или уже у цели
+ }
+
+ position += field.DirectionAt(cx, cy) * (Speed * delta);
+ }
+ }
+ }
+ }
+
+ private sealed class CollisionFlashSystem(CollisionWorld world) : BaseSystem
+ {
+ protected override void OnUpdateGroup()
+ {
+ foreach (var pair in world.Pairs)
+ {
+ Flash(pair.A);
+ Flash(pair.B);
+ }
+ }
+
+ private static void Flash(Entity entity)
+ {
+ if (entity.HasComponent())
+ {
+ entity.GetComponent().Flash = 0.25f;
+ }
+ }
+ }
+
+ private sealed class FlashDecaySystem : QuerySystem
+ {
+ private static readonly Color Calm = new(120, 180, 255);
+ private static readonly Color Hit = new(235, 70, 60);
+
+ protected override void OnUpdate()
+ {
+ var delta = Tick.deltaTime;
+ foreach (var (states, sprites, _) in Query.Chunks)
+ {
+ var a = states.Span;
+ var s = sprites.Span;
+ for (var i = 0; i < a.Length; i++)
+ {
+ a[i].Flash = Math.Max(0f, a[i].Flash - delta);
+ s[i].Color = a[i].Flash > 0f ? Hit : Calm;
+ }
+ }
+ }
+ }
+}
diff --git a/src/MrGameEng.Collisions/Collider.cs b/src/MrGameEng.Collisions/Collider.cs
new file mode 100644
index 0000000..f203b64
--- /dev/null
+++ b/src/MrGameEng.Collisions/Collider.cs
@@ -0,0 +1,61 @@
+using Friflo.Engine.ECS;
+using Microsoft.Xna.Framework;
+
+namespace MrGameEng.Collisions;
+
+/// Shape of a .
+public enum ColliderShape : byte
+{
+ /// Circle of .
+ Circle,
+
+ /// Axis-aligned box of . Does not rotate with the entity.
+ Box,
+}
+
+///
+/// Collision shape component. Create via or —
+/// the struct default has no size and collides with nothing.
+/// Positions come from Transform2D; shifts the shape
+/// relative to it (entity scale and rotation are not applied to collider shapes).
+///
+public struct Collider : IComponent
+{
+ /// Shape kind.
+ public ColliderShape Shape;
+
+ /// Circle radius in world units ( only).
+ public float Radius;
+
+ /// Half extents of the box ( only).
+ public Vector2 HalfExtents;
+
+ /// Shape center offset from the entity's transform position.
+ public Vector2 Offset;
+
+ /// Bit mask of layers this collider belongs to.
+ public uint Layer;
+
+ /// Bit mask of layers this collider collides with. A pair is reported only when the masks agree both ways.
+ public uint CollidesWith;
+
+ /// Creates a circle collider on layer 1 colliding with everything.
+ public static Collider Circle(float radius, Vector2 offset = default) => new()
+ {
+ Shape = ColliderShape.Circle,
+ Radius = radius,
+ Offset = offset,
+ Layer = 1,
+ CollidesWith = uint.MaxValue,
+ };
+
+ /// Creates a box collider on layer 1 colliding with everything.
+ public static Collider Box(float width, float height, Vector2 offset = default) => new()
+ {
+ Shape = ColliderShape.Box,
+ HalfExtents = new Vector2(width / 2f, height / 2f),
+ Offset = offset,
+ Layer = 1,
+ CollidesWith = uint.MaxValue,
+ };
+}
diff --git a/src/MrGameEng.Collisions/CollisionSystem.cs b/src/MrGameEng.Collisions/CollisionSystem.cs
new file mode 100644
index 0000000..b281fe8
--- /dev/null
+++ b/src/MrGameEng.Collisions/CollisionSystem.cs
@@ -0,0 +1,60 @@
+using Friflo.Engine.ECS;
+using Friflo.Engine.ECS.Systems;
+using MrGameEng.Core;
+using MrGameEng.Graphics;
+
+namespace MrGameEng.Collisions;
+
+///
+/// Rebuilds the from every entity that has both
+/// Transform2D and . Register it after movement
+/// systems so pairs reflect this tick's final positions.
+///
+public sealed class CollisionSystem : QuerySystem
+{
+ private readonly CollisionWorld _world;
+
+ /// Creates the system for .
+ public CollisionSystem(CollisionWorld world) => _world = world;
+
+ ///
+ protected override void OnUpdate()
+ {
+ _world.BeginRebuild();
+ foreach (var (transforms, colliders, entities) in Query.Chunks)
+ {
+ var t = transforms.Span;
+ var c = colliders.Span;
+ for (var i = 0; i < t.Length; i++)
+ {
+ _world.Add(entities.EntityAt(i), in t[i], in c[i]);
+ }
+ }
+
+ _world.EndRebuild();
+ }
+}
+
+/// Wires collision detection into a .
+public static class SceneCollisionsExtensions
+{
+ ///
+ /// Returns the shared service (created on first use with
+ /// ) and adds to this scene's
+ /// update phase. Call from OnLoad after adding movement systems; read
+ /// from systems registered later.
+ ///
+ public static CollisionWorld UseCollisions(this Scene scene, float cellSize = 64f)
+ {
+ var services = scene.Context.Services;
+ var world = services.GetOrDefault();
+ if (world is null)
+ {
+ world = new CollisionWorld(cellSize);
+ services.Add(world);
+ }
+
+ scene.UpdateSystems.Add(new CollisionSystem(world));
+ return world;
+ }
+}
diff --git a/src/MrGameEng.Collisions/CollisionWorld.cs b/src/MrGameEng.Collisions/CollisionWorld.cs
new file mode 100644
index 0000000..e49bab9
--- /dev/null
+++ b/src/MrGameEng.Collisions/CollisionWorld.cs
@@ -0,0 +1,388 @@
+using Friflo.Engine.ECS;
+using Microsoft.Xna.Framework;
+using MrGameEng.Graphics;
+
+namespace MrGameEng.Collisions;
+
+/// A pair of entities whose colliders overlap this frame.
+public readonly record struct CollisionPair(Entity A, Entity B);
+
+/// Result of a .
+public readonly record struct RaycastHit(Entity Entity, Vector2 Point, float Fraction);
+
+///
+/// Broad + narrow phase collision detection over a uniform spatial hash, rebuilt from
+/// scratch every tick by — O(n) for moving entities, flat
+/// arrays only, no allocations after warm-up. Overlapping pairs are collected into
+/// (deterministic order); ad-hoc area/ray queries are available to
+/// game systems at any point after the rebuild.
+///
+public sealed class CollisionWorld
+{
+ private struct Entry
+ {
+ public Entity Entity;
+ public Vector2 Center;
+ public RectF Aabb;
+ public float Radius;
+ public Vector2 HalfExtents;
+ public uint Layer;
+ public uint CollidesWith;
+ public ColliderShape Shape;
+ }
+
+ private readonly float _cellSize;
+ private Entry[] _entries = new Entry[256];
+ private int _count;
+
+ // Spatial hash: головы бакетов + связные списки вставок (по индексу записи на ячейку).
+ private int[] _bucketHeads = new int[512];
+ private int[] _cellNext = new int[1024];
+ private int[] _cellEntry = new int[1024];
+ private int _cellCount;
+
+ private int[] _testedStamp = new int[256];
+ private CollisionPair[] _pairs = new CollisionPair[256];
+ private int _pairCount;
+
+ /// Creates a world. should match typical collider size.
+ public CollisionWorld(float cellSize = 64f)
+ {
+ if (cellSize <= 0f)
+ {
+ throw new ArgumentOutOfRangeException(nameof(cellSize));
+ }
+
+ _cellSize = cellSize;
+ }
+
+ /// Pairs found by the last rebuild.
+ public ReadOnlySpan Pairs => _pairs.AsSpan(0, _pairCount);
+
+ /// Colliders registered in the last rebuild.
+ public int Count => _count;
+
+ /// Starts a rebuild. Called by once per tick.
+ public void BeginRebuild()
+ {
+ _count = 0;
+ _cellCount = 0;
+ _pairCount = 0;
+ }
+
+ /// Registers one collider. Order of registration defines pair order (keep it deterministic).
+ public void Add(Entity entity, in Transform2D transform, in Collider collider)
+ {
+ if (_count == _entries.Length)
+ {
+ Array.Resize(ref _entries, _entries.Length * 2);
+ Array.Resize(ref _testedStamp, _entries.Length);
+ }
+
+ var center = transform.Position + collider.Offset;
+ var half = collider.Shape == ColliderShape.Circle
+ ? new Vector2(collider.Radius)
+ : collider.HalfExtents;
+
+ _entries[_count++] = new Entry
+ {
+ Entity = entity,
+ Center = center,
+ Aabb = new RectF(center.X - half.X, center.Y - half.Y, half.X * 2f, half.Y * 2f),
+ Radius = collider.Radius,
+ HalfExtents = collider.HalfExtents,
+ Layer = collider.Layer,
+ CollidesWith = collider.CollidesWith,
+ Shape = collider.Shape,
+ };
+ }
+
+ /// Builds the hash and collects all overlapping pairs.
+ public void EndRebuild()
+ {
+ BuildHash();
+ CollectPairs();
+ }
+
+ ///
+ /// Writes entities whose colliders overlap into
+ /// ; returns the count (truncated to the span length).
+ ///
+ public int QueryAabb(in RectF area, Span results)
+ {
+ var found = 0;
+ var minX = CellOf(area.Left);
+ var maxX = CellOf(area.Right);
+ var minY = CellOf(area.Top);
+ var maxY = CellOf(area.Bottom);
+ var stamp = -1; // запросы используют отрицательные штампы, чтобы не портить пары
+
+ for (var cy = minY; cy <= maxY; cy++)
+ {
+ for (var cx = minX; cx <= maxX; cx++)
+ {
+ for (var i = _bucketHeads[Bucket(cx, cy)]; i >= 0; i = _cellNext[i])
+ {
+ var entryIndex = _cellEntry[i];
+ if (_testedStamp[entryIndex] == stamp)
+ {
+ continue;
+ }
+
+ _testedStamp[entryIndex] = stamp;
+ if (_entries[entryIndex].Aabb.Intersects(area))
+ {
+ if (found == results.Length)
+ {
+ return found;
+ }
+
+ results[found++] = _entries[entryIndex].Entity;
+ }
+ }
+ }
+ }
+
+ ResetQueryStamps();
+ return found;
+ }
+
+ ///
+ /// Casts a segment and returns the closest hit among colliders whose
+ /// intersects .
+ ///
+ public bool Raycast(Vector2 from, Vector2 to, out RaycastHit hit, uint mask = uint.MaxValue)
+ {
+ hit = default;
+ var bestFraction = float.MaxValue;
+
+ for (var i = 0; i < _count; i++)
+ {
+ ref readonly var entry = ref _entries[i];
+ if ((entry.Layer & mask) == 0)
+ {
+ continue;
+ }
+
+ float fraction;
+ var found = entry.Shape == ColliderShape.Circle
+ ? RaySegmentCircle(from, to, entry.Center, entry.Radius, out fraction)
+ : RaySegmentAabb(from, to, entry.Aabb, out fraction);
+
+ if (found && fraction < bestFraction)
+ {
+ bestFraction = fraction;
+ hit = new RaycastHit(entry.Entity, Vector2.Lerp(from, to, fraction), fraction);
+ }
+ }
+
+ return bestFraction <= 1f;
+ }
+
+ private void BuildHash()
+ {
+ var buckets = _bucketHeads.Length;
+ while (buckets < _count * 2)
+ {
+ buckets *= 2;
+ }
+
+ if (buckets != _bucketHeads.Length)
+ {
+ _bucketHeads = new int[buckets];
+ }
+
+ Array.Fill(_bucketHeads, -1);
+
+ for (var i = 0; i < _count; i++)
+ {
+ ref readonly var aabb = ref _entries[i].Aabb;
+ var minX = CellOf(aabb.Left);
+ var maxX = CellOf(aabb.Right);
+ var minY = CellOf(aabb.Top);
+ var maxY = CellOf(aabb.Bottom);
+ for (var cy = minY; cy <= maxY; cy++)
+ {
+ for (var cx = minX; cx <= maxX; cx++)
+ {
+ if (_cellCount == _cellNext.Length)
+ {
+ Array.Resize(ref _cellNext, _cellNext.Length * 2);
+ Array.Resize(ref _cellEntry, _cellEntry.Length * 2);
+ }
+
+ var bucket = Bucket(cx, cy);
+ _cellEntry[_cellCount] = i;
+ _cellNext[_cellCount] = _bucketHeads[bucket];
+ _bucketHeads[bucket] = _cellCount;
+ _cellCount++;
+ }
+ }
+ }
+
+ for (var i = 0; i < _count; i++)
+ {
+ _testedStamp[i] = int.MinValue;
+ }
+ }
+
+ private void CollectPairs()
+ {
+ for (var i = 0; i < _count; i++)
+ {
+ ref readonly var a = ref _entries[i];
+ var minX = CellOf(a.Aabb.Left);
+ var maxX = CellOf(a.Aabb.Right);
+ var minY = CellOf(a.Aabb.Top);
+ var maxY = CellOf(a.Aabb.Bottom);
+
+ for (var cy = minY; cy <= maxY; cy++)
+ {
+ for (var cx = minX; cx <= maxX; cx++)
+ {
+ for (var c = _bucketHeads[Bucket(cx, cy)]; c >= 0; c = _cellNext[c])
+ {
+ var j = _cellEntry[c];
+ if (j <= i || _testedStamp[j] == i)
+ {
+ continue; // только пары (i, j>i), каждая один раз
+ }
+
+ _testedStamp[j] = i;
+ ref readonly var b = ref _entries[j];
+ if ((a.Layer & b.CollidesWith) == 0 || (b.Layer & a.CollidesWith) == 0)
+ {
+ continue;
+ }
+
+ if (Overlaps(in a, in b))
+ {
+ if (_pairCount == _pairs.Length)
+ {
+ Array.Resize(ref _pairs, _pairs.Length * 2);
+ }
+
+ _pairs[_pairCount++] = new CollisionPair(a.Entity, b.Entity);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private static bool Overlaps(in Entry a, in Entry b)
+ {
+ if (a.Shape == ColliderShape.Circle && b.Shape == ColliderShape.Circle)
+ {
+ var sum = a.Radius + b.Radius;
+ return Vector2.DistanceSquared(a.Center, b.Center) <= sum * sum;
+ }
+
+ if (a.Shape == ColliderShape.Box && b.Shape == ColliderShape.Box)
+ {
+ return a.Aabb.Intersects(b.Aabb);
+ }
+
+ // circle vs box
+ ref readonly var circle = ref a.Shape == ColliderShape.Circle ? ref a : ref b;
+ ref readonly var box = ref a.Shape == ColliderShape.Circle ? ref b : ref a;
+ var nearest = new Vector2(
+ Math.Clamp(circle.Center.X, box.Aabb.Left, box.Aabb.Right),
+ Math.Clamp(circle.Center.Y, box.Aabb.Top, box.Aabb.Bottom));
+ return Vector2.DistanceSquared(circle.Center, nearest) <= circle.Radius * circle.Radius;
+ }
+
+ private static bool RaySegmentCircle(Vector2 from, Vector2 to, Vector2 center, float radius, out float fraction)
+ {
+ fraction = 0f;
+ var d = to - from;
+ var f = from - center;
+ var a = Vector2.Dot(d, d);
+ if (a <= float.Epsilon)
+ {
+ return f.LengthSquared() <= radius * radius;
+ }
+
+ var b = 2f * Vector2.Dot(f, d);
+ var c = Vector2.Dot(f, f) - radius * radius;
+ var discriminant = b * b - 4f * a * c;
+ if (discriminant < 0f)
+ {
+ return false;
+ }
+
+ var sqrt = MathF.Sqrt(discriminant);
+ var t = (-b - sqrt) / (2f * a);
+ if (t < 0f)
+ {
+ t = (-b + sqrt) / (2f * a); // старт внутри круга
+ }
+
+ if (t < 0f || t > 1f)
+ {
+ return false;
+ }
+
+ fraction = t;
+ return true;
+ }
+
+ private static bool RaySegmentAabb(Vector2 from, Vector2 to, in RectF aabb, out float fraction)
+ {
+ fraction = 0f;
+ var d = to - from;
+ var tMin = 0f;
+ var tMax = 1f;
+
+ for (var axis = 0; axis < 2; axis++)
+ {
+ var origin = axis == 0 ? from.X : from.Y;
+ var direction = axis == 0 ? d.X : d.Y;
+ var min = axis == 0 ? aabb.Left : aabb.Top;
+ var max = axis == 0 ? aabb.Right : aabb.Bottom;
+
+ if (Math.Abs(direction) < float.Epsilon)
+ {
+ if (origin < min || origin > max)
+ {
+ return false;
+ }
+ }
+ else
+ {
+ var t1 = (min - origin) / direction;
+ var t2 = (max - origin) / direction;
+ if (t1 > t2)
+ {
+ (t1, t2) = (t2, t1);
+ }
+
+ tMin = Math.Max(tMin, t1);
+ tMax = Math.Min(tMax, t2);
+ if (tMin > tMax)
+ {
+ return false;
+ }
+ }
+ }
+
+ fraction = tMin;
+ return true;
+ }
+
+ private void ResetQueryStamps()
+ {
+ for (var i = 0; i < _count; i++)
+ {
+ if (_testedStamp[i] < 0)
+ {
+ _testedStamp[i] = int.MinValue;
+ }
+ }
+ }
+
+ private int CellOf(float coordinate) => (int)MathF.Floor(coordinate / _cellSize);
+
+ private int Bucket(int cellX, int cellY) =>
+ (int)(((uint)(cellX * 73856093 ^ cellY * 19349663)) & (uint)(_bucketHeads.Length - 1));
+}
diff --git a/src/MrGameEng.Collisions/MrGameEng.Collisions.csproj b/src/MrGameEng.Collisions/MrGameEng.Collisions.csproj
new file mode 100644
index 0000000..c594d33
--- /dev/null
+++ b/src/MrGameEng.Collisions/MrGameEng.Collisions.csproj
@@ -0,0 +1,12 @@
+
+
+
+ net8.0
+
+
+
+
+
+
+
+
diff --git a/src/MrGameEng.Pathfinding/FlowField.cs b/src/MrGameEng.Pathfinding/FlowField.cs
new file mode 100644
index 0000000..f58fa9f
--- /dev/null
+++ b/src/MrGameEng.Pathfinding/FlowField.cs
@@ -0,0 +1,244 @@
+using Microsoft.Xna.Framework;
+
+namespace MrGameEng.Pathfinding;
+
+///
+/// A flow field: per-cell distance to the nearest goal and a normalized direction to follow.
+/// Built once per goal change by , then any number of agents
+/// steer by an O(1) lookup per frame — the tool of choice for crowds heading to shared targets.
+///
+public sealed class FlowField
+{
+ /// Grid width in cells.
+ public int Width { get; private set; }
+
+ /// Grid height in cells.
+ public int Height { get; private set; }
+
+ internal float[] Distances = [];
+ internal Vector2[] Directions = [];
+
+ /// Cost-weighted distance to the nearest goal; when unreachable.
+ public float DistanceAt(int x, int y) => Distances[y * Width + x];
+
+ /// Normalized direction toward the nearest goal; at goals and unreachable cells.
+ public Vector2 DirectionAt(int x, int y) => Directions[y * Width + x];
+
+ /// True when a path to a goal exists from this cell.
+ public bool IsReachable(int x, int y) => !float.IsPositiveInfinity(Distances[y * Width + x]);
+
+ internal void EnsureSize(int width, int height)
+ {
+ Width = width;
+ Height = height;
+ var size = width * height;
+ if (Distances.Length < size)
+ {
+ Distances = new float[size];
+ Directions = new Vector2[size];
+ }
+ }
+}
+
+///
+/// Builds s with a multi-source Dijkstra over an .
+/// Buffers are reused between builds (no allocations after warm-up). One instance per system.
+///
+public sealed class FlowFieldBuilder
+{
+ private static readonly int[] OffsetX = [1, -1, 0, 0, 1, 1, -1, -1];
+ private static readonly int[] OffsetY = [0, 0, 1, -1, 1, -1, 1, -1];
+ private const float DiagonalCost = 1.4142135f;
+
+ private readonly IPathGrid _grid;
+ private readonly GridConnectivity _connectivity;
+ private readonly int _width;
+ private readonly int _height;
+ private readonly int[] _closedStamp;
+ private int[] _heapNodes;
+ private float[] _heapPriorities;
+ private int _generation;
+ private int _heapCount;
+
+ /// Creates a builder bound to .
+ public FlowFieldBuilder(IPathGrid grid, GridConnectivity connectivity = GridConnectivity.Eight)
+ {
+ _grid = grid;
+ _connectivity = connectivity;
+ _width = grid.Width;
+ _height = grid.Height;
+ var size = _width * _height;
+ _closedStamp = new int[size];
+ _heapNodes = new int[size + 1];
+ _heapPriorities = new float[size + 1];
+ }
+
+ ///
+ /// Fills with distances and directions toward the nearest of
+ /// . Impassable goals are ignored; with no valid goal the whole
+ /// field is unreachable.
+ ///
+ public void Build(ReadOnlySpan goals, FlowField field)
+ {
+ field.EnsureSize(_width, _height);
+ var distances = field.Distances;
+ var directions = field.Directions;
+ Array.Fill(distances, float.PositiveInfinity, 0, _width * _height);
+
+ _generation++;
+ _heapCount = 0;
+
+ foreach (var goal in goals)
+ {
+ if (goal.X >= 0 && goal.X < _width && goal.Y >= 0 && goal.Y < _height &&
+ _grid.IsPassable(goal.X, goal.Y))
+ {
+ var index = goal.Y * _width + goal.X;
+ distances[index] = 0f;
+ HeapPush(index, 0f);
+ }
+ }
+
+ var directionCount = (int)_connectivity;
+ while (_heapCount > 0)
+ {
+ var current = HeapPop();
+ if (_closedStamp[current] == _generation)
+ {
+ continue;
+ }
+
+ _closedStamp[current] = _generation;
+ var cx = current % _width;
+ var cy = current / _width;
+
+ for (var d = 0; d < directionCount; d++)
+ {
+ var nx = cx + OffsetX[d];
+ var ny = cy + OffsetY[d];
+ if (!Walkable(cx, cy, nx, ny, d))
+ {
+ continue;
+ }
+
+ var neighbor = ny * _width + nx;
+ var tentative = distances[current] + (d < 4 ? 1f : DiagonalCost) * _grid.Cost(nx, ny);
+ if (tentative < distances[neighbor])
+ {
+ distances[neighbor] = tentative;
+ HeapPush(neighbor, tentative);
+ }
+ }
+ }
+
+ // Направление — к соседу с минимальной дистанцией (с учётом запрета срезать углы).
+ for (var y = 0; y < _height; y++)
+ {
+ for (var x = 0; x < _width; x++)
+ {
+ var index = y * _width + x;
+ directions[index] = Vector2.Zero;
+ if (float.IsPositiveInfinity(distances[index]) || distances[index] == 0f)
+ {
+ continue;
+ }
+
+ var best = distances[index];
+ var bestDx = 0;
+ var bestDy = 0;
+ for (var d = 0; d < directionCount; d++)
+ {
+ var nx = x + OffsetX[d];
+ var ny = y + OffsetY[d];
+ if (!Walkable(x, y, nx, ny, d))
+ {
+ continue;
+ }
+
+ var distance = distances[ny * _width + nx];
+ if (distance < best)
+ {
+ best = distance;
+ bestDx = OffsetX[d];
+ bestDy = OffsetY[d];
+ }
+ }
+
+ if (bestDx != 0 || bestDy != 0)
+ {
+ directions[index] = Vector2.Normalize(new Vector2(bestDx, bestDy));
+ }
+ }
+ }
+ }
+
+ private bool Walkable(int fromX, int fromY, int toX, int toY, int direction)
+ {
+ if (toX < 0 || toX >= _width || toY < 0 || toY >= _height || !_grid.IsPassable(toX, toY))
+ {
+ return false;
+ }
+
+ return direction < 4 || (_grid.IsPassable(toX, fromY) && _grid.IsPassable(fromX, toY));
+ }
+
+ private void HeapPush(int node, float priority)
+ {
+ if (_heapCount + 1 == _heapNodes.Length)
+ {
+ Array.Resize(ref _heapNodes, _heapNodes.Length * 2);
+ Array.Resize(ref _heapPriorities, _heapPriorities.Length * 2);
+ }
+
+ var i = ++_heapCount;
+ while (i > 1 && _heapPriorities[i >> 1] > priority)
+ {
+ _heapNodes[i] = _heapNodes[i >> 1];
+ _heapPriorities[i] = _heapPriorities[i >> 1];
+ i >>= 1;
+ }
+
+ _heapNodes[i] = node;
+ _heapPriorities[i] = priority;
+ }
+
+ private int HeapPop()
+ {
+ var top = _heapNodes[1];
+ var lastNode = _heapNodes[_heapCount];
+ var lastPriority = _heapPriorities[_heapCount];
+ _heapCount--;
+
+ var i = 1;
+ while (true)
+ {
+ var child = i << 1;
+ if (child > _heapCount)
+ {
+ break;
+ }
+
+ if (child < _heapCount && _heapPriorities[child + 1] < _heapPriorities[child])
+ {
+ child++;
+ }
+
+ if (_heapPriorities[child] >= lastPriority)
+ {
+ break;
+ }
+
+ _heapNodes[i] = _heapNodes[child];
+ _heapPriorities[i] = _heapPriorities[child];
+ i = child;
+ }
+
+ if (_heapCount > 0)
+ {
+ _heapNodes[i] = lastNode;
+ _heapPriorities[i] = lastPriority;
+ }
+
+ return top;
+ }
+}
diff --git a/src/MrGameEng.Pathfinding/GridPathfinder.cs b/src/MrGameEng.Pathfinding/GridPathfinder.cs
new file mode 100644
index 0000000..3485ae7
--- /dev/null
+++ b/src/MrGameEng.Pathfinding/GridPathfinder.cs
@@ -0,0 +1,301 @@
+using Microsoft.Xna.Framework;
+
+namespace MrGameEng.Pathfinding;
+
+/// Algorithm used by .
+public enum PathAlgorithm
+{
+ /// Best general choice: cost-aware, goal-directed (octile/Manhattan heuristic).
+ AStar,
+
+ /// Cost-aware without a heuristic. Slower than A*, useful as a reference.
+ Dijkstra,
+
+ /// Fastest for uniform-cost grids; ignores .
+ BreadthFirst,
+}
+
+///
+/// Grid pathfinder with A*, Dijkstra and BFS over an .
+/// All working buffers are sized to the grid once and invalidated by a generation stamp,
+/// so repeated queries allocate nothing and never clear arrays. One instance per system
+/// (not thread-safe); results are deterministic for identical inputs.
+///
+public sealed class GridPathfinder
+{
+ private static readonly int[] OffsetX = [1, -1, 0, 0, 1, 1, -1, -1];
+ private static readonly int[] OffsetY = [0, 0, 1, -1, 1, -1, 1, -1];
+ private const float DiagonalCost = 1.4142135f;
+
+ private readonly IPathGrid _grid;
+ private readonly GridConnectivity _connectivity;
+ private readonly int _width;
+ private readonly int _height;
+
+ private readonly float[] _gScore;
+ private readonly int[] _cameFrom;
+ private readonly int[] _openStamp;
+ private readonly int[] _closedStamp;
+ private int[] _heapNodes;
+ private float[] _heapPriorities;
+ private readonly int[] _bfsQueue;
+ private int _generation;
+ private int _heapCount;
+
+ /// Creates a pathfinder bound to .
+ public GridPathfinder(IPathGrid grid, GridConnectivity connectivity = GridConnectivity.Eight)
+ {
+ _grid = grid;
+ _connectivity = connectivity;
+ _width = grid.Width;
+ _height = grid.Height;
+ var size = _width * _height;
+ _gScore = new float[size];
+ _cameFrom = new int[size];
+ _openStamp = new int[size];
+ _closedStamp = new int[size];
+ _heapNodes = new int[size + 1];
+ _heapPriorities = new float[size + 1];
+ _bfsQueue = new int[size];
+ }
+
+ ///
+ /// Finds a path from to (both inclusive)
+ /// and writes it into . Returns false when no path exists;
+ /// the list is cleared either way.
+ ///
+ public bool FindPath(Point start, Point goal, List path, PathAlgorithm algorithm = PathAlgorithm.AStar)
+ {
+ path.Clear();
+ if (!InBounds(start) || !InBounds(goal) ||
+ !_grid.IsPassable(start.X, start.Y) || !_grid.IsPassable(goal.X, goal.Y))
+ {
+ return false;
+ }
+
+ if (start == goal)
+ {
+ path.Add(start);
+ return true;
+ }
+
+ return algorithm == PathAlgorithm.BreadthFirst
+ ? BreadthFirst(start, goal, path)
+ : WeightedSearch(start, goal, path, useHeuristic: algorithm == PathAlgorithm.AStar);
+ }
+
+ private bool WeightedSearch(Point start, Point goal, List path, bool useHeuristic)
+ {
+ _generation++;
+ _heapCount = 0;
+
+ var startIndex = Index(start.X, start.Y);
+ var goalIndex = Index(goal.X, goal.Y);
+ _gScore[startIndex] = 0f;
+ _cameFrom[startIndex] = -1;
+ _openStamp[startIndex] = _generation;
+ HeapPush(startIndex, useHeuristic ? Heuristic(start.X, start.Y, goal) : 0f);
+
+ var directions = (int)_connectivity;
+ while (_heapCount > 0)
+ {
+ var current = HeapPop();
+ if (current == goalIndex)
+ {
+ Reconstruct(goalIndex, path);
+ return true;
+ }
+
+ if (_closedStamp[current] == _generation)
+ {
+ continue; // устаревшая запись кучи
+ }
+
+ _closedStamp[current] = _generation;
+ var cx = current % _width;
+ var cy = current / _width;
+
+ for (var d = 0; d < directions; d++)
+ {
+ var nx = cx + OffsetX[d];
+ var ny = cy + OffsetY[d];
+ if (!Walkable(cx, cy, nx, ny, d))
+ {
+ continue;
+ }
+
+ var neighbor = Index(nx, ny);
+ if (_closedStamp[neighbor] == _generation)
+ {
+ continue;
+ }
+
+ var stepCost = (d < 4 ? 1f : DiagonalCost) * _grid.Cost(nx, ny);
+ var tentative = _gScore[current] + stepCost;
+ if (_openStamp[neighbor] == _generation && tentative >= _gScore[neighbor])
+ {
+ continue;
+ }
+
+ _gScore[neighbor] = tentative;
+ _cameFrom[neighbor] = current;
+ _openStamp[neighbor] = _generation;
+ HeapPush(neighbor, tentative + (useHeuristic ? Heuristic(nx, ny, goal) : 0f));
+ }
+ }
+
+ return false;
+ }
+
+ private bool BreadthFirst(Point start, Point goal, List path)
+ {
+ _generation++;
+ var head = 0;
+ var tail = 0;
+
+ var startIndex = Index(start.X, start.Y);
+ var goalIndex = Index(goal.X, goal.Y);
+ _cameFrom[startIndex] = -1;
+ _openStamp[startIndex] = _generation;
+ _bfsQueue[tail++] = startIndex;
+
+ var directions = (int)_connectivity;
+ while (head < tail)
+ {
+ var current = _bfsQueue[head++];
+ if (current == goalIndex)
+ {
+ Reconstruct(goalIndex, path);
+ return true;
+ }
+
+ var cx = current % _width;
+ var cy = current / _width;
+ for (var d = 0; d < directions; d++)
+ {
+ var nx = cx + OffsetX[d];
+ var ny = cy + OffsetY[d];
+ if (!Walkable(cx, cy, nx, ny, d))
+ {
+ continue;
+ }
+
+ var neighbor = Index(nx, ny);
+ if (_openStamp[neighbor] == _generation)
+ {
+ continue;
+ }
+
+ _openStamp[neighbor] = _generation;
+ _cameFrom[neighbor] = current;
+ _bfsQueue[tail++] = neighbor;
+ }
+ }
+
+ return false;
+ }
+
+ /// True when the move is in bounds, passable and does not cut a corner.
+ private bool Walkable(int fromX, int fromY, int toX, int toY, int direction)
+ {
+ if (toX < 0 || toX >= _width || toY < 0 || toY >= _height || !_grid.IsPassable(toX, toY))
+ {
+ return false;
+ }
+
+ if (direction >= 4)
+ {
+ // Диагональ разрешена только если обе ортогональные клетки проходимы.
+ if (!_grid.IsPassable(toX, fromY) || !_grid.IsPassable(fromX, toY))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private float Heuristic(int x, int y, Point goal)
+ {
+ var dx = Math.Abs(x - goal.X);
+ var dy = Math.Abs(y - goal.Y);
+ return _connectivity == GridConnectivity.Four
+ ? dx + dy
+ : Math.Max(dx, dy) + (DiagonalCost - 1f) * Math.Min(dx, dy);
+ }
+
+ private void Reconstruct(int goalIndex, List path)
+ {
+ for (var index = goalIndex; index >= 0; index = _cameFrom[index])
+ {
+ path.Add(new Point(index % _width, index / _width));
+ }
+
+ path.Reverse();
+ }
+
+ private bool InBounds(Point p) => p.X >= 0 && p.X < _width && p.Y >= 0 && p.Y < _height;
+
+ private int Index(int x, int y) => y * _width + x;
+
+ private void HeapPush(int node, float priority)
+ {
+ // Ленивая вставка кладёт узел повторно при улучшении пути — куче нужен запас.
+ if (_heapCount + 1 == _heapNodes.Length)
+ {
+ Array.Resize(ref _heapNodes, _heapNodes.Length * 2);
+ Array.Resize(ref _heapPriorities, _heapPriorities.Length * 2);
+ }
+
+ var i = ++_heapCount;
+ while (i > 1 && _heapPriorities[i >> 1] > priority)
+ {
+ _heapNodes[i] = _heapNodes[i >> 1];
+ _heapPriorities[i] = _heapPriorities[i >> 1];
+ i >>= 1;
+ }
+
+ _heapNodes[i] = node;
+ _heapPriorities[i] = priority;
+ }
+
+ private int HeapPop()
+ {
+ var top = _heapNodes[1];
+ var lastNode = _heapNodes[_heapCount];
+ var lastPriority = _heapPriorities[_heapCount];
+ _heapCount--;
+
+ var i = 1;
+ while (true)
+ {
+ var child = i << 1;
+ if (child > _heapCount)
+ {
+ break;
+ }
+
+ if (child < _heapCount && _heapPriorities[child + 1] < _heapPriorities[child])
+ {
+ child++;
+ }
+
+ if (_heapPriorities[child] >= lastPriority)
+ {
+ break;
+ }
+
+ _heapNodes[i] = _heapNodes[child];
+ _heapPriorities[i] = _heapPriorities[child];
+ i = child;
+ }
+
+ if (_heapCount > 0)
+ {
+ _heapNodes[i] = lastNode;
+ _heapPriorities[i] = lastPriority;
+ }
+
+ return top;
+ }
+}
diff --git a/src/MrGameEng.Pathfinding/IPathGrid.cs b/src/MrGameEng.Pathfinding/IPathGrid.cs
new file mode 100644
index 0000000..b8e37d3
--- /dev/null
+++ b/src/MrGameEng.Pathfinding/IPathGrid.cs
@@ -0,0 +1,34 @@
+namespace MrGameEng.Pathfinding;
+
+/// Neighbor connectivity of a grid.
+public enum GridConnectivity
+{
+ /// Orthogonal moves only.
+ Four = 4,
+
+ /// Orthogonal and diagonal moves. Diagonals never cut corners.
+ Eight = 8,
+}
+
+///
+/// A grid the pathfinding algorithms operate on. The game implements this over its own
+/// world representation (terrain cells, a TileGrid, …) — the pathfinding module
+/// never owns world data.
+///
+public interface IPathGrid
+{
+ /// Grid width in cells.
+ int Width { get; }
+
+ /// Grid height in cells.
+ int Height { get; }
+
+ /// True when the cell can be entered. Out-of-range cells are never queried.
+ bool IsPassable(int x, int y);
+
+ ///
+ /// Cost multiplier for entering the cell, must be ≥ 1 (1 = normal terrain,
+ /// 3 = swamp three times slower, …). Used by A* and Dijkstra; ignored by BFS.
+ ///
+ float Cost(int x, int y);
+}
diff --git a/src/MrGameEng.Pathfinding/MrGameEng.Pathfinding.csproj b/src/MrGameEng.Pathfinding/MrGameEng.Pathfinding.csproj
new file mode 100644
index 0000000..87669eb
--- /dev/null
+++ b/src/MrGameEng.Pathfinding/MrGameEng.Pathfinding.csproj
@@ -0,0 +1,11 @@
+
+
+
+ net8.0
+
+
+
+
+
+
+
diff --git a/tests/MrGameEng.Collisions.Tests/CollisionWorldTests.cs b/tests/MrGameEng.Collisions.Tests/CollisionWorldTests.cs
new file mode 100644
index 0000000..8657f75
--- /dev/null
+++ b/tests/MrGameEng.Collisions.Tests/CollisionWorldTests.cs
@@ -0,0 +1,185 @@
+using Friflo.Engine.ECS;
+using Microsoft.Xna.Framework;
+using MrGameEng.Core;
+using MrGameEng.Graphics;
+using Xunit;
+
+namespace MrGameEng.Collisions.Tests;
+
+public class CollisionWorldTests
+{
+ private sealed class CollisionScene : Scene
+ {
+ public CollisionWorld World = null!;
+
+ protected override void OnLoad() => World = this.UseCollisions(cellSize: 32f);
+ }
+
+ private static (EngineContext Context, CollisionScene Scene) CreateScene()
+ {
+ var context = new EngineContext();
+ var scene = new CollisionScene();
+ context.Scenes.Switch(scene);
+ context.Scenes.Update(context.Clock); // применяет переключение и первый тик
+ return (context, scene);
+ }
+
+ private static Entity Spawn(Scene scene, Vector2 position, in Collider collider) =>
+ scene.Store.CreateEntity(Transform2D.At(position), collider);
+
+ private static void Tick(EngineContext context)
+ {
+ context.Clock.Advance(0.016f);
+ context.Scenes.Update(context.Clock);
+ }
+
+ [Fact]
+ public void OverlappingCircles_ProduceOnePair()
+ {
+ var (context, scene) = CreateScene();
+ var a = Spawn(scene, new Vector2(0f, 0f), Collider.Circle(10f));
+ var b = Spawn(scene, new Vector2(15f, 0f), Collider.Circle(10f));
+ Spawn(scene, new Vector2(100f, 100f), Collider.Circle(10f)); // далёкий — без пар
+
+ Tick(context);
+
+ var pair = Assert.Single(scene.World.Pairs.ToArray());
+ Assert.True((pair.A == a && pair.B == b) || (pair.A == b && pair.B == a));
+ }
+
+ [Fact]
+ public void SeparatedCircles_NoPairs()
+ {
+ var (context, scene) = CreateScene();
+ Spawn(scene, new Vector2(0f, 0f), Collider.Circle(5f));
+ Spawn(scene, new Vector2(11f, 0f), Collider.Circle(5f));
+
+ Tick(context);
+
+ Assert.Equal(0, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void CircleAndBox_Overlap_DetectedBothWays()
+ {
+ var (context, scene) = CreateScene();
+ Spawn(scene, new Vector2(0f, 0f), Collider.Box(20f, 20f));
+ Spawn(scene, new Vector2(14f, 0f), Collider.Circle(5f)); // касается правой грани
+
+ Tick(context);
+
+ Assert.Equal(1, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void CornerCircle_DoesNotTouchBox()
+ {
+ var (context, scene) = CreateScene();
+ Spawn(scene, new Vector2(0f, 0f), Collider.Box(20f, 20f));
+ // Угол бокса (10,10); круг r=5 в (16,16): расстояние до угла ~8.49 > 5.
+ Spawn(scene, new Vector2(16f, 16f), Collider.Circle(5f));
+
+ Tick(context);
+
+ Assert.Equal(0, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void LayerMasks_FilterPairs()
+ {
+ var (context, scene) = CreateScene();
+ var ghost = Collider.Circle(10f);
+ ghost.Layer = 0b10;
+ ghost.CollidesWith = 0b10; // призраки сталкиваются только с призраками
+
+ var wall = Collider.Circle(10f);
+ wall.Layer = 0b01;
+ wall.CollidesWith = 0b01;
+
+ Spawn(scene, new Vector2(0f, 0f), ghost);
+ Spawn(scene, new Vector2(5f, 0f), wall);
+
+ Tick(context);
+
+ Assert.Equal(0, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void MovingApart_PairDisappearsNextTick()
+ {
+ var (context, scene) = CreateScene();
+ Spawn(scene, new Vector2(0f, 0f), Collider.Circle(10f));
+ var mover = Spawn(scene, new Vector2(5f, 0f), Collider.Circle(10f));
+
+ Tick(context);
+ Assert.Equal(1, scene.World.Pairs.Length);
+
+ mover.GetComponent().Position = new Vector2(100f, 0f);
+ Tick(context);
+ Assert.Equal(0, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void LargeCluster_AllTouchingPairsFound_OnceEach()
+ {
+ var (context, scene) = CreateScene();
+ // Цепочка из 10 кругов: касаются только соседи → ровно 9 пар.
+ for (var i = 0; i < 10; i++)
+ {
+ Spawn(scene, new Vector2(i * 18f, 0f), Collider.Circle(10f));
+ }
+
+ Tick(context);
+
+ Assert.Equal(9, scene.World.Pairs.Length);
+ }
+
+ [Fact]
+ public void QueryAabb_ReturnsOnlyEntitiesInArea()
+ {
+ var (context, scene) = CreateScene();
+ var inside = Spawn(scene, new Vector2(10f, 10f), Collider.Circle(5f));
+ Spawn(scene, new Vector2(200f, 200f), Collider.Circle(5f));
+
+ Tick(context);
+
+ Span results = new Entity[8];
+ var found = scene.World.QueryAabb(new RectF(0f, 0f, 50f, 50f), results);
+
+ Assert.Equal(1, found);
+ Assert.Equal(inside, results[0]);
+ }
+
+ [Fact]
+ public void Raycast_HitsClosestCollider_AndRespectsMask()
+ {
+ var (context, scene) = CreateScene();
+ var near = Collider.Circle(5f);
+ near.Layer = 0b01;
+ var far = Collider.Circle(5f);
+ far.Layer = 0b10;
+
+ var nearEntity = Spawn(scene, new Vector2(30f, 0f), near);
+ var farEntity = Spawn(scene, new Vector2(60f, 0f), far);
+
+ Tick(context);
+
+ Assert.True(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out var hit));
+ Assert.Equal(nearEntity, hit.Entity);
+ Assert.Equal(25f, hit.Point.X, 1);
+
+ Assert.True(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out hit, mask: 0b10));
+ Assert.Equal(farEntity, hit.Entity);
+ }
+
+ [Fact]
+ public void Raycast_Miss_ReturnsFalse()
+ {
+ var (context, scene) = CreateScene();
+ Spawn(scene, new Vector2(0f, 50f), Collider.Box(10f, 10f));
+
+ Tick(context);
+
+ Assert.False(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out _));
+ }
+}
diff --git a/tests/MrGameEng.Collisions.Tests/MrGameEng.Collisions.Tests.csproj b/tests/MrGameEng.Collisions.Tests/MrGameEng.Collisions.Tests.csproj
new file mode 100644
index 0000000..bf04795
--- /dev/null
+++ b/tests/MrGameEng.Collisions.Tests/MrGameEng.Collisions.Tests.csproj
@@ -0,0 +1,19 @@
+
+
+
+ net8.0
+ Exe
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/MrGameEng.Pathfinding.Tests/FlowFieldTests.cs b/tests/MrGameEng.Pathfinding.Tests/FlowFieldTests.cs
new file mode 100644
index 0000000..a880b6d
--- /dev/null
+++ b/tests/MrGameEng.Pathfinding.Tests/FlowFieldTests.cs
@@ -0,0 +1,101 @@
+using Microsoft.Xna.Framework;
+using Xunit;
+
+namespace MrGameEng.Pathfinding.Tests;
+
+public class FlowFieldTests
+{
+ [Fact]
+ public void Build_DistancesGrowFromGoal_DirectionsDescend()
+ {
+ var grid = new TestGrid(
+ ".....",
+ ".###.",
+ ".....");
+ var builder = new FlowFieldBuilder(grid);
+ var field = new FlowField();
+
+ builder.Build([new Point(0, 0)], field);
+
+ Assert.Equal(0f, field.DistanceAt(0, 0));
+ Assert.True(field.DistanceAt(4, 2) > field.DistanceAt(1, 0));
+
+ // Из любой достижимой не-целевой клетки направление ведёт к клетке с меньшей дистанцией.
+ for (var y = 0; y < grid.Height; y++)
+ {
+ for (var x = 0; x < grid.Width; x++)
+ {
+ if (!grid.IsPassable(x, y) || !field.IsReachable(x, y) || field.DistanceAt(x, y) == 0f)
+ {
+ continue;
+ }
+
+ var direction = field.DirectionAt(x, y);
+ Assert.NotEqual(Vector2.Zero, direction);
+ var nx = x + Math.Sign(MathF.Round(direction.X * 10f));
+ var ny = y + Math.Sign(MathF.Round(direction.Y * 10f));
+ Assert.True(field.DistanceAt(nx, ny) < field.DistanceAt(x, y),
+ $"direction at ({x},{y}) does not descend");
+ }
+ }
+ }
+
+ [Fact]
+ public void Build_UnreachablePocket_IsFlagged()
+ {
+ var grid = new TestGrid(
+ "..#..",
+ "..#..",
+ "..#..");
+ var builder = new FlowFieldBuilder(grid);
+ var field = new FlowField();
+
+ builder.Build([new Point(0, 1)], field);
+
+ Assert.False(field.IsReachable(4, 1));
+ Assert.Equal(Vector2.Zero, field.DirectionAt(4, 1));
+ Assert.True(field.IsReachable(1, 2));
+ }
+
+ [Fact]
+ public void Build_MultipleGoals_EachCellFlowsToNearest()
+ {
+ var grid = new TestGrid("..........");
+ var builder = new FlowFieldBuilder(grid);
+ var field = new FlowField();
+
+ builder.Build([new Point(0, 0), new Point(9, 0)], field);
+
+ Assert.True(field.DirectionAt(2, 0).X < 0f); // ближе к левой цели
+ Assert.True(field.DirectionAt(7, 0).X > 0f); // ближе к правой
+ Assert.Equal(0f, field.DistanceAt(9, 0));
+ }
+
+ [Fact]
+ public void Build_Rebuild_OverwritesPreviousField()
+ {
+ var grid = new TestGrid(".....");
+ var builder = new FlowFieldBuilder(grid);
+ var field = new FlowField();
+
+ builder.Build([new Point(0, 0)], field);
+ Assert.True(field.DirectionAt(4, 0).X < 0f);
+
+ builder.Build([new Point(4, 0)], field);
+ Assert.True(field.DirectionAt(0, 0).X > 0f);
+ Assert.Equal(0f, field.DistanceAt(4, 0));
+ }
+
+ [Fact]
+ public void Build_NoValidGoals_EverythingUnreachable()
+ {
+ var grid = new TestGrid(".#.");
+ var builder = new FlowFieldBuilder(grid);
+ var field = new FlowField();
+
+ builder.Build([new Point(1, 0)], field); // цель — стена
+
+ Assert.False(field.IsReachable(0, 0));
+ Assert.False(field.IsReachable(2, 0));
+ }
+}
diff --git a/tests/MrGameEng.Pathfinding.Tests/GridPathfinderTests.cs b/tests/MrGameEng.Pathfinding.Tests/GridPathfinderTests.cs
new file mode 100644
index 0000000..9927a3c
--- /dev/null
+++ b/tests/MrGameEng.Pathfinding.Tests/GridPathfinderTests.cs
@@ -0,0 +1,199 @@
+using Microsoft.Xna.Framework;
+using Xunit;
+
+namespace MrGameEng.Pathfinding.Tests;
+
+public class GridPathfinderTests
+{
+ private static List Path(IPathGrid grid, Point start, Point goal,
+ PathAlgorithm algorithm = PathAlgorithm.AStar,
+ GridConnectivity connectivity = GridConnectivity.Eight)
+ {
+ var pathfinder = new GridPathfinder(grid, connectivity);
+ var path = new List();
+ Assert.True(pathfinder.FindPath(start, goal, path, algorithm));
+ return path;
+ }
+
+ private static void AssertValidPath(IPathGrid grid, List path, Point start, Point goal)
+ {
+ Assert.Equal(start, path[0]);
+ Assert.Equal(goal, path[^1]);
+ for (var i = 0; i < path.Count; i++)
+ {
+ Assert.True(grid.IsPassable(path[i].X, path[i].Y), $"impassable cell {path[i]}");
+ if (i > 0)
+ {
+ var dx = Math.Abs(path[i].X - path[i - 1].X);
+ var dy = Math.Abs(path[i].Y - path[i - 1].Y);
+ Assert.True(dx <= 1 && dy <= 1 && dx + dy > 0, $"non-adjacent step {path[i - 1]} -> {path[i]}");
+ }
+ }
+ }
+
+ [Theory]
+ [InlineData(PathAlgorithm.AStar)]
+ [InlineData(PathAlgorithm.Dijkstra)]
+ [InlineData(PathAlgorithm.BreadthFirst)]
+ public void FindPath_OpenField_StraightLine(PathAlgorithm algorithm)
+ {
+ var grid = new TestGrid(
+ ".....",
+ ".....",
+ ".....");
+
+ var path = Path(grid, new Point(0, 1), new Point(4, 1), algorithm);
+
+ AssertValidPath(grid, path, new Point(0, 1), new Point(4, 1));
+ Assert.Equal(5, path.Count); // прямая, без лишних шагов
+ }
+
+ [Theory]
+ [InlineData(PathAlgorithm.AStar)]
+ [InlineData(PathAlgorithm.Dijkstra)]
+ [InlineData(PathAlgorithm.BreadthFirst)]
+ public void FindPath_WallsForceDetour(PathAlgorithm algorithm)
+ {
+ var grid = new TestGrid(
+ ".....",
+ "####.",
+ ".....");
+
+ var path = Path(grid, new Point(0, 0), new Point(0, 2), algorithm);
+
+ AssertValidPath(grid, path, new Point(0, 0), new Point(0, 2));
+ Assert.Contains(new Point(4, 1), path); // единственный проход
+ }
+
+ [Fact]
+ public void FindPath_NoRoute_ReturnsFalse()
+ {
+ var grid = new TestGrid(
+ ".#.",
+ ".#.",
+ ".#.");
+ var pathfinder = new GridPathfinder(grid);
+ var path = new List();
+
+ Assert.False(pathfinder.FindPath(new Point(0, 0), new Point(2, 0), path));
+ Assert.Empty(path);
+ }
+
+ [Fact]
+ public void FindPath_StartEqualsGoal_SinglePoint()
+ {
+ var grid = new TestGrid("...");
+
+ var path = Path(grid, new Point(1, 0), new Point(1, 0));
+
+ Assert.Equal([new Point(1, 0)], path);
+ }
+
+ [Fact]
+ public void FindPath_DiagonalNeverCutsCorners()
+ {
+ var grid = new TestGrid(
+ ".#",
+ "#.");
+ var pathfinder = new GridPathfinder(grid, GridConnectivity.Eight);
+ var path = new List();
+
+ // Диагональ (0,0)->(1,1) зажата стенами — пути нет.
+ Assert.False(pathfinder.FindPath(new Point(0, 0), new Point(1, 1), path));
+ }
+
+ [Fact]
+ public void FindPath_FourConnectivity_NoDiagonalSteps()
+ {
+ var grid = new TestGrid(
+ "...",
+ "...",
+ "...");
+
+ var path = Path(grid, new Point(0, 0), new Point(2, 2), connectivity: GridConnectivity.Four);
+
+ Assert.Equal(5, path.Count); // манхэттен: 4 шага
+ for (var i = 1; i < path.Count; i++)
+ {
+ var dx = Math.Abs(path[i].X - path[i - 1].X);
+ var dy = Math.Abs(path[i].Y - path[i - 1].Y);
+ Assert.Equal(1, dx + dy);
+ }
+ }
+
+ [Theory]
+ [InlineData(PathAlgorithm.AStar)]
+ [InlineData(PathAlgorithm.Dijkstra)]
+ public void FindPath_CostAware_AvoidsExpensiveTerrain(PathAlgorithm algorithm)
+ {
+ // Прямой путь через болото (цена 9) дороже обхода по краю.
+ var grid = new TestGrid(
+ ".....",
+ ".999.",
+ ".....");
+
+ var path = Path(grid, new Point(0, 1), new Point(4, 1), algorithm);
+
+ Assert.DoesNotContain(path, p => grid.Cost(p.X, p.Y) > 1f);
+ }
+
+ [Fact]
+ public void FindPath_BreadthFirst_IgnoresCosts()
+ {
+ var grid = new TestGrid(
+ ".....",
+ ".999.",
+ ".....");
+
+ var path = Path(grid, new Point(0, 1), new Point(4, 1), PathAlgorithm.BreadthFirst);
+
+ Assert.Equal(5, path.Count); // идёт напрямик через дорогие клетки
+ }
+
+ [Fact]
+ public void FindPath_ReusedInstance_GivesCleanResults()
+ {
+ var grid = new TestGrid(
+ ".....",
+ ".###.",
+ ".....");
+ var pathfinder = new GridPathfinder(grid);
+ var path = new List();
+
+ Assert.True(pathfinder.FindPath(new Point(0, 0), new Point(4, 2), path));
+ var first = path.ToArray();
+ Assert.True(pathfinder.FindPath(new Point(0, 0), new Point(4, 2), path));
+
+ Assert.Equal(first, path); // generation-сброс не оставляет мусора между запросами
+ }
+
+ [Fact]
+ public void FindPath_AStarMatchesDijkstraCost()
+ {
+ var grid = new TestGrid(
+ "..3..",
+ ".#3#.",
+ "..3..",
+ ".###.",
+ ".....");
+ var start = new Point(0, 0);
+ var goal = new Point(4, 4);
+
+ var aStar = Path(grid, start, goal, PathAlgorithm.AStar);
+ var dijkstra = Path(grid, start, goal, PathAlgorithm.Dijkstra);
+
+ Assert.Equal(PathCost(grid, dijkstra), PathCost(grid, aStar), 3);
+ }
+
+ private static float PathCost(IPathGrid grid, List path)
+ {
+ var total = 0f;
+ for (var i = 1; i < path.Count; i++)
+ {
+ var diagonal = path[i].X != path[i - 1].X && path[i].Y != path[i - 1].Y;
+ total += (diagonal ? 1.4142135f : 1f) * grid.Cost(path[i].X, path[i].Y);
+ }
+
+ return total;
+ }
+}
diff --git a/tests/MrGameEng.Pathfinding.Tests/MrGameEng.Pathfinding.Tests.csproj b/tests/MrGameEng.Pathfinding.Tests/MrGameEng.Pathfinding.Tests.csproj
new file mode 100644
index 0000000..ccee2f0
--- /dev/null
+++ b/tests/MrGameEng.Pathfinding.Tests/MrGameEng.Pathfinding.Tests.csproj
@@ -0,0 +1,19 @@
+
+
+
+ net8.0
+ Exe
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/MrGameEng.Pathfinding.Tests/TestGrid.cs b/tests/MrGameEng.Pathfinding.Tests/TestGrid.cs
new file mode 100644
index 0000000..3d65ccd
--- /dev/null
+++ b/tests/MrGameEng.Pathfinding.Tests/TestGrid.cs
@@ -0,0 +1,23 @@
+using MrGameEng.Pathfinding;
+
+namespace MrGameEng.Pathfinding.Tests;
+
+/// Грид из строк: '#' — стена, '.' — клетка с ценой 1, '2'..'9' — клетка с этой ценой.
+public sealed class TestGrid : IPathGrid
+{
+ private readonly string[] _rows;
+
+ public TestGrid(params string[] rows) => _rows = rows;
+
+ public int Width => _rows[0].Length;
+
+ public int Height => _rows.Length;
+
+ public bool IsPassable(int x, int y) => _rows[y][x] != '#';
+
+ public float Cost(int x, int y)
+ {
+ var cell = _rows[y][x];
+ return cell is >= '2' and <= '9' ? cell - '0' : 1f;
+ }
+}