Skip to content

Commit

Permalink
Adds a simple parallel processor
Browse files Browse the repository at this point in the history
Adds a simple ParallelProcessor EntityProcessor which, on Update, processes every registered IParallelComponent in parallel using the Dispatcher.
Also includes a before and after update hook to allow for any sequential processing that might want to be performed manually before or afterwards.
  • Loading branch information
ItsAnJonth committed Feb 17, 2024
1 parent 7717303 commit fa78e5a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

namespace Stride.CommunityToolkit.Engine.EntityProcessors {

/// <summary>
/// Interface for use on components handled by ParallelProcessors.
/// </summary>
public interface IParallelComponent {

/// <summary>
/// Called once per entity processor update, for each relevant component, in arbitrary order.
/// Will be parallelised, so beware of thread safety.
/// </summary>
public void UpdateInParallel();

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Stride.Core.Annotations;
using Stride.Core.Threading;
using Stride.Engine;
using Stride.Games;

namespace Stride.CommunityToolkit.Engine.EntityProcessors {

/// <summary>
/// An entity processor where component and data are the same, and easy
/// parallelisation of operations is supported via the Dispatcher.
/// </summary>
/// <typeparam name="TComponent"></typeparam>
public abstract class ParallelProcessor<TComponent> : EntityProcessor<TComponent> where TComponent : EntityComponent, IParallelComponent
{

/* Keep track of all components in a list as we need to get them by index */
private List<TComponent> componentList = new List<TComponent>();

public override void Update(GameTime time)
{

/* Allow the entity processor implementation to hook into things *before* the parallel processing... */
BeforeUpdate();

/* Dispatch UpdateInParallel across every ComponentData */
Dispatcher.For(0, componentList.Count, i =>
{
componentList[i].UpdateInParallel();
});

/* ... and after */
AfterUpdate();

}

/// <summary>
/// Invoked before the component's UpdateInParallel() method. Should contain any non-thread-safe initialisation.
/// </summary>
abstract protected void BeforeUpdate();

/// <summary>
/// Invoked after the component's UpdateInParallel() method. Should contain any non-thread-safe post-processing.
/// </summary>
abstract protected void AfterUpdate();

protected override void OnEntityComponentAdding(Entity entity, [NotNull] TComponent component, [NotNull] TComponent data)
{
componentList.Add(component);
}

protected override void OnEntityComponentRemoved(Entity entity, [NotNull] TComponent component, [NotNull] TComponent data)
{
componentList.Remove(component);
}

}

}

0 comments on commit fa78e5a

Please sign in to comment.