]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/map.cpp
end-of-day.
[dragonfireclient.git] / src / map.cpp
index 0b5872e05e3c53cae49f28ba74fde447333fd15f..8465813054098cf0e5001363832dbdda17473d69 100644 (file)
@@ -25,6 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "utility.h"
 #include "voxel.h"
 #include "porting.h"
+#include "mineral.h"
 
 /*
        Map
@@ -66,10 +67,8 @@ Map::~Map()
        }
 }
 
-MapSector * Map::getSectorNoGenerate(v2s16 p)
+MapSector * Map::getSectorNoGenerateNoExNoLock(v2s16 p)
 {
-       JMutexAutoLock lock(m_sector_mutex);
-
        if(m_sector_cache != NULL && p == m_sector_cache_p){
                MapSector * sector = m_sector_cache;
                // Reset inactivity timer
@@ -78,11 +77,9 @@ MapSector * Map::getSectorNoGenerate(v2s16 p)
        }
        
        core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p);
-       // If sector doesn't exist, throw an exception
+       
        if(n == NULL)
-       {
-               throw InvalidPositionException();
-       }
+               return NULL;
        
        MapSector *sector = n->getValue();
        
@@ -90,13 +87,27 @@ MapSector * Map::getSectorNoGenerate(v2s16 p)
        m_sector_cache_p = p;
        m_sector_cache = sector;
 
-       //MapSector * ref(sector);
-       
        // Reset inactivity timer
        sector->usage_timer = 0.0;
        return sector;
 }
 
+MapSector * Map::getSectorNoGenerateNoEx(v2s16 p)
+{
+       JMutexAutoLock lock(m_sector_mutex);
+
+       return getSectorNoGenerateNoExNoLock(p);
+}
+
+MapSector * Map::getSectorNoGenerate(v2s16 p)
+{
+       MapSector *sector = getSectorNoGenerateNoEx(p);
+       if(sector == NULL)
+               throw InvalidPositionException();
+       
+       return sector;
+}
+
 MapBlock * Map::getBlockNoCreate(v3s16 p3d)
 {      
        v2s16 p2d(p3d.X, p3d.Z);
@@ -122,6 +133,18 @@ MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d)
        }
 }
 
+/*MapBlock * Map::getBlockCreate(v3s16 p3d)
+{
+       v2s16 p2d(p3d.X, p3d.Z);
+       MapSector * sector = getSectorCreate(p2d);
+       assert(sector);
+       MapBlock *block = sector->getBlockNoCreate(p3d.Y);
+       if(block)
+               return block;
+       block = sector->createBlankBlock(p3d.Y);
+       return block;
+}*/
+
 f32 Map::getGroundHeight(v2s16 p, bool generate)
 {
        try{
@@ -627,9 +650,10 @@ void Map::updateLighting(enum LightBank bank,
        //TimeTaker timer("updateLighting");
        
        // For debugging
-       bool debug=true;
-
-       u32 count_was = modified_blocks.size();
+       //bool debug=true;
+       //u32 count_was = modified_blocks.size();
+       
+       core::map<v3s16, MapBlock*> blocks_to_update;
 
        core::map<v3s16, bool> light_sources;
        
@@ -650,6 +674,8 @@ void Map::updateLighting(enum LightBank bank,
                        v3s16 pos = block->getPos();
                        modified_blocks.insert(pos, block);
 
+                       blocks_to_update.insert(pos, block);
+
                        /*
                                Clear all light from block
                        */
@@ -699,10 +725,12 @@ void Map::updateLighting(enum LightBank bank,
                        }
                        else if(bank == LIGHTBANK_NIGHT)
                        {
+                               // For night lighting, sunlight is not propagated
                                break;
                        }
                        else
                        {
+                               // Invalid lighting bank
                                assert(0);
                        }
                                
@@ -710,7 +738,7 @@ void Map::updateLighting(enum LightBank bank,
                                        <<pos.X<<","<<pos.Y<<","<<pos.Z<<") not valid"
                                        <<std::endl;*/
 
-                       // Else get the block below and loop to it
+                       // Bottom sunlight is not valid; get the block and loop to it
 
                        pos.Y--;
                        try{
@@ -737,13 +765,6 @@ void Map::updateLighting(enum LightBank bank,
                dstream<<"unspreadLight modified "<<diff<<std::endl;
        }
 
-       // TODO: Spread light from propagated sunlight?
-       // Yes, add it to light_sources... somehow.
-       // It has to be added at somewhere above, in the loop.
-       // TODO
-       // NOTE: This actually works fine without doing so
-       //       - Find out why it works
-
        {
                TimeTaker timer("spreadLight");
                spreadLight(bank, light_sources, modified_blocks);
@@ -759,17 +780,44 @@ void Map::updateLighting(enum LightBank bank,
        
        {
                //MapVoxelManipulator vmanip(this);
-
-               ManualMapVoxelManipulator vmanip(this);
                
+               // Make a manual voxel manipulator and load all the blocks
+               // that touch the requested blocks
+               ManualMapVoxelManipulator vmanip(this);
                core::map<v3s16, MapBlock*>::Iterator i;
-               i = a_blocks.getIterator();
+               i = blocks_to_update.getIterator();
                for(; i.atEnd() == false; i++)
                {
                        MapBlock *block = i.getNode()->getValue();
                        v3s16 p = block->getPos();
+                       
+                       // Add all surrounding blocks
                        vmanip.initialEmerge(p - v3s16(1,1,1), p + v3s16(1,1,1));
+
+                       /*
+                               Add all surrounding blocks that have up-to-date lighting
+                               NOTE: This doesn't quite do the job (not everything
+                                     appropriate is lighted)
+                       */
+                       /*for(s16 z=-1; z<=1; z++)
+                       for(s16 y=-1; y<=1; y++)
+                       for(s16 x=-1; x<=1; x++)
+                       {
+                               v3s16 p(x,y,z);
+                               MapBlock *block = getBlockNoCreateNoEx(p);
+                               if(block == NULL)
+                                       continue;
+                               if(block->isDummy())
+                                       continue;
+                               if(block->getLightingExpired())
+                                       continue;
+                               vmanip.initialEmerge(p, p);
+                       }*/
+                       
+                       // Lighting of block will be updated completely
+                       block->setLightingExpired(false);
                }
+
                {
                        //TimeTaker timer("unSpreadLight");
                        vmanip.unspreadLight(bank, unlight_from, light_sources);
@@ -1407,6 +1455,8 @@ void Map::transformLiquids(core::map<v3s16, MapBlock*> & modified_blocks)
        u32 loopcount = 0;
        u32 initial_size = m_transforming_liquid.size();
 
+       //dstream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;
+
        while(m_transforming_liquid.size() != 0)
        {
                /*
@@ -1682,6 +1732,13 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
        Map(dout_server),
        m_heightmap(NULL)
 {
+       
+       //m_chunksize = 64;
+       //m_chunksize = 16;
+       m_chunksize = 8;
+       //m_chunksize = 4;
+       //m_chunksize = 2;
+
        /*
                Experimental and debug stuff
        */
@@ -1692,9 +1749,10 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
                PointAttributeList *list_baseheight = m_padb.getList("hm_baseheight");
                PointAttributeList *list_randmax = m_padb.getList("hm_randmax");
                PointAttributeList *list_randfactor = m_padb.getList("hm_randfactor");
-               PointAttributeList *list_plants_amount = m_padb.getList("plants_amount");
-               PointAttributeList *list_caves_amount = m_padb.getList("caves_amount");
+               //PointAttributeList *list_plants_amount = m_padb.getList("plants_amount");
+               //PointAttributeList *list_caves_amount = m_padb.getList("caves_amount");
 
+#if 0
                /*
                        NOTE: BEWARE: Too big amount of these will make map generation
                        slow. Especially those that are read by every block emerge.
@@ -1705,13 +1763,13 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
                        15000 points: 40ms
                */
                
-               for(u32 i=0; i<5000; i++)
+               for(u32 i=0; i<500; i++)
                {
                        /*u32 lim = MAP_GENERATION_LIMIT;
                        if(i < 400)
                                lim = 2000;*/
 
-                       u32 lim = 1000 + MAP_GENERATION_LIMIT * i / 5000;
+                       u32 lim = 500 + MAP_GENERATION_LIMIT * i / 500;
 
                        v3s16 p(
                                -lim + myrand()%(lim*2),
@@ -1744,13 +1802,13 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
                        list_plants_amount->addPoint(p, Attribute(plants_amount));
                }
 
-               for(u32 i=0; i<1000; i++)
+               for(u32 i=0; i<500; i++)
                {
                        /*u32 lim = MAP_GENERATION_LIMIT;
                        if(i < 400)
                                lim = 2000;*/
 
-                       u32 lim = 500 + MAP_GENERATION_LIMIT * i / 1000;
+                       u32 lim = 500 + MAP_GENERATION_LIMIT * i / 500;
 
                        v3s16 p(
                                -lim + myrand()%(lim*2),
@@ -1775,13 +1833,13 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
                        list_caves_amount->addPoint(p, Attribute(caves_amount));
                }
                
-               for(u32 i=0; i<5000; i++)
+               for(u32 i=0; i<500; i++)
                {
                        /*u32 lim = MAP_GENERATION_LIMIT;
                        if(i < 400)
                                lim = 2000;*/
 
-                       u32 lim = 1000 + MAP_GENERATION_LIMIT * i / 5000;
+                       u32 lim = 500 + MAP_GENERATION_LIMIT * i / 500;
 
                        v3s16 p(
                                -lim + (myrand()%(lim*2)),
@@ -1835,25 +1893,37 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
                                randfactor = 0.5;
                        }*/
                        
-                       baseheight = 0;
-                       randmax = 15;
-                       randfactor = 0.63;
+                       if(myrand()%3 < 2)
+                       {
+                               baseheight = 10;
+                               randmax = 30;
+                               randfactor = 0.7;
+                       }
+                       else
+                       {
+                               baseheight = 0;
+                               randmax = 15;
+                               randfactor = 0.63;
+                       }
 
                        list_baseheight->addPoint(p, Attribute(baseheight));
                        list_randmax->addPoint(p, Attribute(randmax));
                        list_randfactor->addPoint(p, Attribute(randfactor));
                }
-
-               /*list_baseheight->addPoint(v3s16(0,0,0), Attribute(5));
-               list_randmax->addPoint(v3s16(0,0,0), Attribute(20));
-               list_randfactor->addPoint(v3s16(0,0,0), Attribute(0.6));*/
+#endif
+               
+               // Add only one entry
+               list_baseheight->addPoint(v3s16(0,0,0), Attribute(0));
+               list_randmax->addPoint(v3s16(0,0,0), Attribute(22));
+               //list_randmax->addPoint(v3s16(0,0,0), Attribute(0));
+               list_randfactor->addPoint(v3s16(0,0,0), Attribute(0.45));
 
                // Easy spawn point
                /*list_baseheight->addPoint(v3s16(0,0,0), Attribute(0));
                list_randmax->addPoint(v3s16(0,0,0), Attribute(10));
                list_randfactor->addPoint(v3s16(0,0,0), Attribute(0.65));*/
        }
-
+       
        /*
                Try to load map; if not found, create a new one.
        */
@@ -1908,18 +1978,6 @@ ServerMap::ServerMap(std::string savedir, HMParams hmp, MapParams mp):
        dstream<<DTIME<<"Initializing new map."<<std::endl;
        
        // Create master heightmap
-       /*ValueGenerator *maxgen =
-                       ValueGenerator::deSerialize(hmp.randmax);
-       ValueGenerator *factorgen =
-                       ValueGenerator::deSerialize(hmp.randfactor);
-       ValueGenerator *basegen =
-                       ValueGenerator::deSerialize(hmp.base);
-       m_heightmap = new UnlimitedHeightmap
-                       (hmp.blocksize, maxgen, factorgen, basegen, &m_padb);*/
-
-       /*m_heightmap = new UnlimitedHeightmap
-                       (hmp.blocksize, &m_padb);*/
-
        m_heightmap = new UnlimitedHeightmap
                        (32, &m_padb);
        
@@ -1957,326 +2015,1429 @@ ServerMap::~ServerMap()
        
        if(m_heightmap != NULL)
                delete m_heightmap;
+       
+       /*
+               Free all MapChunks
+       */
+       core::map<v2s16, MapChunk*>::Iterator i = m_chunks.getIterator();
+       for(; i.atEnd() == false; i++)
+       {
+               MapChunk *chunk = i.getNode()->getValue();
+               delete chunk;
+       }
 }
 
-MapSector * ServerMap::emergeSector(v2s16 p2d)
+/*
+       Some helper functions
+*/
+
+s16 find_ground_level(VoxelManipulator &vmanip, v2s16 p2d)
 {
-       DSTACK("%s: p2d=(%d,%d)",
-                       __FUNCTION_NAME,
-                       p2d.X, p2d.Y);
-       // Check that it doesn't exist already
-       try{
-               return getSectorNoGenerate(p2d);
+       v3s16 em = vmanip.m_area.getExtent();
+       s16 y_nodes_max = vmanip.m_area.MaxEdge.Y;
+       s16 y_nodes_min = vmanip.m_area.MinEdge.Y;
+       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y));
+       s16 y;
+       for(y=y_nodes_max; y>=y_nodes_min; y--)
+       {
+               MapNode &n = vmanip.m_data[i];
+               if(content_walkable(n.d))
+                       break;
+                       
+               vmanip.m_area.add_y(em, i, -1);
        }
-       catch(InvalidPositionException &e)
+       if(y >= y_nodes_min)
+               return y;
+       else
+               return y_nodes_min;
+}
+
+void make_tree(VoxelManipulator &vmanip, v3s16 p0)
+{
+       MapNode treenode(CONTENT_TREE);
+       MapNode leavesnode(CONTENT_LEAVES);
+
+       s16 trunk_h = myrand_range(2, 6);
+       v3s16 p1 = p0;
+       for(s16 ii=0; ii<trunk_h; ii++)
        {
+               if(vmanip.m_area.contains(p1))
+                       vmanip.m_data[vmanip.m_area.index(p1)] = treenode;
+               p1.Y++;
        }
        
-       /*
-               Try to load the sector from disk.
-       */
-       if(loadSectorFull(p2d) == true)
+       // p1 is now the last piece of the trunk
+       p1.Y -= 1;
+
+       VoxelArea leaves_a(v3s16(-2,-2,-2), v3s16(2,2,2));
+       SharedPtr<u8> leaves_d(new u8[leaves_a.getVolume()]);
+       for(s32 i=0; i<leaves_a.getVolume(); i++)
+               leaves_d[i] = 0;
+       
+       // Force leaves at near the end of the trunk
        {
-               return getSectorNoGenerate(p2d);
+               s16 d = 1;
+               for(s16 z=-d; z<=d; z++)
+               for(s16 y=-d; y<=d; y++)
+               for(s16 x=-d; x<=d; x++)
+               {
+                       leaves_d[leaves_a.index(v3s16(x,y,z))] = 1;
+               }
        }
+       
+       // Add leaves randomly
+       for(u32 iii=0; iii<7; iii++)
+       {
+               s16 d = 1;
 
-       /*
-               If there is no master heightmap, throw.
-       */
-       if(m_heightmap == NULL)
+               v3s16 p(
+                       myrand_range(leaves_a.MinEdge.X, leaves_a.MaxEdge.X-d),
+                       myrand_range(leaves_a.MinEdge.Y, leaves_a.MaxEdge.Y-d),
+                       myrand_range(leaves_a.MinEdge.Z, leaves_a.MaxEdge.Z-d)
+               );
+               
+               for(s16 z=0; z<=d; z++)
+               for(s16 y=0; y<=d; y++)
+               for(s16 x=0; x<=d; x++)
+               {
+                       leaves_d[leaves_a.index(p+v3s16(x,y,z))] = 1;
+               }
+       }
+       
+       // Blit leaves to vmanip
+       for(s16 z=leaves_a.MinEdge.Z; z<=leaves_a.MaxEdge.Z; z++)
+       for(s16 y=leaves_a.MinEdge.Y; y<=leaves_a.MaxEdge.Y; y++)
+       for(s16 x=leaves_a.MinEdge.X; x<=leaves_a.MaxEdge.X; x++)
        {
-               throw InvalidPositionException("emergeSector(): no heightmap");
+               v3s16 p(x,y,z);
+               p += p1;
+               if(vmanip.m_area.contains(p) == false)
+                       continue;
+               u32 vi = vmanip.m_area.index(p);
+               if(vmanip.m_data[vi].d != CONTENT_AIR)
+                       continue;
+               u32 i = leaves_a.index(x,y,z);
+               if(leaves_d[i] == 1)
+                       vmanip.m_data[vi] = leavesnode;
        }
+}
 
+MapChunk* ServerMap::generateChunkRaw(v2s16 chunkpos,
+               core::map<v3s16, MapBlock*> &changed_blocks)
+{
        /*
-               Do not generate over-limit
-       */
-       if(p2d.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-       || p2d.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-       || p2d.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-       || p2d.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
-               throw InvalidPositionException("emergeSector(): pos. over limit");
-
-       /*
-               Generate sector and heightmaps
+               Don't generate if already fully generated
        */
-       
-       // Number of heightmaps in sector in each direction
-       u16 hm_split = SECTOR_HEIGHTMAP_SPLIT;
-
-       // Heightmap side width
-       s16 hm_d = MAP_BLOCKSIZE / hm_split;
+       {
+               MapChunk *chunk = getChunk(chunkpos);
+               if(chunk != NULL && chunk->getGenLevel() == GENERATED_FULLY)
+               {
+                       dstream<<"generateChunkRaw(): Chunk "
+                                       <<"("<<chunkpos.X<<","<<chunkpos.Y<<")"
+                                       <<" already generated"<<std::endl;
+                       return chunk;
+               }
+       }
 
-       ServerMapSector *sector = new ServerMapSector(this, p2d, hm_split);
+       dstream<<"generateChunkRaw(): Generating chunk "
+                       <<"("<<chunkpos.X<<","<<chunkpos.Y<<")"
+                       <<std::endl;
        
-       // Sector position on map in nodes
-       v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
-
-       /*dstream<<"Generating sector ("<<p2d.X<<","<<p2d.Y<<")"
-                       " heightmaps and objects"<<std::endl;*/
+       TimeTaker timer("generateChunkRaw()");
        
-       /*
-               Calculate some information about local properties
-       */
+       // The distance how far into the neighbors the generator is allowed to go
+       s16 max_spread_amount_sectors = 2;
+       assert(max_spread_amount_sectors <= m_chunksize);
+       s16 max_spread_amount = max_spread_amount_sectors * MAP_BLOCKSIZE;
+       // Minimum amount of space left on sides for mud to fall in
+       s16 min_mud_fall_space = 2;
+       // Maximum diameter of stone obstacles in X and Z
+       s16 stone_obstacle_max_size = (max_spread_amount-min_mud_fall_space)*2;
+       assert(stone_obstacle_max_size/2 <= max_spread_amount-min_mud_fall_space);
        
-       v2s16 mhm_p = p2d * hm_split;
-       f32 corners[4] = {
-               m_heightmap->getGroundHeight(mhm_p+v2s16(0,0)*hm_split),
-               m_heightmap->getGroundHeight(mhm_p+v2s16(1,0)*hm_split),
-               m_heightmap->getGroundHeight(mhm_p+v2s16(1,1)*hm_split),
-               m_heightmap->getGroundHeight(mhm_p+v2s16(0,1)*hm_split),
-       };
+       s16 y_blocks_min = -4;
+       s16 y_blocks_max = 3;
+       s16 h_blocks = y_blocks_max - y_blocks_min + 1;
+       s16 y_nodes_min = y_blocks_min * MAP_BLOCKSIZE;
+       s16 y_nodes_max = y_blocks_max * MAP_BLOCKSIZE + MAP_BLOCKSIZE - 1;
+
+       v2s16 sectorpos_base = chunk_to_sector(chunkpos);
+       s16 sectorpos_base_size = m_chunksize;
+
+       /*v2s16 sectorpos_bigbase = chunk_to_sector(chunkpos - v2s16(1,1));
+       s16 sectorpos_bigbase_size = m_chunksize * 3;*/
+       v2s16 sectorpos_bigbase =
+                       sectorpos_base - v2s16(1,1) * max_spread_amount_sectors;
+       s16 sectorpos_bigbase_size =
+                       sectorpos_base_size + 2 * max_spread_amount_sectors;
+
+       v3s16 bigarea_blocks_min(
+               sectorpos_bigbase.X,
+               y_blocks_min,
+               sectorpos_bigbase.Y
+       );
+
+       v3s16 bigarea_blocks_max(
+               sectorpos_bigbase.X + sectorpos_bigbase_size - 1,
+               y_blocks_max,
+               sectorpos_bigbase.Y + sectorpos_bigbase_size - 1
+       );
        
-       float avgheight = (corners[0]+corners[1]+corners[2]+corners[3])/4.0;
-       float avgslope = 0.0;
-       avgslope += fabs(avgheight - corners[0]);
-       avgslope += fabs(avgheight - corners[1]);
-       avgslope += fabs(avgheight - corners[2]);
-       avgslope += fabs(avgheight - corners[3]);
-       avgslope /= 4.0;
-       avgslope /= MAP_BLOCKSIZE;
-       //dstream<<"avgslope="<<avgslope<<std::endl;
-
-       float pitness = 0.0;
-       v2f32 a;
-       a = m_heightmap->getSlope(p2d+v2s16(0,0));
-       pitness += -a.X;
-       pitness += -a.Y;
-       a = m_heightmap->getSlope(p2d+v2s16(0,1));
-       pitness += -a.X;
-       pitness += a.Y;
-       a = m_heightmap->getSlope(p2d+v2s16(1,1));
-       pitness += a.X;
-       pitness += a.Y;
-       a = m_heightmap->getSlope(p2d+v2s16(1,0));
-       pitness += a.X;
-       pitness += -a.Y;
-       pitness /= 4.0;
-       pitness /= MAP_BLOCKSIZE;
-       //dstream<<"pitness="<<pitness<<std::endl;
-
+       // Relative values to control amount of stuff in one chunk
+       u32 relative_area = (u32)sectorpos_base_size*MAP_BLOCKSIZE
+                       *(u32)sectorpos_base_size*MAP_BLOCKSIZE;
+       u32 relative_volume = (u32)sectorpos_base_size*MAP_BLOCKSIZE
+                       *(u32)sectorpos_base_size*MAP_BLOCKSIZE
+                       *(u32)h_blocks*MAP_BLOCKSIZE;
+               
        /*
-               Get local attributes
+               Create the whole area of this and the neighboring chunks
        */
-       
-       float local_plants_amount = 0.0;
        {
-               //dstream<<"emergeSector(): Reading point attribute lists"<<std::endl;
-               //TimeTaker attrtimer("emergeSector() attribute fetch");
+               TimeTaker timer("generateChunkRaw() create area");
                
-               // Get plant amount from attributes
-               PointAttributeList *palist = m_padb.getList("plants_amount");
-               assert(palist);
-               /*local_plants_amount =
-                               palist->getNearAttr(nodepos2d).getFloat();*/
-               local_plants_amount =
-                               palist->getInterpolatedFloat(nodepos2d);
-       }
-
-       /*
-               Generate sector heightmap
-       */
+               for(s16 x=0; x<sectorpos_bigbase_size; x++)
+               for(s16 z=0; z<sectorpos_bigbase_size; z++)
+               {
+                       v2s16 sectorpos = sectorpos_bigbase + v2s16(x,z);
+                       ServerMapSector *sector = createSector(sectorpos);
+                       assert(sector);
 
-       // Loop through sub-heightmaps
-       for(s16 y=0; y<hm_split; y++)
-       for(s16 x=0; x<hm_split; x++)
-       {
-               v2s16 p_in_sector = v2s16(x,y);
-               v2s16 mhm_p = p2d * hm_split + p_in_sector;
-               f32 corners[4] = {
-                       m_heightmap->getGroundHeight(mhm_p+v2s16(0,0)),
-                       m_heightmap->getGroundHeight(mhm_p+v2s16(1,0)),
-                       m_heightmap->getGroundHeight(mhm_p+v2s16(1,1)),
-                       m_heightmap->getGroundHeight(mhm_p+v2s16(0,1)),
-               };
+                       for(s16 y=y_blocks_min; y<=y_blocks_max; y++)
+                       {
+                               v3s16 blockpos(sectorpos.X, y, sectorpos.Y);
+                               MapBlock *block = createBlock(blockpos);
 
-               /*dstream<<"p_in_sector=("<<p_in_sector.X<<","<<p_in_sector.Y<<")"
-                               <<" mhm_p=("<<mhm_p.X<<","<<mhm_p.Y<<")"
-                               <<std::endl;*/
+                               // Lighting won't be calculated
+                               //block->setLightingExpired(true);
+                               // Lighting will be calculated
+                               block->setLightingExpired(false);
 
-               FixedHeightmap *hm = new FixedHeightmap(&m_hwrapper,
-                               mhm_p, hm_d);
-               sector->setHeightmap(p_in_sector, hm);
+                               /*
+                                       Block gets sunlight if this is true.
 
-               //TODO: Make these values configurable
-               //hm->generateContinued(0.0, 0.0, corners);
-               //hm->generateContinued(0.25, 0.2, corners);
-               //hm->generateContinued(0.5, 0.2, corners);
-               //hm->generateContinued(1.0, 0.2, corners);
-               //hm->generateContinued(2.0, 0.2, corners);
-               //hm->generateContinued(2.0 * avgslope, 0.5, corners);
-               hm->generateContinued(avgslope * MAP_BLOCKSIZE/8, 0.5, corners);
+                                       This should be set to true when the top side of a block
+                                       is completely exposed to the sky.
 
-               //hm->print();
+                                       Actually this doesn't matter now because the
+                                       initial lighting is done here.
+                               */
+                               block->setIsUnderground(y != y_blocks_max);
+                       }
+               }
        }
 
        /*
-               Generate objects
+               Now we have a big empty area.
+
+               Make a ManualMapVoxelManipulator that contains this and the
+               neighboring chunks
        */
-       
-       core::map<v3s16, u8> *objects = new core::map<v3s16, u8>;
-       sector->setObjects(objects);
 
-       float area = MAP_BLOCKSIZE * MAP_BLOCKSIZE;
+       ManualMapVoxelManipulator vmanip(this);
+       // Add the area we just generated
+       {
+               TimeTaker timer("generateChunkRaw() initialEmerge");
+               vmanip.initialEmerge(bigarea_blocks_min, bigarea_blocks_max);
+       }
+
+       TimeTaker timer_generate("generateChunkRaw() generate");
 
        /*
-               Plant some trees if there is not much slope
+               Generate general ground level to full area
        */
+       
        {
-               // Avgslope is the derivative of a hill
-               //float t = avgslope * avgslope;
-               float t = avgslope;
-               float a = area/16 * m_params.plants_amount * local_plants_amount;
-               u32 tree_max;
-               //float something = 0.17*0.17;
-               float something = 0.3;
-               if(t > something)
-                       tree_max = a / (t/something);
-               else
-                       tree_max = a;
+       // 22ms @cs=8
+       //TimeTaker timer1("ground level");
+
+       for(s16 x=0; x<sectorpos_bigbase_size*MAP_BLOCKSIZE; x++)
+       for(s16 z=0; z<sectorpos_bigbase_size*MAP_BLOCKSIZE; z++)
+       {
+               // Node position
+               v2s16 p2d = sectorpos_bigbase*MAP_BLOCKSIZE + v2s16(x,z);
                
-               u32 count = (myrand()%(tree_max+1));
-               //u32 count = tree_max;
-               for(u32 i=0; i<count; i++)
+               /*
+                       Skip of already generated
+               */
                {
-                       s16 x = (myrand()%(MAP_BLOCKSIZE-2))+1;
-                       s16 z = (myrand()%(MAP_BLOCKSIZE-2))+1;
-                       s16 y = sector->getGroundHeight(v2s16(x,z))+1;
-                       if(y < WATER_LEVEL)
+                       v3s16 p(p2d.X, y_nodes_min, p2d.Y);
+                       if(vmanip.m_data[vmanip.m_area.index(p)].d != CONTENT_AIR)
                                continue;
-                       objects->insert(v3s16(x, y, z),
-                                       SECTOR_OBJECT_TREE_1);
                }
-       }
-       /*
-               Plant some bushes if sector is pit-like
-       */
-       {
-               // Pitness usually goes at around -0.5...0.5
-               u32 bush_max = 0;
-               u32 a = area/16 * 3.0 * m_params.plants_amount * local_plants_amount;
-               if(pitness > 0)
-                       bush_max = (pitness*a*4);
-               if(bush_max > a)
-                       bush_max = a;
-               u32 count = (myrand()%(bush_max+1));
-               for(u32 i=0; i<count; i++)
+
+               // Ground height at this point
+               float surface_y_f = 0.0;
+               /*
+                       A hack to get the ground height from the sector.
+                       Do this better.
+               */
                {
-                       s16 x = myrand()%(MAP_BLOCKSIZE-0)+0;
-                       s16 z = myrand()%(MAP_BLOCKSIZE-0)+0;
-                       s16 y = sector->getGroundHeight(v2s16(x,z))+1;
-                       if(y < WATER_LEVEL)
-                               continue;
-                       objects->insert(v3s16(x, y, z),
-                                       SECTOR_OBJECT_BUSH_1);
+                       v2s16 sectorpos = getContainerPos(p2d, MAP_BLOCKSIZE);
+                       v2s16 sector_relpos = p2d - sectorpos*MAP_BLOCKSIZE;
+                       MapSector *sector = getSectorNoGenerate(sectorpos);
+                       assert(sector);
+                       float h = sector->getGroundHeight(sector_relpos);
+                       if(h > GROUNDHEIGHT_VALID_MINVALUE)
+                               surface_y_f = h;
+                       else
+                               dstream<<"WARNING: "<<__FUNCTION_NAME
+                               <<": sector->getGroundHeight returned bad height"<<std::endl;
                }
-       }
-       /*
-               Add ravine (randomly)
-       */
-       if(m_params.ravines_amount > 0.001)
-       {
-               if(myrand()%(s32)(200.0 / m_params.ravines_amount) == 0)
+               // Convert to integer
+               s16 surface_y = (s16)surface_y_f;
+
+               /*
+                       Fill ground with stone
+               */
                {
-                       s16 s = 6;
-                       s16 x = myrand()%(MAP_BLOCKSIZE-s*2-1)+s;
-                       s16 z = myrand()%(MAP_BLOCKSIZE-s*2-1)+s;
-                       /*s16 x = 8;
-                       s16 z = 8;*/
-                       s16 y = sector->getGroundHeight(v2s16(x,z))+1;
-                       objects->insert(v3s16(x, y, z),
-                                       SECTOR_OBJECT_RAVINE);
+                       // Use fast index incrementing
+                       v3s16 em = vmanip.m_area.getExtent();
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_min, p2d.Y));
+                       for(s16 y=y_nodes_min; y<surface_y && y<=y_nodes_max; y++)
+                       {
+                               vmanip.m_data[i].d = CONTENT_STONE;
+
+                               vmanip.m_area.add_y(em, i, 1);
+                       }
                }
        }
+       
+       }//timer1
 
        /*
-               Insert to container
+               Randomize some parameters
        */
-       JMutexAutoLock lock(m_sector_mutex);
-       m_sectors.insert(p2d, sector);
-       
-       return sector;
-}
 
-MapBlock * ServerMap::emergeBlock(
-               v3s16 p,
-               bool only_from_disk,
-               core::map<v3s16, MapBlock*> &changed_blocks,
-               core::map<v3s16, MapBlock*> &lighting_invalidated_blocks
-)
-{
-       DSTACK("%s: p=(%d,%d,%d), only_from_disk=%d",
-                       __FUNCTION_NAME,
-                       p.X, p.Y, p.Z, only_from_disk);
-                       
-       /*dstream<<"ServerMap::emergeBlock(): "
-                       <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
-                       <<", only_from_disk="<<only_from_disk<<std::endl;*/
-       v2s16 p2d(p.X, p.Z);
-       s16 block_y = p.Y;
-       /*
-               This will create or load a sector if not found in memory.
-               If block exists on disk, it will be loaded.
+       // 0-100
+       // Usually little, sometimes huge
+       //u32 stone_obstacle_amount = myrand_range(0, myrand_range(0, 100));
+       u32 stone_obstacle_amount = myrand_range(0, 100);
 
-               NOTE: On old save formats, this will be slow, as it generates
-                     lighting on blocks for them.
+       /*
+               Loop this part, it will make stuff look older and newer nicely
        */
-       ServerMapSector *sector = (ServerMapSector*)emergeSector(p2d);
-       assert(sector->getId() == MAPSECTOR_SERVER);
 
-       // Try to get a block from the sector
-       MapBlock *block = NULL;
-       bool not_on_disk = false;
-       try{
-               block = sector->getBlockNoCreate(block_y);
-               if(block->isDummy() == true)
-                       not_on_disk = true;
-               else
-                       return block;
-       }
-       catch(InvalidPositionException &e)
+       for(u32 i_age=0; i_age<2; i_age++)
+       { // Aging loop
+
+       // This is set during the next operation.
+       // Maximum height of the stone surface and obstacles.
+       // This is used to disable dungeon generation from going too high.
+       s16 stone_surface_max_y = 0;
+
        {
-               not_on_disk = true;
-       }
-       
+       // 8ms @cs=8
+       //TimeTaker timer1("stone obstacles");
+
        /*
-               If block was not found on disk and not going to generate a
-               new one, make sure there is a dummy block in place.
+               Add some random stone obstacles
        */
-       if(not_on_disk && only_from_disk)
+       
+       for(u32 ri=0; ri<stone_obstacle_amount/3; ri++)
+       //for(u32 ri=0; ri<7; ri++)
+       //if(0)
        {
-               if(block == NULL)
+               // Randomize max height so usually stuff will be quite low
+               //s16 maxheight_randomized = myrand_range(0, 25);
+               s16 maxheight_randomized = myrand_range(0, stone_obstacle_amount/3);
+
+               // The size of these could actually be m_chunksize*MAP_BLOCKSIZE*2
+               v3s16 ob_size(
+                       myrand_range(5, stone_obstacle_max_size),
+                       myrand_range(0, maxheight_randomized),
+                       myrand_range(5, stone_obstacle_max_size)
+               );
+               v2s16 ob_place(
+                       myrand_range(0, sectorpos_base_size*MAP_BLOCKSIZE-1),
+                       myrand_range(0, sectorpos_base_size*MAP_BLOCKSIZE-1)
+               );
+               
+               // Minimum space left on top of the obstacle
+               s16 min_head_space = 10;
+               
+               for(s16 x=-ob_size.X/2; x<ob_size.X/2; x++)
+               for(s16 z=-ob_size.Z/2; z<ob_size.Z/2; z++)
                {
-                       // Create dummy block
-                       block = new MapBlock(this, p, true);
+                       // Node position in 2d
+                       v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + ob_place + v2s16(x,z);
+                       
+                       // Find stone ground level
+                       // (ignore everything else than mud in already generated chunks)
+                       // and mud amount over the stone level
+                       s16 surface_y = 0;
+                       s16 mud_amount = 0;
+                       {
+                               v3s16 em = vmanip.m_area.getExtent();
+                               u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y));
+                               s16 y;
+                               // Go to ground level
+                               for(y=y_nodes_max; y>=y_nodes_min; y--)
+                               {
+                                       MapNode &n = vmanip.m_data[i];
+                                       /*if(content_walkable(n.d)
+                                                       && n.d != CONTENT_MUD
+                                                       && n.d != CONTENT_GRASS)
+                                               break;*/
+                                       if(n.d == CONTENT_STONE)
+                                               break;
+
+                                       if(n.d == CONTENT_MUD || n.d == CONTENT_GRASS)
+                                               mud_amount++;
+                                               
+                                       vmanip.m_area.add_y(em, i, -1);
+                               }
+                               if(y >= y_nodes_min)
+                                       surface_y = y;
+                               else
+                                       surface_y = y_nodes_min;
+                       }
+
+
+                       /*
+                               Add stone on ground
+                       */
+                       {
+                               v3s16 em = vmanip.m_area.getExtent();
+                               s16 y_start = surface_y+1;
+                               u32 i = vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y));
+                               s16 y;
+                               // Add stone
+                               s16 count = 0;
+                               for(y=y_start; y<=y_nodes_max - min_head_space; y++)
+                               {
+                                       MapNode &n = vmanip.m_data[i];
+                                       n.d = CONTENT_STONE;
+
+                                       if(y > stone_surface_max_y)
+                                               stone_surface_max_y = y;
+
+                                       count++;
+                                       if(count >= ob_size.Y)
+                                               break;
+                                               
+                                       vmanip.m_area.add_y(em, i, 1);
+                               }
+                               // Add mud
+                               count = 0;
+                               for(; y<=y_nodes_max; y++)
+                               {
+                                       MapNode &n = vmanip.m_data[i];
+                                       n.d = CONTENT_MUD;
+                                       count++;
+                                       if(count >= mud_amount)
+                                               break;
+                                               
+                                       vmanip.m_area.add_y(em, i, 1);
+                               }
+                       }
 
-                       // Add block to sector
-                       sector->insertBlock(block);
                }
-               // Done.
-               return block;
        }
 
-       //dstream<<"Not found on disk, generating."<<std::endl;
-       // 0ms
-       //TimeTaker("emergeBlock() generate");
+       }//timer1
+       {
+       // 24ms @cs=8
+       //TimeTaker timer1("dungeons");
+
+       /*
+               Make dungeons
+       */
+       u32 dungeons_count = relative_volume/200000;
+       for(u32 jj=0; jj<dungeons_count; jj++)
+       {
+               s16 min_tunnel_diameter = 1;
+               s16 max_tunnel_diameter = 5;
+               u16 tunnel_routepoints = 15;
+               
+               u32 bruise_surface_maxindex =
+                               dungeons_count / 10 * stone_surface_max_y / 10;
+               bruise_surface_maxindex =
+                               rangelim(bruise_surface_maxindex, 0, dungeons_count/2);
+               bool bruise_surface = (jj < bruise_surface_maxindex);
+
+               if(bruise_surface)
+               {
+                       min_tunnel_diameter = 5;
+                       max_tunnel_diameter = 10;
+                       tunnel_routepoints = 10;
+               }
+
+               // Allowed route area size in nodes
+               v3s16 ar(
+                       sectorpos_base_size*MAP_BLOCKSIZE,
+                       h_blocks*MAP_BLOCKSIZE,
+                       sectorpos_base_size*MAP_BLOCKSIZE
+               );
+
+               // Area starting point in nodes
+               v3s16 of(
+                       sectorpos_base.X*MAP_BLOCKSIZE,
+                       y_blocks_min*MAP_BLOCKSIZE,
+                       sectorpos_base.Y*MAP_BLOCKSIZE
+               );
+
+               // Allow a bit more
+               //(this should be more than the maximum radius of the tunnel)
+               s16 insure = 5;
+               s16 more = max_spread_amount - max_tunnel_diameter/2 - insure;
+               ar += v3s16(1,0,1) * more * 2;
+               of -= v3s16(1,0,1) * more;
+               
+               s16 route_y_min = 0;
+               //s16 route_y_max = ar.Y-1;
+               s16 route_y_max = stone_surface_max_y - of.Y;
+
+               if(bruise_surface)
+               {
+                       // Minimum is at y=0
+                       route_y_min = -of.Y - 0;
+                       route_y_min = rangelim(route_y_min, 0, route_y_max);
+               }
+
+               /*dstream<<"route_y_min = "<<route_y_min
+                               <<", route_y_max = "<<route_y_max<<std::endl;*/
+
+               // Randomize starting position
+               v3f orp(
+                       (float)(myrand()%ar.X)+0.5,
+                       (float)(myrand_range(route_y_min, route_y_max))+0.5,
+                       (float)(myrand()%ar.Z)+0.5
+               );
+
+               MapNode airnode(CONTENT_AIR);
+               
+               /*
+                       Generate some tunnel starting from orp
+               */
+               
+               for(u16 j=0; j<tunnel_routepoints; j++)
+               {
+                       v3s16 maxlen(20, 10, 20);
+
+                       if(bruise_surface)
+                       {
+                               maxlen = v3s16(60,60,60);
+                       }
+
+                       v3f vec(
+                               (float)(myrand()%(maxlen.X*2))-(float)maxlen.X,
+                               (float)(myrand()%(maxlen.Y*2))-(float)maxlen.Y,
+                               (float)(myrand()%(maxlen.Z*2))-(float)maxlen.Z
+                       );
+                       v3f rp = orp + vec;
+                       if(rp.X < 0)
+                               rp.X = 0;
+                       else if(rp.X >= ar.X)
+                               rp.X = ar.X-1;
+                       if(rp.Y < route_y_min)
+                               rp.Y = route_y_min;
+                       else if(rp.Y >= route_y_max)
+                               rp.Y = route_y_max-1;
+                       if(rp.Z < 0)
+                               rp.Z = 0;
+                       else if(rp.Z >= ar.Z)
+                               rp.Z = ar.Z-1;
+                       vec = rp - orp;
+
+                       // Randomize size
+                       s16 min_d = min_tunnel_diameter;
+                       s16 max_d = max_tunnel_diameter;
+                       s16 rs = myrand_range(min_d, max_d);
+                       
+                       for(float f=0; f<1.0; f+=1.0/vec.getLength())
+                       {
+                               v3f fp = orp + vec * f;
+                               v3s16 cp(fp.X, fp.Y, fp.Z);
+
+                               s16 d0 = -rs/2;
+                               s16 d1 = d0 + rs - 1;
+                               for(s16 z0=d0; z0<=d1; z0++)
+                               {
+                                       s16 si = rs - abs(z0);
+                                       for(s16 x0=-si; x0<=si-1; x0++)
+                                       {
+                                               s16 si2 = rs - abs(x0);
+                                               for(s16 y0=-si2+1; y0<=si2-1; y0++)
+                                               {
+                                                       s16 z = cp.Z + z0;
+                                                       s16 y = cp.Y + y0;
+                                                       s16 x = cp.X + x0;
+                                                       v3s16 p(x,y,z);
+                                                       /*if(isInArea(p, ar) == false)
+                                                               continue;*/
+                                                       // Check only height
+                                                       if(y < 0 || y >= ar.Y)
+                                                               continue;
+                                                       p += of;
+                                                       
+                                                       //assert(vmanip.m_area.contains(p));
+                                                       if(vmanip.m_area.contains(p) == false)
+                                                       {
+                                                               dstream<<"WARNING: "<<__FUNCTION_NAME
+                                                                               <<":"<<__LINE__<<": "
+                                                                               <<"point not in area"
+                                                                               <<std::endl;
+                                                               continue;
+                                                       }
+                                                       
+                                                       // Just set it to air, it will be changed to
+                                                       // water afterwards
+                                                       u32 i = vmanip.m_area.index(p);
+                                                       vmanip.m_data[i] = airnode;
+                                               }
+                                       }
+                               }
+                       }
+
+                       orp = rp;
+               }
+       
+       }
+
+       }//timer1
+       {
+       // 46ms @cs=8
+       //TimeTaker timer1("ore veins");
+
+       /*
+               Make ore veins
+       */
+       for(u32 jj=0; jj<relative_volume/524; jj++)
+       {
+               s16 max_vein_diameter = 3;
+
+               // Allowed route area size in nodes
+               v3s16 ar(
+                       sectorpos_base_size*MAP_BLOCKSIZE,
+                       h_blocks*MAP_BLOCKSIZE,
+                       sectorpos_base_size*MAP_BLOCKSIZE
+               );
+
+               // Area starting point in nodes
+               v3s16 of(
+                       sectorpos_base.X*MAP_BLOCKSIZE,
+                       y_blocks_min*MAP_BLOCKSIZE,
+                       sectorpos_base.Y*MAP_BLOCKSIZE
+               );
+
+               // Allow a bit more
+               //(this should be more than the maximum radius of the tunnel)
+               s16 insure = 3;
+               s16 more = max_spread_amount - max_vein_diameter/2 - insure;
+               ar += v3s16(1,0,1) * more * 2;
+               of -= v3s16(1,0,1) * more;
+               
+               // Randomize starting position
+               v3f orp(
+                       (float)(myrand()%ar.X)+0.5,
+                       (float)(myrand()%ar.Y)+0.5,
+                       (float)(myrand()%ar.Z)+0.5
+               );
+
+               // Randomize mineral
+               u8 mineral = myrand_range(1, MINERAL_COUNT-1);
+
+               /*
+                       Generate some vein starting from orp
+               */
+
+               for(u16 j=0; j<2; j++)
+               {
+                       /*v3f rp(
+                               (float)(myrand()%ar.X)+0.5,
+                               (float)(myrand()%ar.Y)+0.5,
+                               (float)(myrand()%ar.Z)+0.5
+                       );
+                       v3f vec = rp - orp;*/
+                       
+                       v3s16 maxlen(10, 10, 10);
+                       v3f vec(
+                               (float)(myrand()%(maxlen.X*2))-(float)maxlen.X,
+                               (float)(myrand()%(maxlen.Y*2))-(float)maxlen.Y,
+                               (float)(myrand()%(maxlen.Z*2))-(float)maxlen.Z
+                       );
+                       v3f rp = orp + vec;
+                       if(rp.X < 0)
+                               rp.X = 0;
+                       else if(rp.X >= ar.X)
+                               rp.X = ar.X;
+                       if(rp.Y < 0)
+                               rp.Y = 0;
+                       else if(rp.Y >= ar.Y)
+                               rp.Y = ar.Y;
+                       if(rp.Z < 0)
+                               rp.Z = 0;
+                       else if(rp.Z >= ar.Z)
+                               rp.Z = ar.Z;
+                       vec = rp - orp;
+
+                       // Randomize size
+                       s16 min_d = 0;
+                       s16 max_d = max_vein_diameter;
+                       s16 rs = myrand_range(min_d, max_d);
+                       
+                       for(float f=0; f<1.0; f+=1.0/vec.getLength())
+                       {
+                               v3f fp = orp + vec * f;
+                               v3s16 cp(fp.X, fp.Y, fp.Z);
+                               s16 d0 = -rs/2;
+                               s16 d1 = d0 + rs - 1;
+                               for(s16 z0=d0; z0<=d1; z0++)
+                               {
+                                       s16 si = rs - abs(z0);
+                                       for(s16 x0=-si; x0<=si-1; x0++)
+                                       {
+                                               s16 si2 = rs - abs(x0);
+                                               for(s16 y0=-si2+1; y0<=si2-1; y0++)
+                                               {
+                                                       // Don't put mineral to every place
+                                                       if(myrand()%5 != 0)
+                                                               continue;
+
+                                                       s16 z = cp.Z + z0;
+                                                       s16 y = cp.Y + y0;
+                                                       s16 x = cp.X + x0;
+                                                       v3s16 p(x,y,z);
+                                                       /*if(isInArea(p, ar) == false)
+                                                               continue;*/
+                                                       // Check only height
+                                                       if(y < 0 || y >= ar.Y)
+                                                               continue;
+                                                       p += of;
+                                                       
+                                                       assert(vmanip.m_area.contains(p));
+                                                       
+                                                       // Just set it to air, it will be changed to
+                                                       // water afterwards
+                                                       u32 i = vmanip.m_area.index(p);
+                                                       MapNode *n = &vmanip.m_data[i];
+                                                       if(n->d == CONTENT_STONE)
+                                                               n->param = mineral;
+                                               }
+                                       }
+                               }
+                       }
+
+                       orp = rp;
+               }
+       
+       }
+
+       }//timer1
+       {
+       // 15ms @cs=8
+       //TimeTaker timer1("add mud");
+
+       /*
+               Add mud to the central chunk
+       */
+       
+       for(s16 x=0; x<sectorpos_base_size*MAP_BLOCKSIZE; x++)
+       for(s16 z=0; z<sectorpos_base_size*MAP_BLOCKSIZE; z++)
+       {
+               // Node position in 2d
+               v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z);
+               
+               // Find ground level
+               s16 surface_y = find_ground_level(vmanip, p2d);
+
+               /*
+                       If topmost node is grass, change it to mud.
+                       It might be if it was flown to there from a neighboring
+                       chunk and then converted.
+               */
+               {
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, surface_y, p2d.Y));
+                       MapNode *n = &vmanip.m_data[i];
+                       if(n->d == CONTENT_GRASS)
+                               n->d = CONTENT_MUD;
+               }
+
+               /*
+                       Add mud on ground
+               */
+               {
+                       s16 mudcount = 0;
+                       v3s16 em = vmanip.m_area.getExtent();
+                       s16 y_start = surface_y+1;
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y));
+                       for(s16 y=y_start; y<=y_nodes_max; y++)
+                       {
+                               MapNode &n = vmanip.m_data[i];
+                               n.d = CONTENT_MUD;
+                               mudcount++;
+                               if(mudcount >= 3)
+                                       break;
+                                       
+                               vmanip.m_area.add_y(em, i, 1);
+                       }
+               }
+
+       }
 
+       }//timer1
+       {
+       // 179ms @cs=8
+       //TimeTaker timer1("flow mud");
+
+       /*
+               Flow mud away from steep edges
+       */
+
+       // Iterate a few times
+       for(s16 k=0; k<4; k++)
+       {
+
+       for(s16 x=0-max_spread_amount+1;
+                       x<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount-1;
+                       x++)
+       for(s16 z=0-max_spread_amount+1;
+                       z<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount-1;
+                       z++)
+       {
+               // Node position in 2d
+               v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z);
+               
+               v3s16 em = vmanip.m_area.getExtent();
+               u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y));
+               s16 y;
+               // Go to ground level
+               for(y=y_nodes_max; y>=y_nodes_min; y--)
+               {
+                       MapNode &n = vmanip.m_data[i];
+                       //if(n.d != CONTENT_AIR)
+                       if(content_walkable(n.d))
+                               break;
+                               
+                       vmanip.m_area.add_y(em, i, -1);
+               }
+
+               // If not mud, do nothing to it
+               MapNode *n = &vmanip.m_data[i];
+               if(n->d != CONTENT_MUD && n->d != CONTENT_GRASS)
+                       continue;
+
+               // Make it exactly mud
+               n->d = CONTENT_MUD;
+
+               v3s16 dirs4[4] = {
+                       v3s16(0,0,1), // back
+                       v3s16(1,0,0), // right
+                       v3s16(0,0,-1), // front
+                       v3s16(-1,0,0), // left
+               };
+
+               // Drop mud on side
+               
+               for(u32 di=0; di<4; di++)
+               {
+                       v3s16 dirp = dirs4[di];
+                       u32 i2 = i;
+                       // Check that side is air
+                       vmanip.m_area.add_p(em, i2, dirp);
+                       MapNode *n2 = &vmanip.m_data[i2];
+                       if(content_walkable(n2->d))
+                               continue;
+                       // Check that under side is air
+                       vmanip.m_area.add_y(em, i2, -1);
+                       n2 = &vmanip.m_data[i2];
+                       if(content_walkable(n2->d))
+                               continue;
+                       // Loop further down until not air
+                       do{
+                               vmanip.m_area.add_y(em, i2, -1);
+                               n2 = &vmanip.m_data[i2];
+                       }while(content_walkable(n2->d) == false);
+                       // Loop one up so that we're in air
+                       vmanip.m_area.add_y(em, i2, 1);
+                       n2 = &vmanip.m_data[i2];
+
+                       // Move mud to new place
+                       *n2 = *n;
+                       // Set old place to be air
+                       *n = MapNode(CONTENT_AIR);
+
+                       #if 0
+                       // Switch mud and other and change mud source to air
+                       //MapNode tempnode = *n2;
+                       *n2 = *n;
+                       //*n = tempnode;
+                       // Force old mud position to be air
+                       n->d = CONTENT_AIR;
+                       #endif
+
+                       // Done
+                       break;
+               }
+       }
+       
+       }
+
+       }//timer1
+       {
+       // 50ms @cs=8
+       //TimeTaker timer1("add water");
+
+       /*
+               Add water to the central chunk (and a bit more)
+       */
+       
+       for(s16 x=0-max_spread_amount;
+                       x<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount;
+                       x++)
+       for(s16 z=0-max_spread_amount;
+                       z<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount;
+                       z++)
+       {
+               // Node position in 2d
+               v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z);
+               
+               // Find ground level
+               //s16 surface_y = find_ground_level(vmanip, p2d);
+
+               /*
+                       If ground level is over water level, skip.
+                       NOTE: This leaves caves near water without water,
+                       which looks especially crappy when the nearby water
+                       won't start flowing either for some reason
+               */
+               /*if(surface_y > WATER_LEVEL)
+                       continue;*/
+
+               /*
+                       Add water on ground
+               */
+               {
+                       v3s16 em = vmanip.m_area.getExtent();
+                       s16 y_start = WATER_LEVEL;
+                       u8 light = LIGHT_MAX;
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y));
+                       MapNode *n = &vmanip.m_data[i];
+                       /*
+                               Add first one to transforming liquid queue
+                       */
+                       if(n->d == CONTENT_WATER || n->d == CONTENT_WATERSOURCE)
+                       {
+                               v3s16 p = v3s16(p2d.X, y_start, p2d.Y);
+                               m_transforming_liquid.push_back(p);
+                       }
+                       for(s16 y=y_start; y>=y_nodes_min; y--)
+                       {
+                               n = &vmanip.m_data[i];
+                               
+                               // Stop when there is no water and no air
+                               if(n->d != CONTENT_AIR && n->d != CONTENT_WATERSOURCE
+                                               && n->d != CONTENT_WATER)
+                               {
+                                       /*
+                                               Add bottom one to transforming liquid queue
+                                       */
+                                       vmanip.m_area.add_y(em, i, 1);
+                                       n = &vmanip.m_data[i];
+                                       if(n->d == CONTENT_WATER || n->d == CONTENT_WATERSOURCE)
+                                       {
+                                               v3s16 p = v3s16(p2d.X, y, p2d.Y);
+                                               m_transforming_liquid.push_back(p);
+                                       }
+
+                                       break;
+                               }
+                               
+                               n->d = CONTENT_WATERSOURCE;
+                               n->setLight(LIGHTBANK_DAY, light);
+
+                               /*// Add to transforming liquid queue (in case it'd
+                               // start flowing)
+                               v3s16 p = v3s16(p2d.X, y, p2d.Y);
+                               m_transforming_liquid.push_back(p);*/
+                               
+                               // Next one
+                               vmanip.m_area.add_y(em, i, -1);
+                               if(light > 0)
+                                       light--;
+                       }
+               }
+
+       }
+
+       }//timer1
+       
+       } // Aging loop
+
+       {
+       // 1ms @cs=8
+       //TimeTaker timer1("plant trees");
+
+       /*
+               Plant some trees
+       */
+       {
+               u32 tree_max = relative_area / 100;
+               
+               u32 count = myrand_range(0, tree_max);
+               for(u32 i=0; i<count; i++)
+               {
+                       s16 x = myrand_range(0, sectorpos_base_size*MAP_BLOCKSIZE-1);
+                       s16 z = myrand_range(0, sectorpos_base_size*MAP_BLOCKSIZE-1);
+                       x += sectorpos_base.X*MAP_BLOCKSIZE;
+                       z += sectorpos_base.Y*MAP_BLOCKSIZE;
+                       s16 y = find_ground_level(vmanip, v2s16(x,z));
+                       // Don't make a tree under water level
+                       if(y < WATER_LEVEL)
+                               continue;
+                       v3s16 p(x,y+1,z);
+                       // Make a tree
+                       make_tree(vmanip, p);
+               }
+       }
+
+       }//timer1
+
+       {
+       // 19ms @cs=8
+       //TimeTaker timer1("grow grass");
+
+       /*
+               Grow grass
+       */
+
+       /*for(s16 x=0-4; x<sectorpos_base_size*MAP_BLOCKSIZE+4; x++)
+       for(s16 z=0-4; z<sectorpos_base_size*MAP_BLOCKSIZE+4; z++)*/
+       for(s16 x=0-max_spread_amount;
+                       x<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount;
+                       x++)
+       for(s16 z=0-max_spread_amount;
+                       z<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount;
+                       z++)
+       {
+               // Node position in 2d
+               v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z);
+               
+               /*
+                       Find the lowest surface to which enough light ends up
+                       to make grass grow.
+
+                       Basically just wait until not air and not leaves.
+               */
+               s16 surface_y = 0;
+               {
+                       v3s16 em = vmanip.m_area.getExtent();
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y));
+                       s16 y;
+                       // Go to ground level
+                       for(y=y_nodes_max; y>=y_nodes_min; y--)
+                       {
+                               MapNode &n = vmanip.m_data[i];
+                               if(n.d != CONTENT_AIR
+                                               && n.d != CONTENT_LEAVES)
+                                       break;
+                               vmanip.m_area.add_y(em, i, -1);
+                       }
+                       if(y >= y_nodes_min)
+                               surface_y = y;
+                       else
+                               surface_y = y_nodes_min;
+               }
+               
+               u32 i = vmanip.m_area.index(p2d.X, surface_y, p2d.Y);
+               MapNode *n = &vmanip.m_data[i];
+               if(n->d == CONTENT_MUD)
+                       n->d = CONTENT_GRASS;
+       }
+
+       }//timer1
+
+       /*
+               Handle lighting
+       */
+
+       core::map<v3s16, bool> light_sources;
+
+       {
+       // 750ms @cs=8, can't optimize more
+       //TimeTaker timer1("initial lighting");
+
+       /*for(s16 x=0; x<sectorpos_base_size*MAP_BLOCKSIZE; x++)
+       for(s16 z=0; z<sectorpos_base_size*MAP_BLOCKSIZE; z++)*/
+       for(s16 x=0-max_spread_amount+1;
+                       x<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount-1;
+                       x++)
+       for(s16 z=0-max_spread_amount+1;
+                       z<sectorpos_base_size*MAP_BLOCKSIZE+max_spread_amount-1;
+                       z++)
+       {
+               // Node position in 2d
+               v2s16 p2d = sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z);
+               
+               /*
+                       Apply initial sunlight
+               */
+               {
+                       u8 light = LIGHT_SUN;
+                       bool add_to_sources = false;
+                       v3s16 em = vmanip.m_area.getExtent();
+                       s16 y_start = y_nodes_max;
+                       u32 i = vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y));
+                       for(s16 y=y_start; y>=y_nodes_min; y--)
+                       {
+                               MapNode *n = &vmanip.m_data[i];
+
+                               if(light_propagates_content(n->d) == false)
+                               {
+                                       light = 0;
+                               }
+                               else if(light != LIGHT_SUN
+                                       || sunlight_propagates_content(n->d) == false)
+                               {
+                                       if(light > 0)
+                                               light--;
+                               }
+                               
+                               // This doesn't take much time
+                               if(add_to_sources == false)
+                               {
+                                       /*
+                                               Check sides. If side is not air or water, start
+                                               adding to light_sources.
+                                       */
+                                       v3s16 dirs4[4] = {
+                                               v3s16(0,0,1), // back
+                                               v3s16(1,0,0), // right
+                                               v3s16(0,0,-1), // front
+                                               v3s16(-1,0,0), // left
+                                       };
+                                       for(u32 di=0; di<4; di++)
+                                       {
+                                               v3s16 dirp = dirs4[di];
+                                               u32 i2 = i;
+                                               vmanip.m_area.add_p(em, i2, dirp);
+                                               MapNode *n2 = &vmanip.m_data[i2];
+                                               if(
+                                                       n2->d != CONTENT_AIR
+                                                       && n2->d != CONTENT_WATERSOURCE
+                                                       && n2->d != CONTENT_WATER
+                                               ){
+                                                       add_to_sources = true;
+                                                       break;
+                                               }
+                                       }
+                               }
+
+                               n->setLight(LIGHTBANK_DAY, light);
+                               n->setLight(LIGHTBANK_NIGHT, 0);
+                               
+                               // This doesn't take much time
+                               if(light != 0 && add_to_sources)
+                               {
+                                       // Insert light source
+                                       light_sources.insert(v3s16(p2d.X, y, p2d.Y), true);
+                               }
+                               
+                               // Increment index by y
+                               vmanip.m_area.add_y(em, i, -1);
+                       }
+               }
+       }
+
+       }//timer1
+
+       // Spread light around
+       {
+               TimeTaker timer("generateChunkRaw() spreadLight");
+               vmanip.spreadLight(LIGHTBANK_DAY, light_sources);
+       }
+       
+       /*
+               Generation ended
+       */
+
+       timer_generate.stop();
+
+       /*
+               Blit generated stuff to map
+       */
+       {
+               // 70ms @cs=8
+               //TimeTaker timer("generateChunkRaw() blitBackAll");
+               vmanip.blitBackAll(&changed_blocks);
+       }
+       /*
+               Update day/night difference cache of the MapBlocks
+       */
+       {
+               for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
+                               i.atEnd() == false; i++)
+               {
+                       MapBlock *block = i.getNode()->getValue();
+                       block->updateDayNightDiff();
+               }
+       }
+
+       
+       /*
+               Create chunk metadata
+       */
+
+       for(s16 x=-1; x<=1; x++)
+       for(s16 y=-1; y<=1; y++)
+       {
+               v2s16 chunkpos0 = chunkpos + v2s16(x,y);
+               // Add chunk meta information
+               MapChunk *chunk = getChunk(chunkpos0);
+               if(chunk == NULL)
+               {
+                       chunk = new MapChunk();
+                       m_chunks.insert(chunkpos0, chunk);
+               }
+               //chunk->setIsVolatile(true);
+               if(chunk->getGenLevel() > GENERATED_PARTLY)
+                       chunk->setGenLevel(GENERATED_PARTLY);
+       }
+
+       /*
+               Set central chunk non-volatile and return it
+       */
+       MapChunk *chunk = getChunk(chunkpos);
+       assert(chunk);
+       // Set non-volatile
+       //chunk->setIsVolatile(false);
+       chunk->setGenLevel(GENERATED_FULLY);
+       // Return it
+       return chunk;
+}
+
+MapChunk* ServerMap::generateChunk(v2s16 chunkpos1,
+               core::map<v3s16, MapBlock*> &changed_blocks)
+{
+       dstream<<"generateChunk(): Generating chunk "
+                       <<"("<<chunkpos1.X<<","<<chunkpos1.Y<<")"
+                       <<std::endl;
+       
+       /*for(s16 x=-1; x<=1; x++)
+       for(s16 y=-1; y<=1; y++)*/
+       for(s16 x=-0; x<=0; x++)
+       for(s16 y=-0; y<=0; y++)
+       {
+               v2s16 chunkpos0 = chunkpos1 + v2s16(x,y);
+               MapChunk *chunk = getChunk(chunkpos0);
+               // Skip if already generated
+               if(chunk != NULL && chunk->getGenLevel() == GENERATED_FULLY)
+                       continue;
+               generateChunkRaw(chunkpos0, changed_blocks);
+       }
+       
+       assert(chunkNonVolatile(chunkpos1));
+
+       MapChunk *chunk = getChunk(chunkpos1);
+       return chunk;
+}
+
+ServerMapSector * ServerMap::createSector(v2s16 p2d)
+{
+       DSTACK("%s: p2d=(%d,%d)",
+                       __FUNCTION_NAME,
+                       p2d.X, p2d.Y);
+       
+       /*
+               Check if it exists already in memory
+       */
+       ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d);
+       if(sector != NULL)
+               return sector;
+       
+       /*
+               Try to load it from disk (with blocks)
+       */
+       if(loadSectorFull(p2d) == true)
+       {
+               ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d);
+               if(sector == NULL)
+               {
+                       dstream<<"ServerMap::createSector(): loadSectorFull didn't make a sector"<<std::endl;
+                       throw InvalidPositionException("");
+               }
+               return sector;
+       }
+
+       /*
+               If there is no master heightmap, throw.
+       */
+       if(m_heightmap == NULL)
+       {
+               throw InvalidPositionException("createSector(): no heightmap");
+       }
+
+       /*
+               Do not create over-limit
+       */
+       if(p2d.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
+       || p2d.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
+       || p2d.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
+       || p2d.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
+               throw InvalidPositionException("createSector(): pos. over limit");
+
+       /*
+               Generate blank sector
+       */
+       
+       // Number of heightmaps in sector in each direction
+       u16 hm_split = SECTOR_HEIGHTMAP_SPLIT;
+
+       // Heightmap side width
+       s16 hm_d = MAP_BLOCKSIZE / hm_split;
+
+       sector = new ServerMapSector(this, p2d, hm_split);
+       
+       // Sector position on map in nodes
+       v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
+
+       /*dstream<<"Generating sector ("<<p2d.X<<","<<p2d.Y<<")"
+                       " heightmaps and objects"<<std::endl;*/
+       
+       /*
+               Generate sector heightmap
+       */
+
+       v2s16 mhm_p = p2d * hm_split;
+       /*f32 corners[4] = {
+               m_heightmap->getGroundHeight(mhm_p+v2s16(0,0)*hm_split),
+               m_heightmap->getGroundHeight(mhm_p+v2s16(1,0)*hm_split),
+               m_heightmap->getGroundHeight(mhm_p+v2s16(1,1)*hm_split),
+               m_heightmap->getGroundHeight(mhm_p+v2s16(0,1)*hm_split),
+       };*/
+       
+       // Loop through sub-heightmaps
+       for(s16 y=0; y<hm_split; y++)
+       for(s16 x=0; x<hm_split; x++)
+       {
+               v2s16 p_in_sector = v2s16(x,y);
+               v2s16 mhm_p = p2d * hm_split + p_in_sector;
+               f32 corners[4] = {
+                       m_heightmap->getGroundHeight(mhm_p+v2s16(0,0)),
+                       m_heightmap->getGroundHeight(mhm_p+v2s16(1,0)),
+                       m_heightmap->getGroundHeight(mhm_p+v2s16(1,1)),
+                       m_heightmap->getGroundHeight(mhm_p+v2s16(0,1)),
+               };
+
+               /*dstream<<"p_in_sector=("<<p_in_sector.X<<","<<p_in_sector.Y<<")"
+                               <<" mhm_p=("<<mhm_p.X<<","<<mhm_p.Y<<")"
+                               <<std::endl;*/
+
+               FixedHeightmap *hm = new FixedHeightmap(&m_hwrapper,
+                               mhm_p, hm_d);
+               sector->setHeightmap(p_in_sector, hm);
+
+               //hm->generateContinued(1.0, 0.5, corners);
+               hm->generateContinued(0.5, 0.5, corners);
+
+               //hm->print();
+       }
+       
+       // Add dummy objects
+       core::map<v3s16, u8> *objects = new core::map<v3s16, u8>;
+       sector->setObjects(objects);
+       
+       /*
+               Insert to container
+       */
+       m_sectors.insert(p2d, sector);
+       
+       return sector;
+}
+
+MapSector * ServerMap::emergeSector(v2s16 p2d,
+               core::map<v3s16, MapBlock*> &changed_blocks)
+{
+       DSTACK("%s: p2d=(%d,%d)",
+                       __FUNCTION_NAME,
+                       p2d.X, p2d.Y);
+       
+       /*
+               Check chunk status
+       */
+       v2s16 chunkpos = sector_to_chunk(p2d);
+       /*bool chunk_nonvolatile = false;
+       MapChunk *chunk = getChunk(chunkpos);
+       if(chunk && chunk->getIsVolatile() == false)
+               chunk_nonvolatile = true;*/
+       bool chunk_nonvolatile = chunkNonVolatile(chunkpos);
+
+       /*
+               If chunk is not fully generated, generate chunk
+       */
+       if(chunk_nonvolatile == false)
+       {
+               // Generate chunk and neighbors
+               generateChunk(chunkpos, changed_blocks);
+       }
+       
+       /*
+               Return sector if it exists now
+       */
+       MapSector *sector = getSectorNoGenerateNoEx(p2d);
+       if(sector != NULL)
+               return sector;
+       
+       /*
+               Try to load it from disk
+       */
+       if(loadSectorFull(p2d) == true)
+       {
+               MapSector *sector = getSectorNoGenerateNoEx(p2d);
+               if(sector == NULL)
+               {
+                       dstream<<"ServerMap::emergeSector(): loadSectorFull didn't make a sector"<<std::endl;
+                       throw InvalidPositionException("");
+               }
+               return sector;
+       }
+
+       /*
+               generateChunk should have generated the sector
+       */
+       assert(0);
+
+       /*
+               Generate directly
+       */
+       //return generateSector();
+}
+
+/*
+       NOTE: This is not used for main map generation, only for blocks
+       that are very high or low
+*/
+MapBlock * ServerMap::generateBlock(
+               v3s16 p,
+               MapBlock *original_dummy,
+               ServerMapSector *sector,
+               core::map<v3s16, MapBlock*> &changed_blocks,
+               core::map<v3s16, MapBlock*> &lighting_invalidated_blocks
+)
+{
+       DSTACK("%s: p=(%d,%d,%d)",
+                       __FUNCTION_NAME,
+                       p.X, p.Y, p.Z);
+       
+       /*dstream<<"generateBlock(): "
+                       <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
+                       <<std::endl;*/
+       
+       MapBlock *block = original_dummy;
+                       
+       v2s16 p2d(p.X, p.Z);
+       s16 block_y = p.Y;
+       
        /*
                Do not generate over-limit
        */
        if(blockpos_over_limit(p))
-               throw InvalidPositionException("emergeBlock(): pos. over limit");
-
-       /*
-               OK; Not found.
-
-               Go on generating the block.
+       {
+               dstream<<__FUNCTION_NAME<<": Block position over limit"<<std::endl;
+               throw InvalidPositionException("generateBlock(): pos. over limit");
+       }
 
-               TODO: If a dungeon gets generated so that it's side gets
-                     revealed to the outside air, the lighting should be
-                         recalculated.
-       */
-       
        /*
                If block doesn't exist, create one.
                If it exists, it is a dummy. In that case unDummify() it.
@@ -2309,7 +3470,7 @@ MapBlock * ServerMap::emergeBlock(
        for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
        for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
        {
-               //dstream<<"emergeBlock: x0="<<x0<<", z0="<<z0<<std::endl;
+               //dstream<<"generateBlock: x0="<<x0<<", z0="<<z0<<std::endl;
 
                float surface_y_f = sector->getGroundHeight(v2s16(x0,z0));
                //assert(surface_y_f > GROUNDHEIGHT_VALID_MINVALUE);
@@ -2442,23 +3603,25 @@ MapBlock * ServerMap::emergeBlock(
                Get local attributes
        */
 
-       //dstream<<"emergeBlock(): Getting local attributes"<<std::endl;
+       //dstream<<"generateBlock(): Getting local attributes"<<std::endl;
 
-       float caves_amount = 0;
-       
+       float caves_amount = 0.5;
+
+#if 0
        {
                /*
                        NOTE: BEWARE: Too big amount of attribute points slows verything
                        down by a lot.
                        1 interpolation from 5000 points takes 2-3ms.
                */
-               //TimeTaker timer("emergeBlock() local attribute retrieval");
+               //TimeTaker timer("generateBlock() local attribute retrieval");
                v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
                PointAttributeList *list_caves_amount = m_padb.getList("caves_amount");
                caves_amount = list_caves_amount->getInterpolatedFloat(nodepos2d);
        }
+#endif
 
-       //dstream<<"emergeBlock(): Done"<<std::endl;
+       //dstream<<"generateBlock(): Done"<<std::endl;
 
        /*
                Generate dungeons
@@ -2608,10 +3771,10 @@ MapBlock * ServerMap::emergeBlock(
                        do_generate_dungeons = false;
                }
                // Don't generate if mostly underwater surface
-               else if(mostly_underwater_surface)
+               /*else if(mostly_underwater_surface)
                {
                        do_generate_dungeons = false;
-               }
+               }*/
                // Partly underground = cave
                else if(!completely_underground)
                {
@@ -2699,7 +3862,7 @@ MapBlock * ServerMap::emergeBlock(
                                        +ued*(y0*ued/MAP_BLOCKSIZE)
                                        +(x0*ued/MAP_BLOCKSIZE)])
                        {
-                               if(is_ground_content(n.d))
+                               if(content_features(n.d).walkable/*is_ground_content(n.d)*/)
                                {
                                        // Has now caves
                                        has_dungeons = true;
@@ -2714,7 +3877,7 @@ MapBlock * ServerMap::emergeBlock(
        
        /*
                This is used for guessing whether or not the block should
-               receive sunlight from the top if the top block doesn't exist
+               receive sunlight from the top if the block above doesn't exist
        */
        block->setIsUnderground(completely_underground);
 
@@ -2755,17 +3918,11 @@ MapBlock * ServerMap::emergeBlock(
                                MapNode n;
                                n.d = CONTENT_MESE;
                                
-                               //if(is_ground_content(block->getNode(cp).d))
-                               if(block->getNode(cp).d == CONTENT_STONE)
-                                       if(myrand()%8 == 0)
-                                               block->setNode(cp, n);
-
-                               for(u16 i=0; i<26; i++)
+                               for(u16 i=0; i<27; i++)
                                {
-                                       //if(is_ground_content(block->getNode(cp+g_26dirs[i]).d))
-                                       if(block->getNode(cp+g_26dirs[i]).d == CONTENT_STONE)
+                                       if(block->getNode(cp+g_27dirs[i]).d == CONTENT_STONE)
                                                if(myrand()%8 == 0)
-                                                       block->setNode(cp+g_26dirs[i], n);
+                                                       block->setNode(cp+g_27dirs[i], n);
                                }
                        }
                }
@@ -2790,21 +3947,47 @@ MapBlock * ServerMap::emergeBlock(
                                );
 
                                MapNode n;
-                               n.d = CONTENT_COALSTONE;
+                               n.d = CONTENT_STONE;
+                               n.param = MINERAL_COAL;
 
-                               //dstream<<"Adding coalstone"<<std::endl;
-                               
-                               //if(is_ground_content(block->getNode(cp).d))
-                               if(block->getNode(cp).d == CONTENT_STONE)
-                                       if(myrand()%8 == 0)
-                                               block->setNode(cp, n);
+                               for(u16 i=0; i<27; i++)
+                               {
+                                       if(block->getNode(cp+g_27dirs[i]).d == CONTENT_STONE)
+                                               if(myrand()%8 == 0)
+                                                       block->setNode(cp+g_27dirs[i], n);
+                               }
+                       }
+               }
+
+               /*
+                       Add iron
+               */
+               //TODO: change to iron_amount or whatever
+               u16 iron_amount = 30.0 * g_settings.getFloat("coal_amount");
+               u16 iron_rareness = 60 / iron_amount;
+               if(iron_rareness == 0)
+                       iron_rareness = 1;
+               if(myrand()%iron_rareness == 0)
+               {
+                       u16 a = myrand() % 16;
+                       u16 amount = iron_amount * a*a*a / 1000;
+                       for(s16 i=0; i<amount; i++)
+                       {
+                               v3s16 cp(
+                                       (myrand()%(MAP_BLOCKSIZE-2))+1,
+                                       (myrand()%(MAP_BLOCKSIZE-2))+1,
+                                       (myrand()%(MAP_BLOCKSIZE-2))+1
+                               );
+
+                               MapNode n;
+                               n.d = CONTENT_STONE;
+                               n.param = MINERAL_IRON;
 
-                               for(u16 i=0; i<26; i++)
+                               for(u16 i=0; i<27; i++)
                                {
-                                       //if(is_ground_content(block->getNode(cp+g_26dirs[i]).d))
-                                       if(block->getNode(cp+g_26dirs[i]).d == CONTENT_STONE)
+                                       if(block->getNode(cp+g_27dirs[i]).d == CONTENT_STONE)
                                                if(myrand()%8 == 0)
-                                                       block->setNode(cp+g_26dirs[i], n);
+                                                       block->setNode(cp+g_27dirs[i], n);
                                }
                        }
                }
@@ -3012,26 +4195,23 @@ MapBlock * ServerMap::emergeBlock(
                                                                <<std::endl;*/
                                                {
                                                        v3s16 p2 = p + v3s16(x,y,z-2);
-                                                       if(is_ground_content(sector->getNode(p2).d)
-                                                                       && !is_mineral(sector->getNode(p2).d))
+                                                       //if(is_ground_content(sector->getNode(p2).d))
+                                                       if(content_features(sector->getNode(p2).d).walkable)
                                                                sector->setNode(p2, n);
                                                }
                                                {
                                                        v3s16 p2 = p + v3s16(x,y,z-1);
-                                                       if(is_ground_content(sector->getNode(p2).d)
-                                                                       && !is_mineral(sector->getNode(p2).d))
+                                                       if(content_features(sector->getNode(p2).d).walkable)
                                                                sector->setNode(p2, n2);
                                                }
                                                {
                                                        v3s16 p2 = p + v3s16(x,y,z+0);
-                                                       if(is_ground_content(sector->getNode(p2).d)
-                                                                       && !is_mineral(sector->getNode(p2).d))
+                                                       if(content_features(sector->getNode(p2).d).walkable)
                                                                sector->setNode(p2, n2);
                                                }
                                                {
                                                        v3s16 p2 = p + v3s16(x,y,z+1);
-                                                       if(is_ground_content(sector->getNode(p2).d)
-                                                                       && !is_mineral(sector->getNode(p2).d))
+                                                       if(content_features(sector->getNode(p2).d).walkable)
                                                                sector->setNode(p2, n);
                                                }
 
@@ -3049,7 +4229,7 @@ MapBlock * ServerMap::emergeBlock(
                }
                else
                {
-                       dstream<<"ServerMap::emergeBlock(): "
+                       dstream<<"ServerMap::generateBlock(): "
                                        "Invalid heightmap object"
                                        <<std::endl;
                }
@@ -3072,6 +4252,182 @@ MapBlock * ServerMap::emergeBlock(
        {
                objects->remove(*i);
        }
+       
+       /*
+               Translate sector's changed blocks to global changed blocks
+       */
+       
+       for(core::map<s16, MapBlock*>::Iterator
+                       i = changed_blocks_sector.getIterator();
+                       i.atEnd() == false; i++)
+       {
+               MapBlock *block = i.getNode()->getValue();
+
+               changed_blocks.insert(block->getPos(), block);
+       }
+
+       block->setLightingExpired(true);
+       
+#if 0
+       /*
+               Debug information
+       */
+       dstream
+       <<"lighting_invalidated_blocks.size()"
+       <<", has_dungeons"
+       <<", completely_ug"
+       <<", some_part_ug"
+       <<"  "<<lighting_invalidated_blocks.size()
+       <<", "<<has_dungeons
+       <<", "<<completely_underground
+       <<", "<<some_part_underground
+       <<std::endl;
+#endif
+
+       return block;
+}
+
+MapBlock * ServerMap::createBlock(v3s16 p)
+{
+       DSTACK("%s: p=(%d,%d,%d)",
+                       __FUNCTION_NAME, p.X, p.Y, p.Z);
+       
+       v2s16 p2d(p.X, p.Z);
+       s16 block_y = p.Y;
+       /*
+               This will create or load a sector if not found in memory.
+               If block exists on disk, it will be loaded.
+
+               NOTE: On old save formats, this will be slow, as it generates
+                     lighting on blocks for them.
+       */
+       ServerMapSector *sector;
+       try{
+               sector = (ServerMapSector*)createSector(p2d);
+               assert(sector->getId() == MAPSECTOR_SERVER);
+       }
+       /*catch(InvalidPositionException &e)
+       {
+               dstream<<"createBlock: createSector() failed"<<std::endl;
+               throw e;
+       }*/
+       catch(std::exception &e)
+       {
+               dstream<<"createBlock: createSector() failed: "
+                               <<e.what()<<std::endl;
+               throw e;
+       }
+
+       /*
+               Try to get a block from the sector
+       */
+
+       MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
+       if(block)
+               return block;
+       // Create blank
+       block = sector->createBlankBlock(block_y);
+       return block;
+}
+
+MapBlock * ServerMap::emergeBlock(
+               v3s16 p,
+               bool only_from_disk,
+               core::map<v3s16, MapBlock*> &changed_blocks,
+               core::map<v3s16, MapBlock*> &lighting_invalidated_blocks
+)
+{
+       DSTACK("%s: p=(%d,%d,%d), only_from_disk=%d",
+                       __FUNCTION_NAME,
+                       p.X, p.Y, p.Z, only_from_disk);
+       
+       v2s16 p2d(p.X, p.Z);
+       s16 block_y = p.Y;
+       /*
+               This will create or load a sector if not found in memory.
+               If block exists on disk, it will be loaded.
+
+               NOTE: On old save formats, this will be slow, as it generates
+                     lighting on blocks for them.
+       */
+       ServerMapSector *sector;
+       try{
+               sector = (ServerMapSector*)emergeSector(p2d, changed_blocks);
+               assert(sector->getId() == MAPSECTOR_SERVER);
+       }
+       catch(std::exception &e)
+       {
+               dstream<<"emergeBlock: emergeSector() failed: "
+                               <<e.what()<<std::endl;
+               throw e;
+       }
+
+       /*
+               Try to get a block from the sector
+       */
+
+       bool does_not_exist = false;
+       bool lighting_expired = false;
+       MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
+
+       if(block == NULL)
+       {
+               does_not_exist = true;
+       }
+       else if(block->isDummy() == true)
+       {
+               does_not_exist = true;
+       }
+       else if(block->getLightingExpired())
+       {
+               lighting_expired = true;
+       }
+       else
+       {
+               // Valid block
+               //dstream<<"emergeBlock(): Returning already valid block"<<std::endl;
+               return block;
+       }
+       
+       /*
+               If block was not found on disk and not going to generate a
+               new one, make sure there is a dummy block in place.
+       */
+       if(only_from_disk && (does_not_exist || lighting_expired))
+       {
+               //dstream<<"emergeBlock(): Was not on disk but not generating"<<std::endl;
+
+               if(block == NULL)
+               {
+                       // Create dummy block
+                       block = new MapBlock(this, p, true);
+
+                       // Add block to sector
+                       sector->insertBlock(block);
+               }
+               // Done.
+               return block;
+       }
+
+       //dstream<<"Not found on disk, generating."<<std::endl;
+       // 0ms
+       //TimeTaker("emergeBlock() generate");
+
+       //dstream<<"emergeBlock(): Didn't find valid block -> making one"<<std::endl;
+
+       /*
+               If the block doesn't exist, generate the block.
+       */
+       if(does_not_exist)
+       {
+               block = generateBlock(p, block, sector, changed_blocks,
+                               lighting_invalidated_blocks); 
+       }
+
+       if(lighting_expired)
+       {
+               lighting_invalidated_blocks.insert(p, block);
+       }
 
        /*
                Initially update sunlight
@@ -3086,7 +4442,8 @@ MapBlock * ServerMap::emergeBlock(
 
                // If sunlight didn't reach everywhere and part of block is
                // above ground, lighting has to be properly updated
-               if(black_air_left && some_part_underground)
+               //if(black_air_left && some_part_underground)
+               if(black_air_left)
                {
                        lighting_invalidated_blocks[block->getPos()] = block;
                }
@@ -3096,37 +4453,7 @@ MapBlock * ServerMap::emergeBlock(
                        lighting_invalidated_blocks[block->getPos()] = block;
                }
        }
-
-       /*
-               Translate sector's changed blocks to global changed blocks
-       */
        
-       for(core::map<s16, MapBlock*>::Iterator
-                       i = changed_blocks_sector.getIterator();
-                       i.atEnd() == false; i++)
-       {
-               MapBlock *block = i.getNode()->getValue();
-
-               changed_blocks.insert(block->getPos(), block);
-       }
-
-       /*
-               Debug information
-       */
-       if(0)
-       {
-               dstream
-               <<"lighting_invalidated_blocks.size()"
-               <<", has_dungeons"
-               <<", completely_ug"
-               <<", some_part_ug"
-               <<"  "<<lighting_invalidated_blocks.size()
-               <<", "<<has_dungeons
-               <<", "<<completely_underground
-               <<", "<<some_part_underground
-               <<std::endl;
-       }
-
        /*
                Debug mode operation
        */
@@ -4027,8 +5354,10 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
                        <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
 }
 
-v3s16 ClientMap::setTempMod(v3s16 p, NodeMod mod, bool *changed)
+bool ClientMap::setTempMod(v3s16 p, NodeMod mod,
+               core::map<v3s16, MapBlock*> *affected_blocks)
 {
+       bool changed = false;
        /*
                Add it to all blocks touching it
        */
@@ -4053,14 +5382,29 @@ v3s16 ClientMap::setTempMod(v3s16 p, NodeMod mod, bool *changed)
                v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
                if(blockref->setTempMod(relpos, mod))
                {
-                       if(changed != NULL)
-                               *changed = true;
+                       changed = true;
+               }
+       }
+       if(changed && affected_blocks!=NULL)
+       {
+               for(u16 i=0; i<7; i++)
+               {
+                       v3s16 p2 = p + dirs[i];
+                       // Block position of neighbor (or requested) node
+                       v3s16 blockpos = getNodeBlockPos(p2);
+                       MapBlock * blockref = getBlockNoCreateNoEx(blockpos);
+                       if(blockref == NULL)
+                               continue;
+                       affected_blocks->insert(blockpos, blockref);
                }
        }
-       return getNodeBlockPos(p);
+       return changed;
 }
-v3s16 ClientMap::clearTempMod(v3s16 p, bool *changed)
+
+bool ClientMap::clearTempMod(v3s16 p,
+               core::map<v3s16, MapBlock*> *affected_blocks)
 {
+       bool changed = false;
        v3s16 dirs[7] = {
                v3s16(0,0,0), // this
                v3s16(0,0,1), // back
@@ -4082,11 +5426,23 @@ v3s16 ClientMap::clearTempMod(v3s16 p, bool *changed)
                v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
                if(blockref->clearTempMod(relpos))
                {
-                       if(changed != NULL)
-                               *changed = true;
+                       changed = true;
+               }
+       }
+       if(changed && affected_blocks!=NULL)
+       {
+               for(u16 i=0; i<7; i++)
+               {
+                       v3s16 p2 = p + dirs[i];
+                       // Block position of neighbor (or requested) node
+                       v3s16 blockpos = getNodeBlockPos(p2);
+                       MapBlock * blockref = getBlockNoCreateNoEx(blockpos);
+                       if(blockref == NULL)
+                               continue;
+                       affected_blocks->insert(blockpos, blockref);
                }
        }
-       return getNodeBlockPos(p);
+       return changed;
 }
 
 void ClientMap::PrintInfo(std::ostream &out)
@@ -4111,7 +5467,6 @@ MapVoxelManipulator::~MapVoxelManipulator()
                        <<std::endl;*/
 }
 
