Re-add jungles, apple trees
[oweals/minetest.git] / src / rollback.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 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 #define POINTS_PER_NODE (16.0)
37
38 // Get nearness factor for subject's action for this action
39 // Return value: 0 = impossible, >0 = factor
40 static float getSuspectNearness(bool is_guess, v3s16 suspect_p, int suspect_t,
41                 v3s16 action_p, int action_t)
42 {
43         // Suspect cannot cause things in the past
44         if(action_t < suspect_t)
45                 return 0; // 0 = cannot be
46         // Start from 100
47         int f = 100;
48         // Distance (1 node = -x points)
49         f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
50         // Time (1 second = -x points)
51         f -= 1 * (action_t - suspect_t);
52         // If is a guess, halve the points
53         if(is_guess)
54                 f *= 0.5;
55         // Limit to 0
56         if(f < 0)
57                 f = 0;
58         return f;
59 }
60
61 class RollbackManager: public IRollbackManager
62 {
63 public:
64         // IRollbackManager interface
65
66         void reportAction(const RollbackAction &action_)
67         {
68                 // Ignore if not important
69                 if(!action_.isImportant(m_gamedef))
70                         return;
71                 RollbackAction action = action_;
72                 action.unix_time = time(0);
73                 // Figure out actor
74                 action.actor = m_current_actor;
75                 action.actor_is_guess = m_current_actor_is_guess;
76                 // If actor is not known, find out suspect or cancel
77                 if(action.actor.empty()){
78                         v3s16 p;
79                         if(!action.getPosition(&p))
80                                 return;
81                         action.actor = getSuspect(p, 83, 1);
82                         if(action.actor.empty())
83                                 return;
84                         action.actor_is_guess = true;
85                 }
86                 infostream<<"RollbackManager::reportAction():"
87                                 <<" time="<<action.unix_time
88                                 <<" actor=\""<<action.actor<<"\""
89                                 <<(action.actor_is_guess?" (guess)":"")
90                                 <<" action="<<action.toString()
91                                 <<std::endl;
92                 addAction(action);
93         }
94         std::string getActor()
95         {
96                 return m_current_actor;
97         }
98         bool isActorGuess()
99         {
100                 return m_current_actor_is_guess;
101         }
102         void setActor(const std::string &actor, bool is_guess)
103         {
104                 m_current_actor = actor;
105                 m_current_actor_is_guess = is_guess;
106         }
107         std::string getSuspect(v3s16 p, float nearness_shortcut, float min_nearness)
108         {
109                 if(m_current_actor != "")
110                         return m_current_actor;
111                 int cur_time = time(0);
112                 int first_time = cur_time - (100-min_nearness);
113                 RollbackAction likely_suspect;
114                 float likely_suspect_nearness = 0;
115                 for(std::list<RollbackAction>::const_reverse_iterator
116                                 i = m_action_latest_buffer.rbegin();
117                                 i != m_action_latest_buffer.rend(); i++)
118                 {
119                         if(i->unix_time < first_time)
120                                 break;
121                         if(i->actor == "")
122                                 continue;
123                         // Find position of suspect or continue
124                         v3s16 suspect_p;
125                         if(!i->getPosition(&suspect_p))
126                                 continue;
127                         float f = getSuspectNearness(i->actor_is_guess, suspect_p,
128                                         i->unix_time, p, cur_time);
129                         if(f >= min_nearness && f > likely_suspect_nearness){
130                                 likely_suspect_nearness = f;
131                                 likely_suspect = *i;
132                                 if(likely_suspect_nearness >= nearness_shortcut)
133                                         break;
134                         }
135                 }
136                 // No likely suspect was found
137                 if(likely_suspect_nearness == 0)
138                         return "";
139                 // Likely suspect was found
140                 return likely_suspect.actor;
141         }
142         void flush()
143         {
144                 infostream<<"RollbackManager::flush()"<<std::endl;
145                 std::ofstream of(m_filepath.c_str(), std::ios::app);
146                 if(!of.good()){
147                         errorstream<<"RollbackManager::flush(): Could not open file "
148                                         <<"for appending: \""<<m_filepath<<"\""<<std::endl;
149                         return;
150                 }
151                 for(std::list<RollbackAction>::const_iterator
152                                 i = m_action_todisk_buffer.begin();
153                                 i != m_action_todisk_buffer.end(); i++)
154                 {
155                         // Do not save stuff that does not have an actor
156                         if(i->actor == "")
157                                 continue;
158                         of<<i->unix_time;
159                         of<<" ";
160                         of<<serializeJsonString(i->actor);
161                         of<<" ";
162                         of<<i->toString();
163                         if(i->actor_is_guess){
164                                 of<<" ";
165                                 of<<"actor_is_guess";
166                         }
167                         of<<std::endl;
168                 }
169                 m_action_todisk_buffer.clear();
170         }
171         
172         // Other
173
174         RollbackManager(const std::string &filepath, IGameDef *gamedef):
175                 m_filepath(filepath),
176                 m_gamedef(gamedef),
177                 m_current_actor_is_guess(false)
178         {
179                 infostream<<"RollbackManager::RollbackManager("<<filepath<<")"
180                                 <<std::endl;
181         }
182         ~RollbackManager()
183         {
184                 infostream<<"RollbackManager::~RollbackManager()"<<std::endl;
185                 flush();
186         }
187
188         void addAction(const RollbackAction &action)
189         {
190                 m_action_todisk_buffer.push_back(action);
191                 m_action_latest_buffer.push_back(action);
192
193                 // Flush to disk sometimes
194                 if(m_action_todisk_buffer.size() >= 100)
195                         flush();
196         }
197         
198         bool readFile(std::list<RollbackAction> &dst)
199         {
200                 // Load whole file to memory
201                 std::ifstream f(m_filepath.c_str(), std::ios::in);
202                 if(!f.good()){
203                         errorstream<<"RollbackManager::readFile(): Could not open "
204                                         <<"file for reading: \""<<m_filepath<<"\""<<std::endl;
205                         return false;
206                 }
207                 for(;;){
208                         if(f.eof() || !f.good())
209                                 break;
210                         std::string line;
211                         std::getline(f, line);
212                         line = trim(line);
213                         if(line == "")
214                                 continue;
215                         std::istringstream is(line);
216                         
217                         try{
218                                 std::string action_time_raw;
219                                 std::getline(is, action_time_raw, ' ');
220                                 std::string action_actor;
221                                 try{
222                                         action_actor = deSerializeJsonString(is);
223                                 }catch(SerializationError &e){
224                                         errorstream<<"RollbackManager: Error deserializing actor: "
225                                                         <<e.what()<<std::endl;
226                                         throw e;
227                                 }
228                                 RollbackAction action;
229                                 action.unix_time = stoi(action_time_raw);
230                                 action.actor = action_actor;
231                                 int c = is.get();
232                                 if(c != ' '){
233                                         is.putback(c);
234                                         throw SerializationError("readFile(): second ' ' not found");
235                                 }
236                                 action.fromStream(is);
237                                 /*infostream<<"RollbackManager::readFile(): Action from disk: "
238                                                 <<action.toString()<<std::endl;*/
239                                 dst.push_back(action);
240                         }
241                         catch(SerializationError &e){
242                                 errorstream<<"RollbackManager: Error on line: "<<line<<std::endl;
243                                 errorstream<<"RollbackManager: ^ error: "<<e.what()<<std::endl;
244                         }
245                 }
246                 return true;
247         }
248
249         std::list<RollbackAction> getEntriesSince(int first_time)
250         {
251                 infostream<<"RollbackManager::getEntriesSince("<<first_time<<")"<<std::endl;
252                 // Collect enough data to this buffer
253                 std::list<RollbackAction> action_buffer;
254                 // Use the latest buffer if it is long enough
255                 if(!m_action_latest_buffer.empty() &&
256                                 m_action_latest_buffer.begin()->unix_time <= first_time){
257                         action_buffer = m_action_latest_buffer;
258                 }
259                 else
260                 {
261                         // Save all remaining stuff
262                         flush();
263                         // Load whole file to memory
264                         bool good = readFile(action_buffer);
265                         if(!good){
266                                 errorstream<<"RollbackManager::getEntriesSince(): Failed to"
267                                                 <<" open file; using data in memory."<<std::endl;
268                                 action_buffer = m_action_latest_buffer;
269                         }
270                 }
271                 return action_buffer;
272         }
273         
274         std::string getLastNodeActor(v3s16 p, int range, int seconds,
275                         v3s16 *act_p, int *act_seconds)
276         {
277                 infostream<<"RollbackManager::getLastNodeActor("<<PP(p)
278                                 <<", "<<seconds<<")"<<std::endl;
279                 // Figure out time
280                 int cur_time = time(0);
281                 int first_time = cur_time - seconds;
282
283                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
284                 
285                 std::list<RollbackAction> result;
286
287                 for(std::list<RollbackAction>::const_reverse_iterator
288                                 i = action_buffer.rbegin();
289                                 i != action_buffer.rend(); i++)
290                 {
291                         if(i->unix_time < first_time)
292                                 break;
293
294                         // Find position of action or continue
295                         v3s16 action_p;
296                         if(!i->getPosition(&action_p))
297                                 continue;
298
299                         if(range == 0){
300                                 if(action_p != p)
301                                         continue;
302                         } else {
303                                 if(abs(action_p.X - p.X) > range ||
304                                                 abs(action_p.Y - p.Y) > range ||
305                                                 abs(action_p.Z - p.Z) > range)
306                                         continue;
307                         }
308                         
309                         if(act_p)
310                                 *act_p = action_p;
311                         if(act_seconds)
312                                 *act_seconds = cur_time - i->unix_time;
313                         return i->actor;
314                 }
315                 return "";
316         }
317
318         std::list<RollbackAction> getRevertActions(const std::string &actor_filter,
319                         int seconds)
320         {
321                 infostream<<"RollbackManager::getRevertActions("<<actor_filter
322                                 <<", "<<seconds<<")"<<std::endl;
323                 // Figure out time
324                 int cur_time = time(0);
325                 int first_time = cur_time - seconds;
326                 
327                 std::list<RollbackAction> action_buffer = getEntriesSince(first_time);
328                 
329                 std::list<RollbackAction> result;
330
331                 for(std::list<RollbackAction>::const_reverse_iterator
332                                 i = action_buffer.rbegin();
333                                 i != action_buffer.rend(); i++)
334                 {
335                         if(i->unix_time < first_time)
336                                 break;
337                         if(i->actor != actor_filter)
338                                 continue;
339                         const RollbackAction &action = *i;
340                         /*infostream<<"RollbackManager::revertAction(): Should revert"
341                                         <<" time="<<action.unix_time
342                                         <<" actor=\""<<action.actor<<"\""
343                                         <<" action="<<action.toString()
344                                         <<std::endl;*/
345                         result.push_back(action);
346                 }
347
348                 return result;
349         }
350
351 private:
352         std::string m_filepath;
353         IGameDef *m_gamedef;
354         std::string m_current_actor;
355         bool m_current_actor_is_guess;
356         std::list<RollbackAction> m_action_todisk_buffer;
357         std::list<RollbackAction> m_action_latest_buffer;
358 };
359
360 IRollbackManager *createRollbackManager(const std::string &filepath, IGameDef *gamedef)
361 {
362         return new RollbackManager(filepath, gamedef);
363 }
364
365