3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
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.
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.
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.
25 #include "clientserver.h"
27 #include "jmutexautolock.h"
29 #include "constants.h"
33 #include "serverobject.h"
36 #include "scriptapi.h"
42 #include "mapgen_v6.h"
43 #include "mapgen_v7.h"
44 #include "mapgen_indev.h"
45 #include "mapgen_singlenode.h"
48 /////////////////////////////// Emerge Manager ////////////////////////////////
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());
57 this->ndef = gamedef->getNodeDefManager();
58 this->biomedef = new BiomeDefManager();
61 mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
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;
71 nthreads = g_settings->getU16("num_emerge_threads");
76 qlimit_total = g_settings->getU16("emergequeue_limit_total");
77 qlimit_diskonly = g_settings->get("emergequeue_limit_diskonly").empty() ?
79 g_settings->getU16("emergequeue_limit_diskonly");
80 qlimit_generate = g_settings->get("emergequeue_limit_generate").empty() ?
82 g_settings->getU16("emergequeue_limit_generate");
84 for (int i = 0; i != nthreads; i++)
85 emergethread.push_back(new EmergeThread((Server *)gamedef, i));
87 infostream << "EmergeManager: using " << nthreads << " threads" << std::endl;
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];
102 for (unsigned int i = 0; i < ores.size(); i++)
106 for (std::map<std::string, MapgenFactory *>::iterator iter = mglist.begin();
107 iter != mglist.end(); iter ++) {
116 void EmergeManager::initMapgens(MapgenParams *mgparams) {
122 biomedef->resolveNodeNames(ndef);
124 this->params = mgparams;
125 for (unsigned int i = 0; i != emergethread.size(); i++) {
126 mg = createMapgen(params->mg_name, 0, params);
128 infostream << "EmergeManager: falling back to mapgen v6" << std::endl;
130 params = createMapgenParams("v6");
131 mg = createMapgen("v6", 0, params);
133 mapgen.push_back(mg);
138 bool EmergeManager::enqueueBlockEmerge(u16 peer_id, v3s16 p, bool allow_generate) {
139 std::map<v3s16, BlockEmergeData *>::const_iterator iter;
140 BlockEmergeData *bedata;
146 flags |= BLOCK_EMERGE_ALLOWGEN;
149 JMutexAutoLock queuelock(queuemutex);
151 count = blocks_enqueued.size();
152 if (count >= qlimit_total)
155 count = peer_queue_count[peer_id];
156 u16 qlimit_peer = allow_generate ? qlimit_generate : qlimit_diskonly;
157 if (count >= qlimit_peer)
160 iter = blocks_enqueued.find(p);
161 if (iter != blocks_enqueued.end()) {
162 bedata = iter->second;
163 bedata->flags |= flags;
167 bedata = new BlockEmergeData;
168 bedata->flags = flags;
169 bedata->peer_requested = peer_id;
170 blocks_enqueued.insert(std::make_pair(p, bedata));
172 peer_queue_count[peer_id] = count + 1;
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) {
180 lowestitems = nitems;
184 emergethread[idx]->blockqueue.push(p);
186 emergethread[idx]->qevent.signal();
192 int EmergeManager::getGroundLevelAtPoint(v2s16 p) {
193 if (mapgen.size() == 0 || !mapgen[0]) {
194 errorstream << "EmergeManager: getGroundLevelAtPoint() called"
195 " before mapgen initialized" << std::endl;
199 return mapgen[0]->getGroundLevelAtPoint(p);
203 bool EmergeManager::isBlockUnderground(v3s16 blockpos) {
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);
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;
217 u32 EmergeManager::getBlockSeed(v3s16 p) {
218 return (u32)(params->seed & 0xFFFFFFFF) +
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;
235 MapgenFactory *mgfactory = iter->second;
236 return mgfactory->createMapgen(mgid, mgparams, this);
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;
249 MapgenFactory *mgfactory = iter->second;
250 return mgfactory->createMapgenParams();
254 MapgenParams *EmergeManager::getParamsFromSettings(Settings *settings) {
255 std::string mg_name = settings->get("mg_name");
256 MapgenParams *mgparams = createMapgenParams(mg_name);
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);
266 if (!mgparams->readParams(settings)) {
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);
281 params->writeParams(settings);
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;
291 ////////////////////////////// Emerge Thread //////////////////////////////////
293 bool EmergeThread::popBlockEmerge(v3s16 *pos, u8 *flags) {
294 std::map<v3s16, BlockEmergeData *>::iterator iter;
295 JMutexAutoLock queuelock(emerge->queuemutex);
297 if (blockqueue.empty())
299 v3s16 p = blockqueue.front();
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!!
308 BlockEmergeData *bedata = iter->second;
309 *flags = bedata->flags;
311 emerge->peer_queue_count[bedata->peer_requested]--;
314 emerge->blocks_enqueued.erase(iter);
320 bool EmergeThread::getBlockOrStartGen(v3s16 p, MapBlock **b,
321 BlockMakeData *data, bool allow_gen) {
323 //envlock: usually takes <=1ms, sometimes 90ms or ~400ms to acquire
324 JMutexAutoLock envlock(m_server->m_env_mutex);
326 // Load sector if it isn't loaded
327 if (map->getSectorNoGenerateNoEx(p2d) == NULL)
328 map->loadSectorMeta(p2d);
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);
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");
342 return map->initBlockMake(data, p);
350 void *EmergeThread::Thread() {
352 log_register_thread("EmergeThread" + id);
353 DSTACK(__FUNCTION_NAME);
354 BEGIN_DEBUG_EXCEPTION_HANDLER
356 v3s16 last_tried_pos(-32768,-32768,-32768); // For error output
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;
367 if (!popBlockEmerge(&p, &flags)) {
373 if (blockpos_over_limit(p))
376 bool allow_generate = flags & BLOCK_EMERGE_ALLOWGEN;
377 EMERGE_DBG_OUT("p=" PP(p) " allow_generate=" << allow_generate);
380 Try to fetch block from memory or disk.
381 If not found and asked to generate, initialize generator.
384 MapBlock *block = NULL;
385 std::map<v3s16, MapBlock *> modified_blocks;
387 if (getBlockOrStartGen(p, &block, &data, allow_generate)) {
389 ScopeProfiler sp(g_profiler, "EmergeThread: Mapgen::makeChunk", SPT_AVG);
390 TimeTaker t("mapgen::make_block()");
392 mapgen->makeChunk(&data);
394 if (enable_mapgen_debug_info == false)
395 t.stop(true); // Hide output
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);
404 map->finishBlockMake(&data, modified_blocks);
406 block = map->getBlockNoCreateNoEx(p);
409 Do some post-generate stuff
411 v3s16 minp = data.blockpos_min * MAP_BLOCKSIZE;
412 v3s16 maxp = data.blockpos_max * MAP_BLOCKSIZE +
413 v3s16(1,1,1) * (MAP_BLOCKSIZE - 1);
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));
425 EMERGE_DBG_OUT("ended up with: " << analyze_block(block));
427 m_server->m_env->activateBlock(block, 0);
433 Set sent status of modified blocks on clients
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
441 modified_blocks[p] = block;
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);
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());
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());
473 END_DEBUG_EXCEPTION_HANDLER(errorstream)
474 log_deregister_thread();