Per-player unit production. Also, fixed an interesting bug in Sequence.

This commit is contained in:
Bob
2009-10-30 04:03:37 +13:00
parent 8580ae0f78
commit 242fa717b6
6 changed files with 551 additions and 481 deletions

View File

@@ -1,13 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using IjwFramework.Types; using IjwFramework.Types;
using System.Drawing; using System.Drawing;
using OpenRa.Game.Traits; using OpenRa.Game.Traits;
namespace OpenRa.Game namespace OpenRa.Game
{ {
class Controller class Controller
{ {
@@ -76,7 +76,7 @@ namespace OpenRa.Game
if (mi.Button == MouseButtons.None && mi.Event == MouseInputEvent.Move) if (mi.Button == MouseButtons.None && mi.Event == MouseInputEvent.Move)
{ {
/* update the cursor to reflect the thing under us - note this /* update the cursor to reflect the thing under us - note this
* needs to also happen when the *thing* changes, so per-frame hook */ * needs to also happen when the *thing* changes, so per-frame hook */
dragStart = dragEnd = xy; dragStart = dragEnd = xy;
} }
@@ -101,31 +101,6 @@ namespace OpenRa.Game
.FirstOrDefault(a => a != null) : null; .FirstOrDefault(a => a != null) : null;
return c ?? (Game.SelectUnitOrBuilding(Game.CellSize * dragEnd).Any() ? Cursor.Select : Cursor.Default); return c ?? (Game.SelectUnitOrBuilding(Game.CellSize * dragEnd).Any() ? Cursor.Select : Cursor.Default);
//foreach( var o in
//var uog = orderGenerator as UnitOrderGenerator;
//if (uog != null)
// uog.selection.RemoveAll(a => a.IsDead);
//if (uog != null && uog.selection.Count > 0
// && uog.selection.Any(a => a.traits.Contains<Traits.Mobile>())
// && uog.selection.All(a => a.Owner == Game.LocalPlayer))
//{
// var umts = uog.selection.Select(a => a.traits.GetOrDefault<Mobile>())
// .Where(m => m != null)
// .Select(m => m.GetMovementType())
// .Distinct();
// if (!umts.Any(umt => Game.IsCellBuildable(dragEnd.ToInt2(), umt)))
// return Cursor.MoveBlocked;
// return Cursor.Move;
//}
//if (Game.SelectUnitOrBuilding(Game.CellSize * dragEnd).Any())
// return Cursor.Select;
//return Cursor.Default;
} }
} }
} }

View File

