clientobject: add null checks
[waspsaliva.git] / src / mapsector.cpp
blob3eefa5410796ac5da4a805e98525116735c99b32
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "mapsector.h"
21 #include "exceptions.h"
22 #include "mapblock.h"
23 #include "serialization.h"
25 MapSector::MapSector(Map *parent, v2s16 pos, IGameDef *gamedef):
26 m_parent(parent),
27 m_pos(pos),
28 m_gamedef(gamedef)
32 MapSector::~MapSector()
34 deleteBlocks();
37 void MapSector::deleteBlocks()
39 // Clear cache
40 m_block_cache = nullptr;
42 // Delete all
43 for (auto &block : m_blocks) {
44 delete block.second;
47 // Clear container
48 m_blocks.clear();
51 MapBlock * MapSector::getBlockBuffered(s16 y)
53 MapBlock *block;
55 if (m_block_cache && y == m_block_cache_y) {
56 return m_block_cache;
59 // If block doesn't exist, return NULL
60 std::unordered_map<s16, MapBlock*>::const_iterator n = m_blocks.find(y);
61 block = (n != m_blocks.end() ? n->second : nullptr);
63 // Cache the last result
64 m_block_cache_y = y;
65 m_block_cache = block;
67 return block;
70 MapBlock * MapSector::getBlockNoCreateNoEx(s16 y)
72 return getBlockBuffered(y);
75 MapBlock * MapSector::createBlankBlockNoInsert(s16 y)
77 assert(getBlockBuffered(y) == NULL); // Pre-condition
79 v3s16 blockpos_map(m_pos.X, y, m_pos.Y);
81 MapBlock *block = new MapBlock(m_parent, blockpos_map, m_gamedef);
83 return block;
86 MapBlock * MapSector::createBlankBlock(s16 y)
88 MapBlock *block = createBlankBlockNoInsert(y);
90 m_blocks[y] = block;
92 return block;
95 void MapSector::insertBlock(MapBlock *block)
97 s16 block_y = block->getPos().Y;
99 MapBlock *block2 = getBlockBuffered(block_y);
100 if (block2) {
101 throw AlreadyExistsException("Block already exists");
104 v2s16 p2d(block->getPos().X, block->getPos().Z);
105 assert(p2d == m_pos);
107 // Insert into container
108 m_blocks[block_y] = block;
111 void MapSector::deleteBlock(MapBlock *block)
113 s16 block_y = block->getPos().Y;
115 // Clear from cache
116 m_block_cache = nullptr;
118 // Remove from container
119 m_blocks.erase(block_y);
121 // Delete
122 delete block;
125 void MapSector::getBlocks(MapBlockVect &dest)
127 for (auto &block : m_blocks) {
128 dest.push_back(block.second);