Skip to content

Commit

Permalink
perf: Optimize GetComponent<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
thiagomvas committed May 29, 2024
1 parent ca865cc commit 48ae99f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 13 deletions.
38 changes: 30 additions & 8 deletions Basalt/Common/Entities/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ public class Entity
[JsonIgnore]
public Rigidbody? Rigidbody;

[JsonIgnore]
public Collider? Collider;

[JsonIgnore]
public Entity? Parent { get; private set; }

Expand Down Expand Up @@ -176,15 +179,25 @@ public void AddComponent(Component component)
return;

components.Add(component);
if (Rigidbody == null && component is Rigidbody rb)
switch (component)
{
Rigidbody = rb;
}
case Rigidbody rb when Rigidbody == null:
Rigidbody = rb;
break;

else if (component is Transform t)
{
Transform = t;
case Transform t:
Transform = t;
break;

case Collider c when Collider == null:
Collider = c;
break;

default:
// Handle other cases if necessary
break;
}

}

private void ForceAddComponent(Component component)
Expand Down Expand Up @@ -230,16 +243,25 @@ public void RemoveComponent(Component component)
/// <returns>The first instance of a component of type <typeparamref name="T"/></returns>
public T? GetComponent<T>() where T : Component
{
if (typeof(T) == typeof(Transform))
return Transform as T;
if (typeof(T) == typeof(Rigidbody))
return Rigidbody as T;
if (typeof(T) == typeof(Collider))
return Collider as T;

foreach (var component in components)
{
if (component is T)
if (component is T match)
{
return (T)component;
return match;
}
}

return null;
}


/// <summary>
/// Gets all components of the entity.
/// </summary>
Expand Down
10 changes: 5 additions & 5 deletions Basalt/Common/Physics/PhysicsEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,23 +92,23 @@ public void Simulate()

Parallel.ForEach(chunking.GetEntitiesChunked(), (chunk) =>
{

for (int i = 0; i < chunk.Count; i++)
if(chunk == null || chunk.Count == 0) return;
Parallel.For(0, chunk.Count, (i) =>
{
for (int j = i + 1; j < chunk.Count; j++)
{
var entityA = chunk[i];
var entityB = chunk[j];

var colliderA = entityA.GetComponent<Collider>();
var colliderB = entityB.GetComponent<Collider>();
var colliderA = entityA.Collider;
var colliderB = entityB.Collider;

if (colliderA != null && colliderB != null)
{
CollisionHandler.Handle(colliderA, colliderB);
}
}
}
});
});

elapsedTime = DateTimeOffset.Now.ToUnixTimeMilliseconds() - startTime;
Expand Down

0 comments on commit 48ae99f

Please sign in to comment.