Changeset 23

User picture

Author: conkerjo

(2009/07/08 19:40) Over 2 years ago


  

Affected files

Updated src/AIDemos/AIDemos.csproj Download diff

2223
86
  <ItemGroup>
86
  <ItemGroup>
87
    <Compile Include="ExtensionMethods.cs" />
87
    <Compile Include="ExtensionMethods.cs" />
88
    <Compile Include="Game.cs" />
88
    <Compile Include="Game.cs" />
89
    <Compile Include="GameClasses\Behaviors\Attack.cs" />
90
    <Compile Include="GameClasses\Behaviors\Decorators\TimerBehavior.cs" />
89
    <Compile Include="GameClasses\Behaviors\DieBehavior.cs" />
91
    <Compile Include="GameClasses\Behaviors\DieBehavior.cs" />
92
    <Compile Include="GameClasses\Behaviors\Conditions\EnemyNearby.cs" />
93
    <Compile Include="GameClasses\Behaviors\RootSoldierBehavior.cs" />
94
    <Compile Include="GameClasses\Critter.cs" />
95
    <Compile Include="GameClasses\GameConsts.cs" />
90
    <Compile Include="GameClasses\GameActor.cs" />
96
    <Compile Include="GameClasses\GameActor.cs" />
97
    <Compile Include="GameClasses\Soldier.cs" />
91
    <Compile Include="Properties\AssemblyInfo.cs" />
98
    <Compile Include="Properties\AssemblyInfo.cs" />
99
    <Compile Include="Screens\Demos\Demo7.cs" />
100
    <Compile Include="Screens\Demos\Demo6.cs" />
92
    <Compile Include="Screens\Demos\Demo5.cs" />
101
    <Compile Include="Screens\Demos\Demo5.cs" />
93
    <Compile Include="Screens\Demos\Demo4.cs" />
102
    <Compile Include="Screens\Demos\Demo4.cs" />
94
    <Compile Include="Screens\Demos\Demo3.cs" />
103
    <Compile Include="Screens\Demos\Demo3.cs" />

Added src/AIDemos/GameClasses/Behaviors/Attack.cs

Show contents

Added src/AIDemos/GameClasses/Behaviors/Conditions/EnemyNearby.cs

Show contents

Added src/AIDemos/GameClasses/Behaviors/Decorators/TimerBehavior.cs

Show contents

Updated src/AIDemos/GameClasses/Behaviors/DieBehavior.cs Download diff

