Skip to content

Commit

Permalink
Separated resource rendering into another trait
Browse files Browse the repository at this point in the history
  • Loading branch information
teinarss authored and abcdefg30 committed Jan 14, 2020
1 parent 0e93d85 commit f0b69f8
Show file tree
Hide file tree
Showing 16 changed files with 377 additions and 180 deletions.
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Orders/PlaceBuildingOrderGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ IEnumerable<IRenderable> IOrderGenerator.RenderAboveShroud(WorldRenderer wr, Wor
{
var isCloseEnough = buildingInfo.IsCloseEnoughToBase(world, world.LocalPlayer, actorInfo, topLeft);
foreach (var t in buildingInfo.Tiles(topLeft))
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResource(t) == null)));
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResourceType(t) == null)));
}

return preview != null ? preview.Render(wr, topLeft, footprint) : Enumerable.Empty<IRenderable>();
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/Buildings/BuildingUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static bool CanPlaceBuilding(this World world, CPos cell, ActorInfo ai, B

var res = world.WorldActor.TraitOrDefault<ResourceLayer>();
return bi.Tiles(cell).All(
t => world.Map.Contains(t) && (res == null || res.GetResource(t) == null) &&
t => world.Map.Contains(t) && (res == null || res.GetResourceType(t) == null) &&
world.IsCellBuildable(t, ai, bi, toIgnore));
}

Expand Down
4 changes: 2 additions & 2 deletions OpenRA.Mods.Common/Traits/Harvester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public bool CanHarvestCell(Actor self, CPos cell)
if (cell.Layer != 0)
return false;

var resType = resLayer.GetResource(cell);
var resType = resLayer.GetResourceType(cell);
if (resType == null)
return false;

Expand Down Expand Up @@ -395,7 +395,7 @@ public bool CanTarget(Actor self, Target target, List<Actor> othersAtTarget, ref
if (!self.Owner.Shroud.IsExplored(location))
return false;

var res = self.World.WorldActor.Trait<ResourceLayer>().GetRenderedResource(location);
var res = self.World.WorldActor.Trait<ResourceRenderer>().GetRenderedResourceType(location);
var info = self.Info.TraitInfo<HarvesterInfo>();

if (res == null || !info.Resources.Contains(res.Info.Type))
Expand Down
2 changes: 1 addition & 1 deletion OpenRA.Mods.Common/Traits/SeedsResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void Seed(Actor self)
var cell = Util.RandomWalk(self.Location, self.World.SharedRandom)
.Take(info.MaxRange)
.SkipWhile(p => !self.World.Map.Contains(p) ||
(resLayer.GetResource(p) == resourceType && resLayer.IsFull(p)))
(resLayer.GetResourceType(p) == resourceType && resLayer.IsFull(p)))
.Cast<CPos?>().FirstOrDefault();

if (cell != null && resLayer.CanSpawnResourceAt(resourceType, cell.Value))
Expand Down
19 changes: 14 additions & 5 deletions OpenRA.Mods.Common/Traits/World/EditorResourceLayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class EditorResourceLayer : IWorldLoaded, IRenderOverlay, INotifyActorDis
protected readonly Map Map;
protected readonly TileSet Tileset;
protected readonly Dictionary<int, ResourceType> Resources;
protected readonly CellLayer<CellContents> Tiles;
protected readonly CellLayer<EditorCellContents> Tiles;
protected readonly HashSet<CPos> Dirty = new HashSet<CPos>();

readonly Dictionary<PaletteReference, TerrainSpriteLayer> spriteLayers = new Dictionary<PaletteReference, TerrainSpriteLayer>();
Expand All @@ -48,7 +48,7 @@ public EditorResourceLayer(Actor self)
Map = self.World.Map;
Tileset = self.World.Map.Rules.TileSet;

Tiles = new CellLayer<CellContents>(Map);
Tiles = new CellLayer<EditorCellContents>(Map);
Resources = self.TraitsImplementing<ResourceType>()
.ToDictionary(r => r.Info.ResourceType, r => r);

Expand Down Expand Up @@ -98,7 +98,7 @@ public void UpdateCell(CPos cell)
ResourceType type;
if (Resources.TryGetValue(tile.Type, out type))
{
Tiles[uv] = new CellContents
Tiles[uv] = new EditorCellContents
{
Type = type,
Variant = ChooseRandomVariant(type),
Expand All @@ -108,7 +108,7 @@ public void UpdateCell(CPos cell)
}
else
{
Tiles[uv] = CellContents.Empty;
Tiles[uv] = EditorCellContents.Empty;
Map.CustomTerrain[uv] = byte.MaxValue;
}

Expand Down Expand Up @@ -143,7 +143,7 @@ public int ResourceDensityAt(CPos c)
return Math.Max(int2.Lerp(0, type.Info.MaxDensity, adjacent, 9), 1);
}

