Zero-Copy optimization
See original GitHub issueCurrently Velcro Physics makes use of a zero-copy optimization when using the MonoGame framework. It is best illustrated with an example:
When you want to use Velcro in your MonoGame game, you have an update loop like this:
public override void Update()
{
//Vector2 from MonoGame
Vector2 position = new Vector2(5, 10);
Vec2 physicsPosition = new Vec2(position.X, position.Y);
_world.Add(new Body(physicsPosition));
}
As you can see, we have to copy Vector2 into Vec2 to use it in the engine, and in the process, we just wasted a bit of CPU and RAM.
The optimization is that Velcro uses the Vector2 class from MonoGame internally (no dependency - source code is copied out), and then I make a MonoGame version of the library that does take dependency on MonoGame, but then I exclude our local Vector2 class from the project with a compiler constant. This way, when people are using MonoGame, we can zero copy like this:
public override void Update()
{
//Vector2 from MonoGame
Vector2 position = new Vector2(5, 10);
_world.Add(new Body(position));
}
This used to be a major optimization in Farseer Physics Engine since it used pixels as unit. However, now we use the Meter-Kilogram-Second (MKS) system instead, which means we have to copy over values anyway. This issue is to start a discussion on the relevancy of this optimization, as well as provide solutions to a better system, now that we use MKS.
Issue Analytics
- State:
- Created 6 years ago
- Comments:21 (13 by maintainers)
To confirm that we are talking about memory pressure and cache coherence, I did some micro benchmarks on both MonoGame Vector2 and System.Numerics Vector2. In theory, the System.Numerics one would be faster due to hardware accelleration (SIMD), but not with much since we are using Vector2 and not Matrix operations.
There are 3 cases:
I also did a special case for operators to see how they compare.
I know this issue is a bit older. But I just stumbled onto Velcro Physics today after searching for a nuget package for good old trusty Farseer
I’d prefer using System.Numeric or internal Vector/Matrix structs. Personally I already use different world coordinate systems for physics, drawing, and sometimes even the logical world. So there is no benefit for me for tying MonoGame to Velcro (even though I usually use MonoGame!).
I also do not see how an interface like IVector2 would work. There is no way MonoGame or any other engine could implement that without tying itself to Velcro so you will need to create your own type then anyway 😃.
Great to see that you’re still so active in the 2D physics world. Can’t wait to see an official release and Nuget package for Velcro!