2223
6
6
7
namespace AIDemos.GameClasses.Behaviors
7
namespace AIDemos.GameClasses.Behaviors
8
{
8
{
9
    [Brains.Framework.Designer.Behavior("DieBehavior")]
9
    public class DieBehavior:BehaviorTask
10
    public class DieBehavior:BehaviorTask
10
    {
11
    {
11
        public DieBehavior()
12
        public DieBehavior()

Added src/AIDemos/GameClasses/Behaviors/RootSoldierBehavior.cs

Show contents

Added src/AIDemos/GameClasses/Critter.cs

Show contents

Added src/AIDemos/GameClasses/GameConsts.cs

Show contents

Added src/AIDemos/GameClasses/Soldier.cs

Show contents

Updated src/AIDemos/Screens/Demos/Demo1.cs Download diff

2223
22
    public class Demo1 : DemoGameScreen
22
    public class Demo1 : DemoGameScreen
23
    {
23
    {
24
        private GridCell _endNode;
24
        private GridCell _endNode;
25
        private AIEngine _engine;
25
        
26
        private MouseState _currentMouse;
26
        private MouseState _currentMouse;
27
        private MouseState _lastMouse;
27
        private MouseState _lastMouse;
28
28
29
        public Demo1()
29
        public Demo1():base("Demo 1 - Basic Pathfinding",
30
            "Click a valid grid cell to spawn a basic actor to pathfind to the destination\n" +
31
                "Red Cross   : Blocked Cell\n" +
32
                "Empty Tile  : Traversable Cell\n" +
33
                "Greed Circle: Destination Cell")
30
        {
34
        {
31
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
35
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
32
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
36
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
33
            Title = "Demo 1 - Basic Pathfinding";
34
            Description = "Click a valid grid cell to spawn a basic actor to pathfind to the destination\n" +
35
                "Red Cross   : Blocked Cell\n" +
36
                "Empty Tile  : Traversable Cell\n" +
37
                "Greed Circle: Destination Cell";
38
        }
37
        }
39
38
40
        public override void LoadContent()
39
        public override void LoadContent()
...
...
42
            base.LoadContent();
41
            base.LoadContent();
43
            
42
            
44
            LoadAI();
43
            LoadAI();
45
            //primitiveBatch.CameraPosition = new Vector2(-(_engine.World.Map.Cluster[0].Width / 2), -(_engine.World.Map.Cluster[0].Height / 2));
46
            ((DrawableWorld)_engine.World).Font = gameFont;
47
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
48
44
49
            primitiveBatch.CameraPosition = new Vector2(
45
            CenterCamOnMap();
50
           -ScreenManager.GraphicsDevice.Viewport.Width / 2 +
51
                       _engine.World.Map.ClusterGrid.Grids[0].Width / 2,
52
           -ScreenManager.GraphicsDevice.Viewport.Height / 2 +
53
                       _engine.World.Map.ClusterGrid.Grids[0].Height / 2);
54
       
46
       
55
47
56
            ScreenManager.Game.ResetElapsedTime();
48
            ScreenManager.Game.ResetElapsedTime();
...
...
58
        
50
        
59
        private void LoadAI()
51
        private void LoadAI()
60
        {
52
        {
61
            _engine = new AIEngine();
62
            _engine.CreateWorld(new DrawableWorld());
53
            _engine.CreateWorld(new DrawableWorld());
63
            _engine.World.LoadMapDataFromTexture(
54
            _engine.World.LoadMapDataFromTexture(
64
                content.Load<Texture2D>("DemoTextures/MAPDemo1"),
55
                content.Load<Texture2D>("DemoTextures/MAPDemo1"),
...
...
124
                    if (cell != null)
115
                    if (cell != null)
125
                    {
116
                    {
126
                        GameActor actor = new GameActor(cell.Position, 5);
117
                        GameActor actor = new GameActor(cell.Position, 5);
127
                        actor.Locomotion = new Brains.Framework.Locomotion.LocomtionSteering();
118
                        actor.Locomotion = new Brains.Framework.Locomotion.LocomotionController();
128
                        actor.Locomotion.MaxSpeed = 50;
119
                        actor.Locomotion.MaxSpeed = 50;
129
                        actor.Locomotion.MaxRotation = MathHelper.TwoPi;
120
                        actor.Locomotion.MaxRotation = MathHelper.TwoPi;
130
121

Updated src/AIDemos/Screens/Demos/Demo2.cs Download diff

2223
22
{
22
{
23
    public class Demo2 : DemoGameScreen
23
    public class Demo2 : DemoGameScreen
24
    {
24
    {
25
        AIEngine _engine;
26
25
27
        public Demo2()
26
        public Demo2():base("Demo 2 - Patrol","")
28
        {
27
        {
29
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
28
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
30
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
29
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
31
            Title = "Demo 2 - Patrol";
30
            
32
            Description = "An Agent is added to the world and set to patrol an area.";
33
        }
31
        }
34
32
35
        public override void LoadContent()
33
        public override void LoadContent()
...
...
37
            base.LoadContent();
35
            base.LoadContent();
38
            
36
            
39
            LoadAI();
37
            LoadAI();
40
            //primitiveBatch.CameraPosition = new Vector2(-(_engine.World.Map.Cluster[0].Width / 2), -(_engine.World.Map.Cluster[0].Height / 2));
38
            CenterCamOnMap();
41
            ((DrawableWorld)_engine.World).Font = gameFont;
42
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
43
44
            primitiveBatch.CameraPosition = new Vector2(
45
            -ScreenManager.GraphicsDevice.Viewport.Width / 2 +
46
                        _engine.World.Map.ClusterGrid.Grids[0].Width / 2,
47
            -ScreenManager.GraphicsDevice.Viewport.Height / 2 +
48
                        _engine.World.Map.ClusterGrid.Grids[0].Height / 2);
49
        
50
            ScreenManager.Game.ResetElapsedTime();
39
            ScreenManager.Game.ResetElapsedTime();
51
        }
40
        }
52
        private void LoadAI()
41
        private void LoadAI()
53
        {
42
        {
54
            _engine = new AIEngine();
43
            
55
            _engine.CreateWorld(new DrawableWorld());
44
            _engine.CreateWorld(new DrawableWorld());
56
            _engine.World.LoadMapDataFromTexture(
45
            _engine.World.LoadMapDataFromTexture(
57
                content.Load<Texture2D>("DemoTextures/MAPDemo2"),
46
                content.Load<Texture2D>("DemoTextures/MAPDemo2"),

Updated src/AIDemos/Screens/Demos/Demo3.cs Download diff

2223
22
{
22
{
23
    public class Demo3 : DemoGameScreen
23
    public class Demo3 : DemoGameScreen
24
    {
24
    {
25
        AIEngine _engine;
26
25
27
        public Demo3()
26
        public Demo3():base("Demo 3 - Custom Behaviors","")
28
        {
27
        {
29
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
28
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
30
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
29
            TransitionOffTime = TimeSpan.FromSeconds(0.5);    
31
            Title = "Demo 3 - Custom Behaviors";
32
            Description = "Custom Behaviors";
33
                
34
                
35
        }
30
        }
36
31
37
        public override void LoadContent()
32
        public override void LoadContent()
...
...
39
            base.LoadContent();
34
            base.LoadContent();
40
            
35
            
41
            LoadAI();
36
            LoadAI();
42
            //primitiveBatch.CameraPosition = new Vector2(-(_engine.World.Map.Cluster[0].Width / 2), -(_engine.World.Map.Cluster[0].Height / 2));
43
            ((DrawableWorld)_engine.World).Font = gameFont;
44
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
45
           
46
37
47
38
            CenterCamOnMap();
48
            ScreenManager.Game.ResetElapsedTime();
39
            ScreenManager.Game.ResetElapsedTime();
49
        }
40
        }
50
        private void LoadAI()
41
        private void LoadAI()
51
        {
42
        {
52
            _engine = new AIEngine();
53
            _engine.CreateWorld(new DrawableWorld());
43
            _engine.CreateWorld(new DrawableWorld());
54
            _engine.World.LoadMapDataFromTexture(
44
            _engine.World.LoadMapDataFromTexture(
55
                content.Load<Texture2D>("DemoTextures/MAPDemo3"),
45
                content.Load<Texture2D>("DemoTextures/MAPDemo3"),

Updated src/AIDemos/Screens/Demos/Demo4.cs Download diff

2223
21
{
21
{
22
    public class Demo4 : DemoGameScreen
22
    public class Demo4 : DemoGameScreen
23
    {
23
    {
24
        AIEngine _engine;
25
        
24
        
26
        public Demo4()
25
        public Demo4():base("Demo 4 - Steering Motion Controller","")
27
        {
26
        {
28
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
27
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
29
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
28
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
30
            Title = "Demo 4 - Steering Motion Controller";
29
            
31
            Description = "";        
30
            
32
        }
31
        }
33
32
34
        public override void LoadContent()
33
        public override void LoadContent()
...
...
36
            base.LoadContent();
35
            base.LoadContent();
37
            
36
            
38
            LoadAI();
37
            LoadAI();
39
            //primitiveBatch.CameraPosition = new Vector2(-(_engine.World.Map.Cluster[0].Width / 2), -(_engine.World.Map.Cluster[0].Height / 2));
40
            ((DrawableWorld)_engine.World).Font = gameFont;
41
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
42
38
43
            primitiveBatch.CameraPosition = new Vector2(
39
            CenterCamOnMap();
44
                        -ScreenManager.GraphicsDevice.Viewport.Width / 2 +
45
                        _engine.World.Map.ClusterGrid.Grids[0].Width / 2,
46
                        -ScreenManager.GraphicsDevice.Viewport.Height / 2 +
47
                        _engine.World.Map.ClusterGrid.Grids[0].Height / 2);
48
            ScreenManager.Game.ResetElapsedTime();
40
            ScreenManager.Game.ResetElapsedTime();
49
        }
41
        }
50
        private void LoadAI()
42
        private void LoadAI()
51
        {
43
        {
52
            _engine = new AIEngine();
44
            
53
            _engine.CreateWorld(new DrawableWorld());
45
            _engine.CreateWorld(new DrawableWorld());
54
            _engine.World.LoadMapDataFromTexture(
46
            _engine.World.LoadMapDataFromTexture(
55
                content.Load<Texture2D>("DemoTextures/MAPDemoBlank8"),
47
                content.Load<Texture2D>("DemoTextures/MAPDemoBlank8"),

Updated src/AIDemos/Screens/Demos/Demo5.cs Download diff

2223
22
{
22
{
23
    public class Demo5 : DemoGameScreen
23
    public class Demo5 : DemoGameScreen
24
    {
24
    {
25
        AIEngine _engine;
26
25
27
        public Demo5()
26
        public Demo5():base("Demo 5 - A Bigger World","")
28
        {
27
        {
29
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
28
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
30
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
29
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
31
            Title = "Demo 5 - A Bigger World";
32
            Description = "An Agent is added to the world and set to patrol an area.";
33
                
30
                
34
                
35
        }
31
        }
36
32
37
        public override void LoadContent()
33
        public override void LoadContent()
...
...
39
            base.LoadContent();
35
            base.LoadContent();
40
            
36
            
41
            LoadAI();
37
            LoadAI();
42
            //primitiveBatch.CameraPosition = new Vector2(-(_engine.World.Map.Cluster[0].Width / 2), -(_engine.World.Map.Cluster[0].Height / 2));
43
            ((DrawableWorld)_engine.World).Font = gameFont;
44
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
45
           
46
38
47
39
            CenterCamOnMap();
40
            ((DrawableWorld)_engine.World).Batch = ScreenManager.SpriteBatch;
41
            ((DrawableWorld)_engine.World).Font= gameFont;
48
            ScreenManager.Game.ResetElapsedTime();
42
            ScreenManager.Game.ResetElapsedTime();
49
        }
43
        }
50
        private void LoadAI()
44
        private void LoadAI()
51
        {
45
        {
52
            _engine = new AIEngine();
53
            _engine.CreateWorld(new DrawableWorld());
46
            _engine.CreateWorld(new DrawableWorld());
54
            _engine.World.LoadMapDataFromTexture(
47
            _engine.World.LoadMapDataFromTexture(
55
                content.Load<Texture2D>("DemoTextures/MAPDemo3"),
48
                content.Load<Texture2D>("DemoTextures/MAPDemo3"),
56
                8,
49
                4,
57
                8,
50
                4,
58
                32,
51
                32,
59
                typeof(DrawableGrid));
52
                typeof(DrawableGrid));
60
53
61
            GridCell fromcell=_engine.World.Map.AllCells.First<GridCell>(
54
            //GridCell fromcell=_engine.World.Map.AllCells.First<GridCell>(
62
                a => a.Labels[AIConsts.COLORR]==0&&
55
            //    a => a.Labels[AIConsts.COLORR]==0&&
63
                    a.Labels[AIConsts.COLORG]==255 &&
56
            //        a.Labels[AIConsts.COLORG]==255 &&
64
                    a.Labels[AIConsts.COLORB]==0);
57
            //        a.Labels[AIConsts.COLORB]==0);
65
            GridCell tocell = _engine.World.Map.AllCells.First<GridCell>(
58
            //GridCell tocell = _engine.World.Map.AllCells.First<GridCell>(
66
                a => a.Labels[AIConsts.COLORR] == 255 &&
59
            //    a => a.Labels[AIConsts.COLORR] == 255 &&
67
                    a.Labels[AIConsts.COLORG] == 0 &&
60
            //        a.Labels[AIConsts.COLORG] == 0 &&
68
                    a.Labels[AIConsts.COLORB] == 0);
61
            //        a.Labels[AIConsts.COLORB] == 0);
69
            GameActor actor = new GameActor(fromcell.Position, 5);
62
            //GameActor actor = new GameActor(fromcell.Position, 5);
70
            actor.Locomotion = new Brains.Framework.Locomotion.LocomtionSteering();
63
            //actor.Locomotion = new Brains.Framework.Locomotion.LocomtionSteering();
71
            actor.Locomotion.MaxSpeed = 50;
64
            //actor.Locomotion.MaxSpeed = 70;
72
            actor.Locomotion.MaxRotation = MathHelper.TwoPi;
65
            //actor.Locomotion.MaxRotation = MathHelper.TwoPi;
73
66
74
            _engine.World.AddActor(actor);
67
            //_engine.World.AddActor(actor);
75
            SequenceBehavior _sequence = new SequenceBehavior();
68
            //SequenceBehavior _sequence = new SequenceBehavior();
76
69
77
            
70
            
78
            DrawableBehaviorGoTo _goto = new DrawableBehaviorGoTo();
71
            //DrawableBehaviorGoTo _goto = new DrawableBehaviorGoTo();
79
            _goto.StartNode = fromcell;
72
            //_goto.StartNode = fromcell;
80
            _goto.EndNode = tocell;
73
            //_goto.EndNode = tocell;
81
            _sequence.SubBehaviors.Add(_goto);
74
            //_sequence.SubBehaviors.Add(_goto);
82
            _sequence.SubBehaviors.Add(new DieBehavior());
75
            //_sequence.SubBehaviors.Add(new DieBehavior());
83
            actor.RootBehavior = _sequence;
76
            //actor.RootBehavior = _sequence;
84
77
85
        }
78
        }
86
        class CellComparer:IComparer
79
        class CellComparer:IComparer
...
...
158
                                               Color.Black, 0, 0);
151
                                               Color.Black, 0, 0);
159
152
160
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
153
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
161
154
            
162
            spriteBatch.Begin();
155
            spriteBatch.Begin();
163
            
156
            
164
            base.Draw(gameTime);
157
            base.Draw(gameTime);

Added src/AIDemos/Screens/Demos/Demo6.cs

Show contents

Added src/AIDemos/Screens/Demos/Demo7.cs

Show contents

Updated src/AIDemos/Screens/Demos/DemoGameScreen.cs Download diff

2223
7
using Microsoft.Xna.Framework.Content;
7
using Microsoft.Xna.Framework.Content;
8
using Microsoft.Xna.Framework;
8
using Microsoft.Xna.Framework;
9
using Microsoft.Xna.Framework.Input;
9
using Microsoft.Xna.Framework.Input;
10
using Brains.Framework;
10
11
11
namespace AIDemos.Screens.Demos
12
namespace AIDemos.Screens.Demos
12
{
13
{
...
...
17
       
18
       
18
        protected SpriteFont gameFont;
19
        protected SpriteFont gameFont;
19
        protected SpriteFont titleFont;
20
        protected SpriteFont titleFont;
21
        protected AIEngine _engine;
20
        public string Title { get; set; }
22
        public string Title { get; set; }
21
        public string Description{ get; set; }
23
        public string Description{ get; set; }
22
        public DemoGameScreen()
24
        public DemoGameScreen(string title,string description)
23
        {
25
        {
26
            Title = title;
27
            Description = description;
24
        }
28
        }
29
        protected void CenterCamOnMap()
30
        {
31
            primitiveBatch.CameraPosition = new Vector2(
32
                -ScreenManager.GraphicsDevice.Viewport.Width / 2 +
33
                _engine.World.Map.ClusterGrid.Grids[0].Width / 2,
34
                -ScreenManager.GraphicsDevice.Viewport.Height / 2 +
35
                _engine.World.Map.ClusterGrid.Grids[0].Height / 2);
25
36
37
        }
26
        public override void LoadContent()
38
        public override void LoadContent()
27
        {
39
        {
28
            if (content == null)
40
            if (content == null)
...
...
31
            gameFont = content.Load<SpriteFont>("gamefont");
43
            gameFont = content.Load<SpriteFont>("gamefont");
32
            titleFont= content.Load<SpriteFont>("titlefont");
44
            titleFont= content.Load<SpriteFont>("titlefont");
33
            primitiveBatch = new PrimitiveBatch(ScreenManager.GraphicsDevice);
45
            primitiveBatch = new PrimitiveBatch(ScreenManager.GraphicsDevice);
46
47
            _engine = new AIEngine();
48
            
34
        }
49
        }
35
50
36
        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
51
        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)

Updated src/AIDemos/Screens/MainMenuScreen.cs Download diff

2223
44
            playGameMenuEntry = new MenuEntry("Demo4 - Steering Motion Controller");
44
            playGameMenuEntry = new MenuEntry("Demo4 - Steering Motion Controller");
45
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
45
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
46
            MenuEntries.Add(playGameMenuEntry);
46
            MenuEntries.Add(playGameMenuEntry);
47
48
            playGameMenuEntry = new MenuEntry("Demo5 - A Bigger World");
49
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
50
            MenuEntries.Add(playGameMenuEntry);
51
52
            playGameMenuEntry = new MenuEntry("Demo6 - Combining Behaviors");
53
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
54
            MenuEntries.Add(playGameMenuEntry);
55
56
            playGameMenuEntry = new MenuEntry("Demo7 - Group Movement");
57
            playGameMenuEntry.Selected += PlayGameMenuEntrySelected;
58
            MenuEntries.Add(playGameMenuEntry);
47
            
59
            
48
            MenuEntry optionsMenuEntry = new MenuEntry("Options");
60
            MenuEntry optionsMenuEntry = new MenuEntry("Options");
49
            MenuEntry exitMenuEntry = new MenuEntry("Exit");
61
            MenuEntry exitMenuEntry = new MenuEntry("Exit");
...
...
90
                    LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
102
                    LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
91
                               new Demo5());
103
                               new Demo5());
92
                    break;
104
                    break;
105
                case "Demo6 - Combining Behaviors":
106
                    LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
107
                               new Demo6());
108
                    break;
109
                case "Demo7 - Group Movement":
110
                    LoadingScreen.Load(ScreenManager, true, e.PlayerIndex,
111
                               new Demo7());
112
                    break;
93
            }
113
            }
94
        }
114
        }
95
115

Updated src/AIRendering/DrawableActor.cs Download diff

2223
29
        {
29
        {
30
            if (behavior == null)
30
            if (behavior == null)
31
                return;
31
                return;
32
            foreach (var item in behavior.SubBehaviors)
32
            if (behavior is ISubBehaviorHolder)
33
            {
33
            {
34
                
35
                ISubBehaviorHolder subs = (ISubBehaviorHolder)behavior;
36
                foreach (var item in subs.SubBehaviors)
37
                {
34
38
35
                if (item.State == BehaviorState.Running && item is IRender)
39
                    if (item.State == BehaviorState.Running && item is IRender)
36
                    ((IRender)item).Render(batch);
40
                        ((IRender)item).Render(batch);
37
                DrawBehavior(item, batch);
41
                    DrawBehavior(item, batch);
42
                }
38
            }
43
            }
44
            if (behavior is IRender)
45
                ((IRender)behavior).Render(batch);
46
            if (CellsIAmIn.Count > 0)
47
            {
48
                Vector2 cellsize = new Vector2(ParentWorld.Map.ClusterGrid.Grids[0].CellSize);
49
                batch.DrawBox(CellsIAmIn[0].Position - (cellsize / 2),
50
                    CellsIAmIn[0].Position + (cellsize / 2), Color.Blue);
51
            }
52
            
39
        }
53
        }
40
54
41
    }
55
    }

Updated src/AIRendering/DrawableCyclicRoute.cs Download diff

2223
3
using System.Linq;
3
using System.Linq;
4
using System.Text;
4
using System.Text;
5
using Brains.Framework.Behaviors.PathFinding;
5
using Brains.Framework.Behaviors.PathFinding;
6
using Brains.Framework.Behaviors;
6
7
7
namespace AIRendering
8
namespace AIRendering
8
{
9
{
...
...
11
12
12
        public void Render(PrimitiveBatch batch)
13
        public void Render(PrimitiveBatch batch)
13
        {
14
        {
14
            if (SubBehaviors[CurrentSubBehavior] is IRender)
15
            if (CurrentSubBehavior > 0)
15
            {
16
            {
16
                ((IRender)SubBehaviors[CurrentSubBehavior]).Render(batch);
17
                if (SubBehaviors[CurrentSubBehavior] is IRender)
17
            }
18
            for (int i = 0; i < SubBehaviors[CurrentSubBehavior].SubBehaviors.Count; i++)
19
            {
20
                if (SubBehaviors[CurrentSubBehavior].SubBehaviors[i] is FollowPathBehavior)
21
                {
18
                {
22
                    DrawableBehaviorGoTo.DrawFollowPath(SubBehaviors[CurrentSubBehavior].SubBehaviors[i] as FollowPathBehavior,
19
                    ((IRender)SubBehaviors[CurrentSubBehavior]).Render(batch);
23
                        batch);
24
                }
20
                }
25
21
22
                ISubBehaviorHolder subs = (ISubBehaviorHolder)SubBehaviors[CurrentSubBehavior];
23
                if (subs != null)
24
                {
25
                    for (int i = 0; i < subs.SubBehaviors.Count; i++)
26
                    {
27
                        if (subs.SubBehaviors[i] is FollowPathBehavior)
28
                        {
29
                            DrawableBehaviorGoTo.DrawFollowPath(subs.SubBehaviors[i] as FollowPathBehavior,
30
                                batch);
31
                        }
32
33
                    }
34
                }
26
            }
35
            }
27
        }
36
        }
28
    }
37
    }

Updated src/AIRendering/DrawableGrid.cs Download diff

2223
27
        }
27
        }
28
28
29
29
30
        public void Render(PrimitiveBatch batch)
30
        public virtual  void Render(PrimitiveBatch batch)
31
        {
31
        {
32
32
33
            //for (int y = 0; y < Rows; y++)
33
            //for (int y = 0; y < Rows; y++)

Updated src/AIRendering/DrawableWorld.cs Download diff

2223
56
                    position,
56
                    position,
57
                    position + new Vector2(0, item.Height),
57
                    position + new Vector2(0, item.Height),
58
                           Color.Yellow);
58
                           Color.Yellow);
59
60
61
62
                Color pathColor;
63
                Color bisectorsColor;
64
                foreach (var path in item.PredeterminedPaths)
65
                {
66
67
68
                    for (int index = 0; index < path.Nodes.Count; index++)
69
                    {
70
71
                        pathColor = Color.Gold;
72
                        bisectorsColor = Color.Honeydew;
73
74
75
                        if (index < path.Nodes.Count - 1)
76
                        {
77
                            Vector2 pos1;
78
                            pos1 = item.GetCell(path.Nodes[index].X, path.Nodes[index].Y).Position;
79
                            Vector2 pos2 = item.GetCell(path.Nodes[index + 1].X, path.Nodes[index + 1].Y).Position;
80
                            
81
                            batch.DrawLine(
82
                                pos1,
83
                                pos2,
84
                                pathColor
85
                            );
86
                        }
87
                        if (index < path.Nodes.Count - 1)
88
                        {
89
                            batch.DrawLine(
90
                                path.Nodes[index].nodePosition,
91
                                path.Nodes[index + 1].nodePosition,
92
                                pathColor
93
                            );
94
                        }
95
96
                        batch.DrawLine(
97
                            path.Nodes[index].biNormalStart,
98
                            path.Nodes[index].biNormalEnd,
99
                            bisectorsColor
100
                            );
101
                        
102
                    }
103
                }
59
            }
104
            }
60
            foreach (DrawableActor item1 in Actors)
105
            foreach (DrawableActor item1 in Actors)
61
            {
106
            {
...
...
63
            }
108
            }
64
        }
109
        }
65
110
66
        private void DrawCell(PrimitiveBatch batch, QuadTreePositionItem<GridCell> item)
111
        protected virtual void DrawCell(PrimitiveBatch batch, QuadTreePositionItem<GridCell> item)
67
        {
112
        {
68
            batch.DrawBox(item.Rect.TopLeft, item.Rect.BottomRight, Color.White);
113
            batch.DrawBox(item.Rect.TopLeft, item.Rect.BottomRight, Color.White);
69
            Vector2 firstLine = item.Rect.TopLeft + new Vector2(3, 3);
114
            Vector2 firstLine = item.Rect.TopLeft + new Vector2(3, 3);
...
...
83
                    item.Rect.BottomLeft + new Vector2(24, -24),
128
                    item.Rect.BottomLeft + new Vector2(24, -24),
84
                    Color.Green);
129
                    Color.Green);
85
            }
130
            }
131
            foreach (var item1 in Map.ClusterGrid.Entrances)
132
            {
133
                batch.DrawLine(
134
                    item1.CellA.Position,
135
                    item1.CellB.Position,
136
                    Color.White);
137
138
                batch.DrawCircle(
139
                    item1.CellA.Position,5,Color.Blue);
140
                batch.DrawCircle(
141
                    item1.CellB.Position, 5, Color.Blue);
142
                        
143
            }
86
            /*for (int i = 0; i < item.Parent.Type; i++)
144
            /*for (int i = 0; i < item.Parent.Type; i++)
87
            {
145
            {
88
                batch.DrawLine(
146
                batch.DrawLine(
...
...
91
                firstLine.X += 6;
149
                firstLine.X += 6;
92
            }*/
150
            }*/
93
151
94
            //string clearance = item.Parent.Labels[AIConsts.CLEARANCEVALUE].ToString();
152
            if (Batch != null)
95
            //Batch.DrawString(
96
            //    Font,
97
            //    clearance,
98
            //    (item.Position - batch.CameraPosition) / batch.Zoom, 
99
            //    Color.White,
100
            //    0,
101
            //    new Vector2(8,8),
102
            //    1,
103
            //    SpriteEffects.None,
104
            //    0);
105
106
            if (item.Parent.Labels[AIConsts.ISVALIDCLUSTEREDGE] == 1)
107
            {
153
            {
108
                batch.DrawCircle(item.Parent.Position, 5, Color.Green);
154
                //string clearance = item.Parent.Labels[AIConsts.CLEARANCEVALUE].ToString();
109
                Vector2 half = new Vector2(item.Parent.Parent.CellSize / 2);
155
                //Batch.DrawString(
110
                batch.DrawLine(
156
                //    Font,
111
                    item.Rect.TopLeft+new Vector2(24),
157
                //    clearance,
112
                    item.Rect.BottomRight - new Vector2(24),
158
                //    (item.Position - batch.CameraPosition) / batch.Zoom,
113
                    Color.Green);
159
                //    Color.White,
160
                //    0,
161
                //    new Vector2(8, 8),
162
                //    1,
163
                //    SpriteEffects.None,
164
                //    0);
114
165
115
116
                batch.DrawLine(
117
                    item.Rect.TopRight - new Vector2(24, -24),
118
                    item.Rect.BottomLeft + new Vector2(24, -24),
119
                    Color.Green);
120
            }
166
            }
121
            if (item.Parent.Type == 0)
167
            if (item.Parent.Type == 0)
122
            {
168
            {

Updated src/BRAINSDesigner/app.config Download diff

2223
8
    <userSettings>
8
    <userSettings>
9
        <Designer.Properties.Settings>
9
        <Designer.Properties.Settings>
10
            <setting name="Behaviors" serializeAs="String">
10
            <setting name="Behaviors" serializeAs="String">
11
                <value>C:\Users\rik\Documents\Visual Studio 2008\Projects\AITester\AITester\bin\x86\Debug\AITester.exe</value>
11
                <value>C:\Work\XNA\BRAINS\src\AIDemos\bin\x86\Debug\AIDemos.exe</value>
12
            </setting>
12
            </setting>
13
        </Designer.Properties.Settings>
13
        </Designer.Properties.Settings>
14
    </userSettings>
14
    </userSettings>

Added src/BRAINSDesigner/Classes/BehaviorTreeViewer.cs

Show contents

Added src/BRAINSDesigner/Classes/BehaviorTreeViewer.Designer.cs

Show contents

Added src/BRAINSDesigner/Classes/BehaviorTreeViewer.resx

Show contents

Updated src/BRAINSDesigner/Designer.csproj Download diff

2223
48
    <Reference Include="System.Xml" />
48
    <Reference Include="System.Xml" />
49
  </ItemGroup>
49
  </ItemGroup>
50
  <ItemGroup>
50
  <ItemGroup>
51
    <Compile Include="Classes\BehaviorTreeViewer.cs">
52
      <SubType>UserControl</SubType>
53
    </Compile>
54
    <Compile Include="Classes\BehaviorTreeViewer.Designer.cs">
55
      <DependentUpon>BehaviorTreeViewer.cs</DependentUpon>
56
    </Compile>
51
    <Compile Include="Form1.cs">
57
    <Compile Include="Form1.cs">
52
      <SubType>Form</SubType>
58
      <SubType>Form</SubType>
53
    </Compile>
59
    </Compile>
...
...
56
    </Compile>
62
    </Compile>
57
    <Compile Include="Program.cs" />
63
    <Compile Include="Program.cs" />
58
    <Compile Include="Properties\AssemblyInfo.cs" />
64
    <Compile Include="Properties\AssemblyInfo.cs" />
65
    <EmbeddedResource Include="Classes\BehaviorTreeViewer.resx">
66
      <DependentUpon>BehaviorTreeViewer.cs</DependentUpon>
67
    </EmbeddedResource>
59
    <EmbeddedResource Include="Form1.resx">
68
    <EmbeddedResource Include="Form1.resx">
60
      <DependentUpon>Form1.cs</DependentUpon>
69
      <DependentUpon>Form1.cs</DependentUpon>
61
    </EmbeddedResource>
70
    </EmbeddedResource>
...
...
89
      <Name>AIRendering</Name>
98
      <Name>AIRendering</Name>
90
    </ProjectReference>
99
    </ProjectReference>
91
  </ItemGroup>
100
  </ItemGroup>
92
  <ItemGroup>
93
    <Folder Include="Classes\" />
94
  </ItemGroup>
95
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
101
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
96
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
102
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
97
       Other similar extension points exist, see Microsoft.Common.targets.
103
       Other similar extension points exist, see Microsoft.Common.targets.

Updated src/BRAINSDesigner/Form1.cs Download diff

2223
25
25
26
            LoadAIBehaviorData();
26
            LoadAIBehaviorData();
27
        }
27
        }
28
28
        string assemblyPath;
29
        private void LoadAIBehaviorData()
29
        private void LoadAIBehaviorData()
30
        {
30
        {
31
            _assemblies = new List<Assembly>();
31
            _assemblies = new List<Assembly>();
32
            string path = Properties.Settings.Default.Behaviors;
32
            string path = Properties.Settings.Default.Behaviors;
33
            
33
            assemblyPath = Path.GetDirectoryName(path);
34
            File.Copy(
34
            //File.Copy(
35
                path,
35
            //    path,
36
                Application.StartupPath +"\\"+ Path.GetFileName(path),true);
36
            //    Application.StartupPath +"\\"+ Path.GetFileName(path),true);
37
37
38
            LoadAssembly(Application.StartupPath + "\\" + "AIFramework.dll");
38
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
39
            LoadAssembly(Application.StartupPath + "\\" + Path.GetFileName(path));
39
            LoadAssembly(Application.StartupPath + "\\" + "Brains.Framework.dll");
40
            LoadAssembly(path);
40
            
41
            
41
        }
42
        }
42
43
44
        Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
45
        {
46
            Console.Write("");
47
            return null;
48
        }
49
43
        private void LoadAssembly(string file)
50
        private void LoadAssembly(string file)
44
        {
51
        {
45
            try
52
            try
...
...
118
                ((BehaviorNode)treeView1.SelectedNode.Tag).SubBehaviors.Add(_node);
125
                ((BehaviorNode)treeView1.SelectedNode.Tag).SubBehaviors.Add(_node);
119
                treeView1.SelectedNode.Nodes.Add(_newTreeNode);
126
                treeView1.SelectedNode.Nodes.Add(_newTreeNode);
120
                treeView1.SelectedNode.Expand();
127
                treeView1.SelectedNode.Expand();
128
                behaviorTreeViewer1.Invalidate();
121
129
122
            }
130
            }
123
        }
131
        }
...
...
128
            _rootNode = new BehaviorNode();
136
            _rootNode = new BehaviorNode();
129
            _rootNode.Name = "Behavior";
137
            _rootNode.Name = "Behavior";
130
            _rootNode.AddParameter("RootType", "");
138
            _rootNode.AddParameter("RootType", "");
139
            _rootNode.BehaviorName = "Root";
131
140
132
            TreeNode _rootBehaviorNode = new TreeNode(_rootNode.Name);
141
            TreeNode _rootBehaviorNode = new TreeNode(_rootNode.Name);
133
            _rootBehaviorNode.Tag = _rootNode;
142
            _rootBehaviorNode.Tag = _rootNode;
134
            treeView1.Nodes.Add(_rootBehaviorNode);
143
            treeView1.Nodes.Add(_rootBehaviorNode);
135
144
145
            behaviorTreeViewer1.rootBehavior = _rootNode;
136
146
137
138
        }
147
        }
139
148
140
149
...
...
143
            TreeNode _no = new TreeNode(name);
152
            TreeNode _no = new TreeNode(name);
144
            BehaviorNode _n = new BehaviorNode();
153
            BehaviorNode _n = new BehaviorNode();
145
            _n.Name = name;
154
            _n.Name = name;
155
            if(type!=null)
156
                _n.BehaviorName = type.Name;
146
            _n.Type =type;
157
            _n.Type =type;
147
            _no.Tag = _n;
158
            _no.Tag = _n;
148
            return _no;
159
            return _no;
...
...
227
238
228
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
239
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
229
        {
240
        {
230
            TreeNode node = treeView1.SelectedNode;
241
            
231
            splitContainer1.Panel2.Controls.Clear();
242
            propertyGrid1.SelectedObject = treeView1.SelectedNode.Tag;
232
            BehaviorNode _node=node.Tag as BehaviorNode;
243
            //TreeNode node = treeView1.SelectedNode;
233
            Point _controlPosition = new Point(15, 25);
244
            //splitContainer1.Panel2.Controls.Clear();
234
            int gap = 25;
245
            //BehaviorNode _node=node.Tag as BehaviorNode;
235
            foreach (var item in _node.Parameters)
246
            //Point _controlPosition = new Point(15, 25);
236
            {
247
            //int gap = 25;
237
                Label label = new Label();
248
            //foreach (var item in _node.Parameters)
238
                label.AutoSize = true;
249
            //{
239
                label.Text = item.Name;
250
            //    Label label = new Label();
240
                label.Location = _controlPosition;
251
            //    label.AutoSize = true;
252
            //    label.Text = item.Name;
253
            //    label.Location = _controlPosition;
241
                
254
                
242
                splitContainer1.Panel2.Controls.Add(label);
255
            //    splitContainer1.Panel2.Controls.Add(label);
243
                Control ctrl = CreateParameterControl(item);
256
            //    Control ctrl = CreateParameterControl(item);
244
                ctrl.Location = new Point(_controlPosition.X + 60, _controlPosition.Y-2);
257
            //    ctrl.Location = new Point(_controlPosition.X + 60, _controlPosition.Y-2);
245
                splitContainer1.Panel2.Controls.Add(ctrl);
258
            //    splitContainer1.Panel2.Controls.Add(ctrl);
246
                _controlPosition.Y += gap;
259
            //    _controlPosition.Y += gap;
247
260
248
                
261
                
249
            }
262
            //}
250
        }
263
        }
251
264
252
        private Control CreateParameterControl(Parameter item)
265
        private Control CreateParameterControl(Parameter item)
...
...
262
        {
275
        {
263
            ((Parameter)((Control)sender).Tag).Value = ((TextBox)sender).Text;
276
            ((Parameter)((Control)sender).Tag).Value = ((TextBox)sender).Text;
264
        }
277
        }
278
279
        private void propertyGrid1_Click(object sender, EventArgs e)
280
        {
281
282
        }
283
284
        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
285
        {
286
            RefreshTreeNode();
287
        }
288
289
        private void RefreshTreeNode()
290
        {
291
            if (((BehaviorNode)treeView1.SelectedNode.Tag).BehaviorName != null)
292
                treeView1.SelectedNode.Text = ((BehaviorNode)treeView1.SelectedNode.Tag).BehaviorName;
293
            else if (((BehaviorNode)treeView1.SelectedNode.Tag).Type != null)
294
                treeView1.SelectedNode.Text = ((BehaviorNode)treeView1.SelectedNode.Tag).Type.Name;
295
            else
296
                treeView1.SelectedNode.Text = "Root";
297
        }
265
    }
298
    }
266
}
299
}

Updated src/BRAINSDesigner/Form1.Designer.cs Download diff

2223
40
            this.compositeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
40
            this.compositeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
41
            this.actionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
41
            this.actionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
42
            this.conditionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
42
            this.conditionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
43
            this.splitContainer2 = new System.Windows.Forms.SplitContainer();
44
            this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
45
            this.behaviorTreeViewer1 = new Designer.Classes.BehaviorTreeViewer();
43
            this.toolStrip1.SuspendLayout();
46
            this.toolStrip1.SuspendLayout();
44
            this.splitContainer1.Panel1.SuspendLayout();
47
            this.splitContainer1.Panel1.SuspendLayout();
48
            this.splitContainer1.Panel2.SuspendLayout();
45
            this.splitContainer1.SuspendLayout();
49
            this.splitContainer1.SuspendLayout();
46
            this.contextMenuStrip1.SuspendLayout();
50
            this.contextMenuStrip1.SuspendLayout();
51
            this.splitContainer2.Panel1.SuspendLayout();
52
            this.splitContainer2.Panel2.SuspendLayout();
53
            this.splitContainer2.SuspendLayout();
47
            this.SuspendLayout();
54
            this.SuspendLayout();
48
            // 
55
            // 
49
            // toolStrip1
56
            // toolStrip1
...
...
99
            // 
106
            // 
100
            // splitContainer1.Panel1
107
            // splitContainer1.Panel1
101
            // 
108
            // 
102
            this.splitContainer1.Panel1.Controls.Add(this.treeView1);
109
            this.splitContainer1.Panel1.Controls.Add(this.splitContainer2);
110
            // 
111
            // splitContainer1.Panel2
112
            // 
113
            this.splitContainer1.Panel2.Controls.Add(this.behaviorTreeViewer1);
103
            this.splitContainer1.Size = new System.Drawing.Size(706, 539);
114
            this.splitContainer1.Size = new System.Drawing.Size(706, 539);
104
            this.splitContainer1.SplitterDistance = 235;
115
            this.splitContainer1.SplitterDistance = 235;
105
            this.splitContainer1.TabIndex = 2;
116
            this.splitContainer1.TabIndex = 2;
...
...
110
            this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
121
            this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
111
            this.treeView1.Location = new System.Drawing.Point(0, 0);
122
            this.treeView1.Location = new System.Drawing.Point(0, 0);
112
            this.treeView1.Name = "treeView1";
123
            this.treeView1.Name = "treeView1";
113
            this.treeView1.Size = new System.Drawing.Size(235, 539);
124
            this.treeView1.Size = new System.Drawing.Size(235, 303);
114
            this.treeView1.TabIndex = 0;
125
            this.treeView1.TabIndex = 0;
115
            this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
126
            this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
116
            this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
127
            this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
...
...
127
            // compositeToolStripMenuItem
138
            // compositeToolStripMenuItem
128
            // 
139
            // 
129
            this.compositeToolStripMenuItem.Name = "compositeToolStripMenuItem";
140
            this.compositeToolStripMenuItem.Name = "compositeToolStripMenuItem";
130
            this.compositeToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
141
            this.compositeToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
131
            this.compositeToolStripMenuItem.Text = "Composite";
142
            this.compositeToolStripMenuItem.Text = "Composite";
132
            // 
143
            // 
133
            // actionsToolStripMenuItem
144
            // actionsToolStripMenuItem
134
            // 
145
            // 
135
            this.actionsToolStripMenuItem.Name = "actionsToolStripMenuItem";
146
            this.actionsToolStripMenuItem.Name = "actionsToolStripMenuItem";
136
            this.actionsToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
147
            this.actionsToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
137
            this.actionsToolStripMenuItem.Text = "Actions";
148
            this.actionsToolStripMenuItem.Text = "Actions";
138
            this.actionsToolStripMenuItem.Click += new System.EventHandler(this.actionsToolStripMenuItem_Click);
149
            this.actionsToolStripMenuItem.Click += new System.EventHandler(this.actionsToolStripMenuItem_Click);
139
            // 
150
            // 
140
            // conditionToolStripMenuItem
151
            // conditionToolStripMenuItem
141
            // 
152
            // 
142
            this.conditionToolStripMenuItem.Name = "conditionToolStripMenuItem";
153
            this.conditionToolStripMenuItem.Name = "conditionToolStripMenuItem";
143
            this.conditionToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
154
            this.conditionToolStripMenuItem.Size = new System.Drawing.Size(132, 22);
144
            this.conditionToolStripMenuItem.Text = "Conditions";
155
            this.conditionToolStripMenuItem.Text = "Conditions";
145
            this.conditionToolStripMenuItem.Click += new System.EventHandler(this.conditionToolStripMenuItem_Click);
156
            this.conditionToolStripMenuItem.Click += new System.EventHandler(this.conditionToolStripMenuItem_Click);
146
            // 
157
            // 
158
            // splitContainer2
159
            // 
160
            this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
161
            this.splitContainer2.Location = new System.Drawing.Point(0, 0);
162
            this.splitContainer2.Name = "splitContainer2";
163
            this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
164
            // 
165
            // splitContainer2.Panel1
166
            // 
167
            this.splitContainer2.Panel1.Controls.Add(this.treeView1);
168
            // 
169
            // splitContainer2.Panel2
170
            // 
171
            this.splitContainer2.Panel2.Controls.Add(this.propertyGrid1);
172
            this.splitContainer2.Size = new System.Drawing.Size(235, 539);
173
            this.splitContainer2.SplitterDistance = 303;
174
            this.splitContainer2.TabIndex = 1;
175
            // 
176
            // propertyGrid1
177
            // 
178
            this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
179
            this.propertyGrid1.Location = new System.Drawing.Point(0, 0);
180
            this.propertyGrid1.Name = "propertyGrid1";
181
            this.propertyGrid1.Size = new System.Drawing.Size(235, 232);
182
            this.propertyGrid1.TabIndex = 1;
183
            this.propertyGrid1.Click += new System.EventHandler(this.propertyGrid1_Click);
184
            this.propertyGrid1.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.propertyGrid1_PropertyValueChanged);
185
            // 
186
            // behaviorTreeViewer1
187
            // 
188
            this.behaviorTreeViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
189
            this.behaviorTreeViewer1.Location = new System.Drawing.Point(0, 0);
190
            this.behaviorTreeViewer1.Name = "behaviorTreeViewer1";
191
            this.behaviorTreeViewer1.Size = new System.Drawing.Size(467, 539);
192
            this.behaviorTreeViewer1.TabIndex = 0;
193
            // 
147
            // Form1
194
            // Form1
148
            // 
195
            // 
149
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
196
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
...
...
156
            this.toolStrip1.ResumeLayout(false);
203
            this.toolStrip1.ResumeLayout(false);
157
            this.toolStrip1.PerformLayout();
204
            this.toolStrip1.PerformLayout();
158
            this.splitContainer1.Panel1.ResumeLayout(false);
205
            this.splitContainer1.Panel1.ResumeLayout(false);
206
            this.splitContainer1.Panel2.ResumeLayout(false);
159
            this.splitContainer1.ResumeLayout(false);
207
            this.splitContainer1.ResumeLayout(false);
160
            this.contextMenuStrip1.ResumeLayout(false);
208
            this.contextMenuStrip1.ResumeLayout(false);
209
            this.splitContainer2.Panel1.ResumeLayout(false);
210
            this.splitContainer2.Panel2.ResumeLayout(false);
211
            this.splitContainer2.ResumeLayout(false);
161
            this.ResumeLayout(false);
212
            this.ResumeLayout(false);
162
            this.PerformLayout();
213
            this.PerformLayout();
163
214
...
...
175
        private System.Windows.Forms.ToolStripButton toolStripButton2;
226
        private System.Windows.Forms.ToolStripButton toolStripButton2;
176
        private System.Windows.Forms.ToolStripButton toolStripButton3;
227
        private System.Windows.Forms.ToolStripButton toolStripButton3;
177
        private System.Windows.Forms.ToolStripMenuItem conditionToolStripMenuItem;
228
        private System.Windows.Forms.ToolStripMenuItem conditionToolStripMenuItem;
229
        private Designer.Classes.BehaviorTreeViewer behaviorTreeViewer1;
230
        private System.Windows.Forms.SplitContainer splitContainer2;
231
        private System.Windows.Forms.PropertyGrid propertyGrid1;
178
    }
232
    }
179
}
233
}
180
234