@@ -1,260 +1,262 @@
using System.Collections.Generic; using System.Collections.Generic;
using OpenRa.FileFormats; using OpenRa.FileFormats;
using OpenRa.Game.Graphics; using OpenRa.Game.Graphics;
using OpenRa.TechTree; using OpenRa.TechTree;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using IrrKlang; using IrrKlang;
using IjwFramework.Collections; using IjwFramework.Collections;
using System; using System;
using IjwFramework.Types; using IjwFramework.Types;
using OpenRa.Game.Traits; using OpenRa.Game.Traits;
using OpenRa.Game.GameRules; using OpenRa.Game.GameRules;
namespace OpenRa.Game namespace OpenRa.Game
{ {
static class Game static class Game
{ {
public static readonly int CellSize = 24; public static readonly int CellSize = 24;
public static World world; public static World world;
public static Map map; public static Map map;
static TreeCache treeCache; static TreeCache treeCache;
public static Viewport viewport; public static Viewport viewport;
public static PathFinder PathFinder; public static PathFinder PathFinder;
public static WorldRenderer worldRenderer; public static WorldRenderer worldRenderer;
public static Controller controller; public static Controller controller;
public static OrderManager orderManager; public static OrderManager orderManager;
static int localPlayerIndex; static int localPlayerIndex;
public static Dictionary<int, Player> players = new Dictionary<int, Player>(); public static Dictionary<int, Player> players = new Dictionary<int, Player>();
public static Player LocalPlayer { get { return players[localPlayerIndex]; } } public static Player LocalPlayer { get { return players[localPlayerIndex]; } }
public static BuildingInfluenceMap BuildingInfluence; public static BuildingInfluenceMap BuildingInfluence;
public static UnitInfluenceMap UnitInfluence; public static UnitInfluenceMap UnitInfluence;
static ISoundEngine soundEngine; static ISoundEngine soundEngine;
public static string Replay; public static string Replay;
public static void Initialize(string mapName, Renderer renderer, int2 clientSize, int localPlayer) public static void Initialize(string mapName, Renderer renderer, int2 clientSize, int localPlayer)
{ {
Rules.LoadRules(mapName); Rules.LoadRules(mapName);
for (int i = 0; i < 8; i++) for (int i = 0; i < 8; i++)
players.Add(i, new Player(i, string.Format("Multi{0}", i), Race.Soviet)); players.Add(i, new Player(i, string.Format("Multi{0}", i), Race.Soviet));
localPlayerIndex = localPlayer; localPlayerIndex = localPlayer;
var mapFile = new IniFile(FileSystem.Open(mapName)); var mapFile = new IniFile(FileSystem.Open(mapName));
map = new Map(mapFile); map = new Map(mapFile);
FileSystem.Mount(new Package(map.Theater + ".mix")); FileSystem.Mount(new Package(map.Theater + ".mix"));
viewport = new Viewport( clientSize, map.Offset, map.Offset + map.Size, renderer ); viewport = new Viewport( clientSize, map.Offset, map.Offset + map.Size, renderer );
world = new World(); world = new World();
treeCache = new TreeCache(map); treeCache = new TreeCache(map);
foreach (TreeReference treeReference in map.Trees) foreach (TreeReference treeReference in map.Trees)
world.Add(new Actor(treeReference, treeCache)); world.Add(new Actor(treeReference, treeCache));
BuildingInfluence = new BuildingInfluenceMap(8); BuildingInfluence = new BuildingInfluenceMap(8);
UnitInfluence = new UnitInfluenceMap(); UnitInfluence = new UnitInfluenceMap();
LoadMapBuildings(mapFile); LoadMapBuildings(mapFile);
LoadMapUnits(mapFile); LoadMapUnits(mapFile);
controller = new Controller(); controller = new Controller();
worldRenderer = new WorldRenderer(renderer); worldRenderer = new WorldRenderer(renderer);
PathFinder = new PathFinder( map, worldRenderer.terrainRenderer.tileSet ); PathFinder = new PathFinder( map, worldRenderer.terrainRenderer.tileSet );
soundEngine = new ISoundEngine(); soundEngine = new ISoundEngine();
sounds = new Cache<string, ISoundSource>(LoadSound); sounds = new Cache<string, ISoundSource>(LoadSound);
orderManager = (Replay == "") orderManager = (Replay == "")
? new OrderManager(new[] { new LocalOrderSource() }, "replay.rep") ? new OrderManager(new[] { new LocalOrderSource() }, "replay.rep")
: new OrderManager(new[] { new ReplayOrderSource(Replay) }); : new OrderManager(new[] { new ReplayOrderSource(Replay) });
PlaySound("intro.aud", false); PlaySound("intro.aud", false);
} }
static void LoadMapBuildings( IniFile mapfile ) static void LoadMapBuildings( IniFile mapfile )
{ {
foreach( var s in mapfile.GetSection( "STRUCTURES", true ) ) foreach( var s in mapfile.GetSection( "STRUCTURES", true ) )
{ {
//num=owner,type,health,location,facing,trigger,unknown,shouldRepair //num=owner,type,health,location,facing,trigger,unknown,shouldRepair
var parts = s.Value.ToLowerInvariant().Split( ',' ); var parts = s.Value.ToLowerInvariant().Split( ',' );
var loc = int.Parse( parts[ 3 ] ); var loc = int.Parse( parts[ 3 ] );
world.Add( new Actor( parts[ 1 ], new int2( loc % 128, loc / 128 ), players[ 0 ] ) ); world.Add( new Actor( parts[ 1 ], new int2( loc % 128, loc / 128 ), players[ 0 ] ) );
} }
} }
static void LoadMapUnits( IniFile mapfile ) static void LoadMapUnits( IniFile mapfile )
{ {
foreach( var s in mapfile.GetSection( "UNITS", true ) ) foreach( var s in mapfile.GetSection( "UNITS", true ) )
{ {
//num=owner,type,health,location,facing,action,trigger //num=owner,type,health,location,facing,action,trigger
var parts = s.Value.ToLowerInvariant().Split( ',' ); var parts = s.Value.ToLowerInvariant().Split( ',' );
var loc = int.Parse( parts[ 3 ] ); var loc = int.Parse( parts[ 3 ] );
world.Add( new Actor( parts[ 1 ], new int2( loc % 128, loc / 128 ), players[ 0 ] ) ); world.Add( new Actor( parts[ 1 ], new int2( loc % 128, loc / 128 ), players[ 0 ] ) );
} }
} }
static Cache<string, ISoundSource> sounds; static Cache<string, ISoundSource> sounds;
static ISoundSource LoadSound(string filename) static ISoundSource LoadSound(string filename)
{ {
var data = AudLoader.LoadSound(FileSystem.Open(filename)); var data = AudLoader.LoadSound(FileSystem.Open(filename));
return soundEngine.AddSoundSourceFromPCMData(data, filename, return soundEngine.AddSoundSourceFromPCMData(data, filename,
new AudioFormat() new AudioFormat()
{ {
ChannelCount = 1, ChannelCount = 1,
FrameCount = data.Length / 2, FrameCount = data.Length / 2,
Format = SampleFormat.Signed16Bit, Format = SampleFormat.Signed16Bit,
SampleRate = 22050 SampleRate = 22050
}); });
} }
public static void PlaySound(string name, bool loop) public static void PlaySound(string name, bool loop)
{ {
var sound = sounds[name]; var sound = sounds[name];
// todo: positioning // todo: positioning
soundEngine.Play2D(sound, loop, false, false); soundEngine.Play2D(sound, loop, false, false);
} }
public static void Tick() public static void Tick()
{ {
world.Update(); world.Update();
UnitInfluence.Tick(); UnitInfluence.Tick();
foreach( var player in players.Values )
viewport.DrawRegions(); player.Tick();
orderManager.Tick(); viewport.DrawRegions();
}
orderManager.Tick();
public static bool IsCellBuildable(int2 a, UnitMovementType umt) }
{
if (BuildingInfluence.GetBuildingAt(a) != null) return false; public static bool IsCellBuildable(int2 a, UnitMovementType umt)
if (UnitInfluence.GetUnitAt(a) != null) return false; {
if (BuildingInfluence.GetBuildingAt(a) != null) return false;
return map.IsInMap(a.X, a.Y) && if (UnitInfluence.GetUnitAt(a) != null) return false;
TerrainCosts.Cost(umt,
worldRenderer.terrainRenderer.tileSet.GetWalkability( map.MapTiles[ a.X, a.Y ] ) ) < double.PositiveInfinity; return map.IsInMap(a.X, a.Y) &&
} TerrainCosts.Cost(umt,
worldRenderer.terrainRenderer.tileSet.GetWalkability( map.MapTiles[ a.X, a.Y ] ) ) < double.PositiveInfinity;
static IEnumerable<Actor> FindUnits(float2 a, float2 b) }
{
var min = float2.Min(a, b); static IEnumerable<Actor> FindUnits(float2 a, float2 b)
var max = float2.Max(a, b); {
var min = float2.Min(a, b);
var rect = new RectangleF(min.X, min.Y, max.X - min.X, max.Y - min.Y); var max = float2.Max(a, b);
return world.Actors var rect = new RectangleF(min.X, min.Y, max.X - min.X, max.Y - min.Y);
.Where(x => x.Bounds.IntersectsWith(rect));
} return world.Actors
.Where(x => x.Bounds.IntersectsWith(rect));
public static IEnumerable<Actor> FindUnitsInCircle(float2 a, float r) }
{
return FindUnits(a - new float2(r, r), a + new float2(r, r)) public static IEnumerable<Actor> FindUnitsInCircle(float2 a, float r)
.Where(x => (x.CenterLocation - a).LengthSquared < r * r); {
} return FindUnits(a - new float2(r, r), a + new float2(r, r))
.Where(x => (x.CenterLocation - a).LengthSquared < r * r);
public static IEnumerable<int2> FindTilesInCircle( int2 a, int r ) }
{
var min = a - new int2(r, r); public static IEnumerable<int2> FindTilesInCircle( int2 a, int r )
var max = a + new int2(r, r); {
if( min.X < 0 ) min.X = 0; var min = a - new int2(r, r);
if( min.Y < 0 ) min.Y = 0; var max = a + new int2(r, r);
if( max.X > 127 ) max.X = 127; if( min.X < 0 ) min.X = 0;
if( max.Y > 127 ) max.Y = 127; if( min.Y < 0 ) min.Y = 0;
if( max.X > 127 ) max.X = 127;
for (var j = min.Y; j <= max.Y; j++) if( max.Y > 127 ) max.Y = 127;
for (var i = min.X; i <= max.X; i++)
if (r * r >= (new int2(i, j) - a).LengthSquared) for (var j = min.Y; j <= max.Y; j++)
yield return new int2(i, j); for (var i = min.X; i <= max.X; i++)
} if (r * r >= (new int2(i, j) - a).LengthSquared)
yield return new int2(i, j);
public static IEnumerable<Actor> SelectUnitsInBox(float2 a, float2 b) }
{
return FindUnits(a, b).Where(x => x.Owner == LocalPlayer && x.traits.Contains<Traits.Mobile>()); public static IEnumerable<Actor> SelectUnitsInBox(float2 a, float2 b)
} {
return FindUnits(a, b).Where(x => x.Owner == LocalPlayer && x.traits.Contains<Traits.Mobile>());
public static IEnumerable<Actor> SelectUnitOrBuilding(float2 a) }
{
var q = FindUnits(a, a); public static IEnumerable<Actor> SelectUnitOrBuilding(float2 a)
return q.Where(x => x.traits.Contains<Traits.Mobile>()).Concat(q).Take(1); {
} var q = FindUnits(a, a);
return q.Where(x => x.traits.Contains<Traits.Mobile>()).Concat(q).Take(1);
public static int GetDistanceToBase(int2 b, Player p) }
{
var building = BuildingInfluence.GetNearestBuilding(b); public static int GetDistanceToBase(int2 b, Player p)
if (building == null || building.Owner != p) {
return int.MaxValue; var building = BuildingInfluence.GetNearestBuilding(b);
if (building == null || building.Owner != p)
return BuildingInfluence.GetDistanceToBuilding(b); return int.MaxValue;
}
return BuildingInfluence.GetDistanceToBuilding(b);
public static Random SharedRandom = new Random(); /* for things that require sync */ }
public static Random CosmeticRandom = new Random(); /* for things that are just fluff */
public static Random SharedRandom = new Random(); /* for things that require sync */
public static readonly Pair<VoicePool, VoicePool> SovietVoices = public static Random CosmeticRandom = new Random(); /* for things that are just fluff */
Pair.New(
new VoicePool("ackno", "affirm1", "noprob", "overout", "ritaway", "roger", "ugotit"), public static readonly Pair<VoicePool, VoicePool> SovietVoices =
new VoicePool("await1", "ready", "report1", "yessir1")); Pair.New(
new VoicePool("ackno", "affirm1", "noprob", "overout", "ritaway", "roger", "ugotit"),
static int2? FindAdjacentTile(Actor a, UnitMovementType umt) new VoicePool("await1", "ready", "report1", "yessir1"));
{
var tiles = Footprint.Tiles(a); static int2? FindAdjacentTile(Actor a, UnitMovementType umt)
var min = tiles.Aggregate(int2.Min) - new int2(1, 1); {
var max = tiles.Aggregate(int2.Max) + new int2(1, 1); var tiles = Footprint.Tiles(a);
var min = tiles.Aggregate(int2.Min) - new int2(1, 1);
for (var j = min.Y; j <= max.Y; j++) var max = tiles.Aggregate(int2.Max) + new int2(1, 1);
for (var i = min.X; i <= max.X; i++)
if (IsCellBuildable(new int2(i, j), umt)) for (var j = min.Y; j <= max.Y; j++)
return new int2(i, j); for (var i = min.X; i <= max.X; i++)
if (IsCellBuildable(new int2(i, j), umt))
return null; return new int2(i, j);
}
return null;
public static void BuildUnit(Player player, string name) }
{
var producerTypes = Rules.UnitInfo[name].BuiltAt; public static void BuildUnit(Player player, string name)
var producer = world.Actors {
.FirstOrDefault(a => a.unitInfo != null var producerTypes = Rules.UnitInfo[name].BuiltAt;
&& producerTypes.Contains(a.unitInfo.Name) && a.Owner == player); var producer = world.Actors
.FirstOrDefault(a => a.unitInfo != null
if (producer == null) && producerTypes.Contains(a.unitInfo.Name) && a.Owner == player);
throw new InvalidOperationException("BuildUnit without suitable production structure!");
if (producer == null)
Actor unit; throw new InvalidOperationException("BuildUnit without suitable production structure!");
if (producerTypes.Contains("spen") || producerTypes.Contains("syrd")) Actor unit;
{
var space = FindAdjacentTile(producer, Rules.UnitInfo[name].WaterBound ? if (producerTypes.Contains("spen") || producerTypes.Contains("syrd"))
UnitMovementType.Float : UnitMovementType.Wheel ); /* hackety hack */ {
var space = FindAdjacentTile(producer, Rules.UnitInfo[name].WaterBound ?
if (space == null) UnitMovementType.Float : UnitMovementType.Wheel ); /* hackety hack */
throw new NotImplementedException("Nowhere to place this unit.");
if (space == null)
unit = new Actor(name, space.Value, player); throw new NotImplementedException("Nowhere to place this unit.");
var mobile = unit.traits.Get<Mobile>();
mobile.facing = SharedRandom.Next(256); unit = new Actor(name, space.Value, player);
} var mobile = unit.traits.Get<Mobile>();
else mobile.facing = SharedRandom.Next(256);
{ }
unit = new Actor(name, (1 / 24f * producer.CenterLocation).ToInt2(), player); else
var mobile = unit.traits.Get<Mobile>(); {
mobile.facing = 128; unit = new Actor(name, (1 / 24f * producer.CenterLocation).ToInt2(), player);
mobile.QueueActivity(new Mobile.MoveTo(unit.Location + new int2(0, 3))); var mobile = unit.traits.Get<Mobile>();
} mobile.facing = 128;
mobile.QueueActivity(new Mobile.MoveTo(unit.Location + new int2(0, 3)));
world.Add(unit); }
if (producer.traits.Contains<RenderWarFactory>()) world.Add(unit);
producer.traits.Get<RenderWarFactory>().EjectUnit();
} if (producer.traits.Contains<RenderWarFactory>())
} producer.traits.Get<RenderWarFactory>().EjectUnit();
} }
}
}