-#if 1
 void MapVoxelManipulator::emerge(VoxelArea a, s32 caller_id)
 {
        TimeTaker timer1("emerge", &emerge_time);
@@ -4169,54 +5524,14 @@ void MapVoxelManipulator::emerge(VoxelArea a, s32 caller_id)
                        }
                }
 
-               m_loaded_blocks.insert(p, true);
+               m_loaded_blocks.insert(p, !block_data_inexistent);
        }
 
        //dstream<<"emerge done"<<std::endl;
 }
-#endif
-
-#if 0
-/*
-       NOTE: This is slow
-*/
-void MapVoxelManipulator::emerge(VoxelArea a, s32 caller_id)
-{
-       TimeTaker timer1("emerge", &emerge_time);
-       
-       v3s16 size = a.getExtent();
-       
-       VoxelArea padded = a;
-       padded.pad(m_area.getExtent() / 4);
-       addArea(padded);
-
-       for(s16 z=0; z<size.Z; z++)
-       for(s16 y=0; y<size.Y; y++)
-       for(s16 x=0; x<size.X; x++)
-       {
-               v3s16 p(x,y,z);
-               s32 i = m_area.index(a.MinEdge + p);
-               // Don't touch nodes that have already been loaded
-               if(!(m_flags[i] & VOXELFLAG_NOT_LOADED))
-                       continue;
-               try
-               {
-                       TimeTaker timer1("emerge load", &emerge_load_time);
-                       MapNode n = m_map->getNode(a.MinEdge + p);
-                       m_data[i] = n;
-                       m_flags[i] = 0;
-               }
-               catch(InvalidPositionException &e)
-               {
-                       m_flags[i] = VOXELFLAG_INEXISTENT;
-               }
-       }
-}
-#endif
-
 
 /*
-       TODO: Add an option to only update eg. water and air nodes.
+       SUGG: Add an option to only update eg. water and air nodes.
              This will make it interfere less with important stuff if
                  run on background.
 */