Updated src/BRAINSDesigner/Properties/Settings.Designer.cs Download diff

2223
25
        
25
        
26
        [global::System.Configuration.UserScopedSettingAttribute()]
26
        [global::System.Configuration.UserScopedSettingAttribute()]
27
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
27
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
28
        [global::System.Configuration.DefaultSettingValueAttribute("C:\\Users\\rik\\Documents\\Visual Studio 2008\\Projects\\AITester\\AITester\\bin\\x86\\Debu" +
28
        [global::System.Configuration.DefaultSettingValueAttribute("C:\\Work\\XNA\\BRAINS\\src\\AIDemos\\bin\\x86\\Debug\\AIDemos.exe")]
29
            "g\\AITester.exe")]
30
        public string Behaviors {
29
        public string Behaviors {
31
            get {
30
            get {
32
                return ((string)(this["Behaviors"]));
31
                return ((string)(this["Behaviors"]));

Updated src/BRAINSDesigner/Properties/Settings.settings Download diff

2223
3
  <Profiles />
3
  <Profiles />
4
  <Settings>
4
  <Settings>
5
    <Setting Name="Behaviors" Type="System.String" Scope="User">
5
    <Setting Name="Behaviors" Type="System.String" Scope="User">
6
      <Value Profile="(Default)">C:\Users\rik\Documents\Visual Studio 2008\Projects\AITester\AITester\bin\x86\Debug\AITester.exe</Value>
6
      <Value Profile="(Default)">C:\Work\XNA\BRAINS\src\AIDemos\bin\x86\Debug\AIDemos.exe</Value>
7
    </Setting>
7
    </Setting>
8
  </Settings>
8
  </Settings>
9
</SettingsFile>
9
</SettingsFile>

Updated src/BRAINSFramework/Agent.cs Download diff

2223
50
            }
50
            }
51
        }
51
        }
