Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a395e58458 | ||
|
|
b3415120c3 | ||
|
|
b318d1e795 |
@@ -19,11 +19,19 @@ docs/ architecture, conventions, roadmap (Russian)
|
||||
Engine modules: `Core` (game loop, ECS world, scenes, time), `Graphics` (custom batched
|
||||
renderer, camera, sprites), `Input`, `Audio`, `Assets` (runtime loading, no content
|
||||
pipeline), `Assets.Generator` (Roslyn source generator for typed asset handles),
|
||||
`UI` (Myra integration: `scene.UseUI()` after `UseRenderer2D()`), `DevConsole`
|
||||
(in-game console capturing `Core.Log`; `scene.UseDevConsole()` last in OnLoad).
|
||||
`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()`), `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 exception: Myra renders with its own SpriteBatch internally.
|
||||
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);
|
||||
`Collisions` depends on `Graphics` (Transform2D, RectF).
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
<PackageVersion Include="FontStashSharp.MonoGame" Version="1.5.6" />
|
||||
<PackageVersion Include="NVorbis" Version="0.10.5" />
|
||||
<PackageVersion Include="Myra" Version="1.6.1" />
|
||||
<PackageVersion Include="StbImageSharp" Version="2.30.15" />
|
||||
<PackageVersion Include="StbImageWriteSharp" Version="1.16.7" />
|
||||
|
||||
<!-- Source generator -->
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
|
||||
|
||||
+137
@@ -37,6 +37,26 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.DevConsole", "src
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.DevConsole.Tests", "tests\MrGameEng.DevConsole.Tests\MrGameEng.DevConsole.Tests.csproj", "{0439A95B-5BF6-48AA-9EA9-BE4F6CCF19D0}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Atlases", "src\MrGameEng.Atlases\MrGameEng.Atlases.csproj", "{B5980FD4-43DF-41B3-97BB-B93D89761FB9}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.AtlasTool", "tools\MrGameEng.AtlasTool\MrGameEng.AtlasTool.csproj", "{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Atlases.Tests", "tests\MrGameEng.Atlases.Tests\MrGameEng.Atlases.Tests.csproj", "{1951D50B-122A-45B5-9356-F186A3CBC974}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Tilemaps", "src\MrGameEng.Tilemaps\MrGameEng.Tilemaps.csproj", "{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}"
|
||||
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
|
||||
@@ -215,6 +235,114 @@ Global
|
||||
{0439A95B-5BF6-48AA-9EA9-BE4F6CCF19D0}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0439A95B-5BF6-48AA-9EA9-BE4F6CCF19D0}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0439A95B-5BF6-48AA-9EA9-BE4F6CCF19D0}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|x64.Build.0 = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974}.Release|x86.Build.0 = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{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
|
||||
@@ -234,5 +362,14 @@ Global
|
||||
{17EB97D5-DCF8-47DF-B810-DA45AE314170} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{5F5E2C77-F2AC-4CC7-9CB7-5E46E4CFACB5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{0439A95B-5BF6-48AA-9EA9-BE4F6CCF19D0} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{B5980FD4-43DF-41B3-97BB-B93D89761FB9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{C9782A2A-1D37-4EAF-A628-AB6F399DE9F9} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
|
||||
{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
|
||||
|
||||
@@ -33,6 +33,10 @@
|
||||
| `MrGameEng.Audio` | Звуковые эффекты и музыка |
|
||||
| `MrGameEng.Assets` | Runtime-загрузка ресурсов без Content Pipeline, кэш, `AssetRef<T>` |
|
||||
| `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`, команды, история, автодополнение |
|
||||
|
||||
@@ -50,6 +54,11 @@ MrGameEng.Assets ─┘ └──► Friflo.Engine.ECS
|
||||
Модули зависят **только от `Core`** и никогда друг от друга. `Core` зависит только
|
||||
от MonoGame и Friflo. Если двум модулям нужен общий тип — он переезжает в `Core`.
|
||||
|
||||
Документированные исключения: `MrGameEng.Atlases` зависит от `Graphics`
|
||||
(выдаёт `Texture2DRegion`) и от `Assets` (регистрирует загрузчик в `AssetManager`) —
|
||||
атлас по своей природе склейка этих двух областей; `MrGameEng.Tilemaps` зависит от
|
||||
`Graphics` (рисует регионы через рендерер и слои).
|
||||
|
||||
`MrGameEng.Assets.Generator` — особый случай: это анализатор (netstandard2.0),
|
||||
он подключается к проекту игры как `Analyzer`, в рантайме не участвует и не зависит
|
||||
от других модулей движка.
|
||||
@@ -125,6 +134,92 @@ public static partial class GameAssets
|
||||
Обращение к ресурсу по строковому пути в коде игры — запрещено соглашением;
|
||||
строки существуют только внутри сгенерированного кода.
|
||||
|
||||
## Текстурные атласы
|
||||
|
||||
`MrGameEng.Atlases` превращает дерево отдельных картинок в атласы и грузит их в рантайме.
|
||||
Спрайты с регионами одной страницы атласа батчер сливает в один draw call.
|
||||
|
||||
### Сборка (билд-тайм, без GPU)
|
||||
|
||||
`AtlasBuilder.Build(AtlasBuildOptions)` — чистый CPU (StbImageSharp/StbImageWriteSharp):
|
||||
|
||||
- Источник сканируется рекурсивно (png/jpg/jpeg/bmp); картинки группируются в атласы
|
||||
по первым `GroupDepth` папкам относительного пути (0 — один атлас на всё).
|
||||
- Упаковка — детерминированный shelf-packer (`ShelfPacker`): сортировка по высоте,
|
||||
полки, страницы до `MaxPageSize`² (по умолчанию 2048), зазор `Padding` (2 px),
|
||||
размер страницы подрезается до степени двойки; негабаритные картинки получают
|
||||
отдельную страницу под себя.
|
||||
- Выход: страницы `<Имя>.atlas.<N>.png` + метаданные `<Имя>.atlas` (JSON: страницы,
|
||||
регионы с ключами и прямоугольниками). Ключ региона — путь от корня источника без
|
||||
расширения (`Things/Pawn/Animal/Fox`).
|
||||
- Инкрементальность: группа пересобирается только если изменились исходники, состав
|
||||
файлов или параметры сборки; атласы исчезнувших групп удаляются из выходной папки.
|
||||
|
||||
CLI-обёртка: `dotnet run --project tools/MrGameEng.AtlasTool -- <источник> <выход>
|
||||
[--group-depth N] [--page-size N] [--padding N] [--root-name Имя] [--force]`.
|
||||
|
||||
### Загрузка (рантайм)
|
||||
|
||||
- `context.UseTextureAtlases()` регистрирует загрузчик `TextureAtlas` в `AssetManager`;
|
||||
кодогенератор выдаёт хендлы `AssetRef<TextureAtlas>` для файлов `.atlas`
|
||||
(страницы `*.atlas.N.png` собственных Texture2D-хендлов не получают).
|
||||
- `TextureAtlas` владеет страницами (premultiplied alpha, как все текстуры движка)
|
||||
и отдаёт регионы: `atlas.GetRegion("Things/Pawn/Animal/Fox")` → `Texture2DRegion`,
|
||||
готовый для `Sprite`.
|
||||
|
||||
## Тайловые карты
|
||||
|
||||
`MrGameEng.Tilemaps` — тайловые карты, создаваемые **кодом** (загрузка Tiled — в бэклоге):
|
||||
|
||||
- `TileSet` — словарь тайлов: `Add(region, tint?)` возвращает id; id 0 зарезервирован
|
||||
под «пусто». Регион + тинт позволяют строить тайлсеты и из текстур атласа,
|
||||
и из тонированной белой текстуры.
|
||||
- `TileGrid` — плотная сетка `ushort`-id с проверкой границ; заполняется генератором
|
||||
мира, мутируется в рантайме (изменение видно со следующего кадра).
|
||||
- Компонент `Tilemap` (`struct : IComponent`): грид + тайлсет + `Origin`, `TileSize`,
|
||||
слой, `Depth`, общий тинт карты. Обычная сущность — карт может быть несколько
|
||||
(земля, декор поверх).
|
||||
- `scene.UseTilemaps()` (после `UseRenderer2D()`) вставляет `TilemapRenderSystem`
|
||||
в Draw-фазу перед flush. Система считает видимый диапазон клеток по cull-rect
|
||||
камеры (`TilemapMath.VisibleCells`) и сабмитит только его: стоимость кадра зависит
|
||||
от экрана, а не от размера грида. Тайлы батчатся со спрайтами по обычному порядку
|
||||
слой → 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` свой батчер,
|
||||
@@ -243,4 +338,6 @@ docs/ документация (русский)
|
||||
| FontStashSharp.MonoGame | 1.5.6 | Шрифты (ttf) в рантайме |
|
||||
| NVorbis | 0.10.5 | Декодирование ogg |
|
||||
| Myra | 1.6.1 | Игровой UI |
|
||||
| StbImageSharp | 2.30.15 | Декодирование картинок при сборке атласов |
|
||||
| StbImageWriteSharp | 1.16.7 | Запись PNG-страниц атласов |
|
||||
| dotnet-mgfxc (dotnet tool) | 3.8.4.1 | Компиляция шейдеров при сборке |
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
## Бэклог
|
||||
|
||||
- Physics2D (выбор библиотеки: Aether.Physics2D / своя)
|
||||
- Tilemap (поддержка Tiled)
|
||||
- Tilemaps: загрузка карт Tiled (.tmx) поверх существующего программного API
|
||||
- Particles
|
||||
- UI: загрузка MML-разметки Myra через AssetManager + хендлы в кодогенераторе
|
||||
- UI: рендер Myra через наш батчер (`IMyraRenderer`), если UI станет узким местом по draw call'ам
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"version": 1,
|
||||
"name": "Textures",
|
||||
"pageSize": 2048,
|
||||
"padding": 2,
|
||||
"pages": [
|
||||
{
|
||||
"file": "Textures.atlas.0.png",
|
||||
"width": 256,
|
||||
"height": 128
|
||||
}
|
||||
],
|
||||
"regions": [
|
||||
{
|
||||
"key": "player",
|
||||
"page": 0,
|
||||
"x": 68,
|
||||
"y": 2,
|
||||
"w": 64,
|
||||
"h": 32
|
||||
},
|
||||
{
|
||||
"key": "shapes",
|
||||
"page": 0,
|
||||
"x": 2,
|
||||
"y": 2,
|
||||
"w": 64,
|
||||
"h": 64
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.0 KiB |
@@ -11,6 +11,10 @@
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Input\MrGameEng.Input.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Audio\MrGameEng.Audio.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Assets\MrGameEng.Assets.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Atlases\MrGameEng.Atlases.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Tilemaps\MrGameEng.Tilemaps.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Collisions\MrGameEng.Collisions.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.UI\MrGameEng.UI.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.DevConsole\MrGameEng.DevConsole.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Assets.Generator\MrGameEng.Assets.Generator.csproj"
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Assets;
|
||||
using MrGameEng.Atlases;
|
||||
using MrGameEng.Audio;
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.DevConsole;
|
||||
using MrGameEng.Graphics;
|
||||
using MrGameEng.Input;
|
||||
using MrGameEng.Tilemaps;
|
||||
using MrGameEng.UI;
|
||||
using Myra.Graphics2D.UI;
|
||||
|
||||
@@ -31,11 +33,17 @@ public sealed class MainScene : Scene
|
||||
|
||||
var renderer = this.UseRenderer2D(new Renderer2DOptions { VirtualResolution = new Point(1280, 720) });
|
||||
SampleLayers.EnsureRegistered(renderer);
|
||||
this.UseTilemaps();
|
||||
|
||||
var playerTexture = assets.Load(GameAssets.Textures.Player);
|
||||
var shapesTexture = assets.Load(GameAssets.Textures.Shapes);
|
||||
var beep = assets.Load(GameAssets.Sounds.Beep);
|
||||
|
||||
// Текстурный атлас: Assets/Atlases собран утилитой MrGameEng.AtlasTool из Assets/Textures
|
||||
// (см. README). Регионы адресуются исходным путём без расширения и батчатся в один draw call.
|
||||
Context.UseTextureAtlases();
|
||||
var atlas = assets.Load(GameAssets.Atlases.Textures);
|
||||
|
||||
var shapeRegions = new[]
|
||||
{
|
||||
new Texture2DRegion(shapesTexture, new Rectangle(0, 0, 32, 32)),
|
||||
@@ -44,6 +52,26 @@ public sealed class MainScene : Scene
|
||||
new Texture2DRegion(shapesTexture, new Rectangle(32, 32, 32, 32)),
|
||||
};
|
||||
|
||||
// Тайловая площадка под стартовой зоной: шахматный пол, строится кодом из TileSet/TileGrid.
|
||||
// Видимые клетки сабмитятся каждый кадр; Depth -10 кладёт пол под декорации.
|
||||
var floorTiles = new TileSet();
|
||||
var floorA = floorTiles.Add(shapeRegions[0], new Color(70, 75, 95));
|
||||
var floorB = floorTiles.Add(shapeRegions[2], new Color(55, 60, 78));
|
||||
var floorGrid = new TileGrid(24, 14);
|
||||
for (var y = 0; y < floorGrid.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < floorGrid.Width; x++)
|
||||
{
|
||||
floorGrid[x, y] = (x + y) % 2 == 0 ? floorA : floorB;
|
||||
}
|
||||
}
|
||||
|
||||
Store.CreateEntity(new Tilemap(floorGrid, floorTiles, tileSize: 48f)
|
||||
{
|
||||
Origin = new Vector2(-24 * 24f, -14 * 24f),
|
||||
Depth = -10f,
|
||||
});
|
||||
|
||||
// Декорации по всему миру: уезжаешь камерой — попадают под culling (см. заголовок окна).
|
||||
var random = new Random(42);
|
||||
for (var i = 0; i < DecorCount; i++)
|
||||
@@ -87,6 +115,15 @@ public sealed class MainScene : Scene
|
||||
playerSprite,
|
||||
new SpriteAnimator(blink));
|
||||
|
||||
// Пара спрайтов из атласа рядом со стартом игрока — вся пара рисуется одним draw call.
|
||||
var atlasShowcase = new[] { ("player", -80f), ("shapes", 80f) };
|
||||
foreach (var (key, offsetX) in atlasShowcase)
|
||||
{
|
||||
var sprite = new Sprite(atlas.GetRegion(key), SampleLayers.Actors);
|
||||
sprite.CenterOrigin();
|
||||
Store.CreateEntity(new Transform2D(new Vector2(offsetX, -120f)), sprite);
|
||||
}
|
||||
|
||||
var camera = Store.CreateEntity(new Camera(Vector2.Zero, zoom: 1f, bounds: WorldBounds));
|
||||
|
||||
// HUD: золотой квадрат в углу на screen-space слое — не двигается с камерой.
|
||||
@@ -131,6 +168,21 @@ public sealed class MainScene : Scene
|
||||
}
|
||||
});
|
||||
console.Register("beep", "play the beep sound", (_, _) => 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)");
|
||||
foreach (var (key, region) in atlas.Regions.OrderBy(r => r.Key, StringComparer.Ordinal))
|
||||
{
|
||||
c.WriteLine($" {key}: {region.Bounds.Width}x{region.Bounds.Height} at ({region.Bounds.X},{region.Bounds.Y})");
|
||||
}
|
||||
});
|
||||
|
||||
UpdateSystems.Add(new PlayerControlSystem(player, actions, audio, beep, console));
|
||||
UpdateSystems.Add(new BounceSystem(WorldBounds));
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Демо поиска пути и коллизий: ЛКМ ставит цель — толпа агентов стекается к ней по
|
||||
/// flow field, жёлтым подсвечен A*-путь из левого верхнего угла, столкнувшиеся агенты
|
||||
/// вспыхивают красным. Tab/'main' — назад.
|
||||
/// </summary>
|
||||
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<Point> _path = [];
|
||||
private readonly List<Entity> _pathMarkers = [];
|
||||
private FlowFieldBuilder _builder = null!;
|
||||
private GridPathfinder _pathfinder = null!;
|
||||
private Texture2DRegion _white = null!;
|
||||
private Entity _goalMarker;
|
||||
|
||||
/// <summary>Состояние агента: время красной вспышки после столкновения.</summary>
|
||||
private struct AgentState : IComponent
|
||||
{
|
||||
public float Flash;
|
||||
}
|
||||
|
||||
protected override void OnLoad()
|
||||
{
|
||||
var assets = Context.Services.GetOrDefault<AssetManager>() ?? 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<Transform2D>().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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Случайные прямоугольные стены; старт A* и центр всегда свободны.</summary>
|
||||
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<Transform2D, AgentState>
|
||||
{
|
||||
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<AgentState>())
|
||||
{
|
||||
entity.GetComponent<AgentState>().Flash = 0.25f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FlashDecaySystem : QuerySystem<AgentState, Sprite>
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ public sealed class AssetHandlesGenerator : IIncrementalGenerator
|
||||
[".wav"] = "global::Microsoft.Xna.Framework.Audio.SoundEffect",
|
||||
[".ogg"] = "global::MrGameEng.Core.MusicTrack",
|
||||
[".mgfx"] = "global::Microsoft.Xna.Framework.Graphics.Effect",
|
||||
[".atlas"] = "global::MrGameEng.Atlases.TextureAtlas",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -62,6 +63,14 @@ public sealed class AssetHandlesGenerator : IIncrementalGenerator
|
||||
}
|
||||
|
||||
var relative = normalized.Substring(marker + "/Assets/".Length);
|
||||
|
||||
// Страницы атласов (Name.atlas.0.png) — внутренние файлы метаданных .atlas,
|
||||
// им собственные Texture2D-хендлы не нужны.
|
||||
if (Path.GetFileName(relative).Contains(".atlas.", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(relative);
|
||||
return TypeByExtension.ContainsKey(extension) ? relative : null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
using StbImageSharp;
|
||||
using StbImageWriteSharp;
|
||||
|
||||
namespace MrGameEng.Atlases;
|
||||
|
||||
/// <summary>Options for one <see cref="AtlasBuilder.Build"/> run.</summary>
|
||||
public sealed class AtlasBuildOptions
|
||||
{
|
||||
/// <summary>Directory scanned recursively for source images (png/jpg/jpeg/bmp).</summary>
|
||||
public required string SourceDirectory { get; init; }
|
||||
|
||||
/// <summary>Directory the <c>.atlas</c> metadata and page images are written to.</summary>
|
||||
public required string OutputDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How many leading directories of a source-relative path form the atlas group:
|
||||
/// 0 packs everything into one atlas, 1 packs per top-level folder, and so on.
|
||||
/// </summary>
|
||||
public int GroupDepth { get; init; } = 1;
|
||||
|
||||
/// <summary>Maximum page width/height in pixels.</summary>
|
||||
public int MaxPageSize { get; init; } = 2048;
|
||||
|
||||
/// <summary>Gap in pixels between packed images and page edges (bleed protection).</summary>
|
||||
public int Padding { get; init; } = 2;
|
||||
|
||||
/// <summary>Atlas name for images that have fewer directories than <see cref="GroupDepth"/>.</summary>
|
||||
public string RootAtlasName { get; init; } = "Atlas";
|
||||
|
||||
/// <summary>Rebuild every atlas even when sources are unchanged.</summary>
|
||||
public bool Force { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Build outcome for one atlas group.</summary>
|
||||
/// <param name="Name">Atlas name (group key with '/' replaced by '.').</param>
|
||||
/// <param name="RegionCount">Number of packed source images.</param>
|
||||
/// <param name="PageCount">Number of page images written.</param>
|
||||
/// <param name="Skipped">True when the atlas was up to date and not rebuilt.</param>
|
||||
public sealed record AtlasGroupResult(string Name, int RegionCount, int PageCount, bool Skipped);
|
||||
|
||||
/// <summary>Result of an <see cref="AtlasBuilder.Build"/> run.</summary>
|
||||
/// <param name="Groups">Per-atlas outcomes, sorted by name.</param>
|
||||
/// <param name="DeletedOrphans">Output files of atlases whose source group no longer exists.</param>
|
||||
public sealed record AtlasBuildResult(IReadOnlyList<AtlasGroupResult> Groups, IReadOnlyList<string> DeletedOrphans);
|
||||
|
||||
/// <summary>
|
||||
/// Build-time utility converting a directory tree of loose images into texture atlases:
|
||||
/// page images plus an <see cref="AtlasMetadata"/> JSON per group. Pure CPU (StbImageSharp),
|
||||
/// no graphics device — intended for tools and build scripts, not for the render loop.
|
||||
/// Region keys are source-relative paths without extension, so game code addresses sprites
|
||||
/// by the same path it would have used for the loose file.
|
||||
/// </summary>
|
||||
public static class AtlasBuilder
|
||||
{
|
||||
private static readonly string[] SourceExtensions = [".png", ".jpg", ".jpeg", ".bmp"];
|
||||
|
||||
/// <summary>Builds (or incrementally refreshes) all atlases for <paramref name="options"/>.</summary>
|
||||
public static AtlasBuildResult Build(AtlasBuildOptions options)
|
||||
{
|
||||
var sourceRoot = Path.GetFullPath(options.SourceDirectory);
|
||||
if (!Directory.Exists(sourceRoot))
|
||||
{
|
||||
throw new DirectoryNotFoundException($"Atlas source directory not found: '{sourceRoot}'.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(options.OutputDirectory);
|
||||
|
||||
var groups = ScanGroups(sourceRoot, options);
|
||||
var results = new List<AtlasGroupResult>();
|
||||
foreach (var (name, files) in groups)
|
||||
{
|
||||
results.Add(BuildGroup(name, files, options));
|
||||
}
|
||||
|
||||
var orphans = DeleteOrphans(options.OutputDirectory, groups.Keys);
|
||||
return new AtlasBuildResult(results, orphans);
|
||||
}
|
||||
|
||||
/// <summary>Maps a source-relative image path to its atlas name and region key.</summary>
|
||||
internal static (string AtlasName, string Key) ClassifyPath(string relativePath, int groupDepth, string rootAtlasName)
|
||||
{
|
||||
var normalized = relativePath.Replace('\\', '/');
|
||||
var key = normalized[..normalized.LastIndexOf('.')];
|
||||
var segments = normalized.Split('/');
|
||||
var depth = Math.Min(groupDepth, segments.Length - 1);
|
||||
var name = depth == 0 ? rootAtlasName : string.Join('.', segments[..depth]);
|
||||
return (name, key);
|
||||
}
|
||||
|
||||
private static SortedDictionary<string, List<(string FullPath, string Key)>> ScanGroups(
|
||||
string sourceRoot, AtlasBuildOptions options)
|
||||
{
|
||||
var groups = new SortedDictionary<string, List<(string, string)>>(StringComparer.Ordinal);
|
||||
var keys = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var fullPath in Directory.EnumerateFiles(sourceRoot, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (!SourceExtensions.Contains(Path.GetExtension(fullPath), StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var relative = Path.GetRelativePath(sourceRoot, fullPath);
|
||||
var (atlasName, key) = ClassifyPath(relative, options.GroupDepth, options.RootAtlasName);
|
||||
if (keys.TryGetValue(key, out var existing))
|
||||
{
|
||||
throw new InvalidDataException($"Duplicate region key '{key}': '{existing}' and '{relative}'.");
|
||||
}
|
||||
|
||||
keys.Add(key, relative);
|
||||
if (!groups.TryGetValue(atlasName, out var list))
|
||||
{
|
||||
list = [];
|
||||
groups.Add(atlasName, list);
|
||||
}
|
||||
|
||||
list.Add((fullPath, key));
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
private static AtlasGroupResult BuildGroup(
|
||||
string name, List<(string FullPath, string Key)> files, AtlasBuildOptions options)
|
||||
{
|
||||
var metadataPath = Path.Combine(options.OutputDirectory, name + ".atlas");
|
||||
if (!options.Force && IsUpToDate(metadataPath, files, options, out var existingPages))
|
||||
{
|
||||
return new AtlasGroupResult(name, files.Count, existingPages, Skipped: true);
|
||||
}
|
||||
|
||||
// Декодирование — самая дорогая фаза, параллелим (билд-тайм, аллокации допустимы).
|
||||
var images = new ImageResult[files.Count];
|
||||
Parallel.For(0, files.Count, i =>
|
||||
{
|
||||
using var stream = File.OpenRead(files[i].FullPath);
|
||||
images[i] = ImageResult.FromStream(stream, StbImageSharp.ColorComponents.RedGreenBlueAlpha);
|
||||
});
|
||||
|
||||
var items = new PackItem[files.Count];
|
||||
for (var i = 0; i < files.Count; i++)
|
||||
{
|
||||
items[i] = new PackItem(files[i].Key, images[i].Width, images[i].Height);
|
||||
}
|
||||
|
||||
var packed = ShelfPacker.Pack(items, options.MaxPageSize, options.Padding);
|
||||
|
||||
var pixelsByKey = new Dictionary<string, ImageResult>(files.Count, StringComparer.Ordinal);
|
||||
for (var i = 0; i < files.Count; i++)
|
||||
{
|
||||
pixelsByKey.Add(files[i].Key, images[i]);
|
||||
}
|
||||
|
||||
WritePages(name, packed, pixelsByKey, options.OutputDirectory);
|
||||
WriteMetadata(name, packed, options, metadataPath);
|
||||
DeleteExtraPages(name, packed.PageSizes.Count, options.OutputDirectory);
|
||||
|
||||
return new AtlasGroupResult(name, files.Count, packed.PageSizes.Count, Skipped: false);
|
||||
}
|
||||
|
||||
private static bool IsUpToDate(
|
||||
string metadataPath, List<(string FullPath, string Key)> files, AtlasBuildOptions options, out int pages)
|
||||
{
|
||||
pages = 0;
|
||||
if (!File.Exists(metadataPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
AtlasMetadata metadata;
|
||||
try
|
||||
{
|
||||
metadata = AtlasMetadata.FromJson(File.ReadAllText(metadataPath));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (metadata.PageSize != options.MaxPageSize || metadata.Padding != options.Padding)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var outputDirectory = Path.GetDirectoryName(metadataPath)!;
|
||||
if (metadata.Pages.Any(page => !File.Exists(Path.Combine(outputDirectory, page.File))))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!metadata.Regions.Select(r => r.Key).Order(StringComparer.Ordinal)
|
||||
.SequenceEqual(files.Select(f => f.Key).Order(StringComparer.Ordinal)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var builtAt = File.GetLastWriteTimeUtc(metadataPath);
|
||||
if (files.Any(f => File.GetLastWriteTimeUtc(f.FullPath) > builtAt))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
pages = metadata.Pages.Count;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void WritePages(
|
||||
string name, PackResult packed, Dictionary<string, ImageResult> pixelsByKey, string outputDirectory)
|
||||
{
|
||||
Parallel.For(0, packed.PageSizes.Count, page =>
|
||||
{
|
||||
var (width, height) = packed.PageSizes[page];
|
||||
var buffer = new byte[width * height * 4];
|
||||
foreach (var placement in packed.Placements)
|
||||
{
|
||||
if (placement.Page != page)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var source = pixelsByKey[placement.Key];
|
||||
for (var row = 0; row < source.Height; row++)
|
||||
{
|
||||
Array.Copy(
|
||||
source.Data, row * source.Width * 4,
|
||||
buffer, ((placement.Y + row) * width + placement.X) * 4,
|
||||
source.Width * 4);
|
||||
}
|
||||
}
|
||||
|
||||
using var stream = File.Create(Path.Combine(outputDirectory, PageFileName(name, page)));
|
||||
new ImageWriter().WritePng(
|
||||
buffer, width, height, StbImageWriteSharp.ColorComponents.RedGreenBlueAlpha, stream);
|
||||
});
|
||||
}
|
||||
|
||||
private static void WriteMetadata(string name, PackResult packed, AtlasBuildOptions options, string metadataPath)
|
||||
{
|
||||
var metadata = new AtlasMetadata
|
||||
{
|
||||
Name = name,
|
||||
PageSize = options.MaxPageSize,
|
||||
Padding = options.Padding,
|
||||
Pages = packed.PageSizes
|
||||
.Select((size, index) => new AtlasPage
|
||||
{
|
||||
File = PageFileName(name, index),
|
||||
Width = size.Width,
|
||||
Height = size.Height,
|
||||
})
|
||||
.ToList(),
|
||||
Regions = packed.Placements
|
||||
.OrderBy(p => p.Key, StringComparer.Ordinal)
|
||||
.Select(p => new AtlasRegion
|
||||
{
|
||||
Key = p.Key,
|
||||
Page = p.Page,
|
||||
X = p.X,
|
||||
Y = p.Y,
|
||||
Width = p.Width,
|
||||
Height = p.Height,
|
||||
})
|
||||
.ToList(),
|
||||
};
|
||||
|
||||
File.WriteAllText(metadataPath, metadata.ToJson());
|
||||
}
|
||||
|
||||
private static string PageFileName(string atlasName, int page) => $"{atlasName}.atlas.{page}.png";
|
||||
|
||||
private static void DeleteExtraPages(string name, int pageCount, string outputDirectory)
|
||||
{
|
||||
for (var page = pageCount; ; page++)
|
||||
{
|
||||
var path = Path.Combine(outputDirectory, PageFileName(name, page));
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> DeleteOrphans(string outputDirectory, IEnumerable<string> liveAtlasNames)
|
||||
{
|
||||
var live = liveAtlasNames.ToHashSet(StringComparer.Ordinal);
|
||||
var deleted = new List<string>();
|
||||
foreach (var metadataPath in Directory.EnumerateFiles(outputDirectory, "*.atlas"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(metadataPath);
|
||||
if (live.Contains(name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
File.Delete(metadataPath);
|
||||
deleted.Add(metadataPath);
|
||||
DeleteExtraPages(name, 0, outputDirectory);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MrGameEng.Atlases;
|
||||
|
||||
/// <summary>
|
||||
/// Serializable description of one packed atlas: its page image files and the source-relative
|
||||
/// region keys with their pixel rectangles. Stored as a JSON <c>.atlas</c> file next to the pages.
|
||||
/// </summary>
|
||||
public sealed class AtlasMetadata
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
|
||||
/// <summary>Format version, bumped on breaking metadata changes.</summary>
|
||||
public int Version { get; init; } = 1;
|
||||
|
||||
/// <summary>Atlas name (group key with '/' replaced by '.').</summary>
|
||||
public string Name { get; init; } = "";
|
||||
|
||||
/// <summary>Maximum page size the atlas was built with (staleness check input).</summary>
|
||||
public int PageSize { get; init; }
|
||||
|
||||
/// <summary>Padding in pixels the atlas was built with (staleness check input).</summary>
|
||||
public int Padding { get; init; }
|
||||
|
||||
/// <summary>Page image files (relative to the metadata file), in page-index order.</summary>
|
||||
public List<AtlasPage> Pages { get; init; } = [];
|
||||
|
||||
/// <summary>Packed regions, sorted by key.</summary>
|
||||
public List<AtlasRegion> Regions { get; init; } = [];
|
||||
|
||||
/// <summary>Serializes this metadata to indented JSON.</summary>
|
||||
public string ToJson() => JsonSerializer.Serialize(this, JsonOptions);
|
||||
|
||||
/// <summary>Parses metadata from JSON produced by <see cref="ToJson"/>.</summary>
|
||||
public static AtlasMetadata FromJson(string json) =>
|
||||
JsonSerializer.Deserialize<AtlasMetadata>(json, JsonOptions)
|
||||
?? throw new InvalidDataException("Atlas metadata JSON deserialized to null.");
|
||||
}
|
||||
|
||||
/// <summary>One page image of an atlas.</summary>
|
||||
public sealed class AtlasPage
|
||||
{
|
||||
/// <summary>Image file name, relative to the metadata file.</summary>
|
||||
public string File { get; init; } = "";
|
||||
|
||||
/// <summary>Page width in pixels.</summary>
|
||||
public int Width { get; init; }
|
||||
|
||||
/// <summary>Page height in pixels.</summary>
|
||||
public int Height { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>One packed source texture inside an atlas.</summary>
|
||||
public sealed class AtlasRegion
|
||||
{
|
||||
/// <summary>
|
||||
/// Region key: the source path relative to the build source root, forward slashes,
|
||||
/// without the file extension (e.g. <c>Things/Pawn/Animal/Fox</c>).
|
||||
/// </summary>
|
||||
public string Key { get; init; } = "";
|
||||
|
||||
/// <summary>Index of the page containing this region.</summary>
|
||||
public int Page { get; init; }
|
||||
|
||||
/// <summary>X of the region in page pixels.</summary>
|
||||
public int X { get; init; }
|
||||
|
||||
/// <summary>Y of the region in page pixels.</summary>
|
||||
public int Y { get; init; }
|
||||
|
||||
/// <summary>Region width in pixels.</summary>
|
||||
[JsonPropertyName("w")]
|
||||
public int Width { get; init; }
|
||||
|
||||
/// <summary>Region height in pixels.</summary>
|
||||
[JsonPropertyName("h")]
|
||||
public int Height { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using MrGameEng.Assets;
|
||||
using MrGameEng.Core;
|
||||
|
||||
namespace MrGameEng.Atlases;
|
||||
|
||||
/// <summary>Wires the atlases module into the engine.</summary>
|
||||
public static class AtlasesEngineExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the <see cref="TextureAtlas"/> loader on the <see cref="AssetManager"/>,
|
||||
/// enabling <c>assets.Load(GameAssets.…)</c> for generated <c>.atlas</c> handles.
|
||||
/// Call once at startup after <see cref="AssetsEngineExtensions.UseAssets"/>.
|
||||
/// </summary>
|
||||
public static void UseTextureAtlases(this EngineContext context)
|
||||
{
|
||||
var assets = context.Services.Get<AssetManager>();
|
||||
assets.RegisterLoader((_, path) => TextureAtlas.Load(context.GraphicsDevice, path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="MrGameEng.Atlases.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="StbImageSharp" />
|
||||
<PackageReference Include="StbImageWriteSharp" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
<ProjectReference Include="..\MrGameEng.Graphics\MrGameEng.Graphics.csproj" />
|
||||
<ProjectReference Include="..\MrGameEng.Assets\MrGameEng.Assets.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,132 @@
|
||||
namespace MrGameEng.Atlases;
|
||||
|
||||
/// <summary>Input rectangle for the packer: an opaque key plus pixel dimensions.</summary>
|
||||
/// <param name="Key">Caller-defined identifier carried through to the placement.</param>
|
||||
/// <param name="Width">Width in pixels.</param>
|
||||
/// <param name="Height">Height in pixels.</param>
|
||||
public readonly record struct PackItem(string Key, int Width, int Height);
|
||||
|
||||
/// <summary>Where one item ended up: page index plus position in page pixels.</summary>
|
||||
/// <param name="Key">Key of the packed item.</param>
|
||||
/// <param name="Page">Index into <see cref="PackResult.PageSizes"/>.</param>
|
||||
/// <param name="X">X position in page pixels.</param>
|
||||
/// <param name="Y">Y position in page pixels.</param>
|
||||
/// <param name="Width">Item width in pixels.</param>
|
||||
/// <param name="Height">Item height in pixels.</param>
|
||||
public readonly record struct PackPlacement(string Key, int Page, int X, int Y, int Width, int Height);
|
||||
|
||||
/// <summary>Result of a packing run: placements plus the trimmed size of every page.</summary>
|
||||
/// <param name="Placements">One placement per input item.</param>
|
||||
/// <param name="PageSizes">Width/height of each page, trimmed to the next power of two covering its content.</param>
|
||||
public sealed record PackResult(IReadOnlyList<PackPlacement> Placements, IReadOnlyList<(int Width, int Height)> PageSizes);
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic shelf packer: items are sorted by height (then width, then key) and laid out
|
||||
/// in horizontal shelves; a new page starts when a shelf does not fit. Simple and fast, with
|
||||
/// good occupancy for sprite sets of similar heights. Items larger than the page size get a
|
||||
/// dedicated page of their own exact size.
|
||||
/// </summary>
|
||||
public static class ShelfPacker
|
||||
{
|
||||
/// <summary>
|
||||
/// Packs <paramref name="items"/> into pages of at most <paramref name="maxPageSize"/>²
|
||||
/// pixels keeping <paramref name="padding"/> pixels between items and page edges.
|
||||
/// </summary>
|
||||
public static PackResult Pack(IReadOnlyList<PackItem> items, int maxPageSize, int padding)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxPageSize, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(padding);
|
||||
|
||||
var sorted = items.ToList();
|
||||
sorted.Sort(static (a, b) =>
|
||||
{
|
||||
var byHeight = b.Height.CompareTo(a.Height);
|
||||
if (byHeight != 0)
|
||||
{
|
||||
return byHeight;
|
||||
}
|
||||
|
||||
var byWidth = b.Width.CompareTo(a.Width);
|
||||
return byWidth != 0 ? byWidth : string.CompareOrdinal(a.Key, b.Key);
|
||||
});
|
||||
|
||||
var placements = new List<PackPlacement>(items.Count);
|
||||
var pageSizes = new List<(int Width, int Height)>();
|
||||
|
||||
// Открытая страница ещё не записана в pageSizes — её индекс всегда pageSizes.Count.
|
||||
var open = false;
|
||||
var x = 0;
|
||||
var y = 0;
|
||||
var shelfHeight = 0;
|
||||
var usedWidth = 0;
|
||||
var usedHeight = 0;
|
||||
|
||||
void CloseOpenPage()
|
||||
{
|
||||
if (open)
|
||||
{
|
||||
pageSizes.Add((NextPowerOfTwo(usedWidth + padding), NextPowerOfTwo(usedHeight + padding)));
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
|
||||
void OpenFreshPage()
|
||||
{
|
||||
CloseOpenPage();
|
||||
open = true;
|
||||
x = padding;
|
||||
y = padding;
|
||||
shelfHeight = 0;
|
||||
usedWidth = 0;
|
||||
usedHeight = 0;
|
||||
}
|
||||
|
||||
foreach (var item in sorted)
|
||||
{
|
||||
// Слишком большой для общей страницы — отдельная страница точно под него.
|
||||
if (item.Width + 2 * padding > maxPageSize || item.Height + 2 * padding > maxPageSize)
|
||||
{
|
||||
CloseOpenPage();
|
||||
placements.Add(new PackPlacement(item.Key, pageSizes.Count, padding, padding, item.Width, item.Height));
|
||||
pageSizes.Add((NextPowerOfTwo(item.Width + 2 * padding), NextPowerOfTwo(item.Height + 2 * padding)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!open)
|
||||
{
|
||||
OpenFreshPage();
|
||||
}
|
||||
else if (x + item.Width + padding > maxPageSize)
|
||||
{
|
||||
// Конец полки: следующая полка ниже; если не влезает по высоте — новая страница.
|
||||
y += shelfHeight + padding;
|
||||
x = padding;
|
||||
shelfHeight = 0;
|
||||
if (y + item.Height + padding > maxPageSize)
|
||||
{
|
||||
OpenFreshPage();
|
||||
}
|
||||
}
|
||||
|
||||
placements.Add(new PackPlacement(item.Key, pageSizes.Count, x, y, item.Width, item.Height));
|
||||
x += item.Width + padding;
|
||||
shelfHeight = Math.Max(shelfHeight, item.Height);
|
||||
usedWidth = Math.Max(usedWidth, x - padding);
|
||||
usedHeight = Math.Max(usedHeight, y + item.Height);
|
||||
}
|
||||
|
||||
CloseOpenPage();
|
||||
return new PackResult(placements, pageSizes);
|
||||
}
|
||||
|
||||
internal static int NextPowerOfTwo(int value)
|
||||
{
|
||||
var result = 1;
|
||||
while (result < value)
|
||||
{
|
||||
result <<= 1;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Atlases;
|
||||
|
||||
/// <summary>
|
||||
/// A loaded texture atlas: page textures plus a lookup from region key (source-relative path
|
||||
/// without extension, e.g. <c>Things/Pawn/Animal/Fox</c>) to <see cref="Texture2DRegion"/>.
|
||||
/// Sprites taken from one atlas page batch into a single draw call automatically.
|
||||
/// Owns its page textures and disposes them with the atlas.
|
||||
/// </summary>
|
||||
public sealed class TextureAtlas : IDisposable
|
||||
{
|
||||
private readonly Dictionary<string, Texture2DRegion> _regions;
|
||||
|
||||
/// <summary>Atlas name from the metadata.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>Page textures, in page-index order.</summary>
|
||||
public IReadOnlyList<Texture2D> Pages { get; }
|
||||
|
||||
/// <summary>All regions by key.</summary>
|
||||
public IReadOnlyDictionary<string, Texture2DRegion> Regions => _regions;
|
||||
|
||||
/// <summary>Creates an atlas over already-loaded page textures.</summary>
|
||||
public TextureAtlas(AtlasMetadata metadata, IReadOnlyList<Texture2D> pages)
|
||||
{
|
||||
Name = metadata.Name;
|
||||
Pages = pages;
|
||||
_regions = new Dictionary<string, Texture2DRegion>(metadata.Regions.Count, StringComparer.Ordinal);
|
||||
foreach (var region in metadata.Regions)
|
||||
{
|
||||
_regions.Add(
|
||||
region.Key,
|
||||
new Texture2DRegion(
|
||||
pages[region.Page],
|
||||
new Rectangle(region.X, region.Y, region.Width, region.Height)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the region for <paramref name="key"/>; throws when the key is unknown.</summary>
|
||||
public Texture2DRegion GetRegion(string key) =>
|
||||
_regions.TryGetValue(key, out var region)
|
||||
? region
|
||||
: throw new KeyNotFoundException($"Atlas '{Name}' has no region '{key}'.");
|
||||
|
||||
/// <summary>Returns the region for <paramref name="key"/> or false when unknown.</summary>
|
||||
public bool TryGetRegion(string key, out Texture2DRegion region) =>
|
||||
_regions.TryGetValue(key, out region!);
|
||||
|
||||
/// <summary>
|
||||
/// Loads an atlas from a <c>.atlas</c> metadata file; page images are loaded from the same
|
||||
/// directory with premultiplied alpha (matching the engine's texture loader).
|
||||
/// </summary>
|
||||
public static TextureAtlas Load(GraphicsDevice graphicsDevice, string metadataPath)
|
||||
{
|
||||
var metadata = AtlasMetadata.FromJson(File.ReadAllText(metadataPath));
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(metadataPath))!;
|
||||
var pages = new Texture2D[metadata.Pages.Count];
|
||||
for (var i = 0; i < pages.Length; i++)
|
||||
{
|
||||
using var stream = File.OpenRead(Path.Combine(directory, metadata.Pages[i].File));
|
||||
pages[i] = Texture2D.FromStream(graphicsDevice, stream, DefaultColorProcessors.PremultiplyAlpha);
|
||||
}
|
||||
|
||||
return new TextureAtlas(metadata, pages);
|
||||
}
|
||||
|
||||
/// <summary>Disposes every page texture.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var page in Pages)
|
||||
{
|
||||
page?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>Shape of a <see cref="Collider"/>.</summary>
|
||||
public enum ColliderShape : byte
|
||||
{
|
||||
/// <summary>Circle of <see cref="Collider.Radius"/>.</summary>
|
||||
Circle,
|
||||
|
||||
/// <summary>Axis-aligned box of <see cref="Collider.HalfExtents"/>. Does not rotate with the entity.</summary>
|
||||
Box,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collision shape component. Create via <see cref="Circle"/> or <see cref="Box"/> —
|
||||
/// the struct default has no size and collides with nothing.
|
||||
/// Positions come from <c>Transform2D</c>; <see cref="Offset"/> shifts the shape
|
||||
/// relative to it (entity scale and rotation are not applied to collider shapes).
|
||||
/// </summary>
|
||||
public struct Collider : IComponent
|
||||
{
|
||||
/// <summary>Shape kind.</summary>
|
||||
public ColliderShape Shape;
|
||||
|
||||
/// <summary>Circle radius in world units (<see cref="ColliderShape.Circle"/> only).</summary>
|
||||
public float Radius;
|
||||
|
||||
/// <summary>Half extents of the box (<see cref="ColliderShape.Box"/> only).</summary>
|
||||
public Vector2 HalfExtents;
|
||||
|
||||
/// <summary>Shape center offset from the entity's transform position.</summary>
|
||||
public Vector2 Offset;
|
||||
|
||||
/// <summary>Bit mask of layers this collider belongs to.</summary>
|
||||
public uint Layer;
|
||||
|
||||
/// <summary>Bit mask of layers this collider collides with. A pair is reported only when the masks agree both ways.</summary>
|
||||
public uint CollidesWith;
|
||||
|
||||
/// <summary>Creates a circle collider on layer 1 colliding with everything.</summary>
|
||||
public static Collider Circle(float radius, Vector2 offset = default) => new()
|
||||
{
|
||||
Shape = ColliderShape.Circle,
|
||||
Radius = radius,
|
||||
Offset = offset,
|
||||
Layer = 1,
|
||||
CollidesWith = uint.MaxValue,
|
||||
};
|
||||
|
||||
/// <summary>Creates a box collider on layer 1 colliding with everything.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Friflo.Engine.ECS.Systems;
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the <see cref="CollisionWorld"/> from every entity that has both
|
||||
/// <c>Transform2D</c> and <see cref="Collider"/>. Register it <b>after</b> movement
|
||||
/// systems so pairs reflect this tick's final positions.
|
||||
/// </summary>
|
||||
public sealed class CollisionSystem : QuerySystem<Transform2D, Collider>
|
||||
{
|
||||
private readonly CollisionWorld _world;
|
||||
|
||||
/// <summary>Creates the system for <paramref name="world"/>.</summary>
|
||||
public CollisionSystem(CollisionWorld world) => _world = world;
|
||||
|
||||
/// <inheritdoc />
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wires collision detection into a <see cref="Scene"/>.</summary>
|
||||
public static class SceneCollisionsExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the shared <see cref="CollisionWorld"/> service (created on first use with
|
||||
/// <paramref name="cellSize"/>) and adds <see cref="CollisionSystem"/> to this scene's
|
||||
/// update phase. Call from <c>OnLoad</c> <b>after</b> adding movement systems; read
|
||||
/// <see cref="CollisionWorld.Pairs"/> from systems registered later.
|
||||
/// </summary>
|
||||
public static CollisionWorld UseCollisions(this Scene scene, float cellSize = 64f)
|
||||
{
|
||||
var services = scene.Context.Services;
|
||||
var world = services.GetOrDefault<CollisionWorld>();
|
||||
if (world is null)
|
||||
{
|
||||
world = new CollisionWorld(cellSize);
|
||||
services.Add(world);
|
||||
}
|
||||
|
||||
scene.UpdateSystems.Add(new CollisionSystem(world));
|
||||
return world;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>A pair of entities whose colliders overlap this frame.</summary>
|
||||
public readonly record struct CollisionPair(Entity A, Entity B);
|
||||
|
||||
/// <summary>Result of a <see cref="CollisionWorld.Raycast"/>.</summary>
|
||||
public readonly record struct RaycastHit(Entity Entity, Vector2 Point, float Fraction);
|
||||
|
||||
/// <summary>
|
||||
/// Broad + narrow phase collision detection over a uniform spatial hash, rebuilt from
|
||||
/// scratch every tick by <see cref="CollisionSystem"/> — O(n) for moving entities, flat
|
||||
/// arrays only, no allocations after warm-up. Overlapping pairs are collected into
|
||||
/// <see cref="Pairs"/> (deterministic order); ad-hoc area/ray queries are available to
|
||||
/// game systems at any point after the rebuild.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates a world. <paramref name="cellSize"/> should match typical collider size.</summary>
|
||||
public CollisionWorld(float cellSize = 64f)
|
||||
{
|
||||
if (cellSize <= 0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(cellSize));
|
||||
}
|
||||
|
||||
_cellSize = cellSize;
|
||||
}
|
||||
|
||||
/// <summary>Pairs found by the last rebuild.</summary>
|
||||
public ReadOnlySpan<CollisionPair> Pairs => _pairs.AsSpan(0, _pairCount);
|
||||
|
||||
/// <summary>Colliders registered in the last rebuild.</summary>
|
||||
public int Count => _count;
|
||||
|
||||
/// <summary>Starts a rebuild. Called by <see cref="CollisionSystem"/> once per tick.</summary>
|
||||
public void BeginRebuild()
|
||||
{
|
||||
_count = 0;
|
||||
_cellCount = 0;
|
||||
_pairCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>Registers one collider. Order of registration defines pair order (keep it deterministic).</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Builds the hash and collects all overlapping pairs.</summary>
|
||||
public void EndRebuild()
|
||||
{
|
||||
BuildHash();
|
||||
CollectPairs();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes entities whose colliders overlap <paramref name="area"/> into
|
||||
/// <paramref name="results"/>; returns the count (truncated to the span length).
|
||||
/// </summary>
|
||||
public int QueryAabb(in RectF area, Span<Entity> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Casts a segment and returns the closest hit among colliders whose
|
||||
/// <see cref="Collider.Layer"/> intersects <paramref name="mask"/>.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
<ProjectReference Include="..\MrGameEng.Graphics\MrGameEng.Graphics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,244 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>
|
||||
/// A flow field: per-cell distance to the nearest goal and a normalized direction to follow.
|
||||
/// Built once per goal change by <see cref="FlowFieldBuilder"/>, then any number of agents
|
||||
/// steer by an O(1) lookup per frame — the tool of choice for crowds heading to shared targets.
|
||||
/// </summary>
|
||||
public sealed class FlowField
|
||||
{
|
||||
/// <summary>Grid width in cells.</summary>
|
||||
public int Width { get; private set; }
|
||||
|
||||
/// <summary>Grid height in cells.</summary>
|
||||
public int Height { get; private set; }
|
||||
|
||||
internal float[] Distances = [];
|
||||
internal Vector2[] Directions = [];
|
||||
|
||||
/// <summary>Cost-weighted distance to the nearest goal; <see cref="float.PositiveInfinity"/> when unreachable.</summary>
|
||||
public float DistanceAt(int x, int y) => Distances[y * Width + x];
|
||||
|
||||
/// <summary>Normalized direction toward the nearest goal; <see cref="Vector2.Zero"/> at goals and unreachable cells.</summary>
|
||||
public Vector2 DirectionAt(int x, int y) => Directions[y * Width + x];
|
||||
|
||||
/// <summary>True when a path to a goal exists from this cell.</summary>
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds <see cref="FlowField"/>s with a multi-source Dijkstra over an <see cref="IPathGrid"/>.
|
||||
/// Buffers are reused between builds (no allocations after warm-up). One instance per system.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates a builder bound to <paramref name="grid"/>.</summary>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills <paramref name="field"/> with distances and directions toward the nearest of
|
||||
/// <paramref name="goals"/>. Impassable goals are ignored; with no valid goal the whole
|
||||
/// field is unreachable.
|
||||
/// </summary>
|
||||
public void Build(ReadOnlySpan<Point> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>Algorithm used by <see cref="GridPathfinder.FindPath"/>.</summary>
|
||||
public enum PathAlgorithm
|
||||
{
|
||||
/// <summary>Best general choice: cost-aware, goal-directed (octile/Manhattan heuristic).</summary>
|
||||
AStar,
|
||||
|
||||
/// <summary>Cost-aware without a heuristic. Slower than A*, useful as a reference.</summary>
|
||||
Dijkstra,
|
||||
|
||||
/// <summary>Fastest for uniform-cost grids; ignores <see cref="IPathGrid.Cost"/>.</summary>
|
||||
BreadthFirst,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grid pathfinder with A*, Dijkstra and BFS over an <see cref="IPathGrid"/>.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Creates a pathfinder bound to <paramref name="grid"/>.</summary>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a path from <paramref name="start"/> to <paramref name="goal"/> (both inclusive)
|
||||
/// and writes it into <paramref name="path"/>. Returns false when no path exists;
|
||||
/// the list is cleared either way.
|
||||
/// </summary>
|
||||
public bool FindPath(Point start, Point goal, List<Point> 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<Point> 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<Point> 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;
|
||||
}
|
||||
|
||||
/// <summary>True when the move is in bounds, passable and does not cut a corner.</summary>
|
||||
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<Point> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>Neighbor connectivity of a grid.</summary>
|
||||
public enum GridConnectivity
|
||||
{
|
||||
/// <summary>Orthogonal moves only.</summary>
|
||||
Four = 4,
|
||||
|
||||
/// <summary>Orthogonal and diagonal moves. Diagonals never cut corners.</summary>
|
||||
Eight = 8,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A grid the pathfinding algorithms operate on. The game implements this over its own
|
||||
/// world representation (terrain cells, a <c>TileGrid</c>, …) — the pathfinding module
|
||||
/// never owns world data.
|
||||
/// </summary>
|
||||
public interface IPathGrid
|
||||
{
|
||||
/// <summary>Grid width in cells.</summary>
|
||||
int Width { get; }
|
||||
|
||||
/// <summary>Grid height in cells.</summary>
|
||||
int Height { get; }
|
||||
|
||||
/// <summary>True when the cell can be entered. Out-of-range cells are never queried.</summary>
|
||||
bool IsPassable(int x, int y);
|
||||
|
||||
/// <summary>
|
||||
/// Cost multiplier for entering the cell, <b>must be ≥ 1</b> (1 = normal terrain,
|
||||
/// 3 = swamp three times slower, …). Used by A* and Dijkstra; ignored by BFS.
|
||||
/// </summary>
|
||||
float Cost(int x, int y);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="MrGameEng.Tilemaps.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
<ProjectReference Include="..\MrGameEng.Graphics\MrGameEng.Graphics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>Wires the tilemaps module into a <see cref="Scene"/>.</summary>
|
||||
public static class SceneTilemapExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds <see cref="TilemapRenderSystem"/> to the scene's draw phase, right before the
|
||||
/// renderer flush. Call from <c>OnLoad</c> after <c>UseRenderer2D()</c>.
|
||||
/// </summary>
|
||||
public static void UseTilemaps(this Scene scene)
|
||||
{
|
||||
var renderer = scene.Context.Services.GetOrDefault<Renderer2D>()
|
||||
?? throw new InvalidOperationException("UseTilemaps requires UseRenderer2D to be called first.");
|
||||
|
||||
var systems = scene.DrawSystems.ChildSystems;
|
||||
for (var i = 0; i < systems.Count; i++)
|
||||
{
|
||||
if (systems[i] is RenderFlushSystem)
|
||||
{
|
||||
scene.DrawSystems.Insert(i, new TilemapRenderSystem(renderer));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("RenderFlushSystem not found (is UseRenderer2D wired on this scene?).");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>
|
||||
/// Dense rectangular grid of tile ids (see <see cref="TileSet"/>; 0 = empty).
|
||||
/// Plain data with bounds-checked access — fill it from worldgen code, mutate at runtime.
|
||||
/// </summary>
|
||||
public sealed class TileGrid
|
||||
{
|
||||
private readonly ushort[] _cells;
|
||||
|
||||
/// <summary>Grid width in cells.</summary>
|
||||
public int Width { get; }
|
||||
|
||||
/// <summary>Grid height in cells.</summary>
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>Creates a grid filled with the empty tile.</summary>
|
||||
public TileGrid(int width, int height)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(width, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(height, 1);
|
||||
Width = width;
|
||||
Height = height;
|
||||
_cells = new ushort[width * height];
|
||||
}
|
||||
|
||||
/// <summary>Tile id at the given cell.</summary>
|
||||
public ushort this[int x, int y]
|
||||
{
|
||||
get
|
||||
{
|
||||
CheckBounds(x, y);
|
||||
return _cells[y * Width + x];
|
||||
}
|
||||
set
|
||||
{
|
||||
CheckBounds(x, y);
|
||||
_cells[y * Width + x] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when the cell lies inside the grid.</summary>
|
||||
public bool Contains(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height;
|
||||
|
||||
/// <summary>Sets every cell to <paramref name="id"/>.</summary>
|
||||
public void Fill(ushort id) => Array.Fill(_cells, id);
|
||||
|
||||
/// <summary>Unchecked read used by the render system after range clamping.</summary>
|
||||
internal ushort UnsafeGet(int x, int y) => _cells[y * Width + x];
|
||||
|
||||
private void CheckBounds(int x, int y)
|
||||
{
|
||||
if (!Contains(x, y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(x), $"Cell ({x},{y}) is outside the {Width}x{Height} grid.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>One tile kind: a texture region plus a tint multiplier.</summary>
|
||||
/// <param name="Region">Texture region the tile is drawn with.</param>
|
||||
/// <param name="Color">Tint, multiplied with the texture. White = unmodified.</param>
|
||||
public readonly record struct TileDef(Texture2DRegion Region, Color Color)
|
||||
{
|
||||
/// <summary>Creates an untinted tile.</summary>
|
||||
public TileDef(Texture2DRegion region)
|
||||
: this(region, Color.White)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps tile ids to <see cref="TileDef"/>s. Built in code: every <see cref="Add"/> returns
|
||||
/// the id to store in a <see cref="TileGrid"/>. Id 0 is reserved for "empty" (nothing drawn).
|
||||
/// </summary>
|
||||
public sealed class TileSet
|
||||
{
|
||||
private readonly List<TileDef> _tiles = [default];
|
||||
|
||||
/// <summary>Number of defined tiles including the reserved empty tile 0.</summary>
|
||||
public int Count => _tiles.Count;
|
||||
|
||||
/// <summary>The tile definition for <paramref name="id"/>. Id 0 has no region.</summary>
|
||||
public TileDef this[int id] => _tiles[id];
|
||||
|
||||
/// <summary>Defines a tile and returns its id (1, 2, …).</summary>
|
||||
public ushort Add(Texture2DRegion region, Color? color = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(region);
|
||||
if (_tiles.Count > ushort.MaxValue)
|
||||
{
|
||||
throw new InvalidOperationException("A TileSet holds at most 65535 tiles.");
|
||||
}
|
||||
|
||||
_tiles.Add(new TileDef(region, color ?? Color.White));
|
||||
return (ushort)(_tiles.Count - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>
|
||||
/// Tilemap component: a <see cref="TileGrid"/> of ids drawn with a <see cref="TileSet"/>.
|
||||
/// Cell (0,0) sits at <see cref="Origin"/>, cells are <see cref="TileSize"/> world units square.
|
||||
/// Only the cells visible through the camera are submitted each frame, so grids can be large.
|
||||
/// Create via the constructor — the struct default has no grid and draws nothing.
|
||||
/// </summary>
|
||||
public struct Tilemap : IComponent
|
||||
{
|
||||
/// <summary>Tile definitions; ids in the grid index into it.</summary>
|
||||
public TileSet? TileSet;
|
||||
|
||||
/// <summary>The cells. Mutating ids takes effect next frame.</summary>
|
||||
public TileGrid? Grid;
|
||||
|
||||
/// <summary>World position of the top-left corner of cell (0,0).</summary>
|
||||
public Vector2 Origin;
|
||||
|
||||
/// <summary>Cell size in world units.</summary>
|
||||
public float TileSize;
|
||||
|
||||
/// <summary>Render layer of the whole map.</summary>
|
||||
public LayerId Layer;
|
||||
|
||||
/// <summary>Draw order within the layer (smaller = drawn first / behind).</summary>
|
||||
public float Depth;
|
||||
|
||||
/// <summary>Tint multiplied into every tile on top of its <see cref="TileDef.Color"/>.</summary>
|
||||
public Color Color;
|
||||
|
||||
/// <summary>Creates a tilemap at world origin.</summary>
|
||||
public Tilemap(TileGrid grid, TileSet tileSet, float tileSize, LayerId layer = default)
|
||||
{
|
||||
Grid = grid;
|
||||
TileSet = tileSet;
|
||||
TileSize = tileSize;
|
||||
Layer = layer;
|
||||
Origin = Vector2.Zero;
|
||||
Depth = 0f;
|
||||
Color = Color.White;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>Pure cell-range math for tilemap rendering. Y axis points down.</summary>
|
||||
public static class TilemapMath
|
||||
{
|
||||
/// <summary>
|
||||
/// Computes the inclusive cell range of a grid that intersects <paramref name="cullRect"/>.
|
||||
/// Returns false when the map is entirely outside the rectangle.
|
||||
/// </summary>
|
||||
public static bool VisibleCells(
|
||||
in RectF cullRect, Vector2 origin, float tileSize, int width, int height,
|
||||
out int x0, out int y0, out int x1, out int y1)
|
||||
{
|
||||
x0 = Math.Max(0, (int)MathF.Floor((cullRect.Left - origin.X) / tileSize));
|
||||
y0 = Math.Max(0, (int)MathF.Floor((cullRect.Top - origin.Y) / tileSize));
|
||||
x1 = Math.Min(width - 1, (int)MathF.Floor((cullRect.Right - origin.X) / tileSize));
|
||||
y1 = Math.Min(height - 1, (int)MathF.Floor((cullRect.Bottom - origin.Y) / tileSize));
|
||||
return x0 <= x1 && y0 <= y1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Friflo.Engine.ECS.Systems;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Tilemaps;
|
||||
|
||||
/// <summary>
|
||||
/// Submits the camera-visible cells of every <see cref="Tilemap"/> entity to the renderer.
|
||||
/// Cells outside the camera are never touched, so per-frame cost scales with the screen,
|
||||
/// not with the grid. Tiles batch with sprites by the usual layer → depth → texture order.
|
||||
/// </summary>
|
||||
public sealed class TilemapRenderSystem : QuerySystem<Tilemap>
|
||||
{
|
||||
private readonly Renderer2D _renderer;
|
||||
|
||||
/// <summary>Creates the system for <paramref name="renderer"/>.</summary>
|
||||
public TilemapRenderSystem(Renderer2D renderer) => _renderer = renderer;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
var cullRect = _renderer.Camera.CullRect;
|
||||
foreach (var (maps, _) in Query.Chunks)
|
||||
{
|
||||
foreach (ref readonly var map in maps.Span)
|
||||
{
|
||||
if (map.Grid is not { } grid || map.TileSet is not { } tileSet || map.TileSize <= 0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var screenSpace = _renderer.Layers[map.Layer].Space == LayerSpace.Screen;
|
||||
if (screenSpace)
|
||||
{
|
||||
// Screen-space слои не куллятся камерой — рисуем весь грид.
|
||||
SubmitRange(in map, grid, tileSet, 0, 0, grid.Width - 1, grid.Height - 1);
|
||||
}
|
||||
else if (TilemapMath.VisibleCells(
|
||||
in cullRect, map.Origin, map.TileSize, grid.Width, grid.Height,
|
||||
out var x0, out var y0, out var x1, out var y1))
|
||||
{
|
||||
SubmitRange(in map, grid, tileSet, x0, y0, x1, y1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SubmitRange(in Tilemap map, TileGrid grid, TileSet tileSet, int x0, int y0, int x1, int y1)
|
||||
{
|
||||
for (var y = y0; y <= y1; y++)
|
||||
{
|
||||
for (var x = x0; x <= x1; x++)
|
||||
{
|
||||
var id = grid.UnsafeGet(x, y);
|
||||
if (id == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var def = tileSet[id];
|
||||
var region = def.Region;
|
||||
var transform = new Transform2D(
|
||||
map.Origin + new Vector2(x, y) * map.TileSize,
|
||||
scale: new Vector2(map.TileSize / region.Width, map.TileSize / region.Height));
|
||||
var sprite = new Sprite(region, map.Layer)
|
||||
{
|
||||
Color = map.Color == Color.White
|
||||
? def.Color
|
||||
: new Color(def.Color.ToVector4() * map.Color.ToVector4()),
|
||||
Depth = map.Depth,
|
||||
};
|
||||
_renderer.Submit(in transform, in sprite);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,22 @@ public class AssetHandlesGeneratorTests
|
||||
Assert.DoesNotContain("Image", source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AtlasFiles_GetTextureAtlasHandles_AndPagesAreExcluded()
|
||||
{
|
||||
var source = RunGenerator(
|
||||
[
|
||||
@"D:\game\Assets\Atlases\Things.Pawn.atlas",
|
||||
@"D:\game\Assets\Atlases\Things.Pawn.atlas.0.png",
|
||||
@"D:\game\Assets\Atlases\Things.Pawn.atlas.1.png",
|
||||
]);
|
||||
|
||||
Assert.Contains(
|
||||
"AssetRef<global::MrGameEng.Atlases.TextureAtlas> ThingsPawn = new(\"Atlases/Things.Pawn.atlas\")",
|
||||
source);
|
||||
Assert.DoesNotContain("Texture2D> ThingsPawn", source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NestedDirectories_BecomeNestedClasses()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
using StbImageSharp;
|
||||
using StbImageWriteSharp;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Atlases.Tests;
|
||||
|
||||
public sealed class AtlasBuilderTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Directory.CreateTempSubdirectory("mrge-atlas-tests-").FullName;
|
||||
|
||||
private string SourceDir => Path.Combine(_root, "Textures");
|
||||
private string OutputDir => Path.Combine(_root, "Atlases");
|
||||
|
||||
public void Dispose() => Directory.Delete(_root, recursive: true);
|
||||
|
||||
/// <summary>Writes a PNG filled with one RGBA color.</summary>
|
||||
private void WritePng(string relativePath, int width, int height, byte r, byte g, byte b, byte a = 255)
|
||||
{
|
||||
var fullPath = Path.Combine(SourceDir, relativePath);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
|
||||
var data = new byte[width * height * 4];
|
||||
for (var i = 0; i < data.Length; i += 4)
|
||||
{
|
||||
data[i] = r;
|
||||
data[i + 1] = g;
|
||||
data[i + 2] = b;
|
||||
data[i + 3] = a;
|
||||
}
|
||||
|
||||
using var stream = File.Create(fullPath);
|
||||
new ImageWriter().WritePng(data, width, height, StbImageWriteSharp.ColorComponents.RedGreenBlueAlpha, stream);
|
||||
}
|
||||
|
||||
private AtlasBuildOptions Options(int groupDepth = 1, bool force = false) => new()
|
||||
{
|
||||
SourceDirectory = SourceDir,
|
||||
OutputDirectory = OutputDir,
|
||||
GroupDepth = groupDepth,
|
||||
MaxPageSize = 128,
|
||||
Padding = 2,
|
||||
Force = force,
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[InlineData("Terrain/Surfaces/Marsh.png", 1, "Terrain", "Terrain/Surfaces/Marsh")]
|
||||
[InlineData("Terrain/Surfaces/Marsh.png", 2, "Terrain.Surfaces", "Terrain/Surfaces/Marsh")]
|
||||
[InlineData("Terrain/Surfaces/Marsh.png", 0, "Root", "Terrain/Surfaces/Marsh")]
|
||||
[InlineData("loose.png", 3, "Root", "loose")]
|
||||
public void ClassifyPath_GroupsByDepth(string path, int depth, string expectedAtlas, string expectedKey)
|
||||
{
|
||||
var (atlas, key) = AtlasBuilder.ClassifyPath(path, depth, "Root");
|
||||
|
||||
Assert.Equal(expectedAtlas, atlas);
|
||||
Assert.Equal(expectedKey, key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_WritesMetadataAndPages_PixelsSurviveRoundtrip()
|
||||
{
|
||||
WritePng("Terrain/Grass.png", 16, 16, 10, 200, 30);
|
||||
WritePng("Terrain/Water.png", 16, 8, 30, 40, 250);
|
||||
|
||||
var result = AtlasBuilder.Build(Options());
|
||||
|
||||
var group = Assert.Single(result.Groups);
|
||||
Assert.Equal("Terrain", group.Name);
|
||||
Assert.Equal(2, group.RegionCount);
|
||||
Assert.False(group.Skipped);
|
||||
|
||||
var metadata = AtlasMetadata.FromJson(File.ReadAllText(Path.Combine(OutputDir, "Terrain.atlas")));
|
||||
Assert.Equal(["Terrain/Grass", "Terrain/Water"], metadata.Regions.Select(x => x.Key));
|
||||
|
||||
var grass = metadata.Regions.Single(x => x.Key == "Terrain/Grass");
|
||||
var page = metadata.Pages[grass.Page];
|
||||
using var stream = File.OpenRead(Path.Combine(OutputDir, page.File));
|
||||
var pixels = ImageResult.FromStream(stream, StbImageSharp.ColorComponents.RedGreenBlueAlpha);
|
||||
|
||||
// Центральный пиксель региона должен быть цветом исходной картинки.
|
||||
var center = ((grass.Y + 8) * pixels.Width + grass.X + 8) * 4;
|
||||
Assert.Equal((byte)10, pixels.Data[center]);
|
||||
Assert.Equal((byte)200, pixels.Data[center + 1]);
|
||||
Assert.Equal((byte)30, pixels.Data[center + 2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_SecondRunWithoutChanges_SkipsGroup()
|
||||
{
|
||||
WritePng("UI/button.png", 8, 8, 1, 2, 3);
|
||||
|
||||
var first = AtlasBuilder.Build(Options());
|
||||
var second = AtlasBuilder.Build(Options());
|
||||
|
||||
Assert.False(Assert.Single(first.Groups).Skipped);
|
||||
Assert.True(Assert.Single(second.Groups).Skipped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ChangedSource_Rebuilds()
|
||||
{
|
||||
WritePng("UI/button.png", 8, 8, 1, 2, 3);
|
||||
AtlasBuilder.Build(Options());
|
||||
|
||||
File.SetLastWriteTimeUtc(
|
||||
Path.Combine(SourceDir, "UI/button.png"), DateTime.UtcNow.AddMinutes(1));
|
||||
var result = AtlasBuilder.Build(Options());
|
||||
|
||||
Assert.False(Assert.Single(result.Groups).Skipped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_AddedFile_RebuildsGroup()
|
||||
{
|
||||
WritePng("UI/button.png", 8, 8, 1, 2, 3);
|
||||
AtlasBuilder.Build(Options());
|
||||
|
||||
WritePng("UI/icon.png", 8, 8, 4, 5, 6);
|
||||
var result = AtlasBuilder.Build(Options());
|
||||
|
||||
var group = Assert.Single(result.Groups);
|
||||
Assert.False(group.Skipped);
|
||||
Assert.Equal(2, group.RegionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_RemovedGroup_DeletesOrphanedAtlas()
|
||||
{
|
||||
WritePng("UI/button.png", 8, 8, 1, 2, 3);
|
||||
WritePng("World/rock.png", 8, 8, 7, 8, 9);
|
||||
AtlasBuilder.Build(Options());
|
||||
|
||||
Directory.Delete(Path.Combine(SourceDir, "World"), recursive: true);
|
||||
var result = AtlasBuilder.Build(Options());
|
||||
|
||||
Assert.NotEmpty(result.DeletedOrphans);
|
||||
Assert.False(File.Exists(Path.Combine(OutputDir, "World.atlas")));
|
||||
Assert.False(File.Exists(Path.Combine(OutputDir, "World.atlas.0.png")));
|
||||
Assert.True(File.Exists(Path.Combine(OutputDir, "UI.atlas")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_ManyImages_SpillToMultiplePages()
|
||||
{
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
WritePng($"Things/sprite{i:D2}.png", 60, 60, (byte)i, 0, 0);
|
||||
}
|
||||
|
||||
var result = AtlasBuilder.Build(Options());
|
||||
|
||||
// 60² с padding 2 на страницу 128² помещаются по 4 — минимум 3 страницы.
|
||||
Assert.True(Assert.Single(result.Groups).PageCount >= 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Metadata_JsonRoundtrip_PreservesEverything()
|
||||
{
|
||||
var metadata = new AtlasMetadata
|
||||
{
|
||||
Name = "Things.Pawn",
|
||||
PageSize = 2048,
|
||||
Padding = 2,
|
||||
Pages = [new AtlasPage { File = "Things.Pawn.atlas.0.png", Width = 256, Height = 128 }],
|
||||
Regions = [new AtlasRegion { Key = "Things/Pawn/Fox", Page = 0, X = 2, Y = 4, Width = 64, Height = 32 }],
|
||||
};
|
||||
|
||||
var parsed = AtlasMetadata.FromJson(metadata.ToJson());
|
||||
|
||||
Assert.Equal("Things.Pawn", parsed.Name);
|
||||
Assert.Equal(2048, parsed.PageSize);
|
||||
var page = Assert.Single(parsed.Pages);
|
||||
Assert.Equal(("Things.Pawn.atlas.0.png", 256, 128), (page.File, page.Width, page.Height));
|
||||
var region = Assert.Single(parsed.Regions);
|
||||
Assert.Equal(("Things/Pawn/Fox", 0, 2, 4, 64, 32),
|
||||
(region.Key, region.Page, region.X, region.Y, region.Width, region.Height));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TextureAtlas_LooksUpRegions_FromMetadata()
|
||||
{
|
||||
var metadata = new AtlasMetadata
|
||||
{
|
||||
Name = "Test",
|
||||
Pages = [new AtlasPage { File = "Test.atlas.0.png", Width = 64, Height = 64 }],
|
||||
Regions =
|
||||
[
|
||||
new AtlasRegion { Key = "a/b", Page = 0, X = 2, Y = 2, Width = 10, Height = 12 },
|
||||
],
|
||||
};
|
||||
|
||||
// Texture2D == null допустим в headless-тестах (см. Texture2DRegion).
|
||||
var atlas = new TextureAtlas(metadata, new Microsoft.Xna.Framework.Graphics.Texture2D[1]);
|
||||
|
||||
var region = atlas.GetRegion("a/b");
|
||||
Assert.Equal(new Microsoft.Xna.Framework.Rectangle(2, 2, 10, 12), region.Bounds);
|
||||
Assert.True(atlas.TryGetRegion("a/b", out _));
|
||||
Assert.False(atlas.TryGetRegion("missing", out _));
|
||||
Assert.Throws<KeyNotFoundException>(() => atlas.GetRegion("missing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Atlases\MrGameEng.Atlases.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,111 @@
|
||||
using MrGameEng.Atlases;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Atlases.Tests;
|
||||
|
||||
public class ShelfPackerTests
|
||||
{
|
||||
private static List<PackItem> Squares(int count, int size) =>
|
||||
Enumerable.Range(0, count).Select(i => new PackItem($"item{i:D3}", size, size)).ToList();
|
||||
|
||||
[Fact]
|
||||
public void Pack_PlacesEveryItem_WithinPageBounds()
|
||||
{
|
||||
var result = ShelfPacker.Pack(Squares(50, 60), maxPageSize: 256, padding: 2);
|
||||
|
||||
Assert.Equal(50, result.Placements.Count);
|
||||
foreach (var p in result.Placements)
|
||||
{
|
||||
var (pageWidth, pageHeight) = result.PageSizes[p.Page];
|
||||
Assert.True(p.X >= 2 && p.Y >= 2);
|
||||
Assert.True(p.X + p.Width <= pageWidth);
|
||||
Assert.True(p.Y + p.Height <= pageHeight);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pack_NoTwoPlacements_Overlap()
|
||||
{
|
||||
var items = new List<PackItem>();
|
||||
var random = new Random(42);
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
items.Add(new PackItem($"r{i:D3}", random.Next(4, 90), random.Next(4, 90)));
|
||||
}
|
||||
|
||||
var result = ShelfPacker.Pack(items, maxPageSize: 512, padding: 2);
|
||||
|
||||
var byPage = result.Placements.GroupBy(p => p.Page);
|
||||
foreach (var page in byPage)
|
||||
{
|
||||
var list = page.ToList();
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
{
|
||||
for (var j = i + 1; j < list.Count; j++)
|
||||
{
|
||||
var a = list[i];
|
||||
var b = list[j];
|
||||
var separated =
|
||||
a.X + a.Width + 2 <= b.X || b.X + b.Width + 2 <= a.X ||
|
||||
a.Y + a.Height + 2 <= b.Y || b.Y + b.Height + 2 <= a.Y;
|
||||
Assert.True(separated, $"{a.Key} overlaps {b.Key} (padding included)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pack_Overflows_ToMultiplePages()
|
||||
{
|
||||
// 9 квадратов 100² на страницу 256² помещаются максимум по 4.
|
||||
var result = ShelfPacker.Pack(Squares(9, 100), maxPageSize: 256, padding: 2);
|
||||
|
||||
Assert.True(result.PageSizes.Count >= 3);
|
||||
Assert.Equal(Enumerable.Range(0, result.PageSizes.Count), result.Placements.Select(p => p.Page).Distinct().Order());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pack_OversizedItem_GetsDedicatedPage()
|
||||
{
|
||||
var items = Squares(2, 30);
|
||||
items.Add(new PackItem("huge", 500, 40));
|
||||
|
||||
var result = ShelfPacker.Pack(items, maxPageSize: 256, padding: 2);
|
||||
|
||||
var huge = result.Placements.Single(p => p.Key == "huge");
|
||||
Assert.Single(result.Placements, p => p.Page == huge.Page);
|
||||
Assert.True(result.PageSizes[huge.Page].Width >= 504);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pack_IsDeterministic_RegardlessOfInputOrder()
|
||||
{
|
||||
var items = Squares(30, 20).Concat(Squares(10, 50).Select(i => i with { Key = "b" + i.Key })).ToList();
|
||||
var shuffled = items.AsEnumerable().Reverse().ToList();
|
||||
|
||||
var a = ShelfPacker.Pack(items, 128, 2);
|
||||
var b = ShelfPacker.Pack(shuffled, 128, 2);
|
||||
|
||||
Assert.Equal(
|
||||
a.Placements.OrderBy(p => p.Key, StringComparer.Ordinal),
|
||||
b.Placements.OrderBy(p => p.Key, StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pack_TrimsPages_ToPowerOfTwo()
|
||||
{
|
||||
var result = ShelfPacker.Pack(Squares(1, 50), maxPageSize: 2048, padding: 2);
|
||||
|
||||
Assert.Equal((64, 64), result.PageSizes.Single());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(64, 64)]
|
||||
[InlineData(65, 128)]
|
||||
[InlineData(2048, 2048)]
|
||||
public void NextPowerOfTwo_RoundsUp(int value, int expected)
|
||||
{
|
||||
Assert.Equal(expected, ShelfPacker.NextPowerOfTwo(value));
|
||||
}
|
||||
}
|
||||
@@ -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<Transform2D>().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<Entity> 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 _));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Collisions\MrGameEng.Collisions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Pathfinding.Tests;
|
||||
|
||||
public class GridPathfinderTests
|
||||
{
|
||||
private static List<Point> 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<Point>();
|
||||
Assert.True(pathfinder.FindPath(start, goal, path, algorithm));
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void AssertValidPath(IPathGrid grid, List<Point> 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<Point>();
|
||||
|
||||
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<Point>();
|
||||
|
||||
// Диагональ (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<Point>();
|
||||
|
||||
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<Point> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,23 @@
|
||||
using MrGameEng.Pathfinding;
|
||||
|
||||
namespace MrGameEng.Pathfinding.Tests;
|
||||
|
||||
/// <summary>Грид из строк: '#' — стена, '.' — клетка с ценой 1, '2'..'9' — клетка с этой ценой.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Tilemaps\MrGameEng.Tilemaps.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,152 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using MrGameEng.Graphics;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Tilemaps.Tests;
|
||||
|
||||
public class TileGridTests
|
||||
{
|
||||
[Fact]
|
||||
public void NewGrid_IsEmpty()
|
||||
{
|
||||
var grid = new TileGrid(4, 3);
|
||||
|
||||
Assert.Equal(4, grid.Width);
|
||||
Assert.Equal(3, grid.Height);
|
||||
for (var y = 0; y < 3; y++)
|
||||
{
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
Assert.Equal(0, grid[x, y]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SetGet_RoundtripsPerCell()
|
||||
{
|
||||
var grid = new TileGrid(3, 3);
|
||||
|
||||
grid[2, 1] = 7;
|
||||
|
||||
Assert.Equal(7, grid[2, 1]);
|
||||
Assert.Equal(0, grid[1, 2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_SetsEveryCell()
|
||||
{
|
||||
var grid = new TileGrid(5, 5);
|
||||
|
||||
grid.Fill(3);
|
||||
|
||||
Assert.Equal(3, grid[0, 0]);
|
||||
Assert.Equal(3, grid[4, 4]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1, 0)]
|
||||
[InlineData(0, -1)]
|
||||
[InlineData(3, 0)]
|
||||
[InlineData(0, 2)]
|
||||
public void OutOfBounds_Throws(int x, int y)
|
||||
{
|
||||
var grid = new TileGrid(3, 2);
|
||||
|
||||
Assert.False(grid.Contains(x, y));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => grid[x, y]);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => grid[x, y] = 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(-1, 1)]
|
||||
public void InvalidSize_Throws(int width, int height)
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new TileGrid(width, height));
|
||||
}
|
||||
}
|
||||
|
||||
public class TileSetTests
|
||||
{
|
||||
// Texture2D == null допустим в headless-тестах (см. Texture2DRegion).
|
||||
private static Texture2DRegion Region(int size = 16) =>
|
||||
new(null!, new Rectangle(0, 0, size, size));
|
||||
|
||||
[Fact]
|
||||
public void Add_ReturnsSequentialIds_StartingAtOne()
|
||||
{
|
||||
var tiles = new TileSet();
|
||||
|
||||
var first = tiles.Add(Region());
|
||||
var second = tiles.Add(Region(), Color.Red);
|
||||
|
||||
Assert.Equal(1, first);
|
||||
Assert.Equal(2, second);
|
||||
Assert.Equal(3, tiles.Count);
|
||||
Assert.Equal(Color.White, tiles[first].Color);
|
||||
Assert.Equal(Color.Red, tiles[second].Color);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyTileZero_HasNoRegion()
|
||||
{
|
||||
var tiles = new TileSet();
|
||||
|
||||
Assert.Null(tiles[0].Region);
|
||||
}
|
||||
}
|
||||
|
||||
public class TilemapMathTests
|
||||
{
|
||||
[Fact]
|
||||
public void CameraInsideMap_ReturnsClampedRange()
|
||||
{
|
||||
var cull = new RectF(35f, 18f, 40f, 30f); // правый край 75, нижний 48
|
||||
|
||||
var visible = TilemapMath.VisibleCells(in cull, Vector2.Zero, 16f, 10, 10,
|
||||
out var x0, out var y0, out var x1, out var y1);
|
||||
|
||||
Assert.True(visible);
|
||||
Assert.Equal((2, 1, 4, 3), (x0, y0, x1, y1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MapOffsetByOrigin_ShiftsRange()
|
||||
{
|
||||
var cull = new RectF(0f, 0f, 64f, 64f);
|
||||
|
||||
var visible = TilemapMath.VisibleCells(in cull, new Vector2(-32f, -32f), 16f, 100, 100,
|
||||
out var x0, out var y0, out var x1, out var y1);
|
||||
|
||||
Assert.True(visible);
|
||||
Assert.Equal((2, 2, 6, 6), (x0, y0, x1, y1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CameraLargerThanMap_ClampsToWholeGrid()
|
||||
{
|
||||
var cull = new RectF(-1000f, -1000f, 5000f, 5000f);
|
||||
|
||||
var visible = TilemapMath.VisibleCells(in cull, Vector2.Zero, 16f, 8, 6,
|
||||
out var x0, out var y0, out var x1, out var y1);
|
||||
|
||||
Assert.True(visible);
|
||||
Assert.Equal((0, 0, 7, 5), (x0, y0, x1, y1));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(200f, 0f)] // справа от карты
|
||||
[InlineData(-200f, 0f)] // слева
|
||||
[InlineData(0f, 200f)] // ниже
|
||||
public void CameraOutsideMap_ReturnsFalse(float offsetX, float offsetY)
|
||||
{
|
||||
var cull = new RectF(offsetX, offsetY, 100f, 100f);
|
||||
|
||||
var visible = TilemapMath.VisibleCells(in cull, new Vector2(-150f, -150f), 16f, 8, 8,
|
||||
out _, out _, out _, out _);
|
||||
|
||||
Assert.False(visible);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Atlases\MrGameEng.Atlases.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.Diagnostics;
|
||||
using MrGameEng.Atlases;
|
||||
|
||||
if (args.Length < 2 || args.Contains("--help") || args.Contains("-h"))
|
||||
{
|
||||
Console.WriteLine(
|
||||
"""
|
||||
MrGameEng.AtlasTool — packs a directory tree of images into texture atlases.
|
||||
|
||||
Usage: MrGameEng.AtlasTool <source-dir> <output-dir> [options]
|
||||
|
||||
Options:
|
||||
--group-depth <n> directories forming one atlas (0 = single atlas; default 1)
|
||||
--page-size <n> maximum page size in pixels (default 2048)
|
||||
--padding <n> gap between images in pixels (default 2)
|
||||
--root-name <name> atlas name for files above group depth (default "Atlas")
|
||||
--force rebuild even when sources are unchanged
|
||||
""");
|
||||
return args.Length < 2 && !args.Contains("--help") && !args.Contains("-h") ? 1 : 0;
|
||||
}
|
||||
|
||||
int Option(string name, int fallback)
|
||||
{
|
||||
var index = Array.IndexOf(args, name);
|
||||
return index >= 0 && index + 1 < args.Length ? int.Parse(args[index + 1]) : fallback;
|
||||
}
|
||||
|
||||
var rootNameIndex = Array.IndexOf(args, "--root-name");
|
||||
var options = new AtlasBuildOptions
|
||||
{
|
||||
SourceDirectory = args[0],
|
||||
OutputDirectory = args[1],
|
||||
GroupDepth = Option("--group-depth", 1),
|
||||
MaxPageSize = Option("--page-size", 2048),
|
||||
Padding = Option("--padding", 2),
|
||||
RootAtlasName = rootNameIndex >= 0 && rootNameIndex + 1 < args.Length ? args[rootNameIndex + 1] : "Atlas",
|
||||
Force = args.Contains("--force"),
|
||||
};
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
var result = AtlasBuilder.Build(options);
|
||||
stopwatch.Stop();
|
||||
|
||||
foreach (var group in result.Groups)
|
||||
{
|
||||
Console.WriteLine(group.Skipped
|
||||
? $" {group.Name}: up to date ({group.RegionCount} regions, {group.PageCount} pages)"
|
||||
: $" {group.Name}: {group.RegionCount} regions -> {group.PageCount} pages");
|
||||
}
|
||||
|
||||
foreach (var orphan in result.DeletedOrphans)
|
||||
{
|
||||
Console.WriteLine($" deleted orphan {orphan}");
|
||||
}
|
||||
|
||||
var built = result.Groups.Count(g => !g.Skipped);
|
||||
Console.WriteLine($"Done: {built} atlases built, {result.Groups.Count - built} up to date, {stopwatch.Elapsed.TotalSeconds:F1}s.");
|
||||
return 0;
|
||||
Reference in New Issue
Block a user