This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride/Entities/LinkEntitySequence.cs
D. Moonfire 9e93eb6ce6 refactor!: fixed missed namespaces
- reformatted code and cleaned up references
2023-01-14 18:19:42 -06:00

71 lines
2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using MfGames.Gallium;
namespace MfGames.Nitride.Entities;
/// <summary>
/// Links a series of entities together in some manner. This assumes that
/// the entities coming into the operation are already ordered.
/// </summary>
[WithProperties]
public partial class LinkEntitySequence : OperationBase, IResolvingOperation
{
private readonly IValidator<LinkEntitySequence> validator;
public LinkEntitySequence(IValidator<LinkEntitySequence> validator)
{
this.validator = validator;
this.CreateSequenceIndex = (
list,
index) => new EntitySequence(list, index);
this.AddSequenceIndex = (
entity,
sequence) => entity.Add(sequence);
}
/// <summary>
/// Gets or sets a callback to add a sequence into a given entity.
/// </summary>
public Func<Entity, EntitySequence, Entity> AddSequenceIndex { get; set; }
/// <summary>
/// Gets or sets the function used to create the sequence index.
/// </summary>
public Func<IReadOnlyList<Entity>, int, EntitySequence> CreateSequenceIndex
{
get;
set;
}
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
// Make sure everything is good.
this.validator.ValidateAndThrow(this);
// We pull all the entities into a list so we can walk through them
// more than once along with index access. We also don't reorder the
// list since we assumed it has been ordered already.
var list = input.ToList();
// Go through the list and assign each entity in order with a unique
// copy of the sequence.
for (int i = 0; i < list.Count; i++)
{
Entity entity = list[i];
EntitySequence index = this.CreateSequenceIndex(
list.AsReadOnly(),
i);
yield return this.AddSequenceIndex(entity, index);
}
}
}