52
52
53
        public Dictionary<uint, int> Labels;
54
53
        /// <summary>
55
        /// <summary>
54
        /// Gets the cells the agent is in
56
        /// Gets the cells the agent is in
55
        /// </summary>
57
        /// </summary>
...
...
60
        /// The position of the Actor
62
        /// The position of the Actor
61
        /// </summary>
63
        /// </summary>
62
        public Vector2 Position { get; set; }
64
        public Vector2 Position { get; set; }
65
        
63
        /// <summary>
66
        /// <summary>
64
        /// Gets or sets the previous position of the agent
67
        /// Gets or sets the previous position of the agent
65
        /// </summary>
68
        /// </summary>
...
...
141
            AddFeeler(.5f, -.5f, Radius + 32);
144
            AddFeeler(.5f, -.5f, Radius + 32);
142
145
143
            Name = CreateUniqueName();
146
            Name = CreateUniqueName();
147
            Labels = new Dictionary<uint, int>();
144
        }
148
        }
145
149
146
        private string CreateUniqueName()
150
        private string CreateUniqueName()
...
...
153
            Feelers.Add(new Feeler(new Vector2(x, y),length,this));
157
            Feelers.Add(new Feeler(new Vector2(x, y),length,this));
154
        }
158
        }
155
159
160
        public virtual void UpdatePerception(GameTime gameTime)
161
        {
162
            //Tag nearby
163
        }
164
156
        /// <summary>
165
        /// <summary>
157
        /// Update the agent every frame. 
166
        /// Update the agent every frame. 
158
        /// </summary>
167
        /// </summary>
...
...
193
            // - for each component calculate row and col
202
            // - for each component calculate row and col
194
203
195
            Vector2 vDistanceFromMapCenter = this.Position;
204
            Vector2 vDistanceFromMapCenter = this.Position;
196
            Grid map = ParentWorld.Map.ClusterGrid.Grids[0];
205
            Grid map = ParentWorld.Map.ClusterGrid.GetGridAtPosition(Position);
206
            if (map == null)
207
                return;
197
            float _hstep = (map.Width/ ((float)map.Cols));
208
            float _hstep = (map.Width/ ((float)map.Cols));
198
            float _vstep = (map.Height/ ((float)map.Rows));
209
            float _vstep = (map.Height/ ((float)map.Rows));
199
            float xComponent = (vDistanceFromMapCenter.X / _hstep) ;
210
            float xComponent = (vDistanceFromMapCenter.X / _hstep) ;
200
            float yComponent = (vDistanceFromMapCenter.Y / _vstep);
211
            float yComponent = (vDistanceFromMapCenter.Y / _vstep);
