Translation to Portuguese of Brazil for Minetest
[oweals/minetest.git] / src / emerge.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21
22 #include "server.h"
23 #include <iostream>
24 #include <queue>
25 #include "clientserver.h"
26 #include "map.h"
27 #include "jmutexautolock.h"
28 #include "main.h"
29 #include "constants.h"
30 #include "voxel.h"
31 #include "config.h"
32 #include "mapblock.h"
33 #include "serverobject.h"
34 #include "settings.h"
35 #include "script.h"
36 #include "scriptapi.h"
37 #include "profiler.h"
38 #include "log.h"
39 #include "nodedef.h"
40 #include "biome.h"
41 #include "emerge.h"
42 #include "mapgen_v6.h"
43 #include "mapgen_v7.h"
44 #include "mapgen_indev.h"
45 #include "mapgen_singlenode.h"
46
47
48 /////////////////////////////// Emerge Manager ////////////////////////////////
49
50 EmergeManager::EmergeManager(IGameDef *gamedef) {
51         //register built-in mapgens
52         registerMapgen("v6", new MapgenFactoryV6());
53         registerMapgen("v7", new MapgenFactoryV7());
54         registerMapgen("indev", new MapgenFactoryIndev());
55         registerMapgen("singlenode", new MapgenFactorySinglenode());
56
57         this->ndef     = gamedef->getNodeDefManager();
58         this->biomedef = new BiomeDefManager();
59         this->params   = NULL;
60         
61         mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
62
63         queuemutex.Init();
64         
65         int nthreads;
66         if (g_settings->get("num_emerge_threads").empty()) {
67                 int nprocs = porting::getNumberOfProcessors();
68                 // leave a proc for the main thread and one for some other misc threads
69                 nthreads = (nprocs > 2) ? nprocs - 2 : 1;
70         } else {
71                 nthreads = g_settings->getU16("num_emerge_threads");
72         }
73         if (nthreads < 1)
74                 nthreads = 1;
75         
76         qlimit_total    = g_settings->getU16("emergequeue_limit_total");
77         qlimit_diskonly = g_settings->get("emergequeue_limit_diskonly").empty() ?
78                 nthreads * 5 + 1 :
79                 g_settings->getU16("emergequeue_limit_diskonly");
80         qlimit_generate = g_settings->get("emergequeue_limit_generate").empty() ?
81                 nthreads + 1 :
82                 g_settings->getU16("emergequeue_limit_generate");
83         
84         for (int i = 0; i != nthreads; i++)
85                 emergethread.push_back(new EmergeThread((Server *)gamedef, i));
86                 
87         infostream << "EmergeManager: using " << nthreads << " threads" << std::endl;
88 }
89
90
91 EmergeManager::~EmergeManager() {
92         for (unsigned int i = 0; i != emergethread.size(); i++) {
93                 emergethread[i]->setRun(false);
94                 emergethread[i]->qevent.signal();
95                 emergethread[i]->stop();
96                 delete emergethread[i];
97                 delete mapgen[i];
98         }
99         emergethread.clear();
100         mapgen.clear();
101
102         for (unsigned int i = 0; i < ores.size(); i++)
103                 delete ores[i];
104         ores.clear();
105         
106         for (std::map<std::string, MapgenFactory *>::iterator iter = mglist.begin();
107                         iter != mglist.end(); iter ++) {
108                 delete iter->second;
109         }
110         mglist.clear();
111
112         delete biomedef;
113 }
114
115
116 void EmergeManager::initMapgens(MapgenParams *mgparams) {
117         Mapgen *mg;
118         
119         if (mapgen.size())
120                 return;
121         
122         biomedef->resolveNodeNames(ndef);
123         
124         this->params = mgparams;
125         for (unsigned int i = 0; i != emergethread.size(); i++) {
126                 mg = createMapgen(params->mg_name, 0, params);
127                 if (!mg) {
128                         infostream << "EmergeManager: falling back to mapgen v6" << std::endl;
129                         delete params;
130                         params = createMapgenParams("v6");
131                         mg = createMapgen("v6", 0, params);
132                 }
133                 mapgen.push_back(mg);
134         }
135 }
136
137
138 bool EmergeManager::enqueueBlockEmerge(u16 peer_id, v3s16 p, bool allow_generate) {
139         std::map<v3s16, BlockEmergeData *>::const_iterator iter;
140         BlockEmergeData *bedata;
141         u16 count;
142         u8 flags = 0;
143         int idx = 0;
144         
145         if (allow_generate)
146                 flags |= BLOCK_EMERGE_ALLOWGEN;
147
148         {
149                 JMutexAutoLock queuelock(queuemutex);
150                 
151                 count = blocks_enqueued.size();
152                 if (count >= qlimit_total)
153                         return false;
154
155                 count = peer_queue_count[peer_id];
156                 u16 qlimit_peer = allow_generate ? qlimit_generate : qlimit_diskonly;
157                 if (count >= qlimit_peer)
158                         return false;
159                 
160                 iter = blocks_enqueued.find(p);
161                 if (iter != blocks_enqueued.end()) {
162                         bedata = iter->second;
163                         bedata->flags |= flags;
164                         return true;
165                 }
166
167                 bedata = new BlockEmergeData;
168                 bedata->flags = flags;
169                 bedata->peer_requested = peer_id;
170                 blocks_enqueued.insert(std::make_pair(p, bedata));
171                 
172                 peer_queue_count[peer_id] = count + 1;
173                 
174                 // insert into the EmergeThread queue with the least items
175                 int lowestitems = emergethread[0]->blockqueue.size();
176                 for (unsigned int i = 1; i != emergethread.size(); i++) {
177                         int nitems = emergethread[i]->blockqueue.size();
178                         if (nitems < lowestitems) {
179                                 idx = i;
180                                 lowestitems = nitems;
181                         }
182                 }
183                 
184                 emergethread[idx]->blockqueue.push(p);
185         }
186         emergethread[idx]->qevent.signal();
187         
188         return true;
189 }
190
191
192 int EmergeManager::getGroundLevelAtPoint(v2s16 p) {
193         if (mapgen.size() == 0 || !mapgen[0]) {
194                 errorstream << "EmergeManager: getGroundLevelAtPoint() called"
195                 " before mapgen initialized" << std::endl;
196                 return 0;
197         }
198         
199         return mapgen[0]->getGroundLevelAtPoint(p);
200 }
201
202
203 bool EmergeManager::isBlockUnderground(v3s16 blockpos) {
204         /*
205         v2s16 p = v2s16((blockpos.X * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2,
206                                         (blockpos.Y * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2);
207         int ground_level = getGroundLevelAtPoint(p);
208         return blockpos.Y * (MAP_BLOCKSIZE + 1) <= min(water_level, ground_level);
209         */
210
211         //yuck, but then again, should i bother being accurate?
212         //the height of the nodes in a single block is quite variable
213         return blockpos.Y * (MAP_BLOCKSIZE + 1) <= params->water_level;
214 }
215
216
217 u32 EmergeManager::getBlockSeed(v3s16 p) {
218         return (u32)(params->seed & 0xFFFFFFFF) +
219                 p.Z * 38134234 +
220                 p.Y * 42123 +
221                 p.X * 23;
222 }
223
224
225 Mapgen *EmergeManager::createMapgen(std::string mgname, int mgid,
226                                                                          MapgenParams *mgparams) {
227         std::map<std::string, MapgenFactory *>::const_iterator iter;
228         iter = mglist.find(mgname);
229         if (iter == mglist.end()) {
230                 errorstream << "EmergeManager; mapgen " << mgname <<
231                  " not registered" << std::endl;
232                 return NULL;
233         }
234         
235         MapgenFactory *mgfactory = iter->second;
236         return mgfactory->createMapgen(mgid, mgparams, this);
237 }
238
239
240 MapgenParams *EmergeManager::createMapgenParams(std::string mgname) {
241         std::map<std::string, MapgenFactory *>::const_iterator iter;
242         iter = mglist.find(mgname);
243         if (iter == mglist.end()) {
244                 errorstream << "EmergeManager: mapgen " << mgname <<
245                  " not registered" << std::endl;
246                 return NULL;
247         }
248         
249         MapgenFactory *mgfactory = iter->second;
250         return mgfactory->createMapgenParams();
251 }
252
253
254 MapgenParams *EmergeManager::getParamsFromSettings(Settings *settings) {
255         std::string mg_name = settings->get("mg_name");
256         MapgenParams *mgparams = createMapgenParams(mg_name);
257         if (!mgparams)
258                 return NULL;
259         
260         mgparams->mg_name     = mg_name;
261         mgparams->seed        = settings->getU64(settings == g_settings ? "fixed_map_seed" : "seed");
262         mgparams->water_level = settings->getS16("water_level");
263         mgparams->chunksize   = settings->getS16("chunksize");
264         mgparams->flags       = settings->getFlagStr("mg_flags", flagdesc_mapgen);
265
266         if (!mgparams->readParams(settings)) {
267                 delete mgparams;
268                 return NULL;
269         }
270         return mgparams;
271 }
272
273
274 void EmergeManager::setParamsToSettings(Settings *settings) {
275         settings->set("mg_name",         params->mg_name);
276         settings->setU64("seed",         params->seed);
277         settings->setS16("water_level",  params->water_level);
278         settings->setS16("chunksize",    params->chunksize);
279         settings->setFlagStr("mg_flags", params->flags, flagdesc_mapgen);
280
281         params->writeParams(settings);
282 }
283
284
285 void EmergeManager::registerMapgen(std::string mgname, MapgenFactory *mgfactory) {
286         mglist.insert(std::make_pair(mgname, mgfactory));
287         infostream << "EmergeManager: registered mapgen " << mgname << std::endl;
288 }
289
290
291 ////////////////////////////// Emerge Thread ////////////////////////////////// 
292
293 bool EmergeThread::popBlockEmerge(v3s16 *pos, u8 *flags) {
294         std::map<v3s16, BlockEmergeData *>::iterator iter;
295         JMutexAutoLock queuelock(emerge->queuemutex);
296
297         if (blockqueue.empty())
298                 return false;
299         v3s16 p = blockqueue.front();
300         blockqueue.pop();
301         
302         *pos = p;
303         
304         iter = emerge->blocks_enqueued.find(p);
305         if (iter == emerge->blocks_enqueued.end()) 
306                 return false; //uh oh, queue and map out of sync!!
307
308         BlockEmergeData *bedata = iter->second;
309         *flags = bedata->flags;
310         
311         emerge->peer_queue_count[bedata->peer_requested]--;
312
313         delete bedata;
314         emerge->blocks_enqueued.erase(iter);
315         
316         return true;
317 }
318
319
320 bool EmergeThread::getBlockOrStartGen(v3s16 p, MapBlock **b, 
321                                                                         BlockMakeData *data, bool allow_gen) {
322         v2s16 p2d(p.X, p.Z);
323         //envlock: usually takes <=1ms, sometimes 90ms or ~400ms to acquire
324         JMutexAutoLock envlock(m_server->m_env_mutex); 
325         
326         // Load sector if it isn't loaded
327         if (map->getSectorNoGenerateNoEx(p2d) == NULL)
328                 map->loadSectorMeta(p2d);
329
330         // Attempt to load block
331         MapBlock *block = map->getBlockNoCreateNoEx(p);
332         if (!block || block->isDummy() || !block->isGenerated()) {
333                 EMERGE_DBG_OUT("not in memory, attempting to load from disk");
334                 block = map->loadBlock(p);
335         }
336
337         // If could not load and allowed to generate,
338         // start generation inside this same envlock
339         if (allow_gen && (block == NULL || !block->isGenerated())) {
340                 EMERGE_DBG_OUT("generating");
341                 *b = block;
342                 return map->initBlockMake(data, p);
343         }
344         
345         *b = block;
346         return false;
347 }
348
349
350 void *EmergeThread::Thread() {
351         ThreadStarted();
352         log_register_thread("EmergeThread" + id);
353         DSTACK(__FUNCTION_NAME);
354         BEGIN_DEBUG_EXCEPTION_HANDLER
355
356         v3s16 last_tried_pos(-32768,-32768,-32768); // For error output
357         v3s16 p;
358         u8 flags;
359         
360         map    = (ServerMap *)&(m_server->m_env->getMap());
361         emerge = m_server->m_emerge;
362         mapgen = emerge->mapgen[id];
363         enable_mapgen_debug_info = emerge->mapgen_debug_info;
364         
365         while (getRun())
366         try {
367                 if (!popBlockEmerge(&p, &flags)) {
368                         qevent.wait();
369                         continue;
370                 }
371
372                 last_tried_pos = p;
373                 if (blockpos_over_limit(p))
374                         continue;
375
376                 bool allow_generate = flags & BLOCK_EMERGE_ALLOWGEN;
377                 EMERGE_DBG_OUT("p=" PP(p) " allow_generate=" << allow_generate);
378                 
379                 /*
380                         Try to fetch block from memory or disk.
381                         If not found and asked to generate, initialize generator.
382                 */
383                 BlockMakeData data;
384                 MapBlock *block = NULL;
385                 std::map<v3s16, MapBlock *> modified_blocks;
386                 
387                 if (getBlockOrStartGen(p, &block, &data, allow_generate)) {
388                         {
389                                 ScopeProfiler sp(g_profiler, "EmergeThread: Mapgen::makeChunk", SPT_AVG);
390                                 TimeTaker t("mapgen::make_block()");
391
392                                 mapgen->makeChunk(&data);
393
394                                 if (enable_mapgen_debug_info == false)
395                                         t.stop(true); // Hide output
396                         }
397
398                         {
399                                 //envlock: usually 0ms, but can take either 30 or 400ms to acquire
400                                 JMutexAutoLock envlock(m_server->m_env_mutex); 
401                                 ScopeProfiler sp(g_profiler, "EmergeThread: after "
402                                                 "Mapgen::makeChunk (envlock)", SPT_AVG);
403
404                                 map->finishBlockMake(&data, modified_blocks);
405                                 
406                                 block = map->getBlockNoCreateNoEx(p);
407                                 if (block) {
408                                         /*
409                                                 Do some post-generate stuff
410                                         */
411                                         v3s16 minp = data.blockpos_min * MAP_BLOCKSIZE;
412                                         v3s16 maxp = data.blockpos_max * MAP_BLOCKSIZE +
413                                                                  v3s16(1,1,1) * (MAP_BLOCKSIZE - 1);
414
415                                         // Ignore map edit events, they will not need to be sent
416                                         // to anybody because the block hasn't been sent to anybody
417                                         MapEditEventAreaIgnorer 
418                                                 ign(&m_server->m_ignore_map_edit_events_area,
419                                                 VoxelArea(minp, maxp));
420                                         {  // takes about 90ms with -O1 on an e3-1230v2
421                                                 scriptapi_environment_on_generated(m_server->m_lua,
422                                                                 minp, maxp, emerge->getBlockSeed(minp));
423                                         }
424
425                                         EMERGE_DBG_OUT("ended up with: " << analyze_block(block));
426                                         
427                                         m_server->m_env->activateBlock(block, 0);
428                                 }
429                         }
430                 }
431
432                 /*
433                         Set sent status of modified blocks on clients
434                 */
435
436                 // NOTE: Server's clients are also behind the connection mutex
437                 //conlock: consistently takes 30-40ms to acquire
438                 JMutexAutoLock lock(m_server->m_con_mutex);
439                 // Add the originally fetched block to the modified list
440                 if (block)
441                         modified_blocks[p] = block;
442
443                 // Set the modified blocks unsent for all the clients
444                 for (std::map<u16, RemoteClient*>::iterator
445                          i = m_server->m_clients.begin();
446                          i != m_server->m_clients.end(); ++i) {
447                         RemoteClient *client = i->second;
448                         if (modified_blocks.size() > 0) {
449                                 // Remove block from sent history
450                                 client->SetBlocksNotSent(modified_blocks);
451                         }
452                 }
453         }
454         catch (VersionMismatchException &e) {
455                 std::ostringstream err;
456                 err << "World data version mismatch in MapBlock "<<PP(last_tried_pos)<<std::endl;
457                 err << "----"<<std::endl;
458                 err << "\""<<e.what()<<"\""<<std::endl;
459                 err << "See debug.txt."<<std::endl;
460                 err << "World probably saved by a newer version of Minetest."<<std::endl;
461                 m_server->setAsyncFatalError(err.str());
462         }
463         catch (SerializationError &e) {
464                 std::ostringstream err;
465                 err << "Invalid data in MapBlock "<<PP(last_tried_pos)<<std::endl;
466                 err << "----"<<std::endl;
467                 err << "\""<<e.what()<<"\""<<std::endl;
468                 err << "See debug.txt."<<std::endl;
469                 err << "You can ignore this using [ignore_world_load_errors = true]."<<std::endl;
470                 m_server->setAsyncFatalError(err.str());
471         }
472         
473         END_DEBUG_EXCEPTION_HANDLER(errorstream)
474         log_deregister_thread();
475         return NULL;
476 }