public virtual CellContents UpdateDirtyTile(CPos c)
public virtual EditorCellContents UpdateDirtyTile(CPos c)
{
var t = Tiles[c];
var type = t.Type;
Expand Down Expand Up @@ -213,4 +213,13 @@ void INotifyActorDisposing.Disposing(Actor self)
disposed = true;
}
}

public struct EditorCellContents
{
public static readonly EditorCellContents Empty = default(EditorCellContents);
public ResourceType Type;
public int Density;
public string Variant;
public Sprite Sprite;
}
}
149 changes: 26 additions & 123 deletions OpenRA.Mods.Common/Traits/World/ResourceLayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,64 +24,38 @@ public class ResourceLayerInfo : ITraitInfo, Requires<ResourceTypeInfo>, Require
public virtual object Create(ActorInitializer init) { return new ResourceLayer(init.Self); }
}

public class ResourceLayer : IRenderOverlay, IWorldLoaded, ITickRender, INotifyActorDisposing
public class ResourceLayer : IWorldLoaded
{
static readonly CellContents EmptyCell = default(CellContents);

readonly World world;
readonly BuildingInfluence buildingInfluence;
readonly HashSet<CPos> dirty = new HashSet<CPos>();
readonly Dictionary<PaletteReference, TerrainSpriteLayer> spriteLayers = new Dictionary<PaletteReference, TerrainSpriteLayer>();

protected readonly CellLayer<CellContents> Content;
protected readonly CellLayer<CellContents> RenderContent;

public bool IsResourceLayerEmpty { get { return resCells < 1; } }

bool disposed;
int resCells;

public event Action<CPos, ResourceType> CellChanged;

public ResourceLayer(Actor self)
{
world = self.World;
buildingInfluence = self.Trait<BuildingInfluence>();

Content = new CellLayer<CellContents>(world.Map);
RenderContent = new CellLayer<CellContents>(world.Map);

RenderContent.CellEntryChanged += UpdateSpriteLayers;
}

void UpdateSpriteLayers(CPos cell)
{
var resource = RenderContent[cell];
foreach (var kv in spriteLayers)
{
// resource.Type is meaningless (and may be null) if resource.Sprite is null
if (resource.Sprite != null && resource.Type.Palette == kv.Key)
kv.Value.Update(cell, resource.Sprite);
else
kv.Value.Update(cell, null);
}
}

void IRenderOverlay.Render(WorldRenderer wr)
{
foreach (var kv in spriteLayers.Values)
kv.Draw(wr.Viewport);
}

int GetAdjacentCellsWith(ResourceType t, CPos cell)
{
var sum = 0;
for (var u = -1; u < 2; u++)
var directions = CVec.Directions;
for (var i = 0; i < directions.Length; i++)
{
for (var v = -1; v < 2; v++)
{
var c = cell + new CVec(u, v);
if (Content.Contains(c) && Content[c].Type == t)
++sum;
}
var c = cell + directions[i];
if (Content.Contains(c) && Content[c].Type == t)
++sum;
}

return sum;
Expand All @@ -92,27 +66,6 @@ public void WorldLoaded(World w, WorldRenderer wr)
var resources = w.WorldActor.TraitsImplementing<ResourceType>()
.ToDictionary(r => r.Info.ResourceType, r => r);

// Build the sprite layer dictionary for rendering resources
// All resources that have the same palette must also share a sheet and blend mode
foreach (var r in resources)
{
var layer = spriteLayers.GetOrAdd(r.Value.Palette, pal =>
{
var first = r.Value.Variants.First().Value.First();
return new TerrainSpriteLayer(w, wr, first.Sheet, first.BlendMode, pal, wr.World.Type != WorldType.Editor);
});

// Validate that sprites are compatible with this layer
var sheet = layer.Sheet;
if (r.Value.Variants.Any(kv => kv.Value.Any(s => s.Sheet != sheet)))
throw new InvalidDataException("Resource sprites span multiple sheets. Try loading their sequences earlier.");

var blendMode = layer.BlendMode;
if (r.Value.Variants.Any(kv => kv.Value.Any(s => s.BlendMode != blendMode)))
throw new InvalidDataException("Resource sprites specify different blend modes. "
+ "Try using different palettes for resource types that use different blend modes.");
}

foreach (var cell in w.Map.AllCells)
{
ResourceType t;
Expand All @@ -127,61 +80,21 @@ public void WorldLoaded(World w, WorldRenderer wr)

foreach (var cell in w.Map.AllCells)
{
var type = Content[cell].Type;
var type = GetResourceType(cell);
if (type != null)
{
// Set initial density based on the number of neighboring resources
// Adjacent includes the current cell, so is always >= 1
var adjacent = GetAdjacentCellsWith(type, cell);
var density = int2.Lerp(0, type.Info.MaxDensity, adjacent, 9);
var temp = Content[cell];
var temp = GetResource(cell);
temp.Density = Math.Max(density, 1);

// Initialize the RenderContent with the initial map state
// because the shroud may not be enabled.
RenderContent[cell] = Content[cell] = temp;
UpdateRenderedSprite(cell);
Content[cell] = temp;
}
}
}

protected virtual void UpdateRenderedSprite(CPos cell)
{
var t = RenderContent[cell];
if (t.Density > 0)
{
var sprites = t.Type.Variants[t.Variant];
var frame = int2.Lerp(0, sprites.Length - 1, t.Density, t.Type.Info.MaxDensity);
t.Sprite = sprites[frame];
}
else
t.Sprite = null;

RenderContent[cell] = t;
}

protected virtual string ChooseRandomVariant(ResourceType t)
{
return t.Variants.Keys.Random(Game.CosmeticRandom);
}

void ITickRender.TickRender(WorldRenderer wr, Actor self)
{
var remove = new List<CPos>();
foreach (var c in dirty)
{
if (!self.World.FogObscures(c))
{
RenderContent[c] = Content[c];
UpdateRenderedSprite(c);
remove.Add(c);
}
}

foreach (var r in remove)
dirty.Remove(r);
}

public bool AllowResourceAt(ResourceType rt, CPos cell)
{
if (!world.Map.Contains(cell))
Expand Down Expand Up @@ -212,7 +125,7 @@ public bool CanSpawnResourceAt(ResourceType newResourceType, CPos cell)
if (!world.Map.Contains(cell))
return false;

var currentResourceType = GetResource(cell);
var currentResourceType = GetResourceType(cell);
return (currentResourceType == newResourceType && !IsFull(cell))
|| (currentResourceType == null && AllowResourceAt(newResourceType, cell));
}
Expand All @@ -224,8 +137,7 @@ CellContents CreateResourceCell(ResourceType t, CPos cell)

return new CellContents
{
Type = t,
Variant = ChooseRandomVariant(t),
Type = t
};
}

Expand All @@ -241,12 +153,14 @@ public void AddResource(ResourceType t, CPos p, int n)
cell.Density = Math.Min(cell.Type.Info.MaxDensity, cell.Density + n);
Content[p] = cell;

dirty.Add(p);
if (CellChanged != null)
CellChanged(p, cell.Type);
}