201
212
202
            xComponent = xComponent - 0.5f;
213
           // xComponent = xComponent - 0.5f;
203
            yComponent = yComponent - 0.5f;
214
            //yComponent = yComponent - 0.5f;
204
215
205
            //debugX = (int)xComponent;
216
            //debugX = (int)xComponent;
206
            //debugY = (int)yComponent;
217
            //debugY = (int)yComponent;
...
...
229
                Console.Write("");
240
                Console.Write("");
230
            }
241
            }
231
        }
242
        }
243
        
232
        /// <summary>
244
        /// <summary>
233
        /// Loads a Behavior from a file
245
        /// Loads a Behavior from a file
234
        /// </summary>
246
        /// </summary>
...
...
240
            BehaviorNode _rootNode = (BehaviorNode)_ser.Deserialize(_reader);
252
            BehaviorNode _rootNode = (BehaviorNode)_ser.Deserialize(_reader);
241
            _reader.Close();
253
            _reader.Close();
242
254
243
            BehaviorBase _behavior = CreateBehaviorInstance(_rootNode.Parameters[0].Value);
255
            CompositeBehavior _behavior = CreateBehaviorInstance(_rootNode.Parameters[0].Value);
244
            
256
            
245
            SetupBehavior(_behavior, _rootNode);
257
            SetupBehavior(_behavior, _rootNode);
246
            RootBehavior = _behavior;
258
            RootBehavior = _behavior;
...
...
263
                    else
275
                    else
264
                        prop.SetValue(behavior, param.Value, null);
276
                        prop.SetValue(behavior, param.Value, null);
265
                }
277
                }
266
                parentBehavior.SubBehaviors.Add(behavior);
278
                if(parentBehavior is ISubBehaviorHolder)
279
                    ((ISubBehaviorHolder)parentBehavior).SubBehaviors.Add(behavior);
267
280
268
                SetupBehavior(behavior, item);
281
                SetupBehavior(behavior, item);
269
            }
282
            }
270
        }
283
        }
271
284
272
        private BehaviorBase CreateBehaviorInstance(string typeName)
285
        private CompositeBehavior CreateBehaviorInstance(string typeName)
273
        {
286
        {
274
            foreach (var item in ParentWorld.Engine.Assemblies)
287
            foreach (var item in ParentWorld.Engine.Assemblies)
275
            {
288
            {
276
                BehaviorBase behavior =(BehaviorBase)item.CreateInstance(typeName);
289
                CompositeBehavior behavior =(CompositeBehavior)item.CreateInstance(typeName);
277
                if (behavior != null)
290
                if (behavior != null)
278
                    return behavior;
291
                    return behavior;
279
            }
292
            }
280
            return null;
293
            return null;
281
        }
294
        }
282
295
283
        public virtual byte TypeToCost(int type)
296
        /// <summary>
297
        /// Gets the cost of a grid cell type for use with pathfinding.
298
        /// </summary>
299
        /// <param name="type">The Type value from a GridCell</param>
300
        /// <returns>The cost of the cell</returns>
301
        /// <remarks>Override this method for greater flexibility in pathfinding</remarks>
302
        public virtual byte GetCostOfCellType(int type)
284
        {
303
        {
285
            if (type == 0)
304
            if (type == 0)
286
                return 99;
305
                return 99;
287
            else
306
            else
288
                return (byte)type;
307
                return (byte)type;
289
        }
308
        }
309
310
        public void SetLabel(uint labelid, int labelvalue)
311
        {
312
            if (!Labels.Keys.Contains(labelid))
313
                Labels.Add(labelid, labelvalue);
314
            else
315
                Labels[labelid] = labelvalue;
316
        }
317
318
        public int GetLabel(uint labelid)
319
        {
320
            if (!Labels.Keys.Contains(labelid))
321
                return 0;
322
            else
323
                return Labels[labelid];
324
        }
290
    }
325
    }
291
}
326
}

Updated src/BRAINSFramework/BrAInS.csproj Download diff

2223
84
  </ItemGroup>
84
  </ItemGroup>
85
  <ItemGroup>
85
  <ItemGroup>
86
    <Compile Include="AIEngine.cs" />
86
    <Compile Include="AIEngine.cs" />
87
    <Compile Include="Behaviors\ConditionBehavior.cs" />
88
    <Compile Include="Behaviors\DecoratorBehavior.cs" />
87
    <Compile Include="Behaviors\GoToBehavior.cs" />
89
    <Compile Include="Behaviors\GoToBehavior.cs" />
90
    <Compile Include="Behaviors\ISubBehaviorHolder.cs" />
91
    <Compile Include="Behaviors\ParallelBehavior.cs" />
88
    <Compile Include="Behaviors\PathFinding\CyclicPathBehavior.cs" />
92
    <Compile Include="Behaviors\PathFinding\CyclicPathBehavior.cs" />
89
    <Compile Include="Behaviors\PathFinding\FindPathBehavior.cs" />
93
    <Compile Include="Behaviors\PathFinding\FindPathBehavior.cs" />
90
    <Compile Include="Behaviors\PathFinding\FollowPathBehavior.cs" />
94
    <Compile Include="Behaviors\PathFinding\FollowPathBehavior.cs" />
95
    <Compile Include="Grouping\Group.cs" />
91
    <Compile Include="Utility\AIConsts.cs" />
96
    <Compile Include="Utility\AIConsts.cs" />
92
    <Compile Include="Map\Cluster.cs" />
97
    <Compile Include="Map\Cluster.cs" />
93
    <Compile Include="Designer\BehaviorNode.cs" />
98
    <Compile Include="Designer\BehaviorNode.cs" />
94
    <Compile Include="Behaviors\BehaviorBase.cs" />
99
    <Compile Include="Behaviors\CompositeBehavior.cs" />
95
    <Compile Include="Behaviors\BehaviorList.cs" />
100
    <Compile Include="Behaviors\BehaviorList.cs" />
96
    <Compile Include="Behaviors\BehaviorTask.cs" />
101
    <Compile Include="Behaviors\TaskBehavior.cs" />
97
    <Compile Include="Behaviors\IConditionBehavior.cs" />
102
    <Compile Include="Behaviors\IConditionBehavior.cs" />
98
    <Compile Include="Behaviors\SelectorBehavior.cs" />
103
    <Compile Include="Behaviors\SelectorBehavior.cs" />
99
    <Compile Include="Behaviors\RandomBehavior.cs" />
104
    <Compile Include="Behaviors\RandomBehavior.cs" />

Updated src/BRAINSFramework/Designer/BehaviorNode.cs Download diff

2223
48
            Parameter p = new Parameter(name, value);
48
            Parameter p = new Parameter(name, value);
49
            Parameters.Add(p);
49
            Parameters.Add(p);
50
        }
50
        }
51
52
        public string BehaviorName { get; set; }
51
    }
53
    }
52
    
54
    
53
    public class Parameter
55
    public class Parameter

Added src/BRAINSFramework/Grouping/Group.cs

Show contents

Updated src/BRAINSFramework/Locomotion/LocomtionSteering.cs Download diff

