diff options
author | LaG1924 <12997935+LaG1924@users.noreply.github.com> | 2023-07-08 21:41:27 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-07-08 21:41:27 +0200 |
commit | a68f48ad526d0843eb451af0be7f119db5ff794e (patch) | |
tree | 3c539c9e7de841c6616f532dadb7c8c1ef552d95 | |
parent | Merge pull request #80 from LaG1924/ftr/better-water (diff) | |
parent | Fixed some errors detected by static analysis (diff) | |
download | AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar.gz AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar.bz2 AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar.lz AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar.xz AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.tar.zst AltCraft-a68f48ad526d0843eb451af0be7f119db5ff794e.zip |
-rw-r--r-- | src/AssetManager.cpp | 71 | ||||
-rw-r--r-- | src/AssetManager.hpp | 2 | ||||
-rw-r--r-- | src/Block.cpp | 6 | ||||
-rw-r--r-- | src/Block.hpp | 8 | ||||
-rw-r--r-- | src/Collision.cpp | 2 | ||||
-rw-r--r-- | src/Collision.hpp | 2 | ||||
-rw-r--r-- | src/Entity.hpp | 2 | ||||
-rw-r--r-- | src/Gal.hpp | 2 | ||||
-rw-r--r-- | src/GalOgl.cpp | 38 | ||||
-rw-r--r-- | src/GameState.cpp | 16 | ||||
-rw-r--r-- | src/Network.cpp | 26 | ||||
-rw-r--r-- | src/Network.hpp | 9 | ||||
-rw-r--r-- | src/NetworkClient.cpp | 2 | ||||
-rw-r--r-- | src/Packet.hpp | 6 | ||||
-rw-r--r-- | src/Plugin.cpp | 18 | ||||
-rw-r--r-- | src/Render.cpp | 13 | ||||
-rw-r--r-- | src/Render.hpp | 6 | ||||
-rw-r--r-- | src/RenderConfigs.cpp | 2 | ||||
-rw-r--r-- | src/RendererEntity.hpp | 1 | ||||
-rw-r--r-- | src/RendererSection.cpp | 4 | ||||
-rw-r--r-- | src/RendererSection.hpp | 2 | ||||
-rw-r--r-- | src/RendererSectionData.cpp | 11 | ||||
-rw-r--r-- | src/RendererWorld.cpp | 21 | ||||
-rw-r--r-- | src/Rml.cpp | 5 | ||||
-rw-r--r-- | src/Rml.hpp | 2 | ||||
-rw-r--r-- | src/Settings.cpp | 4 | ||||
-rw-r--r-- | src/TextureAtlas.cpp | 7 | ||||
-rw-r--r-- | src/Utility.cpp | 4 | ||||
-rw-r--r-- | src/Utility.hpp | 2 | ||||
-rw-r--r-- | src/Vector.hpp | 19 | ||||
-rw-r--r-- | src/Window.cpp | 4 | ||||
-rw-r--r-- | src/World.cpp | 41 | ||||
-rw-r--r-- | src/World.hpp | 30 |
33 files changed, 207 insertions, 181 deletions
diff --git a/src/AssetManager.cpp b/src/AssetManager.cpp index 09f5209..7f3c4ba 100644 --- a/src/AssetManager.cpp +++ b/src/AssetManager.cpp @@ -129,10 +129,10 @@ void LoadScripts() { LOG(INFO) << "Scripts loaded"; } -void WalkDirEntry(const fs::directory_entry &dirEntry, AssetTreeNode *node) { - for (auto &file : fs::directory_iterator(dirEntry)) { +void WalkDirEntry(const fs::directory_entry& dirEntry, AssetTreeNode* node) { + for (auto& file : fs::directory_iterator(dirEntry)) { node->childs.push_back(std::make_unique<AssetTreeNode>()); - AssetTreeNode *fileNode = node->childs.back().get(); + AssetTreeNode* fileNode = node->childs.back().get(); fileNode->parent = node; fileNode->name = file.path().stem().string(); if (fs::is_directory(file)) { @@ -141,9 +141,13 @@ void WalkDirEntry(const fs::directory_entry &dirEntry, AssetTreeNode *node) { else { size_t fileSize = fs::file_size(file); fileNode->data.resize(fileSize); - FILE *f = fopen(file.path().string().c_str(), "rb"); - fread(fileNode->data.data(), 1, fileSize, f); - fclose(f); + FILE* f = fopen(file.path().string().c_str(), "rb"); + if (f) { + fread(fileNode->data.data(), 1, fileSize, f); + fclose(f); + } + else + LOG(WARNING) << "Can't open asset file " << file.path().string(); } } } @@ -188,7 +192,8 @@ void ParseAssetTexture(AssetTreeNode &node) { node.asset = std::make_unique<AssetTexture>(); AssetTexture *asset = dynamic_cast<AssetTexture*>(node.asset.get()); size_t dataLen = w * h * 4; - asset->textureData.resize(dataLen); + if (asset) + asset->textureData.resize(dataLen); std::memcpy(asset->textureData.data(), data, dataLen); asset->realWidth = w; asset->realHeight = h; @@ -280,7 +285,7 @@ void ParseAssetBlockModel(AssetTreeNode &node) { auto face = faceIt.value(); BlockModel::ElementData::FaceData faceData; - FaceDirection faceDir; + FaceDirection faceDir = FaceDirection::none; if (faceIt.key() == "down") faceDir = FaceDirection::down; else if (faceIt.key() == "up") @@ -336,7 +341,8 @@ void ParseAssetBlockModel(AssetTreeNode &node) { } node.asset = std::make_unique<AssetBlockModel>(); - dynamic_cast<AssetBlockModel*>(node.asset.get())->blockModel = model; + if (node.asset) + dynamic_cast<AssetBlockModel*>(node.asset.get())->blockModel = model; node.data.clear(); node.data.shrink_to_fit(); } @@ -350,11 +356,11 @@ void ParseAssetBlockState(AssetTreeNode &node) { j = j["variants"]; for (auto variantIt = j.begin(); variantIt != j.end(); variantIt++) { - std::string variantName = variantIt.key(); BlockStateVariant variant; - variant.variantName = variantName; - if (variantIt.value().is_array()) { - for (auto &it : variantIt.value()) { + variant.variantName = variantIt.key(); + const auto& variantValue = variantIt.value(); + if (variantValue.is_array()) { + for (auto &it : variantValue) { BlockStateVariant::Model model; model.modelName = it["model"].get<std::string>(); if (it.count("x")) @@ -369,15 +375,15 @@ void ParseAssetBlockState(AssetTreeNode &node) { } } else { BlockStateVariant::Model model; - model.modelName = variantIt.value()["model"].get<std::string>(); - if (variantIt.value().count("x")) - model.x = variantIt.value()["x"].get<int>(); - if (variantIt.value().count("y")) - model.y = variantIt.value()["y"].get<int>(); - if (variantIt.value().count("uvlock")) - model.uvLock = variantIt.value()["uvlock"].get<int>(); - if (variantIt.value().count("weight")) - model.weight = variantIt.value()["weight"].get<int>(); + model.modelName = variantValue["model"].get<std::string>(); + if (variantValue.count("x")) + model.x = variantValue["x"].get<int>(); + if (variantValue.count("y")) + model.y = variantValue["y"].get<int>(); + if (variantValue.count("uvlock")) + model.uvLock = variantValue["uvlock"].get<int>(); + if (variantValue.count("weight")) + model.weight = variantValue["weight"].get<int>(); variant.models.push_back(model); } blockState.variants[variant.variantName] = variant; @@ -385,7 +391,8 @@ void ParseAssetBlockState(AssetTreeNode &node) { node.asset = std::make_unique<AssetBlockState>(); AssetBlockState *asset = dynamic_cast<AssetBlockState*>(node.asset.get()); - asset->blockState = blockState; + if (asset) + asset->blockState = blockState; node.data.clear(); node.data.shrink_to_fit(); @@ -398,7 +405,8 @@ void ParseAssetShader(AssetTreeNode &node) { void ParseAssetScript(AssetTreeNode &node) { node.asset = std::make_unique<AssetScript>(); AssetScript *asset = dynamic_cast<AssetScript*>(node.asset.get()); - asset->code = std::string((char*)node.data.data(), (char*)node.data.data() + node.data.size()); + if (asset) + asset->code = std::string((char*)node.data.data(), (char*)node.data.data() + node.data.size()); } void ParseBlockModels() { @@ -408,6 +416,9 @@ void ParseBlockModels() { if (!node.asset) return; + if (!dynamic_cast<AssetBlockModel*>(node.asset.get())) + return; + BlockModel &model = dynamic_cast<AssetBlockModel*>(node.asset.get())->blockModel; for (const auto& element : model.Elements) { Vector t = element.to - element.from; @@ -421,7 +432,7 @@ void ParseBlockModels() { static const glm::vec3 yAxis(0.0f, 1.0f, 0.0f); static const glm::vec3 zAxis(0.0f, 0.0f, 1.0f); - const glm::vec3 *targetAxis = nullptr; + const glm::vec3 *targetAxis = &xAxis; switch (element.rotationAxis) { case BlockModel::ElementData::Axis::x: targetAxis = &xAxis; @@ -533,7 +544,7 @@ void ParseBlockModels() { if (!(face.second.uv == BlockModel::ElementData::FaceData::Uv{ 0,16,0,16 }) && !(face.second.uv == BlockModel::ElementData::FaceData::Uv{ 0,0,0,0 }) && !(face.second.uv == BlockModel::ElementData::FaceData::Uv{ 0,0,16,16 })) { double x = face.second.uv.x1; - double y = face.second.uv.x1; + double y = face.second.uv.y1; double w = face.second.uv.x2 - face.second.uv.x1; double h = face.second.uv.y2 - face.second.uv.y1; x /= 16.0; @@ -617,7 +628,7 @@ BlockFaces &AssetManager::GetBlockModelByBlockId(BlockId block) { }); } - return blockIdToBlockFaces.insert(std::make_pair(block, blockFaces)).first->second; + return blockIdToBlockFaces.try_emplace(block, blockFaces).first->second; } AssetBlockState *asset = GetAsset<AssetBlockState>("/minecraft/blockstates/" + blockInfo->blockstate); if (!asset) @@ -663,7 +674,7 @@ BlockFaces &AssetManager::GetBlockModelByBlockId(BlockId block) { blockFaces.faceDirectionVector[i] = Vector(roundf(vec.x), roundf(vec.y), roundf(vec.z)); } - return blockIdToBlockFaces.insert(std::make_pair(block, blockFaces)).first->second; + return blockIdToBlockFaces.try_emplace(block, blockFaces).first->second; } Asset *AssetManager::GetAssetPtr(const std::string & assetName) { @@ -697,7 +708,7 @@ AssetTreeNode *AssetManager::GetAssetByAssetName(const std::string & assetName) unsigned int prevPos = 1; size_t x = assetName.size(); while (pos < assetName.size()) { - for (; assetName[pos] != '/' && pos < assetName.size(); pos++); + for (; pos < assetName.size() && assetName[pos] != '/'; pos++); std::string dirName = assetName.substr(prevPos, pos - prevPos); for (const auto &asset : node->childs) { if (asset->name == dirName) { @@ -716,7 +727,7 @@ std::shared_ptr<Gal::Texture> AssetManager::GetTextureAtlas() return atlas->GetGalTexture(); } -TextureCoord AssetManager::GetTexture(const std::string assetName) { +TextureCoord AssetManager::GetTexture(const std::string &assetName) { AssetTexture *asset = GetAsset<AssetTexture>(assetName); if (!asset) return GetTexture("/minecraft/textures/error"); diff --git a/src/AssetManager.hpp b/src/AssetManager.hpp index 250524e..bd16577 100644 --- a/src/AssetManager.hpp +++ b/src/AssetManager.hpp @@ -200,5 +200,5 @@ namespace AssetManager { std::shared_ptr<Gal::Texture> GetTextureAtlas(); - TextureCoord GetTexture(const std::string assetName); + TextureCoord GetTexture(const std::string &assetName); }; diff --git a/src/Block.cpp b/src/Block.cpp index 8af5a4b..70ad75b 100644 --- a/src/Block.cpp +++ b/src/Block.cpp @@ -9,13 +9,13 @@ static BlockInfo UnknownBlock{ true, "", "" }; static LiquidInfo UnknownLiquid{ "", "" }; void RegisterStaticBlockInfo(BlockId blockId, BlockInfo blockInfo) { - blocks.emplace(blockId, blockInfo); + blocks.try_emplace(blockId, blockInfo); } -void RegisterStaticLiquidInfo(BlockId blockId, LiquidInfo liquidInfo) { +void RegisterStaticLiquidInfo(BlockId blockId, const LiquidInfo& liquidInfo) { liquids[blockId] = liquidInfo; for (uint8_t i = 0; i < 16; i++) - blocks.emplace(BlockId{ blockId.id, i }, BlockInfo{ true, "@liquid", liquidInfo.stillTexture }); + blocks.try_emplace(BlockId{ blockId.id, i }, BlockInfo{ true, "@liquid", liquidInfo.stillTexture }); } BlockInfo* GetBlockInfo(BlockId blockId) { diff --git a/src/Block.hpp b/src/Block.hpp index 535ae68..c1883ab 100644 --- a/src/Block.hpp +++ b/src/Block.hpp @@ -19,11 +19,11 @@ enum BlockFacing { East }; -inline bool operator==(const BlockId& lhs, const BlockId &rhs) { +inline bool operator==(BlockId lhs, BlockId rhs) { return (lhs.id == rhs.id) && (lhs.state == rhs.state); } -inline bool operator<(const BlockId& lhs, const BlockId &rhs) { +inline bool operator<(BlockId lhs, BlockId rhs) { if (lhs.id != rhs.id) return lhs.id < rhs.id; return lhs.state < rhs.state; @@ -32,7 +32,7 @@ inline bool operator<(const BlockId& lhs, const BlockId &rhs) { namespace std { template <> struct hash<BlockId> { - std::size_t operator()(const BlockId& k) const { + std::size_t operator()(BlockId k) const { size_t id = std::hash<unsigned short>()(k.id); size_t state = std::hash<unsigned char>()(k.state); @@ -54,7 +54,7 @@ struct LiquidInfo { void RegisterStaticBlockInfo(BlockId blockId, BlockInfo blockInfo); -void RegisterStaticLiquidInfo(BlockId blockId, LiquidInfo liquidInfo); +void RegisterStaticLiquidInfo(BlockId blockId, const LiquidInfo& liquidInfo); BlockInfo* GetBlockInfo(BlockId blockId); diff --git a/src/Collision.cpp b/src/Collision.cpp index 4f2c837..0caad03 100644 --- a/src/Collision.cpp +++ b/src/Collision.cpp @@ -1,6 +1,6 @@ #include "Collision.hpp" -bool TestCollision(AABB first, AABB second) { +bool TestCollision(const AABB& first, const AABB& second) { double firstXl = first.x; double firstXr = first.x + first.w; diff --git a/src/Collision.hpp b/src/Collision.hpp index b88fbf7..be4cb97 100644 --- a/src/Collision.hpp +++ b/src/Collision.hpp @@ -5,4 +5,4 @@ struct AABB { double w,l,h; }; -bool TestCollision(AABB first, AABB second);
\ No newline at end of file +bool TestCollision(const AABB& first, const AABB& second);
\ No newline at end of file diff --git a/src/Entity.hpp b/src/Entity.hpp index 2b1a041..bbcb5c7 100644 --- a/src/Entity.hpp +++ b/src/Entity.hpp @@ -135,7 +135,7 @@ struct Entity { double height = 1.0; glm::vec3 renderColor; int entityType=0; - EntityType type; + EntityType type = EntityType::Object; bool isSolid = true; double gravity = 32.0; // in m/s^2 double drag = 0.4; diff --git a/src/Gal.hpp b/src/Gal.hpp index ed0b559..a12bdb7 100644 --- a/src/Gal.hpp +++ b/src/Gal.hpp @@ -96,7 +96,7 @@ namespace Gal { struct VertexAttribute { std::string name; - Type type; + Type type = Type::Float; size_t count = 1; size_t instances = 0; }; diff --git a/src/GalOgl.cpp b/src/GalOgl.cpp index b046d4b..a258cdc 100644 --- a/src/GalOgl.cpp +++ b/src/GalOgl.cpp @@ -678,11 +678,11 @@ struct BufferOgl : public Buffer { struct TextureConfigOgl : public TextureConfig { - Format format; + Format format = Format::R8; size_t width = 1, height = 1, depth = 1; bool interpolateLayers = false; bool linear = true; - GLenum type; + GLenum type = 0; Filtering min = Filtering::Nearest, max = Filtering::Nearest; Wrapping wrap = Wrapping::Clamp; @@ -759,8 +759,8 @@ struct TextureOgl : public Texture { oglState.BindTexture(type, 0); } - virtual void SetSubData(size_t x, size_t y, size_t z, size_t width, size_t height, size_t depth, std::vector<std::byte>&& data, size_t mipLevel = 0) override { - size_t expectedSize = width * height * depth * GalFormatGetSize(format); + virtual void SetSubData(size_t x, size_t y, size_t z, size_t w, size_t h, size_t d, std::vector<std::byte>&& data, size_t mipLevel = 0) override { + size_t expectedSize = w * h * d * GalFormatGetSize(format); if (data.size() != expectedSize) throw std::logic_error("Size of data is not valid for this texture"); @@ -783,13 +783,13 @@ struct TextureOgl : public Texture { case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: case GL_PROXY_TEXTURE_CUBE_MAP: - glTexSubImage2D(type, mipLevel, x, y, width, height, GalFormatGetGlFormat(format), GalFormatGetGlType(format), data.data()); + glTexSubImage2D(type, mipLevel, x, y, w, h, GalFormatGetGlFormat(format), GalFormatGetGlType(format), data.data()); break; case GL_TEXTURE_3D: case GL_PROXY_TEXTURE_3D: case GL_TEXTURE_2D_ARRAY: case GL_PROXY_TEXTURE_2D_ARRAY: - glTexSubImage3D(type, mipLevel, x, y, z, width, height, depth, GalFormatGetGlFormat(format), GalFormatGetGlType(format), data.data()); + glTexSubImage3D(type, mipLevel, x, y, z, w, h, d, GalFormatGetGlFormat(format), GalFormatGetGlType(format), data.data()); break; default: throw std::runtime_error("Unknown texture type"); @@ -842,7 +842,7 @@ struct FramebufferConfigOgl : public FramebufferConfig { virtual void SetTexture(size_t location, std::shared_ptr<Texture> texture) override { auto tex = std::static_pointer_cast<TextureOgl, Texture>(texture); - colors.emplace(location, tex); + colors.try_emplace(location, tex); } }; @@ -881,12 +881,12 @@ struct PipelineConfigOgl : public PipelineConfig { } virtual void AddShaderParameter(std::string_view name, Type type) override { - shaderParameters.emplace(std::string(name), type); + shaderParameters.try_emplace(std::string(name), type); } virtual void AddStaticTexture(std::string_view name, std::shared_ptr<Texture> texture) override { auto tex = std::static_pointer_cast<TextureOgl, Texture>(texture); - textures.emplace(std::string(name), tex); + textures.try_emplace(std::string(name), tex); } virtual void SetTarget(std::shared_ptr<Framebuffer> target) override { @@ -919,7 +919,7 @@ struct PipelineInstanceOgl : public PipelineInstance { GlResource vao; bool useIndex = false; - Primitive primitive; + Primitive primitive = Primitive::Triangle; size_t instances = 0; virtual void Activate() override { @@ -1031,7 +1031,7 @@ struct PipelineOgl : public Pipeline { if (bind->bufferId == BufferBindingOgl::indexValue) indexBuffer = buff->vbo; else - bufferBindingId.insert({ bind->bufferId,buff->vbo }); + bufferBindingId.try_emplace(bind->bufferId, buff->vbo); } GLuint newVao; @@ -1040,7 +1040,10 @@ struct PipelineOgl : public Pipeline { oglState.BindVao(instance->vao); for (const auto& cmd : vertexBindCmds) { - oglState.BindVbo(bufferBindingId.find(cmd.bufferId)->second); + auto it = bufferBindingId.find(cmd.bufferId); + if (it == bufferBindingId.end()) + continue; + oglState.BindVbo(it->second); switch (cmd.type) { case GL_FLOAT: case GL_DOUBLE: @@ -1055,7 +1058,7 @@ struct PipelineOgl : public Pipeline { glVertexAttribIPointer(cmd.location, cmd.count, cmd.type, cmd.offset, reinterpret_cast<void*>(cmd.stride)); break; } - + glEnableVertexAttribArray(cmd.location); if (cmd.instances) { glVertexAttribDivisor(cmd.location, cmd.instances); @@ -1407,7 +1410,8 @@ struct ImplOgl : public Impl { size_t bufferId = 0; for (const auto& buffer : config->vertexBuffers) { size_t vertexSize = 0; - size_t cmdOffset = pipeline->vertexBindCmds.size(); + auto& binds = pipeline->vertexBindCmds; + size_t cmdOffset = binds.size(); for (const auto& [name, type, count, instances] : buffer) { if (name.empty()) { vertexSize += GalTypeGetSize(type) * count; @@ -1427,7 +1431,7 @@ struct ImplOgl : public Impl { continue; } - pipeline->vertexBindCmds.push_back({ + binds.push_back({ bufferId, static_cast<size_t>(location + i), GalTypeGetComponentGlType(type), @@ -1441,8 +1445,8 @@ struct ImplOgl : public Impl { } } - for (size_t i = cmdOffset; i < pipeline->vertexBindCmds.size(); i++) - pipeline->vertexBindCmds[i].offset = vertexSize; + for (size_t i = cmdOffset; i < binds.size(); i++) + binds[i].offset = vertexSize; bufferId++; } diff --git a/src/GameState.cpp b/src/GameState.cpp index 89743e4..e6f988d 100644 --- a/src/GameState.cpp +++ b/src/GameState.cpp @@ -512,6 +512,10 @@ void GameState::UpdatePacket(std::shared_ptr<Packet> ptr) { break; case EntityEffect: break; + + default: + LOG(WARNING) << "Server sent unknown packet"; + break; } while (!playerInventory.pendingTransactions.empty()) { @@ -642,7 +646,7 @@ void GameState::CancelDigging() { PUSH_EVENT("SendPacket", packet); } -BlockFacing detectHitFace(VectorF raycastHit, Vector selectedBlock) { +BlockFacing detectHitFace(const VectorF& raycastHit, const Vector& selectedBlock) { auto vec = VectorF(selectedBlock.x + .5, selectedBlock.y + .5, selectedBlock.z + .5) - raycastHit; // TODO: move these vectors to Vector.hpp @@ -658,15 +662,15 @@ BlockFacing detectHitFace(VectorF raycastHit, Vector selectedBlock) { const double backward = -forward; const double min_cos = _min(up, down, right, left, forward, backward); - if (min_cos == down) + if (std::abs(min_cos - down) < DBL_EPSILON) return BlockFacing::Bottom; - else if (min_cos == up) + else if (std::abs(min_cos - up) < DBL_EPSILON) return BlockFacing::Top; - else if (min_cos == forward) + else if (std::abs(min_cos - forward) < DBL_EPSILON) return BlockFacing::North; - else if (min_cos == backward) + else if (std::abs(min_cos - backward) < DBL_EPSILON) return BlockFacing::South; - else if (min_cos == left) + else if (std::abs(min_cos - left) < DBL_EPSILON) return BlockFacing::West; else return BlockFacing::East; } diff --git a/src/Network.cpp b/src/Network.cpp index 4332c29..54a7d3e 100644 --- a/src/Network.cpp +++ b/src/Network.cpp @@ -37,18 +37,18 @@ std::shared_ptr<Packet> Network::ReceivePacket(ConnectionState state, bool useCo std::vector<unsigned char> uncompressedData; uncompressedData.resize(dataLength); - z_stream stream; - stream.avail_in = compressedData.size(); - stream.next_in = compressedData.data(); - stream.avail_out = uncompressedData.size(); - stream.next_out = uncompressedData.data(); - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - if (inflateInit(&stream) != Z_OK) + z_stream zStream; + zStream.avail_in = compressedData.size(); + zStream.next_in = compressedData.data(); + zStream.avail_out = uncompressedData.size(); + zStream.next_out = uncompressedData.data(); + zStream.zalloc = Z_NULL; + zStream.zfree = Z_NULL; + zStream.opaque = Z_NULL; + if (inflateInit(&zStream) != Z_OK) throw std::runtime_error("Zlib decompression initalization error"); - int status = inflate(&stream, Z_FINISH); + int status = inflate(&zStream, Z_FINISH); switch (status) { case Z_STREAM_END: break; @@ -58,7 +58,7 @@ std::shared_ptr<Packet> Network::ReceivePacket(ConnectionState state, bool useCo throw std::runtime_error("Zlib decompression error: " + std::to_string(status)); } - if (inflateEnd(&stream) != Z_OK) + if (inflateEnd(&zStream) != Z_OK) throw std::runtime_error("Zlib decompression end error"); StreamBuffer streamBuffer(uncompressedData.data(), uncompressedData.size()); @@ -102,7 +102,7 @@ void Network::SendPacket(Packet &packet, int compressionThreshold) { stream->Flush(); } -std::shared_ptr<Packet> Network::ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &stream) { +std::shared_ptr<Packet> Network::ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &in) { std::shared_ptr < Packet > packet(nullptr); switch (state) { case Handshaking: @@ -132,7 +132,7 @@ std::shared_ptr<Packet> Network::ReceivePacketByPacketId(int packetId, Connectio break; } if (packet.get() != nullptr) - packet->FromStream(&stream); + packet->FromStream(&in); return packet; } diff --git a/src/Network.hpp b/src/Network.hpp index 29a090f..2640e0f 100644 --- a/src/Network.hpp +++ b/src/Network.hpp @@ -14,10 +14,17 @@ class Network { std::unique_ptr<Socket> socket; std::unique_ptr<StreamSocket> stream; - std::shared_ptr<Packet> ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &stream); + std::shared_ptr<Packet> ReceivePacketByPacketId(int packetId, ConnectionState state, StreamInput &in); public: Network(std::string address, unsigned short port); + Network(const Network&) = delete; + + Network(Network&&) = default; + + Network& operator=(const Network&) = delete; + Network& operator=(Network&&) = default; + ~Network(); std::shared_ptr<Packet> ReceivePacket(ConnectionState state = Play, bool useCompression = false); diff --git a/src/NetworkClient.cpp b/src/NetworkClient.cpp index ee79fb9..a8660fe 100644 --- a/src/NetworkClient.cpp +++ b/src/NetworkClient.cpp @@ -11,7 +11,7 @@ NetworkClient::NetworkClient(std::string address, unsigned short port, std::stri PacketHandshake handshake; handshake.protocolVersion = 340; - handshake.serverAddress = address; + handshake.serverAddress = std::move(address); handshake.serverPort = port; handshake.nextState = 2; network->SendPacket(handshake); diff --git a/src/Packet.hpp b/src/Packet.hpp index 56a2e5e..00e151a 100644 --- a/src/Packet.hpp +++ b/src/Packet.hpp @@ -1091,7 +1091,7 @@ struct PacketChatMessageSB : Packet { std::string Message; - PacketChatMessageSB(const std::string msg) : Message(msg) {}; + PacketChatMessageSB(const std::string& msg) : Message(msg) {}; }; struct PacketPlayerDigging : Packet { @@ -1184,7 +1184,7 @@ struct PacketPluginMessageSB : Packet { return PacketNamePlaySB::PluginMessageSB; } - PacketPluginMessageSB(const std::string& channel, const std::vector<unsigned char> data) : Channel(channel), Data(data) {} + PacketPluginMessageSB(const std::string& channel, const std::vector<unsigned char>& data) : Channel(channel), Data(data) {} std::string Channel; std::vector<unsigned char> Data; @@ -1209,7 +1209,7 @@ struct PacketClientSettings : Packet { } PacketClientSettings( - const std::string locale, + const std::string& locale, unsigned char viewDistance, int chatMode, bool chatColors, diff --git a/src/Plugin.cpp b/src/Plugin.cpp index 7a3b716..22afb90 100644 --- a/src/Plugin.cpp +++ b/src/Plugin.cpp @@ -54,15 +54,15 @@ namespace PluginApi { LOG(INFO) << "Loaded plugin " << (!nativePlugin.displayName.empty() ? nativePlugin.displayName : nativePlugin.name); } - void LogWarning(std::string text) { + void LogWarning(const std::string& text) { LOG(WARNING) << text; } - void LogInfo(std::string text) { + void LogInfo(const std::string& text) { LOG(INFO) << text; } - void LogError(std::string text) { + void LogError(const std::string& text) { LOG(ERROR) << text; } @@ -70,7 +70,7 @@ namespace PluginApi { return ::GetGameState(); } - void RegisterBlock(BlockId blockId, bool collides, std::string blockstate, std::string variant) { + void RegisterBlock(BlockId blockId, bool collides, const std::string& blockstate, const std::string& variant) { RegisterStaticBlockInfo(blockId, BlockInfo{ collides, blockstate, @@ -78,18 +78,18 @@ namespace PluginApi { }); } - void RegisterLiquid(BlockId blockId, std::string flowTexture, std::string stillTexture) { + void RegisterLiquid(BlockId blockId, const std::string& flowTexture, const std::string& stillTexture) { RegisterStaticLiquidInfo(blockId, LiquidInfo{ flowTexture, stillTexture }); } - void RegisterDimension(int dimId, Dimension dim) { + void RegisterDimension(int dimId, const Dimension& dim) { RegisterNewDimension(dimId, dim); } - void ConnectToServer(std::string host, std::string username) { + void ConnectToServer(const std::string& host, const std::string& username) { size_t index = host.find_last_of(':'); unsigned short port; if (index == std::string::npos) @@ -231,8 +231,8 @@ void PluginSystem::Init() { "GetEntitiesList", &World::GetEntitiesList, "GetEntity",&World::GetEntityPtr, "Raycast", &World::Raycast, - "GetBlockLight", sol::resolve<unsigned char(Vector)const>(&World::GetBlockLight), - "GetBlockSkyLight", sol::resolve<unsigned char(Vector)const>(&World::GetBlockSkyLight), + "GetBlockLight", sol::resolve<unsigned char(const Vector&)const>(&World::GetBlockLight), + "GetBlockSkyLight", sol::resolve<unsigned char(const Vector&)const>(&World::GetBlockSkyLight), "GetBlockId", &World::GetBlockId, "SetBlockId", &World::SetBlockId); diff --git a/src/Render.cpp b/src/Render.cpp index fe9dc04..ce5fdca 100644 --- a/src/Render.cpp +++ b/src/Render.cpp @@ -52,13 +52,13 @@ inline int ConvertKeymodsSdlToRml(unsigned short keyMods) { return ret; } -Render::Render(unsigned int windowWidth, unsigned int windowHeight, - std::string windowTitle) { +Render::Render(unsigned int width, unsigned int height, + std::string title) { InitEvents(); Settings::Load(); - InitSdl(windowWidth, windowHeight, windowTitle); + InitSdl(width, height, title); glCheckError(); InitGlew(); glCheckError(); @@ -615,17 +615,14 @@ void Render::InitEvents() { } - float mouseSensetivity = Settings::ReadDouble("mouseSensetivity", 0.1f); - if (mouseSensetivity != sensetivity) - sensetivity = mouseSensetivity; + sensetivity = Settings::ReadDouble("mouseSensetivity", 0.1f); if (GetGameState()) { bool flight = Settings::ReadBool("flight", false); GetGameState()->GetPlayer()->isFlying = flight; } - bool wireframe = Settings::ReadBool("wireframe", false); - isWireframe = wireframe; + isWireframe = Settings::ReadBool("wireframe", false); float targetFps = Settings::ReadDouble("targetFps", 60.0f); GetTime()->SetDelayLength(std::chrono::duration<double, std::milli>(1.0 / targetFps * 1000.0)); diff --git a/src/Render.hpp b/src/Render.hpp index 3ac76e3..a0e5b96 100644 --- a/src/Render.hpp +++ b/src/Render.hpp @@ -28,8 +28,8 @@ class Render { bool renderGui = false; bool isMouseCaptured = false; - int prevMouseX, prevMouseY; - float mouseXDelta, mouseYDelta; + int prevMouseX=0, prevMouseY=0; + float mouseXDelta=0.0f, mouseYDelta=0.0f; std::unique_ptr<RendererWorld> world; bool renderWorld = false; size_t windowWidth, windowHeight; @@ -76,7 +76,7 @@ class Render { void InitRml(); public: - Render(unsigned int windowWidth, unsigned int windowHeight, std::string windowTitle); + Render(unsigned int width, unsigned int height, std::string title); ~Render(); void Update(); diff --git a/src/RenderConfigs.cpp b/src/RenderConfigs.cpp index 78b442d..ad39924 100644 --- a/src/RenderConfigs.cpp +++ b/src/RenderConfigs.cpp @@ -77,7 +77,7 @@ TextureFbCopy::TextureFbCopy( auto gal = Gal::GetImplementation(); - framebuffer = outputFb; + framebuffer = std::move(outputFb); auto fbPPC = gal->CreatePipelineConfig(); fbPPC->SetTarget(framebuffer); diff --git a/src/RendererEntity.hpp b/src/RendererEntity.hpp index b9097bd..2c62956 100644 --- a/src/RendererEntity.hpp +++ b/src/RendererEntity.hpp @@ -6,7 +6,6 @@ class World; class RendererEntity { unsigned int entityId; - std::shared_ptr<Gal::Pipeline> pipeline; public: RendererEntity(unsigned int id); diff --git a/src/RendererSection.cpp b/src/RendererSection.cpp index 7ea74df..817a3c2 100644 --- a/src/RendererSection.cpp +++ b/src/RendererSection.cpp @@ -38,10 +38,6 @@ RendererSection::RendererSection(RendererSection && other) { swap(*this, other); } -RendererSection::~RendererSection() { - -} - void RendererSection::RenderSolid() { OPTICK_EVENT(); solidPipelineInstance->Activate(); diff --git a/src/RendererSection.hpp b/src/RendererSection.hpp index 8125e4e..700e1e5 100644 --- a/src/RendererSection.hpp +++ b/src/RendererSection.hpp @@ -27,8 +27,6 @@ public: RendererSection(RendererSection &&other); - ~RendererSection(); - void RenderSolid(); void RenderLiquid(); diff --git a/src/RendererSectionData.cpp b/src/RendererSectionData.cpp index fdd961d..156d6a3 100644 --- a/src/RendererSectionData.cpp +++ b/src/RendererSectionData.cpp @@ -16,7 +16,7 @@ inline const BlockId& GetBlockId(int x, int y, int z, const std::array<BlockId, return blockIdData[y * 256 + z * 16 + x]; } -glm::vec2 TransformTextureCoord(glm::vec4 TextureAtlasCoords, glm::vec2 UvCoords, float frames) { +glm::vec2 TransformTextureCoord(const glm::vec4& TextureAtlasCoords, const glm::vec2& UvCoords, float frames) { float x = TextureAtlasCoords.x; float y = TextureAtlasCoords.y; float w = TextureAtlasCoords.z; @@ -131,7 +131,7 @@ void AddFacesByBlockModel(RendererSectionData& data, const BlockFaces& model, co } } -void AddLiquidFacesByBlockModel(RendererSectionData& data, const BlockId& blockId, const BlockFaces& model, const glm::mat4& transform, bool visibility[FaceDirection::none], const Vector& pos, const SectionsData& sections, bool smoothLighting) { +void AddLiquidFacesByBlockModel(RendererSectionData& data, BlockId blockId, const BlockFaces& model, const glm::mat4& transform, bool visibility[FaceDirection::none], const Vector& pos, const SectionsData& sections, bool smoothLighting) { const ParsedFace& flowData = model.faces[0]; const ParsedFace& stillData = model.faces[1]; size_t addedFaces = 0; @@ -241,7 +241,7 @@ void AddLiquidFacesByBlockModel(RendererSectionData& data, const BlockId& blockI if (!neighborsLiquids[FaceDirection::up]) { addedFaces++; - FaceDirection flowDirection = FaceDirection::north; + FaceDirection flowDirection = FaceDirection::none; if (nwCorner.y + swCorner.y > neCorner.y + seCorner.y) flowDirection = FaceDirection::east; else if (neCorner.y + seCorner.y > nwCorner.y + swCorner.y) @@ -373,12 +373,12 @@ void AddLiquidFacesByBlockModel(RendererSectionData& data, const BlockId& blockI } } -BlockFaces *GetInternalBlockModel(const BlockId& id, std::vector<std::pair<BlockId, BlockFaces*>> &idModels) { +BlockFaces *GetInternalBlockModel(BlockId id, std::vector<std::pair<BlockId, BlockFaces*>> &idModels) { for (const auto& it : idModels) { if (it.first == id) return it.second; } - idModels.push_back(std::make_pair(id, &AssetManager::GetBlockModelByBlockId(id))); + idModels.emplace_back(std::pair{ id, &AssetManager::GetBlockModelByBlockId(id) }); return idModels.back().second; } @@ -436,7 +436,6 @@ RendererSectionData ParseSection(const SectionsData §ions, bool smoothLighti std::vector<std::pair<BlockId, BlockFaces*>> idModels; std::array<BlockId, 4096> blockIdData = SetBlockIdData(sections); std::array<bool[FaceDirection::none], 4096> blockVisibility = GetBlockVisibilityData(sections, blockIdData, idModels); - std::string textureName; data.hash = sections.data[1][1][1].GetHash(); data.sectionPos = sections.data[1][1][1].GetPosition(); diff --git a/src/RendererWorld.cpp b/src/RendererWorld.cpp index 26c1f69..648b7f5 100644 --- a/src/RendererWorld.cpp +++ b/src/RendererWorld.cpp @@ -1,4 +1,4 @@ -#include "RendererWorld.hpp" + #include "RendererWorld.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> @@ -119,7 +119,7 @@ void RendererWorld::ParseQeueueRemoveUnnecessary() { void RendererWorld::UpdateAllSections(VectorF playerPos) { OPTICK_EVENT(); - Vector playerChunk(std::floor(GetGameState()->GetPlayer()->pos.x / 16), 0, std::floor(GetGameState()->GetPlayer()->pos.z / 16)); + Vector playerChunk(std::floor(playerPos.x / 16), 0, std::floor(playerPos.z / 16)); std::vector<Vector> suitableChunks; auto chunks = GetGameState()->GetWorld().GetSectionsList(); @@ -189,7 +189,7 @@ RendererWorld::RendererWorld(std::shared_ptr<Gal::Framebuffer> target, bool deff } it->second.UpdateData(parsing[id].renderer); } else - sections.emplace(std::make_pair(parsing[id].renderer.sectionPos, RendererSection(parsing[id].renderer, solidSectionsPipeline, solidSectionsBufferBinding, liquidSectionsPipeline, liquidSectionsBufferBinding))); + sections.try_emplace(parsing[id].renderer.sectionPos, RendererSection(parsing[id].renderer, solidSectionsPipeline, solidSectionsBufferBinding, liquidSectionsPipeline, liquidSectionsBufferBinding)); parsing[id] = RendererWorld::SectionParsing(); }); @@ -199,7 +199,7 @@ RendererWorld::RendererWorld(std::shared_ptr<Gal::Framebuffer> target, bool deff auto data = eventData.get<unsigned int>(); for (unsigned int entityId : GetGameState()->GetWorld().GetEntitiesList()) { if (entityId == data) { - entities.push_back(RendererEntity(entityId)); + entities.emplace_back(entityId); } } }); @@ -213,7 +213,7 @@ RendererWorld::RendererWorld(std::shared_ptr<Gal::Framebuffer> target, bool deff Vector playerChunk(std::floor(GetGameState()->GetPlayer()->pos.x / 16), 0, std::floor(GetGameState()->GetPlayer()->pos.z / 16)); double distanceToChunk = (Vector(vec.x, 0, vec.z) - playerChunk).GetLength(); - if (MaxRenderingDistance != 1000 && distanceToChunk > MaxRenderingDistance) { + if (distanceToChunk > MaxRenderingDistance) { return; } @@ -231,7 +231,7 @@ RendererWorld::RendererWorld(std::shared_ptr<Gal::Framebuffer> target, bool deff Vector playerChunk(std::floor(GetGameState()->GetPlayer()->pos.x / 16), 0, std::floor(GetGameState()->GetPlayer()->pos.z / 16)); double distanceToChunk = (Vector(vec.x, 0, vec.z) - playerChunk).GetLength(); - if (MaxRenderingDistance != 1000 && distanceToChunk > MaxRenderingDistance) { + if (distanceToChunk > MaxRenderingDistance) { return; } @@ -259,7 +259,7 @@ RendererWorld::RendererWorld(std::shared_ptr<Gal::Framebuffer> target, bool deff }); for (int i = 0; i < numOfWorkers; i++) - workers.push_back(std::thread(&RendererWorld::WorkerFunction, this, i)); + workers.emplace_back(&RendererWorld::WorkerFunction, this, i); PUSH_EVENT("UpdateSectionsRender", 0); } @@ -349,10 +349,11 @@ void RendererWorld::Render(float screenRatio) { size_t culledSections = sections.size(); unsigned int renderedFaces = 0; for (auto& section : sections) { + const auto& sectionPos = section.second.GetPosition(); glm::vec3 point{ - section.second.GetPosition().x * 16 + 8, - section.second.GetPosition().y * 16 + 8, - section.second.GetPosition().z * 16 + 8 + sectionPos.x * 16 + 8, + sectionPos.y * 16 + 8, + sectionPos.z * 16 + 8 }; bool isVisible = frustum.TestSphere(point, 16.0f); diff --git a/src/Rml.cpp b/src/Rml.cpp index f6fff44..7f114cd 100644 --- a/src/Rml.cpp +++ b/src/Rml.cpp @@ -161,7 +161,8 @@ bool RmlRenderInterface::GenerateTexture(Rml::TextureHandle& texture_handle, con } void RmlRenderInterface::ReleaseTexture(Rml::TextureHandle texture) { - textures.erase(textures.find(texture)); + if (auto it = textures.find(texture); it != textures.end()) + textures.erase(it); } void RmlRenderInterface::Update(unsigned int windowWidth, unsigned int windowHeight) { @@ -183,7 +184,7 @@ Rml::FileHandle RmlFileInterface::Open(const Rml::String& path) { handle.filePos = 0; if (handle.assetPtr != nullptr) - handles.insert(std::make_pair(fileId, handle)); + handles.try_emplace(fileId, handle); else fileId = 0; return fileId; diff --git a/src/Rml.hpp b/src/Rml.hpp index 2e3a672..6936ed9 100644 --- a/src/Rml.hpp +++ b/src/Rml.hpp @@ -35,7 +35,7 @@ class RmlRenderInterface : public Rml::RenderInterface { std::shared_ptr<Gal::Buffer> vertexBuffer, indexBuffer; std::map<size_t, std::shared_ptr<Gal::Texture>> textures; - unsigned int vpWidth, vpHeight; + unsigned int vpWidth=0, vpHeight=0; public: RmlRenderInterface(); diff --git a/src/Settings.cpp b/src/Settings.cpp index a585752..5287556 100644 --- a/src/Settings.cpp +++ b/src/Settings.cpp @@ -23,7 +23,7 @@ void Settings::Load() { stream >> j; for (json::iterator it = j.begin(); it != j.end(); ++it) { - values.insert(std::make_pair(it.key(), it->get<std::string>())); + values.try_emplace(it.key(), it->get<std::string>()); } LOG(INFO) << "Loaded " << values.size() << " settings"; } @@ -47,7 +47,7 @@ void Settings::Save() { std::string Settings::Read(const std::string &key, const std::string &defaultValue) { auto it = values.find(key); if (it == values.end()) { - values.insert(std::make_pair(key, defaultValue)); + values.try_emplace(key, defaultValue); it = values.find(key); } return it->second; diff --git a/src/TextureAtlas.cpp b/src/TextureAtlas.cpp index 9ad018e..e2cd355 100644 --- a/src/TextureAtlas.cpp +++ b/src/TextureAtlas.cpp @@ -96,10 +96,11 @@ TextureAtlas::TextureAtlas(std::vector<TextureData> &textures) { //Uploading texture data for (int i = 0; i < textureCoords.size(); i++) { size_t bytesPerLine = textureCoords[i].pixelW * 4; + auto& textureData = textures[i].data; for (int y = 0; y < textureCoords[i].pixelH / 2; y++) { int invY = textureCoords[i].pixelH - y - 1; - unsigned char *src = textures[i].data.data() + y * bytesPerLine; - unsigned char *dst = textures[i].data.data() + invY * bytesPerLine; + unsigned char *src = textureData.data() + y * bytesPerLine; + unsigned char *dst = textureData.data() + invY * bytesPerLine; for (int j = 0; j < bytesPerLine; j++) { std::swap(*(src + j), *(dst + j)); } @@ -111,7 +112,7 @@ TextureAtlas::TextureAtlas(std::vector<TextureData> &textures) { textureCoords[i].pixelW, textureCoords[i].pixelH, 1, - { reinterpret_cast<std::byte*>(textures[i].data.data()), reinterpret_cast<std::byte*>(textures[i].data.data()) + textures[i].data.size() } + { reinterpret_cast<std::byte*>(textureData.data()), reinterpret_cast<std::byte*>(textureData.data()) + textureData.size() } ); } diff --git a/src/Utility.cpp b/src/Utility.cpp index 28d920d..3bc9df9 100644 --- a/src/Utility.cpp +++ b/src/Utility.cpp @@ -10,10 +10,6 @@ LoopExecutionTimeController::LoopExecutionTimeController(duration delayLength) previousUpdate = clock::now(); } -LoopExecutionTimeController::~LoopExecutionTimeController() { - -} - void LoopExecutionTimeController::SetDelayLength(duration length) { delayLength = length; } diff --git a/src/Utility.hpp b/src/Utility.hpp index f16f49a..5bce76e 100644 --- a/src/Utility.hpp +++ b/src/Utility.hpp @@ -56,8 +56,6 @@ class LoopExecutionTimeController { public: LoopExecutionTimeController(duration delayLength); - ~LoopExecutionTimeController(); - void SetDelayLength(duration length); unsigned long long GetIterations(); diff --git a/src/Vector.hpp b/src/Vector.hpp index a067ea0..82f5132 100644 --- a/src/Vector.hpp +++ b/src/Vector.hpp @@ -2,6 +2,7 @@ #include <ostream> #include <cmath> +#include <cfloat> #include <glm/vec3.hpp> @@ -137,5 +138,21 @@ struct Vector3 { } }; +template<> +inline bool Vector3<float>::operator==(const Vector3<float>& rhs) const { + return + std::fabs(rhs.x - x) < FLT_EPSILON && + std::fabs(rhs.y - y) < FLT_EPSILON && + std::fabs(rhs.z - z) < FLT_EPSILON; +} + +template<> +inline bool Vector3<double>::operator==(const Vector3<double>& rhs) const { + return + std::fabs(rhs.x - x) < DBL_EPSILON && + std::fabs(rhs.y - y) < DBL_EPSILON && + std::fabs(rhs.z - z) < DBL_EPSILON; +} + using VectorF = Vector3<double>; -using Vector = Vector3<signed long long>;
\ No newline at end of file +using Vector = Vector3<signed long long>; diff --git a/src/Window.cpp b/src/Window.cpp index 37d9c74..c0d3fe8 100644 --- a/src/Window.cpp +++ b/src/Window.cpp @@ -5,11 +5,11 @@ void Window::MakeClick(short ClickedSlot, bool Lmb, bool dropMode) { PacketClickWindow packet(WindowId, ClickedSlot, Lmb ? 0 : 1, actions++, 0, slots[ClickedSlot]); this->pendingTransactions.push(packet); std::swap(slots[ClickedSlot], handSlot); - transactions.push_back(std::make_pair(actions, std::make_pair(ClickedSlot, -1))); + transactions.emplace_back(std::make_pair(actions, std::make_pair(ClickedSlot, -1))); } else { PacketClickWindow packet(WindowId, ClickedSlot, Lmb ? 0 : 1, actions++, 0, SlotDataType()); this->pendingTransactions.push(packet); - transactions.push_back(std::make_pair(actions, std::make_pair(ClickedSlot, -1))); + transactions.emplace_back(std::make_pair(actions, std::make_pair(ClickedSlot, -1))); } } diff --git a/src/World.cpp b/src/World.cpp index 6fcbdcd..f3c262c 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -1,5 +1,6 @@ #include "World.hpp" +#include <array> #include <bitset> #include <glm/glm.hpp> #include <optick.h> @@ -11,7 +12,7 @@ std::map<int, Dimension> registeredDimensions; -void RegisterNewDimension(int dimensionId, Dimension newDimension) { +void RegisterNewDimension(int dimensionId, const Dimension& newDimension) { registeredDimensions[dimensionId] = newDimension; } @@ -28,7 +29,7 @@ void World::ParseChunkData(std::shared_ptr<PacketChunkData> packet) { auto section = std::make_shared<Section>(ParseSection(&chunkData, chunkPosition)); if (packet->GroundUpContinuous) { - if (!sections.insert(std::make_pair(chunkPosition, section)).second) { + if (!sections.try_emplace(chunkPosition, section).second) { LOG(ERROR) << "New chunk not created " << chunkPosition << " potential memory leak"; } @@ -37,7 +38,7 @@ void World::ParseChunkData(std::shared_ptr<PacketChunkData> packet) { auto it = sections.find(chunkPosition); if (it == sections.end()) { LOG(WARNING) << "Chunk updating empty chunk"; - sections.insert(std::make_pair(chunkPosition, section)); + sections.try_emplace(chunkPosition, section); } else std::swap(sections.at(chunkPosition), section); @@ -48,7 +49,7 @@ void World::ParseChunkData(std::shared_ptr<PacketChunkData> packet) { } } -Section World::ParseSection(StreamInput *data, Vector position) { +Section World::ParseSection(StreamInput *data, const Vector& position) { unsigned char bitsPerBlock = data->ReadUByte(); int paletteLength = data->ReadVarInt(); @@ -80,7 +81,7 @@ bool World::isPlayerCollides(double X, double Y, double Z) const { sections.find(PlayerChunk - Vector(0, 1, 0)) == sections.end()) return false; - std::vector<Vector> closestSectionsCoordinates = { + std::array<Vector, 7> closestSectionsCoordinates = { Vector(PlayerChunk.x, PlayerChunk.y, PlayerChunk.z), Vector(PlayerChunk.x + 1, PlayerChunk.y, PlayerChunk.z), Vector(PlayerChunk.x - 1, PlayerChunk.y, PlayerChunk.z), @@ -90,6 +91,7 @@ bool World::isPlayerCollides(double X, double Y, double Z) const { Vector(PlayerChunk.x, PlayerChunk.y, PlayerChunk.z - 1), }; std::vector<Vector> closestSections; + closestSections.reserve(7); for (auto &coord : closestSectionsCoordinates) { if (sections.find(coord) != sections.end()) closestSections.push_back(coord); @@ -128,14 +130,9 @@ bool World::isPlayerCollides(double X, double Y, double Z) const { return false; } -std::vector<Vector> World::GetSectionsList() const { - auto vec = sectionsList; - return vec; -} - static Section fallbackSection; -const Section &World::GetSection(Vector sectionPos) const { +const Section &World::GetSection(const Vector& sectionPos) const { auto result = sections.find(sectionPos); if (result == sections.end()) { //LOG(ERROR) << "Accessed not loaded section " << sectionPos; @@ -147,7 +144,7 @@ const Section &World::GetSection(Vector sectionPos) const { } // TODO: skip liquid blocks -RaycastResult World::Raycast(glm::vec3 position, glm::vec3 direction) const { +RaycastResult World::Raycast(const glm::vec3& position, const glm::vec3& direction) const { OPTICK_EVENT(); const float maxLen = 5.0; const float step = 0.01; @@ -292,7 +289,7 @@ std::vector<unsigned int> World::GetEntitiesList() const { return ret; } -void World::AddEntity(Entity entity) { +void World::AddEntity(const Entity& entity) { for (auto& it : entities) { if (it.entityId == entity.entityId) { LOG(ERROR) << "Adding already existing entity: " << entity.entityId; @@ -364,7 +361,7 @@ void World::UpdateSectionsList() { } } -BlockId World::GetBlockId(Vector pos) const { +BlockId World::GetBlockId(const Vector& pos) const { Vector sectionPos(std::floor(pos.x / 16.0), std::floor(pos.y / 16.0), std::floor(pos.z / 16.0)); @@ -373,7 +370,7 @@ BlockId World::GetBlockId(Vector pos) const { return !section ? BlockId{0, 0} : section->GetBlockId(pos - (sectionPos * 16)); } -void World::SetBlockId(Vector pos, BlockId block) { +void World::SetBlockId(const Vector& pos, BlockId block) { Vector sectionPos(std::floor(pos.x / 16.0), std::floor(pos.y / 16.0), std::floor(pos.z / 16.0)); @@ -401,15 +398,15 @@ void World::SetBlockId(Vector pos, BlockId block) { PUSH_EVENT("ChunkChangedForce", sectionPos + Vector(0, 0, 1)); } -void World::SetBlockLight(Vector pos, unsigned char light) { +void World::SetBlockLight(const Vector& pos, unsigned char light) { } -void World::SetBlockSkyLight(Vector pos, unsigned char light) { +void World::SetBlockSkyLight(const Vector& pos, unsigned char light) { } -const Section *World::GetSectionPtr(Vector position) const { +const Section *World::GetSectionPtr(const Vector& position) const { auto it = sections.find(position); if (it == sections.end()) @@ -427,7 +424,7 @@ Entity* World::GetEntityPtr(unsigned int EntityId) { return nullptr; } -unsigned char World::GetBlockLight(Vector pos) const { +unsigned char World::GetBlockLight(const Vector& pos) const { Vector sectionPos(std::floor(pos.x / 16.0), std::floor(pos.y / 16.0), std::floor(pos.z / 16.0)); @@ -448,7 +445,7 @@ unsigned char World::GetBlockLight(Vector pos) const { return GetBlockLight(blockPos, section, xp, xn, yp, yn, zp, zn); } -unsigned char World::GetBlockLight(const Vector &blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const { +unsigned char World::GetBlockLight(const Vector& blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const { static const Vector directions[] = { Vector(0,0,0), Vector(1,0,0), @@ -486,7 +483,7 @@ unsigned char World::GetBlockLight(const Vector &blockPos, const Section *sectio return value; } -unsigned char World::GetBlockSkyLight(Vector pos) const { +unsigned char World::GetBlockSkyLight(const Vector& pos) const { Vector sectionPos( std::floor(pos.x / 16.0), std::floor(pos.y / 16.0), std::floor(pos.z / 16.0)); @@ -507,7 +504,7 @@ unsigned char World::GetBlockSkyLight(Vector pos) const { return GetBlockSkyLight(blockPos, section, xp, xn, yp, yn, zp, zn); } -unsigned char World::GetBlockSkyLight(const Vector &blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const { +unsigned char World::GetBlockSkyLight(const Vector& blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const { static const Vector directions[] = { Vector(0,0,0), Vector(1,0,0), diff --git a/src/World.hpp b/src/World.hpp index 3e53efc..f7fcda2 100644 --- a/src/World.hpp +++ b/src/World.hpp @@ -30,14 +30,14 @@ struct Dimension { bool skylight; }; -void RegisterNewDimension(int dimensionId, Dimension newDimension); +void RegisterNewDimension(int dimensionId, const Dimension& newDimension); class World { int dimension = 0; std::map<Vector, std::shared_ptr<Section>> sections; - Section ParseSection(StreamInput *data, Vector position); + Section ParseSection(StreamInput *data, const Vector& position); std::list<Entity> entities; @@ -61,11 +61,11 @@ public: bool isPlayerCollides(double X, double Y, double Z) const; - std::vector<Vector> GetSectionsList() const; + const std::vector<Vector>& GetSectionsList() const { return sectionsList; } - const Section &GetSection(Vector sectionPos) const; + const Section &GetSection(const Vector& sectionPos) const; - RaycastResult Raycast(glm::vec3 position, glm::vec3 direction) const; + RaycastResult Raycast(const glm::vec3& position, const glm::vec3& direction) const; void UpdatePhysics(float delta); @@ -77,25 +77,25 @@ public: std::vector<unsigned int> GetEntitiesList() const; - void AddEntity(Entity entity); + void AddEntity(const Entity& entity); void DeleteEntity(unsigned int EntityId); - BlockId GetBlockId(Vector pos) const; + BlockId GetBlockId(const Vector& pos) const; - void SetBlockId(Vector pos, BlockId block); + void SetBlockId(const Vector& pos, BlockId block); - void SetBlockLight(Vector pos, unsigned char light); + void SetBlockLight(const Vector& pos, unsigned char light); - void SetBlockSkyLight(Vector pos, unsigned char light); + void SetBlockSkyLight(const Vector& pos, unsigned char light); - const Section *GetSectionPtr(Vector position) const; + const Section *GetSectionPtr(const Vector& position) const; - unsigned char GetBlockLight(Vector pos) const; + unsigned char GetBlockLight(const Vector& pos) const; - unsigned char GetBlockLight(const Vector &blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const; + unsigned char GetBlockLight(const Vector& blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const; - unsigned char GetBlockSkyLight(Vector pos) const; + unsigned char GetBlockSkyLight(const Vector& pos) const; - unsigned char GetBlockSkyLight(const Vector &blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const; + unsigned char GetBlockSkyLight(const Vector& blockPos, const Section *section, const Section *xp, const Section *xn, const Section *yp, const Section *yn, const Section *zp, const Section *zn) const; };
\ No newline at end of file |