View File

@@ -21,11 +21,11 @@ namespace OpenRa.Game.Graphics
start = src.Start + int.Parse(e.GetAttribute("start")); start = src.Start + int.Parse(e.GetAttribute("start"));
if (e.GetAttribute("length") == "*" || e.GetAttribute("end") == "*") if (e.GetAttribute("length") == "*" || e.GetAttribute("end") == "*")
length = src.End - start; length = src.End - start + 1;
else if (e.HasAttribute("length")) else if (e.HasAttribute("length"))
length = int.Parse(e.GetAttribute("length")); length = int.Parse(e.GetAttribute("length"));
else if (e.HasAttribute("end")) else if (e.HasAttribute("end"))
length = int.Parse(e.GetAttribute("end")) - start; length = int.Parse(e.GetAttribute("end")) - int.Parse(e.GetAttribute("start"));
else else
length = 1; length = 1;
} }

View File

@@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Linq; using System.Linq;
using OpenRa.Game.Traits; using OpenRa.Game.Traits;
using System.IO; using System.IO;
@@ -43,7 +43,7 @@ namespace OpenRa.Game
var ret = new MemoryStream(); var ret = new MemoryStream();
var w = new BinaryWriter(ret); var w = new BinaryWriter(ret);
w.Write((uint)Player.Palette | 0x80000000u); w.Write((uint)Player.Palette | 0x80000000u);
w.Write((byte)0xFF); // w.Write((byte)0xFF);
w.Write(OrderString); w.Write(OrderString);
w.Write(Subject == null ? 0xFFFFFFFF : Subject.ActorID); w.Write(Subject == null ? 0xFFFFFFFF : Subject.ActorID);
w.Write(TargetActor == null ? 0xFFFFFFFF : TargetActor.ActorID); w.Write(TargetActor == null ? 0xFFFFFFFF : TargetActor.ActorID);
@@ -112,4 +112,4 @@ namespace OpenRa.Game
return new Order(subject, "BuildUnit", null, null, int2.Zero, unitName, Cursor.Default); return new Order(subject, "BuildUnit", null, null, int2.Zero, unitName, Cursor.Default);
} }
} }
} }