2223
4
using System.Text;
4
using System.Text;
5
using Microsoft.Xna.Framework;
5
using Microsoft.Xna.Framework;
6
using Brains.Framework.Utility;
6
using Brains.Framework.Utility;
7
using Brains.Grouping;
7
8
8
namespace Brains.Framework.Locomotion
9
namespace Brains.Framework.Locomotion
9
{
10
{
...
...
16
        private static Random rand = new Random();
17
        private static Random rand = new Random();
17
        private Vector2 _wanderTarget;
18
        private Vector2 _wanderTarget;
18
19
19
        public const float WanderRadius = 1.2f;
20
        public const float WanderRadius = 20;
20
        public const float WanderDistance = 2.0f;
21
        public const float WanderDistance = 30;
21
        public const float WanderJitter = 80;
22
        public const float WanderJitter = 80;
22
         
23
         
23
        public enum Deceleration
24
        public enum Deceleration
...
...
35
            Flee= 0x00004,
36
            Flee= 0x00004,
36
            Arrive= 0x00008,
37
            Arrive= 0x00008,
37
            Wander = 0x00010,
38
            Wander = 0x00010,
38
            //Cohesion= 0x00020,
39
            Cohesion= 0x00020,
39
            //Seperation= 0x00040,
40
            Seperation= 0x00040,
40
            //Alignment = 0x00080,
41
            Alignment = 0x00080,
41
            //ObstacleAvoidance= 0x00100,
42
            //ObstacleAvoidance= 0x00100,
42
            //WallAvoidance = 0x00200,
43
            //WallAvoidance = 0x00200,
43
            //FollowPath = 0x00400,
44
            //FollowPath = 0x00400,
...
...
85
        {
86
        {
86
            TurnOff(BehaviorType.Wander);
87
            TurnOff(BehaviorType.Wander);
87
        }
88
        }
88
        
89
90
        public void TurnOnSeperation()
91
        {
92
            TurnOn(BehaviorType.Seperation);
93
        }
94
        public void TurnOffSeperation()
95
        {
96
            TurnOff(BehaviorType.Seperation);
97
        }
98
        public void TurnOnCohesion()
99
        {
100
            TurnOn(BehaviorType.Cohesion);
101
        }
102
        public void TurnOffCohesion()
103
        {
104
            TurnOff(BehaviorType.Cohesion);
105
        }
106
        public void TurnOnAlignment()
107
        {
108
            TurnOn(BehaviorType.Alignment);
109
        }
110
        public void TurnOffAlignment()
111
        {
112
            TurnOff(BehaviorType.Alignment);
113
        }
114
89
        public void TurnOnOffsetPursuit(Vector2 seek)
115
        public void TurnOnOffsetPursuit(Vector2 seek)
90
        {
116
        {
91
117
...
...
120
        private float ObstacleAvoidanceWeight=10;
146
        private float ObstacleAvoidanceWeight=10;
121
        private Vector2 SteeringForce = Vector2.Zero;
147
        private Vector2 SteeringForce = Vector2.Zero;
122
        private Vector2 Heading;
148
        private Vector2 Heading;
123
        private float MaxForce = 4;
149
        private float MaxForce = 2;
124
        private Vector2 Velocity;
150
        private Vector2 Velocity;
125
        private BehaviorType _behaviorFlags;
151
        private BehaviorType _behaviorFlags;
126
152
...
...
128
        public float SeekWeight = 1;
154
        public float SeekWeight = 1;
129
        public float ArriveWeight= 1;
155
        public float ArriveWeight= 1;
130
        public float WanderWeight= 1;
156
        public float WanderWeight= 1;
157
        public float SeperationWeight= 2;
158
        public float AlignmentWeight= 1;
159
        public float CohesionWeight = 1;
131
160
132
        public Vector2 SeekPos { get; set; }
161
        public Vector2 SeekPos { get; set; }
133
        public Deceleration DecelerationSpeed { get; set; }
162
        public Deceleration DecelerationSpeed { get; set; }
...
...
139
        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
168
        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
140
        {
169
        {
141
            timeElapsed = gameTime.GetElapsed();
170
            timeElapsed = gameTime.GetElapsed();
171
            
142
            SteeringUpdate(gameTime.GetElapsed());
172
            SteeringUpdate(gameTime.GetElapsed());
143
        }
173
        }
144
174
145
        
146
147
        private void SteeringUpdate(float elapsed)
175
        private void SteeringUpdate(float elapsed)
148
        {
176
        {
149
            Vector2 OldPos = Owner.Position;
177
            Vector2 OldPos = Owner.Position;
...
...
159
                SetHeading(Vector2.Normalize(Velocity));
187
                SetHeading(Vector2.Normalize(Velocity));
160
            }
188
            }
161
            Owner.Position += Velocity * elapsed;
189
            Owner.Position += Velocity * elapsed;
162
            Owner.Orientation = Heading;// (float)Math.Atan2(Heading.Y, Heading.X);
190
            if(Heading!=Vector2.Zero)
191
                Owner.Orientation = Heading;// (float)Math.Atan2(Heading.Y, Heading.X);
163
        }
192
        }
164
193
165
        private void SetHeading(Vector2 new_heading)
194
        private void SetHeading(Vector2 new_heading)
...
...
207
        
236
        
208
        private Vector2 CalculatePrioritized()
237
        private Vector2 CalculatePrioritized()
209
        {
238
        {
210
239
            
211
            Vector2 force = Vector2.Zero;
240
            Vector2 force = Vector2.Zero;
212
241
242
            if (On(BehaviorType.Seperation))
243
            {
244
                force = Separation() * SeperationWeight;
245
246
                if (!AccumulateForce(ref _steeringForce, force)) return _steeringForce;
247
            }
248
            if (On(BehaviorType.Alignment))
249
            {
250
                force = Alignment() * AlignmentWeight;
251
252
                if (!AccumulateForce(ref _steeringForce, force)) return _steeringForce;
253
            }
254
            if (On(BehaviorType.Cohesion))
255
            {
256
                force = Cohesion() * CohesionWeight;
257
258
                if (!AccumulateForce(ref _steeringForce, force)) return _steeringForce;
259
            }
260
213
            if (On(BehaviorType.Seek))
261
            if (On(BehaviorType.Seek))
214
            {
262
            {
215
                force = Seek(SeekPos);
263
                force = Seek(SeekPos);
...
...
237
            return _steeringForce;
285
            return _steeringForce;
238
        }
286
        }
239
287
288
        private Vector2 Cohesion()
289
        {
290
            if (Owner.GetLabel(AIConsts.ISGROUPMEMBER) == 0)
291
                return Vector2.Zero;
292
            Group g = Owner.ParentWorld.GetGroup(Owner.GetLabel(AIConsts.GROUPID));
293
294
            //first find the center of mass of all the agents
295
            Vector2 CenterOfMass=Vector2.Zero;
296
            Vector2 SteeringForce=Vector2.Zero;
297
298
            int NeighborCount = 0;
299
300
            //iterate through the neighbors and sum up all the position vectors
301
            for (int a = 0; a < g.Agents.Count; ++a)
302
            {
303
                //make sure *this* agent isn't included in the calculations and that
304
                //the agent being examined is a neighbor
305
                if ((g.Agents[a] != Owner))// && neighbors[a]->IsTagged())
306
                {
307
                    CenterOfMass += g.Agents[a].Position;
308
309
                    ++NeighborCount;
310
                }
311
            }
312
313
            if (NeighborCount > 0)
314
            {
315
                //the center of mass is the average of the sum of positions
316
                CenterOfMass /= (float)NeighborCount;
317
318
                //now seek toward that position
319
                SteeringForce = Seek(CenterOfMass);
320
            }
321
322
            return SteeringForce;
323
324
        }
325
326
        private Vector2 Alignment()
327
        {
328
            if (Owner.GetLabel(AIConsts.ISGROUPMEMBER) == 0)
329
                return Vector2.Zero;
330
            Group g = Owner.ParentWorld.GetGroup(Owner.GetLabel(AIConsts.GROUPID));
331
332
333
            //used to record the average heading of the neighbors
334
            Vector2 AverageHeading = Vector2.Zero;
335
336
            //used to count the number of vehicles in the neighborhood
337
            int NeighborCount = 0;
338
339
            //iterate through all the tagged vehicles and sum their heading vectors
340
            for (int a = 0; a < g.Agents.Count; ++a)
341
            {
342
                //make sure *this* agent isn't included in the calculations and that
343
                //the agent being examined is close enough
344
                if ((g.Agents[a] != Owner))// && g.Agents[a]->IsTagged)
345
                {
346
                    AverageHeading += g.Agents[a].Orientation;
347
348
                    ++NeighborCount;
349
                }
350
            }
351
352
            //if the neighborhood contained one or more vehicles, average their
353
            //heading vectors.
354
            if (NeighborCount > 0)
355
            {
356
                AverageHeading /= (float)NeighborCount;
357
                AverageHeading -= Owner.Orientation;
358
            }
359
360
            return AverageHeading;
361
362
        }
363
364
        private Vector2 Separation()
365
        {
366
            if (Owner.GetLabel(AIConsts.ISGROUPMEMBER) == 0)
367
                return Vector2.Zero;
368
            Group g = Owner.ParentWorld.GetGroup(Owner.GetLabel(AIConsts.GROUPID));
369
370
            Vector2 SteeringForce = Vector2.Zero;
371
            
372
            for (int a = 0; a < g.Agents.Count; ++a)
373
            {
374
                //make sure this agent isn't included in the calculations and that
375
                //the agent being examined is close enough.
376
                if ((g.Agents[a] != Owner)) // && g.Agents[a]->IsTagged())
377
                {
378
                    Vector2 ToAgent = Owner.Position - g.Agents[a].Position;
379
                    if (ToAgent == Vector2.Zero)
380
                        continue;
381
                    //scale the force inversely proportional to the agent's distance
382
                    //from its neighbor.
383
                    SteeringForce +=Vector2.Normalize(ToAgent) / ToAgent.Length();
384
                }
385
            }
386
387
            return SteeringForce;
388
389
        }
390
240
        
391
        
241
        
392
        
242
        private bool AccumulateForce(ref Vector2 sf, Vector2 ForceToAdd)
393
        private bool AccumulateForce(ref Vector2 sf, Vector2 ForceToAdd)
...
...
313
       
464
       
314
        public Vector2 Wander()
465
        public Vector2 Wander()
315
        {
466
        {
316
            double JitterThisTimeSlice = WanderJitter * timeElapsed;
467
            float JitterThisTimeSlice = WanderJitter * timeElapsed;
317
468
318
            //first, add a small random vector to the target's position (RandomClamped
469
            //first, add a small random vector to the target's position (RandomClamped
319
            //returns a value between -1 and 1)
470
            //returns a value between -1 and 1)
320
            _wanderTarget+= new Vector2(RandomClamped() * WanderJitter,
471
            _wanderTarget += new Vector2(RandomClamped() * JitterThisTimeSlice,
321
                                  RandomClamped() * WanderJitter);
472
                                  RandomClamped() * JitterThisTimeSlice);
322
473
323
            if (_wanderTarget != Vector2.Zero) //reproject this new vector back on to a unit circle
474
            if (_wanderTarget != Vector2.Zero) //reproject this new vector back on to a unit circle
324
                _wanderTarget.Normalize();
475
                _wanderTarget.Normalize();
...
...
382
        float RandomClamped()
533
        float RandomClamped()
383
        {
534
        {
384
            return rand.Next() - rand.Next();
535
            return rand.Next() - rand.Next();
385
        } 
536
        }
537
386
    }
538
    }
387
}
539
}

Updated src/BRAINSFramework/Map/Cluster.cs Download diff

2223
4
using System.Text;
4
using System.Text;
5
using Brains.Framework;
5
using Brains.Framework;
6
using Microsoft.Xna.Framework;
6
using Microsoft.Xna.Framework;
7
using Brains.Framework.PathFinding;
7
8
8
namespace Brains.Framework.Map
9
namespace Brains.Framework.Map
9
{
10
{
10
    public class Cluster
11
    public class Cluster
11
    {
12
    {
13
        
12
        private int _rows;
14
        private int _rows;
13
        private int _cols;
15
        private int _cols;
14
        private List<Grid> _grids;
16
        private List<Grid> _grids;
...
...
37
            //HACK: should support different sized grids
39
            //HACK: should support different sized grids
38
            get { return Grids[0].Cols * Cols; }
40
            get { return Grids[0].Cols * Cols; }
39
        }
41
        }
42
40
        public int TotalRows
43
        public int TotalRows
41
        {
44
        {
42
            //HACK: should support different sized grids
45
            //HACK: should support different sized grids
...
...
57
            }
60
            }
58
            return null;
61
            return null;
59
        }
62
        }
60
        
63
64
        public int GetGridIndex(int x, int y)
65
        {
66
            return y * Cols + x;
67
        }
68
        public Grid GetGrid(int x, int y)
69
        {
70
            return Grids[GetGridIndex(x, y)];
71
        }
72
73
        internal void AddEntrance(GridCell cellA, GridCell cellB)
74
        {
75
            if (!EntranceExists(cellA, cellB))
76
                Entrances.Add(new Entrance(cellA, cellB));
77
        }
78
79
        private bool EntranceExists(GridCell cellA, GridCell cellB)
80
        {
81
            for (int i = 0; i < Entrances.Count; i++)
82
            {
83
                Entrance ent = Entrances[i];
84
                if (ent.CellA == cellA && ent.CellB == cellB)
85
                    return true;
86
            }
87
            return false;
88
        }
89
        public List<Entrance> Entrances = new List<Entrance>();
61
    }
90
    }
91
    public class Entrance
92
    {
93
        public GridCell CellA { get; set; }
94
        public GridCell CellB { get; set; }
95
        public Entrance(GridCell a, GridCell b)
96
        {
97
            CellA = a;
98
            CellB = b;
99
        }
100
      
101
    }
62
}
102
}

Updated src/BRAINSFramework/Map/Grid.cs Download diff

