From 5e3e06b74eb150823757c27514c9c06704ba1f11 Mon Sep 17 00:00:00 2001 From: Cyberarm Date: Sun, 16 Apr 2023 20:26:29 -0500 Subject: [PATCH] Improve Vector arithmetic performance by 2x --- lib/cyberarm_engine/vector.rb | 59 +++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 20 deletions(-) diff --git a/lib/cyberarm_engine/vector.rb b/lib/cyberarm_engine/vector.rb index 8842b49..4afd413 100644 --- a/lib/cyberarm_engine/vector.rb +++ b/lib/cyberarm_engine/vector.rb @@ -95,39 +95,58 @@ module CyberarmEngine Vector.new(@x, @y) end - # Performs math operation, excluding {weight} - private def operator(function, other) - if other.is_a?(Numeric) - Vector.new( - @x.send(:"#{function}", other), - @y.send(:"#{function}", other), - @z.send(:"#{function}", other) - ) - else - Vector.new( - @x.send(:"#{function}", other.x), - @y.send(:"#{function}", other.y), - @z.send(:"#{function}", other.z) - ) - end - end - # Adds Vector and Numeric or Vector and Vector, excluding {weight} # @return [CyberarmEngine::Vector] def +(other) - operator("+", other) + if other.is_a?(Numeric) + Vector.new( + @x + other, + @y + other, + @z + other + ) + else + Vector.new( + @x + other.x, + @y + other.y, + @z + other.z + ) + end end # Subtracts Vector and Numeric or Vector and Vector, excluding {weight} # @return [CyberarmEngine::Vector] def -(other) - operator("-", other) + if other.is_a?(Numeric) + Vector.new( + @x - other, + @y - other, + @z - other + ) + else + Vector.new( + @x - other.x, + @y - other.y, + @z - other.z + ) + end end # Multiplies Vector and Numeric or Vector and Vector, excluding {weight} # @return [CyberarmEngine::Vector] def *(other) - operator("*", other) + if other.is_a?(Numeric) + Vector.new( + @x * other, + @y * other, + @z * other + ) + else + Vector.new( + @x * other.x, + @y * other.y, + @z * other.z + ) + end end def multiply_transform(transform)