Pattern to share an entity lookup, for spatial partitioning

Hello

I have been struggling to try find a good pattern to solve a data layout problem in ECS. There is probably a more obvious way to achieve what I am trying to accomplish.

Ultimately I am creating a spatial partitioning layer for my entities so I can avoid n^2 lookup times when checking against other entities. For say collisions and other systems that may need it.

My strategy is as follows:

On initialisation an entity will be created for every grid cell, each would have a GridCellComponent and a DynamicBuffer to contain the entities that are currently active within that grid cell. We can use an aspect for this and a GridCellCalculationSystem will introduce each entity into the respective GridCell.

    public readonly partial struct GridCellAspect : IAspect
    {
        public readonly Entity Entity;
        public readonly RefRW<GridCellComponent> GridCell;
        public readonly DynamicBuffer<GridCellEntity> GridCellEntities;
    }

Now any other system can query using that aspect to get a list of entities in any grid cell. Great!

But lets say we want to speed things up and only search adjacent cells to that GridCell. We currently have an array of GridCellComponents and their GridCellEntities, but its unsorted and not an efficient lookup.

So, we could probably introduce some form of lookup-table to avoid having to search unsorted. So my idea at this stage was to generate an entity lookup - we can use a provided container NativeParallelMultiHashMap and jobify this process.

Now - because I do not like repeating myself this particular lookup as far as I understand it cannot easily be shared to other systems. Since it is not of a fixed size, we cannot use NativeParallelMultiHashMap in a component - and this seems a little overkill. I considered sharing this lookup to other systems using some kind of unsafe SystemHandle but I do not want to go down this road.

I am fairly new to dots ECS so there is probably an obvious pattern I am missing here - can anyone help? Am I overcomplicating something?

Many thanks

How is this problem different from the boids sample or the spatial database in the galaxy sample?

It might not be! I’ll check them out - thank you

@DreamingImLatios I wanted to thank you for making me aware of the following:

I was very close to the solution but the part I was missing was the pattern of storing two DynamicBuffers and using one of those buffers as a lookup to the second - and storing the database contiguously like this.

Thank you again

1 Like