17constexpr std::size_t kMostSnapshots = 20;
20float Mix(
float a,
float b,
float share) {
return a + (b - a) * share; }
24template <
typename Unit,
typename Places>
25void Between(google::protobuf::RepeatedPtrField<Unit>& units, uint32_t you,
26 const Places& before,
const Places& after,
float share) {
27 for (Unit& unit : units) {
28 const auto from = before.find(unit.id());
29 const auto to = after.find(unit.id());
30 if (unit.id() == you || from == before.end() || to == after.end()) {
33 unit.set_x(
Mix(from->second.x, to->second.x, share));
34 unit.set_z(
Mix(from->second.z, to->second.z, share));
41 const double sent =
static_cast<double>(world.sent()) / 1e6;
43 if (!snapshots_.empty() && sent < snapshots_.back().sent) {
46 if (snapshots_.empty() || sent > snapshots_.back().sent) {
47 snapshots_.push_back({.sent = sent, .ahead = now - sent});
48 if (snapshots_.size() > kMostSnapshots) {
49 snapshots_.pop_front();
52 Snapshot& snapshot = snapshots_.back();
53 for (
const protocol::Player& player : world.players()) {
54 snapshot.players[player.id()] = {player.x(), player.z()};
56 for (
const protocol::Monster& monster : world.monsters()) {
57 snapshot.monsters[monster.id()] = {monster.x(), monster.z()};
61double Interpolation::Then(
double now)
const {
64 double ahead = std::numeric_limits<double>::infinity();
65 for (
const Snapshot& snapshot : snapshots_) {
66 ahead = std::min(ahead, snapshot.ahead);
68 return now - ahead -
kDelay;
72 if (snapshots_.empty()) {
75 return std::llround(Then(now) * 1e6);
80 protocol::World shown = newest;
81 if (snapshots_.size() < 2) {
84 const double then = Then(now);
88 auto after = std::ranges::find_if(
89 snapshots_, [then](
const Snapshot& s) {
return s.sent > then; });
90 if (after == snapshots_.begin()) {
93 if (after == snapshots_.end()) {
94 after = std::prev(snapshots_.end());
96 const Snapshot& from = *std::prev(after);
97 const Snapshot& to = *after;
98 const double gap = to.sent - from.sent;
99 const float share =
static_cast<float>(
100 std::min((then - from.sent) / gap, 1.0 +
kMostAhead / gap));
101 Between(*shown.mutable_players(), newest.you(), from.players, to.players,
103 Between(*shown.mutable_monsters(), 0, from.monsters, to.monsters, share);
void Add(const protocol::World &world, double now)
int64_t Drawn(double now) const
static constexpr double kDelay
protocol::World Shown(const protocol::World &newest, double now) const
static constexpr double kMostAhead
void Mix(Samples &mix, const Samples &sound, float at, float gain)