forked from RevenantX/NetGameExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAntilagSystem.cs
More file actions
106 lines (91 loc) · 3.32 KB
/
Copy pathAntilagSystem.cs
File metadata and controls
106 lines (91 loc) · 3.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Collections.Generic;
using UnityEngine;
namespace Code.Server
{
public struct StateInfo
{
public Vector2 Position;
}
public class AntilagSystem
{
private readonly Dictionary<int, StateInfo>[] _storedPositions;
private readonly Dictionary<int, StateInfo> _savedStates;
private int _currentArrayPos;
private ushort _lastTick;
private readonly int _maxTicks;
public AntilagSystem(int maxTicks, int maxPlayers)
{
int dictSize = (maxPlayers + 1)*3;
_maxTicks = maxTicks;
_storedPositions = new Dictionary<int, StateInfo>[maxTicks];
_savedStates = new Dictionary<int, StateInfo>(dictSize);
for (int i = 0; i < _storedPositions.Length; i++)
{
_storedPositions[i] = new Dictionary<int, StateInfo>(dictSize);
}
}
private Dictionary<int, StateInfo> GetStates(ushort tick)
{
if (tick < _lastTick - _maxTicks || _lastTick < _maxTicks)
return null;
return _storedPositions[(_currentArrayPos - _lastTick + tick - 1) % _maxTicks];
}
public void StorePositions(ushort serverTick, ServerPlayer[] players)
{
var currentDict = _storedPositions[_currentArrayPos];
currentDict.Clear();
foreach (var p in players)
{
if (!p.IsAlive)
continue;
StateInfo si = new StateInfo
{
Position = p.Position
};
currentDict.Add(p.AssociatedPeer.Id, si);
}
_lastTick = serverTick;
_currentArrayPos = (_currentArrayPos + 1) % _maxTicks;
}
public bool TryApplyAntilag(ServerPlayer[] players, ushort tick, int exceptId)
{
var antilagStates = GetStates(tick);
if (antilagStates == null)
return false;
_savedStates.Clear();
foreach (var p in players)
{
int id = p.AssociatedPeer.Id;
if (id == exceptId)
continue;
//Save current states
StateInfo state = new StateInfo
{
Position = p.Position
};
//Console.WriteLine("Save state {0} = {1} {2}", id, state.Position, state.Pose);
_savedStates[id] = state;
//Apply antilag
StateInfo antilagState;
if (antilagStates.TryGetValue(id, out antilagState))
{
//serverController.Player.ChangeState(antilagState.Position, antilagState.Pose, true);
}
}
return true;
}
public void RevertAntilag(ServerPlayer[] players)
{
//Revert states
foreach (var p in players)
{
StateInfo state;
if (_savedStates.TryGetValue(p.AssociatedPeer.Id, out state))
{
//Console.WriteLine("Load state {0} = {1} {2}", serverController.ServerId, state.Position, state.Pose);
//p.ChangeState(state.Position, state.Pose, true);
}
}
}
}
}