From 48ae99faadc15130127a7fdec289186c922f9560 Mon Sep 17 00:00:00 2001 From: Thiago Menezes Date: Wed, 29 May 2024 17:37:42 -0300 Subject: [PATCH] perf: Optimize GetComponent --- Basalt/Common/Entities/Entity.cs | 38 ++++++++++++++++++++------ Basalt/Common/Physics/PhysicsEngine.cs | 10 +++---- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/Basalt/Common/Entities/Entity.cs b/Basalt/Common/Entities/Entity.cs index 8419e62..335cb45 100644 --- a/Basalt/Common/Entities/Entity.cs +++ b/Basalt/Common/Entities/Entity.cs @@ -34,6 +34,9 @@ public class Entity [JsonIgnore] public Rigidbody? Rigidbody; + [JsonIgnore] + public Collider? Collider; + [JsonIgnore] public Entity? Parent { get; private set; } @@ -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) @@ -230,16 +243,25 @@ public void RemoveComponent(Component component) /// The first instance of a component of type public T? GetComponent() 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; } + /// /// Gets all components of the entity. /// diff --git a/Basalt/Common/Physics/PhysicsEngine.cs b/Basalt/Common/Physics/PhysicsEngine.cs index 1a3d7a8..c3e8651 100644 --- a/Basalt/Common/Physics/PhysicsEngine.cs +++ b/Basalt/Common/Physics/PhysicsEngine.cs @@ -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(); - var colliderB = entityB.GetComponent(); + var colliderA = entityA.Collider; + var colliderB = entityB.Collider; if (colliderA != null && colliderB != null) { CollisionHandler.Handle(colliderA, colliderB); } } - } + }); }); elapsedTime = DateTimeOffset.Now.ToUnixTimeMilliseconds() - startTime;