Megafunk / MassSample

My understanding of Unreal Engine 5's experimental ECS plugin with a small sample project.
MIT License
681 stars 112 forks source link

About the condition `OptionalFragmentList.Num() > 0` inside ForEachEntityChunk #34

Closed liusida closed 2 years ago

liusida commented 2 years ago

First, I want to thank you for this great demo. I'm learning a lot from it.

When I was reading README.md, I noticed there's a code snippet like this:

MyQuery.ForEachEntityChunk(EntitySubsystem, Context, [](FMassExecutionContext& Context)
{
    const auto OptionalFragmentList = Context.GetMutableFragmentView<FMyOptionalFragment>();
    const auto HorseFragmentList = Context.GetMutableFragmentView<FHorseFragment>();    
    const auto SheepFragmentList = Context.GetMutableFragmentView<FSheepFragment>();
    for (int32 i = 0; i < Context.GetNumEntities(); ++i)
    {
        // An optional fragment array is present in our current chunk if the OptionalFragmentList isn't empty
        if(OptionalFragmentList.Num() > 0)
        {
            // Now that we know it is safe to do so, we can compute
            OptionalFragmentList[i].DoOptionalStuff();
        }

        // Same with fragments marked with Any
        if(HorseFragmentList.Num() > 0)
        {
            HorseFragmentList[i].DoHorseStuff();
        }
        if(SheepFragmentList.Num() > 0)
        {
            SheepFragmentList[i].DoSheepStuff();
        }       
    }
});

I was thinking, say, if we have a chunk of 5 entities, and 3 of them has the optional fragment. When we loop i from 0 to 5-1, we will have time when i==4 when we face the if condition if(OptionalFragmentList.Num() > 0), and since we have 3 entities with optional fragment, this will be 3>0, and we will execute OptionalFragmentList[i].DoOptionalStuff();. But OptionalFragmentList only has 3 members, so OptionalFragmentList [4] would cause error.

Megafunk commented 2 years ago

Each chunk we iterate on can only be one kind of archetype, so checking for the presence at all like this is okay. I suppose it would be smarter to check before we enter the loop instead of every entity. :P

liusida commented 2 years ago

Each chunk we iterate on can only be one kind of archetype

Aha! I didn't know this! Thanks for the answer!