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