Make the rollback system VERY FUCKING GOD DAMN POWERFUL
[oweals/minetest.git] / src / rollback.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2012 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "rollback.h"
21 #include <fstream>
22 #include <list>
23 #include <sstream>
24 #include "log.h"
25 #include "mapnode.h"
26 #include "gamedef.h"
27 #include "nodedef.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
30 #include "strfnd.h"
31 #include "util/numeric.h"
32 #include "inventorymanager.h" // deserializing InventoryLocations
33
34 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
35
36 // Get nearness factor for subject's action for this action
37 // Return value: 0 = impossible, >0 = factor
38 static float getSuspectNearness(bool is_guess, v3s16 suspect_p, int suspect_t,
39                 v3s16 action_p, int action_t)
40 {
41         // Suspect cannot cause things in the past
42         if(action_t < suspect_t)
43                 return 0; // 0 = cannot be
44         // Start from 100
45         int f = 100;
46         // Distance (1 node = +1 point)
47         f += 1.0 * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
48         // Time (1 second = -1 point)
49         f -= 1.0 * (action_t - suspect_t);
50         // If is a guess, halve the points
51         if(is_guess)
52                 f *= 0.5;
53         // Limit to 0
54         if(f < 0)
55                 f = 0;
56         return f;
57 }
58
59 class RollbackManager: public IRollbackManager
60 {
61 public:
62         // IRollbackManager interface
63
64         void reportAction(const RollbackAction &action_)
65         {
66                 // Ignore if not important
67                 if(!action_.isImportant(m_gamedef))
68                         return;
69                 RollbackAction action = action_;
70                 action.unix_time = time(0);
71                 // Figure out actor
72                 action.actor = m_current_actor;
73                 action.actor_is_guess = m_current_actor_is_guess;
74                 // If actor is not known, find out suspect or cancel
75                 if(action.actor.empty()){
76                         v3s16 p;
77                         if(!action.getPosition(&p))
78                                 return;
79                         action.actor = getSuspect(p, 5); // 5s timeframe
80                         if(action.actor.empty())
81                                 return;
82                         action.actor_is_guess = true;
83                 }
84                 infostream<<"RollbackManager::reportAction():"
85                                 <<" time="<<action.unix_time
86                                 <<" actor=\""<<action.actor<<"\""
87                                 <<(action.actor_is_guess?" (guess)":"")
88                                 <<" action="<<action.toString()
89                                 <<std::endl;
90                 addAction(action);
91         }
92         std::string getActor()
93         {
94                 return m_current_actor;
95         }
96         bool isActorGuess()
97         {
98                 return m_current_actor_is_guess;
99         }
100         void setActor(const std::string &actor, bool is_guess)
101         {
102                 m_current_actor = actor;
103                 m_current_actor_is_guess = is_guess;
104         }
105         std::string getSuspect(v3s16 p, int max_time)
106         {
107                 if(m_current_actor != "")
108                         return m_current_actor;
109                 int cur_time = time(0);
110                 int first_time = cur_time - max_time;
111                 RollbackAction likely_suspect;
112                 float likely_suspect_nearness = 0;
113                 for(std::list<RollbackAction>::const_reverse_iterator
114                                 i = m_action_latest_buffer.rbegin();
115                                 i != m_action_latest_buffer.rend(); i++)
116                 {
117                         if(i->unix_time < first_time)
118                                 break;
119                         // Find position of suspect or continue
120                         v3s16 suspect_p;
121                         if(!i->getPosition(&suspect_p))
122                                 continue;
123                         float f = getSuspectNearness(i->actor_is_guess, suspect_p,
124                                         i->unix_time, p, cur_time);
125                         if(f > likely_suspect_nearness){
126                                 likely_suspect_nearness = f;
127                                 likely_suspect = *i;
128                         }
129                 }
130                 // No likely suspect was found
131                 if(likely_suspect_nearness == 0)
132                         return "";
133                 // Likely suspect was found
134                 return likely_suspect.actor;
135         }
136         void flush()
137         {
138                 infostream<<"RollbackManager::flush()"<<std::endl;
139                 std::ofstream of(m_filepath.c_str(), std::ios::app);
140                 if(!of.good()){
141                         errorstream<<"RollbackManager::flush(): Could not open file "
142                                         <<"for appending: \""<<m_filepath<<"\""<<std::endl;
143                         return;
144                 }
145                 for(std::list<RollbackAction>::const_iterator
146                                 i = m_action_todisk_buffer.begin();
147                                 i != m_action_todisk_buffer.end(); i++)
148                 {
149                         // Do not save stuff that does not have an actor
150                         if(i->actor == "")
151                                 continue;
152                         of<<i->unix_time;
153                         of<<" ";
154                         of<<serializeJsonString(i->actor);
155                         of<<" ";
156                         of<<i->toString();
157                         if(i->actor_is_guess){
158                                 of<<" ";
159                                 of<<"actor_is_guess";
160                         }
161                         of<<std::endl;
162                 }
163                 m_action_todisk_buffer.clear();
164         }
165         
166         // Other
167
168         RollbackManager(const std::string &filepath, IGameDef *gamedef):
169                 m_filepath(filepath),
170                 m_gamedef(gamedef),
171                 m_current_actor_is_guess(false)
172         {
173                 infostream<<"RollbackManager::RollbackManager("<<filepath<<")"
174                                 <<std::endl;
175         }
176         ~RollbackManager()
177         {
178                 infostream<<"RollbackManager::~RollbackManager()"<<std::endl;
179                 flush();
180         }
181
182         void addAction(const RollbackAction &action)
183         {
184                 m_action_todisk_buffer.push_back(action);
185                 m_action_latest_buffer.push_back(action);
186
187                 // Flush to disk sometimes
188                 if(m_action_todisk_buffer.size() >= 100)
189                         flush();
190         }
191         
192         bool readFile(std::list<RollbackAction> &dst)
193         {
194                 // Load whole file to memory
195                 std::ifstream f(m_filepath.c_str(), std::ios::in);
196                 if(!f.good()){
197                         errorstream<<"RollbackManager::readFile(): Could not open "
198                                         <<"file for reading: \""<<m_filepath<<"\""<<std::endl;
199                         return false;
200                 }
201                 for(;;){
202                         if(f.eof() || !f.good())
203                                 break;
204                         std::string line;
205                         std::getline(f, line);
206                         line = trim(line);
207                         if(line == "")
208                                 continue;
209                         std::istringstream is(line);
210                         
211                         try{
212                                 std::string action_time_raw;
213                                 std::getline(is, action_time_raw, ' ');
214                                 std::string action_actor;
215                                 try{
216                                         action_actor = deSerializeJsonString(is);
217                                 }catch(SerializationError &e){
218                                         errorstream<<"RollbackManager: Error deserializing actor: "
219                                                         <<e.what()<<std::endl;
220                                         throw e;
221                                 }
222                                 RollbackAction action;
223                                 action.unix_time = stoi(action_time_raw);
224                                 action.actor = action_actor;
225                                 int c = is.get();
226                                 if(c != ' '){
227                                         is.putback(c);
228                                         throw SerializationError("readFile(): second ' ' not found");
229                                 }
230                                 action.fromStream(is);
231                                 /*infostream<<"RollbackManager::readFile(): Action from disk: "
232                                                 <<action.toString()<<std::endl;*/
233                                 dst.push_back(action);
234                         }
235                         catch(SerializationError &e){
236                                 errorstream<<"RollbackManager: Error on line: "<<line<<std::endl;
237                                 errorstream<<"RollbackManager: ^ error: "<<e.what()<<std::endl;
238                         }
239                 }
240                 return true;
241         }
242
243         std::list<RollbackAction> getEntriesSince(int first_time)
244         {
245                 infostream<<"RollbackManager::getEntriesSince("<<first_time<<")"<<std::endl;
246                 // Collect enough data to this buffer
247                 std::list<RollbackAction> action_buffer;
248                 // Use the latest buffer if it is long enough
249                 if(!m_action_latest_buffer.empty() &&
250                                 m_action_latest_buffer.begin()->unix_time <= first_time){
251                         action_buffer = m_action_latest_buffer;
252                 }
253                 else
254                 {
255                         // Save all remaining stuff
256                         flush();
257                         // Load whole file to memory
258                         bool good = readFile(action_buffer);
259                         if(!good){
260                                 errorstream<<"RollbackManager::getEntriesSince(): Failed to"
261                                                 <<" open file; using data in memory."<<std::endl;
262                                 action_buffer = m_action_latest_buffer;
263                         }
264                 }
265                 return action_buffer;
266         }
267         
268         std::string getLastNodeActor(v3s16 p, int range, int seconds,
269                         v3s16 *act_p, int *act_seconds)
270         {
271                 infostream<<"RollbackManager::getLastNodeActor("<<PP(p)
272                                 <<", "<<seconds<<")"<<std::endl;
273                 // Figure out time
274                 int cur_time = time(0);
275                 int first_time = cur_time - seconds;
276
277                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
278                 
279                 std::list<RollbackAction> result;
280
281                 for(std::list<RollbackAction>::const_reverse_iterator
282                                 i = action_buffer.rbegin();
283                                 i != action_buffer.rend(); i++)
284                 {
285                         if(i->unix_time < first_time)
286                                 break;
287
288                         // Find position of action or continue
289                         v3s16 action_p;
290                         if(!i->getPosition(&action_p))
291                                 continue;
292
293                         if(range == 0){
294                                 if(action_p != p)
295                                         continue;
296                         } else {
297                                 if(abs(action_p.X - p.X) > range ||
298                                                 abs(action_p.Y - p.Y) > range ||
299                                                 abs(action_p.Z - p.Z) > range)
300                                         continue;
301                         }
302                         
303                         if(act_p)
304                                 *act_p = action_p;
305                         if(act_seconds)
306                                 *act_seconds = cur_time - i->unix_time;
307                         return i->actor;
308                 }
309                 return "";
310         }
311
312         std::list<RollbackAction> getRevertActions(const std::string &actor_filter,
313                         int seconds)
314         {
315                 infostream<<"RollbackManager::getRevertActions("<<actor_filter
316                                 <<", "<<seconds<<")"<<std::endl;
317                 // Figure out time
318                 int cur_time = time(0);
319                 int first_time = cur_time - seconds;
320                 
321                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
322                 
323                 std::list<RollbackAction> result;
324
325                 for(std::list<RollbackAction>::const_reverse_iterator
326                                 i = action_buffer.rbegin();
327                                 i != action_buffer.rend(); i++)
328                 {
329                         if(i->unix_time < first_time)
330                                 break;
331                         if(i->actor != actor_filter)
332                                 continue;
333                         const RollbackAction &action = *i;
334                         /*infostream<<"RollbackManager::revertAction(): Should revert"
335                                         <<" time="<<action.unix_time
336                                         <<" actor=\""<<action.actor<<"\""
337                                         <<" action="<<action.toString()
338                                         <<std::endl;*/
339                         result.push_back(action);
340                 }
341
342                 return result;
343         }
344
345 private:
346         std::string m_filepath;
347         IGameDef *m_gamedef;
348         std::string m_current_actor;
349         bool m_current_actor_is_guess;
350         std::list<RollbackAction> m_action_todisk_buffer;
351         std::list<RollbackAction> m_action_latest_buffer;
352 };
353
354 IRollbackManager *createRollbackManager(const std::string &filepath, IGameDef *gamedef)
355 {
356         return new RollbackManager(filepath, gamedef);
357 }
358
359