View File

@@ -1,3 +1,5 @@
using System;
using System.Collections.Generic;
namespace OpenRa.Game namespace OpenRa.Game
{ {
@@ -19,5 +21,87 @@ namespace OpenRa.Game
{ {
return 0.5f; /* todo: work this out the same way as RA */ return 0.5f; /* todo: work this out the same way as RA */
} }
public void GiveCash( int num )
{
// TODO: increase cash
}
public bool TakeCash( int num )
{
// TODO: decrease cash.
// returns: if enough cash was available, true
return true;
}
public void Tick()
{
foreach( var p in production )
{
if( p.Value != null )
p.Value.Tick( this );
}
}
// Key: Production category. Categories are: building, infantry, vehicle, boat, plane (and one per super, if they're done in here)
readonly Dictionary<string, ProductionItem> production = new Dictionary<string, ProductionItem>();
public void ProductionInit( string category )
{
production.Add( category, null );
}
public ProductionItem Producing( string category )
{
return production[ category ];
}
public void CancelProduction( string category )
{
var item = production[ category ];
if( item == null ) return;
GiveCash( item.TotalCost - item.RemainingCost ); // refund what's been paid so far.
production[ category ] = null;
}
public void BeginProduction( string group, ProductionItem item )
{
if( production[ group ] != null ) return;
production[ group ] = item;
}
}
class ProductionItem
{
public readonly string Item;
public readonly int TotalTime;
public readonly int TotalCost;
public int RemainingTime { get; private set; }
public int RemainingCost { get; private set; }
public bool Paused = false, Done = false;
public ProductionItem( string item, int time, int cost )
{
Item = item;
RemainingTime = TotalTime = time;
RemainingCost = TotalCost = cost;
}
public void Tick( Player player )
{
if( Paused || Done ) return;
var costThisFrame = RemainingCost / RemainingTime;
if( costThisFrame == 0 && !player.TakeCash( costThisFrame ) ) return;
RemainingCost -= costThisFrame;
RemainingTime -= 1;
if( RemainingTime > 0 ) return;
// item finished; do whatever needs done.
Done = true;
}
} }
} }