@@ -4297,29 +5612,14 @@ ManualMapVoxelManipulator::~ManualMapVoxelManipulator()
 
 void ManualMapVoxelManipulator::emerge(VoxelArea a, s32 caller_id)
 {
-       // Just create the area to avoid segfaults
+       // Just create the area so that it can be pointed to
        VoxelManipulator::emerge(a, caller_id);
-
-       /*
-               Just create the area to avoid segfaults
-       */
-       /*addArea(a);
-       for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
-       for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++)
-       for(s32 x=a.MinEdge.X; x<=a.MaxEdge.X; x++)
-       {
-               s32 i = m_area.index(x,y,z);
-               // Don't touch nodes that have already been loaded
-               if(!(m_flags[i] & VOXELFLAG_NOT_LOADED))
-                       continue;
-               m_flags[i] = VOXELFLAG_INEXISTENT;
-       }*/
 }
 
 void ManualMapVoxelManipulator::initialEmerge(
                v3s16 blockpos_min, v3s16 blockpos_max)
 {
-       TimeTaker timer1("emerge", &emerge_time);
+       TimeTaker timer1("initialEmerge", &emerge_time);
 
        // Units of these are MapBlocks
        v3s16 p_min = blockpos_min;
@@ -4327,6 +5627,15 @@ void ManualMapVoxelManipulator::initialEmerge(
 
        VoxelArea block_area_nodes
                        (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
+       
+       u32 size_MB = block_area_nodes.getVolume()*4/1000000;
+       if(size_MB >= 1)
+       {
+               dstream<<"initialEmerge: area: ";
+               block_area_nodes.print(dstream);
+               dstream<<" ("<<size_MB<<"MB)";
+               dstream<<std::endl;
+       }
 
        addArea(block_area_nodes);
 
@@ -4358,6 +5667,9 @@ void ManualMapVoxelManipulator::initialEmerge(
 
                if(block_data_inexistent)
                {
+                       /*
+                               Mark area inexistent
+                       */
                        VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
                        // Fill with VOXELFLAG_INEXISTENT
                        for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
@@ -4368,7 +5680,41 @@ void ManualMapVoxelManipulator::initialEmerge(
                        }
                }
 
-               m_loaded_blocks.insert(p, true);
+               m_loaded_blocks.insert(p, !block_data_inexistent);
+       }
+}
+
+void ManualMapVoxelManipulator::blitBackAll(
+               core::map<v3s16, MapBlock*> * modified_blocks)
+{
+       if(m_area.getExtent() == v3s16(0,0,0))
+               return;
+       
+       /*
+               Copy data of all blocks
+       */
+       for(core::map<v3s16, bool>::Iterator
+                       i = m_loaded_blocks.getIterator();
+                       i.atEnd() == false; i++)
+       {
+               bool existed = i.getNode()->getValue();
+               if(existed == false)
+                       continue;
+               v3s16 p = i.getNode()->getKey();
+               MapBlock *block = m_map->getBlockNoCreateNoEx(p);
+               if(block == NULL)
+               {
+                       dstream<<"WARNING: "<<__FUNCTION_NAME
+                                       <<": got NULL block "
+                                       <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
+                                       <<std::endl;
+                       continue;
+               }
+
+               block->copyFrom(*this);
+
+               if(modified_blocks)
+                       modified_blocks->insert(p, block);
        }
 }