2223
4
using System.Text;
4
using System.Text;
5
using Microsoft.Xna.Framework;
5
using Microsoft.Xna.Framework;
6
using Microsoft.Xna.Framework.Graphics;
6
using Microsoft.Xna.Framework.Graphics;
7
using Brains.Framework.PathFinding;
8
using Brains.Framework.Behaviors.PathFinding;
7
9
8
namespace Brains.Framework.Map
10
namespace Brains.Framework.Map
9
{
11
{
...
...
12
    /// </summary>
14
    /// </summary>
13
    public class Grid 
15
    public class Grid 
14
    {
16
    {
17
        public List<PreStoredPath> PredeterminedPaths = new List<PreStoredPath>();
18
15
        private int _cols;
19
        private int _cols;
16
        private int _rows;
20
        private int _rows;
17
        private List<GridCell> _cells;
21
        private List<GridCell> _cells;
...
...
39
        /// </summary>
43
        /// </summary>
40
        public Vector2 Center
44
        public Vector2 Center
41
        {
45
        {
42
            get { return Position; }
46
            get { return Position+(Size/2); }
43
        }
47
        }
44
        
48
        
45
        /// <summary>
49
        /// <summary>

Updated src/BRAINSFramework/Map/GridCell.cs Download diff

2223
48
        /// Type value of the Grid Cell.
48
        /// Type value of the Grid Cell.
49
        /// </summary>
49
        /// </summary>
50
        /// <remarks>1 = Empty, 0 = Blocked</remarks>
50
        /// <remarks>1 = Empty, 0 = Blocked</remarks>
51
        public int Type { get { return _type; } set { _type = value; } }
51
        public int Type 
52
        { 
53
            get { return _type; }
54
            set
55
            {
56
                _type = value;
57
                Labels[AIConsts.BLOCKED_TILE] = _type == 0 ? 1 : 0;
58
            }
59
        }
52
        
60
        
53
        /// <summary>
61
        /// <summary>
54
        /// The Parent Grid
62
        /// The Parent Grid
...
...
73
        {
81
        {
74
82
75
            Labels = new Dictionary<uint, int>();
83
            Labels = new Dictionary<uint, int>();
76
            Labels.Add(AIConsts.ISVALIDCLUSTEREDGE, 0);
84
            Labels.Add(AIConsts.BLOCKED_TILE, 0);
85
            Labels.Add(AIConsts.RESERVED, 0);
77
            Labels.Add(AIConsts.CLEARANCEVALUE,0);
86
            Labels.Add(AIConsts.CLEARANCEVALUE,0);
78
            Labels.Add(AIConsts.COLORR, 0);
87
            Labels.Add(AIConsts.COLORR, 0);
79
            Labels.Add(AIConsts.COLORG, 0);
88
            Labels.Add(AIConsts.COLORG, 0);

Updated src/BRAINSFramework/PathFinding/PathFinder.cs Download diff

2223
108
                {
108
                {
109
                    for (int h = 0; h < _map.Rows; h++)
109
                    for (int h = 0; h < _map.Rows; h++)
110
                    {
110
                    {
111
                        _grid[w, h] = _agent.TypeToCost(_map.GetCell(w, h).Type);
111
                        if (_agent == null)
112
                        {
113
                            if (_map.GetCell(w, h).Type == 0)
114
                                _grid[w, h] = 99;
115
                            else
116
                                _grid[w, h] = _map.GetCell(w, h).Type;
117
                        }
118
                        else
119
                            _grid[w, h] = _agent.GetCostOfCellType(_map.GetCell(w, h).Type);
112
                    }
120
                    }
113
                }
121
                }
114
            }
122
            }
...
...
237
245
238
                            float Heuristic = 0;
246
                            float Heuristic = 0;
239
                            //Three different types of Heuristic calculation
247
                            //Three different types of Heuristic calculation
240
                            if(HType==HeuristicType.Euclidean)
248
                            //if(HType==HeuristicType.Euclidean)
241
                                Heuristic = (int)(_heuristicEstimateValue  * (Math.Sqrt(Math.Pow((_node.X - _endNode.X), 2) + Math.Pow((_node.Y - _endNode.Y),
2))));
249
                            //    Heuristic = (int)(_heuristicEstimateValue  * (Math.Sqrt(Math.Pow((_node.X - _endNode.X), 2) + Math.Pow((_node.Y - _endNode.Y), 2))));
242
                            else if(HType==HeuristicType.Manhattan)
250
                            //else //if(HType==HeuristicType.Manhattan)
243
                                Heuristic = _heuristicEstimateValue * (Math.Abs(_endNode.X - _node.X) + Math.Abs(_endNode.Y - _node.Y));
251
                                Heuristic = _heuristicEstimateValue * (Math.Abs(_endNode.X - _node.X) + Math.Abs(_endNode.Y - _node.Y));
244
                            else if(HType==HeuristicType.Diagonal)
252
                            //else if(HType==HeuristicType.Diagonal)
245
                                Heuristic = _heuristicEstimateValue * Math.Max(Math.Abs(_node.X - _endNode.X), Math.Abs(_node.X- _endNode.Y));
253
                              //  Heuristic = _heuristicEstimateValue * Math.Max(Math.Abs(_node.X - _endNode.X), Math.Abs(_node.X- _endNode.Y));
246
254
247
                            _node.H = (int)Heuristic;
255
                            _node.H = (int)Heuristic;
248
256

Updated src/BRAINSFramework/Utility/AIConsts.cs Download diff

2223
11
    public static class AIConsts
11
    public static class AIConsts
12
    {
12
    {
13
        public const uint BLOCKED_TILE = 0;
13
        public const uint BLOCKED_TILE = 0;
14
        public const int ISVALIDCLUSTEREDGE = 1;
14
        public const int RESERVED = 1;
15
        public const int CLEARANCEVALUE = 2;
15
        public const int CLEARANCEVALUE = 2;
16
        public const int COLORR = 3;
16
        public const int COLORR = 3;
17
        public const int COLORG = 4;
17
        public const int COLORG = 4;
18
        public const int COLORB = 5;
18
        public const int COLORB = 5;
19
        public const int COLORA = 6;
19
        public const int COLORA = 6;
20
        public const int ISGROUPMEMBER = 7;
21
        public const int GROUPID= 8;
20
22
21
    }
23
    }
22
}
24
}

Updated src/BRAINSFramework/World.cs Download diff

2223
9
using Brains.Framework.QuadTree;
9
using Brains.Framework.QuadTree;
10
using Brains.Framework.Map;
10
using Brains.Framework.Map;
11
using Brains.Framework.Utility;
11
using Brains.Framework.Utility;
12
using Brains.Framework.Behaviors.PathFinding;
13
using Brains.Grouping;
12
namespace Brains.Framework
14
namespace Brains.Framework
13
{
15
{
14
    /// <summary>
16
    /// <summary>
...
...
23
        private List<Agent> _agentsToRemove = new List<Agent>();
25
        private List<Agent> _agentsToRemove = new List<Agent>();
24
        private Texture2D _mapTexture;
26
        private Texture2D _mapTexture;
25
        private WorldMap _map;
27
        private WorldMap _map;
28
26
        //
29
        //
27
        //Public properties
30
        //Public properties
28
        //
31
        //
...
...
36
        /// </summary>
39
        /// </summary>
37
        public List<Agent> Actors = new List<Agent>();
40
        public List<Agent> Actors = new List<Agent>();
38
41
42
        public Dictionary<int,Group> Groups { get; set; }
43
39
        /// <summary>
44
        /// <summary>
40
        /// Gets the world map
45
        /// Gets the world map
41
        /// </summary>
46
        /// </summary>
42
        public WorldMap Map { get { return _map; } }
47
        public WorldMap Map { get { return _map; } }
43
48
49
        public World()
50
        {
51
            Groups = new Dictionary<int, Group>();
52
        }
44
        //
53
        //
45
        //Public Methods
54
        //Public Methods
46
        //
55
        //
...
...
52
        {
61
        {
53
            foreach (var item in Actors)
62
            foreach (var item in Actors)
54
            {
63
            {
64
                item.UpdatePerception(gameTime);
65
            }
66
            foreach (var item in Actors)
67
            {
55
                item.Update(gameTime);
68
                item.Update(gameTime);
56
            }
69
            }
57
            if (_agentsToRemove.Count > 0)
70
            if (_agentsToRemove.Count > 0)
...
...
74
        {
87
        {
75
            SetupMap(width, height, cellsize, width / cellsize, height / cellsize,typeof(Grid));
88
            SetupMap(width, height, cellsize, width / cellsize, height / cellsize,typeof(Grid));
76
        }
89
        }
90
        protected static sbyte[,] direction = new sbyte[4, 2]
91
            { 
92
                { 0,-1} , 
93
                { 1, 0}, 
94
                { 0, 1}, 
95
                {-1, 0}
96
            };
77
97
78
        /// <summary>
98
        /// <summary>
79
        /// This method will create a game Map of the defined size and automatically cluster the map into grids
99
        /// This method will create a game Map of the defined size and automatically cluster the map into grids
...
...
119
            }
139
            }
120
            
140
            
121
        }
141
        }
122
        
142
143
      
144
       
123
        public void AnotateMap()
145
        public void AnotateMap()
124
        {
146
        {
125
            List<QuadTreePositionItem<GridCell>> list = new List<QuadTreePositionItem<GridCell>>();
147
            List<QuadTreePositionItem<GridCell>> list = new List<QuadTreePositionItem<GridCell>>();
...
...
197
                {
219
                {
198
                    for (int x = 0; x < cols; x++)
220
                    for (int x = 0; x < cols; x++)
199
                    {
221
                    {
200
                        
222
                        SetHorizontalEntrancesOnGrid(x, y);
201
                        //Check right edge
223
                        SetVerticalEntrancesOnGrid(x, y);
202
                        if (cluster.Grids.Count > index + 1)
224
                        ////Check right edge
203
                        {
225
                        //if (cluster.Grids.Count > index + 1)
204
                            for (int row = 0; row < cluster.Grids[index].Rows; row++)
226
                        //{
205
                            {
227
                        //    for (int row = 0; row < cluster.Grids[index].Rows; row++)
206
                                GridCell leftcell = cluster.Grids[index].GetCell(
228
                        //    {
207
                                                cluster.Grids[index].Cols - 1,
229
                        //        GridCell leftcell = cluster.Grids[index].GetCell(
208
                                                row);
230
                        //                        cluster.Grids[index].Cols - 1,
209
                                GridCell rightcell = cluster.Grids[index + 1].GetCell(
231
                        //                        row);
210
                                                0,
232
                        //        GridCell rightcell = cluster.Grids[index + 1].GetCell(
211
                                                row);
233
                        //                        0,
234
                        //                        row);
212
235
213
                                if (leftcell.Type != AIConsts.BLOCKED_TILE &&
236
                        //        if (leftcell.Type != AIConsts.BLOCKED_TILE &&
214
                                    rightcell.Type != AIConsts.BLOCKED_TILE)
237
                        //            rightcell.Type != AIConsts.BLOCKED_TILE)
215
                                {
238
                        //        {
216
                                    leftcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
239
                        //            //leftcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
217
                                    rightcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
240
                        //            //rightcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
218
                                }
241
                        //        }
219
                            }
242
                        //    }
220
                        }
243
                        //}
221
244
222
                        //check left edge
245
                        ////check left edge
223
246
224
                        if (index > 1)
247
                        //if (index > 1)
225
                        {
248
                        //{
226
                            for (int row = 0; row < cluster.Grids[index].Rows; row++)
249
                        //    for (int row = 0; row < cluster.Grids[index].Rows; row++)
227
                            {
250
                        //    {
228
                                GridCell leftcell = cluster.Grids[index - 1].GetCell(
251
                        //        GridCell leftcell = cluster.Grids[index - 1].GetCell(
229
                                                    cluster.Grids[index - 1].Cols - 1,
252
                        //                            cluster.Grids[index - 1].Cols - 1,
230
                                                    row);
253
                        //                            row);
231
                                GridCell rightcell = cluster.Grids[index].GetCell(
254
                        //        GridCell rightcell = cluster.Grids[index].GetCell(
232
                                                0,
255
                        //                        0,
233
                                                row);
256
                        //                        row);
234
257
235
                                if (leftcell.Type != AIConsts.BLOCKED_TILE &&
258
                        //        if (leftcell.Type != AIConsts.BLOCKED_TILE &&
236
                                    rightcell.Type != AIConsts.BLOCKED_TILE)
259
                        //            rightcell.Type != AIConsts.BLOCKED_TILE)
237
                                {
260
                        //        {
238
                                    leftcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
261
                        //            //leftcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
239
                                    rightcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
262
                        //            //rightcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
240
                                }
263
                        //        }
241
                            }
264
                        //    }
242
                        }
265
                        //}
243
266
244
                        //check bottom edge
267
                        ////check bottom edge
245
268
246
                        if (index + cols < cluster.Grids.Count)
269
                        //if (index + cols < cluster.Grids.Count)
247
                        {
270
                        //{
248
                            for (int col = 0; col < cluster.Grids[index].Cols; col++)
271
                        //    for (int col = 0; col < cluster.Grids[index].Cols; col++)
249
                            {
272
                        //    {
250
                                GridCell topcell = cluster.Grids[index].GetCell(
273
                        //        GridCell topcell = cluster.Grids[index].GetCell(
251
                                                col,
274
                        //                        col,
252
                                                cluster.Grids[index].Rows - 1);
275
                        //                        cluster.Grids[index].Rows - 1);
253
                                GridCell bottomcell = cluster.Grids[index + cols].GetCell(
276
                        //        GridCell bottomcell = cluster.Grids[index + cols].GetCell(
254
                                                col,
277
                        //                        col,
255
                                                0);
278
                        //                        0);
256
279
257
                                if (topcell.Type != AIConsts.BLOCKED_TILE &&
280
                        //        if (topcell.Type != AIConsts.BLOCKED_TILE &&
258
                                    bottomcell.Type != AIConsts.BLOCKED_TILE)
281
                        //            bottomcell.Type != AIConsts.BLOCKED_TILE)
259
                                {
282
                        //        {
260
                                    bottomcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
283
                        //          //  bottomcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
261
                                    topcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
284
                        //          //  topcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
262
                                }
285
                        //        }
263
                            }
286
                        //    }
264
                        }
287
                        //}
265
                        //Check Top
288
                        ////Check Top
266
                        if (index - cols > 0)
289
                        //if (index - cols > 0)
267
                        {
290
                        //{
268
                            for (int col = 0; col < cluster.Grids[index].Cols; col++)
291
                        //    for (int col = 0; col < cluster.Grids[index].Cols; col++)
269
                            {
292
                        //    {
270
                                GridCell topcell = cluster.Grids[index - cols].GetCell(
293
                        //        GridCell topcell = cluster.Grids[index - cols].GetCell(
271
                                                col,
294
                        //                        col,
272
                                                cluster.Grids[index - cols].Rows - 1);
295
                        //                        cluster.Grids[index - cols].Rows - 1);
273
                                GridCell bottomcell = cluster.Grids[index].GetCell(
296
                        //        GridCell bottomcell = cluster.Grids[index].GetCell(
274
                                                col,
297
                        //                        col,
275
                                                0);
298
                        //                        0);
276
299
277
                                if (topcell.Type != AIConsts.BLOCKED_TILE &&
300
                        //        if (topcell.Type != AIConsts.BLOCKED_TILE &&
278
                                    bottomcell.Type != AIConsts.BLOCKED_TILE)
301
                        //            bottomcell.Type != AIConsts.BLOCKED_TILE)
279
                                {
302
                        //        {
280
                                    bottomcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
303
                        //            //bottomcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
281
                                    topcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
304
                        //            //topcell.Labels[AIConsts.ISVALIDCLUSTEREDGE] = 1;
282
                                }
305
                        //        }
283
                            }
306
                        //    }
284
                        }
307
                        //}
285
                        index++;
308
                        index++;
286
                    }
309
                    }
287
                }
310
                }
288
            }
311
            }
312
313
314
            //Precalculate paths for each grid transition
315
            int gridIndex = 0;
316
            foreach (var item in Map.ClusterGrid.Grids)
317
            {
318
                
319
                int y = (gridIndex - (gridIndex % Map.ClusterGrid.Cols)) / Map.ClusterGrid.Cols;
320
                int x = gridIndex % Map.ClusterGrid.Cols;
321
                //North To East
322
                if (y > 0 && x < Map.ClusterGrid.Cols - 1)
323
                {
324
                    PredeterminePaths(item,x, y - 1, x + 1, y);
325
                }
326
                //East To South
327
                if (x < Map.ClusterGrid.Cols - 1 && y<Map.ClusterGrid.Rows-1)
328
                {
329
                    PredeterminePaths(item, x + 1, y, x, y + 1);
330
                }
331
                //South To West
332
                if (y < Map.ClusterGrid.Rows - 1 && x > 0)
333
                {
334
                    PredeterminePaths(item, x, y + 1, x - 1, y);
335
                }
336
                //West To Nort
337
                if (x>0 && y>0)
338
                {
339
                    PredeterminePaths(item, x - 1, y, x, y - 1);
340
                }
341
342
                //West To East
343
                if (x > 0 && x < Map.ClusterGrid.Cols-1)
344
                {
345
                    PredeterminePaths(item, x - 1, y, x + 1, y);
346
                }
347
348
                //North To South
349
                if (y > 0 && y < Map.ClusterGrid.Rows- 1)
350
                {
351
                    PredeterminePaths(item, x, y - 1, x, y + 1);
352
                }
353
                gridIndex++;
354
            }
355
356
357
            //Cluster cl = Map.ClusterGrid;
358
            //int index1 = 0;
359
360
361
            //foreach (var item in Map.ClusterGrid.Grids)
362
            //{
363
            //    int y = (index1 - (index1 % cl.Cols)) / cl.Cols;
364
            //    int x = index1 % cl.Cols;
365
366
            //    //Top To Right
367
            //    if (y > 0 && x < cl.Cols - 1)
368
            //    {
369
            //        int indexF = (y-1) * cl.Cols + x ;
370
            //        int indexT = y * cl.Cols + (x+1);
371
            //        GridCell from;
372
            //        GridCell to;
373
374
            //        from = GetFreeCellAt(item, Direction.up);
375
            //        to = GetFreeCellAt(item, Direction.rigth);
376
            //        if(from!=null&& to!=null)
377
            //            CalculatePath(from, to,indexF,indexT);
378
            //    }
379
            //    //Right To Bottom
380
            //    if (y < cl.Rows - 1 && x < cl.Cols - 1)
381
            //    {
382
            //        int indexF = y * cl.Cols + (x + 1);
383
            //        int indexT = (y + 1) * cl.Cols + x;
384
            //        GridCell from;
385
            //        GridCell to;
386
387
            //        from = GetFreeCellAt(item, Direction.rigth);
388
            //        to = GetFreeCellAt(item, Direction.down);
389
            //        if (from != null && to != null)
390
            //            CalculatePath(from, to, indexF, indexT);
391
            //    }
392
            //    //Bottom To Left
393
            //    if (y < cl.Rows - 1 && x > 0)
394
            //    {
395
            //        int indexF = (y + 1) * cl.Cols + x;
396
            //        int indexT = y * cl.Cols + (x - 1);
397
            //        GridCell from;
398
            //        GridCell to;
399
400
            //        from = GetFreeCellAt(item, Direction.down);
401
            //        to = GetFreeCellAt(item, Direction.left);
402
            //        if (from != null && to != null)
403
            //            CalculatePath(from, to, indexF, indexT);
404
            //    }
405
            //    //Left To Top
406
            //    if (y > 0 && x > 0)
407
            //    {
408
            //        int indexF = y * cl.Cols + (x-1);
409
            //        int indexT = (y-1) * cl.Cols + x;
410
            //        GridCell from;
411
            //        GridCell to;
412
413
            //        from = GetFreeCellAt(item, Direction.left);
414
            //        to = GetFreeCellAt(item, Direction.up);
415
            //        if (from != null && to != null)
416
            //            CalculatePath(from, to, indexF, indexT);
417
            //    }
418
            //    //Top to bottom
419
            //    if (y > 0 && y < cl.Rows - 1)
420
            //    {
421
            //        int indexF = (y - 1) * cl.Cols + x;
422
            //        int indexT = (y + 1) * cl.Cols + x;
423
            //        GridCell from;
424
            //        GridCell to;
425
426
            //        from = GetFreeCellAt(item, Direction.up);
427
            //        to = GetFreeCellAt(item, Direction.down);
428
            //        if (from != null && to != null)
429
            //            CalculatePath(from, to, indexF, indexT);
430
            //    }
431
            //    //Left To Right
432
            //    if (x > 0 && x < cl.Cols - 1)
433
            //    {
434
            //        int indexF = y * cl.Cols + (x - 1);
435
            //        int indexT = y * cl.Cols + (x + 1);
436
            //        GridCell from;
437
            //        GridCell to;
438
439
            //        from = GetFreeCellAt(item, Direction.left);
440
            //        to = GetFreeCellAt(item, Direction.rigth);
441
            //        if (from != null && to != null)
442
            //            CalculatePath(from, to,indexF,indexT);
443
            //    }
444
445
            //    index1++;
446
            //}
289
        }
447
        }