View File

@@ -1,180 +1,189 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using OpenRa.FileFormats; using OpenRa.FileFormats;
using OpenRa.Game.Graphics; using OpenRa.Game.Graphics;
using OpenRa.TechTree; using OpenRa.TechTree;
using System.Linq; using System.Linq;
namespace OpenRa.Game namespace OpenRa.Game
{ {
using GRegion = OpenRa.Game.Graphics.Region; using GRegion = OpenRa.Game.Graphics.Region;
class Sidebar class Sidebar
{ {
TechTree.TechTree techTree; TechTree.TechTree techTree;
SpriteRenderer spriteRenderer, clockRenderer; SpriteRenderer spriteRenderer, clockRenderer;
Sprite blank; Sprite blank;
readonly GRegion region; readonly GRegion region;
public GRegion Region { get { return region; } } public GRegion Region { get { return region; } }
public float Width { get { return spriteWidth * 2; } } public float Width { get { return spriteWidth * 2; } }
Dictionary<string, Sprite> sprites = new Dictionary<string,Sprite>(); Dictionary<string, Sprite> sprites = new Dictionary<string,Sprite>();
const int spriteWidth = 64, spriteHeight = 48; const int spriteWidth = 64, spriteHeight = 48;
static string[] groups = new string[] { "building", "vehicle", "boat", "infantry", "plane" }; static string[] groups = new string[] { "building", "vehicle", "boat", "infantry", "plane" };
Dictionary<string, string> itemGroups = new Dictionary<string,string>(); //item->group Dictionary<string, string> itemGroups = new Dictionary<string,string>(); //item->group
Dictionary<string, Animation> clockAnimations = new Dictionary<string,Animation>(); //group->clockAnimation Dictionary<string, Animation> clockAnimations = new Dictionary<string,Animation>(); //group->clockAnimation
Dictionary<string, SidebarItem> selectedItems = new Dictionary<string,SidebarItem>(); //group->selectedItem
List<SidebarItem> items = new List<SidebarItem>();
List<SidebarItem> items = new List<SidebarItem>();
public Sidebar( Renderer renderer )
public Sidebar( Renderer renderer )
{
this.techTree = Game.LocalPlayer.TechTree;
this.techTree.BuildableItemsChanged += PopulateItemList;
region = GRegion.Create(Game.viewport, DockStyle.Right, 128, Paint, MouseHandler);
Game.viewport.AddRegion( region );
spriteRenderer = new SpriteRenderer(renderer, false);
clockRenderer = new SpriteRenderer(renderer, true);
LoadSprites( "BuildingTypes", "building" );
LoadSprites( "VehicleTypes", "vehicle" );
LoadSprites( "InfantryTypes", "infantry" );
LoadSprites( "ShipTypes", "boat" );
LoadSprites( "PlaneTypes", "plane" );
foreach (string s in groups)
{
clockAnimations.Add(s, new Animation("clock"));
clockAnimations[s].PlayRepeating("idle");
selectedItems.Add(s, null);
}
blank = SheetBuilder.Add(new Size((int)spriteWidth, (int)spriteHeight), 16);
}
public void Build(SidebarItem item)
{ {
if (item == null) return; this.techTree = Game.LocalPlayer.TechTree;
this.techTree.BuildableItemsChanged += PopulateItemList;
region = GRegion.Create(Game.viewport, DockStyle.Right, 128, Paint, MouseHandler);
Game.viewport.AddRegion( region );
spriteRenderer = new SpriteRenderer(renderer, false);
clockRenderer = new SpriteRenderer(renderer, true);
LoadSprites( "BuildingTypes", "building" );
LoadSprites( "VehicleTypes", "vehicle" );
LoadSprites( "InfantryTypes", "infantry" );
LoadSprites( "ShipTypes", "boat" );
LoadSprites( "PlaneTypes", "plane" );
foreach (string group in groups)
{
Game.LocalPlayer.ProductionInit( group );
clockAnimations.Add( group, new Animation( "clock" ) );
clockAnimations[ group ].PlayFetchIndex( "idle", ClockAnimFrame( group ) );
}
blank = SheetBuilder.Add(new Size((int)spriteWidth, (int)spriteHeight), 16);
}
const int NumClockFrames = 54;
Func<int> ClockAnimFrame( string group )
{
return () =>
{
var producing = Game.LocalPlayer.Producing( group );
if( producing == null ) return 0;
return ( producing.TotalTime - producing.RemainingTime ) * NumClockFrames / producing.TotalTime;
};
}
public void Build(SidebarItem item)
{
if (item == null) return;
if (item.techTreeItem.IsStructure) if (item.techTreeItem.IsStructure)
Game.controller.orderGenerator = new PlaceBuilding(Game.LocalPlayer, Game.controller.orderGenerator = new PlaceBuilding(Game.LocalPlayer,
item.techTreeItem.tag.ToLowerInvariant()); item.techTreeItem.tag.ToLowerInvariant());
else else
Game.controller.AddOrder(Order.BuildUnit(Game.LocalPlayer, item.techTreeItem.tag.ToLowerInvariant())); Game.controller.AddOrder(Order.BuildUnit(Game.LocalPlayer, item.techTreeItem.tag.ToLowerInvariant()));
} }
void LoadSprites( string category, string group ) void LoadSprites( string category, string group )
{ {
foreach( var u in Rules.AllRules.GetSection( category ) ) foreach( var u in Rules.AllRules.GetSection( category ) )
{ {
var unit = Rules.UnitInfo[ u.Key ]; var unit = Rules.UnitInfo[ u.Key ];
if( unit.TechLevel != -1 ) if( unit.TechLevel != -1 )
sprites.Add( unit.Name, SpriteSheetBuilder.LoadSprite( unit.Name + "icon", ".shp" ) ); sprites.Add( unit.Name, SpriteSheetBuilder.LoadSprite( unit.Name + "icon", ".shp" ) );
itemGroups.Add( unit.Name, group ); itemGroups.Add( unit.Name, group );
} }
} }
void DrawSprite(Sprite s, ref float2 p) void DrawSprite(Sprite s, ref float2 p)
{ {
spriteRenderer.DrawSprite(s, p, 0); spriteRenderer.DrawSprite(s, p, 0);
p.Y += spriteHeight; p.Y += spriteHeight;
} }
void Fill(float height, float2 p) void Fill(float height, float2 p)
{ {
while (p.Y < height) while (p.Y < height)
DrawSprite(blank, ref p); DrawSprite(blank, ref p);
} }
int buildPos = 0; int buildPos = 0;
int unitPos = 0; int unitPos = 0;
void PopulateItemList() void PopulateItemList()
{ {
buildPos = 0; unitPos = 0; buildPos = 0; unitPos = 0;
items.Clear(); items.Clear();
foreach (Item i in techTree.BuildableItems) foreach (Item i in techTree.BuildableItems)
{ {
Sprite sprite; Sprite sprite;
if (!sprites.TryGetValue(i.tag, out sprite)) continue; if (!sprites.TryGetValue(i.tag, out sprite)) continue;
items.Add(new SidebarItem(sprite, i, i.IsStructure ? buildPos : unitPos)); items.Add(new SidebarItem(sprite, i, i.IsStructure ? buildPos : unitPos));
if (i.IsStructure) if (i.IsStructure)
buildPos += spriteHeight; buildPos += spriteHeight;
else else
unitPos += spriteHeight; unitPos += spriteHeight;
} }
foreach (string g in groups) selectedItems[g] = null; foreach( string g in groups ) Game.LocalPlayer.CancelProduction( g );
} }
void Paint() void Paint()
{ {
foreach (SidebarItem i in items) foreach( SidebarItem i in items )
i.Paint(spriteRenderer, region.Location); {
var group = itemGroups[ i.techTreeItem.tag ];
Fill(region.Size.Y + region.Location.Y, new float2(region.Location.X, buildPos + region.Location.Y)); var producing = Game.LocalPlayer.Producing( group );
Fill(region.Size.Y + region.Location.Y, new float2(region.Location.X + spriteWidth, unitPos + region.Location.Y)); if( producing != null && producing.Item == i.techTreeItem.tag )
{
spriteRenderer.Flush(); clockAnimations[ group ].Tick();
clockRenderer.DrawSprite( clockAnimations[ group ].Image, region.Location.ToFloat2() + i.location, 0 );
foreach (var kvp in selectedItems) }
{ i.Paint( spriteRenderer, region.Location );
if (kvp.Value != null) }
{
clockRenderer.DrawSprite(clockAnimations[kvp.Key].Image, region.Location.ToFloat2() + kvp.Value.location, 0); Fill(region.Size.Y + region.Location.Y, new float2(region.Location.X, buildPos + region.Location.Y));
clockAnimations[kvp.Key].Tick(1); Fill(region.Size.Y + region.Location.Y, new float2(region.Location.X + spriteWidth, unitPos + region.Location.Y));
}
} spriteRenderer.Flush();
clockRenderer.Flush();
clockRenderer.Flush(); }
}
public SidebarItem GetItem(float2 point)
public SidebarItem GetItem(float2 point) {
{ foreach (SidebarItem i in items)
foreach (SidebarItem i in items) if (i.Clicked(point))
if (i.Clicked(point)) return i;
return i;
return null;
return null; }
}
void MouseHandler(MouseInput mi)
void MouseHandler(MouseInput mi) {
{ if (mi.Button == MouseButtons.Left && mi.Event == MouseInputEvent.Down)
if (mi.Button == MouseButtons.Left && mi.Event == MouseInputEvent.Down) {
{ var point = mi.Location.ToFloat2();
var point = mi.Location.ToFloat2(); var item = GetItem(point);
var item = GetItem(point); if (item != null)
if (item != null) {
{ string group = itemGroups[item.techTreeItem.tag];
string group = itemGroups[item.techTreeItem.tag]; if (Game.LocalPlayer.Producing(group) == null)
if (selectedItems[group] == null) {
{ Game.LocalPlayer.BeginProduction( group, new ProductionItem( item.techTreeItem.tag, 25, 0 ) );
selectedItems[group] = item; Build(item);
Build(item); }
} }
} }
} else if( mi.Button == MouseButtons.Right && mi.Event == MouseInputEvent.Down )
else if( mi.Button == MouseButtons.Right && mi.Event == MouseInputEvent.Down ) {
{ var point = mi.Location.ToFloat2();
var point = mi.Location.ToFloat2(); var item = GetItem(point);
var item = GetItem(point); if( item != null )
if( item != null ) {
{ string group = itemGroups[ item.techTreeItem.tag ];
string group = itemGroups[ item.techTreeItem.tag ]; Game.LocalPlayer.CancelProduction( group );
selectedItems[ group ] = null; }
} }
} }
} }
} }
}