pygame-community / pygame-ce

🐍🎮 pygame - Community Edition is a FOSS Python library for multimedia applications (like games). Built on top of the excellent SDL library.
https://pyga.me
909 stars 148 forks source link

Rect getters should return Vector2s? #2311

Open ScriptLineStudios opened 1 year ago

ScriptLineStudios commented 1 year ago

I think the the rect getters which return tuples should return Vectors2s instead. This could aid in making calculations which use these results easier.

itzpr3d4t0r commented 1 year ago

I would be in favour of this if we actually had a more performant Vector implementation. Vector just isn't good at access and other stuff:

from pygame import Vector2
from timeit import timeit

v = Vector2(1, 2)
t = (1, 2)

G = globals()
print("X")
print(timeit('v.x', globals=G))
print(timeit('v[0]', globals=G))
print(timeit('t[0]', globals=G))
print("Y")
print(timeit('v.y', globals=G))
print(timeit('v[1]', globals=G))
print(timeit('t[1]', globals=G))
print("unpack")
print(timeit('x, y = v', globals=G))
print(timeit('x, y = t', globals=G))
X
0.030178999997588107
0.030862300001899712
0.016415099998994265
Y
0.030032300001039403
0.03028210000047693
0.016151399999216665
unpack
0.05890949999957229
0.015941900001053

I could go way more in depth as to why if necessary. Another thing is that while python tuples will get faster over time due to Cpython improvements, our vector implementation has a limit, and we're very close to it. Also tuples are waaaay faster to instantiate compared to vectors:

print(timeit('Vector2(1, 2)', globals=G))
print(timeit('(1, 2)', globals=G))
0.13981520000015735
0.008219399998779409

So we'd be adding tons of overhead, with instantiation and later on access. Another thing is that most pygame users are newbies that are still learning python and tuples, so it makes sense to keep basic stuff simple. If you really need a vectors you can simply convert the tuple to Vector2 if needed. basically with tuples you have a choice, with vectors you don't, you just lose performance.

Starbuck5 commented 1 year ago

Matt was championing going down this road before. See https://github.com/pygame-community/pygame-ce/issues/1906

The problem is that tuples are hashable (since they're immutable), vectors are not. Then apparently even a hypothetical "frozen vector" wouldn't be backwards compatible either.