448
449
        private void PredeterminePaths(Grid grid,int x1,int y1,int x2,int y2)
450
        {
451
452
            int indexF = Map.ClusterGrid.GetGridIndex(x1, y1);
453
            int indexT = Map.ClusterGrid.GetGridIndex(x2, y2);
454
455
            Grid gridA = Map.ClusterGrid.GetGrid(x1, y1);
456
            GridCell cellA= GetValidCellFromEntrance(gridA,grid);
457
458
            Grid gridB= Map.ClusterGrid.GetGrid(x2, y2);
459
            GridCell cellB = GetValidCellFromEntrance(gridB, grid);
460
461
            if (cellB != null && cellA != null)
462
            {
463
                CalculatePath(
464
                    grid.GetCell(cellA.X,cellA.Y),
465
                    grid.GetCell(cellB.X, cellB.Y), 
466
                    indexF, 
467
                    indexT);
468
            }
469
        }
470
471
        private GridCell GetValidCellFromEntrance(Grid fromGrid,Grid toGrid)
472
        {
473
            foreach (var entrance in Map.ClusterGrid.Entrances)
474
            {
475
                if (entrance.CellA.Parent == fromGrid && entrance.CellB.Parent==toGrid)
476
                    return entrance.CellB;
477
                if (entrance.CellB.Parent == fromGrid && entrance.CellA.Parent == toGrid)
478
                    return entrance.CellA;
479
            }
480
            return null;
481
        }
482
483
        private void SetVerticalEntrancesOnGrid(int x, int y)
484
        {
485
            bool checkEast = false;
486
            bool checkWest = false;
487
488
            Grid thisGrid = Map.ClusterGrid.GetGrid(x, y);
489
490
            if (x > 0)
491
                checkWest= true;
492
493
            if (x < Map.ClusterGrid.Cols- 1)
494
                checkEast = true;
495
496
            if (checkEast)
497
            {
498
                Grid eastGrid = Map.ClusterGrid.GetGrid(x+1, y);
499
                SetVertEntranceBetweenGrids(thisGrid, eastGrid);
500
            }
501
            if (checkWest)
502
            {
503
                Grid westGrid= Map.ClusterGrid.GetGrid(x-1, y);
504
                SetVertEntranceBetweenGrids(thisGrid, westGrid);
505
            }
506
        }
507
508
        private void SetVertEntranceBetweenGrids(Grid gridA, Grid gridB)
509
        {
510
            int yIndexa = 0;
511
            int yIndexb = gridA.Cols- 1;
512
            if (gridB.Position.X > gridA.Position.X)
513
            {
514
                yIndexa = yIndexb;
515
                yIndexb = 0;
516
            }
517
            //Start near the middle
518
            int startRow = gridA.Rows/ 2;
519
            //Currently supports 1 transition per set of grids
520
            bool continueChecking = true;
521
            //Loop to end ignoring the corner cell
522
            for (int i = startRow; i < gridA.Rows - 1; i++)
523
            {
524
525
                GridCell _edgeCell = gridA.GetCell(yIndexa,i);
526
                GridCell _adjacentCell = gridB.GetCell(yIndexb,i);
527
                if (_edgeCell.Labels[AIConsts.BLOCKED_TILE] == 0 &&
528
                    _adjacentCell.Labels[AIConsts.BLOCKED_TILE] == 0)
529
                {
530
                    Map.ClusterGrid.AddEntrance(_edgeCell, _adjacentCell);
531
                    continueChecking = false;
532
                    break;
533
                }
534
            }
535
            if (continueChecking)
536
            {
537
                //Loop to beginning column ignoring the corner cell
538
                for (int i = startRow; i > 0; i--)
539
                {
540
                    GridCell _edgeCell = gridA.GetCell(yIndexa, i);
541
                    GridCell _adjacentCell = gridB.GetCell(yIndexb, i);
542
                    if (_edgeCell.Labels[AIConsts.BLOCKED_TILE] == 0 && _adjacentCell.Labels[AIConsts.BLOCKED_TILE] == 0)
543
                    {
544
                        Map.ClusterGrid.AddEntrance(_edgeCell, _adjacentCell);
545
                        continueChecking = false;
546
                        break;
547
                    }
548
                }
549
            }
550
551
        }
290
        
552
        
553
        private void SetHorizontalEntrancesOnGrid(int x, int y)
554
        {
555
            bool checkNorth = false;
556
            bool checkSouth = false;
557
558
            Grid thisGrid = Map.ClusterGrid.GetGrid(x,y);
559
            
560
            if (y > 0)
561
                checkNorth = true;
562
            
563
            if (y < Map.ClusterGrid.Rows-1)
564
                checkSouth= true;
565
566
            if (checkNorth)
567
            {
568
                Grid northGrid = Map.ClusterGrid.GetGrid(x, y - 1);
569
                SetHorizEntranceBetweenGrids(thisGrid, northGrid);
570
            }
571
            if (checkSouth)
572
            {
573
                Grid southGrid = Map.ClusterGrid.GetGrid(x, y + 1);
574
                SetHorizEntranceBetweenGrids(thisGrid, southGrid);
575
            }
576
            
577
578
        }
579
580
        private void SetHorizEntranceBetweenGrids(Grid gridA, Grid gridB)
581
        {
582
            int yIndexa = 0;
583
            int yIndexb = gridA.Rows - 1;
584
            if (gridB.Position.Y > gridA.Position.Y)
585
            {
586
                yIndexa = yIndexb;
587
                yIndexb = 0;
588
            }
589
            //Start near the middle
590
            int startCol = gridA.Cols / 2;
591
            //Currently supports 1 transition per set of grids
592
            bool continueChecking = true;
593
            //Loop to end ignoring the corner cell
594
            for (int i = startCol; i < gridA.Cols - 1; i++)
595
            {
596
                
597
                GridCell _edgeCell = gridA.GetCell(i, yIndexa);
598
                GridCell _adjacentCell = gridB.GetCell(i, yIndexb);
599
                if (_edgeCell.Labels[AIConsts.BLOCKED_TILE] == 0 && 
600
                    _adjacentCell.Labels[AIConsts.BLOCKED_TILE] == 0)
601
                {
602
                    Map.ClusterGrid.AddEntrance(_edgeCell, _adjacentCell);
603
                    continueChecking = false;
604
                    break;
605
                }
606
            }
607
            if (continueChecking)
608
            {
609
                //Loop to beginning column ignoring the corner cell
610
                for (int i = startCol; i > 0; i--)
611
                {
612
                    GridCell _edgeCell = gridA.GetCell(i, yIndexa);
613
                    GridCell _adjacentCell = gridB.GetCell(i, yIndexb);
614
                    if (_edgeCell.Labels[AIConsts.BLOCKED_TILE] == 0 && _adjacentCell.Labels[AIConsts.BLOCKED_TILE] == 0)
615
                    {
616
                        Map.ClusterGrid.AddEntrance(_edgeCell, _adjacentCell);
617
                        continueChecking = false;
618
                        break;
619
                    }
620
                }
621
            }
622
623
624
        }
625
626
        private void CalculatePath(GridCell from, GridCell to,int gridfrom,int gridto)
627
        {
628
            PathFinding.PathFinder _f = new Brains.Framework.PathFinding.PathFinder();
629
            _f.Grid = from.Parent;
630
            _f.StartNode = from;
631
            _f.EndNode = to;
632
            _f.Reset();
633
634
            while (_f.State == Brains.Framework.PathFinding.PathFinderState.Working)
635
            {
636
                _f.Iterate();
637
            }
638
            if (_f.State == Brains.Framework.PathFinding.PathFinderState.Finished)
639
            {
640
                // copying nodes
641
                PreStoredPath _path = new PreStoredPath();
642
                _path.Nodes = new List<StoredPathNode>();
643
                
644
                int counter = 0;
645
                //for (int index = pathFinder.closeList.Count - 1; index >= 0; index--)
646
                for (int index = 0; index <= _f.closeList.Count - 1; index++)
647
                {
648
                    StoredPathNode newNode = new StoredPathNode();
649
                    Grid grid = from.Parent;
650
                    GridCell _node = grid.GetCell(_f.closeList[index].X,
651
                                            _f.closeList[index].Y);
652
                    newNode.nodePosition.X = grid.GetCell(_f.closeList[index].X,
653
                                            _f.closeList[index].Y).Position.X;
654
                    newNode.nodePosition.Y = grid.GetCell(_f.closeList[index].X,
655
                                            _f.closeList[index].Y).Position.Y;
656
                    newNode.X = _f.closeList[index].X;
657
                    newNode.Y = _f.closeList[index].Y;
658
659
660
                    _path.FromGrid =gridfrom;
661
                    _path.ToGrid = gridto;
662
                    //pathNodes[counter] = newNode;
663
                    _path.Nodes.Add(newNode);
664
                    counter++;
665
                }
666
667
668
                from.Parent.PredeterminedPaths.Add(_path);
669
            }
670
            if (_f.State == Brains.Framework.PathFinding.PathFinderState.Failed)
671
            {
672
                Console.WriteLine("");
673
            }
674
675
        }
676
        
291
        /// <summary>
677
        /// <summary>
292
        /// Adds the specified Actor to the Actors collection
678
        /// Adds the specified Actor to the Actors collection
293
        /// </summary>
679
        /// </summary>
...
...
324
        /// <param name="cols">The number of cols to split the map into</param>
710
        /// <param name="cols">The number of cols to split the map into</param>
325
        /// <param name="rows">The number of rows to split the map into</param>
711
        /// <param name="rows">The number of rows to split the map into</param>
326
        /// <param name="gridType">The type of grid to create</param>
712
        /// <param name="gridType">The type of grid to create</param>
327
        public void LoadMapDataFromTexture(Texture2D texture, int cols, int rows, int cellSize, Type gridType)
713
        public void LoadMapDataFromTexture(Texture2D texture, int clusterColumnSplit, int clusterRowSplit, int cellSize, Type gridType)
328
        {
714
        {
329
            _mapTexture = texture;
715
            _mapTexture = texture;
330
716
331
            Vector2 position = new Vector2();
717
            Vector2 position = new Vector2();
332
            int clusterCols = texture.Width / cols;
718
            int clusterCols = texture.Width / clusterColumnSplit;
333
            int clusterRows = texture.Height / rows;
719
            int clusterRows = texture.Height / clusterRowSplit;
334
720
335
            SetupMap(
721
            SetupMap(
336
                texture.Width * cellSize,
722
                texture.Width * cellSize,
...
...
341
                gridType);
727
                gridType);
342
728
343
            int index = 0;
729
            int index = 0;
344
            for (int y = 0; y < rows; y++)
730
            for (int y = 0; y < clusterRowSplit; y++)
345
            {
731
            {
346
                for (int x = 0; x < cols; x++)
732
                for (int x = 0; x < clusterColumnSplit; x++)
347
                {
733
                {
348
                    Grid item = Map.ClusterGrid.Grids[index];
734
                    Grid item = Map.ClusterGrid.Grids[index];
349
                    index++;
735
                    index++;
...
...
408
        {
794
        {
409
            _agentsToRemove.Add(agent);
795
            _agentsToRemove.Add(agent);
410
        }
796
        }
797
798
        public void AddGroup(Group group)
799
        {
800
            Groups.Add(group.GroupID, group);
801
        }
802
        public Group GetGroup(int id)
803
        {
804
            return Groups[id];
805
        }
411
    }
806
    }
412
}
807
}