summaryrefslogtreecommitdiff
path: root/Plugins/MonoGame.Extended/tests/MonoGame.Extended.Entities.Tests/WorldManagerTests.cs
blob: 7620f1e8f907a206a7440631e14d3eff4a503ae9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Entities.Systems;
using MonoGame.Extended.Sprites;
using Xunit;

namespace MonoGame.Extended.Entities.Tests;

public class WorldManagerTests
{
    private GameTime _gameTime = new GameTime(TimeSpan.Zero, TimeSpan.FromMilliseconds(16));

    [Fact]
    public void CrudEntity()
    {
        var dummySystem = new DummySystem();
        var worldBuilder = new WorldBuilder();
        worldBuilder.AddSystem(dummySystem);
        var world = worldBuilder.Build();

        world.Initialize();

        var entity = world.CreateEntity();
        entity.Attach(new Transform2());
        world.Update(_gameTime);
        world.Draw(_gameTime);
        var otherEntity = world.GetEntity(entity.Id);
        Assert.Equal(entity, otherEntity);
        Assert.True(otherEntity.Has<Transform2>());
        Assert.Contains(entity.Id, dummySystem.AddedEntitiesId);

        entity.Destroy();
        world.Update(_gameTime);
        world.Draw(_gameTime);
        otherEntity = world.GetEntity(entity.Id);
        Assert.Null(otherEntity);
        Assert.Contains(entity.Id, dummySystem.RemovedEntitiesId);
    }

    private class DummyComponent { }

    private class DummySystem : EntitySystem, IUpdateSystem, IDrawSystem
    {
        public List<int> AddedEntitiesId { get; } = new ();
        public List<int> RemovedEntitiesId { get; } = new ();

        public DummySystem() : base(Aspect.All(typeof(DummyComponent))) { }

        public override void Initialize(IComponentMapperService mapperService)
        {
            // Do NOT initialize mapper in  order to test: https://github.com/craftworkgames/MonoGame.Extended/issues/707
        }

        public void Draw(GameTime gameTime) { }

        public void Update(GameTime gameTime) { }

        protected override void OnEntityAdded(int entityId)
        {
            base.OnEntityAdded(entityId);
            AddedEntitiesId.Add(entityId);
        }

        protected override void OnEntityRemoved(int entityId)
        {
            base.OnEntityRemoved(entityId);
            RemovedEntitiesId.Add(entityId);
        }
    }
}