Skip to content

Commit

Permalink
items: fix Item_GetDistance overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
rr- committed Nov 6, 2024
1 parent 92ced59 commit 63df6b2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
17 changes: 13 additions & 4 deletions src/tr1/game/items.c
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,19 @@ bool Item_IsNearItem(const ITEM *item, const XYZ_32 *pos, int32_t distance)

int32_t Item_GetDistance(const ITEM *const item, const XYZ_32 *const target)
{
const int32_t x = (item->pos.x - target->x);
const int32_t y = (item->pos.y - target->y);
const int32_t z = (item->pos.z - target->z);
return Math_Sqrt(SQUARE(x) + SQUARE(y) + SQUARE(z));
int32_t x = (item->pos.x - target->x);
int32_t y = (item->pos.y - target->y);
int32_t z = (item->pos.z - target->z);

int32_t scale = 0;
while ((int16_t)x != x || (int16_t)y != y || (int16_t)z != z) {
scale++;
x >>= 1;
y >>= 1;
z >>= 1;
}

return Math_Sqrt(SQUARE(x) + SQUARE(y) + SQUARE(z)) << scale;
}

bool Item_Test3DRange(int32_t x, int32_t y, int32_t z, int32_t range)
Expand Down
20 changes: 13 additions & 7 deletions src/tr2/game/math.c
Original file line number Diff line number Diff line change
Expand Up @@ -506,13 +506,19 @@ int16_t Math_DirectionToAngle(DIRECTION dir)

int32_t XYZ_32_GetDistance(const XYZ_32 *const pos1, const XYZ_32 *const pos2)
{
// clang-format off
return Math_Sqrt(
SQUARE(pos1->x - pos2->x) +
SQUARE(pos1->y - pos2->y) +
SQUARE(pos1->z - pos2->z)
);
// clang-format on
int32_t x = (pos1->x - pos2->x);
int32_t y = (pos1->y - pos2->y);
int32_t z = (pos1->z - pos2->z);

int32_t scale = 0;
while ((int16_t)x != x || (int16_t)y != y || (int16_t)z != z) {
scale++;
x >>= 1;
y >>= 1;
z >>= 1;
}

return Math_Sqrt(SQUARE(x) + SQUARE(y) + SQUARE(z)) << scale;
}

int32_t XYZ_32_GetDistance0(const XYZ_32 *const pos)
Expand Down

0 comments on commit 63df6b2

Please sign in to comment.