public bool IsFull(CPos cell)
{
return Content[cell].Density == Content[cell].Type.Info.MaxDensity;
var cellContents = Content[cell];
return cellContents.Density == cellContents.Type.Info.MaxDensity;
}

public ResourceType Harvest(CPos cell)
Expand All @@ -264,15 +178,17 @@ public ResourceType Harvest(CPos cell)
else
Content[cell] = c;

dirty.Add(cell);
if (CellChanged != null)
CellChanged(cell, c.Type);

return c.Type;
}

public void Destroy(CPos cell)
{
// Don't break other users of CustomTerrain if there are no resources
if (Content[cell].Type == null)
var c = Content[cell];
if (c.Type == null)
return;

--resCells;
Expand All @@ -281,11 +197,13 @@ public void Destroy(CPos cell)
Content[cell] = EmptyCell;
world.Map.CustomTerrain[cell] = byte.MaxValue;

dirty.Add(cell);
if (CellChanged != null)
CellChanged(cell, c.Type);
}

public ResourceType GetResource(CPos cell) { return Content[cell].Type; }
public ResourceType GetRenderedResource(CPos cell) { return RenderContent[cell].Type; }
public CellContents GetResource(CPos cell) { return Content[cell]; }
public ResourceType GetResourceType(CPos cell) { return Content[cell].Type; }

public int GetResourceDensity(CPos cell) { return Content[cell].Density; }
public int GetMaxResourceDensity(CPos cell)
{
Expand All @@ -295,26 +213,11 @@ public int GetMaxResourceDensity(CPos cell)
return Content[cell].Type.Info.MaxDensity;
}

void INotifyActorDisposing.Disposing(Actor self)
{
if (disposed)
return;

foreach (var kv in spriteLayers.Values)
kv.Dispose();

RenderContent.CellEntryChanged -= UpdateSpriteLayers;

disposed = true;
}

public struct CellContents
{
public static readonly CellContents Empty = default(CellContents);
public ResourceType Type;
public int Density;
public string Variant;
public Sprite Sprite;
}
}
}
Loading

0 comments on commit f0b69f8

Please sign in to comment.