Avoid allocations while interpolating cube lines (#8773)

This commit is contained in:
2026-07-24 09:24:34 -07:00
committed by GitHub
parent 4ff32ec0b2
commit f672126a00
@@ -78,7 +78,8 @@ auto FixupCube(
// Always rounds half up, instead of away from zero.
auto RoundHalfUp(const double d) -> double { return std::floor(d + 0.5); }
auto CubeLerp(const Cube &c1, const Cube &c2, const double t) -> std::vector<Cube> {
auto AppendCubeLerp(std::vector<Cube> &cubes, const Cube &c1, const Cube &c2, const double t)
-> void {
const auto floatX = std::lerp(c1.x, c2.x, t);
const auto newX = RoundHalfUp(floatX);
const auto xDiff = abs(newX - floatX);
@@ -91,8 +92,6 @@ auto CubeLerp(const Cube &c1, const Cube &c2, const double t) -> std::vector<Cub
const auto newZ = RoundHalfUp(floatZ);
const auto zDiff = abs(newZ - floatZ);
std::vector<Cube> cubes{};
cubes.reserve(2);
cubes.push_back(FixupCube(newX, xDiff, newY, yDiff, newZ, zDiff));
// The 0.5 case represents a situation where the line passes exactly between two hexes. In that
@@ -103,8 +102,6 @@ auto CubeLerp(const Cube &c1, const Cube &c2, const double t) -> std::vector<Cub
} else if (yDiff == 0.5) {
cubes.push_back(FixupCube(newX, xDiff, floatY - 0.5, yDiff, newZ, zDiff));
}
return cubes;
}
// Slight variation of the method described in
@@ -119,9 +116,7 @@ auto CubeLineInclusive(const Cube &c1, const Cube &c2) -> std::vector<Cube> {
cubes.reserve(2 * (dist + 1));
const double reciprocal = 1.0 / dist;
for (int i = 0; i <= dist; ++i) {
for (const auto &c : CubeLerp(c1, c2, i * reciprocal)) { cubes.push_back(c); }
}
for (int i = 0; i <= dist; ++i) { AppendCubeLerp(cubes, c1, c2, i * reciprocal); }
return cubes;
}