code
string
repo_name
string
path
string
language
string
license
string
size
int64
/* This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "util/basic_macros.h" #include <string> #include <atomic> #include <thread> #include <mutex> #ifdef _AIX #include <sys/thread.h> // for tid_t #endif /* * On platforms using pthreads, these five priority classes correlate to * even divisions between the minimum and maximum reported thread priority. */ #if !defined(_WIN32) #define THREAD_PRIORITY_LOWEST 0 #define THREAD_PRIORITY_BELOW_NORMAL 1 #define THREAD_PRIORITY_NORMAL 2 #define THREAD_PRIORITY_ABOVE_NORMAL 3 #define THREAD_PRIORITY_HIGHEST 4 #endif class Thread { public: Thread(const std::string &name=""); virtual ~Thread(); DISABLE_CLASS_COPY(Thread) /* * Begins execution of a new thread at the pure virtual method Thread::run(). * Execution of the thread is guaranteed to have started after this function * returns. */ bool start(); /* * Requests that the thread exit gracefully. * Returns immediately; thread execution is guaranteed to be complete after * a subsequent call to Thread::wait. */ bool stop(); /* * Immediately terminates the thread. * This should be used with extreme caution, as the thread will not have * any opportunity to release resources it may be holding (such as memory * or locks). */ bool kill(); /* * Waits for thread to finish. * Note: This does not stop a thread, you have to do this on your own. * Returns false immediately if the thread is not started or has been waited * on before. */ bool wait(); /* * Returns true if the calling thread is this Thread object. */ bool isCurrentThread() { return std::this_thread::get_id() == getThreadId(); } bool isRunning() { return m_running; } bool stopRequested() { return m_request_stop; } std::thread::id getThreadId() { return m_thread_obj->get_id(); } /* * Gets the thread return value. * Returns true if the thread has exited and the return value was available, * or false if the thread has yet to finish. */ bool getReturnValue(void **ret); /* * Binds (if possible, otherwise sets the affinity of) the thread to the * specific processor specified by proc_number. */ bool bindToProcessor(unsigned int proc_number); /* * Sets the thread priority to the specified priority. * * prio can be one of: THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, * THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST. * On Windows, any of the other priorites as defined by SetThreadPriority * are supported as well. * * Note that it may be necessary to first set the threading policy or * scheduling algorithm to one that supports thread priorities if not * supported by default, otherwise this call will have no effect. */ bool setPriority(int prio); /* * Sets the currently executing thread's name to where supported; useful * for debugging. */ static void setName(const std::string &name); /* * Returns the number of processors/cores configured and active on this machine. */ static unsigned int getNumberOfProcessors(); protected: std::string m_name; virtual void *run() = 0; private: std::thread::native_handle_type getThreadHandle() { return m_thread_obj->native_handle(); } static void threadProc(Thread *thr); void *m_retval = nullptr; bool m_joinable = false; std::atomic<bool> m_request_stop; std::atomic<bool> m_running; std::mutex m_mutex; std::mutex m_start_finished_mutex; std::thread *m_thread_obj = nullptr; #ifdef _AIX // For AIX, there does not exist any mapping from pthread_t to tid_t // available to us, so we maintain one ourselves. This is set on thread start. tid_t m_kernel_thread_id; #endif };
pgimeno/minetest
src/threading/thread.h
C++
mit
4,918
/* Minetest Copyright (C) 2016 sfan5 <sfan5@live.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "tileanimation.h" #include "util/serialize.h" void TileAnimationParams::serialize(std::ostream &os, u8 tiledef_version) const { writeU8(os, type); if (type == TAT_VERTICAL_FRAMES) { writeU16(os, vertical_frames.aspect_w); writeU16(os, vertical_frames.aspect_h); writeF32(os, vertical_frames.length); } else if (type == TAT_SHEET_2D) { writeU8(os, sheet_2d.frames_w); writeU8(os, sheet_2d.frames_h); writeF32(os, sheet_2d.frame_length); } } void TileAnimationParams::deSerialize(std::istream &is, u8 tiledef_version) { type = (TileAnimationType) readU8(is); if (type == TAT_VERTICAL_FRAMES) { vertical_frames.aspect_w = readU16(is); vertical_frames.aspect_h = readU16(is); vertical_frames.length = readF32(is); } else if (type == TAT_SHEET_2D) { sheet_2d.frames_w = readU8(is); sheet_2d.frames_h = readU8(is); sheet_2d.frame_length = readF32(is); } } void TileAnimationParams::determineParams(v2u32 texture_size, int *frame_count, int *frame_length_ms, v2u32 *frame_size) const { if (type == TAT_VERTICAL_FRAMES) { int frame_height = (float)texture_size.X / (float)vertical_frames.aspect_w * (float)vertical_frames.aspect_h; int _frame_count = texture_size.Y / frame_height; if (frame_count) *frame_count = _frame_count; if (frame_length_ms) *frame_length_ms = 1000.0 * vertical_frames.length / _frame_count; if (frame_size) *frame_size = v2u32(texture_size.X, frame_height); } else if (type == TAT_SHEET_2D) { if (frame_count) *frame_count = sheet_2d.frames_w * sheet_2d.frames_h; if (frame_length_ms) *frame_length_ms = 1000 * sheet_2d.frame_length; if (frame_size) *frame_size = v2u32(texture_size.X / sheet_2d.frames_w, texture_size.Y / sheet_2d.frames_h); } // caller should check for TAT_NONE } void TileAnimationParams::getTextureModifer(std::ostream &os, v2u32 texture_size, int frame) const { if (type == TAT_NONE) return; if (type == TAT_VERTICAL_FRAMES) { int frame_count; determineParams(texture_size, &frame_count, NULL, NULL); os << "^[verticalframe:" << frame_count << ":" << frame; } else if (type == TAT_SHEET_2D) { int q, r; q = frame / sheet_2d.frames_w; r = frame % sheet_2d.frames_w; os << "^[sheet:" << sheet_2d.frames_w << "x" << sheet_2d.frames_h << ":" << r << "," << q; } } v2f TileAnimationParams::getTextureCoords(v2u32 texture_size, int frame) const { v2u32 ret(0, 0); if (type == TAT_VERTICAL_FRAMES) { int frame_height = (float)texture_size.X / (float)vertical_frames.aspect_w * (float)vertical_frames.aspect_h; ret = v2u32(0, frame_height * frame); } else if (type == TAT_SHEET_2D) { v2u32 frame_size; determineParams(texture_size, NULL, NULL, &frame_size); int q, r; q = frame / sheet_2d.frames_w; r = frame % sheet_2d.frames_w; ret = v2u32(r * frame_size.X, q * frame_size.Y); } return v2f(ret.X / (float) texture_size.X, ret.Y / (float) texture_size.Y); }
pgimeno/minetest
src/tileanimation.cpp
C++
mit
3,697
/* Minetest Copyright (C) 2016 sfan5 <sfan5@live.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <iostream> #include "irrlichttypes_bloated.h" enum TileAnimationType { TAT_NONE = 0, TAT_VERTICAL_FRAMES = 1, TAT_SHEET_2D = 2, }; struct TileAnimationParams { enum TileAnimationType type; union { // struct { // } none; struct { int aspect_w; // width for aspect ratio int aspect_h; // height for aspect ratio float length; // seconds } vertical_frames; struct { int frames_w; // number of frames left-to-right int frames_h; // number of frames top-to-bottom float frame_length; // seconds } sheet_2d; }; void serialize(std::ostream &os, u8 tiledef_version) const; void deSerialize(std::istream &is, u8 tiledef_version); void determineParams(v2u32 texture_size, int *frame_count, int *frame_length_ms, v2u32 *frame_size) const; void getTextureModifer(std::ostream &os, v2u32 texture_size, int frame) const; v2f getTextureCoords(v2u32 texture_size, int frame) const; };
pgimeno/minetest
src/tileanimation.h
C++
mit
1,717
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "tool.h" #include "itemgroup.h" #include "log.h" #include "inventory.h" #include "exceptions.h" #include "util/serialize.h" #include "util/numeric.h" void ToolGroupCap::toJson(Json::Value &object) const { object["maxlevel"] = maxlevel; object["uses"] = uses; Json::Value times_object; for (auto time : times) times_object[time.first] = time.second; object["times"] = times_object; } void ToolGroupCap::fromJson(const Json::Value &json) { if (json.isObject()) { if (json["maxlevel"].isInt()) maxlevel = json["maxlevel"].asInt(); if (json["uses"].isInt()) uses = json["uses"].asInt(); const Json::Value &times_object = json["times"]; if (times_object.isArray()) { Json::ArrayIndex size = times_object.size(); for (Json::ArrayIndex i = 0; i < size; ++i) if (times_object[i].isDouble()) times[i] = times_object[i].asFloat(); } } } void ToolCapabilities::serialize(std::ostream &os, u16 protocol_version) const { writeU8(os, 4); // protocol_version >= 37 writeF32(os, full_punch_interval); writeS16(os, max_drop_level); writeU32(os, groupcaps.size()); for (const auto &groupcap : groupcaps) { const std::string *name = &groupcap.first; const ToolGroupCap *cap = &groupcap.second; os << serializeString(*name); writeS16(os, cap->uses); writeS16(os, cap->maxlevel); writeU32(os, cap->times.size()); for (const auto &time : cap->times) { writeS16(os, time.first); writeF32(os, time.second); } } writeU32(os, damageGroups.size()); for (const auto &damageGroup : damageGroups) { os << serializeString(damageGroup.first); writeS16(os, damageGroup.second); } } void ToolCapabilities::deSerialize(std::istream &is) { int version = readU8(is); if (version < 4) throw SerializationError("unsupported ToolCapabilities version"); full_punch_interval = readF32(is); max_drop_level = readS16(is); groupcaps.clear(); u32 groupcaps_size = readU32(is); for (u32 i = 0; i < groupcaps_size; i++) { std::string name = deSerializeString(is); ToolGroupCap cap; cap.uses = readS16(is); cap.maxlevel = readS16(is); u32 times_size = readU32(is); for(u32 i = 0; i < times_size; i++) { int level = readS16(is); float time = readF32(is); cap.times[level] = time; } groupcaps[name] = cap; } u32 damage_groups_size = readU32(is); for (u32 i = 0; i < damage_groups_size; i++) { std::string name = deSerializeString(is); s16 rating = readS16(is); damageGroups[name] = rating; } } void ToolCapabilities::serializeJson(std::ostream &os) const { Json::Value root; root["full_punch_interval"] = full_punch_interval; root["max_drop_level"] = max_drop_level; Json::Value groupcaps_object; for (auto groupcap : groupcaps) { groupcap.second.toJson(groupcaps_object[groupcap.first]); } root["groupcaps"] = groupcaps_object; Json::Value damage_groups_object; DamageGroup::const_iterator dgiter; for (dgiter = damageGroups.begin(); dgiter != damageGroups.end(); ++dgiter) { damage_groups_object[dgiter->first] = dgiter->second; } root["damage_groups"] = damage_groups_object; os << root; } void ToolCapabilities::deserializeJson(std::istream &is) { Json::Value root; is >> root; if (root.isObject()) { if (root["full_punch_interval"].isDouble()) full_punch_interval = root["full_punch_interval"].asFloat(); if (root["max_drop_level"].isInt()) max_drop_level = root["max_drop_level"].asInt(); Json::Value &groupcaps_object = root["groupcaps"]; if (groupcaps_object.isObject()) { Json::ValueIterator gciter; for (gciter = groupcaps_object.begin(); gciter != groupcaps_object.end(); ++gciter) { ToolGroupCap groupcap; groupcap.fromJson(*gciter); groupcaps[gciter.key().asString()] = groupcap; } } Json::Value &damage_groups_object = root["damage_groups"]; if (damage_groups_object.isObject()) { Json::ValueIterator dgiter; for (dgiter = damage_groups_object.begin(); dgiter != damage_groups_object.end(); ++dgiter) { Json::Value &value = *dgiter; if (value.isInt()) damageGroups[dgiter.key().asString()] = value.asInt(); } } } } DigParams getDigParams(const ItemGroupList &groups, const ToolCapabilities *tp) { // Group dig_immediate has fixed time and no wear switch (itemgroup_get(groups, "dig_immediate")) { case 2: return DigParams(true, 0.5, 0, "dig_immediate"); case 3: return DigParams(true, 0, 0, "dig_immediate"); default: break; } // Values to be returned (with a bit of conversion) bool result_diggable = false; float result_time = 0.0; float result_wear = 0.0; std::string result_main_group; int level = itemgroup_get(groups, "level"); for (const auto &groupcap : tp->groupcaps) { const ToolGroupCap &cap = groupcap.second; int leveldiff = cap.maxlevel - level; if (leveldiff < 0) continue; const std::string &groupname = groupcap.first; float time = 0; int rating = itemgroup_get(groups, groupname); bool time_exists = cap.getTime(rating, &time); if (!time_exists) continue; if (leveldiff > 1) time /= leveldiff; if (!result_diggable || time < result_time) { result_time = time; result_diggable = true; if (cap.uses != 0) result_wear = 1.0 / cap.uses / pow(3.0, leveldiff); else result_wear = 0; result_main_group = groupname; } } u16 wear_i = U16_MAX * result_wear; return DigParams(result_diggable, result_time, wear_i, result_main_group); } HitParams getHitParams(const ItemGroupList &armor_groups, const ToolCapabilities *tp, float time_from_last_punch) { s16 damage = 0; float full_punch_interval = tp->full_punch_interval; for (const auto &damageGroup : tp->damageGroups) { s16 armor = itemgroup_get(armor_groups, damageGroup.first); damage += damageGroup.second * rangelim(time_from_last_punch / full_punch_interval, 0.0, 1.0) * armor / 100.0; } return {damage, 0}; } HitParams getHitParams(const ItemGroupList &armor_groups, const ToolCapabilities *tp) { return getHitParams(armor_groups, tp, 1000000); } PunchDamageResult getPunchDamage( const ItemGroupList &armor_groups, const ToolCapabilities *toolcap, const ItemStack *punchitem, float time_from_last_punch ){ bool do_hit = true; { if (do_hit && punchitem) { if (itemgroup_get(armor_groups, "punch_operable") && (toolcap == NULL || punchitem->name.empty())) do_hit = false; } if (do_hit) { if(itemgroup_get(armor_groups, "immortal")) do_hit = false; } } PunchDamageResult result; if(do_hit) { HitParams hitparams = getHitParams(armor_groups, toolcap, time_from_last_punch); result.did_punch = true; result.wear = hitparams.wear; result.damage = hitparams.hp; } return result; }
pgimeno/minetest
src/tool.cpp
C++
mit
7,506
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include <string> #include <iostream> #include "itemgroup.h" #include <json/json.h> struct ToolGroupCap { std::unordered_map<int, float> times; int maxlevel = 1; int uses = 20; ToolGroupCap() = default; bool getTime(int rating, float *time) const { std::unordered_map<int, float>::const_iterator i = times.find(rating); if (i == times.end()) { *time = 0; return false; } *time = i->second; return true; } void toJson(Json::Value &object) const; void fromJson(const Json::Value &json); }; typedef std::unordered_map<std::string, struct ToolGroupCap> ToolGCMap; typedef std::unordered_map<std::string, s16> DamageGroup; struct ToolCapabilities { float full_punch_interval; int max_drop_level; ToolGCMap groupcaps; DamageGroup damageGroups; ToolCapabilities( float full_punch_interval_=1.4, int max_drop_level_=1, const ToolGCMap &groupcaps_ = ToolGCMap(), const DamageGroup &damageGroups_ = DamageGroup() ): full_punch_interval(full_punch_interval_), max_drop_level(max_drop_level_), groupcaps(groupcaps_), damageGroups(damageGroups_) {} void serialize(std::ostream &os, u16 version) const; void deSerialize(std::istream &is); void serializeJson(std::ostream &os) const; void deserializeJson(std::istream &is); }; struct DigParams { bool diggable; // Digging time in seconds float time; // Caused wear u16 wear; std::string main_group; DigParams(bool a_diggable = false, float a_time = 0.0f, u16 a_wear = 0, const std::string &a_main_group = ""): diggable(a_diggable), time(a_time), wear(a_wear), main_group(a_main_group) {} }; DigParams getDigParams(const ItemGroupList &groups, const ToolCapabilities *tp); struct HitParams { s16 hp; s16 wear; HitParams(s16 hp_=0, s16 wear_=0): hp(hp_), wear(wear_) {} }; HitParams getHitParams(const ItemGroupList &armor_groups, const ToolCapabilities *tp, float time_from_last_punch); HitParams getHitParams(const ItemGroupList &armor_groups, const ToolCapabilities *tp); struct PunchDamageResult { bool did_punch = false; int damage = 0; int wear = 0; PunchDamageResult() = default; }; struct ItemStack; PunchDamageResult getPunchDamage( const ItemGroupList &armor_groups, const ToolCapabilities *toolcap, const ItemStack *punchitem, float time_from_last_punch );
pgimeno/minetest
src/tool.h
C++
mit
3,153
/* Minetest Copyright (C) 2017 Nore, Nathanaël Courant <nore@mesecons.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "translation.h" #include "log.h" #include "util/string.h" static Translations main_translations; Translations *g_translations = &main_translations; Translations::~Translations() { clear(); } void Translations::clear() { m_translations.clear(); } const std::wstring &Translations::getTranslation( const std::wstring &textdomain, const std::wstring &s) { std::wstring key = textdomain + L"|" + s; try { return m_translations.at(key); } catch (const std::out_of_range &) { verbosestream << "Translations: can't find translation for string \"" << wide_to_utf8(s) << "\" in textdomain \"" << wide_to_utf8(textdomain) << "\"" << std::endl; // Silence that warning in the future m_translations[key] = s; return s; } } void Translations::loadTranslation(const std::string &data) { std::istringstream is(data); std::wstring textdomain; std::string line; while (is.good()) { std::getline(is, line); // Trim last character if file was using a \r\n line ending if (line.length () > 0 && line[line.length() - 1] == '\r') line.resize(line.length() - 1); if (str_starts_with(line, "# textdomain:")) { textdomain = utf8_to_wide(trim(str_split(line, ':')[1])); } if (line.empty() || line[0] == '#') continue; std::wstring wline = utf8_to_wide(line); if (wline.empty()) continue; // Read line // '=' marks the key-value pair, but may be escaped by an '@'. // '\n' may also be escaped by '@'. // All other escapes are preserved. size_t i = 0; std::wostringstream word1, word2; while (i < wline.length() && wline[i] != L'=') { if (wline[i] == L'@') { if (i + 1 < wline.length()) { if (wline[i + 1] == L'=') { word1.put(L'='); } else if (wline[i + 1] == L'n') { word1.put(L'\n'); } else { word1.put(L'@'); word1.put(wline[i + 1]); } i += 2; } else { // End of line, go to the next one. word1.put(L'\n'); if (!is.good()) { break; } i = 0; std::getline(is, line); wline = utf8_to_wide(line); } } else { word1.put(wline[i]); i++; } } if (i == wline.length()) { errorstream << "Malformed translation line \"" << line << "\"" << std::endl; continue; } i++; while (i < wline.length()) { if (wline[i] == L'@') { if (i + 1 < wline.length()) { if (wline[i + 1] == L'=') { word2.put(L'='); } else if (wline[i + 1] == L'n') { word2.put(L'\n'); } else { word2.put(L'@'); word2.put(wline[i + 1]); } i += 2; } else { // End of line, go to the next one. word2.put(L'\n'); if (!is.good()) { break; } i = 0; std::getline(is, line); wline = utf8_to_wide(line); } } else { word2.put(wline[i]); i++; } } std::wstring oword1 = word1.str(), oword2 = word2.str(); if (oword2.empty()) { oword2 = oword1; errorstream << "Ignoring empty translation for \"" << wide_to_utf8(oword1) << "\"" << std::endl; } m_translations[textdomain + L"|" + oword1] = oword2; } }
pgimeno/minetest
src/translation.cpp
C++
mit
3,919
/* Minetest Copyright (C) 2017 Nore, Nathanaël Courant <nore@mesecons.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <unordered_map> #include <string> class Translations; extern Translations *g_translations; class Translations { public: Translations() = default; ~Translations(); void loadTranslation(const std::string &data); void clear(); const std::wstring &getTranslation( const std::wstring &textdomain, const std::wstring &s); private: std::unordered_map<std::wstring, std::wstring> m_translations; };
pgimeno/minetest
src/translation.h
C++
mit
1,212
set (UNITTEST_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_address.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_authdatabase.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_activeobject.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_areastore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_ban.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_collision.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_compression.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_connection.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_filepath.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_inventory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_map_settings_manager.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_mapnode.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_modchannels.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_nodedef.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_noderesolver.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_noise.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_objdef.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_player.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_profiler.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_random.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_schematic.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_serialization.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_serveractiveobjectmgr.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_server_shutdown_state.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_settings.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_socket.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_servermodmanager.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_threading.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_utilities.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_voxelarea.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_voxelalgorithms.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_voxelmanipulator.cpp PARENT_SCOPE) set (UNITTEST_CLIENT_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/test_clientactiveobjectmgr.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_eventmanager.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_gameui.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_keycode.cpp PARENT_SCOPE) set (TEST_WORLDDIR ${CMAKE_CURRENT_SOURCE_DIR}/test_world) set (TEST_SUBGAME_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../games/minimal) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/test_config.h.in" "${PROJECT_BINARY_DIR}/test_config.h" )
pgimeno/minetest
src/unittest/CMakeLists.txt
Text
mit
2,132
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "client/sound.h" #include "nodedef.h" #include "itemdef.h" #include "gamedef.h" #include "modchannels.h" #include "content/mods.h" #include "util/numeric.h" #include "porting.h" content_t t_CONTENT_STONE; content_t t_CONTENT_GRASS; content_t t_CONTENT_TORCH; content_t t_CONTENT_WATER; content_t t_CONTENT_LAVA; content_t t_CONTENT_BRICK; //////////////////////////////////////////////////////////////////////////////// //// //// TestGameDef //// class TestGameDef : public IGameDef { public: TestGameDef(); ~TestGameDef(); IItemDefManager *getItemDefManager() { return m_itemdef; } const NodeDefManager *getNodeDefManager() { return m_nodedef; } ICraftDefManager *getCraftDefManager() { return m_craftdef; } ITextureSource *getTextureSource() { return m_texturesrc; } IShaderSource *getShaderSource() { return m_shadersrc; } ISoundManager *getSoundManager() { return m_soundmgr; } scene::ISceneManager *getSceneManager() { return m_scenemgr; } IRollbackManager *getRollbackManager() { return m_rollbackmgr; } EmergeManager *getEmergeManager() { return m_emergemgr; } scene::IAnimatedMesh *getMesh(const std::string &filename) { return NULL; } bool checkLocalPrivilege(const std::string &priv) { return false; } u16 allocateUnknownNodeId(const std::string &name) { return 0; } void defineSomeNodes(); virtual const std::vector<ModSpec> &getMods() const { static std::vector<ModSpec> testmodspec; return testmodspec; } virtual const ModSpec* getModSpec(const std::string &modname) const { return NULL; } virtual std::string getModStoragePath() const { return "."; } virtual bool registerModStorage(ModMetadata *meta) { return true; } virtual void unregisterModStorage(const std::string &name) {} bool joinModChannel(const std::string &channel); bool leaveModChannel(const std::string &channel); bool sendModChannelMessage(const std::string &channel, const std::string &message); ModChannel *getModChannel(const std::string &channel) { return m_modchannel_mgr->getModChannel(channel); } private: IItemDefManager *m_itemdef = nullptr; const NodeDefManager *m_nodedef = nullptr; ICraftDefManager *m_craftdef = nullptr; ITextureSource *m_texturesrc = nullptr; IShaderSource *m_shadersrc = nullptr; ISoundManager *m_soundmgr = nullptr; scene::ISceneManager *m_scenemgr = nullptr; IRollbackManager *m_rollbackmgr = nullptr; EmergeManager *m_emergemgr = nullptr; std::unique_ptr<ModChannelMgr> m_modchannel_mgr; }; TestGameDef::TestGameDef() : m_modchannel_mgr(new ModChannelMgr()) { m_itemdef = createItemDefManager(); m_nodedef = createNodeDefManager(); defineSomeNodes(); } TestGameDef::~TestGameDef() { delete m_itemdef; delete m_nodedef; } void TestGameDef::defineSomeNodes() { IWritableItemDefManager *idef = (IWritableItemDefManager *)m_itemdef; NodeDefManager *ndef = (NodeDefManager *)m_nodedef; ItemDefinition itemdef; ContentFeatures f; //// Stone itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:stone"; itemdef.description = "Stone"; itemdef.groups["cracky"] = 3; itemdef.inventory_image = "[inventorycube" "{default_stone.png" "{default_stone.png" "{default_stone.png"; f = ContentFeatures(); f.name = itemdef.name; for (TileDef &tiledef : f.tiledef) tiledef.name = "default_stone.png"; f.is_ground_content = true; idef->registerItem(itemdef); t_CONTENT_STONE = ndef->set(f.name, f); //// Grass itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:dirt_with_grass"; itemdef.description = "Dirt with grass"; itemdef.groups["crumbly"] = 3; itemdef.inventory_image = "[inventorycube" "{default_grass.png" "{default_dirt.png&default_grass_side.png" "{default_dirt.png&default_grass_side.png"; f = ContentFeatures(); f.name = itemdef.name; f.tiledef[0].name = "default_grass.png"; f.tiledef[1].name = "default_dirt.png"; for(int i = 2; i < 6; i++) f.tiledef[i].name = "default_dirt.png^default_grass_side.png"; f.is_ground_content = true; idef->registerItem(itemdef); t_CONTENT_GRASS = ndef->set(f.name, f); //// Torch (minimal definition for lighting tests) itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:torch"; f = ContentFeatures(); f.name = itemdef.name; f.param_type = CPT_LIGHT; f.light_propagates = true; f.sunlight_propagates = true; f.light_source = LIGHT_MAX-1; idef->registerItem(itemdef); t_CONTENT_TORCH = ndef->set(f.name, f); //// Water itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:water"; itemdef.description = "Water"; itemdef.inventory_image = "[inventorycube" "{default_water.png" "{default_water.png" "{default_water.png"; f = ContentFeatures(); f.name = itemdef.name; f.alpha = 128; f.liquid_type = LIQUID_SOURCE; f.liquid_viscosity = 4; f.is_ground_content = true; f.groups["liquids"] = 3; for (TileDef &tiledef : f.tiledef) tiledef.name = "default_water.png"; idef->registerItem(itemdef); t_CONTENT_WATER = ndef->set(f.name, f); //// Lava itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:lava"; itemdef.description = "Lava"; itemdef.inventory_image = "[inventorycube" "{default_lava.png" "{default_lava.png" "{default_lava.png"; f = ContentFeatures(); f.name = itemdef.name; f.alpha = 128; f.liquid_type = LIQUID_SOURCE; f.liquid_viscosity = 7; f.light_source = LIGHT_MAX-1; f.is_ground_content = true; f.groups["liquids"] = 3; for (TileDef &tiledef : f.tiledef) tiledef.name = "default_lava.png"; idef->registerItem(itemdef); t_CONTENT_LAVA = ndef->set(f.name, f); //// Brick itemdef = ItemDefinition(); itemdef.type = ITEM_NODE; itemdef.name = "default:brick"; itemdef.description = "Brick"; itemdef.groups["cracky"] = 3; itemdef.inventory_image = "[inventorycube" "{default_brick.png" "{default_brick.png" "{default_brick.png"; f = ContentFeatures(); f.name = itemdef.name; for (TileDef &tiledef : f.tiledef) tiledef.name = "default_brick.png"; f.is_ground_content = true; idef->registerItem(itemdef); t_CONTENT_BRICK = ndef->set(f.name, f); } bool TestGameDef::joinModChannel(const std::string &channel) { return m_modchannel_mgr->joinChannel(channel, PEER_ID_SERVER); } bool TestGameDef::leaveModChannel(const std::string &channel) { return m_modchannel_mgr->leaveChannel(channel, PEER_ID_SERVER); } bool TestGameDef::sendModChannelMessage(const std::string &channel, const std::string &message) { if (!m_modchannel_mgr->channelRegistered(channel)) return false; return true; } //// //// run_tests //// bool run_tests() { u64 t1 = porting::getTimeMs(); TestGameDef gamedef; g_logger.setLevelSilenced(LL_ERROR, true); u32 num_modules_failed = 0; u32 num_total_tests_failed = 0; u32 num_total_tests_run = 0; std::vector<TestBase *> &testmods = TestManager::getTestModules(); for (size_t i = 0; i != testmods.size(); i++) { if (!testmods[i]->testModule(&gamedef)) num_modules_failed++; num_total_tests_failed += testmods[i]->num_tests_failed; num_total_tests_run += testmods[i]->num_tests_run; } u64 tdiff = porting::getTimeMs() - t1; g_logger.setLevelSilenced(LL_ERROR, false); const char *overall_status = (num_modules_failed == 0) ? "PASSED" : "FAILED"; rawstream << "++++++++++++++++++++++++++++++++++++++++" << "++++++++++++++++++++++++++++++++++++++++" << std::endl << "Unit Test Results: " << overall_status << std::endl << " " << num_modules_failed << " / " << testmods.size() << " failed modules (" << num_total_tests_failed << " / " << num_total_tests_run << " failed individual tests)." << std::endl << " Testing took " << tdiff << "ms total." << std::endl << "++++++++++++++++++++++++++++++++++++++++" << "++++++++++++++++++++++++++++++++++++++++" << std::endl; return num_modules_failed; } //// //// TestBase //// bool TestBase::testModule(IGameDef *gamedef) { rawstream << "======== Testing module " << getName() << std::endl; u64 t1 = porting::getTimeMs(); runTests(gamedef); u64 tdiff = porting::getTimeMs() - t1; rawstream << "======== Module " << getName() << " " << (num_tests_failed ? "failed" : "passed") << " (" << num_tests_failed << " failures / " << num_tests_run << " tests) - " << tdiff << "ms" << std::endl; if (!m_test_dir.empty()) fs::RecursiveDelete(m_test_dir); return num_tests_failed == 0; } std::string TestBase::getTestTempDirectory() { if (!m_test_dir.empty()) return m_test_dir; char buf[32]; porting::mt_snprintf(buf, sizeof(buf), "%08X", myrand()); m_test_dir = fs::TempPath() + DIR_DELIM "mttest_" + buf; if (!fs::CreateDir(m_test_dir)) throw TestFailedException(); return m_test_dir; } std::string TestBase::getTestTempFile() { char buf[32]; porting::mt_snprintf(buf, sizeof(buf), "%08X", myrand()); return getTestTempDirectory() + DIR_DELIM + buf + ".tmp"; } /* NOTE: These tests became non-working then NodeContainer was removed. These should be redone, utilizing some kind of a virtual interface for Map (IMap would be fine). */ #if 0 struct TestMapBlock: public TestBase { class TC : public NodeContainer { public: MapNode node; bool position_valid; core::list<v3s16> validity_exceptions; TC() { position_valid = true; } virtual bool isValidPosition(v3s16 p) { //return position_valid ^ (p==position_valid_exception); bool exception = false; for(core::list<v3s16>::Iterator i=validity_exceptions.begin(); i != validity_exceptions.end(); i++) { if(p == *i) { exception = true; break; } } return exception ? !position_valid : position_valid; } virtual MapNode getNode(v3s16 p) { if(isValidPosition(p) == false) throw InvalidPositionException(); return node; } virtual void setNode(v3s16 p, MapNode & n) { if(isValidPosition(p) == false) throw InvalidPositionException(); }; virtual u16 nodeContainerId() const { return 666; } }; void Run() { TC parent; MapBlock b(&parent, v3s16(1,1,1)); v3s16 relpos(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE); UASSERT(b.getPosRelative() == relpos); UASSERT(b.getBox().MinEdge.X == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.X == MAP_BLOCKSIZE*2-1); UASSERT(b.getBox().MinEdge.Y == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.Y == MAP_BLOCKSIZE*2-1); UASSERT(b.getBox().MinEdge.Z == MAP_BLOCKSIZE); UASSERT(b.getBox().MaxEdge.Z == MAP_BLOCKSIZE*2-1); UASSERT(b.isValidPosition(v3s16(0,0,0)) == true); UASSERT(b.isValidPosition(v3s16(-1,0,0)) == false); UASSERT(b.isValidPosition(v3s16(-1,-142,-2341)) == false); UASSERT(b.isValidPosition(v3s16(-124,142,2341)) == false); UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true); UASSERT(b.isValidPosition(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE,MAP_BLOCKSIZE-1)) == false); /* TODO: this method should probably be removed if the block size isn't going to be set variable */ /*UASSERT(b.getSizeNodes() == v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE));*/ // Changed flag should be initially set UASSERT(b.getModified() == MOD_STATE_WRITE_NEEDED); b.resetModified(); UASSERT(b.getModified() == MOD_STATE_CLEAN); // All nodes should have been set to // .d=CONTENT_IGNORE and .getLight() = 0 for(u16 z=0; z<MAP_BLOCKSIZE; z++) for(u16 y=0; y<MAP_BLOCKSIZE; y++) for(u16 x=0; x<MAP_BLOCKSIZE; x++) { //UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_AIR); UASSERT(b.getNode(v3s16(x,y,z)).getContent() == CONTENT_IGNORE); UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(x,y,z)).getLight(LIGHTBANK_NIGHT) == 0); } { MapNode n(CONTENT_AIR); for(u16 z=0; z<MAP_BLOCKSIZE; z++) for(u16 y=0; y<MAP_BLOCKSIZE; y++) for(u16 x=0; x<MAP_BLOCKSIZE; x++) { b.setNode(v3s16(x,y,z), n); } } /* Parent fetch functions */ parent.position_valid = false; parent.node.setContent(5); MapNode n; // Positions in the block should still be valid UASSERT(b.isValidPositionParent(v3s16(0,0,0)) == true); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1)) == true); n = b.getNodeParent(v3s16(0,MAP_BLOCKSIZE-1,0)); UASSERT(n.getContent() == CONTENT_AIR); // ...but outside the block they should be invalid UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == false); UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == false); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == false); { bool exception_thrown = false; try{ // This should throw an exception MapNode n = b.getNodeParent(v3s16(0,0,-1)); } catch(InvalidPositionException &e) { exception_thrown = true; } UASSERT(exception_thrown); } parent.position_valid = true; // Now the positions outside should be valid UASSERT(b.isValidPositionParent(v3s16(-121,2341,0)) == true); UASSERT(b.isValidPositionParent(v3s16(-1,0,0)) == true); UASSERT(b.isValidPositionParent(v3s16(MAP_BLOCKSIZE-1,MAP_BLOCKSIZE-1,MAP_BLOCKSIZE)) == true); n = b.getNodeParent(v3s16(0,0,MAP_BLOCKSIZE)); UASSERT(n.getContent() == 5); /* Set a node */ v3s16 p(1,2,0); n.setContent(4); b.setNode(p, n); UASSERT(b.getNode(p).getContent() == 4); //TODO: Update to new system /*UASSERT(b.getNodeTile(p) == 4); UASSERT(b.getNodeTile(v3s16(-1,-1,0)) == 5);*/ /* propagateSunlight() */ // Set lighting of all nodes to 0 for(u16 z=0; z<MAP_BLOCKSIZE; z++){ for(u16 y=0; y<MAP_BLOCKSIZE; y++){ for(u16 x=0; x<MAP_BLOCKSIZE; x++){ MapNode n = b.getNode(v3s16(x,y,z)); n.setLight(LIGHTBANK_DAY, 0); n.setLight(LIGHTBANK_NIGHT, 0); b.setNode(v3s16(x,y,z), n); } } } { /* Check how the block handles being a lonely sky block */ parent.position_valid = true; b.setIsUnderground(false); parent.node.setContent(CONTENT_AIR); parent.node.setLight(LIGHTBANK_DAY, LIGHT_SUN); parent.node.setLight(LIGHTBANK_NIGHT, 0); core::map<v3s16, bool> light_sources; // The bottom block is invalid, because we have a shadowing node UASSERT(b.propagateSunlight(light_sources) == false); UASSERT(b.getNode(v3s16(1,4,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getNode(v3s16(1,3,0)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getNode(v3s16(1,2,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,1,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,0,0)).getLight(LIGHTBANK_DAY) == 0); UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == LIGHT_SUN); UASSERT(b.getFaceLight2(1000, p, v3s16(0,1,0)) == LIGHT_SUN); UASSERT(b.getFaceLight2(1000, p, v3s16(0,-1,0)) == 0); UASSERT(b.getFaceLight2(0, p, v3s16(0,-1,0)) == 0); // According to MapBlock::getFaceLight, // The face on the z+ side should have double-diminished light //UASSERT(b.getFaceLight(p, v3s16(0,0,1)) == diminish_light(diminish_light(LIGHT_MAX))); // The face on the z+ side should have diminished light UASSERT(b.getFaceLight2(1000, p, v3s16(0,0,1)) == diminish_light(LIGHT_MAX)); } /* Check how the block handles being in between blocks with some non-sunlight while being underground */ { // Make neighbours to exist and set some non-sunlight to them parent.position_valid = true; b.setIsUnderground(true); parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2); core::map<v3s16, bool> light_sources; // The block below should be valid because there shouldn't be // sunlight in there either UASSERT(b.propagateSunlight(light_sources, true) == true); // Should not touch nodes that are not affected (that is, all of them) //UASSERT(b.getNode(v3s16(1,2,3)).getLight() == LIGHT_SUN); // Should set light of non-sunlighted blocks to 0. UASSERT(b.getNode(v3s16(1,2,3)).getLight(LIGHTBANK_DAY) == 0); } /* Set up a situation where: - There is only air in this block - There is a valid non-sunlighted block at the bottom, and - Invalid blocks elsewhere. - the block is not underground. This should result in bottom block invalidity */ { b.setIsUnderground(false); // Clear block for(u16 z=0; z<MAP_BLOCKSIZE; z++){ for(u16 y=0; y<MAP_BLOCKSIZE; y++){ for(u16 x=0; x<MAP_BLOCKSIZE; x++){ MapNode n; n.setContent(CONTENT_AIR); n.setLight(LIGHTBANK_DAY, 0); b.setNode(v3s16(x,y,z), n); } } } // Make neighbours invalid parent.position_valid = false; // Add exceptions to the top of the bottom block for(u16 x=0; x<MAP_BLOCKSIZE; x++) for(u16 z=0; z<MAP_BLOCKSIZE; z++) { parent.validity_exceptions.push_back(v3s16(MAP_BLOCKSIZE+x, MAP_BLOCKSIZE-1, MAP_BLOCKSIZE+z)); } // Lighting value for the valid nodes parent.node.setLight(LIGHTBANK_DAY, LIGHT_MAX/2); core::map<v3s16, bool> light_sources; // Bottom block is not valid UASSERT(b.propagateSunlight(light_sources) == false); } } }; struct TestMapSector: public TestBase { class TC : public NodeContainer { public: MapNode node; bool position_valid; TC() { position_valid = true; } virtual bool isValidPosition(v3s16 p) { return position_valid; } virtual MapNode getNode(v3s16 p) { if(position_valid == false) throw InvalidPositionException(); return node; } virtual void setNode(v3s16 p, MapNode & n) { if(position_valid == false) throw InvalidPositionException(); }; virtual u16 nodeContainerId() const { return 666; } }; void Run() { TC parent; parent.position_valid = false; // Create one with no heightmaps ServerMapSector sector(&parent, v2s16(1,1)); UASSERT(sector.getBlockNoCreateNoEx(0) == 0); UASSERT(sector.getBlockNoCreateNoEx(1) == 0); MapBlock * bref = sector.createBlankBlock(-2); UASSERT(sector.getBlockNoCreateNoEx(0) == 0); UASSERT(sector.getBlockNoCreateNoEx(-2) == bref); //TODO: Check for AlreadyExistsException /*bool exception_thrown = false; try{ sector.getBlock(0); } catch(InvalidPositionException &e){ exception_thrown = true; } UASSERT(exception_thrown);*/ } }; #endif
pgimeno/minetest
src/unittest/test.cpp
C++
mit
19,074
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <exception> #include <vector> #include "irrlichttypes_extrabloated.h" #include "porting.h" #include "filesys.h" #include "mapnode.h" class TestFailedException : public std::exception { }; // Runs a unit test and reports results #define TEST(fxn, ...) { \ u64 t1 = porting::getTimeMs(); \ try { \ fxn(__VA_ARGS__); \ rawstream << "[PASS] "; \ } catch (TestFailedException &e) { \ rawstream << "[FAIL] "; \ num_tests_failed++; \ } catch (std::exception &e) { \ rawstream << "Caught unhandled exception: " << e.what() << std::endl; \ rawstream << "[FAIL] "; \ num_tests_failed++; \ } \ num_tests_run++; \ u64 tdiff = porting::getTimeMs() - t1; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ } // Asserts the specified condition is true, or fails the current unit test #define UASSERT(x) \ if (!(x)) { \ rawstream << "Test assertion failed: " #x << std::endl \ << " at " << fs::GetFilenameFromPath(__FILE__) \ << ":" << __LINE__ << std::endl; \ throw TestFailedException(); \ } // Asserts the specified condition is true, or fails the current unit test // and prints the format specifier fmt #define UTEST(x, fmt, ...) \ if (!(x)) { \ char utest_buf[1024]; \ snprintf(utest_buf, sizeof(utest_buf), fmt, __VA_ARGS__); \ rawstream << "Test assertion failed: " << utest_buf << std::endl \ << " at " << fs::GetFilenameFromPath(__FILE__) \ << ":" << __LINE__ << std::endl; \ throw TestFailedException(); \ } // Asserts the comparison specified by CMP is true, or fails the current unit test #define UASSERTCMP(T, CMP, actual, expected) { \ T a = (actual); \ T e = (expected); \ if (!(a CMP e)) { \ rawstream \ << "Test assertion failed: " << #actual << " " << #CMP << " " \ << #expected << std::endl \ << " at " << fs::GetFilenameFromPath(__FILE__) << ":" \ << __LINE__ << std::endl \ << " actual: " << a << std::endl << " expected: " \ << e << std::endl; \ throw TestFailedException(); \ } \ } #define UASSERTEQ(T, actual, expected) UASSERTCMP(T, ==, actual, expected) // UASSERTs that the specified exception occurs #define EXCEPTION_CHECK(EType, code) { \ bool exception_thrown = false; \ try { \ code; \ } catch (EType &e) { \ exception_thrown = true; \ } \ UASSERT(exception_thrown); \ } class IGameDef; class TestBase { public: bool testModule(IGameDef *gamedef); std::string getTestTempDirectory(); std::string getTestTempFile(); virtual void runTests(IGameDef *gamedef) = 0; virtual const char *getName() = 0; u32 num_tests_failed; u32 num_tests_run; private: std::string m_test_dir; }; class TestManager { public: static std::vector<TestBase *> &getTestModules() { static std::vector<TestBase *> m_modules_to_test; return m_modules_to_test; } static void registerTestModule(TestBase *module) { getTestModules().push_back(module); } }; // A few item and node definitions for those tests that need them extern content_t t_CONTENT_STONE; extern content_t t_CONTENT_GRASS; extern content_t t_CONTENT_TORCH; extern content_t t_CONTENT_WATER; extern content_t t_CONTENT_LAVA; extern content_t t_CONTENT_BRICK; bool run_tests();
pgimeno/minetest
src/unittest/test.h
C++
mit
5,685
/* Minetest Copyright (C) 2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "activeobject.h" class TestActiveObject : public TestBase { public: TestActiveObject() { TestManager::registerTestModule(this); } const char *getName() { return "TestActiveObject"; } void runTests(IGameDef *gamedef); void testAOAttributes(); }; static TestActiveObject g_test_instance; void TestActiveObject::runTests(IGameDef *gamedef) { TEST(testAOAttributes); } class TestAO : public ActiveObject { public: TestAO(u16 id) : ActiveObject(id) {} virtual ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; } virtual bool getCollisionBox(aabb3f *toset) const { return false; } virtual bool getSelectionBox(aabb3f *toset) const { return false; } virtual bool collideWithObjects() const { return false; } }; void TestActiveObject::testAOAttributes() { TestAO ao(44); UASSERT(ao.getId() == 44); ao.setId(558); UASSERT(ao.getId() == 558); }
pgimeno/minetest
src/unittest/test_activeobject.cpp
C++
mit
1,691
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "log.h" #include "settings.h" #include "network/socket.h" class TestAddress : public TestBase { public: TestAddress() { TestManager::registerTestModule(this); } const char *getName() { return "TestAddress"; } void runTests(IGameDef *gamedef); void testIsLocalhost(); }; static TestAddress g_test_instance; void TestAddress::runTests(IGameDef *gamedef) { TEST(testIsLocalhost); } void TestAddress::testIsLocalhost() { // v4 UASSERT(Address(127, 0, 0, 1, 0).isLocalhost()); UASSERT(Address(127, 254, 12, 99, 0).isLocalhost()); UASSERT(Address(127, 188, 255, 247, 0).isLocalhost()); UASSERT(!Address(126, 255, 255, 255, 0).isLocalhost()); UASSERT(!Address(128, 0, 0, 0, 0).isLocalhost()); UASSERT(!Address(1, 0, 0, 0, 0).isLocalhost()); UASSERT(!Address(255, 255, 255, 255, 0).isLocalhost()); UASSERT(!Address(36, 45, 99, 158, 0).isLocalhost()); UASSERT(!Address(172, 45, 37, 68, 0).isLocalhost()); // v6 std::unique_ptr<IPv6AddressBytes> ipv6Bytes(new IPv6AddressBytes()); std::vector<u8> ipv6RawAddr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; memcpy(ipv6Bytes->bytes, &ipv6RawAddr[0], 16); UASSERT(Address(ipv6Bytes.get(), 0).isLocalhost()) ipv6RawAddr = {16, 34, 0, 0, 0, 0, 29, 0, 0, 0, 188, 0, 0, 0, 0, 14}; memcpy(ipv6Bytes->bytes, &ipv6RawAddr[0], 16); UASSERT(!Address(ipv6Bytes.get(), 0).isLocalhost()) }
pgimeno/minetest
src/unittest/test_address.cpp
C++
mit
2,165
/* Minetest Copyright (C) 2015 est31, <MTest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "util/areastore.h" class TestAreaStore : public TestBase { public: TestAreaStore() { TestManager::registerTestModule(this); } const char *getName() { return "TestAreaStore"; } void runTests(IGameDef *gamedef); void genericStoreTest(AreaStore *store); void testVectorStore(); void testSpatialStore(); void testSerialization(); }; static TestAreaStore g_test_instance; void TestAreaStore::runTests(IGameDef *gamedef) { TEST(testVectorStore); #if USE_SPATIAL TEST(testSpatialStore); #endif TEST(testSerialization); } //////////////////////////////////////////////////////////////////////////////// void TestAreaStore::testVectorStore() { VectorAreaStore store; genericStoreTest(&store); } void TestAreaStore::testSpatialStore() { #if USE_SPATIAL SpatialAreaStore store; genericStoreTest(&store); #endif } void TestAreaStore::genericStoreTest(AreaStore *store) { Area a(v3s16(-10, -3, 5), v3s16(0, 29, 7)); Area b(v3s16(-5, -2, 5), v3s16(0, 28, 6)); Area c(v3s16(-7, -3, 6), v3s16(-1, 27, 7)); std::vector<Area *> res; UASSERTEQ(size_t, store->size(), 0); store->reserve(2); // sic store->insertArea(&a); store->insertArea(&b); store->insertArea(&c); UASSERTEQ(size_t, store->size(), 3); store->getAreasForPos(&res, v3s16(-1, 0, 6)); UASSERTEQ(size_t, res.size(), 3); res.clear(); store->getAreasForPos(&res, v3s16(0, 0, 7)); UASSERTEQ(size_t, res.size(), 1); res.clear(); store->removeArea(a.id); store->getAreasForPos(&res, v3s16(0, 0, 7)); UASSERTEQ(size_t, res.size(), 0); res.clear(); store->insertArea(&a); store->getAreasForPos(&res, v3s16(0, 0, 7)); UASSERTEQ(size_t, res.size(), 1); res.clear(); store->getAreasInArea(&res, v3s16(-10, -3, 5), v3s16(0, 29, 7), false); UASSERTEQ(size_t, res.size(), 3); res.clear(); store->getAreasInArea(&res, v3s16(-100, 0, 6), v3s16(200, 0, 6), false); UASSERTEQ(size_t, res.size(), 0); res.clear(); store->getAreasInArea(&res, v3s16(-100, 0, 6), v3s16(200, 0, 6), true); UASSERTEQ(size_t, res.size(), 3); res.clear(); store->removeArea(a.id); store->removeArea(b.id); store->removeArea(c.id); Area d(v3s16(-100, -300, -200), v3s16(-50, -200, -100)); d.data = "Hi!"; store->insertArea(&d); store->getAreasForPos(&res, v3s16(-75, -250, -150)); UASSERTEQ(size_t, res.size(), 1); UASSERTEQ(u16, res[0]->data.size(), 3); UASSERT(strncmp(res[0]->data.c_str(), "Hi!", 3) == 0); res.clear(); store->removeArea(d.id); } void TestAreaStore::testSerialization() { VectorAreaStore store; Area a(v3s16(-1, 0, 1), v3s16(0, 1, 2)); a.data = "Area A"; store.insertArea(&a); Area b(v3s16(123, 456, 789), v3s16(32000, 100, 10)); b.data = "Area B"; store.insertArea(&b); std::ostringstream os; store.serialize(os); std::string str = os.str(); std::string str_wanted("\x00" // Version "\x00\x02" // Count "\xFF\xFF\x00\x00\x00\x01" // Area A min edge "\x00\x00\x00\x01\x00\x02" // Area A max edge "\x00\x06" // Area A data length "Area A" // Area A data "\x00\x7B\x00\x64\x00\x0A" // Area B min edge (last two swapped with max edge for sorting) "\x7D\x00\x01\xC8\x03\x15" // Area B max edge (^) "\x00\x06" // Area B data length "Area B", // Area B data 1 + 2 + 6 + 6 + 2 + 6 + 6 + 6 + 2 + 6); UASSERTEQ(std::string, str, str_wanted); std::istringstream is(str); store.deserialize(is); UASSERTEQ(size_t, store.size(), 4); // deserialize() doesn't clear the store }
pgimeno/minetest
src/unittest/test_areastore.cpp
C++
mit
4,232
/* Minetest Copyright (C) 2018 bendeutsch, Ben Deutsch <ben@bendeutsch.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <algorithm> #include "database/database-files.h" #include "database/database-sqlite3.h" #include "util/string.h" #include "filesys.h" namespace { // Anonymous namespace to create classes that are only // visible to this file // // These are helpers that return a *AuthDatabase and // allow us to run the same tests on different databases and // database acquisition strategies. class AuthDatabaseProvider { public: virtual ~AuthDatabaseProvider() = default; virtual AuthDatabase *getAuthDatabase() = 0; }; class FixedProvider : public AuthDatabaseProvider { public: FixedProvider(AuthDatabase *auth_db) : auth_db(auth_db){}; virtual ~FixedProvider(){}; virtual AuthDatabase *getAuthDatabase() { return auth_db; }; private: AuthDatabase *auth_db; }; class FilesProvider : public AuthDatabaseProvider { public: FilesProvider(const std::string &dir) : dir(dir){}; virtual ~FilesProvider() { delete auth_db; }; virtual AuthDatabase *getAuthDatabase() { delete auth_db; auth_db = new AuthDatabaseFiles(dir); return auth_db; }; private: std::string dir; AuthDatabase *auth_db = nullptr; }; class SQLite3Provider : public AuthDatabaseProvider { public: SQLite3Provider(const std::string &dir) : dir(dir){}; virtual ~SQLite3Provider() { delete auth_db; }; virtual AuthDatabase *getAuthDatabase() { delete auth_db; auth_db = new AuthDatabaseSQLite3(dir); return auth_db; }; private: std::string dir; AuthDatabase *auth_db = nullptr; }; } class TestAuthDatabase : public TestBase { public: TestAuthDatabase() { TestManager::registerTestModule(this); } const char *getName() { return "TestAuthDatabase"; } void runTests(IGameDef *gamedef); void runTestsForCurrentDB(); void testRecallFail(); void testCreate(); void testRecall(); void testChange(); void testRecallChanged(); void testChangePrivileges(); void testRecallChangedPrivileges(); void testListNames(); void testDelete(); private: AuthDatabaseProvider *auth_provider; }; static TestAuthDatabase g_test_instance; void TestAuthDatabase::runTests(IGameDef *gamedef) { // fixed directory, for persistence thread_local const std::string test_dir = getTestTempDirectory(); // Each set of tests is run twice for each database type: // one where we reuse the same AuthDatabase object (to test local caching), // and one where we create a new AuthDatabase object for each call // (to test actual persistence). rawstream << "-------- Files database (same object)" << std::endl; AuthDatabase *auth_db = new AuthDatabaseFiles(test_dir); auth_provider = new FixedProvider(auth_db); runTestsForCurrentDB(); delete auth_db; delete auth_provider; // reset database fs::DeleteSingleFileOrEmptyDirectory(test_dir + DIR_DELIM + "auth.txt"); rawstream << "-------- Files database (new objects)" << std::endl; auth_provider = new FilesProvider(test_dir); runTestsForCurrentDB(); delete auth_provider; rawstream << "-------- SQLite3 database (same object)" << std::endl; auth_db = new AuthDatabaseSQLite3(test_dir); auth_provider = new FixedProvider(auth_db); runTestsForCurrentDB(); delete auth_db; delete auth_provider; // reset database fs::DeleteSingleFileOrEmptyDirectory(test_dir + DIR_DELIM + "auth.sqlite"); rawstream << "-------- SQLite3 database (new objects)" << std::endl; auth_provider = new SQLite3Provider(test_dir); runTestsForCurrentDB(); delete auth_provider; } //////////////////////////////////////////////////////////////////////////////// void TestAuthDatabase::runTestsForCurrentDB() { TEST(testRecallFail); TEST(testCreate); TEST(testRecall); TEST(testChange); TEST(testRecallChanged); TEST(testChangePrivileges); TEST(testRecallChangedPrivileges); TEST(testListNames); TEST(testDelete); TEST(testRecallFail); } void TestAuthDatabase::testRecallFail() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; // no such user yet UASSERT(!auth_db->getAuth("TestName", authEntry)); } void TestAuthDatabase::testCreate() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; authEntry.name = "TestName"; authEntry.password = "TestPassword"; authEntry.privileges.emplace_back("shout"); authEntry.privileges.emplace_back("interact"); authEntry.last_login = 1000; UASSERT(auth_db->createAuth(authEntry)); } void TestAuthDatabase::testRecall() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; UASSERT(auth_db->getAuth("TestName", authEntry)); UASSERTEQ(std::string, authEntry.name, "TestName"); UASSERTEQ(std::string, authEntry.password, "TestPassword"); // the order of privileges is unimportant std::sort(authEntry.privileges.begin(), authEntry.privileges.end()); UASSERTEQ(std::string, str_join(authEntry.privileges, ","), "interact,shout"); } void TestAuthDatabase::testChange() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; UASSERT(auth_db->getAuth("TestName", authEntry)); authEntry.password = "NewPassword"; authEntry.last_login = 1002; UASSERT(auth_db->saveAuth(authEntry)); } void TestAuthDatabase::testRecallChanged() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; UASSERT(auth_db->getAuth("TestName", authEntry)); UASSERTEQ(std::string, authEntry.password, "NewPassword"); // the order of privileges is unimportant std::sort(authEntry.privileges.begin(), authEntry.privileges.end()); UASSERTEQ(std::string, str_join(authEntry.privileges, ","), "interact,shout"); UASSERTEQ(u64, authEntry.last_login, 1002); } void TestAuthDatabase::testChangePrivileges() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; UASSERT(auth_db->getAuth("TestName", authEntry)); authEntry.privileges.clear(); authEntry.privileges.emplace_back("interact"); authEntry.privileges.emplace_back("fly"); authEntry.privileges.emplace_back("dig"); UASSERT(auth_db->saveAuth(authEntry)); } void TestAuthDatabase::testRecallChangedPrivileges() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); AuthEntry authEntry; UASSERT(auth_db->getAuth("TestName", authEntry)); // the order of privileges is unimportant std::sort(authEntry.privileges.begin(), authEntry.privileges.end()); UASSERTEQ(std::string, str_join(authEntry.privileges, ","), "dig,fly,interact"); } void TestAuthDatabase::testListNames() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); std::vector<std::string> list; AuthEntry authEntry; authEntry.name = "SecondName"; authEntry.password = "SecondPassword"; authEntry.privileges.emplace_back("shout"); authEntry.privileges.emplace_back("interact"); authEntry.last_login = 1003; auth_db->createAuth(authEntry); auth_db->listNames(list); // not necessarily sorted, so sort before comparing std::sort(list.begin(), list.end()); UASSERTEQ(std::string, str_join(list, ","), "SecondName,TestName"); } void TestAuthDatabase::testDelete() { AuthDatabase *auth_db = auth_provider->getAuthDatabase(); UASSERT(!auth_db->deleteAuth("NoSuchName")); UASSERT(auth_db->deleteAuth("TestName")); // second try, expect failure UASSERT(!auth_db->deleteAuth("TestName")); }
pgimeno/minetest
src/unittest/test_authdatabase.cpp
C++
mit
8,007
/* Minetest Copyright (C) 2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "ban.h" class TestBan : public TestBase { public: TestBan() { TestManager::registerTestModule(this); } const char *getName() { return "TestBan"; } void runTests(IGameDef *gamedef); private: void testCreate(); void testAdd(); void testRemove(); void testModificationFlag(); void testGetBanName(); void testGetBanDescription(); void reinitTestEnv(); }; static TestBan g_test_instance; void TestBan::runTests(IGameDef *gamedef) { reinitTestEnv(); TEST(testCreate); reinitTestEnv(); TEST(testAdd); reinitTestEnv(); TEST(testRemove); reinitTestEnv(); TEST(testModificationFlag); reinitTestEnv(); TEST(testGetBanName); reinitTestEnv(); TEST(testGetBanDescription); } // This module is stateful due to disk writes, add helper to remove files void TestBan::reinitTestEnv() { fs::DeleteSingleFileOrEmptyDirectory("testbm.txt"); fs::DeleteSingleFileOrEmptyDirectory("testbm2.txt"); } void TestBan::testCreate() { // test save on object removal { BanManager bm("testbm.txt"); } UASSERT(std::ifstream("testbm.txt", std::ios::binary).is_open()); // test manual save { BanManager bm("testbm2.txt"); bm.save(); UASSERT(std::ifstream("testbm2.txt", std::ios::binary).is_open()); } } void TestBan::testAdd() { std::string bm_test1_entry = "192.168.0.246"; std::string bm_test1_result = "test_username"; BanManager bm("testbm.txt"); bm.add(bm_test1_entry, bm_test1_result); UASSERT(bm.getBanName(bm_test1_entry) == bm_test1_result); } void TestBan::testRemove() { std::string bm_test1_entry = "192.168.0.249"; std::string bm_test1_result = "test_username"; std::string bm_test2_entry = "192.168.0.250"; std::string bm_test2_result = "test_username7"; BanManager bm("testbm.txt"); // init data bm.add(bm_test1_entry, bm_test1_result); bm.add(bm_test2_entry, bm_test2_result); // the test bm.remove(bm_test1_entry); UASSERT(bm.getBanName(bm_test1_entry).empty()); bm.remove(bm_test2_result); UASSERT(bm.getBanName(bm_test2_result).empty()); } void TestBan::testModificationFlag() { BanManager bm("testbm.txt"); bm.add("192.168.0.247", "test_username"); UASSERT(bm.isModified()); bm.remove("192.168.0.247"); UASSERT(bm.isModified()); // Clear the modification flag bm.save(); // Test modification flag is entry was not present bm.remove("test_username"); UASSERT(!bm.isModified()); } void TestBan::testGetBanName() { std::string bm_test1_entry = "192.168.0.247"; std::string bm_test1_result = "test_username"; BanManager bm("testbm.txt"); bm.add(bm_test1_entry, bm_test1_result); // Test with valid entry UASSERT(bm.getBanName(bm_test1_entry) == bm_test1_result); // Test with invalid entry UASSERT(bm.getBanName("---invalid---").empty()); } void TestBan::testGetBanDescription() { std::string bm_test1_entry = "192.168.0.247"; std::string bm_test1_entry2 = "test_username"; std::string bm_test1_result = "192.168.0.247|test_username"; BanManager bm("testbm.txt"); bm.add(bm_test1_entry, bm_test1_entry2); UASSERT(bm.getBanDescription(bm_test1_entry) == bm_test1_result); UASSERT(bm.getBanDescription(bm_test1_entry2) == bm_test1_result); }
pgimeno/minetest
src/unittest/test_ban.cpp
C++
mit
3,955
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "client/activeobjectmgr.h" #include <algorithm> #include "test.h" #include "profiler.h" class TestClientActiveObject : public ClientActiveObject { public: TestClientActiveObject() : ClientActiveObject(0, nullptr, nullptr) {} ~TestClientActiveObject() = default; ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; } }; class TestClientActiveObjectMgr : public TestBase { public: TestClientActiveObjectMgr() { TestManager::registerTestModule(this); } const char *getName() { return "TestClientActiveObjectMgr"; } void runTests(IGameDef *gamedef); void testFreeID(); void testRegisterObject(); void testRemoveObject(); }; static TestClientActiveObjectMgr g_test_instance; void TestClientActiveObjectMgr::runTests(IGameDef *gamedef) { TEST(testFreeID); TEST(testRegisterObject) TEST(testRemoveObject) } //////////////////////////////////////////////////////////////////////////////// void TestClientActiveObjectMgr::testFreeID() { client::ActiveObjectMgr caomgr; std::vector<u16> aoids; u16 aoid = caomgr.getFreeId(); // Ensure it's not the same id UASSERT(caomgr.getFreeId() != aoid); aoids.push_back(aoid); // Register basic objects, ensure we never found for (u8 i = 0; i < UINT8_MAX; i++) { // Register an object auto tcao = new TestClientActiveObject(); caomgr.registerObject(tcao); aoids.push_back(tcao->getId()); // Ensure next id is not in registered list UASSERT(std::find(aoids.begin(), aoids.end(), caomgr.getFreeId()) == aoids.end()); } caomgr.clear(); } void TestClientActiveObjectMgr::testRegisterObject() { client::ActiveObjectMgr caomgr; auto tcao = new TestClientActiveObject(); UASSERT(caomgr.registerObject(tcao)); u16 id = tcao->getId(); auto tcaoToCompare = caomgr.getActiveObject(id); UASSERT(tcaoToCompare->getId() == id); UASSERT(tcaoToCompare == tcao); tcao = new TestClientActiveObject(); UASSERT(caomgr.registerObject(tcao)); UASSERT(caomgr.getActiveObject(tcao->getId()) == tcao); UASSERT(caomgr.getActiveObject(tcao->getId()) != tcaoToCompare); caomgr.clear(); } void TestClientActiveObjectMgr::testRemoveObject() { client::ActiveObjectMgr caomgr; auto tcao = new TestClientActiveObject(); UASSERT(caomgr.registerObject(tcao)); u16 id = tcao->getId(); UASSERT(caomgr.getActiveObject(id) != nullptr) caomgr.removeObject(tcao->getId()); UASSERT(caomgr.getActiveObject(id) == nullptr) caomgr.clear(); }
pgimeno/minetest
src/unittest/test_clientactiveobjectmgr.cpp
C++
mit
3,219
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "collision.h" class TestCollision : public TestBase { public: TestCollision() { TestManager::registerTestModule(this); } const char *getName() { return "TestCollision"; } void runTests(IGameDef *gamedef); void testAxisAlignedCollision(); }; static TestCollision g_test_instance; void TestCollision::runTests(IGameDef *gamedef) { TEST(testAxisAlignedCollision); } //////////////////////////////////////////////////////////////////////////////// void TestCollision::testAxisAlignedCollision() { for (s16 bx = -3; bx <= 3; bx++) for (s16 by = -3; by <= 3; by++) for (s16 bz = -3; bz <= 3; bz++) { // X- { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1); v3f v(1, 0, 0); f32 dtime = 0; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 1.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by, bz, bx-1, by+1, bz+1); v3f v(-1, 0, 0); f32 dtime = 0; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by+1.5, bz, bx-1, by+2.5, bz-1); v3f v(1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1); v3f v(0.5, 0.1, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 3.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx-2, by-1.5, bz, bx-1.5, by+0.5, bz+1); v3f v(0.5, 0.1, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 3.000) < 0.001); } // X+ { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1); v3f v(-1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 1.000) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz, bx+3, by+1, bz+1); v3f v(1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by, bz+1.5, bx+3, by+1, bz+3.5); v3f v(-1, 0, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == -1); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1); v3f v(-0.5, 0.2, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 1); // Y, not X! UASSERT(fabs(dtime - 2.500) < 0.001); } { aabb3f s(bx, by, bz, bx+1, by+1, bz+1); aabb3f m(bx+2, by-1.5, bz, bx+2.5, by-0.5, bz+1); v3f v(-0.5, 0.3, 0); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 2.000) < 0.001); } // TODO: Y-, Y+, Z-, Z+ // misc { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.3, by+2.29, bz+2.29, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.29, by+2.3, bz+2.29, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 1); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx+2.29, by+2.29, bz+2.3, bx+4.2, by+4.2, bz+4.2); v3f v(-1./3, -1./3, -1./3); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 2); UASSERT(fabs(dtime - 0.9) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.3, by-2.29, bz-2.29); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 0); UASSERT(fabs(dtime - 16.1) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.3, bz-2.29); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 1); UASSERT(fabs(dtime - 16.1) < 0.001); } { aabb3f s(bx, by, bz, bx+2, by+2, bz+2); aabb3f m(bx-4.2, by-4.2, bz-4.2, bx-2.29, by-2.29, bz-2.3); v3f v(1./7, 1./7, 1./7); f32 dtime; UASSERT(axisAlignedCollision(s, m, v, 0, &dtime) == 2); UASSERT(fabs(dtime - 16.1) < 0.001); } } }
pgimeno/minetest
src/unittest/test_collision.cpp
C++
mit
5,235
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <sstream> #include "irrlichttypes_extrabloated.h" #include "log.h" #include "serialization.h" #include "nodedef.h" #include "noise.h" class TestCompression : public TestBase { public: TestCompression() { TestManager::registerTestModule(this); } const char *getName() { return "TestCompression"; } void runTests(IGameDef *gamedef); void testRLECompression(); void testZlibCompression(); void testZlibLargeData(); }; static TestCompression g_test_instance; void TestCompression::runTests(IGameDef *gamedef) { TEST(testRLECompression); TEST(testZlibCompression); TEST(testZlibLargeData); } //////////////////////////////////////////////////////////////////////////////// void TestCompression::testRLECompression() { SharedBuffer<u8> fromdata(4); fromdata[0]=1; fromdata[1]=5; fromdata[2]=5; fromdata[3]=1; std::ostringstream os(std::ios_base::binary); compress(fromdata, os, 0); std::string str_out = os.str(); infostream << "str_out.size()="<<str_out.size()<<std::endl; infostream << "TestCompress: 1,5,5,1 -> "; for (char i : str_out) infostream << (u32) i << ","; infostream << std::endl; UASSERT(str_out.size() == 10); UASSERT(str_out[0] == 0); UASSERT(str_out[1] == 0); UASSERT(str_out[2] == 0); UASSERT(str_out[3] == 4); UASSERT(str_out[4] == 0); UASSERT(str_out[5] == 1); UASSERT(str_out[6] == 1); UASSERT(str_out[7] == 5); UASSERT(str_out[8] == 0); UASSERT(str_out[9] == 1); std::istringstream is(str_out, std::ios_base::binary); std::ostringstream os2(std::ios_base::binary); decompress(is, os2, 0); std::string str_out2 = os2.str(); infostream << "decompress: "; for (char i : str_out2) infostream << (u32) i << ","; infostream << std::endl; UASSERTEQ(size_t, str_out2.size(), fromdata.getSize()); for (u32 i = 0; i < str_out2.size(); i++) UASSERT(str_out2[i] == fromdata[i]); } void TestCompression::testZlibCompression() { SharedBuffer<u8> fromdata(4); fromdata[0]=1; fromdata[1]=5; fromdata[2]=5; fromdata[3]=1; std::ostringstream os(std::ios_base::binary); compress(fromdata, os, SER_FMT_VER_HIGHEST_READ); std::string str_out = os.str(); infostream << "str_out.size()=" << str_out.size() <<std::endl; infostream << "TestCompress: 1,5,5,1 -> "; for (char i : str_out) infostream << (u32) i << ","; infostream << std::endl; std::istringstream is(str_out, std::ios_base::binary); std::ostringstream os2(std::ios_base::binary); decompress(is, os2, SER_FMT_VER_HIGHEST_READ); std::string str_out2 = os2.str(); infostream << "decompress: "; for (char i : str_out2) infostream << (u32) i << ","; infostream << std::endl; UASSERTEQ(size_t, str_out2.size(), fromdata.getSize()); for (u32 i = 0; i < str_out2.size(); i++) UASSERT(str_out2[i] == fromdata[i]); } void TestCompression::testZlibLargeData() { infostream << "Test: Testing zlib wrappers with a large amount " "of pseudorandom data" << std::endl; u32 size = 50000; infostream << "Test: Input size of large compressZlib is " << size << std::endl; std::string data_in; data_in.resize(size); PseudoRandom pseudorandom(9420); for (u32 i = 0; i < size; i++) data_in[i] = pseudorandom.range(0, 255); std::ostringstream os_compressed(std::ios::binary); compressZlib(data_in, os_compressed); infostream << "Test: Output size of large compressZlib is " << os_compressed.str().size()<<std::endl; std::istringstream is_compressed(os_compressed.str(), std::ios::binary); std::ostringstream os_decompressed(std::ios::binary); decompressZlib(is_compressed, os_decompressed); infostream << "Test: Output size of large decompressZlib is " << os_decompressed.str().size() << std::endl; std::string str_decompressed = os_decompressed.str(); UASSERTEQ(size_t, str_decompressed.size(), data_in.size()); for (u32 i = 0; i < size && i < str_decompressed.size(); i++) { UTEST(str_decompressed[i] == data_in[i], "index out[%i]=%i differs from in[%i]=%i", i, str_decompressed[i], i, data_in[i]); } }
pgimeno/minetest
src/unittest/test_compression.cpp
C++
mit
4,796
// Filled in by the build system #pragma once #define TEST_WORLDDIR "@TEST_WORLDDIR@" #define TEST_SUBGAME_PATH "@TEST_SUBGAME_PATH@"
pgimeno/minetest
src/unittest/test_config.h.in
in
mit
136
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "log.h" #include "porting.h" #include "settings.h" #include "util/serialize.h" #include "network/connection.h" #include "network/networkpacket.h" #include "network/socket.h" class TestConnection : public TestBase { public: TestConnection() { if (INTERNET_SIMULATOR == false) TestManager::registerTestModule(this); } const char *getName() { return "TestConnection"; } void runTests(IGameDef *gamedef); void testHelpers(); void testConnectSendReceive(); }; static TestConnection g_test_instance; void TestConnection::runTests(IGameDef *gamedef) { TEST(testHelpers); TEST(testConnectSendReceive); } //////////////////////////////////////////////////////////////////////////////// struct Handler : public con::PeerHandler { Handler(const char *a_name) : name(a_name) {} void peerAdded(con::Peer *peer) { infostream << "Handler(" << name << ")::peerAdded(): " "id=" << peer->id << std::endl; last_id = peer->id; count++; } void deletingPeer(con::Peer *peer, bool timeout) { infostream << "Handler(" << name << ")::deletingPeer(): " "id=" << peer->id << ", timeout=" << timeout << std::endl; last_id = peer->id; count--; } s32 count = 0; u16 last_id = 0; const char *name; }; void TestConnection::testHelpers() { // Some constants for testing u32 proto_id = 0x12345678; session_t peer_id = 123; u8 channel = 2; SharedBuffer<u8> data1(1); data1[0] = 100; Address a(127,0,0,1, 10); const u16 seqnum = 34352; con::BufferedPacket p1 = con::makePacket(a, data1, proto_id, peer_id, channel); /* We should now have a packet with this data: Header: [0] u32 protocol_id [4] session_t sender_peer_id [6] u8 channel Data: [7] u8 data1[0] */ UASSERT(readU32(&p1.data[0]) == proto_id); UASSERT(readU16(&p1.data[4]) == peer_id); UASSERT(readU8(&p1.data[6]) == channel); UASSERT(readU8(&p1.data[7]) == data1[0]); //infostream<<"initial data1[0]="<<((u32)data1[0]&0xff)<<std::endl; SharedBuffer<u8> p2 = con::makeReliablePacket(data1, seqnum); /*infostream<<"p2.getSize()="<<p2.getSize()<<", data1.getSize()=" <<data1.getSize()<<std::endl; infostream<<"readU8(&p2[3])="<<readU8(&p2[3]) <<" p2[3]="<<((u32)p2[3]&0xff)<<std::endl; infostream<<"data1[0]="<<((u32)data1[0]&0xff)<<std::endl;*/ UASSERT(p2.getSize() == 3 + data1.getSize()); UASSERT(readU8(&p2[0]) == con::PACKET_TYPE_RELIABLE); UASSERT(readU16(&p2[1]) == seqnum); UASSERT(readU8(&p2[3]) == data1[0]); } void TestConnection::testConnectSendReceive() { /* Test some real connections NOTE: This mostly tests the legacy interface. */ u32 proto_id = 0xad26846a; Handler hand_server("server"); Handler hand_client("client"); Address address(0, 0, 0, 0, 30001); Address bind_addr(0, 0, 0, 0, 30001); /* * Try to use the bind_address for servers with no localhost address * For example: FreeBSD jails */ std::string bind_str = g_settings->get("bind_address"); try { bind_addr.Resolve(bind_str.c_str()); if (!bind_addr.isIPv6()) { address = bind_addr; } } catch (ResolveError &e) { } infostream << "** Creating server Connection" << std::endl; con::Connection server(proto_id, 512, 5.0, false, &hand_server); server.Serve(address); infostream << "** Creating client Connection" << std::endl; con::Connection client(proto_id, 512, 5.0, false, &hand_client); UASSERT(hand_server.count == 0); UASSERT(hand_client.count == 0); sleep_ms(50); Address server_address(127, 0, 0, 1, 30001); if (address != Address(0, 0, 0, 0, 30001)) { server_address = bind_addr; } infostream << "** running client.Connect()" << std::endl; client.Connect(server_address); sleep_ms(50); // Client should not have added client yet UASSERT(hand_client.count == 0); try { NetworkPacket pkt; infostream << "** running client.Receive()" << std::endl; client.Receive(&pkt); infostream << "** Client received: peer_id=" << pkt.getPeerId() << ", size=" << pkt.getSize() << std::endl; } catch (con::NoIncomingDataException &e) { } // Client should have added server now UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); // Server should not have added client yet UASSERT(hand_server.count == 0); sleep_ms(100); try { NetworkPacket pkt; infostream << "** running server.Receive()" << std::endl; server.Receive(&pkt); infostream << "** Server received: peer_id=" << pkt.getPeerId() << ", size=" << pkt.getSize() << std::endl; } catch (con::NoIncomingDataException &e) { // No actual data received, but the client has // probably been connected } // Client should be the same UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); // Server should have the client UASSERT(hand_server.count == 1); UASSERT(hand_server.last_id == 2); //sleep_ms(50); while (client.Connected() == false) { try { NetworkPacket pkt; infostream << "** running client.Receive()" << std::endl; client.Receive(&pkt); infostream << "** Client received: peer_id=" << pkt.getPeerId() << ", size=" << pkt.getSize() << std::endl; } catch (con::NoIncomingDataException &e) { } sleep_ms(50); } sleep_ms(50); try { NetworkPacket pkt; infostream << "** running server.Receive()" << std::endl; server.Receive(&pkt); infostream << "** Server received: peer_id=" << pkt.getPeerId() << ", size=" << pkt.getSize() << std::endl; } catch (con::NoIncomingDataException &e) { } /* Simple send-receive test */ { NetworkPacket pkt; pkt.putRawPacket((u8*) "Hello World !", 14, 0); SharedBuffer<u8> sentdata = pkt.oldForgePacket(); infostream<<"** running client.Send()"<<std::endl; client.Send(PEER_ID_SERVER, 0, &pkt, true); sleep_ms(50); NetworkPacket recvpacket; infostream << "** running server.Receive()" << std::endl; server.Receive(&recvpacket); infostream << "** Server received: peer_id=" << pkt.getPeerId() << ", size=" << pkt.getSize() << ", data=" << (const char*)pkt.getU8Ptr(0) << std::endl; SharedBuffer<u8> recvdata = pkt.oldForgePacket(); UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0); } session_t peer_id_client = 2; /* Send a large packet */ { const int datasize = 30000; NetworkPacket pkt(0, datasize); for (u16 i=0; i<datasize; i++) { pkt << (u8) i/4; } infostream << "Sending data (size=" << datasize << "):"; for (int i = 0; i < datasize && i < 20; i++) { if (i % 2 == 0) infostream << " "; char buf[10]; porting::mt_snprintf(buf, sizeof(buf), "%.2X", ((int)((const char *)pkt.getU8Ptr(0))[i]) & 0xff); infostream<<buf; } if (datasize > 20) infostream << "..."; infostream << std::endl; SharedBuffer<u8> sentdata = pkt.oldForgePacket(); server.Send(peer_id_client, 0, &pkt, true); //sleep_ms(3000); SharedBuffer<u8> recvdata; infostream << "** running client.Receive()" << std::endl; session_t peer_id = 132; u16 size = 0; bool received = false; u64 timems0 = porting::getTimeMs(); for (;;) { if (porting::getTimeMs() - timems0 > 5000 || received) break; try { NetworkPacket pkt; client.Receive(&pkt); size = pkt.getSize(); peer_id = pkt.getPeerId(); recvdata = pkt.oldForgePacket(); received = true; } catch (con::NoIncomingDataException &e) { } sleep_ms(10); } UASSERT(received); infostream << "** Client received: peer_id=" << peer_id << ", size=" << size << std::endl; infostream << "Received data (size=" << size << "): "; for (int i = 0; i < size && i < 20; i++) { if (i % 2 == 0) infostream << " "; char buf[10]; porting::mt_snprintf(buf, sizeof(buf), "%.2X", ((int)(recvdata[i])) & 0xff); infostream << buf; } if (size > 20) infostream << "..."; infostream << std::endl; UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0); UASSERT(peer_id == PEER_ID_SERVER); } // Check peer handlers UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); UASSERT(hand_server.count == 1); UASSERT(hand_server.last_id == 2); }
pgimeno/minetest
src/unittest/test_connection.cpp
C++
mit
8,869
/* Minetest Copyright (C) 2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <unordered_map> #include "test.h" #include "client/event_manager.h" class TestEventManager : public TestBase { public: TestEventManager() { TestManager::registerTestModule(this); } const char *getName() override { return "TestEventManager"; } void runTests(IGameDef *gamedef) override; void testRegister(); void testDeregister(); void testRealEvent(); void testRealEventAfterDereg(); }; // EventManager test class class EventManagerTest : public EventManager { public: static void eventTest(MtEvent *e, void *data) { UASSERT(e->getType() >= 0); UASSERT(e->getType() < MtEvent::TYPE_MAX); EventManagerTest *emt = (EventManagerTest *)data; emt->m_test_value = e->getType(); } u64 getTestValue() const { return m_test_value; } void resetValue() { m_test_value = 0; } private: u64 m_test_value = 0; }; static TestEventManager g_test_instance; void TestEventManager::runTests(IGameDef *gamedef) { TEST(testRegister); TEST(testDeregister); TEST(testRealEvent); TEST(testRealEventAfterDereg); } void TestEventManager::testRegister() { EventManager ev; ev.reg(MtEvent::PLAYER_DAMAGE, nullptr, nullptr); ev.reg(MtEvent::PLAYER_DAMAGE, nullptr, nullptr); } void TestEventManager::testDeregister() { EventManager ev; ev.dereg(MtEvent::NODE_DUG, nullptr, nullptr); ev.reg(MtEvent::PLAYER_DAMAGE, nullptr, nullptr); ev.dereg(MtEvent::PLAYER_DAMAGE, nullptr, nullptr); } void TestEventManager::testRealEvent() { EventManager ev; std::unique_ptr<EventManagerTest> emt(new EventManagerTest()); ev.reg(MtEvent::PLAYER_REGAIN_GROUND, EventManagerTest::eventTest, emt.get()); // Put event & verify event value ev.put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); UASSERT(emt->getTestValue() == MtEvent::PLAYER_REGAIN_GROUND); } void TestEventManager::testRealEventAfterDereg() { EventManager ev; std::unique_ptr<EventManagerTest> emt(new EventManagerTest()); ev.reg(MtEvent::PLAYER_REGAIN_GROUND, EventManagerTest::eventTest, emt.get()); // Put event & verify event value ev.put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); UASSERT(emt->getTestValue() == MtEvent::PLAYER_REGAIN_GROUND); // Reset internal value emt->resetValue(); // Remove the registered event ev.dereg(MtEvent::PLAYER_REGAIN_GROUND, EventManagerTest::eventTest, emt.get()); // Push the new event & ensure we target the default value ev.put(new SimpleTriggerEvent(MtEvent::PLAYER_REGAIN_GROUND)); UASSERT(emt->getTestValue() == 0); }
pgimeno/minetest
src/unittest/test_eventmanager.cpp
C++
mit
3,268
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <sstream> #include "log.h" #include "serialization.h" #include "nodedef.h" #include "noise.h" class TestFilePath : public TestBase { public: TestFilePath() { TestManager::registerTestModule(this); } const char *getName() { return "TestFilePath"; } void runTests(IGameDef *gamedef); void testIsDirDelimiter(); void testPathStartsWith(); void testRemoveLastPathComponent(); void testRemoveLastPathComponentWithTrailingDelimiter(); void testRemoveRelativePathComponent(); }; static TestFilePath g_test_instance; void TestFilePath::runTests(IGameDef *gamedef) { TEST(testIsDirDelimiter); TEST(testPathStartsWith); TEST(testRemoveLastPathComponent); TEST(testRemoveLastPathComponentWithTrailingDelimiter); TEST(testRemoveRelativePathComponent); } //////////////////////////////////////////////////////////////////////////////// // adjusts a POSIX path to system-specific conventions // -> changes '/' to DIR_DELIM // -> absolute paths start with "C:\\" on windows std::string p(std::string path) { for (size_t i = 0; i < path.size(); ++i) { if (path[i] == '/') { path.replace(i, 1, DIR_DELIM); i += std::string(DIR_DELIM).size() - 1; // generally a no-op } } #ifdef _WIN32 if (path[0] == '\\') path = "C:" + path; #endif return path; } void TestFilePath::testIsDirDelimiter() { UASSERT(fs::IsDirDelimiter('/') == true); UASSERT(fs::IsDirDelimiter('A') == false); UASSERT(fs::IsDirDelimiter(0) == false); #ifdef _WIN32 UASSERT(fs::IsDirDelimiter('\\') == true); #else UASSERT(fs::IsDirDelimiter('\\') == false); #endif } void TestFilePath::testPathStartsWith() { const int numpaths = 12; std::string paths[numpaths] = { "", p("/"), p("/home/user/minetest"), p("/home/user/minetest/bin"), p("/home/user/.minetest"), p("/tmp/dir/file"), p("/tmp/file/"), p("/tmP/file"), p("/tmp"), p("/tmp/dir"), p("/home/user2/minetest/worlds"), p("/home/user2/minetest/world"), }; /* expected fs::PathStartsWith results 0 = returns false 1 = returns true 2 = returns false on windows, true elsewhere 3 = returns true on windows, false elsewhere 4 = returns true if and only if FILESYS_CASE_INSENSITIVE is true */ int expected_results[numpaths][numpaths] = { {1,2,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0}, {1,1,1,0,0,0,0,0,0,0,0,0}, {1,1,1,1,0,0,0,0,0,0,0,0}, {1,1,0,0,1,0,0,0,0,0,0,0}, {1,1,0,0,0,1,0,0,1,1,0,0}, {1,1,0,0,0,0,1,4,1,0,0,0}, {1,1,0,0,0,0,4,1,4,0,0,0}, {1,1,0,0,0,0,0,0,1,0,0,0}, {1,1,0,0,0,0,0,0,1,1,0,0}, {1,1,0,0,0,0,0,0,0,0,1,0}, {1,1,0,0,0,0,0,0,0,0,0,1}, }; for (int i = 0; i < numpaths; i++) for (int j = 0; j < numpaths; j++){ /*verbosestream<<"testing fs::PathStartsWith(\"" <<paths[i]<<"\", \"" <<paths[j]<<"\")"<<std::endl;*/ bool starts = fs::PathStartsWith(paths[i], paths[j]); int expected = expected_results[i][j]; if(expected == 0){ UASSERT(starts == false); } else if(expected == 1){ UASSERT(starts == true); } #ifdef _WIN32 else if(expected == 2){ UASSERT(starts == false); } else if(expected == 3){ UASSERT(starts == true); } #else else if(expected == 2){ UASSERT(starts == true); } else if(expected == 3){ UASSERT(starts == false); } #endif else if(expected == 4){ UASSERT(starts == (bool)FILESYS_CASE_INSENSITIVE); } } } void TestFilePath::testRemoveLastPathComponent() { std::string path, result, removed; UASSERT(fs::RemoveLastPathComponent("") == ""); path = p("/home/user/minetest/bin/..//worlds/world1"); result = fs::RemoveLastPathComponent(path, &removed, 0); UASSERT(result == path); UASSERT(removed == ""); result = fs::RemoveLastPathComponent(path, &removed, 1); UASSERT(result == p("/home/user/minetest/bin/..//worlds")); UASSERT(removed == p("world1")); result = fs::RemoveLastPathComponent(path, &removed, 2); UASSERT(result == p("/home/user/minetest/bin/..")); UASSERT(removed == p("worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 3); UASSERT(result == p("/home/user/minetest/bin")); UASSERT(removed == p("../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 4); UASSERT(result == p("/home/user/minetest")); UASSERT(removed == p("bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 5); UASSERT(result == p("/home/user")); UASSERT(removed == p("minetest/bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 6); UASSERT(result == p("/home")); UASSERT(removed == p("user/minetest/bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 7); #ifdef _WIN32 UASSERT(result == "C:"); #else UASSERT(result == ""); #endif UASSERT(removed == p("home/user/minetest/bin/../worlds/world1")); } void TestFilePath::testRemoveLastPathComponentWithTrailingDelimiter() { std::string path, result, removed; path = p("/home/user/minetest/bin/..//worlds/world1/"); result = fs::RemoveLastPathComponent(path, &removed, 0); UASSERT(result == path); UASSERT(removed == ""); result = fs::RemoveLastPathComponent(path, &removed, 1); UASSERT(result == p("/home/user/minetest/bin/..//worlds")); UASSERT(removed == p("world1")); result = fs::RemoveLastPathComponent(path, &removed, 2); UASSERT(result == p("/home/user/minetest/bin/..")); UASSERT(removed == p("worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 3); UASSERT(result == p("/home/user/minetest/bin")); UASSERT(removed == p("../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 4); UASSERT(result == p("/home/user/minetest")); UASSERT(removed == p("bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 5); UASSERT(result == p("/home/user")); UASSERT(removed == p("minetest/bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 6); UASSERT(result == p("/home")); UASSERT(removed == p("user/minetest/bin/../worlds/world1")); result = fs::RemoveLastPathComponent(path, &removed, 7); #ifdef _WIN32 UASSERT(result == "C:"); #else UASSERT(result == ""); #endif UASSERT(removed == p("home/user/minetest/bin/../worlds/world1")); } void TestFilePath::testRemoveRelativePathComponent() { std::string path, result, removed; path = p("/home/user/minetest/bin"); result = fs::RemoveRelativePathComponents(path); UASSERT(result == path); path = p("/home/user/minetest/bin/../worlds/world1"); result = fs::RemoveRelativePathComponents(path); UASSERT(result == p("/home/user/minetest/worlds/world1")); path = p("/home/user/minetest/bin/../worlds/world1/"); result = fs::RemoveRelativePathComponents(path); UASSERT(result == p("/home/user/minetest/worlds/world1")); path = p("."); result = fs::RemoveRelativePathComponents(path); UASSERT(result == ""); path = p("../a"); result = fs::RemoveRelativePathComponents(path); UASSERT(result == ""); path = p("./subdir/../.."); result = fs::RemoveRelativePathComponents(path); UASSERT(result == ""); path = p("/a/b/c/.././../d/../e/f/g/../h/i/j/../../../.."); result = fs::RemoveRelativePathComponents(path); UASSERT(result == p("/a/e")); }
pgimeno/minetest
src/unittest/test_filepath.cpp
C++
mit
7,928
/* Minetest Copyright (C) 2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "client/gameui.h" class TestGameUI : public TestBase { public: TestGameUI() { TestManager::registerTestModule(this); } const char *getName() { return "TestGameUI"; } void runTests(IGameDef *gamedef); void testInit(); void testFlagSetters(); void testInfoText(); void testStatusText(); }; static TestGameUI g_test_instance; void TestGameUI::runTests(IGameDef *gamedef) { TEST(testInit); TEST(testFlagSetters); TEST(testInfoText); TEST(testStatusText); } void TestGameUI::testInit() { GameUI gui{}; // Ensure flags on GameUI init UASSERT(gui.getFlags().show_chat) UASSERT(gui.getFlags().show_hud) UASSERT(!gui.getFlags().show_minimap) UASSERT(!gui.getFlags().show_profiler_graph) // And after the initFlags init stage gui.initFlags(); UASSERT(gui.getFlags().show_chat) UASSERT(gui.getFlags().show_hud) UASSERT(!gui.getFlags().show_minimap) UASSERT(!gui.getFlags().show_profiler_graph) // @TODO verify if we can create non UI nulldevice to test this function // gui.init(); } void TestGameUI::testFlagSetters() { GameUI gui{}; gui.showMinimap(true); UASSERT(gui.getFlags().show_minimap); gui.showMinimap(false); UASSERT(!gui.getFlags().show_minimap); } void TestGameUI::testStatusText() { GameUI gui{}; gui.showStatusText(L"test status"); UASSERT(gui.m_statustext_time == 0.0f); UASSERT(gui.m_statustext == L"test status"); } void TestGameUI::testInfoText() { GameUI gui{}; gui.setInfoText(L"test info"); UASSERT(gui.m_infotext == L"test info"); }
pgimeno/minetest
src/unittest/test_gameui.cpp
C++
mit
2,313
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <sstream> #include "gamedef.h" #include "inventory.h" class TestInventory : public TestBase { public: TestInventory() { TestManager::registerTestModule(this); } const char *getName() { return "TestInventory"; } void runTests(IGameDef *gamedef); void testSerializeDeserialize(IItemDefManager *idef); static const char *serialized_inventory; static const char *serialized_inventory_2; }; static TestInventory g_test_instance; void TestInventory::runTests(IGameDef *gamedef) { TEST(testSerializeDeserialize, gamedef->getItemDefManager()); } //////////////////////////////////////////////////////////////////////////////// void TestInventory::testSerializeDeserialize(IItemDefManager *idef) { Inventory inv(idef); std::istringstream is(serialized_inventory, std::ios::binary); inv.deSerialize(is); UASSERT(inv.getList("0")); UASSERT(!inv.getList("main")); inv.getList("0")->setName("main"); UASSERT(!inv.getList("0")); UASSERT(inv.getList("main")); UASSERTEQ(u32, inv.getList("main")->getWidth(), 3); inv.getList("main")->setWidth(5); std::ostringstream inv_os(std::ios::binary); inv.serialize(inv_os); UASSERTEQ(std::string, inv_os.str(), serialized_inventory_2); } const char *TestInventory::serialized_inventory = "List 0 32\n" "Width 3\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:cobble 61\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 71\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 99\n" "Item default:cobble 38\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "EndInventoryList\n" "EndInventory\n"; const char *TestInventory::serialized_inventory_2 = "List main 32\n" "Width 5\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:cobble 61\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 71\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Item default:dirt 99\n" "Item default:cobble 38\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "Empty\n" "EndInventoryList\n" "EndInventory\n";
pgimeno/minetest
src/unittest/test_inventory.cpp
C++
mit
3,085
/* Minetest Copyright (C) 2016 sfan5 <sfan5@live.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <string> #include "exceptions.h" #include "client/keycode.h" class TestKeycode : public TestBase { public: TestKeycode() { TestManager::registerTestModule(this); } const char *getName() { return "TestKeycode"; } void runTests(IGameDef *gamedef); void testCreateFromString(); void testCreateFromSKeyInput(); void testCompare(); }; static TestKeycode g_test_instance; void TestKeycode::runTests(IGameDef *gamedef) { TEST(testCreateFromString); TEST(testCreateFromSKeyInput); TEST(testCompare); } //////////////////////////////////////////////////////////////////////////////// #define UASSERTEQ_STR(one, two) UASSERT(strcmp(one, two) == 0) void TestKeycode::testCreateFromString() { KeyPress k; // Character key, from char k = KeyPress("R"); UASSERTEQ_STR(k.sym(), "KEY_KEY_R"); UASSERTCMP(int, >, strlen(k.name()), 0); // should have human description // Character key, from identifier k = KeyPress("KEY_KEY_B"); UASSERTEQ_STR(k.sym(), "KEY_KEY_B"); UASSERTCMP(int, >, strlen(k.name()), 0); // Non-Character key, from identifier k = KeyPress("KEY_UP"); UASSERTEQ_STR(k.sym(), "KEY_UP"); UASSERTCMP(int, >, strlen(k.name()), 0); k = KeyPress("KEY_F6"); UASSERTEQ_STR(k.sym(), "KEY_F6"); UASSERTCMP(int, >, strlen(k.name()), 0); // Irrlicht-unknown key, from char k = KeyPress("/"); UASSERTEQ_STR(k.sym(), "/"); UASSERTCMP(int, >, strlen(k.name()), 0); } void TestKeycode::testCreateFromSKeyInput() { KeyPress k; irr::SEvent::SKeyInput in; // Character key in.Key = irr::KEY_KEY_3; in.Char = L'3'; k = KeyPress(in); UASSERTEQ_STR(k.sym(), "KEY_KEY_3"); // Non-Character key in.Key = irr::KEY_RSHIFT; in.Char = L'\0'; k = KeyPress(in); UASSERTEQ_STR(k.sym(), "KEY_RSHIFT"); // Irrlicht-unknown key in.Key = irr::KEY_KEY_CODES_COUNT; in.Char = L'?'; k = KeyPress(in); UASSERTEQ_STR(k.sym(), "?"); // prefer_character mode in.Key = irr::KEY_COMMA; in.Char = L'G'; k = KeyPress(in, true); UASSERTEQ_STR(k.sym(), "KEY_KEY_G"); } void TestKeycode::testCompare() { // Basic comparison UASSERT(KeyPress("5") == KeyPress("KEY_KEY_5")); UASSERT(!(KeyPress("5") == KeyPress("KEY_NUMPAD_5"))); // Matching char suffices // note: This is a real-world example, Irrlicht maps XK_equal to irr::KEY_PLUS on Linux irr::SEvent::SKeyInput in; in.Key = irr::KEY_PLUS; in.Char = L'='; UASSERT(KeyPress("=") == KeyPress(in)); // Matching keycode suffices irr::SEvent::SKeyInput in2; in.Key = in2.Key = irr::KEY_OEM_CLEAR; in.Char = L'\0'; in2.Char = L';'; UASSERT(KeyPress(in) == KeyPress(in2)); }
pgimeno/minetest
src/unittest/test_keycode.cpp
C++
mit
3,348
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "noise.h" #include "settings.h" #include "mapgen/mapgen_v5.h" #include "util/sha1.h" #include "map_settings_manager.h" class TestMapSettingsManager : public TestBase { public: TestMapSettingsManager() { TestManager::registerTestModule(this); } const char *getName() { return "TestMapSettingsManager"; } void makeUserConfig(Settings *conf); std::string makeMetaFile(bool make_corrupt); void runTests(IGameDef *gamedef); void testMapSettingsManager(); void testMapMetaSaveLoad(); void testMapMetaFailures(); }; static TestMapSettingsManager g_test_instance; void TestMapSettingsManager::runTests(IGameDef *gamedef) { TEST(testMapSettingsManager); TEST(testMapMetaSaveLoad); TEST(testMapMetaFailures); } //////////////////////////////////////////////////////////////////////////////// void check_noise_params(const NoiseParams *np1, const NoiseParams *np2) { UASSERTEQ(float, np1->offset, np2->offset); UASSERTEQ(float, np1->scale, np2->scale); UASSERT(np1->spread == np2->spread); UASSERTEQ(s32, np1->seed, np2->seed); UASSERTEQ(u16, np1->octaves, np2->octaves); UASSERTEQ(float, np1->persist, np2->persist); UASSERTEQ(float, np1->lacunarity, np2->lacunarity); UASSERTEQ(u32, np1->flags, np2->flags); } std::string read_file_to_string(const std::string &filepath) { std::string buf; FILE *f = fopen(filepath.c_str(), "rb"); if (!f) return ""; fseek(f, 0, SEEK_END); long filesize = ftell(f); if (filesize == -1) { fclose(f); return ""; } rewind(f); buf.resize(filesize); UASSERTEQ(size_t, fread(&buf[0], 1, filesize, f), 1); fclose(f); return buf; } void TestMapSettingsManager::makeUserConfig(Settings *conf) { conf->set("mg_name", "v7"); conf->set("seed", "5678"); conf->set("water_level", "20"); conf->set("mgv5_np_factor", "0, 12, (500, 250, 500), 920382, 5, 0.45, 3.0"); conf->set("mgv5_np_height", "0, 15, (500, 250, 500), 841746, 5, 0.5, 3.0"); conf->set("mgv5_np_filler_depth", "20, 1, (150, 150, 150), 261, 4, 0.7, 1.0"); conf->set("mgv5_np_ground", "-43, 40, (80, 80, 80), 983240, 4, 0.55, 2.0"); } std::string TestMapSettingsManager::makeMetaFile(bool make_corrupt) { std::string metafile = getTestTempFile(); const char *metafile_contents = "mg_name = v5\n" "seed = 1234\n" "mg_flags = light\n" "mgv5_np_filler_depth = 20, 1, (150, 150, 150), 261, 4, 0.7, 1.0\n" "mgv5_np_height = 20, 10, (250, 250, 250), 84174, 4, 0.5, 1.0\n"; FILE *f = fopen(metafile.c_str(), "wb"); UASSERT(f != NULL); fputs(metafile_contents, f); if (!make_corrupt) fputs("[end_of_params]\n", f); fclose(f); return metafile; } void TestMapSettingsManager::testMapSettingsManager() { Settings user_settings; makeUserConfig(&user_settings); std::string test_mapmeta_path = makeMetaFile(false); MapSettingsManager mgr(&user_settings, test_mapmeta_path); std::string value; UASSERT(mgr.getMapSetting("mg_name", &value)); UASSERT(value == "v7"); // Pretend we're initializing the ServerMap UASSERT(mgr.loadMapMeta()); // Pretend some scripts are requesting mapgen params UASSERT(mgr.getMapSetting("mg_name", &value)); UASSERT(value == "v5"); UASSERT(mgr.getMapSetting("seed", &value)); UASSERT(value == "1234"); UASSERT(mgr.getMapSetting("water_level", &value)); UASSERT(value == "20"); // Pretend we have some mapgen settings configured from the scripting UASSERT(mgr.setMapSetting("water_level", "15")); UASSERT(mgr.setMapSetting("seed", "02468")); UASSERT(mgr.setMapSetting("mg_flags", "nolight", true)); NoiseParams script_np_filler_depth(0, 100, v3f(200, 100, 200), 261, 4, 0.7, 2.0); NoiseParams script_np_factor(0, 100, v3f(50, 50, 50), 920381, 3, 0.45, 2.0); NoiseParams script_np_height(0, 100, v3f(450, 450, 450), 84174, 4, 0.5, 2.0); NoiseParams meta_np_height(20, 10, v3f(250, 250, 250), 84174, 4, 0.5, 1.0); NoiseParams user_np_ground(-43, 40, v3f(80, 80, 80), 983240, 4, 0.55, 2.0, NOISE_FLAG_EASED); mgr.setMapSettingNoiseParams("mgv5_np_filler_depth", &script_np_filler_depth, true); mgr.setMapSettingNoiseParams("mgv5_np_height", &script_np_height); mgr.setMapSettingNoiseParams("mgv5_np_factor", &script_np_factor); // Now make our Params and see if the values are correctly sourced MapgenParams *params = mgr.makeMapgenParams(); UASSERT(params->mgtype == MAPGEN_V5); UASSERT(params->chunksize == 5); UASSERT(params->water_level == 15); UASSERT(params->seed == 1234); UASSERT((params->flags & MG_LIGHT) == 0); MapgenV5Params *v5params = (MapgenV5Params *)params; check_noise_params(&v5params->np_filler_depth, &script_np_filler_depth); check_noise_params(&v5params->np_factor, &script_np_factor); check_noise_params(&v5params->np_height, &meta_np_height); check_noise_params(&v5params->np_ground, &user_np_ground); UASSERT(mgr.setMapSetting("foobar", "25") == false); // Pretend the ServerMap is shutting down UASSERT(mgr.saveMapMeta()); // Make sure our interface expectations are met UASSERT(mgr.mapgen_params == params); UASSERT(mgr.makeMapgenParams() == params); #if 0 // TODO(paramat or hmmmm): change this to compare the result against a static file // Load the resulting map_meta.txt and make sure it contains what we expect unsigned char expected_contents_hash[20] = { 0x48, 0x3f, 0x88, 0x5a, 0xc0, 0x7a, 0x14, 0x48, 0xa4, 0x71, 0x78, 0x56, 0x95, 0x2d, 0xdc, 0x6a, 0xf7, 0x61, 0x36, 0x5f }; SHA1 ctx; std::string metafile_contents = read_file_to_string(test_mapmeta_path); ctx.addBytes(&metafile_contents[0], metafile_contents.size()); unsigned char *sha1_result = ctx.getDigest(); int resultdiff = memcmp(sha1_result, expected_contents_hash, 20); free(sha1_result); UASSERT(!resultdiff); #endif } void TestMapSettingsManager::testMapMetaSaveLoad() { Settings conf; std::string path = getTestTempDirectory() + DIR_DELIM + "foobar" + DIR_DELIM + "map_meta.txt"; // Create a set of mapgen params and save them to map meta conf.set("seed", "12345"); conf.set("water_level", "5"); MapSettingsManager mgr1(&conf, path); MapgenParams *params1 = mgr1.makeMapgenParams(); UASSERT(params1); UASSERT(mgr1.saveMapMeta()); // Now try loading the map meta to mapgen params conf.set("seed", "67890"); conf.set("water_level", "32"); MapSettingsManager mgr2(&conf, path); UASSERT(mgr2.loadMapMeta()); MapgenParams *params2 = mgr2.makeMapgenParams(); UASSERT(params2); // Check that both results are correct UASSERTEQ(u64, params1->seed, 12345); UASSERTEQ(s16, params1->water_level, 5); UASSERTEQ(u64, params2->seed, 12345); UASSERTEQ(s16, params2->water_level, 5); } void TestMapSettingsManager::testMapMetaFailures() { std::string test_mapmeta_path; Settings conf; // Check to see if it'll fail on a non-existent map meta file test_mapmeta_path = "woobawooba/fgdfg/map_meta.txt"; UASSERT(!fs::PathExists(test_mapmeta_path)); MapSettingsManager mgr1(&conf, test_mapmeta_path); UASSERT(!mgr1.loadMapMeta()); // Check to see if it'll fail on a corrupt map meta file test_mapmeta_path = makeMetaFile(true); UASSERT(fs::PathExists(test_mapmeta_path)); MapSettingsManager mgr2(&conf, test_mapmeta_path); UASSERT(!mgr2.loadMapMeta()); }
pgimeno/minetest
src/unittest/test_map_settings_manager.cpp
C++
mit
7,969
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "gamedef.h" #include "nodedef.h" #include "content_mapnode.h" class TestMapNode : public TestBase { public: TestMapNode() { TestManager::registerTestModule(this); } const char *getName() { return "TestMapNode"; } void runTests(IGameDef *gamedef); void testNodeProperties(const NodeDefManager *nodedef); }; static TestMapNode g_test_instance; void TestMapNode::runTests(IGameDef *gamedef) { TEST(testNodeProperties, gamedef->getNodeDefManager()); } //////////////////////////////////////////////////////////////////////////////// void TestMapNode::testNodeProperties(const NodeDefManager *nodedef) { MapNode n(CONTENT_AIR); UASSERT(n.getContent() == CONTENT_AIR); UASSERT(n.getLight(LIGHTBANK_DAY, nodedef) == 0); UASSERT(n.getLight(LIGHTBANK_NIGHT, nodedef) == 0); // Transparency n.setContent(CONTENT_AIR); UASSERT(nodedef->get(n).light_propagates == true); }
pgimeno/minetest
src/unittest/test_mapnode.cpp
C++
mit
1,695
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "gamedef.h" #include "modchannels.h" class TestModChannels : public TestBase { public: TestModChannels() { TestManager::registerTestModule(this); } const char *getName() { return "TestModChannels"; } void runTests(IGameDef *gamedef); void testJoinChannel(IGameDef *gamedef); void testLeaveChannel(IGameDef *gamedef); void testSendMessageToChannel(IGameDef *gamedef); }; static TestModChannels g_test_instance; void TestModChannels::runTests(IGameDef *gamedef) { TEST(testJoinChannel, gamedef); TEST(testLeaveChannel, gamedef); TEST(testSendMessageToChannel, gamedef); } void TestModChannels::testJoinChannel(IGameDef *gamedef) { // Test join UASSERT(gamedef->joinModChannel("test_join_channel")); // Test join (fail, already join) UASSERT(!gamedef->joinModChannel("test_join_channel")); } void TestModChannels::testLeaveChannel(IGameDef *gamedef) { // Test leave (not joined) UASSERT(!gamedef->leaveModChannel("test_leave_channel")); UASSERT(gamedef->joinModChannel("test_leave_channel")); // Test leave (joined) UASSERT(gamedef->leaveModChannel("test_leave_channel")); } void TestModChannels::testSendMessageToChannel(IGameDef *gamedef) { // Test sendmsg (not joined) UASSERT(!gamedef->sendModChannelMessage( "test_sendmsg_channel", "testmsgchannel")); UASSERT(gamedef->joinModChannel("test_sendmsg_channel")); // Test sendmsg (joined) UASSERT(gamedef->sendModChannelMessage("test_sendmsg_channel", "testmsgchannel")); }
pgimeno/minetest
src/unittest/test_modchannels.cpp
C++
mit
2,273
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <sstream> #include "gamedef.h" #include "nodedef.h" #include "network/networkprotocol.h" class TestNodeDef : public TestBase { public: TestNodeDef() { TestManager::registerTestModule(this); } const char *getName() { return "TestNodeDef"; } void runTests(IGameDef *gamedef); void testContentFeaturesSerialization(); }; static TestNodeDef g_test_instance; void TestNodeDef::runTests(IGameDef *gamedef) { TEST(testContentFeaturesSerialization); } //////////////////////////////////////////////////////////////////////////////// void TestNodeDef::testContentFeaturesSerialization() { ContentFeatures f; f.name = "default:stone"; for (TileDef &tiledef : f.tiledef) tiledef.name = "default_stone.png"; f.is_ground_content = true; std::ostringstream os(std::ios::binary); f.serialize(os, LATEST_PROTOCOL_VERSION); // verbosestream<<"Test ContentFeatures size: "<<os.str().size()<<std::endl; std::istringstream is(os.str(), std::ios::binary); ContentFeatures f2; f2.deSerialize(is); UASSERT(f.walkable == f2.walkable); UASSERT(f.node_box.type == f2.node_box.type); }
pgimeno/minetest
src/unittest/test_nodedef.cpp
C++
mit
1,903
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "util/numeric.h" #include "exceptions.h" #include "gamedef.h" #include "nodedef.h" #include <algorithm> class TestNodeResolver : public TestBase { public: TestNodeResolver() { TestManager::registerTestModule(this); } const char *getName() { return "TestNodeResolver"; } void runTests(IGameDef *gamedef); void testNodeResolving(NodeDefManager *ndef); void testPendingResolveCancellation(NodeDefManager *ndef); void testDirectResolveMethod(NodeDefManager *ndef); void testNoneResolveMethod(NodeDefManager *ndef); }; static TestNodeResolver g_test_instance; void TestNodeResolver::runTests(IGameDef *gamedef) { NodeDefManager *ndef = (NodeDefManager *)gamedef->getNodeDefManager(); ndef->resetNodeResolveState(); TEST(testNodeResolving, ndef); ndef->resetNodeResolveState(); TEST(testPendingResolveCancellation, ndef); } class Foobar : public NodeResolver { public: void resolveNodeNames(); content_t test_nr_node1; content_t test_nr_node2; content_t test_nr_node3; content_t test_nr_node4; content_t test_nr_node5; std::vector<content_t> test_nr_list; std::vector<content_t> test_nr_list_group; std::vector<content_t> test_nr_list_required; std::vector<content_t> test_nr_list_empty; }; class Foobaz : public NodeResolver { public: void resolveNodeNames(); content_t test_content1; content_t test_content2; }; //////////////////////////////////////////////////////////////////////////////// void Foobar::resolveNodeNames() { UASSERT(getIdFromNrBacklog(&test_nr_node1, "", CONTENT_IGNORE) == true); UASSERT(getIdsFromNrBacklog(&test_nr_list) == true); UASSERT(getIdsFromNrBacklog(&test_nr_list_group) == true); UASSERT(getIdsFromNrBacklog(&test_nr_list_required, true, CONTENT_AIR) == false); UASSERT(getIdsFromNrBacklog(&test_nr_list_empty) == true); UASSERT(getIdFromNrBacklog(&test_nr_node2, "", CONTENT_IGNORE) == true); UASSERT(getIdFromNrBacklog(&test_nr_node3, "default:brick", CONTENT_IGNORE) == true); UASSERT(getIdFromNrBacklog(&test_nr_node4, "default:gobbledygook", CONTENT_AIR) == false); UASSERT(getIdFromNrBacklog(&test_nr_node5, "", CONTENT_IGNORE) == false); } void Foobaz::resolveNodeNames() { UASSERT(getIdFromNrBacklog(&test_content1, "", CONTENT_IGNORE) == true); UASSERT(getIdFromNrBacklog(&test_content2, "", CONTENT_IGNORE) == false); } void TestNodeResolver::testNodeResolving(NodeDefManager *ndef) { Foobar foobar; size_t i; foobar.m_nodenames.emplace_back("default:torch"); foobar.m_nodenames.emplace_back("default:dirt_with_grass"); foobar.m_nodenames.emplace_back("default:water"); foobar.m_nodenames.emplace_back("default:abloobloobloo"); foobar.m_nodenames.emplace_back("default:stone"); foobar.m_nodenames.emplace_back("default:shmegoldorf"); foobar.m_nnlistsizes.push_back(5); foobar.m_nodenames.emplace_back("group:liquids"); foobar.m_nnlistsizes.push_back(1); foobar.m_nodenames.emplace_back("default:warf"); foobar.m_nodenames.emplace_back("default:stone"); foobar.m_nodenames.emplace_back("default:bloop"); foobar.m_nnlistsizes.push_back(3); foobar.m_nnlistsizes.push_back(0); foobar.m_nodenames.emplace_back("default:brick"); foobar.m_nodenames.emplace_back("default:desert_stone"); foobar.m_nodenames.emplace_back("default:shnitzle"); ndef->pendNodeResolve(&foobar); UASSERT(foobar.m_ndef == ndef); ndef->setNodeRegistrationStatus(true); ndef->runNodeResolveCallbacks(); // Check that we read single nodes successfully UASSERTEQ(content_t, foobar.test_nr_node1, t_CONTENT_TORCH); UASSERTEQ(content_t, foobar.test_nr_node2, t_CONTENT_BRICK); UASSERTEQ(content_t, foobar.test_nr_node3, t_CONTENT_BRICK); UASSERTEQ(content_t, foobar.test_nr_node4, CONTENT_AIR); UASSERTEQ(content_t, foobar.test_nr_node5, CONTENT_IGNORE); // Check that we read all the regular list items static const content_t expected_test_nr_list[] = { t_CONTENT_GRASS, t_CONTENT_WATER, t_CONTENT_STONE, }; UASSERTEQ(size_t, foobar.test_nr_list.size(), 3); for (i = 0; i != foobar.test_nr_list.size(); i++) UASSERTEQ(content_t, foobar.test_nr_list[i], expected_test_nr_list[i]); // Check that we read all the list items that were from a group entry static const content_t expected_test_nr_list_group[] = { t_CONTENT_WATER, t_CONTENT_LAVA, }; UASSERTEQ(size_t, foobar.test_nr_list_group.size(), 2); for (i = 0; i != foobar.test_nr_list_group.size(); i++) { UASSERT(CONTAINS(foobar.test_nr_list_group, expected_test_nr_list_group[i])); } // Check that we read all the items we're able to in a required list static const content_t expected_test_nr_list_required[] = { CONTENT_AIR, t_CONTENT_STONE, CONTENT_AIR, }; UASSERTEQ(size_t, foobar.test_nr_list_required.size(), 3); for (i = 0; i != foobar.test_nr_list_required.size(); i++) UASSERTEQ(content_t, foobar.test_nr_list_required[i], expected_test_nr_list_required[i]); // Check that the edge case of 0 is successful UASSERTEQ(size_t, foobar.test_nr_list_empty.size(), 0); } void TestNodeResolver::testPendingResolveCancellation(NodeDefManager *ndef) { Foobaz foobaz1; foobaz1.test_content1 = 1234; foobaz1.test_content2 = 5678; foobaz1.m_nodenames.emplace_back("default:dirt_with_grass"); foobaz1.m_nodenames.emplace_back("default:abloobloobloo"); ndef->pendNodeResolve(&foobaz1); Foobaz foobaz2; foobaz2.test_content1 = 1234; foobaz2.test_content2 = 5678; foobaz2.m_nodenames.emplace_back("default:dirt_with_grass"); foobaz2.m_nodenames.emplace_back("default:abloobloobloo"); ndef->pendNodeResolve(&foobaz2); ndef->cancelNodeResolveCallback(&foobaz1); ndef->setNodeRegistrationStatus(true); ndef->runNodeResolveCallbacks(); UASSERT(foobaz1.test_content1 == 1234); UASSERT(foobaz1.test_content2 == 5678); UASSERT(foobaz2.test_content1 == t_CONTENT_GRASS); UASSERT(foobaz2.test_content2 == CONTENT_IGNORE); }
pgimeno/minetest
src/unittest/test_noderesolver.cpp
C++
mit
6,653
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <cmath> #include "exceptions.h" #include "noise.h" class TestNoise : public TestBase { public: TestNoise() { TestManager::registerTestModule(this); } const char *getName() { return "TestNoise"; } void runTests(IGameDef *gamedef); void testNoise2dPoint(); void testNoise2dBulk(); void testNoise3dPoint(); void testNoise3dBulk(); void testNoiseInvalidParams(); static const float expected_2d_results[10 * 10]; static const float expected_3d_results[10 * 10 * 10]; }; static TestNoise g_test_instance; void TestNoise::runTests(IGameDef *gamedef) { TEST(testNoise2dPoint); TEST(testNoise2dBulk); TEST(testNoise3dPoint); TEST(testNoise3dBulk); TEST(testNoiseInvalidParams); } //////////////////////////////////////////////////////////////////////////////// void TestNoise::testNoise2dPoint() { NoiseParams np_normal(20, 40, v3f(50, 50, 50), 9, 5, 0.6, 2.0); u32 i = 0; for (u32 y = 0; y != 10; y++) for (u32 x = 0; x != 10; x++, i++) { float actual = NoisePerlin2D(&np_normal, x, y, 1337); float expected = expected_2d_results[i]; UASSERT(std::fabs(actual - expected) <= 0.00001); } } void TestNoise::testNoise2dBulk() { NoiseParams np_normal(20, 40, v3f(50, 50, 50), 9, 5, 0.6, 2.0); Noise noise_normal_2d(&np_normal, 1337, 10, 10); float *noisevals = noise_normal_2d.perlinMap2D(0, 0, NULL); for (u32 i = 0; i != 10 * 10; i++) { float actual = noisevals[i]; float expected = expected_2d_results[i]; UASSERT(std::fabs(actual - expected) <= 0.00001); } } void TestNoise::testNoise3dPoint() { NoiseParams np_normal(20, 40, v3f(50, 50, 50), 9, 5, 0.6, 2.0); u32 i = 0; for (u32 z = 0; z != 10; z++) for (u32 y = 0; y != 10; y++) for (u32 x = 0; x != 10; x++, i++) { float actual = NoisePerlin3D(&np_normal, x, y, z, 1337); float expected = expected_3d_results[i]; UASSERT(std::fabs(actual - expected) <= 0.00001); } } void TestNoise::testNoise3dBulk() { NoiseParams np_normal(20, 40, v3f(50, 50, 50), 9, 5, 0.6, 2.0); Noise noise_normal_3d(&np_normal, 1337, 10, 10, 10); float *noisevals = noise_normal_3d.perlinMap3D(0, 0, 0, NULL); for (u32 i = 0; i != 10 * 10 * 10; i++) { float actual = noisevals[i]; float expected = expected_3d_results[i]; UASSERT(std::fabs(actual - expected) <= 0.00001); } } void TestNoise::testNoiseInvalidParams() { bool exception_thrown = false; try { NoiseParams np_highmem(4, 70, v3f(1, 1, 1), 5, 60, 0.7, 10.0); Noise noise_highmem_3d(&np_highmem, 1337, 200, 200, 200); noise_highmem_3d.perlinMap3D(0, 0, 0, NULL); } catch (InvalidNoiseParamsException &) { exception_thrown = true; } UASSERT(exception_thrown); } const float TestNoise::expected_2d_results[10 * 10] = { 19.11726, 18.49626, 16.48476, 15.02135, 14.75713, 16.26008, 17.54822, 18.06860, 18.57016, 18.48407, 18.49649, 17.89160, 15.94162, 14.54901, 14.31298, 15.72643, 16.94669, 17.55494, 18.58796, 18.87925, 16.08101, 15.53764, 13.83844, 12.77139, 12.73648, 13.95632, 14.97904, 15.81829, 18.37694, 19.73759, 13.19182, 12.71924, 11.34560, 10.78025, 11.18980, 12.52303, 13.45012, 14.30001, 17.43298, 19.15244, 10.93217, 10.48625, 9.30923, 9.18632, 10.16251, 12.11264, 13.19697, 13.80801, 16.39567, 17.66203, 10.40222, 9.86070, 8.47223, 8.45471, 10.04780, 13.54730, 15.33709, 15.48503, 16.46177, 16.52508, 10.80333, 10.19045, 8.59420, 8.47646, 10.22676, 14.43173, 16.48353, 16.24859, 16.20863, 15.52847, 11.01179, 10.45209, 8.98678, 8.83986, 10.43004, 14.46054, 16.29387, 15.73521, 15.01744, 13.85542, 10.55201, 10.33375, 9.85102, 10.07821, 11.58235, 15.62046, 17.35505, 16.13181, 12.66011, 9.51853, 11.50994, 11.54074, 11.77989, 12.29790, 13.76139, 17.81982, 19.49008, 17.79470, 12.34344, 7.78363, }; const float TestNoise::expected_3d_results[10 * 10 * 10] = { 19.11726, 18.01059, 16.90392, 15.79725, 16.37154, 17.18597, 18.00040, 18.33467, 18.50889, 18.68311, 17.85386, 16.90585, 15.95785, 15.00985, 15.61132, 16.43415, 17.25697, 17.95415, 18.60942, 19.26471, 16.59046, 15.80112, 15.01178, 14.22244, 14.85110, 15.68232, 16.51355, 17.57361, 18.70996, 19.84631, 15.32705, 14.69638, 14.06571, 13.43504, 14.09087, 14.93050, 15.77012, 17.19309, 18.81050, 20.42790, 15.06729, 14.45855, 13.84981, 13.24107, 14.39364, 15.79782, 17.20201, 18.42640, 19.59085, 20.75530, 14.95090, 14.34456, 13.73821, 13.13187, 14.84825, 16.89645, 18.94465, 19.89025, 20.46832, 21.04639, 14.83452, 14.23057, 13.62662, 13.02267, 15.30287, 17.99508, 20.68730, 21.35411, 21.34580, 21.33748, 15.39817, 15.03590, 14.67364, 14.31137, 16.78242, 19.65824, 22.53405, 22.54626, 21.60395, 20.66164, 16.18850, 16.14768, 16.10686, 16.06603, 18.60362, 21.50956, 24.41549, 23.64784, 21.65566, 19.66349, 16.97884, 17.25946, 17.54008, 17.82069, 20.42482, 23.36088, 26.29694, 24.74942, 21.70738, 18.66534, 18.78506, 17.51834, 16.25162, 14.98489, 15.14217, 15.50287, 15.86357, 16.40597, 17.00895, 17.61193, 18.20160, 16.98795, 15.77430, 14.56065, 14.85059, 15.35533, 15.86007, 16.63399, 17.49763, 18.36128, 17.61814, 16.45757, 15.29699, 14.13641, 14.55902, 15.20779, 15.85657, 16.86200, 17.98632, 19.11064, 17.03468, 15.92718, 14.81968, 13.71218, 14.26744, 15.06026, 15.85306, 17.09001, 18.47501, 19.86000, 16.67870, 15.86256, 15.04641, 14.23026, 15.31397, 16.66909, 18.02420, 18.89042, 19.59369, 20.29695, 16.35522, 15.86447, 15.37372, 14.88297, 16.55165, 18.52883, 20.50600, 20.91547, 20.80237, 20.68927, 16.03174, 15.86639, 15.70103, 15.53568, 17.78933, 20.38857, 22.98780, 22.94051, 22.01105, 21.08159, 16.42434, 16.61407, 16.80381, 16.99355, 19.16133, 21.61169, 24.06204, 23.65252, 22.28970, 20.92689, 17.05562, 17.61035, 18.16508, 18.71981, 20.57809, 22.62260, 24.66711, 23.92686, 22.25835, 20.58984, 17.68691, 18.60663, 19.52635, 20.44607, 21.99486, 23.63352, 25.27217, 24.20119, 22.22699, 20.25279, 18.45285, 17.02608, 15.59931, 14.17254, 13.91279, 13.81976, 13.72674, 14.47727, 15.50900, 16.54073, 18.54934, 17.07005, 15.59076, 14.11146, 14.08987, 14.27651, 14.46316, 15.31383, 16.38584, 17.45785, 18.64582, 17.11401, 15.58220, 14.05039, 14.26694, 14.73326, 15.19958, 16.15038, 17.26268, 18.37498, 18.74231, 17.15798, 15.57364, 13.98932, 14.44402, 15.19001, 15.93600, 16.98694, 18.13952, 19.29210, 18.29012, 17.26656, 16.24301, 15.21946, 16.23430, 17.54035, 18.84639, 19.35445, 19.59653, 19.83860, 17.75954, 17.38438, 17.00923, 16.63407, 18.25505, 20.16120, 22.06734, 21.94068, 21.13642, 20.33215, 17.22896, 17.50220, 17.77544, 18.04868, 20.27580, 22.78205, 25.28829, 24.52691, 22.67631, 20.82571, 17.45050, 18.19224, 18.93398, 19.67573, 21.54024, 23.56514, 25.59004, 24.75878, 22.97546, 21.19213, 17.92274, 19.07302, 20.22330, 21.37358, 22.55256, 23.73565, 24.91873, 24.20587, 22.86103, 21.51619, 18.39499, 19.95381, 21.51263, 23.07145, 23.56490, 23.90615, 24.24741, 23.65296, 22.74660, 21.84024, 18.12065, 16.53382, 14.94700, 13.36018, 12.68341, 12.13666, 11.58990, 12.54858, 14.00906, 15.46955, 18.89708, 17.15214, 15.40721, 13.66227, 13.32914, 13.19769, 13.06625, 13.99367, 15.27405, 16.55443, 19.67351, 17.77046, 15.86741, 13.96436, 13.97486, 14.25873, 14.54260, 15.43877, 16.53904, 17.63931, 20.44994, 18.38877, 16.32761, 14.26645, 14.62059, 15.31977, 16.01895, 16.88387, 17.80403, 18.72419, 19.90153, 18.67057, 17.43962, 16.20866, 17.15464, 18.41161, 19.66858, 19.81848, 19.59936, 19.38024, 19.16386, 18.90429, 18.64473, 18.38517, 19.95845, 21.79357, 23.62868, 22.96589, 21.47046, 19.97503, 18.42618, 19.13802, 19.84985, 20.56168, 22.76226, 25.17553, 27.58879, 26.11330, 23.34156, 20.56982, 18.47667, 19.77041, 21.06416, 22.35790, 23.91914, 25.51859, 27.11804, 25.86504, 23.66121, 21.45738, 18.78986, 20.53570, 22.28153, 24.02736, 24.52704, 24.84869, 25.17035, 24.48488, 23.46371, 22.44254, 19.10306, 21.30098, 23.49890, 25.69682, 25.13494, 24.17879, 23.22265, 23.10473, 23.26621, 23.42769, 17.93453, 16.72707, 15.51962, 14.31216, 12.96039, 11.58800, 10.21561, 11.29675, 13.19573, 15.09471, 18.05853, 16.85308, 15.64762, 14.44216, 13.72634, 13.08047, 12.43459, 13.48912, 15.11045, 16.73179, 18.18253, 16.97908, 15.77562, 14.57217, 14.49229, 14.57293, 14.65357, 15.68150, 17.02518, 18.36887, 18.30654, 17.10508, 15.90363, 14.70217, 15.25825, 16.06540, 16.87255, 17.87387, 18.93991, 20.00595, 17.54117, 17.32369, 17.10622, 16.88875, 18.07494, 19.46166, 20.84837, 21.12988, 21.04298, 20.95609, 16.64874, 17.55554, 18.46234, 19.36913, 21.18461, 23.12989, 25.07517, 24.53784, 23.17297, 21.80810, 15.75632, 17.78738, 19.81845, 21.84951, 24.29427, 26.79812, 29.30198, 27.94580, 25.30295, 22.66010, 15.98046, 18.43027, 20.88008, 23.32989, 25.21976, 27.02964, 28.83951, 27.75863, 25.71416, 23.66970, 16.57679, 19.21017, 21.84355, 24.47693, 25.41719, 26.11557, 26.81396, 26.37308, 25.55245, 24.73182, 17.17313, 19.99008, 22.80702, 25.62397, 25.61462, 25.20151, 24.78840, 24.98753, 25.39074, 25.79395, 17.76927, 17.01824, 16.26722, 15.51620, 13.45256, 11.20141, 8.95025, 10.14162, 12.48049, 14.81936, 17.05051, 16.49955, 15.94860, 15.39764, 14.28896, 13.10061, 11.91225, 13.10109, 15.08232, 17.06355, 16.33175, 15.98086, 15.62998, 15.27909, 15.12537, 14.99981, 14.87425, 16.06056, 17.68415, 19.30775, 15.61299, 15.46217, 15.31136, 15.16054, 15.96177, 16.89901, 17.83625, 19.02003, 20.28599, 21.55194, 14.61341, 15.58383, 16.55426, 17.52469, 18.99524, 20.53725, 22.07925, 22.56233, 22.69243, 22.82254, 13.57371, 15.79697, 18.02024, 20.24351, 22.34258, 24.42392, 26.50526, 26.18790, 25.07097, 23.95404, 12.53401, 16.01011, 19.48622, 22.96232, 25.68993, 28.31060, 30.93126, 29.81347, 27.44951, 25.08555, 12.98106, 16.67323, 20.36540, 24.05756, 26.36633, 28.47748, 30.58862, 29.76471, 27.96244, 26.16016, 13.92370, 17.48634, 21.04897, 24.61161, 26.15244, 27.40443, 28.65643, 28.49117, 27.85349, 27.21581, 14.86633, 18.29944, 21.73255, 25.16566, 25.93854, 26.33138, 26.72423, 27.21763, 27.74455, 28.27147, 17.60401, 17.30942, 17.01482, 16.72023, 13.94473, 10.81481, 7.68490, 8.98648, 11.76524, 14.54400, 16.04249, 16.14603, 16.24958, 16.35312, 14.85158, 13.12075, 11.38991, 12.71305, 15.05418, 17.39531, 14.48097, 14.98265, 15.48433, 15.98602, 15.75844, 15.42668, 15.09493, 16.43962, 18.34312, 20.24663, 12.91945, 13.81927, 14.71909, 15.61891, 16.66530, 17.73262, 18.79995, 20.16619, 21.63206, 23.09794, 11.68565, 13.84398, 16.00230, 18.16062, 19.91554, 21.61284, 23.31013, 23.99478, 24.34188, 24.68898, 10.49868, 14.03841, 17.57814, 21.11788, 23.50056, 25.71795, 27.93534, 27.83796, 26.96897, 26.09999, 9.31170, 14.23284, 19.15399, 24.07513, 27.08558, 29.82307, 32.56055, 31.68113, 29.59606, 27.51099, 9.98166, 14.91619, 19.85071, 24.78524, 27.51291, 29.92532, 32.33773, 31.77077, 30.21070, 28.65063, 11.27060, 15.76250, 20.25440, 24.74629, 26.88768, 28.69329, 30.49889, 30.60925, 30.15453, 29.69981, 12.55955, 16.60881, 20.65808, 24.70735, 26.26245, 27.46126, 28.66005, 29.44773, 30.09835, 30.74898, 15.20134, 15.53016, 15.85898, 16.18780, 13.53087, 10.44740, 7.36393, 8.95806, 12.11139, 15.26472, 13.87432, 14.52378, 15.17325, 15.82272, 14.49093, 12.87611, 11.26130, 12.73342, 15.23453, 17.73563, 12.54730, 13.51741, 14.48752, 15.45763, 15.45100, 15.30483, 15.15867, 16.50878, 18.35766, 20.20654, 11.22027, 12.51103, 13.80179, 15.09254, 16.41106, 17.73355, 19.05603, 20.28415, 21.48080, 22.67745, 10.27070, 12.53633, 14.80195, 17.06758, 19.04654, 20.98454, 22.92254, 23.63840, 23.94687, 24.25534, 9.37505, 12.70901, 16.04297, 19.37693, 21.92136, 24.35300, 26.78465, 26.93249, 26.31907, 25.70565, 8.47939, 12.88168, 17.28398, 21.68627, 24.79618, 27.72146, 30.64674, 30.22658, 28.69127, 27.15597, 9.77979, 13.97583, 18.17186, 22.36790, 25.18828, 27.81215, 30.43601, 30.34293, 29.34420, 28.34548, 11.81220, 15.37712, 18.94204, 22.50695, 24.75282, 26.81024, 28.86766, 29.40003, 29.42404, 29.44806, 13.84461, 16.77841, 19.71221, 22.64601, 24.31735, 25.80833, 27.29932, 28.45713, 29.50388, 30.55064, 12.05287, 13.06077, 14.06866, 15.07656, 12.81500, 10.08638, 7.35776, 9.30520, 12.81134, 16.31747, 11.31943, 12.47863, 13.63782, 14.79702, 13.82253, 12.54323, 11.26392, 12.88993, 15.48436, 18.07880, 10.58600, 11.89649, 13.20698, 14.51747, 14.83005, 15.00007, 15.17009, 16.47465, 18.15739, 19.84013, 9.85256, 11.31435, 12.77614, 14.23793, 15.83757, 17.45691, 19.07625, 20.05937, 20.83042, 21.60147, 9.36002, 11.37275, 13.38548, 15.39822, 17.58109, 19.78828, 21.99546, 22.68573, 22.87036, 23.05500, 8.90189, 11.52266, 14.14343, 16.76420, 19.42976, 22.10172, 24.77368, 25.17519, 24.81987, 24.46455, 8.44375, 11.67256, 14.90137, 18.13018, 21.27843, 24.41516, 27.55190, 27.66464, 26.76937, 25.87411, 10.51042, 13.30769, 16.10496, 18.90222, 21.70659, 24.51197, 27.31734, 27.77045, 27.43945, 27.10846, 13.41869, 15.43789, 17.45709, 19.47628, 21.66124, 23.86989, 26.07853, 27.08170, 27.68305, 28.28440, 16.32697, 17.56809, 18.80922, 20.05033, 21.61590, 23.22781, 24.83972, 26.39296, 27.92665, 29.46033, 8.90439, 10.59137, 12.27835, 13.96532, 12.09914, 9.72536, 7.35159, 9.65235, 13.51128, 17.37022, 8.76455, 10.43347, 12.10239, 13.77132, 13.15412, 12.21033, 11.26655, 13.04643, 15.73420, 18.42198, 8.62470, 10.27557, 11.92644, 13.57731, 14.20910, 14.69531, 15.18151, 16.44051, 17.95712, 19.47373, 8.48485, 10.11767, 11.75049, 13.38331, 15.26408, 17.18027, 19.09647, 19.83460, 20.18004, 20.52548, 8.44933, 10.20917, 11.96901, 13.72885, 16.11565, 18.59202, 21.06838, 21.73307, 21.79386, 21.85465, 8.42872, 10.33631, 12.24389, 14.15147, 16.93816, 19.85044, 22.76272, 23.41788, 23.32067, 23.22346, 8.40812, 10.46344, 12.51877, 14.57409, 17.76068, 21.10886, 24.45705, 25.10269, 24.84748, 24.59226, 11.24106, 12.63955, 14.03805, 15.43654, 18.22489, 21.21178, 24.19868, 25.19796, 25.53469, 25.87143, 15.02519, 15.49866, 15.97213, 16.44560, 18.56967, 20.92953, 23.28940, 24.76337, 25.94205, 27.12073, 18.80933, 18.35777, 17.90622, 17.45466, 18.91445, 20.64729, 22.38013, 24.32880, 26.34941, 28.37003, };
pgimeno/minetest
src/unittest/test_noise.cpp
C++
mit
14,738
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "exceptions.h" #include "objdef.h" class TestObjDef : public TestBase { public: TestObjDef() { TestManager::registerTestModule(this); } const char *getName() { return "TestObjDef"; } void runTests(IGameDef *gamedef); void testHandles(); void testAddGetSetClear(); }; static TestObjDef g_test_instance; void TestObjDef::runTests(IGameDef *gamedef) { TEST(testHandles); TEST(testAddGetSetClear); } //////////////////////////////////////////////////////////////////////////////// void TestObjDef::testHandles() { u32 uid = 0; u32 index = 0; ObjDefType type = OBJDEF_GENERIC; ObjDefHandle handle = ObjDefManager::createHandle(9530, OBJDEF_ORE, 47); UASSERTEQ(ObjDefHandle, 0xAF507B55, handle); UASSERT(ObjDefManager::decodeHandle(handle, &index, &type, &uid)); UASSERTEQ(u32, 9530, index); UASSERTEQ(u32, 47, uid); UASSERTEQ(ObjDefHandle, OBJDEF_ORE, type); } void TestObjDef::testAddGetSetClear() { ObjDefManager testmgr(NULL, OBJDEF_GENERIC); ObjDefHandle hObj0, hObj1, hObj2, hObj3; ObjDef *obj0, *obj1, *obj2, *obj3; UASSERTEQ(ObjDefType, testmgr.getType(), OBJDEF_GENERIC); obj0 = new ObjDef; obj0->name = "foobar"; hObj0 = testmgr.add(obj0); UASSERT(hObj0 != OBJDEF_INVALID_HANDLE); UASSERTEQ(u32, obj0->index, 0); obj1 = new ObjDef; obj1->name = "FooBaz"; hObj1 = testmgr.add(obj1); UASSERT(hObj1 != OBJDEF_INVALID_HANDLE); UASSERTEQ(u32, obj1->index, 1); obj2 = new ObjDef; obj2->name = "asdf"; hObj2 = testmgr.add(obj2); UASSERT(hObj2 != OBJDEF_INVALID_HANDLE); UASSERTEQ(u32, obj2->index, 2); obj3 = new ObjDef; obj3->name = "foobaz"; hObj3 = testmgr.add(obj3); UASSERT(hObj3 == OBJDEF_INVALID_HANDLE); UASSERTEQ(size_t, testmgr.getNumObjects(), 3); UASSERT(testmgr.get(hObj0) == obj0); UASSERT(testmgr.getByName("FOOBAZ") == obj1); UASSERT(testmgr.set(hObj0, obj3) == obj0); UASSERT(testmgr.get(hObj0) == obj3); delete obj0; testmgr.clear(); UASSERTEQ(size_t, testmgr.getNumObjects(), 0); }
pgimeno/minetest
src/unittest/test_objdef.cpp
C++
mit
2,782
/* Minetest Copyright (C) 2010-2016 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "exceptions.h" #include "remoteplayer.h" #include "content_sao.h" #include "server.h" class TestPlayer : public TestBase { public: TestPlayer() { TestManager::registerTestModule(this); } const char *getName() { return "TestPlayer"; } void runTests(IGameDef *gamedef); }; static TestPlayer g_test_instance; void TestPlayer::runTests(IGameDef *gamedef) { }
pgimeno/minetest
src/unittest/test_player.cpp
C++
mit
1,184
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "profiler.h" class TestProfiler : public TestBase { public: TestProfiler() { TestManager::registerTestModule(this); } const char *getName() { return "TestProfiler"; } void runTests(IGameDef *gamedef); void testProfilerAverage(); }; static TestProfiler g_test_instance; void TestProfiler::runTests(IGameDef *gamedef) { TEST(testProfilerAverage); } //////////////////////////////////////////////////////////////////////////////// void TestProfiler::testProfilerAverage() { Profiler p; p.avg("Test1", 1.f); UASSERT(p.getValue("Test1") == 1.f); p.avg("Test1", 2.f); UASSERT(p.getValue("Test1") == 1.5f); p.avg("Test1", 3.f); UASSERT(p.getValue("Test1") == 2.f); p.avg("Test1", 486.f); UASSERT(p.getValue("Test1") == 123.f); p.avg("Test1", 8); UASSERT(p.getValue("Test1") == 100.f); p.avg("Test1", 700); UASSERT(p.getValue("Test1") == 200.f); p.avg("Test1", 10000); UASSERT(p.getValue("Test1") == 1600.f); p.avg("Test2", 123.56); p.avg("Test2", 123.58); UASSERT(p.getValue("Test2") == 123.57f); }
pgimeno/minetest
src/unittest/test_profiler.cpp
C++
mit
1,844
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <cmath> #include "util/numeric.h" #include "exceptions.h" #include "noise.h" class TestRandom : public TestBase { public: TestRandom() { TestManager::registerTestModule(this); } const char *getName() { return "TestRandom"; } void runTests(IGameDef *gamedef); void testPseudoRandom(); void testPseudoRandomRange(); void testPcgRandom(); void testPcgRandomRange(); void testPcgRandomBytes(); void testPcgRandomNormalDist(); static const int expected_pseudorandom_results[256]; static const u32 expected_pcgrandom_results[256]; static const u8 expected_pcgrandom_bytes_result[24]; static const u8 expected_pcgrandom_bytes_result2[24]; }; static TestRandom g_test_instance; void TestRandom::runTests(IGameDef *gamedef) { TEST(testPseudoRandom); TEST(testPseudoRandomRange); TEST(testPcgRandom); TEST(testPcgRandomRange); TEST(testPcgRandomBytes); TEST(testPcgRandomNormalDist); } //////////////////////////////////////////////////////////////////////////////// void TestRandom::testPseudoRandom() { PseudoRandom pr(814538); for (u32 i = 0; i != 256; i++) UASSERTEQ(int, pr.next(), expected_pseudorandom_results[i]); } void TestRandom::testPseudoRandomRange() { PseudoRandom pr((int)time(NULL)); EXCEPTION_CHECK(PrngException, pr.range(2000, 6000)); EXCEPTION_CHECK(PrngException, pr.range(5, 1)); for (u32 i = 0; i != 32768; i++) { int min = (pr.next() % 3000) - 500; int max = (pr.next() % 3000) - 500; if (min > max) SWAP(int, min, max); int randval = pr.range(min, max); UASSERT(randval >= min); UASSERT(randval <= max); } } void TestRandom::testPcgRandom() { PcgRandom pr(814538, 998877); for (u32 i = 0; i != 256; i++) UASSERTEQ(u32, pr.next(), expected_pcgrandom_results[i]); } void TestRandom::testPcgRandomRange() { PcgRandom pr((int)time(NULL)); EXCEPTION_CHECK(PrngException, pr.range(5, 1)); // Regression test for bug 3027 pr.range(pr.RANDOM_MIN, pr.RANDOM_MAX); for (u32 i = 0; i != 32768; i++) { int min = (pr.next() % 3000) - 500; int max = (pr.next() % 3000) - 500; if (min > max) SWAP(int, min, max); int randval = pr.range(min, max); UASSERT(randval >= min); UASSERT(randval <= max); } } void TestRandom::testPcgRandomBytes() { char buf[32]; PcgRandom r(1538, 877); memset(buf, 0, sizeof(buf)); r.bytes(buf + 5, 23); UASSERT(memcmp(buf + 5, expected_pcgrandom_bytes_result, sizeof(expected_pcgrandom_bytes_result)) == 0); memset(buf, 0, sizeof(buf)); r.bytes(buf, 17); UASSERT(memcmp(buf, expected_pcgrandom_bytes_result2, sizeof(expected_pcgrandom_bytes_result2)) == 0); } void TestRandom::testPcgRandomNormalDist() { static const int max = 120; static const int min = -120; static const int num_trials = 20; static const u32 num_samples = 61000; s32 bins[max - min + 1]; memset(bins, 0, sizeof(bins)); PcgRandom r(486179 + (int)time(NULL)); for (u32 i = 0; i != num_samples; i++) { s32 randval = r.randNormalDist(min, max, num_trials); UASSERT(randval <= max); UASSERT(randval >= min); bins[randval - min]++; } // Note that here we divide variance by the number of trials; // this is because variance is a biased estimator. int range = (max - min + 1); float mean = (max + min) / 2; float variance = ((range * range - 1) / 12) / num_trials; float stddev = std::sqrt(variance); static const float prediction_intervals[] = { 0.68269f, // 1.0 0.86639f, // 1.5 0.95450f, // 2.0 0.98758f, // 2.5 0.99730f, // 3.0 }; //// Simple normality test using the 68-95-99.7% rule for (u32 i = 0; i != ARRLEN(prediction_intervals); i++) { float deviations = i / 2.f + 1.f; int lbound = myround(mean - deviations * stddev); int ubound = myround(mean + deviations * stddev); UASSERT(lbound >= min); UASSERT(ubound <= max); int accum = 0; for (int j = lbound; j != ubound; j++) accum += bins[j - min]; float actual = (float)accum / num_samples; UASSERT(std::fabs(actual - prediction_intervals[i]) < 0.02f); } } const int TestRandom::expected_pseudorandom_results[256] = { 0x02fa, 0x60d5, 0x6c10, 0x606b, 0x098b, 0x5f1e, 0x4f56, 0x3fbd, 0x77af, 0x4fe9, 0x419a, 0x6fe1, 0x177b, 0x6858, 0x36f8, 0x6d83, 0x14fc, 0x2d62, 0x1077, 0x23e2, 0x041b, 0x7a7e, 0x5b52, 0x215d, 0x682b, 0x4716, 0x47e3, 0x08c0, 0x1952, 0x56ae, 0x146d, 0x4b4f, 0x239f, 0x3fd0, 0x6794, 0x7796, 0x7be2, 0x75b7, 0x5691, 0x28ee, 0x2656, 0x40c0, 0x133c, 0x63cd, 0x2aeb, 0x518f, 0x7dbc, 0x6ad8, 0x736e, 0x5b05, 0x160b, 0x589f, 0x6f64, 0x5edc, 0x092c, 0x0a39, 0x199e, 0x1927, 0x562b, 0x2689, 0x3ba3, 0x366f, 0x46da, 0x4e49, 0x0abb, 0x40a1, 0x3846, 0x40db, 0x7adb, 0x6ec1, 0x6efa, 0x01cc, 0x6335, 0x4352, 0x72fb, 0x4b2d, 0x509a, 0x257e, 0x2f7d, 0x5891, 0x2195, 0x6107, 0x5269, 0x56e3, 0x4849, 0x38f7, 0x2791, 0x04f2, 0x4e05, 0x78ff, 0x6bae, 0x50b3, 0x74ad, 0x31af, 0x531e, 0x7d56, 0x11c9, 0x0b5e, 0x405e, 0x1e15, 0x7f6a, 0x5bd3, 0x6649, 0x71b4, 0x3ec2, 0x6ab4, 0x520e, 0x6ad6, 0x287e, 0x10b8, 0x18f2, 0x7107, 0x46ea, 0x1d85, 0x25cc, 0x2689, 0x35c1, 0x3065, 0x6237, 0x3edd, 0x23d9, 0x6fb5, 0x37a1, 0x3211, 0x526a, 0x4b09, 0x23f1, 0x58cc, 0x2e42, 0x341f, 0x5e16, 0x3d1a, 0x5e8c, 0x7a82, 0x4635, 0x2bf8, 0x6577, 0x3603, 0x1daf, 0x539f, 0x2e91, 0x6bd8, 0x42d3, 0x7a93, 0x26e3, 0x5a91, 0x6c67, 0x1b66, 0x3ac7, 0x18bf, 0x20d8, 0x7153, 0x558d, 0x7262, 0x653d, 0x417d, 0x3ed3, 0x3117, 0x600d, 0x6d04, 0x719c, 0x3afd, 0x6ba5, 0x17c5, 0x4935, 0x346c, 0x5479, 0x6ff6, 0x1fcc, 0x1054, 0x3f14, 0x6266, 0x3acc, 0x3b77, 0x71d8, 0x478b, 0x20fa, 0x4e46, 0x7e77, 0x5554, 0x3652, 0x719c, 0x072b, 0x61ad, 0x399f, 0x621d, 0x1bba, 0x41d0, 0x7fdc, 0x3e6c, 0x6a2a, 0x5253, 0x094e, 0x0c10, 0x3f43, 0x73eb, 0x4c5f, 0x1f23, 0x12c9, 0x0902, 0x5238, 0x50c0, 0x1b77, 0x3ffd, 0x0124, 0x302a, 0x26b9, 0x3648, 0x30a6, 0x1abc, 0x3031, 0x4029, 0x6358, 0x6696, 0x74e8, 0x6142, 0x4284, 0x0c00, 0x7e50, 0x41e3, 0x3782, 0x79a5, 0x60fe, 0x2d15, 0x3ed2, 0x7f70, 0x2b27, 0x6366, 0x5100, 0x7c44, 0x3ee0, 0x4e76, 0x7d34, 0x3a60, 0x140e, 0x613d, 0x1193, 0x268d, 0x1e2f, 0x3123, 0x6d61, 0x4e0b, 0x51ce, 0x13bf, 0x58d4, 0x4f43, 0x05c6, 0x4d6a, 0x7eb5, 0x2921, 0x2c36, 0x1c89, 0x63b9, 0x1555, 0x1f41, 0x2d9f, }; const u32 TestRandom::expected_pcgrandom_results[256] = { 0x48c593f8, 0x054f59f5, 0x0d062dc1, 0x23852a23, 0x7fbbc97b, 0x1f9f141e, 0x364e6ed8, 0x995bba58, 0xc9307dc0, 0x73fb34c4, 0xcd8de88d, 0x52e8ce08, 0x1c4a78e4, 0x25c0882e, 0x8a82e2e0, 0xe3bc3311, 0xb8068d42, 0x73186110, 0x19988df4, 0x69bd970b, 0x7214728c, 0x0aee320c, 0x2a5a536c, 0xaf48d715, 0x00bce504, 0xd2b8f548, 0x520df366, 0x96d8fff5, 0xa1bb510b, 0x63477049, 0xb85990b7, 0x7e090689, 0x275fb468, 0x50206257, 0x8bab4f8a, 0x0d6823db, 0x63faeaac, 0x2d92deeb, 0x2ba78024, 0x0d30f631, 0x338923a0, 0xd07248d8, 0xa5db62d3, 0xddba8af6, 0x0ad454e9, 0x6f0fd13a, 0xbbfde2bf, 0x91188009, 0x966b394d, 0xbb9d2012, 0x7e6926cb, 0x95183860, 0x5ff4c59b, 0x035f628a, 0xb67085ef, 0x33867e23, 0x68d1b887, 0x2e3298d7, 0x84fd0650, 0x8bc91141, 0x6fcb0452, 0x2836fee9, 0x2e83c0a3, 0xf1bafdc5, 0x9ff77777, 0xfdfbba87, 0x527aebeb, 0x423e5248, 0xd1756490, 0xe41148fa, 0x3361f7b4, 0xa2824f23, 0xf4e08072, 0xc50442be, 0x35adcc21, 0x36be153c, 0xc7709012, 0xf0eeb9f2, 0x3d73114e, 0x1c1574ee, 0x92095b9c, 0x1503d01c, 0xd6ce0677, 0x026a8ec1, 0x76d0084d, 0x86c23633, 0x36f75ce6, 0x08fa7bbe, 0x35f6ff2a, 0x31cc9525, 0x2c1a35e6, 0x8effcd62, 0xc782fa07, 0x8a86e248, 0x8fdb7a9b, 0x77246626, 0x5767723f, 0x3a78b699, 0xe548ce1c, 0x5820f37d, 0x148ed9b8, 0xf6796254, 0x32232c20, 0x392bf3a2, 0xe9af6625, 0xd40b0d88, 0x636cfa23, 0x6a5de514, 0xc4a69183, 0xc785c853, 0xab0de901, 0x16ae7e44, 0x376f13b5, 0x070f7f31, 0x34cbc93b, 0xe6184345, 0x1b7f911f, 0x631fbe4b, 0x86d6e023, 0xc689b518, 0x88ef4f7c, 0xddf06b45, 0xc97f18d4, 0x2aaee94b, 0x45694723, 0x6db111d2, 0x91974fce, 0xe33e29e2, 0xc5e99494, 0x8017e02b, 0x3ebd8143, 0x471ffb80, 0xc0d7ca1b, 0x4954c860, 0x48935d6a, 0xf2d27999, 0xb93d608d, 0x40696e90, 0x60b18162, 0x1a156998, 0x09b8bbab, 0xc80a79b6, 0x8adbcfbc, 0xc375248c, 0xa584e2ea, 0x5b46fe11, 0x58e84680, 0x8a8bc456, 0xd668b94f, 0x8b9035be, 0x278509d4, 0x6663a140, 0x81a9817a, 0xd4f9d3cf, 0x6dc5f607, 0x6ae04450, 0x694f22a4, 0x1d061788, 0x2e39ad8b, 0x748f4db2, 0xee569b52, 0xd157166d, 0xdabc161e, 0xc8d50176, 0x7e3110e5, 0x9f7d033b, 0x128df67f, 0xb0078583, 0xa3a75d26, 0xc1ad8011, 0x07dd89ec, 0xef04f456, 0x91bf866c, 0x6aac5306, 0xdd5a1573, 0xf73ff97a, 0x4e1186ad, 0xb9680680, 0xc8894515, 0xdc95a08e, 0xc894fd8e, 0xf84ade15, 0xd787f8c1, 0x40dcecca, 0x1b24743e, 0x1ce6ab23, 0x72321653, 0xb80fbaf7, 0x1bcf099b, 0x1ff26805, 0x78f66c8e, 0xf93bf51a, 0xfb0c06fe, 0xe50d48cf, 0x310947e0, 0x1b78804a, 0xe73e2c14, 0x8deb8381, 0xe576122a, 0xe5a8df39, 0x42397c5e, 0xf5503f3c, 0xbe3dbf8d, 0x1b360e5c, 0x9254caaf, 0x7a9f6744, 0x6d4144fa, 0xd77c65fe, 0x44ca7b12, 0xf58a4c00, 0x159500d0, 0x92769857, 0x7134fdd4, 0xa3fea693, 0xbd044831, 0xeded39a1, 0xe4570204, 0xaea37f2f, 0x9a302971, 0x620f8402, 0x1d2f3e5e, 0xf9c2f49c, 0x738e813a, 0xb3c92251, 0x7ecba63b, 0xbe7eebc7, 0xf800267c, 0x3fdeb760, 0xf12d5e7d, 0x5a18dce1, 0xb35a539c, 0xe565f057, 0x2babf38c, 0xae5800ad, 0x421004dd, 0x6715acb6, 0xff529b64, 0xd520d207, 0x7cb193e7, 0xe9b18e4c, 0xfd2a8a59, 0x47826ae3, 0x56ba43f8, 0x453b3d99, 0x8ae1675f, 0xf66f5c34, 0x057a6ac1, 0x010769e4, 0xa8324158, 0x410379a5, 0x5dfc8c97, 0x72848afe, 0x59f169e5, 0xe32acb78, 0x5dfaa9c4, 0x51bb956a, }; const u8 TestRandom::expected_pcgrandom_bytes_result[24] = { 0xf3, 0x79, 0x8f, 0x31, 0xac, 0xd9, 0x34, 0xf8, 0x3c, 0x6e, 0x82, 0x37, 0x6b, 0x4b, 0x77, 0xe3, 0xbd, 0x0a, 0xee, 0x22, 0x79, 0x6e, 0x40, 0x00, }; const u8 TestRandom::expected_pcgrandom_bytes_result2[24] = { 0x47, 0x9e, 0x08, 0x3e, 0xd4, 0x21, 0x2d, 0xf6, 0xb4, 0xb1, 0x9d, 0x7a, 0x60, 0x02, 0x5a, 0xb2, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
pgimeno/minetest
src/unittest/test_random.cpp
C++
mit
10,554
/* Minetest Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "mapgen/mg_schematic.h" #include "gamedef.h" #include "nodedef.h" class TestSchematic : public TestBase { public: TestSchematic() { TestManager::registerTestModule(this); } const char *getName() { return "TestSchematic"; } void runTests(IGameDef *gamedef); void testMtsSerializeDeserialize(const NodeDefManager *ndef); void testLuaTableSerialize(const NodeDefManager *ndef); void testFileSerializeDeserialize(const NodeDefManager *ndef); static const content_t test_schem1_data[7 * 6 * 4]; static const content_t test_schem2_data[3 * 3 * 3]; static const u8 test_schem2_prob[3 * 3 * 3]; static const char *expected_lua_output; }; static TestSchematic g_test_instance; void TestSchematic::runTests(IGameDef *gamedef) { NodeDefManager *ndef = (NodeDefManager *)gamedef->getNodeDefManager(); ndef->setNodeRegistrationStatus(true); TEST(testMtsSerializeDeserialize, ndef); TEST(testLuaTableSerialize, ndef); TEST(testFileSerializeDeserialize, ndef); ndef->resetNodeResolveState(); } //////////////////////////////////////////////////////////////////////////////// void TestSchematic::testMtsSerializeDeserialize(const NodeDefManager *ndef) { static const v3s16 size(7, 6, 4); static const u32 volume = size.X * size.Y * size.Z; std::stringstream ss(std::ios_base::binary | std::ios_base::in | std::ios_base::out); std::vector<std::string> names; names.emplace_back("foo"); names.emplace_back("bar"); names.emplace_back("baz"); names.emplace_back("qux"); Schematic schem, schem2; schem.flags = 0; schem.size = size; schem.schemdata = new MapNode[volume]; schem.slice_probs = new u8[size.Y]; for (size_t i = 0; i != volume; i++) schem.schemdata[i] = MapNode(test_schem1_data[i], MTSCHEM_PROB_ALWAYS, 0); for (s16 y = 0; y != size.Y; y++) schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; UASSERT(schem.serializeToMts(&ss, names)); ss.seekg(0); names.clear(); UASSERT(schem2.deserializeFromMts(&ss, &names)); UASSERTEQ(size_t, names.size(), 4); UASSERTEQ(std::string, names[0], "foo"); UASSERTEQ(std::string, names[1], "bar"); UASSERTEQ(std::string, names[2], "baz"); UASSERTEQ(std::string, names[3], "qux"); UASSERT(schem2.size == size); for (size_t i = 0; i != volume; i++) UASSERT(schem2.schemdata[i] == schem.schemdata[i]); for (s16 y = 0; y != size.Y; y++) UASSERTEQ(u8, schem2.slice_probs[y], schem.slice_probs[y]); } void TestSchematic::testLuaTableSerialize(const NodeDefManager *ndef) { static const v3s16 size(3, 3, 3); static const u32 volume = size.X * size.Y * size.Z; Schematic schem; schem.flags = 0; schem.size = size; schem.schemdata = new MapNode[volume]; schem.slice_probs = new u8[size.Y]; for (size_t i = 0; i != volume; i++) schem.schemdata[i] = MapNode(test_schem2_data[i], test_schem2_prob[i], 0); for (s16 y = 0; y != size.Y; y++) schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; std::vector<std::string> names; names.emplace_back("air"); names.emplace_back("default:lava_source"); names.emplace_back("default:glass"); std::ostringstream ss(std::ios_base::binary); UASSERT(schem.serializeToLua(&ss, names, false, 0)); UASSERTEQ(std::string, ss.str(), expected_lua_output); } void TestSchematic::testFileSerializeDeserialize(const NodeDefManager *ndef) { static const v3s16 size(3, 3, 3); static const u32 volume = size.X * size.Y * size.Z; static const content_t content_map[] = { CONTENT_AIR, t_CONTENT_STONE, t_CONTENT_LAVA, }; static const content_t content_map2[] = { CONTENT_AIR, t_CONTENT_STONE, t_CONTENT_WATER, }; StringMap replace_names; replace_names["default:lava"] = "default:water"; Schematic schem1, schem2; //// Construct the schematic to save schem1.flags = 0; schem1.size = size; schem1.schemdata = new MapNode[volume]; schem1.slice_probs = new u8[size.Y]; schem1.slice_probs[0] = 80; schem1.slice_probs[1] = 160; schem1.slice_probs[2] = 240; for (size_t i = 0; i != volume; i++) { content_t c = content_map[test_schem2_data[i]]; schem1.schemdata[i] = MapNode(c, test_schem2_prob[i], 0); } std::string temp_file = getTestTempFile(); UASSERT(schem1.saveSchematicToFile(temp_file, ndef)); UASSERT(schem2.loadSchematicFromFile(temp_file, ndef, &replace_names)); UASSERT(schem2.size == size); UASSERT(schem2.slice_probs[0] == 80); UASSERT(schem2.slice_probs[1] == 160); UASSERT(schem2.slice_probs[2] == 240); for (size_t i = 0; i != volume; i++) { content_t c = content_map2[test_schem2_data[i]]; UASSERT(schem2.schemdata[i] == MapNode(c, test_schem2_prob[i], 0)); } } // Should form a cross-shaped-thing...? const content_t TestSchematic::test_schem1_data[7 * 6 * 4] = { 3, 3, 1, 1, 1, 3, 3, // Y=0, Z=0 3, 0, 1, 2, 1, 0, 3, // Y=1, Z=0 3, 0, 1, 2, 1, 0, 3, // Y=2, Z=0 3, 1, 1, 2, 1, 1, 3, // Y=3, Z=0 3, 2, 2, 2, 2, 2, 3, // Y=4, Z=0 3, 1, 1, 2, 1, 1, 3, // Y=5, Z=0 0, 0, 1, 1, 1, 0, 0, // Y=0, Z=1 0, 0, 1, 2, 1, 0, 0, // Y=1, Z=1 0, 0, 1, 2, 1, 0, 0, // Y=2, Z=1 1, 1, 1, 2, 1, 1, 1, // Y=3, Z=1 1, 2, 2, 2, 2, 2, 1, // Y=4, Z=1 1, 1, 1, 2, 1, 1, 1, // Y=5, Z=1 0, 0, 1, 1, 1, 0, 0, // Y=0, Z=2 0, 0, 1, 2, 1, 0, 0, // Y=1, Z=2 0, 0, 1, 2, 1, 0, 0, // Y=2, Z=2 1, 1, 1, 2, 1, 1, 1, // Y=3, Z=2 1, 2, 2, 2, 2, 2, 1, // Y=4, Z=2 1, 1, 1, 2, 1, 1, 1, // Y=5, Z=2 3, 3, 1, 1, 1, 3, 3, // Y=0, Z=3 3, 0, 1, 2, 1, 0, 3, // Y=1, Z=3 3, 0, 1, 2, 1, 0, 3, // Y=2, Z=3 3, 1, 1, 2, 1, 1, 3, // Y=3, Z=3 3, 2, 2, 2, 2, 2, 3, // Y=4, Z=3 3, 1, 1, 2, 1, 1, 3, // Y=5, Z=3 }; const content_t TestSchematic::test_schem2_data[3 * 3 * 3] = { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 2, 1, 2, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, }; const u8 TestSchematic::test_schem2_prob[3 * 3 * 3] = { 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, }; const char *TestSchematic::expected_lua_output = "schematic = {\n" "\tsize = {x=3, y=3, z=3},\n" "\tyslice_prob = {\n" "\t\t{ypos=0, prob=254},\n" "\t\t{ypos=1, prob=254},\n" "\t\t{ypos=2, prob=254},\n" "\t},\n" "\tdata = {\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"default:lava_source\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"default:glass\", prob=254, param2=0, force_place=true},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t\t{name=\"air\", prob=0, param2=0},\n" "\t},\n" "}\n";
pgimeno/minetest
src/unittest/test_schematic.cpp
C++
mit
8,371
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "util/string.h" #include "util/serialize.h" #include <cmath> class TestSerialization : public TestBase { public: TestSerialization() { TestManager::registerTestModule(this); } const char *getName() { return "TestSerialization"; } void runTests(IGameDef *gamedef); void buildTestStrings(); void testSerializeString(); void testSerializeWideString(); void testSerializeLongString(); void testSerializeJsonString(); void testSerializeHex(); void testDeSerializeString(); void testDeSerializeWideString(); void testDeSerializeLongString(); void testStreamRead(); void testStreamWrite(); void testVecPut(); void testStringLengthLimits(); void testBufReader(); void testFloatFormat(); std::string teststring2; std::wstring teststring2_w; std::string teststring2_w_encoded; static const u8 test_serialized_data[12 * 13 - 8]; }; static TestSerialization g_test_instance; void TestSerialization::runTests(IGameDef *gamedef) { buildTestStrings(); TEST(testSerializeString); TEST(testDeSerializeString); TEST(testSerializeWideString); TEST(testDeSerializeWideString); TEST(testSerializeLongString); TEST(testDeSerializeLongString); TEST(testSerializeJsonString); TEST(testSerializeHex); TEST(testStreamRead); TEST(testStreamWrite); TEST(testVecPut); TEST(testStringLengthLimits); TEST(testBufReader); TEST(testFloatFormat); } //////////////////////////////////////////////////////////////////////////////// // To be used like this: // mkstr("Some\0string\0with\0embedded\0nuls") // since std::string("...") doesn't work as expected in that case. template<size_t N> std::string mkstr(const char (&s)[N]) { return std::string(s, N - 1); } void TestSerialization::buildTestStrings() { std::ostringstream tmp_os; std::wostringstream tmp_os_w; std::ostringstream tmp_os_w_encoded; for (int i = 0; i < 256; i++) { tmp_os << (char)i; tmp_os_w << (wchar_t)i; tmp_os_w_encoded << (char)0 << (char)i; } teststring2 = tmp_os.str(); teststring2_w = tmp_os_w.str(); teststring2_w_encoded = tmp_os_w_encoded.str(); } void TestSerialization::testSerializeString() { // Test blank string UASSERT(serializeString("") == mkstr("\0\0")); // Test basic string UASSERT(serializeString("Hello world!") == mkstr("\0\14Hello world!")); // Test character range UASSERT(serializeString(teststring2) == mkstr("\1\0") + teststring2); } void TestSerialization::testDeSerializeString() { // Test deserialize { std::istringstream is(serializeString(teststring2), std::ios::binary); UASSERT(deSerializeString(is) == teststring2); UASSERT(!is.eof()); is.get(); UASSERT(is.eof()); } // Test deserialize an incomplete length specifier { std::istringstream is(mkstr("\x53"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeString(is)); } // Test deserialize a string with incomplete data { std::istringstream is(mkstr("\x00\x55 abcdefg"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeString(is)); } } void TestSerialization::testSerializeWideString() { // Test blank string UASSERT(serializeWideString(L"") == mkstr("\0\0")); // Test basic string UASSERT(serializeWideString(utf8_to_wide("Hello world!")) == mkstr("\0\14\0H\0e\0l\0l\0o\0 \0w\0o\0r\0l\0d\0!")); // Test character range UASSERT(serializeWideString(teststring2_w) == mkstr("\1\0") + teststring2_w_encoded); } void TestSerialization::testDeSerializeWideString() { // Test deserialize { std::istringstream is(serializeWideString(teststring2_w), std::ios::binary); UASSERT(deSerializeWideString(is) == teststring2_w); UASSERT(!is.eof()); is.get(); UASSERT(is.eof()); } // Test deserialize an incomplete length specifier { std::istringstream is(mkstr("\x53"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeWideString(is)); } // Test deserialize a string with an incomplete character { std::istringstream is(mkstr("\x00\x07\0a\0b\0c\0d\0e\0f\0"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeWideString(is)); } // Test deserialize a string with incomplete data { std::istringstream is(mkstr("\x00\x08\0a\0b\0c\0d\0e\0f"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeWideString(is)); } } void TestSerialization::testSerializeLongString() { // Test blank string UASSERT(serializeLongString("") == mkstr("\0\0\0\0")); // Test basic string UASSERT(serializeLongString("Hello world!") == mkstr("\0\0\0\14Hello world!")); // Test character range UASSERT(serializeLongString(teststring2) == mkstr("\0\0\1\0") + teststring2); } void TestSerialization::testDeSerializeLongString() { // Test deserialize { std::istringstream is(serializeLongString(teststring2), std::ios::binary); UASSERT(deSerializeLongString(is) == teststring2); UASSERT(!is.eof()); is.get(); UASSERT(is.eof()); } // Test deserialize an incomplete length specifier { std::istringstream is(mkstr("\x53"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeLongString(is)); } // Test deserialize a string with incomplete data { std::istringstream is(mkstr("\x00\x00\x00\x05 abc"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeLongString(is)); } // Test deserialize a string with a length too large { std::istringstream is(mkstr("\xFF\xFF\xFF\xFF blah"), std::ios::binary); EXCEPTION_CHECK(SerializationError, deSerializeLongString(is)); } } void TestSerialization::testSerializeJsonString() { // Test blank string UASSERT(serializeJsonString("") == "\"\""); // Test basic string UASSERT(serializeJsonString("Hello world!") == "\"Hello world!\""); // MSVC fails when directly using "\\\\" std::string backslash = "\\"; UASSERT(serializeJsonString(teststring2) == mkstr("\"") + "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007" + "\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f" + "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" + "\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f" + " !\\\"" + teststring2.substr(0x23, 0x2f-0x23) + "\\/" + teststring2.substr(0x30, 0x5c-0x30) + backslash + backslash + teststring2.substr(0x5d, 0x7f-0x5d) + "\\u007f" + "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087" + "\\u0088\\u0089\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" + "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097" + "\\u0098\\u0099\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" + "\\u00a0\\u00a1\\u00a2\\u00a3\\u00a4\\u00a5\\u00a6\\u00a7" + "\\u00a8\\u00a9\\u00aa\\u00ab\\u00ac\\u00ad\\u00ae\\u00af" + "\\u00b0\\u00b1\\u00b2\\u00b3\\u00b4\\u00b5\\u00b6\\u00b7" + "\\u00b8\\u00b9\\u00ba\\u00bb\\u00bc\\u00bd\\u00be\\u00bf" + "\\u00c0\\u00c1\\u00c2\\u00c3\\u00c4\\u00c5\\u00c6\\u00c7" + "\\u00c8\\u00c9\\u00ca\\u00cb\\u00cc\\u00cd\\u00ce\\u00cf" + "\\u00d0\\u00d1\\u00d2\\u00d3\\u00d4\\u00d5\\u00d6\\u00d7" + "\\u00d8\\u00d9\\u00da\\u00db\\u00dc\\u00dd\\u00de\\u00df" + "\\u00e0\\u00e1\\u00e2\\u00e3\\u00e4\\u00e5\\u00e6\\u00e7" + "\\u00e8\\u00e9\\u00ea\\u00eb\\u00ec\\u00ed\\u00ee\\u00ef" + "\\u00f0\\u00f1\\u00f2\\u00f3\\u00f4\\u00f5\\u00f6\\u00f7" + "\\u00f8\\u00f9\\u00fa\\u00fb\\u00fc\\u00fd\\u00fe\\u00ff" + "\""); // Test deserialize std::istringstream is(serializeJsonString(teststring2), std::ios::binary); UASSERT(deSerializeJsonString(is) == teststring2); UASSERT(!is.eof()); is.get(); UASSERT(is.eof()); } void TestSerialization::testSerializeHex() { // Test blank string UASSERT(serializeHexString("") == ""); UASSERT(serializeHexString("", true) == ""); // Test basic string UASSERT(serializeHexString("Hello world!") == "48656c6c6f20776f726c6421"); UASSERT(serializeHexString("Hello world!", true) == "48 65 6c 6c 6f 20 77 6f 72 6c 64 21"); // Test binary string UASSERT(serializeHexString(mkstr("\x00\x0a\xb0\x63\x1f\x00\xff")) == "000ab0631f00ff"); UASSERT(serializeHexString(mkstr("\x00\x0a\xb0\x63\x1f\x00\xff"), true) == "00 0a b0 63 1f 00 ff"); } void TestSerialization::testStreamRead() { std::string datastr( (const char *)test_serialized_data, sizeof(test_serialized_data)); std::istringstream is(datastr, std::ios_base::binary); UASSERT(readU8(is) == 0x11); UASSERT(readU16(is) == 0x2233); UASSERT(readU32(is) == 0x44556677); UASSERT(readU64(is) == 0x8899AABBCCDDEEFFLL); UASSERT(readS8(is) == -128); UASSERT(readS16(is) == 30000); UASSERT(readS32(is) == -6); UASSERT(readS64(is) == -43); UASSERT(readF1000(is) == 53.534f); UASSERT(readF1000(is) == -300000.32f); UASSERT(readF1000(is) == F1000_MIN); UASSERT(readF1000(is) == F1000_MAX); UASSERT(deSerializeString(is) == "foobar!"); UASSERT(readV2S16(is) == v2s16(500, 500)); UASSERT(readV3S16(is) == v3s16(4207, 604, -30)); UASSERT(readV2S32(is) == v2s32(1920, 1080)); UASSERT(readV3S32(is) == v3s32(-400, 6400054, 290549855)); UASSERT(deSerializeWideString(is) == L"\x02~woof~\x5455"); UASSERT(readV3F1000(is) == v3f(500, 10024.2f, -192.54f)); UASSERT(readARGB8(is) == video::SColor(255, 128, 50, 128)); UASSERT(deSerializeLongString(is) == "some longer string here"); UASSERT(is.rdbuf()->in_avail() == 2); UASSERT(readU16(is) == 0xF00D); UASSERT(is.rdbuf()->in_avail() == 0); } void TestSerialization::testStreamWrite() { std::ostringstream os(std::ios_base::binary); std::string data; writeU8(os, 0x11); writeU16(os, 0x2233); writeU32(os, 0x44556677); writeU64(os, 0x8899AABBCCDDEEFFLL); writeS8(os, -128); writeS16(os, 30000); writeS32(os, -6); writeS64(os, -43); writeF1000(os, 53.53467f); writeF1000(os, -300000.32f); writeF1000(os, F1000_MIN); writeF1000(os, F1000_MAX); os << serializeString("foobar!"); data = os.str(); UASSERT(data.size() < sizeof(test_serialized_data)); UASSERT(!memcmp(&data[0], test_serialized_data, data.size())); writeV2S16(os, v2s16(500, 500)); writeV3S16(os, v3s16(4207, 604, -30)); writeV2S32(os, v2s32(1920, 1080)); writeV3S32(os, v3s32(-400, 6400054, 290549855)); os << serializeWideString(L"\x02~woof~\x5455"); writeV3F1000(os, v3f(500, 10024.2f, -192.54f)); writeARGB8(os, video::SColor(255, 128, 50, 128)); os << serializeLongString("some longer string here"); writeU16(os, 0xF00D); data = os.str(); UASSERT(data.size() == sizeof(test_serialized_data)); UASSERT(!memcmp(&data[0], test_serialized_data, sizeof(test_serialized_data))); } void TestSerialization::testVecPut() { std::vector<u8> buf; putU8(&buf, 0x11); putU16(&buf, 0x2233); putU32(&buf, 0x44556677); putU64(&buf, 0x8899AABBCCDDEEFFLL); putS8(&buf, -128); putS16(&buf, 30000); putS32(&buf, -6); putS64(&buf, -43); putF1000(&buf, 53.53467f); putF1000(&buf, -300000.32f); putF1000(&buf, F1000_MIN); putF1000(&buf, F1000_MAX); putString(&buf, "foobar!"); putV2S16(&buf, v2s16(500, 500)); putV3S16(&buf, v3s16(4207, 604, -30)); putV2S32(&buf, v2s32(1920, 1080)); putV3S32(&buf, v3s32(-400, 6400054, 290549855)); putWideString(&buf, L"\x02~woof~\x5455"); putV3F1000(&buf, v3f(500, 10024.2f, -192.54f)); putARGB8(&buf, video::SColor(255, 128, 50, 128)); putLongString(&buf, "some longer string here"); putU16(&buf, 0xF00D); UASSERT(buf.size() == sizeof(test_serialized_data)); UASSERT(!memcmp(&buf[0], test_serialized_data, sizeof(test_serialized_data))); } void TestSerialization::testStringLengthLimits() { std::vector<u8> buf; std::string too_long(STRING_MAX_LEN + 1, 'A'); std::string way_too_large(LONG_STRING_MAX_LEN + 1, 'B'); std::wstring too_long_wide(WIDE_STRING_MAX_LEN + 1, L'C'); EXCEPTION_CHECK(SerializationError, putString(&buf, too_long)); putLongString(&buf, too_long); too_long.resize(too_long.size() - 1); putString(&buf, too_long); EXCEPTION_CHECK(SerializationError, putWideString(&buf, too_long_wide)); too_long_wide.resize(too_long_wide.size() - 1); putWideString(&buf, too_long_wide); } void TestSerialization::testBufReader() { u8 u8_data; u16 u16_data; u32 u32_data; u64 u64_data; s8 s8_data; s16 s16_data; s32 s32_data; s64 s64_data; f32 f32_data, f32_data2, f32_data3, f32_data4; video::SColor scolor_data; v2s16 v2s16_data; v3s16 v3s16_data; v2s32 v2s32_data; v3s32 v3s32_data; v3f v3f_data; std::string string_data; std::wstring widestring_data; std::string longstring_data; u8 raw_data[10] = {0}; BufReader buf(test_serialized_data, sizeof(test_serialized_data)); // Try reading data like normal UASSERT(buf.getU8() == 0x11); UASSERT(buf.getU16() == 0x2233); UASSERT(buf.getU32() == 0x44556677); UASSERT(buf.getU64() == 0x8899AABBCCDDEEFFLL); UASSERT(buf.getS8() == -128); UASSERT(buf.getS16() == 30000); UASSERT(buf.getS32() == -6); UASSERT(buf.getS64() == -43); UASSERT(buf.getF1000() == 53.534f); UASSERT(buf.getF1000() == -300000.32f); UASSERT(buf.getF1000() == F1000_MIN); UASSERT(buf.getF1000() == F1000_MAX); UASSERT(buf.getString() == "foobar!"); UASSERT(buf.getV2S16() == v2s16(500, 500)); UASSERT(buf.getV3S16() == v3s16(4207, 604, -30)); UASSERT(buf.getV2S32() == v2s32(1920, 1080)); UASSERT(buf.getV3S32() == v3s32(-400, 6400054, 290549855)); UASSERT(buf.getWideString() == L"\x02~woof~\x5455"); UASSERT(buf.getV3F1000() == v3f(500, 10024.2f, -192.54f)); UASSERT(buf.getARGB8() == video::SColor(255, 128, 50, 128)); UASSERT(buf.getLongString() == "some longer string here"); // Verify the offset and data is unchanged after a failed read size_t orig_pos = buf.pos; u32_data = 0; UASSERT(buf.getU32NoEx(&u32_data) == false); UASSERT(buf.pos == orig_pos); UASSERT(u32_data == 0); // Now try the same for a failed string read UASSERT(buf.getStringNoEx(&string_data) == false); UASSERT(buf.pos == orig_pos); UASSERT(string_data == ""); // Now try the same for a failed string read UASSERT(buf.getWideStringNoEx(&widestring_data) == false); UASSERT(buf.pos == orig_pos); UASSERT(widestring_data == L""); UASSERT(buf.getU16() == 0xF00D); UASSERT(buf.remaining() == 0); // Check to make sure these each blow exceptions as they're supposed to EXCEPTION_CHECK(SerializationError, buf.getU8()); EXCEPTION_CHECK(SerializationError, buf.getU16()); EXCEPTION_CHECK(SerializationError, buf.getU32()); EXCEPTION_CHECK(SerializationError, buf.getU64()); EXCEPTION_CHECK(SerializationError, buf.getS8()); EXCEPTION_CHECK(SerializationError, buf.getS16()); EXCEPTION_CHECK(SerializationError, buf.getS32()); EXCEPTION_CHECK(SerializationError, buf.getS64()); EXCEPTION_CHECK(SerializationError, buf.getF1000()); EXCEPTION_CHECK(SerializationError, buf.getARGB8()); EXCEPTION_CHECK(SerializationError, buf.getV2S16()); EXCEPTION_CHECK(SerializationError, buf.getV3S16()); EXCEPTION_CHECK(SerializationError, buf.getV2S32()); EXCEPTION_CHECK(SerializationError, buf.getV3S32()); EXCEPTION_CHECK(SerializationError, buf.getV3F1000()); EXCEPTION_CHECK(SerializationError, buf.getString()); EXCEPTION_CHECK(SerializationError, buf.getWideString()); EXCEPTION_CHECK(SerializationError, buf.getLongString()); EXCEPTION_CHECK(SerializationError, buf.getRawData(raw_data, sizeof(raw_data))); // See if we can skip backwards buf.pos = 5; UASSERT(buf.getRawDataNoEx(raw_data, 3) == true); UASSERT(raw_data[0] == 0x66); UASSERT(raw_data[1] == 0x77); UASSERT(raw_data[2] == 0x88); UASSERT(buf.getU32() == 0x99AABBCC); UASSERT(buf.pos == 12); // Now let's try it all over again using the NoEx variants buf.pos = 0; UASSERT(buf.getU8NoEx(&u8_data)); UASSERT(buf.getU16NoEx(&u16_data)); UASSERT(buf.getU32NoEx(&u32_data)); UASSERT(buf.getU64NoEx(&u64_data)); UASSERT(buf.getS8NoEx(&s8_data)); UASSERT(buf.getS16NoEx(&s16_data)); UASSERT(buf.getS32NoEx(&s32_data)); UASSERT(buf.getS64NoEx(&s64_data)); UASSERT(buf.getF1000NoEx(&f32_data)); UASSERT(buf.getF1000NoEx(&f32_data2)); UASSERT(buf.getF1000NoEx(&f32_data3)); UASSERT(buf.getF1000NoEx(&f32_data4)); UASSERT(buf.getStringNoEx(&string_data)); UASSERT(buf.getV2S16NoEx(&v2s16_data)); UASSERT(buf.getV3S16NoEx(&v3s16_data)); UASSERT(buf.getV2S32NoEx(&v2s32_data)); UASSERT(buf.getV3S32NoEx(&v3s32_data)); UASSERT(buf.getWideStringNoEx(&widestring_data)); UASSERT(buf.getV3F1000NoEx(&v3f_data)); UASSERT(buf.getARGB8NoEx(&scolor_data)); UASSERT(buf.getLongStringNoEx(&longstring_data)); // and make sure we got the correct data UASSERT(u8_data == 0x11); UASSERT(u16_data == 0x2233); UASSERT(u32_data == 0x44556677); UASSERT(u64_data == 0x8899AABBCCDDEEFFLL); UASSERT(s8_data == -128); UASSERT(s16_data == 30000); UASSERT(s32_data == -6); UASSERT(s64_data == -43); UASSERT(f32_data == 53.534f); UASSERT(f32_data2 == -300000.32f); UASSERT(f32_data3 == F1000_MIN); UASSERT(f32_data4 == F1000_MAX); UASSERT(string_data == "foobar!"); UASSERT(v2s16_data == v2s16(500, 500)); UASSERT(v3s16_data == v3s16(4207, 604, -30)); UASSERT(v2s32_data == v2s32(1920, 1080)); UASSERT(v3s32_data == v3s32(-400, 6400054, 290549855)); UASSERT(widestring_data == L"\x02~woof~\x5455"); UASSERT(v3f_data == v3f(500, 10024.2f, -192.54f)); UASSERT(scolor_data == video::SColor(255, 128, 50, 128)); UASSERT(longstring_data == "some longer string here"); UASSERT(buf.remaining() == 2); UASSERT(buf.getRawDataNoEx(raw_data, 3) == false); UASSERT(buf.remaining() == 2); UASSERT(buf.getRawDataNoEx(raw_data, 2) == true); UASSERT(raw_data[0] == 0xF0); UASSERT(raw_data[1] == 0x0D); UASSERT(buf.remaining() == 0); // Make sure no more available data causes a failure UASSERT(!buf.getU8NoEx(&u8_data)); UASSERT(!buf.getU16NoEx(&u16_data)); UASSERT(!buf.getU32NoEx(&u32_data)); UASSERT(!buf.getU64NoEx(&u64_data)); UASSERT(!buf.getS8NoEx(&s8_data)); UASSERT(!buf.getS16NoEx(&s16_data)); UASSERT(!buf.getS32NoEx(&s32_data)); UASSERT(!buf.getS64NoEx(&s64_data)); UASSERT(!buf.getF1000NoEx(&f32_data)); UASSERT(!buf.getARGB8NoEx(&scolor_data)); UASSERT(!buf.getV2S16NoEx(&v2s16_data)); UASSERT(!buf.getV3S16NoEx(&v3s16_data)); UASSERT(!buf.getV2S32NoEx(&v2s32_data)); UASSERT(!buf.getV3S32NoEx(&v3s32_data)); UASSERT(!buf.getV3F1000NoEx(&v3f_data)); UASSERT(!buf.getStringNoEx(&string_data)); UASSERT(!buf.getWideStringNoEx(&widestring_data)); UASSERT(!buf.getLongStringNoEx(&longstring_data)); UASSERT(!buf.getRawDataNoEx(raw_data, sizeof(raw_data))); } void TestSerialization::testFloatFormat() { FloatType type = getFloatSerializationType(); u32 i; f32 fs, fm; // Check precision of float calculations on this platform const std::unordered_map<f32, u32> float_results = { { 0.0f, 0x00000000UL }, { 1.0f, 0x3F800000UL }, { -1.0f, 0xBF800000UL }, { 0.1f, 0x3DCCCCCDUL }, { -0.1f, 0xBDCCCCCDUL }, { 1945329.25f, 0x49ED778AUL }, { -23298764.f, 0xCBB1C166UL }, { 0.5f, 0x3F000000UL }, { -0.5f, 0xBF000000UL } }; for (const auto &v : float_results) { i = f32Tou32Slow(v.first); if (std::abs((s64)v.second - i) > 32) { printf("Inaccurate float values on %.9g, expected 0x%X, actual 0x%X\n", v.first, v.second, i); UASSERT(false); } fs = u32Tof32Slow(v.second); if (std::fabs(v.first - fs) > std::fabs(v.first * 0.000005f)) { printf("Inaccurate float values on 0x%X, expected %.9g, actual 0x%.9g\n", v.second, v.first, fs); UASSERT(false); } } if (type == FLOATTYPE_SLOW) { // conversion using memcpy is not possible // Skip exact float comparison checks below return; } // The code below compares the IEEE conversion functions with a // known good IEC559/IEEE754 implementation. This test neeeds // IEC559 compliance in the compiler. #if defined(__GNUC__) && (!defined(__STDC_IEC_559__) || defined(__FAST_MATH__)) // GNU C++ lies about its IEC559 support when -ffast-math is active. // https://gcc.gnu.org/bugzilla//show_bug.cgi?id=84949 bool is_iec559 = false; #else bool is_iec559 = std::numeric_limits<f32>::is_iec559; #endif if (!is_iec559) return; auto test_single = [&fs, &fm](const u32 &i) -> bool { memcpy(&fm, &i, 4); fs = u32Tof32Slow(i); if (fm != fs) { printf("u32Tof32Slow failed on 0x%X, expected %.9g, actual %.9g\n", i, fm, fs); return false; } if (f32Tou32Slow(fs) != i) { printf("f32Tou32Slow failed on %.9g, expected 0x%X, actual 0x%X\n", fs, i, f32Tou32Slow(fs)); return false; } return true; }; // Use step of prime 277 to speed things up from 3 minutes to a few seconds // Test from 0 to 0xFF800000UL (positive) for (i = 0x00000000UL; i <= 0x7F800000UL; i += 277) UASSERT(test_single(i)); // Ensure +inf and -inf are tested UASSERT(test_single(0x7F800000UL)); UASSERT(test_single(0xFF800000UL)); // Test from 0x80000000UL to 0xFF800000UL (negative) for (i = 0x80000000UL; i <= 0xFF800000UL; i += 277) UASSERT(test_single(i)); } const u8 TestSerialization::test_serialized_data[12 * 13 - 8] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x80, 0x75, 0x30, 0xff, 0xff, 0xff, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd5, 0x00, 0x00, 0xd1, 0x1e, 0xee, 0x1e, 0x5b, 0xc0, 0x80, 0x00, 0x02, 0x80, 0x7F, 0xFF, 0xFD, 0x80, 0x00, 0x07, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0x21, 0x01, 0xf4, 0x01, 0xf4, 0x10, 0x6f, 0x02, 0x5c, 0xff, 0xe2, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x04, 0x38, 0xff, 0xff, 0xfe, 0x70, 0x00, 0x61, 0xa8, 0x36, 0x11, 0x51, 0x70, 0x5f, 0x00, 0x08, 0x00, 0x02, 0x00, 0x7e, 0x00, 'w', 0x00, 'o', 0x00, 'o', 0x00, 'f', 0x00, // \x02~woof~\x5455 0x7e, 0x54, 0x55, 0x00, 0x07, 0xa1, 0x20, 0x00, 0x98, 0xf5, 0x08, 0xff, 0xfd, 0x0f, 0xe4, 0xff, 0x80, 0x32, 0x80, 0x00, 0x00, 0x00, 0x17, 0x73, 0x6f, 0x6d, 0x65, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x68, 0x65, 0x72, 0x65, 0xF0, 0x0D, };
pgimeno/minetest
src/unittest/test_serialization.cpp
C++
mit
22,436
/* Minetest Copyright (C) 2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <server.h> #include "test.h" #include "util/string.h" #include "util/serialize.h" class FakeServer : public Server { public: // clang-format off FakeServer() : Server("fakeworld", SubgameSpec("fakespec", "fakespec"), true, Address(), true, nullptr) { } // clang-format on private: void SendChatMessage(session_t peer_id, const ChatMessage &message) { // NOOP } }; class TestServerShutdownState : public TestBase { public: TestServerShutdownState() { TestManager::registerTestModule(this); } const char *getName() { return "TestServerShutdownState"; } void runTests(IGameDef *gamedef); void testInit(); void testReset(); void testTrigger(); void testTick(); }; static TestServerShutdownState g_test_instance; void TestServerShutdownState::runTests(IGameDef *gamedef) { TEST(testInit); TEST(testReset); TEST(testTrigger); TEST(testTick); } void TestServerShutdownState::testInit() { Server::ShutdownState ss; UASSERT(!ss.is_requested); UASSERT(!ss.should_reconnect); UASSERT(ss.message.empty()); UASSERT(ss.m_timer == 0.0f); } void TestServerShutdownState::testReset() { Server::ShutdownState ss; ss.reset(); UASSERT(!ss.is_requested); UASSERT(!ss.should_reconnect); UASSERT(ss.message.empty()); UASSERT(ss.m_timer == 0.0f); } void TestServerShutdownState::testTrigger() { Server::ShutdownState ss; ss.trigger(3.0f, "testtrigger", true); UASSERT(!ss.is_requested); UASSERT(ss.should_reconnect); UASSERT(ss.message == "testtrigger"); UASSERT(ss.m_timer == 3.0f); } void TestServerShutdownState::testTick() { std::unique_ptr<FakeServer> fakeServer(new FakeServer()); Server::ShutdownState ss; ss.trigger(28.0f, "testtrigger", true); ss.tick(0.0f, fakeServer.get()); // Tick with no time should not change anything UASSERT(!ss.is_requested); UASSERT(ss.should_reconnect); UASSERT(ss.message == "testtrigger"); UASSERT(ss.m_timer == 28.0f); // Tick 2 seconds ss.tick(2.0f, fakeServer.get()); UASSERT(!ss.is_requested); UASSERT(ss.should_reconnect); UASSERT(ss.message == "testtrigger"); UASSERT(ss.m_timer == 26.0f); // Tick remaining seconds + additional expire ss.tick(26.1f, fakeServer.get()); UASSERT(ss.is_requested); UASSERT(ss.should_reconnect); UASSERT(ss.message == "testtrigger"); UASSERT(ss.m_timer == 0.0f); }
pgimeno/minetest
src/unittest/test_server_shutdown_state.cpp
C++
mit
3,093
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "server/activeobjectmgr.h" #include <algorithm> #include <queue> #include "test.h" #include "profiler.h" class TestServerActiveObject : public ServerActiveObject { public: TestServerActiveObject(const v3f &p = v3f()) : ServerActiveObject(nullptr, p) {} ~TestServerActiveObject() = default; ActiveObjectType getType() const override { return ACTIVEOBJECT_TYPE_TEST; } bool getCollisionBox(aabb3f *toset) const override { return false; } bool getSelectionBox(aabb3f *toset) const override { return false; } bool collideWithObjects() const override { return false; } }; class TestServerActiveObjectMgr : public TestBase { public: TestServerActiveObjectMgr() { TestManager::registerTestModule(this); } const char *getName() { return "TestServerActiveObjectMgr"; } void runTests(IGameDef *gamedef); void testFreeID(); void testRegisterObject(); void testRemoveObject(); void testGetObjectsInsideRadius(); void testGetAddedActiveObjectsAroundPos(); }; static TestServerActiveObjectMgr g_test_instance; void TestServerActiveObjectMgr::runTests(IGameDef *gamedef) { TEST(testFreeID); TEST(testRegisterObject) TEST(testRemoveObject) TEST(testGetObjectsInsideRadius); TEST(testGetAddedActiveObjectsAroundPos); } void clearSAOMgr(server::ActiveObjectMgr *saomgr) { auto clear_cb = [](ServerActiveObject *obj, u16 id) { delete obj; return true; }; saomgr->clear(clear_cb); } //////////////////////////////////////////////////////////////////////////////// void TestServerActiveObjectMgr::testFreeID() { server::ActiveObjectMgr saomgr; std::vector<u16> aoids; u16 aoid = saomgr.getFreeId(); // Ensure it's not the same id UASSERT(saomgr.getFreeId() != aoid); aoids.push_back(aoid); // Register basic objects, ensure we never found for (u8 i = 0; i < UINT8_MAX; i++) { // Register an object auto tsao = new TestServerActiveObject(); saomgr.registerObject(tsao); aoids.push_back(tsao->getId()); // Ensure next id is not in registered list UASSERT(std::find(aoids.begin(), aoids.end(), saomgr.getFreeId()) == aoids.end()); } clearSAOMgr(&saomgr); } void TestServerActiveObjectMgr::testRegisterObject() { server::ActiveObjectMgr saomgr; auto tsao = new TestServerActiveObject(); UASSERT(saomgr.registerObject(tsao)); u16 id = tsao->getId(); auto tsaoToCompare = saomgr.getActiveObject(id); UASSERT(tsaoToCompare->getId() == id); UASSERT(tsaoToCompare == tsao); tsao = new TestServerActiveObject(); UASSERT(saomgr.registerObject(tsao)); UASSERT(saomgr.getActiveObject(tsao->getId()) == tsao); UASSERT(saomgr.getActiveObject(tsao->getId()) != tsaoToCompare); clearSAOMgr(&saomgr); } void TestServerActiveObjectMgr::testRemoveObject() { server::ActiveObjectMgr saomgr; auto tsao = new TestServerActiveObject(); UASSERT(saomgr.registerObject(tsao)); u16 id = tsao->getId(); UASSERT(saomgr.getActiveObject(id) != nullptr) saomgr.removeObject(tsao->getId()); UASSERT(saomgr.getActiveObject(id) == nullptr); clearSAOMgr(&saomgr); } void TestServerActiveObjectMgr::testGetObjectsInsideRadius() { server::ActiveObjectMgr saomgr; static const v3f sao_pos[] = { v3f(10, 40, 10), v3f(740, 100, -304), v3f(-200, 100, -304), v3f(740, -740, -304), v3f(1500, -740, -304), }; for (const auto &p : sao_pos) { saomgr.registerObject(new TestServerActiveObject(p)); } std::vector<u16> result; saomgr.getObjectsInsideRadius(v3f(), 50, result); UASSERTCMP(int, ==, result.size(), 1); result.clear(); saomgr.getObjectsInsideRadius(v3f(), 750, result); UASSERTCMP(int, ==, result.size(), 2); clearSAOMgr(&saomgr); } void TestServerActiveObjectMgr::testGetAddedActiveObjectsAroundPos() { server::ActiveObjectMgr saomgr; static const v3f sao_pos[] = { v3f(10, 40, 10), v3f(740, 100, -304), v3f(-200, 100, -304), v3f(740, -740, -304), v3f(1500, -740, -304), }; for (const auto &p : sao_pos) { saomgr.registerObject(new TestServerActiveObject(p)); } std::queue<u16> result; std::set<u16> cur_objects; saomgr.getAddedActiveObjectsAroundPos(v3f(), 100, 50, cur_objects, result); UASSERTCMP(int, ==, result.size(), 1); result = std::queue<u16>(); cur_objects.clear(); saomgr.getAddedActiveObjectsAroundPos(v3f(), 740, 50, cur_objects, result); UASSERTCMP(int, ==, result.size(), 2); clearSAOMgr(&saomgr); }
pgimeno/minetest
src/unittest/test_serveractiveobjectmgr.cpp
C++
mit
5,122
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <algorithm> #include "server/mods.h" #include "test_config.h" class TestServerModManager : public TestBase { public: TestServerModManager() { TestManager::registerTestModule(this); } const char *getName() { return "TestServerModManager"; } void runTests(IGameDef *gamedef); void testCreation(); void testIsConsistent(); void testUnsatisfiedMods(); void testGetMods(); void testGetModsWrongDir(); void testGetModspec(); void testGetModNamesWrongDir(); void testGetModNames(); void testGetModMediaPathsWrongDir(); void testGetModMediaPaths(); }; static TestServerModManager g_test_instance; void TestServerModManager::runTests(IGameDef *gamedef) { const char *saved_env_mt_subgame_path = getenv("MINETEST_SUBGAME_PATH"); #ifdef WIN32 { std::string subgame_path("MINETEST_SUBGAME_PATH="); subgame_path.append(TEST_SUBGAME_PATH); _putenv(subgame_path.c_str()); } #else setenv("MINETEST_SUBGAME_PATH", TEST_SUBGAME_PATH, 1); #endif TEST(testCreation); TEST(testIsConsistent); TEST(testGetModsWrongDir); TEST(testUnsatisfiedMods); TEST(testGetMods); TEST(testGetModspec); TEST(testGetModNamesWrongDir); TEST(testGetModNames); TEST(testGetModMediaPathsWrongDir); TEST(testGetModMediaPaths); #ifdef WIN32 { std::string subgame_path("MINETEST_SUBGAME_PATH="); if (saved_env_mt_subgame_path) subgame_path.append(saved_env_mt_subgame_path); _putenv(subgame_path.c_str()); } #else if (saved_env_mt_subgame_path) setenv("MINETEST_SUBGAME_PATH", saved_env_mt_subgame_path, 1); else unsetenv("MINETEST_SUBGAME_PATH"); #endif } void TestServerModManager::testCreation() { ServerModManager sm(TEST_WORLDDIR); } void TestServerModManager::testGetModsWrongDir() { // Test in non worlddir to ensure no mods are found ServerModManager sm(std::string(TEST_WORLDDIR) + DIR_DELIM + ".."); UASSERTEQ(bool, sm.getMods().empty(), true); } void TestServerModManager::testUnsatisfiedMods() { ServerModManager sm(std::string(TEST_WORLDDIR)); UASSERTEQ(bool, sm.getUnsatisfiedMods().empty(), true); } void TestServerModManager::testIsConsistent() { ServerModManager sm(std::string(TEST_WORLDDIR)); UASSERTEQ(bool, sm.isConsistent(), true); } void TestServerModManager::testGetMods() { ServerModManager sm(std::string(TEST_WORLDDIR)); const auto &mods = sm.getMods(); UASSERTEQ(bool, mods.empty(), false); // Ensure we found default mod inside the test folder bool default_found = false; for (const auto &m : mods) { if (m.name == "default") default_found = true; // Verify if paths are not empty UASSERTEQ(bool, m.path.empty(), false); } UASSERTEQ(bool, default_found, true); } void TestServerModManager::testGetModspec() { ServerModManager sm(std::string(TEST_WORLDDIR)); UASSERTEQ(const ModSpec *, sm.getModSpec("wrongmod"), NULL); UASSERT(sm.getModSpec("default") != NULL); } void TestServerModManager::testGetModNamesWrongDir() { ServerModManager sm(std::string(TEST_WORLDDIR) + DIR_DELIM + ".."); std::vector<std::string> result; sm.getModNames(result); UASSERTEQ(bool, result.empty(), true); } void TestServerModManager::testGetModNames() { ServerModManager sm(std::string(TEST_WORLDDIR)); std::vector<std::string> result; sm.getModNames(result); UASSERTEQ(bool, result.empty(), false); UASSERT(std::find(result.begin(), result.end(), "default") != result.end()); } void TestServerModManager::testGetModMediaPathsWrongDir() { ServerModManager sm(std::string(TEST_WORLDDIR) + DIR_DELIM + ".."); std::vector<std::string> result; sm.getModsMediaPaths(result); UASSERTEQ(bool, result.empty(), true); } void TestServerModManager::testGetModMediaPaths() { ServerModManager sm(std::string(TEST_WORLDDIR)); std::vector<std::string> result; sm.getModsMediaPaths(result); UASSERTEQ(bool, result.empty(), false); // We should have 5 folders for each mod (textures, media, locale, model, sounds) UASSERTEQ(unsigned long, result.size() % 5, 0); }
pgimeno/minetest
src/unittest/test_servermodmanager.cpp
C++
mit
4,742
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <cmath> #include "settings.h" #include "noise.h" class TestSettings : public TestBase { public: TestSettings() { TestManager::registerTestModule(this); } const char *getName() { return "TestSettings"; } void runTests(IGameDef *gamedef); void testAllSettings(); static const char *config_text_before; static const std::string config_text_after; }; static TestSettings g_test_instance; void TestSettings::runTests(IGameDef *gamedef) { TEST(testAllSettings); } //////////////////////////////////////////////////////////////////////////////// const char *TestSettings::config_text_before = "leet = 1337\n" "leetleet = 13371337\n" "leetleet_neg = -13371337\n" "floaty_thing = 1.1\n" "stringy_thing = asd /( ¤%&(/\" BLÖÄRP\n" "coord = (1, 2, 4.5)\n" " # this is just a comment\n" "this is an invalid line\n" "asdf = {\n" " a = 5\n" " bb = 2.5\n" " ccc = \"\"\"\n" "testy\n" " testa \n" "\"\"\"\n" "\n" "}\n" "blarg = \"\"\" \n" "some multiline text\n" " with leading whitespace!\n" "\"\"\"\n" "np_terrain = 5, 40, (250, 250, 250), 12341, 5, 0.7, 2.4\n" "zoop = true"; const std::string TestSettings::config_text_after = "leet = 1337\n" "leetleet = 13371337\n" "leetleet_neg = -13371337\n" "floaty_thing = 1.1\n" "stringy_thing = asd /( ¤%&(/\" BLÖÄRP\n" "coord = (1, 2, 4.5)\n" " # this is just a comment\n" "this is an invalid line\n" "asdf = {\n" " a = 5\n" " bb = 2.5\n" " ccc = \"\"\"\n" "testy\n" " testa \n" "\"\"\"\n" "\n" "}\n" "blarg = \"\"\" \n" "some multiline text\n" " with leading whitespace!\n" "\"\"\"\n" "np_terrain = {\n" " flags = defaults\n" " lacunarity = 2.4\n" " octaves = 6\n" " offset = 3.5\n" " persistence = 0.7\n" " scale = 40\n" " seed = 12341\n" " spread = (250,250,250)\n" "}\n" "zoop = true\n" "coord2 = (1,2,3.3)\n" "floaty_thing_2 = 1.2\n" "groupy_thing = {\n" " animals = cute\n" " num_apples = 4\n" " num_oranges = 53\n" "}\n"; void TestSettings::testAllSettings() { try { Settings s; // Test reading of settings std::istringstream is(config_text_before); s.parseConfigLines(is); UASSERT(s.getS32("leet") == 1337); UASSERT(s.getS16("leetleet") == 32767); UASSERT(s.getS16("leetleet_neg") == -32768); // Not sure if 1.1 is an exact value as a float, but doesn't matter UASSERT(fabs(s.getFloat("floaty_thing") - 1.1) < 0.001); UASSERT(s.get("stringy_thing") == "asd /( ¤%&(/\" BLÖÄRP"); UASSERT(fabs(s.getV3F("coord").X - 1.0) < 0.001); UASSERT(fabs(s.getV3F("coord").Y - 2.0) < 0.001); UASSERT(fabs(s.getV3F("coord").Z - 4.5) < 0.001); // Test the setting of settings too s.setFloat("floaty_thing_2", 1.2); s.setV3F("coord2", v3f(1, 2, 3.3)); UASSERT(s.get("floaty_thing_2").substr(0,3) == "1.2"); UASSERT(fabs(s.getFloat("floaty_thing_2") - 1.2) < 0.001); UASSERT(fabs(s.getV3F("coord2").X - 1.0) < 0.001); UASSERT(fabs(s.getV3F("coord2").Y - 2.0) < 0.001); UASSERT(fabs(s.getV3F("coord2").Z - 3.3) < 0.001); // Test settings groups Settings *group = s.getGroup("asdf"); UASSERT(group != NULL); UASSERT(s.getGroupNoEx("zoop", group) == false); UASSERT(group->getS16("a") == 5); UASSERT(fabs(group->getFloat("bb") - 2.5) < 0.001); Settings *group3 = new Settings; group3->set("cat", "meow"); group3->set("dog", "woof"); Settings *group2 = new Settings; group2->setS16("num_apples", 4); group2->setS16("num_oranges", 53); group2->setGroup("animals", group3); group2->set("animals", "cute"); //destroys group 3 s.setGroup("groupy_thing", group2); // Test set failure conditions UASSERT(s.set("Zoop = Poop\nsome_other_setting", "false") == false); UASSERT(s.set("sneaky", "\"\"\"\njabberwocky = false") == false); UASSERT(s.set("hehe", "asdfasdf\n\"\"\"\nsomething = false") == false); // Test multiline settings UASSERT(group->get("ccc") == "testy\n testa "); UASSERT(s.get("blarg") == "some multiline text\n" " with leading whitespace!"); // Test NoiseParams UASSERT(s.getEntry("np_terrain").is_group == false); NoiseParams np; UASSERT(s.getNoiseParams("np_terrain", np) == true); UASSERT(std::fabs(np.offset - 5) < 0.001f); UASSERT(std::fabs(np.scale - 40) < 0.001f); UASSERT(std::fabs(np.spread.X - 250) < 0.001f); UASSERT(std::fabs(np.spread.Y - 250) < 0.001f); UASSERT(std::fabs(np.spread.Z - 250) < 0.001f); UASSERT(np.seed == 12341); UASSERT(np.octaves == 5); UASSERT(std::fabs(np.persist - 0.7) < 0.001f); np.offset = 3.5; np.octaves = 6; s.setNoiseParams("np_terrain", np); UASSERT(s.getEntry("np_terrain").is_group == true); // Test writing std::ostringstream os(std::ios_base::binary); is.clear(); is.seekg(0); UASSERT(s.updateConfigObject(is, os, "", 0) == true); //printf(">>>> expected config:\n%s\n", TEST_CONFIG_TEXT_AFTER); //printf(">>>> actual config:\n%s\n", os.str().c_str()); #if __cplusplus < 201103L // This test only works in older C++ versions than C++11 because we use unordered_map UASSERT(os.str() == config_text_after); #endif } catch (SettingNotFoundException &e) { UASSERT(!"Setting not found!"); } }
pgimeno/minetest
src/unittest/test_settings.cpp
C++
mit
5,895
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "log.h" #include "settings.h" #include "network/socket.h" class TestSocket : public TestBase { public: TestSocket() { if (INTERNET_SIMULATOR == false) TestManager::registerTestModule(this); } const char *getName() { return "TestSocket"; } void runTests(IGameDef *gamedef); void testIPv4Socket(); void testIPv6Socket(); static const int port = 30003; }; static TestSocket g_test_instance; void TestSocket::runTests(IGameDef *gamedef) { TEST(testIPv4Socket); if (g_settings->getBool("enable_ipv6")) TEST(testIPv6Socket); } //////////////////////////////////////////////////////////////////////////////// void TestSocket::testIPv4Socket() { Address address(0, 0, 0, 0, port); Address bind_addr(0, 0, 0, 0, port); /* * Try to use the bind_address for servers with no localhost address * For example: FreeBSD jails */ std::string bind_str = g_settings->get("bind_address"); try { bind_addr.Resolve(bind_str.c_str()); if (!bind_addr.isIPv6()) { address = bind_addr; } } catch (ResolveError &e) { } UDPSocket socket(false); socket.Bind(address); const char sendbuffer[] = "hello world!"; /* * If there is a bind address, use it. * It's useful in container environments */ if (address != Address(0, 0, 0, 0, port)) socket.Send(address, sendbuffer, sizeof(sendbuffer)); else socket.Send(Address(127, 0, 0, 1, port), sendbuffer, sizeof(sendbuffer)); sleep_ms(50); char rcvbuffer[256] = { 0 }; Address sender; for (;;) { if (socket.Receive(sender, rcvbuffer, sizeof(rcvbuffer)) < 0) break; } //FIXME: This fails on some systems UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0); if (address != Address(0, 0, 0, 0, port)) { UASSERT(sender.getAddress().sin_addr.s_addr == address.getAddress().sin_addr.s_addr); } else { UASSERT(sender.getAddress().sin_addr.s_addr == Address(127, 0, 0, 1, 0).getAddress().sin_addr.s_addr); } } void TestSocket::testIPv6Socket() { Address address6((IPv6AddressBytes *)NULL, port); UDPSocket socket6; if (!socket6.init(true, true)) { /* Note: Failing to create an IPv6 socket is not technically an error because the OS may not support IPv6 or it may have been disabled. IPv6 is not /required/ by minetest and therefore this should not cause the unit test to fail */ dstream << "WARNING: IPv6 socket creation failed (unit test)" << std::endl; return; } const char sendbuffer[] = "hello world!"; IPv6AddressBytes bytes; bytes.bytes[15] = 1; socket6.Bind(address6); try { socket6.Send(Address(&bytes, port), sendbuffer, sizeof(sendbuffer)); sleep_ms(50); char rcvbuffer[256] = { 0 }; Address sender; for(;;) { if (socket6.Receive(sender, rcvbuffer, sizeof(rcvbuffer)) < 0) break; } //FIXME: This fails on some systems UASSERT(strncmp(sendbuffer, rcvbuffer, sizeof(sendbuffer)) == 0); UASSERT(memcmp(sender.getAddress6().sin6_addr.s6_addr, Address(&bytes, 0).getAddress6().sin6_addr.s6_addr, 16) == 0); } catch (SendFailedException &e) { errorstream << "IPv6 support enabled but not available!" << std::endl; } }
pgimeno/minetest
src/unittest/test_socket.cpp
C++
mit
3,940
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <atomic> #include "threading/semaphore.h" #include "threading/thread.h" class TestThreading : public TestBase { public: TestThreading() { TestManager::registerTestModule(this); } const char *getName() { return "TestThreading"; } void runTests(IGameDef *gamedef); void testStartStopWait(); void testThreadKill(); void testAtomicSemaphoreThread(); }; static TestThreading g_test_instance; void TestThreading::runTests(IGameDef *gamedef) { TEST(testStartStopWait); TEST(testThreadKill); TEST(testAtomicSemaphoreThread); } class SimpleTestThread : public Thread { public: SimpleTestThread(unsigned int interval) : Thread("SimpleTest"), m_interval(interval) { } private: void *run() { void *retval = this; if (isCurrentThread() == false) retval = (void *)0xBAD; while (!stopRequested()) sleep_ms(m_interval); return retval; } unsigned int m_interval; }; void TestThreading::testStartStopWait() { void *thread_retval; SimpleTestThread *thread = new SimpleTestThread(25); // Try this a couple times, since a Thread should be reusable after waiting for (size_t i = 0; i != 5; i++) { // Can't wait() on a joined, stopped thread UASSERT(thread->wait() == false); // start() should work the first time, but not the second. UASSERT(thread->start() == true); UASSERT(thread->start() == false); UASSERT(thread->isRunning() == true); UASSERT(thread->isCurrentThread() == false); // Let it loop a few times... sleep_ms(70); // It's still running, so the return value shouldn't be available to us. UASSERT(thread->getReturnValue(&thread_retval) == false); // stop() should always succeed UASSERT(thread->stop() == true); // wait() only needs to wait the first time - the other two are no-ops. UASSERT(thread->wait() == true); UASSERT(thread->wait() == false); UASSERT(thread->wait() == false); // Now that the thread is stopped, we should be able to get the // return value, and it should be the object itself. thread_retval = NULL; UASSERT(thread->getReturnValue(&thread_retval) == true); UASSERT(thread_retval == thread); } delete thread; } void TestThreading::testThreadKill() { SimpleTestThread *thread = new SimpleTestThread(300); UASSERT(thread->start() == true); // kill()ing is quite violent, so let's make sure our victim is sleeping // before we do this... so we don't corrupt the rest of the program's state sleep_ms(100); UASSERT(thread->kill() == true); // The state of the thread object should be reset if all went well UASSERT(thread->isRunning() == false); UASSERT(thread->start() == true); UASSERT(thread->stop() == true); UASSERT(thread->wait() == true); // kill() after already waiting should fail. UASSERT(thread->kill() == false); delete thread; } class AtomicTestThread : public Thread { public: AtomicTestThread(std::atomic<u32> &v, Semaphore &trigger) : Thread("AtomicTest"), val(v), trigger(trigger) { } private: void *run() { trigger.wait(); for (u32 i = 0; i < 0x10000; ++i) ++val; return NULL; } std::atomic<u32> &val; Semaphore &trigger; }; void TestThreading::testAtomicSemaphoreThread() { std::atomic<u32> val; val = 0; Semaphore trigger; static const u8 num_threads = 4; AtomicTestThread *threads[num_threads]; for (auto &thread : threads) { thread = new AtomicTestThread(val, trigger); UASSERT(thread->start()); } trigger.post(num_threads); for (AtomicTestThread *thread : threads) { thread->wait(); delete thread; } UASSERT(val == num_threads * 0x10000); }
pgimeno/minetest
src/unittest/test_threading.cpp
C++
mit
4,366
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <cmath> #include "util/numeric.h" #include "util/string.h" class TestUtilities : public TestBase { public: TestUtilities() { TestManager::registerTestModule(this); } const char *getName() { return "TestUtilities"; } void runTests(IGameDef *gamedef); void testAngleWrapAround(); void testWrapDegrees_0_360_v3f(); void testLowercase(); void testTrim(); void testIsYes(); void testRemoveStringEnd(); void testUrlEncode(); void testUrlDecode(); void testPadString(); void testStartsWith(); void testStrEqual(); void testStringTrim(); void testStrToIntConversion(); void testStringReplace(); void testStringAllowed(); void testAsciiPrintableHelper(); void testUTF8(); void testRemoveEscapes(); void testWrapRows(); void testIsNumber(); void testIsPowerOfTwo(); void testMyround(); void testStringJoin(); void testEulerConversion(); }; static TestUtilities g_test_instance; void TestUtilities::runTests(IGameDef *gamedef) { TEST(testAngleWrapAround); TEST(testWrapDegrees_0_360_v3f); TEST(testLowercase); TEST(testTrim); TEST(testIsYes); TEST(testRemoveStringEnd); TEST(testUrlEncode); TEST(testUrlDecode); TEST(testPadString); TEST(testStartsWith); TEST(testStrEqual); TEST(testStringTrim); TEST(testStrToIntConversion); TEST(testStringReplace); TEST(testStringAllowed); TEST(testAsciiPrintableHelper); TEST(testUTF8); TEST(testRemoveEscapes); TEST(testWrapRows); TEST(testIsNumber); TEST(testIsPowerOfTwo); TEST(testMyround); TEST(testStringJoin); TEST(testEulerConversion); } //////////////////////////////////////////////////////////////////////////////// inline float ref_WrapDegrees180(float f) { // This is a slower alternative to the wrapDegrees_180() function; // used as a reference for testing float value = fmodf(f + 180, 360); if (value < 0) value += 360; return value - 180; } inline float ref_WrapDegrees_0_360(float f) { // This is a slower alternative to the wrapDegrees_0_360() function; // used as a reference for testing float value = fmodf(f, 360); if (value < 0) value += 360; return value < 0 ? value + 360 : value; } void TestUtilities::testAngleWrapAround() { UASSERT(fabs(modulo360f(100.0) - 100.0) < 0.001); UASSERT(fabs(modulo360f(720.5) - 0.5) < 0.001); UASSERT(fabs(modulo360f(-0.5) - (-0.5)) < 0.001); UASSERT(fabs(modulo360f(-365.5) - (-5.5)) < 0.001); for (float f = -720; f <= -360; f += 0.25) { UASSERT(std::fabs(modulo360f(f) - modulo360f(f + 360)) < 0.001); } for (float f = -1440; f <= 1440; f += 0.25) { UASSERT(std::fabs(modulo360f(f) - fmodf(f, 360)) < 0.001); UASSERT(std::fabs(wrapDegrees_180(f) - ref_WrapDegrees180(f)) < 0.001); UASSERT(std::fabs(wrapDegrees_0_360(f) - ref_WrapDegrees_0_360(f)) < 0.001); UASSERT(wrapDegrees_0_360( std::fabs(wrapDegrees_180(f) - wrapDegrees_0_360(f))) < 0.001); } } void TestUtilities::testWrapDegrees_0_360_v3f() { // only x test with little step for (float x = -720.f; x <= 720; x += 0.05) { v3f r = wrapDegrees_0_360_v3f(v3f(x, 0, 0)); UASSERT(r.X >= 0.0f && r.X < 360.0f) UASSERT(r.Y == 0.0f) UASSERT(r.Z == 0.0f) } // only y test with little step for (float y = -720.f; y <= 720; y += 0.05) { v3f r = wrapDegrees_0_360_v3f(v3f(0, y, 0)); UASSERT(r.X == 0.0f) UASSERT(r.Y >= 0.0f && r.Y < 360.0f) UASSERT(r.Z == 0.0f) } // only z test with little step for (float z = -720.f; z <= 720; z += 0.05) { v3f r = wrapDegrees_0_360_v3f(v3f(0, 0, z)); UASSERT(r.X == 0.0f) UASSERT(r.Y == 0.0f) UASSERT(r.Z >= 0.0f && r.Z < 360.0f) } // test the whole coordinate translation for (float x = -720.f; x <= 720; x += 2.5) { for (float y = -720.f; y <= 720; y += 2.5) { for (float z = -720.f; z <= 720; z += 2.5) { v3f r = wrapDegrees_0_360_v3f(v3f(x, y, z)); UASSERT(r.X >= 0.0f && r.X < 360.0f) UASSERT(r.Y >= 0.0f && r.Y < 360.0f) UASSERT(r.Z >= 0.0f && r.Z < 360.0f) } } } } void TestUtilities::testLowercase() { UASSERT(lowercase("Foo bAR") == "foo bar"); UASSERT(lowercase("eeeeeeaaaaaaaaaaaààààà") == "eeeeeeaaaaaaaaaaaààààà"); UASSERT(lowercase("MINETEST-powa") == "minetest-powa"); } void TestUtilities::testTrim() { UASSERT(trim("") == ""); UASSERT(trim("dirt_with_grass") == "dirt_with_grass"); UASSERT(trim("\n \t\r Foo bAR \r\n\t\t ") == "Foo bAR"); UASSERT(trim("\n \t\r \r\n\t\t ") == ""); } void TestUtilities::testIsYes() { UASSERT(is_yes("YeS") == true); UASSERT(is_yes("") == false); UASSERT(is_yes("FAlse") == false); UASSERT(is_yes("-1") == true); UASSERT(is_yes("0") == false); UASSERT(is_yes("1") == true); UASSERT(is_yes("2") == true); } void TestUtilities::testRemoveStringEnd() { const char *ends[] = {"abc", "c", "bc", "", NULL}; UASSERT(removeStringEnd("abc", ends) == ""); UASSERT(removeStringEnd("bc", ends) == "b"); UASSERT(removeStringEnd("12c", ends) == "12"); UASSERT(removeStringEnd("foo", ends) == ""); } void TestUtilities::testUrlEncode() { UASSERT(urlencode("\"Aardvarks lurk, OK?\"") == "%22Aardvarks%20lurk%2C%20OK%3F%22"); } void TestUtilities::testUrlDecode() { UASSERT(urldecode("%22Aardvarks%20lurk%2C%20OK%3F%22") == "\"Aardvarks lurk, OK?\""); } void TestUtilities::testPadString() { UASSERT(padStringRight("hello", 8) == "hello "); } void TestUtilities::testStartsWith() { UASSERT(str_starts_with(std::string(), std::string()) == true); UASSERT(str_starts_with(std::string("the sharp pickaxe"), std::string()) == true); UASSERT(str_starts_with(std::string("the sharp pickaxe"), std::string("the")) == true); UASSERT(str_starts_with(std::string("the sharp pickaxe"), std::string("The")) == false); UASSERT(str_starts_with(std::string("the sharp pickaxe"), std::string("The"), true) == true); UASSERT(str_starts_with(std::string("T"), std::string("The")) == false); } void TestUtilities::testStrEqual() { UASSERT(str_equal(narrow_to_wide("abc"), narrow_to_wide("abc"))); UASSERT(str_equal(narrow_to_wide("ABC"), narrow_to_wide("abc"), true)); } void TestUtilities::testStringTrim() { UASSERT(trim(" a") == "a"); UASSERT(trim(" a ") == "a"); UASSERT(trim("a ") == "a"); UASSERT(trim("") == ""); } void TestUtilities::testStrToIntConversion() { UASSERT(mystoi("123", 0, 1000) == 123); UASSERT(mystoi("123", 0, 10) == 10); } void TestUtilities::testStringReplace() { std::string test_str; test_str = "Hello there"; str_replace(test_str, "there", "world"); UASSERT(test_str == "Hello world"); test_str = "ThisAisAaAtest"; str_replace(test_str, 'A', ' '); UASSERT(test_str == "This is a test"); } void TestUtilities::testStringAllowed() { UASSERT(string_allowed("hello", "abcdefghijklmno") == true); UASSERT(string_allowed("123", "abcdefghijklmno") == false); UASSERT(string_allowed_blacklist("hello", "123") == true); UASSERT(string_allowed_blacklist("hello123", "123") == false); } void TestUtilities::testAsciiPrintableHelper() { UASSERT(IS_ASCII_PRINTABLE_CHAR('e') == true); UASSERT(IS_ASCII_PRINTABLE_CHAR('\0') == false); // Ensures that there is no cutting off going on... // If there were, 331 would be cut to 75 in this example // and 73 is a valid ASCII char. int ch = 331; UASSERT(IS_ASCII_PRINTABLE_CHAR(ch) == false); } void TestUtilities::testUTF8() { UASSERT(wide_to_utf8(utf8_to_wide("")) == ""); UASSERT(wide_to_utf8(utf8_to_wide("the shovel dug a crumbly node!")) == "the shovel dug a crumbly node!"); } void TestUtilities::testRemoveEscapes() { UASSERT(unescape_enriched<wchar_t>( L"abc\x1bXdef") == L"abcdef"); UASSERT(unescape_enriched<wchar_t>( L"abc\x1b(escaped)def") == L"abcdef"); UASSERT(unescape_enriched<wchar_t>( L"abc\x1b((escaped with parenthesis\\))def") == L"abcdef"); UASSERT(unescape_enriched<wchar_t>( L"abc\x1b(incomplete") == L"abc"); UASSERT(unescape_enriched<wchar_t>( L"escape at the end\x1b") == L"escape at the end"); // Nested escapes not supported UASSERT(unescape_enriched<wchar_t>( L"abc\x1b(outer \x1b(inner escape)escape)def") == L"abcescape)def"); } void TestUtilities::testWrapRows() { UASSERT(wrap_rows("12345678",4) == "1234\n5678"); // test that wrap_rows doesn't wrap inside multibyte sequences { const unsigned char s[] = { 0x2f, 0x68, 0x6f, 0x6d, 0x65, 0x2f, 0x72, 0x61, 0x70, 0x74, 0x6f, 0x72, 0x2f, 0xd1, 0x82, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x82, 0x2f, 0x6d, 0x69, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x74, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x2e, 0x2e, 0}; std::string str((char *)s); UASSERT(utf8_to_wide(wrap_rows(str, 20)) != L"<invalid UTF-8 string>"); }; { const unsigned char s[] = { 0x74, 0x65, 0x73, 0x74, 0x20, 0xd1, 0x82, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x82, 0x20, 0xd1, 0x82, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x82, 0x20, 0xd1, 0x82, 0xd0, 0xb5, 0xd1, 0x81, 0xd1, 0x82, 0}; std::string str((char *)s); UASSERT(utf8_to_wide(wrap_rows(str, 8)) != L"<invalid UTF-8 string>"); } } void TestUtilities::testIsNumber() { UASSERT(is_number("123") == true); UASSERT(is_number("") == false); UASSERT(is_number("123a") == false); } void TestUtilities::testIsPowerOfTwo() { UASSERT(is_power_of_two(0) == false); UASSERT(is_power_of_two(1) == true); UASSERT(is_power_of_two(2) == true); UASSERT(is_power_of_two(3) == false); for (int exponent = 2; exponent <= 31; ++exponent) { UASSERT(is_power_of_two((1 << exponent) - 1) == false); UASSERT(is_power_of_two((1 << exponent)) == true); UASSERT(is_power_of_two((1 << exponent) + 1) == false); } UASSERT(is_power_of_two(U32_MAX) == false); } void TestUtilities::testMyround() { UASSERT(myround(4.6f) == 5); UASSERT(myround(1.2f) == 1); UASSERT(myround(-3.1f) == -3); UASSERT(myround(-6.5f) == -7); } void TestUtilities::testStringJoin() { std::vector<std::string> input; UASSERT(str_join(input, ",") == ""); input.emplace_back("one"); UASSERT(str_join(input, ",") == "one"); input.emplace_back("two"); UASSERT(str_join(input, ",") == "one,two"); input.emplace_back("three"); UASSERT(str_join(input, ",") == "one,two,three"); input[1] = ""; UASSERT(str_join(input, ",") == "one,,three"); input[1] = "two"; UASSERT(str_join(input, " and ") == "one and two and three"); } static bool within(const f32 value1, const f32 value2, const f32 precision) { return std::fabs(value1 - value2) <= precision; } static bool within(const v3f &v1, const v3f &v2, const f32 precision) { return within(v1.X, v2.X, precision) && within(v1.Y, v2.Y, precision) && within(v1.Z, v2.Z, precision); } static bool within(const core::matrix4 &m1, const core::matrix4 &m2, const f32 precision) { const f32 *M1 = m1.pointer(); const f32 *M2 = m2.pointer(); for (int i = 0; i < 16; i++) if (! within(M1[i], M2[i], precision)) return false; return true; } static bool roundTripsDeg(const v3f &v, const f32 precision) { core::matrix4 m; setPitchYawRoll(m, v); return within(v, getPitchYawRoll(m), precision); } void TestUtilities::testEulerConversion() { // This test may fail on non-IEEE systems. // Low tolerance is 4 ulp(1.0) for binary floats with 24 bit mantissa. // (ulp = unit in the last place; ulp(1.0) = 2^-23). const f32 tolL = 4.76837158203125e-7f; // High tolerance is 2 ulp(180.0), needed for numbers in degrees. // ulp(180.0) = 2^-16 const f32 tolH = 3.0517578125e-5f; v3f v1, v2; core::matrix4 m1, m2; const f32 *M1 = m1.pointer(); const f32 *M2 = m2.pointer(); // Check that the radians version and the degrees version // produce the same results. Check also that the conversion // works both ways for these values. v1 = v3f(M_PI/3.0, M_PI/5.0, M_PI/4.0); v2 = v3f(60.0f, 36.0f, 45.0f); setPitchYawRollRad(m1, v1); setPitchYawRoll(m2, v2); UASSERT(within(m1, m2, tolL)); UASSERT(within(getPitchYawRollRad(m1), v1, tolL)); UASSERT(within(getPitchYawRoll(m2), v2, tolH)); // Check the rotation matrix produced. UASSERT(within(M1[0], 0.932004869f, tolL)); UASSERT(within(M1[1], 0.353553385f, tolL)); UASSERT(within(M1[2], 0.0797927827f, tolL)); UASSERT(within(M1[4], -0.21211791f, tolL)); UASSERT(within(M1[5], 0.353553355f, tolL)); UASSERT(within(M1[6], 0.911046684f, tolL)); UASSERT(within(M1[8], 0.293892622f, tolL)); UASSERT(within(M1[9], -0.866025448f, tolL)); UASSERT(within(M1[10], 0.404508471f, tolL)); // Check that the matrix is still homogeneous with no translation UASSERT(M1[3] == 0.0f); UASSERT(M1[7] == 0.0f); UASSERT(M1[11] == 0.0f); UASSERT(M1[12] == 0.0f); UASSERT(M1[13] == 0.0f); UASSERT(M1[14] == 0.0f); UASSERT(M1[15] == 1.0f); UASSERT(M2[3] == 0.0f); UASSERT(M2[7] == 0.0f); UASSERT(M2[11] == 0.0f); UASSERT(M2[12] == 0.0f); UASSERT(M2[13] == 0.0f); UASSERT(M2[14] == 0.0f); UASSERT(M2[15] == 1.0f); // Compare to Irrlicht's results. To be comparable, the // angles must come in a different order and the matrix // elements to compare are different too. m2.setRotationRadians(v3f(v1.Z, v1.X, v1.Y)); UASSERT(within(M1[0], M2[5], tolL)); UASSERT(within(M1[1], M2[6], tolL)); UASSERT(within(M1[2], M2[4], tolL)); UASSERT(within(M1[4], M2[9], tolL)); UASSERT(within(M1[5], M2[10], tolL)); UASSERT(within(M1[6], M2[8], tolL)); UASSERT(within(M1[8], M2[1], tolL)); UASSERT(within(M1[9], M2[2], tolL)); UASSERT(within(M1[10], M2[0], tolL)); // Check that Eulers that produce near gimbal-lock still round-trip UASSERT(roundTripsDeg(v3f(89.9999f, 17.f, 0.f), tolH)); UASSERT(roundTripsDeg(v3f(89.9999f, 0.f, 19.f), tolH)); UASSERT(roundTripsDeg(v3f(89.9999f, 17.f, 19.f), tolH)); // Check that Eulers at an angle > 90 degrees may not round-trip... v1 = v3f(90.00001f, 1.f, 1.f); setPitchYawRoll(m1, v1); v2 = getPitchYawRoll(m1); //UASSERT(within(v1, v2, tolL)); // this is typically false // ... however the rotation matrix is the same for both setPitchYawRoll(m2, v2); UASSERT(within(m1, m2, tolL)); }
pgimeno/minetest
src/unittest/test_utilities.cpp
C++
mit
14,850
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "gamedef.h" #include "voxelalgorithms.h" #include "util/numeric.h" class TestVoxelAlgorithms : public TestBase { public: TestVoxelAlgorithms() { TestManager::registerTestModule(this); } const char *getName() { return "TestVoxelAlgorithms"; } void runTests(IGameDef *gamedef); void testVoxelLineIterator(const NodeDefManager *ndef); }; static TestVoxelAlgorithms g_test_instance; void TestVoxelAlgorithms::runTests(IGameDef *gamedef) { const NodeDefManager *ndef = gamedef->getNodeDefManager(); TEST(testVoxelLineIterator, ndef); } //////////////////////////////////////////////////////////////////////////////// void TestVoxelAlgorithms::testVoxelLineIterator(const NodeDefManager *ndef) { // Test some lines // Do not test lines that start or end on the border of // two voxels as rounding errors can make the test fail! std::vector<core::line3d<f32> > lines; for (f32 x = -9.1; x < 9; x += 3.124) { for (f32 y = -9.2; y < 9; y += 3.123) { for (f32 z = -9.3; z < 9; z += 3.122) { lines.emplace_back(-x, -y, -z, x, y, z); } } } lines.emplace_back(0, 0, 0, 0, 0, 0); // Test every line std::vector<core::line3d<f32> >::iterator it = lines.begin(); for (; it < lines.end(); it++) { core::line3d<f32> l = *it; // Initialize test voxalgo::VoxelLineIterator iterator(l.start, l.getVector()); //Test the first voxel v3s16 start_voxel = floatToInt(l.start, 1); UASSERT(iterator.m_current_node_pos == start_voxel); // Values for testing v3s16 end_voxel = floatToInt(l.end, 1); v3s16 voxel_vector = end_voxel - start_voxel; int nodecount = abs(voxel_vector.X) + abs(voxel_vector.Y) + abs(voxel_vector.Z); int actual_nodecount = 0; v3s16 old_voxel = iterator.m_current_node_pos; while (iterator.hasNext()) { iterator.next(); actual_nodecount++; v3s16 new_voxel = iterator.m_current_node_pos; // This must be a neighbor of the old voxel UASSERTEQ(f32, (new_voxel - old_voxel).getLengthSQ(), 1); // The line must intersect with the voxel v3f voxel_center = intToFloat(iterator.m_current_node_pos, 1); aabb3f box(voxel_center - v3f(0.5, 0.5, 0.5), voxel_center + v3f(0.5, 0.5, 0.5)); UASSERT(box.intersectsWithLine(l)); // Update old voxel old_voxel = new_voxel; } // Test last node UASSERT(iterator.m_current_node_pos == end_voxel); // Test node count UASSERTEQ(int, actual_nodecount, nodecount); } }
pgimeno/minetest
src/unittest/test_voxelalgorithms.cpp
C++
mit
3,214
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include "voxel.h" class TestVoxelArea : public TestBase { public: TestVoxelArea() { TestManager::registerTestModule(this); } const char *getName() { return "TestVoxelArea"; } void runTests(IGameDef *gamedef); void test_addarea(); void test_pad(); void test_volume(); void test_contains_voxelarea(); void test_contains_point(); void test_contains_i(); void test_equal(); void test_plus(); void test_minor(); void test_index_xyz_all_pos(); void test_index_xyz_x_neg(); void test_index_xyz_y_neg(); void test_index_xyz_z_neg(); void test_index_xyz_xy_neg(); void test_index_xyz_xz_neg(); void test_index_xyz_yz_neg(); void test_index_xyz_all_neg(); void test_index_v3s16_all_pos(); void test_index_v3s16_x_neg(); void test_index_v3s16_y_neg(); void test_index_v3s16_z_neg(); void test_index_v3s16_xy_neg(); void test_index_v3s16_xz_neg(); void test_index_v3s16_yz_neg(); void test_index_v3s16_all_neg(); void test_add_x(); void test_add_y(); void test_add_z(); void test_add_p(); }; static TestVoxelArea g_test_instance; void TestVoxelArea::runTests(IGameDef *gamedef) { TEST(test_addarea); TEST(test_pad); TEST(test_volume); TEST(test_contains_voxelarea); TEST(test_contains_point); TEST(test_contains_i); TEST(test_equal); TEST(test_plus); TEST(test_minor); TEST(test_index_xyz_all_pos); TEST(test_index_xyz_x_neg); TEST(test_index_xyz_y_neg); TEST(test_index_xyz_z_neg); TEST(test_index_xyz_xy_neg); TEST(test_index_xyz_xz_neg); TEST(test_index_xyz_yz_neg); TEST(test_index_xyz_all_neg); TEST(test_index_v3s16_all_pos); TEST(test_index_v3s16_x_neg); TEST(test_index_v3s16_y_neg); TEST(test_index_v3s16_z_neg); TEST(test_index_v3s16_xy_neg); TEST(test_index_v3s16_xz_neg); TEST(test_index_v3s16_yz_neg); TEST(test_index_v3s16_all_neg); TEST(test_add_x); TEST(test_add_y); TEST(test_add_z); TEST(test_add_p); } void TestVoxelArea::test_addarea() { VoxelArea v1(v3s16(-1447, 8854, -875), v3s16(-147, -9547, 669)); VoxelArea v2(v3s16(-887, 4445, -5478), v3s16(447, -8779, 4778)); v1.addArea(v2); UASSERT(v1.MinEdge == v3s16(-1447, 4445, -5478)); UASSERT(v1.MaxEdge == v3s16(447, -8779, 4778)); } void TestVoxelArea::test_pad() { VoxelArea v1(v3s16(-1447, 8854, -875), v3s16(-147, -9547, 669)); v1.pad(v3s16(100, 200, 300)); UASSERT(v1.MinEdge == v3s16(-1547, 8654, -1175)); UASSERT(v1.MaxEdge == v3s16(-47, -9347, 969)); } void TestVoxelArea::test_volume() { VoxelArea v1(v3s16(-1337, 447, -789), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v1.getVolume(), -184657133); } void TestVoxelArea::test_contains_voxelarea() { VoxelArea v1(v3s16(-1337, -9547, -789), v3s16(-147, 750, 669)); UASSERTEQ(bool, v1.contains(VoxelArea(v3s16(-200, 10, 10), v3s16(-150, 10, 10))), true); UASSERTEQ(bool, v1.contains(VoxelArea(v3s16(-2550, 10, 10), v3s16(10, 10, 10))), false); UASSERTEQ(bool, v1.contains(VoxelArea(v3s16(-10, 10, 10), v3s16(3500, 10, 10))), false); UASSERTEQ(bool, v1.contains(VoxelArea( v3s16(-800, -400, 669), v3s16(-500, 200, 669))), true); UASSERTEQ(bool, v1.contains(VoxelArea( v3s16(-800, -400, 670), v3s16(-500, 200, 670))), false); } void TestVoxelArea::test_contains_point() { VoxelArea v1(v3s16(-1337, -9547, -789), v3s16(-147, 750, 669)); UASSERTEQ(bool, v1.contains(v3s16(-200, 10, 10)), true); UASSERTEQ(bool, v1.contains(v3s16(-10000, 10, 10)), false); UASSERTEQ(bool, v1.contains(v3s16(-100, 10000, 10)), false); UASSERTEQ(bool, v1.contains(v3s16(-100, 100, 10000)), false); UASSERTEQ(bool, v1.contains(v3s16(-100, 100, -10000)), false); UASSERTEQ(bool, v1.contains(v3s16(10000, 100, 10)), false); } void TestVoxelArea::test_contains_i() { VoxelArea v1(v3s16(-1337, -9547, -789), v3s16(-147, 750, 669)); UASSERTEQ(bool, v1.contains(10), true); UASSERTEQ(bool, v1.contains(v1.getVolume()), false); UASSERTEQ(bool, v1.contains(v1.getVolume() - 1), true); UASSERTEQ(bool, v1.contains(v1.getVolume() + 1), false); UASSERTEQ(bool, v1.contains(-1), false) VoxelArea v2(v3s16(10, 10, 10), v3s16(30, 30, 30)); UASSERTEQ(bool, v2.contains(10), true); UASSERTEQ(bool, v2.contains(0), true); UASSERTEQ(bool, v2.contains(-1), false); } void TestVoxelArea::test_equal() { VoxelArea v1(v3s16(-1337, -9547, -789), v3s16(-147, 750, 669)); UASSERTEQ(bool, v1 == VoxelArea(v3s16(-1337, -9547, -789), v3s16(-147, 750, 669)), true); UASSERTEQ(bool, v1 == VoxelArea(v3s16(0, 0, 0), v3s16(-147, 750, 669)), false); UASSERTEQ(bool, v1 == VoxelArea(v3s16(0, 0, 0), v3s16(-147, 750, 669)), false); UASSERTEQ(bool, v1 == VoxelArea(v3s16(0, 0, 0), v3s16(0, 0, 0)), false); } void TestVoxelArea::test_plus() { VoxelArea v1(v3s16(-10, -10, -10), v3s16(100, 100, 100)); UASSERT(v1 + v3s16(10, 0, 0) == VoxelArea(v3s16(0, -10, -10), v3s16(110, 100, 100))); UASSERT(v1 + v3s16(10, -10, 0) == VoxelArea(v3s16(0, -20, -10), v3s16(110, 90, 100))); UASSERT(v1 + v3s16(0, 0, 35) == VoxelArea(v3s16(-10, -10, 25), v3s16(100, 100, 135))); } void TestVoxelArea::test_minor() { VoxelArea v1(v3s16(-10, -10, -10), v3s16(100, 100, 100)); UASSERT(v1 - v3s16(10, 0, 0) == VoxelArea(v3s16(-20, -10, -10), v3s16(90, 100, 100))); UASSERT(v1 - v3s16(10, -10, 0) == VoxelArea(v3s16(-20, 0, -10), v3s16(90, 110, 100))); UASSERT(v1 - v3s16(0, 0, 35) == VoxelArea(v3s16(-10, -10, -45), v3s16(100, 100, 65))); } void TestVoxelArea::test_index_xyz_all_pos() { VoxelArea v1; UASSERTEQ(s32, v1.index(156, 25, 236), 155); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(156, 25, 236), 1267138774); } void TestVoxelArea::test_index_xyz_x_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(-147, 25, 366), -148); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(-147, 25, 366), -870244825); } void TestVoxelArea::test_index_xyz_y_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(247, -269, 100), 246); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(247, -269, 100), -989760747); } void TestVoxelArea::test_index_xyz_z_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(244, 336, -887), 243); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(244, 336, -887), -191478876); } void TestVoxelArea::test_index_xyz_xy_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(-365, -47, 6978), -366); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(-365, -47, 6978), 1493679101); } void TestVoxelArea::test_index_xyz_yz_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(66, -58, -789), 65); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(66, -58, -789), 1435362734); } void TestVoxelArea::test_index_xyz_xz_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(-36, 589, -992), -37); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(-36, 589, -992), -1934371362); } void TestVoxelArea::test_index_xyz_all_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(-88, -99, -1474), -89); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(-88, -99, -1474), -1343473846); } void TestVoxelArea::test_index_v3s16_all_pos() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(156, 25, 236)), 155); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(156, 25, 236)), 1267138774); } void TestVoxelArea::test_index_v3s16_x_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(-147, 25, 366)), -148); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(-147, 25, 366)), -870244825); } void TestVoxelArea::test_index_v3s16_y_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(247, -269, 100)), 246); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(247, -269, 100)), -989760747); } void TestVoxelArea::test_index_v3s16_z_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(244, 336, -887)), 243); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(244, 336, -887)), -191478876); } void TestVoxelArea::test_index_v3s16_xy_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(-365, -47, 6978)), -366); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(-365, -47, 6978)), 1493679101); } void TestVoxelArea::test_index_v3s16_yz_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(66, -58, -789)), 65); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(66, -58, -789)), 1435362734); } void TestVoxelArea::test_index_v3s16_xz_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(-36, 589, -992)), -37); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(-36, 589, -992)), -1934371362); } void TestVoxelArea::test_index_v3s16_all_neg() { VoxelArea v1; UASSERTEQ(s32, v1.index(v3s16(-88, -99, -1474)), -89); VoxelArea v2(v3s16(756, 8854, -875), v3s16(-147, -9547, 669)); UASSERTEQ(s32, v2.index(v3s16(-88, -99, -1474)), -1343473846); } void TestVoxelArea::test_add_x() { v3s16 extent; u32 i = 4; VoxelArea::add_x(extent, i, 8); UASSERTEQ(u32, i, 12) } void TestVoxelArea::test_add_y() { v3s16 extent(740, 16, 87); u32 i = 8; VoxelArea::add_y(extent, i, 88); UASSERTEQ(u32, i, 65128) } void TestVoxelArea::test_add_z() { v3s16 extent(114, 80, 256); u32 i = 4; VoxelArea::add_z(extent, i, 8); UASSERTEQ(u32, i, 72964) } void TestVoxelArea::test_add_p() { v3s16 extent(33, 14, 742); v3s16 a(15, 12, 369); u32 i = 4; VoxelArea::add_p(extent, i, a); UASSERTEQ(u32, i, 170893) }
pgimeno/minetest
src/unittest/test_voxelarea.cpp
C++
mit
10,547
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "test.h" #include <algorithm> #include "gamedef.h" #include "log.h" #include "voxel.h" class TestVoxelManipulator : public TestBase { public: TestVoxelManipulator() { TestManager::registerTestModule(this); } const char *getName() { return "TestVoxelManipulator"; } void runTests(IGameDef *gamedef); void testVoxelArea(); void testVoxelManipulator(const NodeDefManager *nodedef); }; static TestVoxelManipulator g_test_instance; void TestVoxelManipulator::runTests(IGameDef *gamedef) { TEST(testVoxelArea); TEST(testVoxelManipulator, gamedef->getNodeDefManager()); } //////////////////////////////////////////////////////////////////////////////// void TestVoxelManipulator::testVoxelArea() { VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1)); UASSERT(a.index(0,0,0) == 1*3*3 + 1*3 + 1); UASSERT(a.index(-1,-1,-1) == 0); VoxelArea c(v3s16(-2,-2,-2), v3s16(2,2,2)); // An area that is 1 bigger in x+ and z- VoxelArea d(v3s16(-2,-2,-3), v3s16(3,2,2)); std::list<VoxelArea> aa; d.diff(c, aa); // Correct results std::vector<VoxelArea> results; results.emplace_back(v3s16(-2,-2,-3), v3s16(3,2,-3)); results.emplace_back(v3s16(3,-2,-2), v3s16(3,2,2)); UASSERT(aa.size() == results.size()); infostream<<"Result of diff:"<<std::endl; for (std::list<VoxelArea>::const_iterator it = aa.begin(); it != aa.end(); ++it) { it->print(infostream); infostream << std::endl; std::vector<VoxelArea>::iterator j; j = std::find(results.begin(), results.end(), *it); UASSERT(j != results.end()); results.erase(j); } } void TestVoxelManipulator::testVoxelManipulator(const NodeDefManager *nodedef) { VoxelManipulator v; v.print(infostream, nodedef); infostream << "*** Setting (-1,0,-1)=2 ***" << std::endl; v.setNodeNoRef(v3s16(-1,0,-1), MapNode(t_CONTENT_GRASS)); v.print(infostream, nodedef); UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == t_CONTENT_GRASS); infostream << "*** Reading from inexistent (0,0,-1) ***" << std::endl; EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,0,-1))); v.print(infostream, nodedef); infostream << "*** Adding area ***" << std::endl; VoxelArea a(v3s16(-1,-1,-1), v3s16(1,1,1)); v.addArea(a); v.print(infostream, nodedef); UASSERT(v.getNode(v3s16(-1,0,-1)).getContent() == t_CONTENT_GRASS); EXCEPTION_CHECK(InvalidPositionException, v.getNode(v3s16(0,1,1))); }
pgimeno/minetest
src/unittest/test_voxelmanipulator.cpp
C++
mit
3,151
gameid = minimal
pgimeno/minetest
src/unittest/test_world/world.mt
mt
mit
17
set(UTIL_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/areastore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/auth.cpp ${CMAKE_CURRENT_SOURCE_DIR}/base64.cpp ${CMAKE_CURRENT_SOURCE_DIR}/directiontables.cpp ${CMAKE_CURRENT_SOURCE_DIR}/enriched_string.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ieee_float.cpp ${CMAKE_CURRENT_SOURCE_DIR}/numeric.cpp ${CMAKE_CURRENT_SOURCE_DIR}/pointedthing.cpp ${CMAKE_CURRENT_SOURCE_DIR}/serialize.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sha1.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sha256.c ${CMAKE_CURRENT_SOURCE_DIR}/string.cpp ${CMAKE_CURRENT_SOURCE_DIR}/srp.cpp ${CMAKE_CURRENT_SOURCE_DIR}/timetaker.cpp PARENT_SCOPE)
pgimeno/minetest
src/util/CMakeLists.txt
Text
mit
619
/* Minetest Copyright (C) 2015 est31 <mtest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "util/areastore.h" #include "util/serialize.h" #include "util/container.h" #if USE_SPATIAL #include <spatialindex/SpatialIndex.h> #include <spatialindex/RTree.h> #include <spatialindex/Point.h> #endif #define AST_SMALLER_EQ_AS(p, q) (((p).X <= (q).X) && ((p).Y <= (q).Y) && ((p).Z <= (q).Z)) #define AST_OVERLAPS_IN_DIMENSION(amine, amaxe, b, d) \ (!(((amine).d > (b)->maxedge.d) || ((amaxe).d < (b)->minedge.d))) #define AST_CONTAINS_PT(a, p) (AST_SMALLER_EQ_AS((a)->minedge, (p)) && \ AST_SMALLER_EQ_AS((p), (a)->maxedge)) #define AST_CONTAINS_AREA(amine, amaxe, b) \ (AST_SMALLER_EQ_AS((amine), (b)->minedge) \ && AST_SMALLER_EQ_AS((b)->maxedge, (amaxe))) #define AST_AREAS_OVERLAP(amine, amaxe, b) \ (AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), X) && \ AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Y) && \ AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Z)) AreaStore *AreaStore::getOptimalImplementation() { #if USE_SPATIAL return new SpatialAreaStore(); #else return new VectorAreaStore(); #endif } const Area *AreaStore::getArea(u32 id) const { AreaMap::const_iterator it = areas_map.find(id); if (it == areas_map.end()) return nullptr; return &it->second; } void AreaStore::serialize(std::ostream &os) const { writeU8(os, 0); // Serialisation version // TODO: Compression? writeU16(os, areas_map.size()); for (const auto &it : areas_map) { const Area &a = it.second; writeV3S16(os, a.minedge); writeV3S16(os, a.maxedge); writeU16(os, a.data.size()); os.write(a.data.data(), a.data.size()); } } void AreaStore::deserialize(std::istream &is) { u8 ver = readU8(is); if (ver != 0) throw SerializationError("Unknown AreaStore " "serialization version!"); u16 num_areas = readU16(is); for (u32 i = 0; i < num_areas; ++i) { Area a; a.minedge = readV3S16(is); a.maxedge = readV3S16(is); u16 data_len = readU16(is); char *data = new char[data_len]; is.read(data, data_len); a.data = std::string(data, data_len); insertArea(&a); delete [] data; } } void AreaStore::invalidateCache() { if (m_cache_enabled) { m_res_cache.invalidate(); } } void AreaStore::setCacheParams(bool enabled, u8 block_radius, size_t limit) { m_cache_enabled = enabled; m_cacheblock_radius = MYMAX(block_radius, 16); m_res_cache.setLimit(MYMAX(limit, 20)); invalidateCache(); } void AreaStore::cacheMiss(void *data, const v3s16 &mpos, std::vector<Area *> *dest) { AreaStore *as = (AreaStore *)data; u8 r = as->m_cacheblock_radius; // get the points at the edges of the mapblock v3s16 minedge(mpos.X * r, mpos.Y * r, mpos.Z * r); v3s16 maxedge( minedge.X + r - 1, minedge.Y + r - 1, minedge.Z + r - 1); as->getAreasInArea(dest, minedge, maxedge, true); /* infostream << "Cache miss with " << dest->size() << " areas, between (" << minedge.X << ", " << minedge.Y << ", " << minedge.Z << ") and (" << maxedge.X << ", " << maxedge.Y << ", " << maxedge.Z << ")" << std::endl; // */ } void AreaStore::getAreasForPos(std::vector<Area *> *result, v3s16 pos) { if (m_cache_enabled) { v3s16 mblock = getContainerPos(pos, m_cacheblock_radius); const std::vector<Area *> *pre_list = m_res_cache.lookupCache(mblock); size_t s_p_l = pre_list->size(); for (size_t i = 0; i < s_p_l; i++) { Area *b = (*pre_list)[i]; if (AST_CONTAINS_PT(b, pos)) { result->push_back(b); } } } else { return getAreasForPosImpl(result, pos); } } //// // VectorAreaStore //// bool VectorAreaStore::insertArea(Area *a) { if (a->id == U32_MAX) a->id = getNextId(); std::pair<AreaMap::iterator, bool> res = areas_map.insert(std::make_pair(a->id, *a)); if (!res.second) // ID is not unique return false; m_areas.push_back(&res.first->second); invalidateCache(); return true; } bool VectorAreaStore::removeArea(u32 id) { AreaMap::iterator it = areas_map.find(id); if (it == areas_map.end()) return false; Area *a = &it->second; for (std::vector<Area *>::iterator v_it = m_areas.begin(); v_it != m_areas.end(); ++v_it) { if (*v_it == a) { m_areas.erase(v_it); break; } } areas_map.erase(it); invalidateCache(); return true; } void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos) { for (Area *area : m_areas) { if (AST_CONTAINS_PT(area, pos)) { result->push_back(area); } } } void VectorAreaStore::getAreasInArea(std::vector<Area *> *result, v3s16 minedge, v3s16 maxedge, bool accept_overlap) { for (Area *area : m_areas) { if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, area) : AST_CONTAINS_AREA(minedge, maxedge, area)) { result->push_back(area); } } } #if USE_SPATIAL static inline SpatialIndex::Region get_spatial_region(const v3s16 minedge, const v3s16 maxedge) { const double p_low[] = {(double)minedge.X, (double)minedge.Y, (double)minedge.Z}; const double p_high[] = {(double)maxedge.X, (double)maxedge.Y, (double)maxedge.Z}; return SpatialIndex::Region(p_low, p_high, 3); } static inline SpatialIndex::Point get_spatial_point(const v3s16 pos) { const double p[] = {(double)pos.X, (double)pos.Y, (double)pos.Z}; return SpatialIndex::Point(p, 3); } bool SpatialAreaStore::insertArea(Area *a) { if (a->id == U32_MAX) a->id = getNextId(); if (!areas_map.insert(std::make_pair(a->id, *a)).second) // ID is not unique return false; m_tree->insertData(0, nullptr, get_spatial_region(a->minedge, a->maxedge), a->id); invalidateCache(); return true; } bool SpatialAreaStore::removeArea(u32 id) { std::map<u32, Area>::iterator itr = areas_map.find(id); if (itr != areas_map.end()) { Area *a = &itr->second; bool result = m_tree->deleteData(get_spatial_region(a->minedge, a->maxedge), id); areas_map.erase(itr); invalidateCache(); return result; } else { return false; } } void SpatialAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos) { VectorResultVisitor visitor(result, this); m_tree->pointLocationQuery(get_spatial_point(pos), visitor); } void SpatialAreaStore::getAreasInArea(std::vector<Area *> *result, v3s16 minedge, v3s16 maxedge, bool accept_overlap) { VectorResultVisitor visitor(result, this); if (accept_overlap) { m_tree->intersectsWithQuery(get_spatial_region(minedge, maxedge), visitor); } else { m_tree->containsWhatQuery(get_spatial_region(minedge, maxedge), visitor); } } SpatialAreaStore::~SpatialAreaStore() { delete m_tree; } SpatialAreaStore::SpatialAreaStore() { m_storagemanager = SpatialIndex::StorageManager::createNewMemoryStorageManager(); SpatialIndex::id_type id; m_tree = SpatialIndex::RTree::createNewRTree( *m_storagemanager, .7, // Fill factor 100, // Index capacity 100, // Leaf capacity 3, // dimension :) SpatialIndex::RTree::RV_RSTAR, id); } #endif
pgimeno/minetest
src/util/areastore.cpp
C++
mit
7,580
/* Minetest Copyright (C) 2015 est31 <mtest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" #include "noise.h" // for PcgRandom #include <map> #include <list> #include <vector> #include <istream> #include "util/container.h" #include "util/numeric.h" #ifndef ANDROID #include "cmake_config.h" #endif #if USE_SPATIAL #include <spatialindex/SpatialIndex.h> #include "util/serialize.h" #endif struct Area { Area() = default; Area(const v3s16 &mine, const v3s16 &maxe) : minedge(mine), maxedge(maxe) { sortBoxVerticies(minedge, maxedge); } u32 id = U32_MAX; v3s16 minedge, maxedge; std::string data; }; class AreaStore { public: AreaStore() : m_res_cache(1000, &cacheMiss, this) {} virtual ~AreaStore() = default; static AreaStore *getOptimalImplementation(); virtual void reserve(size_t count) {}; size_t size() const { return areas_map.size(); } /// Add an area to the store. /// Updates the area's ID if it hasn't already been set. /// @return Whether the area insertion was successful. virtual bool insertArea(Area *a) = 0; /// Removes an area from the store by ID. /// @return Whether the area was in the store and removed. virtual bool removeArea(u32 id) = 0; /// Finds areas that the passed position is contained in. /// Stores output in passed vector. void getAreasForPos(std::vector<Area *> *result, v3s16 pos); /// Finds areas that are completely contained inside the area defined /// by the passed edges. If @p accept_overlap is true this finds any /// areas that intersect with the passed area at any point. virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, v3s16 maxedge, bool accept_overlap) = 0; /// Sets cache parameters. void setCacheParams(bool enabled, u8 block_radius, size_t limit); /// Returns a pointer to the area coresponding to the passed ID, /// or NULL if it doesn't exist. const Area *getArea(u32 id) const; /// Serializes the store's areas to a binary ostream. void serialize(std::ostream &is) const; /// Deserializes the Areas from a binary istream. /// This does not currently clear the AreaStore before adding the /// areas, making it possible to deserialize multiple serialized /// AreaStores. void deserialize(std::istream &is); protected: /// Invalidates the getAreasForPos cache. /// Call after adding or removing an area. void invalidateCache(); /// Implementation of getAreasForPos. /// getAreasForPos calls this if the cache is disabled. virtual void getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos) = 0; /// Returns the next area ID and increments it. u32 getNextId() { return m_next_id++; } // Note: This can't be an unordered_map, since all // references would be invalidated on rehash. typedef std::map<u32, Area> AreaMap; AreaMap areas_map; private: /// Called by the cache when a value isn't found in the cache. static void cacheMiss(void *data, const v3s16 &mpos, std::vector<Area *> *dest); bool m_cache_enabled = true; /// Range, in nodes, of the getAreasForPos cache. /// If you modify this, call invalidateCache() u8 m_cacheblock_radius = 64; LRUCache<v3s16, std::vector<Area *> > m_res_cache; u32 m_next_id = 0; }; class VectorAreaStore : public AreaStore { public: virtual void reserve(size_t count) { m_areas.reserve(count); } virtual bool insertArea(Area *a); virtual bool removeArea(u32 id); virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, v3s16 maxedge, bool accept_overlap); protected: virtual void getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos); private: std::vector<Area *> m_areas; }; #if USE_SPATIAL class SpatialAreaStore : public AreaStore { public: SpatialAreaStore(); virtual ~SpatialAreaStore(); virtual bool insertArea(Area *a); virtual bool removeArea(u32 id); virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, v3s16 maxedge, bool accept_overlap); protected: virtual void getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos); private: SpatialIndex::ISpatialIndex *m_tree = nullptr; SpatialIndex::IStorageManager *m_storagemanager = nullptr; class VectorResultVisitor : public SpatialIndex::IVisitor { public: VectorResultVisitor(std::vector<Area *> *result, SpatialAreaStore *store) : m_store(store), m_result(result) {} ~VectorResultVisitor() {} virtual void visitNode(const SpatialIndex::INode &in) {} virtual void visitData(const SpatialIndex::IData &in) { u32 id = in.getIdentifier(); std::map<u32, Area>::iterator itr = m_store->areas_map.find(id); assert(itr != m_store->areas_map.end()); m_result->push_back(&itr->second); } virtual void visitData(std::vector<const SpatialIndex::IData *> &v) { for (size_t i = 0; i < v.size(); i++) visitData(*(v[i])); } private: SpatialAreaStore *m_store = nullptr; std::vector<Area *> *m_result = nullptr; }; }; #endif // USE_SPATIAL
pgimeno/minetest
src/util/areastore.h
C++
mit
5,630
/* Minetest Copyright (C) 2015, 2016 est31 <MTest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <algorithm> #include <string> #include "auth.h" #include "base64.h" #include "sha1.h" #include "srp.h" #include "util/string.h" #include "debug.h" // Get an sha-1 hash of the player's name combined with // the password entered. That's what the server uses as // their password. (Exception : if the password field is // blank, we send a blank password - this is for backwards // compatibility with password-less players). std::string translate_password(const std::string &name, const std::string &password) { if (password.length() == 0) return ""; std::string slt = name + password; SHA1 sha1; sha1.addBytes(slt.c_str(), slt.length()); unsigned char *digest = sha1.getDigest(); std::string pwd = base64_encode(digest, 20); free(digest); return pwd; } // Call lower level SRP code to generate a verifier with the // given pointers. Contains the preparations, call parameters // and error checking common to all srp verifier generation code. // See docs of srp_create_salted_verification_key for more info. static inline void gen_srp_v(const std::string &name, const std::string &password, char **salt, size_t *salt_len, char **bytes_v, size_t *len_v) { std::string n_name = lowercase(name); SRP_Result res = srp_create_salted_verification_key(SRP_SHA256, SRP_NG_2048, n_name.c_str(), (const unsigned char *)password.c_str(), password.size(), (unsigned char **)salt, salt_len, (unsigned char **)bytes_v, len_v, NULL, NULL); FATAL_ERROR_IF(res != SRP_OK, "Couldn't create salted SRP verifier"); } /// Creates a verification key with given salt and password. std::string generate_srp_verifier(const std::string &name, const std::string &password, const std::string &salt) { size_t salt_len = salt.size(); // The API promises us that the salt doesn't // get modified if &salt_ptr isn't NULL. char *salt_ptr = (char *)salt.c_str(); char *bytes_v = nullptr; size_t verifier_len = 0; gen_srp_v(name, password, &salt_ptr, &salt_len, &bytes_v, &verifier_len); std::string verifier = std::string(bytes_v, verifier_len); free(bytes_v); return verifier; } /// Creates a verification key and salt with given password. void generate_srp_verifier_and_salt(const std::string &name, const std::string &password, std::string *verifier, std::string *salt) { char *bytes_v = nullptr; size_t verifier_len; char *salt_ptr = nullptr; size_t salt_len; gen_srp_v(name, password, &salt_ptr, &salt_len, &bytes_v, &verifier_len); *verifier = std::string(bytes_v, verifier_len); *salt = std::string(salt_ptr, salt_len); free(bytes_v); free(salt_ptr); } /// Gets an SRP verifier, generating a salt, /// and encodes it as DB-ready string. std::string get_encoded_srp_verifier(const std::string &name, const std::string &password) { std::string verifier; std::string salt; generate_srp_verifier_and_salt(name, password, &verifier, &salt); return encode_srp_verifier(verifier, salt); } /// Converts the passed SRP verifier into a DB-ready format. std::string encode_srp_verifier(const std::string &verifier, const std::string &salt) { std::ostringstream ret_str; ret_str << "#1#" << base64_encode((unsigned char *)salt.c_str(), salt.size()) << "#" << base64_encode((unsigned char *)verifier.c_str(), verifier.size()); return ret_str.str(); } /// Reads the DB-formatted SRP verifier and gets the verifier /// and salt components. bool decode_srp_verifier_and_salt(const std::string &encoded, std::string *verifier, std::string *salt) { std::vector<std::string> components = str_split(encoded, '#'); if ((components.size() != 4) || (components[1] != "1") // 1 means srp || !base64_is_valid(components[2]) || !base64_is_valid(components[3])) return false; *salt = base64_decode(components[2]); *verifier = base64_decode(components[3]); return true; }
pgimeno/minetest
src/util/auth.cpp
C++
mit
4,581
/* Minetest Copyright (C) 2015, 2016 est31 <MTest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once /// Gets the base64 encoded legacy password db entry. std::string translate_password(const std::string &name, const std::string &password); /// Creates a verification key with given salt and password. std::string generate_srp_verifier(const std::string &name, const std::string &password, const std::string &salt); /// Creates a verification key and salt with given password. void generate_srp_verifier_and_salt(const std::string &name, const std::string &password, std::string *verifier, std::string *salt); /// Gets an SRP verifier, generating a salt, /// and encodes it as DB-ready string. std::string get_encoded_srp_verifier(const std::string &name, const std::string &password); /// Converts the passed SRP verifier into a DB-ready format. std::string encode_srp_verifier(const std::string &verifier, const std::string &salt); /// Reads the DB-formatted SRP verifier and gets the verifier /// and salt components. bool decode_srp_verifier_and_salt(const std::string &encoded, std::string *verifier, std::string *salt);
pgimeno/minetest
src/util/auth.h
C++
mit
1,824
/* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include <iostream> static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } bool base64_is_valid(std::string const& s) { for (char i : s) if (!is_base64(i)) return false; return true; } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; // Don't pad it with = /*while((i++ < 3)) ret += '=';*/ } return ret; } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; }
pgimeno/minetest
src/util/base64.cpp
C++
mit
3,677
/* Minetest Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> bool base64_is_valid(std::string const& s); std::string base64_encode(unsigned char const* , unsigned int len); std::string base64_decode(std::string const& s);
pgimeno/minetest
src/util/base64.h
C++
mit
984
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #define ARRLEN(x) (sizeof(x) / sizeof((x)[0])) #define MYMIN(a, b) ((a) < (b) ? (a) : (b)) #define MYMAX(a, b) ((a) > (b) ? (a) : (b)) // Requires <algorithm> #define CONTAINS(c, v) (std::find((c).begin(), (c).end(), (v)) != (c).end()) // To disable copy constructors and assignment operations for some class // 'Foobar', add the macro DISABLE_CLASS_COPY(Foobar) as a private member. // Note this also disables copying for any classes derived from 'Foobar' as well // as classes having a 'Foobar' member. #define DISABLE_CLASS_COPY(C) \ C(const C &) = delete; \ C &operator=(const C &) = delete; #ifndef _MSC_VER #define UNUSED_ATTRIBUTE __attribute__ ((unused)) #else #define UNUSED_ATTRIBUTE #endif // Fail compilation if condition expr is not met. // Note that 'msg' must follow the format of a valid identifier, e.g. // STATIC_ASSERT(sizeof(foobar_t) == 40), foobar_t_is_wrong_size); #define STATIC_ASSERT(expr, msg) \ UNUSED_ATTRIBUTE typedef char msg[!!(expr) * 2 - 1] // Macros to facilitate writing position vectors to a stream // Usage: // v3s16 pos(1,2,3); // mystream << "message " << PP(pos) << std::endl; #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")" #define PP2(x) "("<<(x).X<<","<<(x).Y<<")"
pgimeno/minetest
src/util/basic_macros.h
C++
mit
2,050
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "exceptions.h" #include "threading/mutex_auto_lock.h" #include "threading/semaphore.h" #include <list> #include <vector> #include <map> #include <set> #include <queue> /* Queue with unique values with fast checking of value existence */ template<typename Value> class UniqueQueue { public: /* Does nothing if value is already queued. Return value: true: value added false: value already exists */ bool push_back(const Value& value) { if (m_set.insert(value).second) { m_queue.push(value); return true; } return false; } void pop_front() { m_set.erase(m_queue.front()); m_queue.pop(); } const Value& front() const { return m_queue.front(); } u32 size() const { return m_queue.size(); } private: std::set<Value> m_set; std::queue<Value> m_queue; }; template<typename Key, typename Value> class MutexedMap { public: MutexedMap() = default; void set(const Key &name, const Value &value) { MutexAutoLock lock(m_mutex); m_values[name] = value; } bool get(const Key &name, Value *result) const { MutexAutoLock lock(m_mutex); typename std::map<Key, Value>::const_iterator n = m_values.find(name); if (n == m_values.end()) return false; if (result) *result = n->second; return true; } std::vector<Value> getValues() const { MutexAutoLock lock(m_mutex); std::vector<Value> result; for (typename std::map<Key, Value>::const_iterator it = m_values.begin(); it != m_values.end(); ++it){ result.push_back(it->second); } return result; } void clear() { m_values.clear(); } private: std::map<Key, Value> m_values; mutable std::mutex m_mutex; }; // Thread-safe Double-ended queue template<typename T> class MutexedQueue { public: template<typename Key, typename U, typename Caller, typename CallerData> friend class RequestQueue; MutexedQueue() = default; bool empty() const { MutexAutoLock lock(m_mutex); return m_queue.empty(); } void push_back(T t) { MutexAutoLock lock(m_mutex); m_queue.push_back(t); m_signal.post(); } /* this version of pop_front returns a empty element of T on timeout. * Make sure default constructor of T creates a recognizable "empty" element */ T pop_frontNoEx(u32 wait_time_max_ms) { if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); T t = m_queue.front(); m_queue.pop_front(); return t; } return T(); } T pop_front(u32 wait_time_max_ms) { if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); T t = m_queue.front(); m_queue.pop_front(); return t; } throw ItemNotFoundException("MutexedQueue: queue is empty"); } T pop_frontNoEx() { m_signal.wait(); MutexAutoLock lock(m_mutex); T t = m_queue.front(); m_queue.pop_front(); return t; } T pop_back(u32 wait_time_max_ms=0) { if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); T t = m_queue.back(); m_queue.pop_back(); return t; } throw ItemNotFoundException("MutexedQueue: queue is empty"); } /* this version of pop_back returns a empty element of T on timeout. * Make sure default constructor of T creates a recognizable "empty" element */ T pop_backNoEx(u32 wait_time_max_ms) { if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); T t = m_queue.back(); m_queue.pop_back(); return t; } return T(); } T pop_backNoEx() { m_signal.wait(); MutexAutoLock lock(m_mutex); T t = m_queue.back(); m_queue.pop_back(); return t; } protected: std::mutex &getMutex() { return m_mutex; } std::deque<T> &getQueue() { return m_queue; } std::deque<T> m_queue; mutable std::mutex m_mutex; Semaphore m_signal; }; template<typename K, typename V> class LRUCache { public: LRUCache(size_t limit, void (*cache_miss)(void *data, const K &key, V *dest), void *data) { m_limit = limit; m_cache_miss = cache_miss; m_cache_miss_data = data; } void setLimit(size_t limit) { m_limit = limit; invalidate(); } void invalidate() { m_map.clear(); m_queue.clear(); } const V *lookupCache(K key) { typename cache_type::iterator it = m_map.find(key); V *ret; if (it != m_map.end()) { // found! cache_entry_t &entry = it->second; ret = &entry.second; // update the usage information m_queue.erase(entry.first); m_queue.push_front(key); entry.first = m_queue.begin(); } else { // cache miss -- enter into cache cache_entry_t &entry = m_map[key]; ret = &entry.second; m_cache_miss(m_cache_miss_data, key, &entry.second); // delete old entries if (m_queue.size() == m_limit) { const K &id = m_queue.back(); m_map.erase(id); m_queue.pop_back(); } m_queue.push_front(key); entry.first = m_queue.begin(); } return ret; } private: void (*m_cache_miss)(void *data, const K &key, V *dest); void *m_cache_miss_data; size_t m_limit; typedef typename std::template pair<typename std::template list<K>::iterator, V> cache_entry_t; typedef std::template map<K, cache_entry_t> cache_type; cache_type m_map; // we can't use std::deque here, because its iterators get invalidated std::list<K> m_queue; };
pgimeno/minetest
src/util/container.h
C++
mit
6,015
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "directiontables.h" const v3s16 g_6dirs[6] = { // +right, +top, +back v3s16( 0, 0, 1), // back v3s16( 0, 1, 0), // top v3s16( 1, 0, 0), // right v3s16( 0, 0,-1), // front v3s16( 0,-1, 0), // bottom v3s16(-1, 0, 0) // left }; const v3s16 g_7dirs[7] = { v3s16(0,0,1), // back v3s16(0,1,0), // top v3s16(1,0,0), // right v3s16(0,0,-1), // front v3s16(0,-1,0), // bottom v3s16(-1,0,0), // left v3s16(0,0,0), // self }; const v3s16 g_26dirs[26] = { // +right, +top, +back v3s16( 0, 0, 1), // back v3s16( 0, 1, 0), // top v3s16( 1, 0, 0), // right v3s16( 0, 0,-1), // front v3s16( 0,-1, 0), // bottom v3s16(-1, 0, 0), // left // 6 v3s16(-1, 1, 0), // top left v3s16( 1, 1, 0), // top right v3s16( 0, 1, 1), // top back v3s16( 0, 1,-1), // top front v3s16(-1, 0, 1), // back left v3s16( 1, 0, 1), // back right v3s16(-1, 0,-1), // front left v3s16( 1, 0,-1), // front right v3s16(-1,-1, 0), // bottom left v3s16( 1,-1, 0), // bottom right v3s16( 0,-1, 1), // bottom back v3s16( 0,-1,-1), // bottom front // 18 v3s16(-1, 1, 1), // top back-left v3s16( 1, 1, 1), // top back-right v3s16(-1, 1,-1), // top front-left v3s16( 1, 1,-1), // top front-right v3s16(-1,-1, 1), // bottom back-left v3s16( 1,-1, 1), // bottom back-right v3s16(-1,-1,-1), // bottom front-left v3s16( 1,-1,-1), // bottom front-right // 26 }; const v3s16 g_27dirs[27] = { // +right, +top, +back v3s16( 0, 0, 1), // back v3s16( 0, 1, 0), // top v3s16( 1, 0, 0), // right v3s16( 0, 0,-1), // front v3s16( 0,-1, 0), // bottom v3s16(-1, 0, 0), // left // 6 v3s16(-1, 1, 0), // top left v3s16( 1, 1, 0), // top right v3s16( 0, 1, 1), // top back v3s16( 0, 1,-1), // top front v3s16(-1, 0, 1), // back left v3s16( 1, 0, 1), // back right v3s16(-1, 0,-1), // front left v3s16( 1, 0,-1), // front right v3s16(-1,-1, 0), // bottom left v3s16( 1,-1, 0), // bottom right v3s16( 0,-1, 1), // bottom back v3s16( 0,-1,-1), // bottom front // 18 v3s16(-1, 1, 1), // top back-left v3s16( 1, 1, 1), // top back-right v3s16(-1, 1,-1), // top front-left v3s16( 1, 1,-1), // top front-right v3s16(-1,-1, 1), // bottom back-left v3s16( 1,-1, 1), // bottom back-right v3s16(-1,-1,-1), // bottom front-left v3s16( 1,-1,-1), // bottom front-right // 26 v3s16(0,0,0), }; const u8 wallmounted_to_facedir[6] = { 20, 0, 16 + 1, 12 + 3, 8, 4 + 2 };
pgimeno/minetest
src/util/directiontables.cpp
C++
mit
3,166
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "irr_v3d.h" extern const v3s16 g_6dirs[6]; extern const v3s16 g_7dirs[7]; extern const v3s16 g_26dirs[26]; // 26th is (0,0,0) extern const v3s16 g_27dirs[27]; extern const u8 wallmounted_to_facedir[6]; /// Direction in the 6D format. g_27dirs contains corresponding vectors. /// Here P means Positive, N stands for Negative. enum Direction6D { // 0 D6D_ZP, D6D_YP, D6D_XP, D6D_ZN, D6D_YN, D6D_XN, // 6 D6D_XN_YP, D6D_XP_YP, D6D_YP_ZP, D6D_YP_ZN, D6D_XN_ZP, D6D_XP_ZP, D6D_XN_ZN, D6D_XP_ZN, D6D_XN_YN, D6D_XP_YN, D6D_YN_ZP, D6D_YN_ZN, // 18 D6D_XN_YP_ZP, D6D_XP_YP_ZP, D6D_XN_YP_ZN, D6D_XP_YP_ZN, D6D_XN_YN_ZP, D6D_XP_YN_ZP, D6D_XN_YN_ZN, D6D_XP_YN_ZN, // 26 D6D, // aliases D6D_BACK = D6D_ZP, D6D_TOP = D6D_YP, D6D_RIGHT = D6D_XP, D6D_FRONT = D6D_ZN, D6D_BOTTOM = D6D_YN, D6D_LEFT = D6D_XN, }; /// Direction in the wallmounted format. /// P is Positive, N is Negative. enum DirectionWallmounted { DWM_YP, DWM_YN, DWM_XP, DWM_XN, DWM_ZP, DWM_ZN, };
pgimeno/minetest
src/util/directiontables.h
C++
mit
1,844
/* Copyright (C) 2013 xyz, Ilya Zhuravlev <whatever@xyz.is> Copyright (C) 2016 Nore, Nathanaël Courant <nore@mesecons.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "enriched_string.h" #include "util/string.h" #include "log.h" using namespace irr::video; EnrichedString::EnrichedString() { clear(); } EnrichedString::EnrichedString(const std::wstring &string, const std::vector<SColor> &colors): m_string(string), m_colors(colors) {} EnrichedString::EnrichedString(const std::wstring &s, const SColor &color) { clear(); addAtEnd(translate_string(s), color); } EnrichedString::EnrichedString(const wchar_t *str, const SColor &color) { clear(); addAtEnd(translate_string(std::wstring(str)), color); } void EnrichedString::operator=(const wchar_t *str) { clear(); addAtEnd(translate_string(std::wstring(str)), SColor(255, 255, 255, 255)); } void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color) { SColor color(initial_color); size_t i = 0; while (i < s.length()) { if (s[i] != L'\x1b') { m_string += s[i]; m_colors.push_back(color); ++i; continue; } ++i; size_t start_index = i; size_t length; if (i == s.length()) { break; } if (s[i] == L'(') { ++i; ++start_index; while (i < s.length() && s[i] != L')') { if (s[i] == L'\\') { ++i; } ++i; } length = i - start_index; ++i; } else { ++i; length = 1; } std::wstring escape_sequence(s, start_index, length); std::vector<std::wstring> parts = split(escape_sequence, L'@'); if (parts[0] == L"c") { if (parts.size() < 2) { continue; } parseColorString(wide_to_utf8(parts[1]), color, true); } else if (parts[0] == L"b") { if (parts.size() < 2) { continue; } parseColorString(wide_to_utf8(parts[1]), m_background, true); m_has_background = true; } } } void EnrichedString::addChar(const EnrichedString &source, size_t i) { m_string += source.m_string[i]; m_colors.push_back(source.m_colors[i]); } void EnrichedString::addCharNoColor(wchar_t c) { m_string += c; if (m_colors.empty()) { m_colors.emplace_back(255, 255, 255, 255); } else { m_colors.push_back(m_colors[m_colors.size() - 1]); } } EnrichedString EnrichedString::operator+(const EnrichedString &other) const { std::vector<SColor> result; result.insert(result.end(), m_colors.begin(), m_colors.end()); result.insert(result.end(), other.m_colors.begin(), other.m_colors.end()); return EnrichedString(m_string + other.m_string, result); } void EnrichedString::operator+=(const EnrichedString &other) { m_string += other.m_string; m_colors.insert(m_colors.end(), other.m_colors.begin(), other.m_colors.end()); } EnrichedString EnrichedString::substr(size_t pos, size_t len) const { if (pos == m_string.length()) { return EnrichedString(); } if (len == std::string::npos || pos + len > m_string.length()) { return EnrichedString( m_string.substr(pos, std::string::npos), std::vector<SColor>(m_colors.begin() + pos, m_colors.end()) ); } return EnrichedString( m_string.substr(pos, len), std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len) ); } const wchar_t *EnrichedString::c_str() const { return m_string.c_str(); } const std::vector<SColor> &EnrichedString::getColors() const { return m_colors; } const std::wstring &EnrichedString::getString() const { return m_string; }
pgimeno/minetest
src/util/enriched_string.cpp
C++
mit
4,081
/* Copyright (C) 2013 xyz, Ilya Zhuravlev <whatever@xyz.is> Copyright (C) 2016 Nore, Nathanaël Courant <nore@mesecons.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <vector> #include <SColor.h> class EnrichedString { public: EnrichedString(); EnrichedString(const std::wstring &s, const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); EnrichedString(const wchar_t *str, const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); EnrichedString(const std::wstring &string, const std::vector<irr::video::SColor> &colors); void operator=(const wchar_t *str); void addAtEnd(const std::wstring &s, const irr::video::SColor &color); // Adds the character source[i] at the end. // An EnrichedString should always be able to be copied // to the end of an existing EnrichedString that way. void addChar(const EnrichedString &source, size_t i); // Adds a single character at the end, without specifying its // color. The color used will be the one from the last character. void addCharNoColor(wchar_t c); EnrichedString substr(size_t pos = 0, size_t len = std::string::npos) const; EnrichedString operator+(const EnrichedString &other) const; void operator+=(const EnrichedString &other); const wchar_t *c_str() const; const std::vector<irr::video::SColor> &getColors() const; const std::wstring &getString() const; inline bool operator==(const EnrichedString &other) const { return (m_string == other.m_string && m_colors == other.m_colors); } inline bool operator!=(const EnrichedString &other) const { return !(*this == other); } inline void clear() { m_string.clear(); m_colors.clear(); m_has_background = false; } inline bool empty() const { return m_string.empty(); } inline size_t size() const { return m_string.size(); } inline bool hasBackground() const { return m_has_background; } inline irr::video::SColor getBackground() const { return m_background; } private: std::wstring m_string; std::vector<irr::video::SColor> m_colors; bool m_has_background = false; irr::video::SColor m_background; };
pgimeno/minetest
src/util/enriched_string.h
C++
mit
2,813
/* Minetest Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> static const char hex_chars[] = "0123456789abcdef"; static inline std::string hex_encode(const char *data, unsigned int data_size) { std::string ret; ret.reserve(data_size * 2); char buf2[3]; buf2[2] = '\0'; for (unsigned int i = 0; i < data_size; i++) { unsigned char c = (unsigned char)data[i]; buf2[0] = hex_chars[(c & 0xf0) >> 4]; buf2[1] = hex_chars[c & 0x0f]; ret.append(buf2); } return ret; } static inline std::string hex_encode(const std::string &data) { return hex_encode(data.c_str(), data.size()); } static inline bool hex_digit_decode(char hexdigit, unsigned char &value) { if (hexdigit >= '0' && hexdigit <= '9') value = hexdigit - '0'; else if (hexdigit >= 'A' && hexdigit <= 'F') value = hexdigit - 'A' + 10; else if (hexdigit >= 'a' && hexdigit <= 'f') value = hexdigit - 'a' + 10; else return false; return true; }
pgimeno/minetest
src/util/hex.h
C++
mit
1,685
/* * Conversion of f32 to IEEE-754 and vice versa. * * © Copyright 2018 Pedro Gimeno Fortea. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ieee_float.h" #include "log.h" #include "porting.h" #include <limits> #include <cmath> // Given an unsigned 32-bit integer representing an IEEE-754 single-precision // float, return the float. f32 u32Tof32Slow(u32 i) { // clang-format off int exp = (i >> 23) & 0xFF; u32 sign = i & 0x80000000UL; u32 imant = i & 0x7FFFFFUL; if (exp == 0xFF) { // Inf/NaN if (imant == 0) { if (std::numeric_limits<f32>::has_infinity) return sign ? -std::numeric_limits<f32>::infinity() : std::numeric_limits<f32>::infinity(); return sign ? std::numeric_limits<f32>::max() : std::numeric_limits<f32>::lowest(); } return std::numeric_limits<f32>::has_quiet_NaN ? std::numeric_limits<f32>::quiet_NaN() : -0.f; } if (!exp) { // Denormal or zero return sign ? -ldexpf((f32)imant, -149) : ldexpf((f32)imant, -149); } return sign ? -ldexpf((f32)(imant | 0x800000UL), exp - 150) : ldexpf((f32)(imant | 0x800000UL), exp - 150); // clang-format on } // Given a float, return an unsigned 32-bit integer representing the f32 // in IEEE-754 single-precision format. u32 f32Tou32Slow(f32 f) { u32 signbit = std::copysign(1.0f, f) == 1.0f ? 0 : 0x80000000UL; if (f == 0.f) return signbit; if (std::isnan(f)) return signbit | 0x7FC00000UL; if (std::isinf(f)) return signbit | 0x7F800000UL; int exp = 0; // silence warning f32 mant = frexpf(f, &exp); u32 imant = (u32)std::floor((signbit ? -16777216.f : 16777216.f) * mant); exp += 126; if (exp <= 0) { // Denormal return signbit | (exp <= -31 ? 0 : imant >> (1 - exp)); } if (exp >= 255) { // Overflow due to the platform having exponents bigger than IEEE ones. // Return signed infinity. return signbit | 0x7F800000UL; } // Regular number return signbit | (exp << 23) | (imant & 0x7FFFFFUL); } // This test needs the following requisites in order to work: // - The float type must be a 32 bits IEEE-754 single-precision float. // - The endianness of f32s and integers must match. FloatType getFloatSerializationType() { // clang-format off const f32 cf = -22220490.f; const u32 cu = 0xCBA98765UL; if (std::numeric_limits<f32>::is_iec559 && sizeof(cf) == 4 && sizeof(cu) == 4 && !memcmp(&cf, &cu, 4)) { // u32Tof32Slow and f32Tou32Slow are not needed, use memcpy return FLOATTYPE_SYSTEM; } // Run quick tests to ensure the custom functions provide acceptable results warningstream << "floatSerialization: f32 and u32 endianness are " "not equal or machine is not IEEE-754 compliant" << std::endl; u32 i; char buf[128]; // NaN checks aren't included in the main loop if (!std::isnan(u32Tof32Slow(0x7FC00000UL))) { porting::mt_snprintf(buf, sizeof(buf), "u32Tof32Slow(0x7FC00000) failed to produce a NaN, actual: %.9g", u32Tof32Slow(0x7FC00000UL)); infostream << buf << std::endl; } if (!std::isnan(u32Tof32Slow(0xFFC00000UL))) { porting::mt_snprintf(buf, sizeof(buf), "u32Tof32Slow(0xFFC00000) failed to produce a NaN, actual: %.9g", u32Tof32Slow(0xFFC00000UL)); infostream << buf << std::endl; } i = f32Tou32Slow(std::numeric_limits<f32>::quiet_NaN()); // check that it corresponds to a NaN encoding if ((i & 0x7F800000UL) != 0x7F800000UL || (i & 0x7FFFFFUL) == 0) { porting::mt_snprintf(buf, sizeof(buf), "f32Tou32Slow(NaN) failed to encode NaN, actual: 0x%X", i); infostream << buf << std::endl; } return FLOATTYPE_SLOW; // clang-format on }
pgimeno/minetest
src/util/ieee_float.cpp
C++
mit
4,593
/* Minetest Copyright (C) 2018 SmallJoker <mk939@ymail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" enum FloatType { FLOATTYPE_UNKNOWN, FLOATTYPE_SLOW, FLOATTYPE_SYSTEM }; f32 u32Tof32Slow(u32 i); u32 f32Tou32Slow(f32 f); FloatType getFloatSerializationType();
pgimeno/minetest
src/util/ieee_float.h
C++
mit
976
/* md32_common.h file used by sha256 implementation */ /* ==================================================================== * Copyright (c) 1999-2007 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * */ /*- * This is a generic 32 bit "collector" for message digest algorithms. * Whenever needed it collects input character stream into chunks of * 32 bit values and invokes a block function that performs actual hash * calculations. * * Porting guide. * * Obligatory macros: * * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN * this macro defines byte order of input stream. * HASH_CBLOCK * size of a unit chunk HASH_BLOCK operates on. * HASH_LONG * has to be at lest 32 bit wide, if it's wider, then * HASH_LONG_LOG2 *has to* be defined along * HASH_CTX * context structure that at least contains following * members: * typedef struct { * ... * HASH_LONG Nl,Nh; * either { * HASH_LONG data[HASH_LBLOCK]; * unsigned char data[HASH_CBLOCK]; * }; * unsigned int num; * ... * } HASH_CTX; * data[] vector is expected to be zeroed upon first call to * HASH_UPDATE. * HASH_UPDATE * name of "Update" function, implemented here. * HASH_TRANSFORM * name of "Transform" function, implemented here. * HASH_FINAL * name of "Final" function, implemented here. * HASH_BLOCK_DATA_ORDER * name of "block" function capable of treating *unaligned* input * message in original (data) byte order, implemented externally. * HASH_MAKE_STRING * macro convering context variables to an ASCII hash string. * * MD5 example: * * #define DATA_ORDER_IS_LITTLE_ENDIAN * * #define HASH_LONG MD5_LONG * #define HASH_LONG_LOG2 MD5_LONG_LOG2 * #define HASH_CTX MD5_CTX * #define HASH_CBLOCK MD5_CBLOCK * #define HASH_UPDATE MD5_Update * #define HASH_TRANSFORM MD5_Transform * #define HASH_FINAL MD5_Final * #define HASH_BLOCK_DATA_ORDER md5_block_data_order * * <appro@fy.chalmers.se> */ #if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN) # error "DATA_ORDER must be defined!" #endif #ifndef HASH_CBLOCK # error "HASH_CBLOCK must be defined!" #endif #ifndef HASH_LONG # error "HASH_LONG must be defined!" #endif #ifndef HASH_CTX # error "HASH_CTX must be defined!" #endif #ifndef HASH_UPDATE # error "HASH_UPDATE must be defined!" #endif #ifndef HASH_TRANSFORM # error "HASH_TRANSFORM must be defined!" #endif #ifndef HASH_FINAL # error "HASH_FINAL must be defined!" #endif #ifndef HASH_BLOCK_DATA_ORDER # error "HASH_BLOCK_DATA_ORDER must be defined!" #endif /* * Engage compiler specific rotate intrinsic function if available. */ #undef ROTATE #ifndef PEDANTIC # if defined(_MSC_VER) # define ROTATE(a,n) _lrotl(a,n) # elif defined(__ICC) # define ROTATE(a,n) _rotl(a,n) # elif defined(__MWERKS__) # if defined(__POWERPC__) # define ROTATE(a,n) __rlwinm(a,n,0,31) # elif defined(__MC68K__) /* Motorola specific tweak. <appro@fy.chalmers.se> */ # define ROTATE(a,n) ( n<24 ? __rol(a,n) : __ror(a,32-n) ) # else # define ROTATE(a,n) __rol(a,n) # endif # elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) /* * Some GNU C inline assembler templates. Note that these are * rotates by *constant* number of bits! But that's exactly * what we need here... * <appro@fy.chalmers.se> */ # if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) # define ROTATE(a,n) ({ register unsigned int ret; \ asm ( \ "roll %1,%0" \ : "=r"(ret) \ : "I"(n), "0"((unsigned int)(a)) \ : "cc"); \ ret; \ }) # elif defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \ defined(__powerpc) || defined(__ppc__) || defined(__powerpc64__) # define ROTATE(a,n) ({ register unsigned int ret; \ asm ( \ "rlwinm %0,%1,%2,0,31" \ : "=r"(ret) \ : "r"(a), "I"(n)); \ ret; \ }) # elif defined(__s390x__) # define ROTATE(a,n) ({ register unsigned int ret; \ asm ("rll %0,%1,%2" \ : "=r"(ret) \ : "r"(a), "I"(n)); \ ret; \ }) # endif # endif #endif /* PEDANTIC */ #ifndef ROTATE # define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n)))) #endif #if defined(DATA_ORDER_IS_BIG_ENDIAN) # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if ((defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)) || \ (defined(__x86_64) || defined(__x86_64__)) # if !defined(B_ENDIAN) /* * This gives ~30-40% performance improvement in SHA-256 compiled * with gcc [on P4]. Well, first macro to be frank. We can pull * this trick on x86* platforms only, because these CPUs can fetch * unaligned data without raising an exception. */ # define HOST_c2l(c,l) ({ unsigned int r=*((const unsigned int *)(c)); \ asm ("bswapl %0":"=r"(r):"0"(r)); \ (c)+=4; (l)=r; }) # define HOST_l2c(l,c) ({ unsigned int r=(l); \ asm ("bswapl %0":"=r"(r):"0"(r)); \ *((unsigned int *)(c))=r; (c)+=4; r; }) # endif # elif defined(__aarch64__) # if defined(__BYTE_ORDER__) # if defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__ # define HOST_c2l(c,l) ({ unsigned int r; \ asm ("rev %w0,%w1" \ :"=r"(r) \ :"r"(*((const unsigned int *)(c))));\ (c)+=4; (l)=r; }) # define HOST_l2c(l,c) ({ unsigned int r; \ asm ("rev %w0,%w1" \ :"=r"(r) \ :"r"((unsigned int)(l)));\ *((unsigned int *)(c))=r; (c)+=4; r; }) # elif defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__ # define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, (l)) # define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, (l)) # endif # endif # endif # endif # if defined(__s390__) || defined(__s390x__) # define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, (l)) # define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, (l)) # endif # endif # ifndef HOST_c2l # define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ l|=(((unsigned long)(*((c)++)))<<16), \ l|=(((unsigned long)(*((c)++)))<< 8), \ l|=(((unsigned long)(*((c)++))) ) ) # endif # ifndef HOST_l2c # define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff), \ l) # endif #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__s390x__) # define HOST_c2l(c,l) ({ asm ("lrv %0,%1" \ :"=d"(l) :"m"(*(const unsigned int *)(c)));\ (c)+=4; (l); }) # define HOST_l2c(l,c) ({ asm ("strv %1,%0" \ :"=m"(*(unsigned int *)(c)) :"d"(l));\ (c)+=4; (l); }) # endif # endif # if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) # ifndef B_ENDIAN /* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */ # define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, l) # define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, l) # endif # endif # endif # ifndef HOST_c2l # define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ l|=(((unsigned long)(*((c)++)))<< 8), \ l|=(((unsigned long)(*((c)++)))<<16), \ l|=(((unsigned long)(*((c)++)))<<24) ) # endif # ifndef HOST_l2c # define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff), \ l) # endif #endif /* * Time for some action:-) */ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) { const unsigned char *data = data_; unsigned char *p; HASH_LONG l; size_t n; if (len == 0) return 1; l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL; /* * 95-05-24 eay Fixed a bug with the overflow handling, thanks to Wei Dai * <weidai@eskimo.com> for pointing it out. */ if (l < c->Nl) /* overflow */ c->Nh++; c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on * 16-bit */ c->Nl = l; n = c->num; if (n != 0) { p = (unsigned char *)c->data; if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) { memcpy(p + n, data, HASH_CBLOCK - n); HASH_BLOCK_DATA_ORDER(c, p, 1); n = HASH_CBLOCK - n; data += n; len -= n; c->num = 0; memset(p, 0, HASH_CBLOCK); /* keep it zeroed */ } else { memcpy(p + n, data, len); c->num += (unsigned int)len; return 1; } } n = len / HASH_CBLOCK; if (n > 0) { HASH_BLOCK_DATA_ORDER(c, data, n); n *= HASH_CBLOCK; data += n; len -= n; } if (len != 0) { p = (unsigned char *)c->data; c->num = (unsigned int)len; memcpy(p, data, len); } return 1; } void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data) { HASH_BLOCK_DATA_ORDER(c, data, 1); } int HASH_FINAL(unsigned char *md, HASH_CTX *c) { unsigned char *p = (unsigned char *)c->data; size_t n = c->num; p[n] = 0x80; /* there is always room for one */ n++; if (n > (HASH_CBLOCK - 8)) { memset(p + n, 0, HASH_CBLOCK - n); n = 0; HASH_BLOCK_DATA_ORDER(c, p, 1); } memset(p + n, 0, HASH_CBLOCK - 8 - n); p += HASH_CBLOCK - 8; #if defined(DATA_ORDER_IS_BIG_ENDIAN) (void)HOST_l2c(c->Nh, p); (void)HOST_l2c(c->Nl, p); #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) (void)HOST_l2c(c->Nl, p); (void)HOST_l2c(c->Nh, p); #endif p -= HASH_CBLOCK; HASH_BLOCK_DATA_ORDER(c, p, 1); c->num = 0; memset(p, 0, HASH_CBLOCK); #ifndef HASH_MAKE_STRING # error "HASH_MAKE_STRING must be defined!" #else HASH_MAKE_STRING(c, md); #endif return 1; } #ifndef MD32_REG_T # if defined(__alpha) || defined(__sparcv9) || defined(__mips) # define MD32_REG_T long /* * This comment was originaly written for MD5, which is why it * discusses A-D. But it basically applies to all 32-bit digests, * which is why it was moved to common header file. * * In case you wonder why A-D are declared as long and not * as MD5_LONG. Doing so results in slight performance * boost on LP64 architectures. The catch is we don't * really care if 32 MSBs of a 64-bit register get polluted * with eventual overflows as we *save* only 32 LSBs in * *either* case. Now declaring 'em long excuses the compiler * from keeping 32 MSBs zeroed resulting in 13% performance * improvement under SPARC Solaris7/64 and 5% under AlphaLinux. * Well, to be honest it should say that this *prevents* * performance degradation. * <appro@fy.chalmers.se> */ # else /* * Above is not absolute and there are LP64 compilers that * generate better code if MD32_REG_T is defined int. The above * pre-processor condition reflects the circumstances under which * the conclusion was made and is subject to further extension. * <appro@fy.chalmers.se> */ # define MD32_REG_T int # endif #endif
pgimeno/minetest
src/util/md32_common.h
C++
mit
16,104
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "numeric.h" #include "log.h" #include "constants.h" // BS, MAP_BLOCKSIZE #include "noise.h" // PseudoRandom, PcgRandom #include "threading/mutex_auto_lock.h" #include <cstring> #include <cmath> // myrand PcgRandom g_pcgrand; u32 myrand() { return g_pcgrand.next(); } void mysrand(unsigned int seed) { g_pcgrand.seed(seed); } void myrand_bytes(void *out, size_t len) { g_pcgrand.bytes(out, len); } int myrand_range(int min, int max) { return g_pcgrand.range(min, max); } /* 64-bit unaligned version of MurmurHash */ u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed) { const u64 m = 0xc6a4a7935bd1e995ULL; const int r = 47; u64 h = seed ^ (len * m); const u8 *data = (const u8 *)key; const u8 *end = data + (len / 8) * 8; while (data != end) { u64 k; memcpy(&k, data, sizeof(u64)); data += sizeof(u64); k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; } const unsigned char *data2 = (const unsigned char *)data; switch (len & 7) { case 7: h ^= (u64)data2[6] << 48; case 6: h ^= (u64)data2[5] << 40; case 5: h ^= (u64)data2[4] << 32; case 4: h ^= (u64)data2[3] << 24; case 3: h ^= (u64)data2[2] << 16; case 2: h ^= (u64)data2[1] << 8; case 1: h ^= (u64)data2[0]; h *= m; } h ^= h >> r; h *= m; h ^= h >> r; return h; } /* blockpos_b: position of block in block coordinates camera_pos: position of camera in nodes camera_dir: an unit vector pointing to camera direction range: viewing range distance_ptr: return location for distance from the camera */ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, f32 range, f32 *distance_ptr) { // Maximum radius of a block. The magic number is // sqrt(3.0) / 2.0 in literal form. static constexpr const f32 block_max_radius = 0.866025403784f * MAP_BLOCKSIZE * BS; v3s16 blockpos_nodes = blockpos_b * MAP_BLOCKSIZE; // Block center position v3f blockpos( ((float)blockpos_nodes.X + MAP_BLOCKSIZE/2) * BS, ((float)blockpos_nodes.Y + MAP_BLOCKSIZE/2) * BS, ((float)blockpos_nodes.Z + MAP_BLOCKSIZE/2) * BS ); // Block position relative to camera v3f blockpos_relative = blockpos - camera_pos; // Total distance f32 d = MYMAX(0, blockpos_relative.getLength() - block_max_radius); if (distance_ptr) *distance_ptr = d; // If block is far away, it's not in sight if (d > range) return false; // If block is (nearly) touching the camera, don't // bother validating further (that is, render it anyway) if (d == 0) return true; // Adjust camera position, for purposes of computing the angle, // such that a block that has any portion visible with the // current camera position will have the center visible at the // adjusted postion f32 adjdist = block_max_radius / cos((M_PI - camera_fov) / 2); // Block position relative to adjusted camera v3f blockpos_adj = blockpos - (camera_pos - camera_dir * adjdist); // Distance in camera direction (+=front, -=back) f32 dforward = blockpos_adj.dotProduct(camera_dir); // Cosine of the angle between the camera direction // and the block direction (camera_dir is an unit vector) f32 cosangle = dforward / blockpos_adj.getLength(); // If block is not in the field of view, skip it // HOTFIX: use sligthly increased angle (+10%) to fix too agressive // culling. Somebody have to find out whats wrong with the math here. // Previous value: camera_fov / 2 if (cosangle < std::cos(camera_fov * 0.55f)) return false; return true; } s16 adjustDist(s16 dist, float zoom_fov) { // 1.775 ~= 72 * PI / 180 * 1.4, the default FOV on the client. // The heuristic threshold for zooming is half of that. static constexpr const float threshold_fov = 1.775f / 2.0f; if (zoom_fov < 0.001f || zoom_fov > threshold_fov) return dist; return std::round(dist * std::cbrt((1.0f - std::cos(threshold_fov)) / (1.0f - std::cos(zoom_fov / 2.0f)))); } void setPitchYawRollRad(core::matrix4 &m, const v3f &rot) { f64 a1 = rot.Z, a2 = rot.X, a3 = rot.Y; f64 c1 = cos(a1), s1 = sin(a1); f64 c2 = cos(a2), s2 = sin(a2); f64 c3 = cos(a3), s3 = sin(a3); f32 *M = m.pointer(); M[0] = s1 * s2 * s3 + c1 * c3; M[1] = s1 * c2; M[2] = s1 * s2 * c3 - c1 * s3; M[4] = c1 * s2 * s3 - s1 * c3; M[5] = c1 * c2; M[6] = c1 * s2 * c3 + s1 * s3; M[8] = c2 * s3; M[9] = -s2; M[10] = c2 * c3; } v3f getPitchYawRollRad(const core::matrix4 &m) { const f32 *M = m.pointer(); f64 a1 = atan2(M[1], M[5]); f32 c2 = std::sqrt((f64)M[10]*M[10] + (f64)M[8]*M[8]); f32 a2 = atan2f(-M[9], c2); f64 c1 = cos(a1); f64 s1 = sin(a1); f32 a3 = atan2f(s1*M[6] - c1*M[2], c1*M[0] - s1*M[4]); return v3f(a2, a3, a1); }
pgimeno/minetest
src/util/numeric.cpp
C++
mit
5,451
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "basic_macros.h" #include "irrlichttypes.h" #include "irr_v2d.h" #include "irr_v3d.h" #include "irr_aabb3d.h" #include <matrix4.h> #define rangelim(d, min, max) ((d) < (min) ? (min) : ((d) > (max) ? (max) : (d))) #define myfloor(x) ((x) < 0.0 ? (int)(x) - 1 : (int)(x)) // The naive swap performs better than the xor version #define SWAP(t, x, y) do { \ t temp = x; \ x = y; \ y = temp; \ } while (0) inline s16 getContainerPos(s16 p, s16 d) { return (p >= 0 ? p : p - d + 1) / d; } inline v2s16 getContainerPos(v2s16 p, s16 d) { return v2s16( getContainerPos(p.X, d), getContainerPos(p.Y, d) ); } inline v3s16 getContainerPos(v3s16 p, s16 d) { return v3s16( getContainerPos(p.X, d), getContainerPos(p.Y, d), getContainerPos(p.Z, d) ); } inline v2s16 getContainerPos(v2s16 p, v2s16 d) { return v2s16( getContainerPos(p.X, d.X), getContainerPos(p.Y, d.Y) ); } inline v3s16 getContainerPos(v3s16 p, v3s16 d) { return v3s16( getContainerPos(p.X, d.X), getContainerPos(p.Y, d.Y), getContainerPos(p.Z, d.Z) ); } inline void getContainerPosWithOffset(s16 p, s16 d, s16 &container, s16 &offset) { container = (p >= 0 ? p : p - d + 1) / d; offset = p & (d - 1); } inline void getContainerPosWithOffset(const v2s16 &p, s16 d, v2s16 &container, v2s16 &offset) { getContainerPosWithOffset(p.X, d, container.X, offset.X); getContainerPosWithOffset(p.Y, d, container.Y, offset.Y); } inline void getContainerPosWithOffset(const v3s16 &p, s16 d, v3s16 &container, v3s16 &offset) { getContainerPosWithOffset(p.X, d, container.X, offset.X); getContainerPosWithOffset(p.Y, d, container.Y, offset.Y); getContainerPosWithOffset(p.Z, d, container.Z, offset.Z); } inline bool isInArea(v3s16 p, s16 d) { return ( p.X >= 0 && p.X < d && p.Y >= 0 && p.Y < d && p.Z >= 0 && p.Z < d ); } inline bool isInArea(v2s16 p, s16 d) { return ( p.X >= 0 && p.X < d && p.Y >= 0 && p.Y < d ); } inline bool isInArea(v3s16 p, v3s16 d) { return ( p.X >= 0 && p.X < d.X && p.Y >= 0 && p.Y < d.Y && p.Z >= 0 && p.Z < d.Z ); } inline void sortBoxVerticies(v3s16 &p1, v3s16 &p2) { if (p1.X > p2.X) SWAP(s16, p1.X, p2.X); if (p1.Y > p2.Y) SWAP(s16, p1.Y, p2.Y); if (p1.Z > p2.Z) SWAP(s16, p1.Z, p2.Z); } inline v3s16 componentwise_min(const v3s16 &a, const v3s16 &b) { return v3s16(MYMIN(a.X, b.X), MYMIN(a.Y, b.Y), MYMIN(a.Z, b.Z)); } inline v3s16 componentwise_max(const v3s16 &a, const v3s16 &b) { return v3s16(MYMAX(a.X, b.X), MYMAX(a.Y, b.Y), MYMAX(a.Z, b.Z)); } /** Returns \p f wrapped to the range [-360, 360] * * See test.cpp for example cases. * * \note This is also used in cases where degrees wrapped to the range [0, 360] * is innapropriate (e.g. pitch needs negative values) * * \internal functionally equivalent -- although precision may vary slightly -- * to fmodf((f), 360.0f) however empirical tests indicate that this approach is * faster. */ inline float modulo360f(float f) { int sign; int whole; float fraction; if (f < 0) { f = -f; sign = -1; } else { sign = 1; } whole = f; fraction = f - whole; whole %= 360; return sign * (whole + fraction); } /** Returns \p f wrapped to the range [0, 360] */ inline float wrapDegrees_0_360(float f) { float value = modulo360f(f); return value < 0 ? value + 360 : value; } /** Returns \p v3f wrapped to the range [0, 360] */ inline v3f wrapDegrees_0_360_v3f(v3f v) { v3f value_v3f; value_v3f.X = modulo360f(v.X); value_v3f.Y = modulo360f(v.Y); value_v3f.Z = modulo360f(v.Z); // Now that values are wrapped, use to get values for certain ranges value_v3f.X = value_v3f.X < 0 ? value_v3f.X + 360 : value_v3f.X; value_v3f.Y = value_v3f.Y < 0 ? value_v3f.Y + 360 : value_v3f.Y; value_v3f.Z = value_v3f.Z < 0 ? value_v3f.Z + 360 : value_v3f.Z; return value_v3f; } /** Returns \p f wrapped to the range [-180, 180] */ inline float wrapDegrees_180(float f) { float value = modulo360f(f + 180); if (value < 0) value += 360; return value - 180; } /* Pseudo-random (VC++ rand() sucks) */ #define MYRAND_RANGE 0xffffffff u32 myrand(); void mysrand(unsigned int seed); void myrand_bytes(void *out, size_t len); int myrand_range(int min, int max); /* Miscellaneous functions */ inline u32 get_bits(u32 x, u32 pos, u32 len) { u32 mask = (1 << len) - 1; return (x >> pos) & mask; } inline void set_bits(u32 *x, u32 pos, u32 len, u32 val) { u32 mask = (1 << len) - 1; *x &= ~(mask << pos); *x |= (val & mask) << pos; } inline u32 calc_parity(u32 v) { v ^= v >> 16; v ^= v >> 8; v ^= v >> 4; v &= 0xf; return (0x6996 >> v) & 1; } u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed); bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, f32 range, f32 *distance_ptr=NULL); s16 adjustDist(s16 dist, float zoom_fov); /* Returns nearest 32-bit integer for given floating point number. <cmath> and <math.h> in VC++ don't provide round(). */ inline s32 myround(f32 f) { return (s32)(f < 0.f ? (f - 0.5f) : (f + 0.5f)); } inline constexpr f32 sqr(f32 f) { return f * f; } /* Returns integer position of node in given floating point position */ inline v3s16 floatToInt(v3f p, f32 d) { return v3s16( (p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); } /* Returns integer position of node in given double precision position */ inline v3s16 doubleToInt(v3d p, double d) { return v3s16( (p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); } /* Returns floating point position of node in given integer position */ inline v3f intToFloat(v3s16 p, f32 d) { return v3f( (f32)p.X * d, (f32)p.Y * d, (f32)p.Z * d ); } // Random helper. Usually d=BS inline aabb3f getNodeBox(v3s16 p, float d) { return aabb3f( (float)p.X * d - 0.5f * d, (float)p.Y * d - 0.5f * d, (float)p.Z * d - 0.5f * d, (float)p.X * d + 0.5f * d, (float)p.Y * d + 0.5f * d, (float)p.Z * d + 0.5f * d ); } class IntervalLimiter { public: IntervalLimiter() = default; /* dtime: time from last call to this method wanted_interval: interval wanted return value: true: action should be skipped false: action should be done */ bool step(float dtime, float wanted_interval) { m_accumulator += dtime; if (m_accumulator < wanted_interval) return false; m_accumulator -= wanted_interval; return true; } private: float m_accumulator = 0.0f; }; /* Splits a list into "pages". For example, the list [1,2,3,4,5] split into two pages would be [1,2,3],[4,5]. This function computes the minimum and maximum indices of a single page. length: Length of the list that should be split page: Page number, 1 <= page <= pagecount pagecount: The number of pages, >= 1 minindex: Receives the minimum index (inclusive). maxindex: Receives the maximum index (exclusive). Ensures 0 <= minindex <= maxindex <= length. */ inline void paging(u32 length, u32 page, u32 pagecount, u32 &minindex, u32 &maxindex) { if (length < 1 || pagecount < 1 || page < 1 || page > pagecount) { // Special cases or invalid parameters minindex = maxindex = 0; } else if(pagecount <= length) { // Less pages than entries in the list: // Each page contains at least one entry minindex = (length * (page-1) + (pagecount-1)) / pagecount; maxindex = (length * page + (pagecount-1)) / pagecount; } else { // More pages than entries in the list: // Make sure the empty pages are at the end if (page < length) { minindex = page-1; maxindex = page; } else { minindex = 0; maxindex = 0; } } } inline float cycle_shift(float value, float by = 0, float max = 1) { if (value + by < 0) return value + by + max; if (value + by > max) return value + by - max; return value + by; } inline bool is_power_of_two(u32 n) { return n != 0 && (n & (n - 1)) == 0; } // Compute next-higher power of 2 efficiently, e.g. for power-of-2 texture sizes. // Public Domain: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 inline u32 npot2(u32 orig) { orig--; orig |= orig >> 1; orig |= orig >> 2; orig |= orig >> 4; orig |= orig >> 8; orig |= orig >> 16; return orig + 1; } // Gradual steps towards the target value in a wrapped (circular) system // using the shorter of both ways template<typename T> inline void wrappedApproachShortest(T &current, const T target, const T stepsize, const T maximum) { T delta = target - current; if (delta < 0) delta += maximum; if (delta > stepsize && maximum - delta > stepsize) { current += (delta < maximum / 2) ? stepsize : -stepsize; if (current >= maximum) current -= maximum; } else { current = target; } } void setPitchYawRollRad(core::matrix4 &m, const v3f &rot); inline void setPitchYawRoll(core::matrix4 &m, const v3f &rot) { setPitchYawRollRad(m, rot * core::DEGTORAD64); } v3f getPitchYawRollRad(const core::matrix4 &m); inline v3f getPitchYawRoll(const core::matrix4 &m) { return getPitchYawRollRad(m) * core::RADTODEG64; }
pgimeno/minetest
src/util/numeric.h
C++
mit
9,925
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "pointedthing.h" #include "serialize.h" #include "exceptions.h" #include <sstream> PointedThing::PointedThing(const v3s16 &under, const v3s16 &above, const v3s16 &real_under, const v3f &point, const v3s16 &normal, u16 box_id, f32 distSq): type(POINTEDTHING_NODE), node_undersurface(under), node_abovesurface(above), node_real_undersurface(real_under), intersection_point(point), intersection_normal(normal), box_id(box_id), distanceSq(distSq) {} PointedThing::PointedThing(s16 id, const v3f &point, const v3s16 &normal, f32 distSq) : type(POINTEDTHING_OBJECT), object_id(id), intersection_point(point), intersection_normal(normal), distanceSq(distSq) {} std::string PointedThing::dump() const { std::ostringstream os(std::ios::binary); switch (type) { case POINTEDTHING_NOTHING: os << "[nothing]"; break; case POINTEDTHING_NODE: { const v3s16 &u = node_undersurface; const v3s16 &a = node_abovesurface; os << "[node under=" << u.X << "," << u.Y << "," << u.Z << " above=" << a.X << "," << a.Y << "," << a.Z << "]"; } break; case POINTEDTHING_OBJECT: os << "[object " << object_id << "]"; break; default: os << "[unknown PointedThing]"; } return os.str(); } void PointedThing::serialize(std::ostream &os) const { writeU8(os, 0); // version writeU8(os, (u8)type); switch (type) { case POINTEDTHING_NOTHING: break; case POINTEDTHING_NODE: writeV3S16(os, node_undersurface); writeV3S16(os, node_abovesurface); break; case POINTEDTHING_OBJECT: writeS16(os, object_id); break; } } void PointedThing::deSerialize(std::istream &is) { int version = readU8(is); if (version != 0) throw SerializationError( "unsupported PointedThing version"); type = (PointedThingType) readU8(is); switch (type) { case POINTEDTHING_NOTHING: break; case POINTEDTHING_NODE: node_undersurface = readV3S16(is); node_abovesurface = readV3S16(is); break; case POINTEDTHING_OBJECT: object_id = readS16(is); break; default: throw SerializationError("unsupported PointedThingType"); } } bool PointedThing::operator==(const PointedThing &pt2) const { if (type != pt2.type) { return false; } if (type == POINTEDTHING_NODE) { if ((node_undersurface != pt2.node_undersurface) || (node_abovesurface != pt2.node_abovesurface) || (node_real_undersurface != pt2.node_real_undersurface)) return false; } else if (type == POINTEDTHING_OBJECT) { if (object_id != pt2.object_id) return false; } return true; } bool PointedThing::operator!=(const PointedThing &pt2) const { return !(*this == pt2); }
pgimeno/minetest
src/util/pointedthing.cpp
C++
mit
3,381
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "irr_v3d.h" #include <iostream> #include <string> enum PointedThingType { POINTEDTHING_NOTHING, POINTEDTHING_NODE, POINTEDTHING_OBJECT }; //! An active object or node which is selected by a ray on the map. struct PointedThing { //! The type of the pointed object. PointedThingType type = POINTEDTHING_NOTHING; /*! * Only valid if type is POINTEDTHING_NODE. * The coordinates of the node which owns the * nodebox that the ray hits first. * This may differ from node_real_undersurface if * a nodebox exceeds the limits of its node. */ v3s16 node_undersurface; /*! * Only valid if type is POINTEDTHING_NODE. * The coordinates of the last node the ray intersects * before node_undersurface. Same as node_undersurface * if the ray starts in a nodebox. */ v3s16 node_abovesurface; /*! * Only valid if type is POINTEDTHING_NODE. * The coordinates of the node which contains the * point of the collision and the nodebox of the node. */ v3s16 node_real_undersurface; /*! * Only valid if type is POINTEDTHING_OBJECT. * The ID of the object the ray hit. */ s16 object_id = -1; /*! * Only valid if type isn't POINTEDTHING_NONE. * First intersection point of the ray and the nodebox in irrlicht * coordinates. */ v3f intersection_point; /*! * Only valid if type isn't POINTEDTHING_NONE. * Normal vector of the intersection. * This is perpendicular to the face the ray hits, * points outside of the box and it's length is 1. */ v3s16 intersection_normal; /*! * Only valid if type isn't POINTEDTHING_NONE. * Indicates which selection box is selected, if there are more of them. */ u16 box_id = 0; /*! * Square of the distance between the pointing * ray's start point and the intersection point in irrlicht coordinates. */ f32 distanceSq = 0; //! Constructor for POINTEDTHING_NOTHING PointedThing() = default; //! Constructor for POINTEDTHING_NODE PointedThing(const v3s16 &under, const v3s16 &above, const v3s16 &real_under, const v3f &point, const v3s16 &normal, u16 box_id, f32 distSq); //! Constructor for POINTEDTHING_OBJECT PointedThing(s16 id, const v3f &point, const v3s16 &normal, f32 distSq); std::string dump() const; void serialize(std::ostream &os) const; void deSerialize(std::istream &is); /*! * This function ignores the intersection point and normal. */ bool operator==(const PointedThing &pt2) const; bool operator!=(const PointedThing &pt2) const; };
pgimeno/minetest
src/util/pointedthing.h
C++
mit
3,304
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "debug.h" // For assert() #include <cstring> template <typename T> class Buffer { public: Buffer() { m_size = 0; data = NULL; } Buffer(unsigned int size) { m_size = size; if(size != 0) data = new T[size]; else data = NULL; } Buffer(const Buffer &buffer) { m_size = buffer.m_size; if(m_size != 0) { data = new T[buffer.m_size]; memcpy(data, buffer.data, buffer.m_size); } else data = NULL; } Buffer(const T *t, unsigned int size) { m_size = size; if(size != 0) { data = new T[size]; memcpy(data, t, size); } else data = NULL; } ~Buffer() { drop(); } Buffer& operator=(const Buffer &buffer) { if(this == &buffer) return *this; drop(); m_size = buffer.m_size; if(m_size != 0) { data = new T[buffer.m_size]; memcpy(data, buffer.data, buffer.m_size); } else data = NULL; return *this; } T & operator[](unsigned int i) const { return data[i]; } T * operator*() const { return data; } unsigned int getSize() const { return m_size; } private: void drop() { delete[] data; } T *data; unsigned int m_size; }; /************************************************ * !!! W A R N I N G !!! * * * * This smart pointer class is NOT thread safe. * * ONLY use in a single-threaded context! * * * ************************************************/ template <typename T> class SharedBuffer { public: SharedBuffer() { m_size = 0; data = NULL; refcount = new unsigned int; (*refcount) = 1; } SharedBuffer(unsigned int size) { m_size = size; if(m_size != 0) data = new T[m_size]; else data = NULL; refcount = new unsigned int; memset(data,0,sizeof(T)*m_size); (*refcount) = 1; } SharedBuffer(const SharedBuffer &buffer) { m_size = buffer.m_size; data = buffer.data; refcount = buffer.refcount; (*refcount)++; } SharedBuffer & operator=(const SharedBuffer & buffer) { if(this == &buffer) return *this; drop(); m_size = buffer.m_size; data = buffer.data; refcount = buffer.refcount; (*refcount)++; return *this; } /* Copies whole buffer */ SharedBuffer(const T *t, unsigned int size) { m_size = size; if(m_size != 0) { data = new T[m_size]; memcpy(data, t, m_size); } else data = NULL; refcount = new unsigned int; (*refcount) = 1; } /* Copies whole buffer */ SharedBuffer(const Buffer<T> &buffer) { m_size = buffer.getSize(); if (m_size != 0) { data = new T[m_size]; memcpy(data, *buffer, buffer.getSize()); } else data = NULL; refcount = new unsigned int; (*refcount) = 1; } ~SharedBuffer() { drop(); } T & operator[](unsigned int i) const { assert(i < m_size); return data[i]; } T * operator*() const { return data; } unsigned int getSize() const { return m_size; } operator Buffer<T>() const { return Buffer<T>(data, m_size); } private: void drop() { assert((*refcount) > 0); (*refcount)--; if(*refcount == 0) { delete[] data; delete refcount; } } T *data; unsigned int m_size; unsigned int *refcount; };
pgimeno/minetest
src/util/pointer.h
C++
mit
4,043
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "serialize.h" #include "pointer.h" #include "porting.h" #include "util/string.h" #include "exceptions.h" #include "irrlichttypes.h" #include <sstream> #include <iomanip> #include <vector> FloatType g_serialize_f32_type = FLOATTYPE_UNKNOWN; //// //// BufReader //// bool BufReader::getStringNoEx(std::string *val) { u16 num_chars; if (!getU16NoEx(&num_chars)) return false; if (pos + num_chars > size) { pos -= sizeof(num_chars); return false; } val->assign((const char *)data + pos, num_chars); pos += num_chars; return true; } bool BufReader::getWideStringNoEx(std::wstring *val) { u16 num_chars; if (!getU16NoEx(&num_chars)) return false; if (pos + num_chars * 2 > size) { pos -= sizeof(num_chars); return false; } for (size_t i = 0; i != num_chars; i++) { val->push_back(readU16(data + pos)); pos += 2; } return true; } bool BufReader::getLongStringNoEx(std::string *val) { u32 num_chars; if (!getU32NoEx(&num_chars)) return false; if (pos + num_chars > size) { pos -= sizeof(num_chars); return false; } val->assign((const char *)data + pos, num_chars); pos += num_chars; return true; } bool BufReader::getRawDataNoEx(void *val, size_t len) { if (pos + len > size) return false; memcpy(val, data + pos, len); pos += len; return true; } //// //// String //// std::string serializeString(const std::string &plain) { std::string s; char buf[2]; if (plain.size() > STRING_MAX_LEN) throw SerializationError("String too long for serializeString"); writeU16((u8 *)&buf[0], plain.size()); s.append(buf, 2); s.append(plain); return s; } std::string deSerializeString(std::istream &is) { std::string s; char buf[2]; is.read(buf, 2); if (is.gcount() != 2) throw SerializationError("deSerializeString: size not read"); u16 s_size = readU16((u8 *)buf); if (s_size == 0) return s; Buffer<char> buf2(s_size); is.read(&buf2[0], s_size); if (is.gcount() != s_size) throw SerializationError("deSerializeString: couldn't read all chars"); s.reserve(s_size); s.append(&buf2[0], s_size); return s; } //// //// Wide String //// std::string serializeWideString(const std::wstring &plain) { std::string s; char buf[2]; if (plain.size() > WIDE_STRING_MAX_LEN) throw SerializationError("String too long for serializeWideString"); writeU16((u8 *)buf, plain.size()); s.append(buf, 2); for (wchar_t i : plain) { writeU16((u8 *)buf, i); s.append(buf, 2); } return s; } std::wstring deSerializeWideString(std::istream &is) { std::wstring s; char buf[2]; is.read(buf, 2); if (is.gcount() != 2) throw SerializationError("deSerializeWideString: size not read"); u16 s_size = readU16((u8 *)buf); if (s_size == 0) return s; s.reserve(s_size); for (u32 i = 0; i < s_size; i++) { is.read(&buf[0], 2); if (is.gcount() != 2) { throw SerializationError( "deSerializeWideString: couldn't read all chars"); } wchar_t c16 = readU16((u8 *)buf); s.append(&c16, 1); } return s; } //// //// Long String //// std::string serializeLongString(const std::string &plain) { char buf[4]; if (plain.size() > LONG_STRING_MAX_LEN) throw SerializationError("String too long for serializeLongString"); writeU32((u8*)&buf[0], plain.size()); std::string s; s.append(buf, 4); s.append(plain); return s; } std::string deSerializeLongString(std::istream &is) { std::string s; char buf[4]; is.read(buf, 4); if (is.gcount() != 4) throw SerializationError("deSerializeLongString: size not read"); u32 s_size = readU32((u8 *)buf); if (s_size == 0) return s; // We don't really want a remote attacker to force us to allocate 4GB... if (s_size > LONG_STRING_MAX_LEN) { throw SerializationError("deSerializeLongString: " "string too long: " + itos(s_size) + " bytes"); } Buffer<char> buf2(s_size); is.read(&buf2[0], s_size); if ((u32)is.gcount() != s_size) throw SerializationError("deSerializeLongString: couldn't read all chars"); s.reserve(s_size); s.append(&buf2[0], s_size); return s; } //// //// JSON //// std::string serializeJsonString(const std::string &plain) { std::ostringstream os(std::ios::binary); os << "\""; for (char c : plain) { switch (c) { case '"': os << "\\\""; break; case '\\': os << "\\\\"; break; case '/': os << "\\/"; break; case '\b': os << "\\b"; break; case '\f': os << "\\f"; break; case '\n': os << "\\n"; break; case '\r': os << "\\r"; break; case '\t': os << "\\t"; break; default: { if (c >= 32 && c <= 126) { os << c; } else { u32 cnum = (u8)c; os << "\\u" << std::hex << std::setw(4) << std::setfill('0') << cnum; } break; } } } os << "\""; return os.str(); } std::string deSerializeJsonString(std::istream &is) { std::ostringstream os(std::ios::binary); char c, c2; // Parse initial doublequote is >> c; if (c != '"') throw SerializationError("JSON string must start with doublequote"); // Parse characters for (;;) { c = is.get(); if (is.eof()) throw SerializationError("JSON string ended prematurely"); if (c == '"') { return os.str(); } if (c == '\\') { c2 = is.get(); if (is.eof()) throw SerializationError("JSON string ended prematurely"); switch (c2) { case 'b': os << '\b'; break; case 'f': os << '\f'; break; case 'n': os << '\n'; break; case 'r': os << '\r'; break; case 't': os << '\t'; break; case 'u': { int hexnumber; char hexdigits[4 + 1]; is.read(hexdigits, 4); if (is.eof()) throw SerializationError("JSON string ended prematurely"); hexdigits[4] = 0; std::istringstream tmp_is(hexdigits, std::ios::binary); tmp_is >> std::hex >> hexnumber; os << (char)hexnumber; break; } default: os << c2; break; } } else { os << c; } } return os.str(); } std::string serializeJsonStringIfNeeded(const std::string &s) { for (size_t i = 0; i < s.size(); ++i) { if (s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"') return serializeJsonString(s); } return s; } std::string deSerializeJsonStringIfNeeded(std::istream &is) { std::ostringstream tmp_os; bool expect_initial_quote = true; bool is_json = false; bool was_backslash = false; for (;;) { char c = is.get(); if (is.eof()) break; if (expect_initial_quote && c == '"') { tmp_os << c; is_json = true; } else if(is_json) { tmp_os << c; if (was_backslash) was_backslash = false; else if (c == '\\') was_backslash = true; else if (c == '"') break; // Found end of string } else { if (c == ' ') { // Found end of word is.unget(); break; } tmp_os << c; } expect_initial_quote = false; } if (is_json) { std::istringstream tmp_is(tmp_os.str(), std::ios::binary); return deSerializeJsonString(tmp_is); } return tmp_os.str(); } //// //// String/Struct conversions //// bool deSerializeStringToStruct(std::string valstr, std::string format, void *out, size_t olen) { size_t len = olen; std::vector<std::string *> strs_alloced; std::string *str; char *f, *snext; size_t pos; char *s = &valstr[0]; char *buf = new char[len]; char *bufpos = buf; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos)) && s) { fmt = nullptr; bool is_unsigned = false; int width = 0; char valtype = *f; width = (int)strtol(f + 1, &f, 10); if (width && valtype == 's') valtype = 'i'; switch (valtype) { case 'u': is_unsigned = true; /* FALLTHROUGH */ case 'i': if (width == 16) { bufpos += PADDING(bufpos, u16); if ((bufpos - buf) + sizeof(u16) <= len) { if (is_unsigned) *(u16 *)bufpos = (u16)strtoul(s, &s, 10); else *(s16 *)bufpos = (s16)strtol(s, &s, 10); } bufpos += sizeof(u16); } else if (width == 32) { bufpos += PADDING(bufpos, u32); if ((bufpos - buf) + sizeof(u32) <= len) { if (is_unsigned) *(u32 *)bufpos = (u32)strtoul(s, &s, 10); else *(s32 *)bufpos = (s32)strtol(s, &s, 10); } bufpos += sizeof(u32); } else if (width == 64) { bufpos += PADDING(bufpos, u64); if ((bufpos - buf) + sizeof(u64) <= len) { if (is_unsigned) *(u64 *)bufpos = (u64)strtoull(s, &s, 10); else *(s64 *)bufpos = (s64)strtoll(s, &s, 10); } bufpos += sizeof(u64); } s = strchr(s, ','); break; case 'b': snext = strchr(s, ','); if (snext) *snext++ = 0; bufpos += PADDING(bufpos, bool); if ((bufpos - buf) + sizeof(bool) <= len) *(bool *)bufpos = is_yes(std::string(s)); bufpos += sizeof(bool); s = snext; break; case 'f': bufpos += PADDING(bufpos, float); if ((bufpos - buf) + sizeof(float) <= len) *(float *)bufpos = strtof(s, &s); bufpos += sizeof(float); s = strchr(s, ','); break; case 's': while (*s == ' ' || *s == '\t') s++; if (*s++ != '"') //error, expected string goto fail; snext = s; while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"')) snext++; *snext++ = 0; bufpos += PADDING(bufpos, std::string *); str = new std::string(s); pos = 0; while ((pos = str->find("\\\"", pos)) != std::string::npos) str->erase(pos, 1); if ((bufpos - buf) + sizeof(std::string *) <= len) *(std::string **)bufpos = str; bufpos += sizeof(std::string *); strs_alloced.push_back(str); s = *snext ? snext + 1 : nullptr; break; case 'v': while (*s == ' ' || *s == '\t') s++; if (*s++ != '(') //error, expected vector goto fail; if (width == 2) { bufpos += PADDING(bufpos, v2f); if ((bufpos - buf) + sizeof(v2f) <= len) { v2f *v = (v2f *)bufpos; v->X = strtof(s, &s); s++; v->Y = strtof(s, &s); } bufpos += sizeof(v2f); } else if (width == 3) { bufpos += PADDING(bufpos, v3f); if ((bufpos - buf) + sizeof(v3f) <= len) { v3f *v = (v3f *)bufpos; v->X = strtof(s, &s); s++; v->Y = strtof(s, &s); s++; v->Z = strtof(s, &s); } bufpos += sizeof(v3f); } s = strchr(s, ','); break; default: //error, invalid format specifier goto fail; } if (s && *s == ',') s++; if ((size_t)(bufpos - buf) > len) //error, buffer too small goto fail; } if (f && *f) { //error, mismatched number of fields and values fail: for (size_t i = 0; i != strs_alloced.size(); i++) delete strs_alloced[i]; delete[] buf; return false; } memcpy(out, buf, olen); delete[] buf; return true; } // Casts *buf to a signed or unsigned fixed-width integer of 'w' width #define SIGN_CAST(w, buf) (is_unsigned ? *((u##w *) buf) : *((s##w *) buf)) bool serializeStructToString(std::string *out, std::string format, void *value) { std::ostringstream os; std::string str; char *f; size_t strpos; char *bufpos = (char *) value; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos))) { fmt = nullptr; bool is_unsigned = false; int width = 0; char valtype = *f; width = (int)strtol(f + 1, &f, 10); if (width && valtype == 's') valtype = 'i'; switch (valtype) { case 'u': is_unsigned = true; /* FALLTHROUGH */ case 'i': if (width == 16) { bufpos += PADDING(bufpos, u16); os << SIGN_CAST(16, bufpos); bufpos += sizeof(u16); } else if (width == 32) { bufpos += PADDING(bufpos, u32); os << SIGN_CAST(32, bufpos); bufpos += sizeof(u32); } else if (width == 64) { bufpos += PADDING(bufpos, u64); os << SIGN_CAST(64, bufpos); bufpos += sizeof(u64); } break; case 'b': bufpos += PADDING(bufpos, bool); os << std::boolalpha << *((bool *) bufpos); bufpos += sizeof(bool); break; case 'f': bufpos += PADDING(bufpos, float); os << *((float *) bufpos); bufpos += sizeof(float); break; case 's': bufpos += PADDING(bufpos, std::string *); str = **((std::string **) bufpos); strpos = 0; while ((strpos = str.find('"', strpos)) != std::string::npos) { str.insert(strpos, 1, '\\'); strpos += 2; } os << str; bufpos += sizeof(std::string *); break; case 'v': if (width == 2) { bufpos += PADDING(bufpos, v2f); v2f *v = (v2f *) bufpos; os << '(' << v->X << ", " << v->Y << ')'; bufpos += sizeof(v2f); } else { bufpos += PADDING(bufpos, v3f); v3f *v = (v3f *) bufpos; os << '(' << v->X << ", " << v->Y << ", " << v->Z << ')'; bufpos += sizeof(v3f); } break; default: return false; } os << ", "; } *out = os.str(); // Trim off the trailing comma and space if (out->size() >= 2) out->resize(out->size() - 2); return true; } #undef SIGN_CAST //// //// Other //// std::string serializeHexString(const std::string &data, bool insert_spaces) { std::string result; result.reserve(data.size() * (2 + insert_spaces)); static const char hex_chars[] = "0123456789abcdef"; const size_t len = data.size(); for (size_t i = 0; i != len; i++) { u8 byte = data[i]; result.push_back(hex_chars[(byte >> 4) & 0x0F]); result.push_back(hex_chars[(byte >> 0) & 0x0F]); if (insert_spaces && i != len - 1) result.push_back(' '); } return result; }
pgimeno/minetest
src/util/serialize.cpp
C++
mit
14,261
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include "exceptions.h" // for SerializationError #include "debug.h" // for assert #include "ieee_float.h" #include "config.h" #if HAVE_ENDIAN_H #ifdef _WIN32 #define __BYTE_ORDER 0 #define __LITTLE_ENDIAN 0 #define __BIG_ENDIAN 1 #elif defined(__MACH__) && defined(__APPLE__) #include <machine/endian.h> #elif defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/endian.h> #else #include <endian.h> #endif #endif #include <cstring> // for memcpy #include <iostream> #include <string> #include <vector> #define FIXEDPOINT_FACTOR 1000.0f // 0x7FFFFFFF / 1000.0f is not serializable. // The limited float precision at this magnitude may cause the result to round // to a greater value than can be represented by a 32 bit integer when increased // by a factor of FIXEDPOINT_FACTOR. As a result, [F1000_MIN..F1000_MAX] does // not represent the full range, but rather the largest safe range, of values on // all supported architectures. Note: This definition makes assumptions on // platform float-to-int conversion behavior. #define F1000_MIN ((float)(s32)((-0x7FFFFFFF - 1) / FIXEDPOINT_FACTOR)) #define F1000_MAX ((float)(s32)((0x7FFFFFFF) / FIXEDPOINT_FACTOR)) #define STRING_MAX_LEN 0xFFFF #define WIDE_STRING_MAX_LEN 0xFFFF // 64 MB ought to be enough for anybody - Billy G. #define LONG_STRING_MAX_LEN (64 * 1024 * 1024) extern FloatType g_serialize_f32_type; #if HAVE_ENDIAN_H // use machine native byte swapping routines // Note: memcpy below is optimized out by modern compilers inline u16 readU16(const u8 *data) { u16 val; memcpy(&val, data, 2); return be16toh(val); } inline u32 readU32(const u8 *data) { u32 val; memcpy(&val, data, 4); return be32toh(val); } inline u64 readU64(const u8 *data) { u64 val; memcpy(&val, data, 8); return be64toh(val); } inline void writeU16(u8 *data, u16 i) { u16 val = htobe16(i); memcpy(data, &val, 2); } inline void writeU32(u8 *data, u32 i) { u32 val = htobe32(i); memcpy(data, &val, 4); } inline void writeU64(u8 *data, u64 i) { u64 val = htobe64(i); memcpy(data, &val, 8); } #else // generic byte-swapping implementation inline u16 readU16(const u8 *data) { return ((u16)data[0] << 8) | ((u16)data[1] << 0); } inline u32 readU32(const u8 *data) { return ((u32)data[0] << 24) | ((u32)data[1] << 16) | ((u32)data[2] << 8) | ((u32)data[3] << 0); } inline u64 readU64(const u8 *data) { return ((u64)data[0] << 56) | ((u64)data[1] << 48) | ((u64)data[2] << 40) | ((u64)data[3] << 32) | ((u64)data[4] << 24) | ((u64)data[5] << 16) | ((u64)data[6] << 8) | ((u64)data[7] << 0); } inline void writeU16(u8 *data, u16 i) { data[0] = (i >> 8) & 0xFF; data[1] = (i >> 0) & 0xFF; } inline void writeU32(u8 *data, u32 i) { data[0] = (i >> 24) & 0xFF; data[1] = (i >> 16) & 0xFF; data[2] = (i >> 8) & 0xFF; data[3] = (i >> 0) & 0xFF; } inline void writeU64(u8 *data, u64 i) { data[0] = (i >> 56) & 0xFF; data[1] = (i >> 48) & 0xFF; data[2] = (i >> 40) & 0xFF; data[3] = (i >> 32) & 0xFF; data[4] = (i >> 24) & 0xFF; data[5] = (i >> 16) & 0xFF; data[6] = (i >> 8) & 0xFF; data[7] = (i >> 0) & 0xFF; } #endif // HAVE_ENDIAN_H //////////////// read routines //////////////// inline u8 readU8(const u8 *data) { return ((u8)data[0] << 0); } inline s8 readS8(const u8 *data) { return (s8)readU8(data); } inline s16 readS16(const u8 *data) { return (s16)readU16(data); } inline s32 readS32(const u8 *data) { return (s32)readU32(data); } inline s64 readS64(const u8 *data) { return (s64)readU64(data); } inline f32 readF1000(const u8 *data) { return (f32)readS32(data) / FIXEDPOINT_FACTOR; } inline f32 readF32(const u8 *data) { u32 u = readU32(data); switch (g_serialize_f32_type) { case FLOATTYPE_SYSTEM: { f32 f; memcpy(&f, &u, 4); return f; } case FLOATTYPE_SLOW: return u32Tof32Slow(u); case FLOATTYPE_UNKNOWN: // First initialization g_serialize_f32_type = getFloatSerializationType(); return readF32(data); } throw SerializationError("readF32: Unreachable code"); } inline video::SColor readARGB8(const u8 *data) { video::SColor p(readU32(data)); return p; } inline v2s16 readV2S16(const u8 *data) { v2s16 p; p.X = readS16(&data[0]); p.Y = readS16(&data[2]); return p; } inline v3s16 readV3S16(const u8 *data) { v3s16 p; p.X = readS16(&data[0]); p.Y = readS16(&data[2]); p.Z = readS16(&data[4]); return p; } inline v2s32 readV2S32(const u8 *data) { v2s32 p; p.X = readS32(&data[0]); p.Y = readS32(&data[4]); return p; } inline v3s32 readV3S32(const u8 *data) { v3s32 p; p.X = readS32(&data[0]); p.Y = readS32(&data[4]); p.Z = readS32(&data[8]); return p; } inline v3f readV3F1000(const u8 *data) { v3f p; p.X = readF1000(&data[0]); p.Y = readF1000(&data[4]); p.Z = readF1000(&data[8]); return p; } inline v2f readV2F32(const u8 *data) { v2f p; p.X = readF32(&data[0]); p.Y = readF32(&data[4]); return p; } inline v3f readV3F32(const u8 *data) { v3f p; p.X = readF32(&data[0]); p.Y = readF32(&data[4]); p.Z = readF32(&data[8]); return p; } /////////////// write routines //////////////// inline void writeU8(u8 *data, u8 i) { data[0] = (i >> 0) & 0xFF; } inline void writeS8(u8 *data, s8 i) { writeU8(data, (u8)i); } inline void writeS16(u8 *data, s16 i) { writeU16(data, (u16)i); } inline void writeS32(u8 *data, s32 i) { writeU32(data, (u32)i); } inline void writeS64(u8 *data, s64 i) { writeU64(data, (u64)i); } inline void writeF1000(u8 *data, f32 i) { assert(i >= F1000_MIN && i <= F1000_MAX); writeS32(data, i * FIXEDPOINT_FACTOR); } inline void writeF32(u8 *data, f32 i) { switch (g_serialize_f32_type) { case FLOATTYPE_SYSTEM: { u32 u; memcpy(&u, &i, 4); return writeU32(data, u); } case FLOATTYPE_SLOW: return writeU32(data, f32Tou32Slow(i)); case FLOATTYPE_UNKNOWN: // First initialization g_serialize_f32_type = getFloatSerializationType(); return writeF32(data, i); } throw SerializationError("writeF32: Unreachable code"); } inline void writeARGB8(u8 *data, video::SColor p) { writeU32(data, p.color); } inline void writeV2S16(u8 *data, v2s16 p) { writeS16(&data[0], p.X); writeS16(&data[2], p.Y); } inline void writeV3S16(u8 *data, v3s16 p) { writeS16(&data[0], p.X); writeS16(&data[2], p.Y); writeS16(&data[4], p.Z); } inline void writeV2S32(u8 *data, v2s32 p) { writeS32(&data[0], p.X); writeS32(&data[4], p.Y); } inline void writeV3S32(u8 *data, v3s32 p) { writeS32(&data[0], p.X); writeS32(&data[4], p.Y); writeS32(&data[8], p.Z); } inline void writeV3F1000(u8 *data, v3f p) { writeF1000(&data[0], p.X); writeF1000(&data[4], p.Y); writeF1000(&data[8], p.Z); } inline void writeV2F32(u8 *data, v2f p) { writeF32(&data[0], p.X); writeF32(&data[4], p.Y); } inline void writeV3F32(u8 *data, v3f p) { writeF32(&data[0], p.X); writeF32(&data[4], p.Y); writeF32(&data[8], p.Z); } //// //// Iostream wrapper for data read/write //// #define MAKE_STREAM_READ_FXN(T, N, S) \ inline T read ## N(std::istream &is) \ { \ char buf[S] = {0}; \ is.read(buf, sizeof(buf)); \ return read ## N((u8 *)buf); \ } #define MAKE_STREAM_WRITE_FXN(T, N, S) \ inline void write ## N(std::ostream &os, T val) \ { \ char buf[S]; \ write ## N((u8 *)buf, val); \ os.write(buf, sizeof(buf)); \ } MAKE_STREAM_READ_FXN(u8, U8, 1); MAKE_STREAM_READ_FXN(u16, U16, 2); MAKE_STREAM_READ_FXN(u32, U32, 4); MAKE_STREAM_READ_FXN(u64, U64, 8); MAKE_STREAM_READ_FXN(s8, S8, 1); MAKE_STREAM_READ_FXN(s16, S16, 2); MAKE_STREAM_READ_FXN(s32, S32, 4); MAKE_STREAM_READ_FXN(s64, S64, 8); MAKE_STREAM_READ_FXN(f32, F1000, 4); MAKE_STREAM_READ_FXN(f32, F32, 4); MAKE_STREAM_READ_FXN(v2s16, V2S16, 4); MAKE_STREAM_READ_FXN(v3s16, V3S16, 6); MAKE_STREAM_READ_FXN(v2s32, V2S32, 8); MAKE_STREAM_READ_FXN(v3s32, V3S32, 12); MAKE_STREAM_READ_FXN(v3f, V3F1000, 12); MAKE_STREAM_READ_FXN(v2f, V2F32, 8); MAKE_STREAM_READ_FXN(v3f, V3F32, 12); MAKE_STREAM_READ_FXN(video::SColor, ARGB8, 4); MAKE_STREAM_WRITE_FXN(u8, U8, 1); MAKE_STREAM_WRITE_FXN(u16, U16, 2); MAKE_STREAM_WRITE_FXN(u32, U32, 4); MAKE_STREAM_WRITE_FXN(u64, U64, 8); MAKE_STREAM_WRITE_FXN(s8, S8, 1); MAKE_STREAM_WRITE_FXN(s16, S16, 2); MAKE_STREAM_WRITE_FXN(s32, S32, 4); MAKE_STREAM_WRITE_FXN(s64, S64, 8); MAKE_STREAM_WRITE_FXN(f32, F1000, 4); MAKE_STREAM_WRITE_FXN(f32, F32, 4); MAKE_STREAM_WRITE_FXN(v2s16, V2S16, 4); MAKE_STREAM_WRITE_FXN(v3s16, V3S16, 6); MAKE_STREAM_WRITE_FXN(v2s32, V2S32, 8); MAKE_STREAM_WRITE_FXN(v3s32, V3S32, 12); MAKE_STREAM_WRITE_FXN(v3f, V3F1000, 12); MAKE_STREAM_WRITE_FXN(v2f, V2F32, 8); MAKE_STREAM_WRITE_FXN(v3f, V3F32, 12); MAKE_STREAM_WRITE_FXN(video::SColor, ARGB8, 4); //// //// More serialization stuff //// // Creates a string with the length as the first two bytes std::string serializeString(const std::string &plain); // Creates a string with the length as the first two bytes from wide string std::string serializeWideString(const std::wstring &plain); // Reads a string with the length as the first two bytes std::string deSerializeString(std::istream &is); // Reads a wide string with the length as the first two bytes std::wstring deSerializeWideString(std::istream &is); // Creates a string with the length as the first four bytes std::string serializeLongString(const std::string &plain); // Reads a string with the length as the first four bytes std::string deSerializeLongString(std::istream &is); // Creates a string encoded in JSON format (almost equivalent to a C string literal) std::string serializeJsonString(const std::string &plain); // Reads a string encoded in JSON format std::string deSerializeJsonString(std::istream &is); // If the string contains spaces, quotes or control characters, encodes as JSON. // Else returns the string unmodified. std::string serializeJsonStringIfNeeded(const std::string &s); // Parses a string serialized by serializeJsonStringIfNeeded. std::string deSerializeJsonStringIfNeeded(std::istream &is); // Creates a string consisting of the hexadecimal representation of `data` std::string serializeHexString(const std::string &data, bool insert_spaces=false); // Creates a string containing comma delimited values of a struct whose layout is // described by the parameter format bool serializeStructToString(std::string *out, std::string format, void *value); // Reads a comma delimited string of values into a struct whose layout is // decribed by the parameter format bool deSerializeStringToStruct(std::string valstr, std::string format, void *out, size_t olen); //// //// BufReader //// #define MAKE_BUFREADER_GETNOEX_FXN(T, N, S) \ inline bool get ## N ## NoEx(T *val) \ { \ if (pos + S > size) \ return false; \ *val = read ## N(data + pos); \ pos += S; \ return true; \ } #define MAKE_BUFREADER_GET_FXN(T, N) \ inline T get ## N() \ { \ T val; \ if (!get ## N ## NoEx(&val)) \ throw SerializationError("Attempted read past end of data"); \ return val; \ } class BufReader { public: BufReader(const u8 *data_, size_t size_) : data(data_), size(size_) { } MAKE_BUFREADER_GETNOEX_FXN(u8, U8, 1); MAKE_BUFREADER_GETNOEX_FXN(u16, U16, 2); MAKE_BUFREADER_GETNOEX_FXN(u32, U32, 4); MAKE_BUFREADER_GETNOEX_FXN(u64, U64, 8); MAKE_BUFREADER_GETNOEX_FXN(s8, S8, 1); MAKE_BUFREADER_GETNOEX_FXN(s16, S16, 2); MAKE_BUFREADER_GETNOEX_FXN(s32, S32, 4); MAKE_BUFREADER_GETNOEX_FXN(s64, S64, 8); MAKE_BUFREADER_GETNOEX_FXN(f32, F1000, 4); MAKE_BUFREADER_GETNOEX_FXN(v2s16, V2S16, 4); MAKE_BUFREADER_GETNOEX_FXN(v3s16, V3S16, 6); MAKE_BUFREADER_GETNOEX_FXN(v2s32, V2S32, 8); MAKE_BUFREADER_GETNOEX_FXN(v3s32, V3S32, 12); MAKE_BUFREADER_GETNOEX_FXN(v3f, V3F1000, 12); MAKE_BUFREADER_GETNOEX_FXN(video::SColor, ARGB8, 4); bool getStringNoEx(std::string *val); bool getWideStringNoEx(std::wstring *val); bool getLongStringNoEx(std::string *val); bool getRawDataNoEx(void *data, size_t len); MAKE_BUFREADER_GET_FXN(u8, U8); MAKE_BUFREADER_GET_FXN(u16, U16); MAKE_BUFREADER_GET_FXN(u32, U32); MAKE_BUFREADER_GET_FXN(u64, U64); MAKE_BUFREADER_GET_FXN(s8, S8); MAKE_BUFREADER_GET_FXN(s16, S16); MAKE_BUFREADER_GET_FXN(s32, S32); MAKE_BUFREADER_GET_FXN(s64, S64); MAKE_BUFREADER_GET_FXN(f32, F1000); MAKE_BUFREADER_GET_FXN(v2s16, V2S16); MAKE_BUFREADER_GET_FXN(v3s16, V3S16); MAKE_BUFREADER_GET_FXN(v2s32, V2S32); MAKE_BUFREADER_GET_FXN(v3s32, V3S32); MAKE_BUFREADER_GET_FXN(v3f, V3F1000); MAKE_BUFREADER_GET_FXN(video::SColor, ARGB8); MAKE_BUFREADER_GET_FXN(std::string, String); MAKE_BUFREADER_GET_FXN(std::wstring, WideString); MAKE_BUFREADER_GET_FXN(std::string, LongString); inline void getRawData(void *val, size_t len) { if (!getRawDataNoEx(val, len)) throw SerializationError("Attempted read past end of data"); } inline size_t remaining() { assert(pos <= size); return size - pos; } const u8 *data; size_t size; size_t pos = 0; }; #undef MAKE_BUFREADER_GET_FXN #undef MAKE_BUFREADER_GETNOEX_FXN //// //// Vector-based write routines //// inline void putU8(std::vector<u8> *dest, u8 val) { dest->push_back((val >> 0) & 0xFF); } inline void putU16(std::vector<u8> *dest, u16 val) { dest->push_back((val >> 8) & 0xFF); dest->push_back((val >> 0) & 0xFF); } inline void putU32(std::vector<u8> *dest, u32 val) { dest->push_back((val >> 24) & 0xFF); dest->push_back((val >> 16) & 0xFF); dest->push_back((val >> 8) & 0xFF); dest->push_back((val >> 0) & 0xFF); } inline void putU64(std::vector<u8> *dest, u64 val) { dest->push_back((val >> 56) & 0xFF); dest->push_back((val >> 48) & 0xFF); dest->push_back((val >> 40) & 0xFF); dest->push_back((val >> 32) & 0xFF); dest->push_back((val >> 24) & 0xFF); dest->push_back((val >> 16) & 0xFF); dest->push_back((val >> 8) & 0xFF); dest->push_back((val >> 0) & 0xFF); } inline void putS8(std::vector<u8> *dest, s8 val) { putU8(dest, val); } inline void putS16(std::vector<u8> *dest, s16 val) { putU16(dest, val); } inline void putS32(std::vector<u8> *dest, s32 val) { putU32(dest, val); } inline void putS64(std::vector<u8> *dest, s64 val) { putU64(dest, val); } inline void putF1000(std::vector<u8> *dest, f32 val) { putS32(dest, val * FIXEDPOINT_FACTOR); } inline void putV2S16(std::vector<u8> *dest, v2s16 val) { putS16(dest, val.X); putS16(dest, val.Y); } inline void putV3S16(std::vector<u8> *dest, v3s16 val) { putS16(dest, val.X); putS16(dest, val.Y); putS16(dest, val.Z); } inline void putV2S32(std::vector<u8> *dest, v2s32 val) { putS32(dest, val.X); putS32(dest, val.Y); } inline void putV3S32(std::vector<u8> *dest, v3s32 val) { putS32(dest, val.X); putS32(dest, val.Y); putS32(dest, val.Z); } inline void putV3F1000(std::vector<u8> *dest, v3f val) { putF1000(dest, val.X); putF1000(dest, val.Y); putF1000(dest, val.Z); } inline void putARGB8(std::vector<u8> *dest, video::SColor val) { putU32(dest, val.color); } inline void putString(std::vector<u8> *dest, const std::string &val) { if (val.size() > STRING_MAX_LEN) throw SerializationError("String too long"); putU16(dest, val.size()); dest->insert(dest->end(), val.begin(), val.end()); } inline void putWideString(std::vector<u8> *dest, const std::wstring &val) { if (val.size() > WIDE_STRING_MAX_LEN) throw SerializationError("String too long"); putU16(dest, val.size()); for (size_t i = 0; i != val.size(); i++) putU16(dest, val[i]); } inline void putLongString(std::vector<u8> *dest, const std::string &val) { if (val.size() > LONG_STRING_MAX_LEN) throw SerializationError("String too long"); putU32(dest, val.size()); dest->insert(dest->end(), val.begin(), val.end()); } inline void putRawData(std::vector<u8> *dest, const void *src, size_t len) { dest->insert(dest->end(), (u8 *)src, (u8 *)src + len); }
pgimeno/minetest
src/util/serialize.h
C++
mit
17,350
/* sha1.cpp Copyright (c) 2005 Michael D. Leonhard http://tamale.net/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include "sha1.h" // print out memory in hexadecimal void SHA1::hexPrinter( unsigned char* c, int l ) { assert( c ); assert( l > 0 ); while( l > 0 ) { printf( " %02x", *c ); l--; c++; } } // circular left bit rotation. MSB wraps around to LSB Uint32 SHA1::lrot( Uint32 x, int bits ) { return (x<<bits) | (x>>(32 - bits)); }; // Save a 32-bit unsigned integer to memory, in big-endian order void SHA1::storeBigEndianUint32( unsigned char* byte, Uint32 num ) { assert( byte ); byte[0] = (unsigned char)(num>>24); byte[1] = (unsigned char)(num>>16); byte[2] = (unsigned char)(num>>8); byte[3] = (unsigned char)num; } // Constructor ******************************************************* SHA1::SHA1() { // make sure that the data type is the right size assert( sizeof( Uint32 ) * 5 == 20 ); } // Destructor ******************************************************** SHA1::~SHA1() { // erase data H0 = H1 = H2 = H3 = H4 = 0; for( int c = 0; c < 64; c++ ) bytes[c] = 0; unprocessedBytes = size = 0; } // process *********************************************************** void SHA1::process() { assert( unprocessedBytes == 64 ); //printf( "process: " ); hexPrinter( bytes, 64 ); printf( "\n" ); int t; Uint32 a, b, c, d, e, K, f, W[80]; // starting values a = H0; b = H1; c = H2; d = H3; e = H4; // copy and expand the message block for( t = 0; t < 16; t++ ) W[t] = (bytes[t*4] << 24) +(bytes[t*4 + 1] << 16) +(bytes[t*4 + 2] << 8) + bytes[t*4 + 3]; for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); /* main loop */ Uint32 temp; for( t = 0; t < 80; t++ ) { if( t < 20 ) { K = 0x5a827999; f = (b & c) | ((b ^ 0xFFFFFFFF) & d);//TODO: try using ~ } else if( t < 40 ) { K = 0x6ed9eba1; f = b ^ c ^ d; } else if( t < 60 ) { K = 0x8f1bbcdc; f = (b & c) | (b & d) | (c & d); } else { K = 0xca62c1d6; f = b ^ c ^ d; } temp = lrot(a,5) + f + e + W[t] + K; e = d; d = c; c = lrot(b,30); b = a; a = temp; //printf( "t=%d %08x %08x %08x %08x %08x\n",t,a,b,c,d,e ); } /* add variables */ H0 += a; H1 += b; H2 += c; H3 += d; H4 += e; //printf( "Current: %08x %08x %08x %08x %08x\n",H0,H1,H2,H3,H4 ); /* all bytes have been processed */ unprocessedBytes = 0; } // addBytes ********************************************************** void SHA1::addBytes( const char* data, int num ) { assert( data ); assert( num >= 0 ); // add these bytes to the running total size += num; // repeat until all data is processed while( num > 0 ) { // number of bytes required to complete block int needed = 64 - unprocessedBytes; assert( needed > 0 ); // number of bytes to copy (use smaller of two) int toCopy = (num < needed) ? num : needed; // Copy the bytes memcpy( bytes + unprocessedBytes, data, toCopy ); // Bytes have been copied num -= toCopy; data += toCopy; unprocessedBytes += toCopy; // there is a full block if( unprocessedBytes == 64 ) process(); } } // digest ************************************************************ unsigned char* SHA1::getDigest() { // save the message size Uint32 totalBitsL = size << 3; Uint32 totalBitsH = size >> 29; // add 0x80 to the message addBytes( "\x80", 1 ); unsigned char footer[64] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // block has no room for 8-byte filesize, so finish it if( unprocessedBytes > 56 ) addBytes( (char*)footer, 64 - unprocessedBytes); assert( unprocessedBytes <= 56 ); // how many zeros do we need int neededZeros = 56 - unprocessedBytes; // store file size (in bits) in big-endian format storeBigEndianUint32( footer + neededZeros , totalBitsH ); storeBigEndianUint32( footer + neededZeros + 4, totalBitsL ); // finish the final block addBytes( (char*)footer, neededZeros + 8 ); // allocate memory for the digest bytes unsigned char* digest = (unsigned char*)malloc( 20 ); // copy the digest bytes storeBigEndianUint32( digest, H0 ); storeBigEndianUint32( digest + 4, H1 ); storeBigEndianUint32( digest + 8, H2 ); storeBigEndianUint32( digest + 12, H3 ); storeBigEndianUint32( digest + 16, H4 ); // return the digest return digest; }
pgimeno/minetest
src/util/sha1.cpp
C++
mit
5,531
/* sha1.h Copyright (c) 2005 Michael D. Leonhard http://tamale.net/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once typedef unsigned int Uint32; class SHA1 { private: // fields Uint32 H0 = 0x67452301; Uint32 H1 = 0xefcdab89; Uint32 H2 = 0x98badcfe; Uint32 H3 = 0x10325476; Uint32 H4 = 0xc3d2e1f0; unsigned char bytes[64]; int unprocessedBytes = 0; Uint32 size = 0; void process(); public: SHA1(); ~SHA1(); void addBytes(const char *data, int num); unsigned char *getDigest(); // utility methods static Uint32 lrot(Uint32 x, int bits); static void storeBigEndianUint32(unsigned char *byte, Uint32 num); static void hexPrinter(unsigned char *c, int l); };
pgimeno/minetest
src/util/sha1.h
C++
mit
1,671
/* crypto/sha/sha.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #pragma once #include <stddef.h> #ifdef __cplusplus extern "C" { #endif #if defined(OPENSSL_NO_SHA) || (defined(OPENSSL_NO_SHA0) && defined(OPENSSL_NO_SHA1)) #error SHA is disabled. #endif #if defined(OPENSSL_FIPS) #define FIPS_SHA_SIZE_T size_t #endif /* Compat stuff from OpenSSL land */ /* crypto.h */ #define fips_md_init(alg) fips_md_init_ctx(alg, alg) #define fips_md_init_ctx(alg, cx) int alg##_Init(cx##_CTX *c) #define fips_cipher_abort(alg) while (0) /*- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * ! SHA_LONG has to be at least 32 bits wide. If it's wider, then ! * ! SHA_LONG_LOG2 has to be defined along. ! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ #if defined(__LP32__) #define SHA_LONG unsigned long #elif defined(__ILP64__) #define SHA_LONG unsigned long #define SHA_LONG_LOG2 3 #else #define SHA_LONG unsigned int #endif #define SHA_LBLOCK 16 #define SHA_CBLOCK \ (SHA_LBLOCK * 4) /* SHA treats input data as a \ * contiguous array of 32 bit wide \ * big-endian values. */ #define SHA_LAST_BLOCK (SHA_CBLOCK - 8) #define SHA_DIGEST_LENGTH 20 typedef struct SHAstate_st { SHA_LONG h0, h1, h2, h3, h4; SHA_LONG Nl, Nh; SHA_LONG data[SHA_LBLOCK]; unsigned int num; } SHA_CTX; #define SHA256_CBLOCK \ (SHA_LBLOCK * 4) /* SHA-256 treats input data as a \ * contiguous array of 32 bit wide \ * big-endian values. */ #define SHA224_DIGEST_LENGTH 28 #define SHA256_DIGEST_LENGTH 32 typedef struct SHA256state_st { SHA_LONG h[8]; SHA_LONG Nl, Nh; SHA_LONG data[SHA_LBLOCK]; unsigned int num, md_len; } SHA256_CTX; #ifndef OPENSSL_NO_SHA256 #ifdef OPENSSL_FIPS int private_SHA224_Init(SHA256_CTX *c); int private_SHA256_Init(SHA256_CTX *c); #endif int SHA224_Init(SHA256_CTX *c); int SHA224_Update(SHA256_CTX *c, const void *data, size_t len); int SHA224_Final(unsigned char *md, SHA256_CTX *c); unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md); int SHA256_Init(SHA256_CTX *c); int SHA256_Update(SHA256_CTX *c, const void *data, size_t len); int SHA256_Final(unsigned char *md, SHA256_CTX *c); unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md); void SHA256_Transform(SHA256_CTX *c, const unsigned char *data); #endif #define SHA384_DIGEST_LENGTH 48 #define SHA512_DIGEST_LENGTH 64 #ifdef __cplusplus } #endif
pgimeno/minetest
src/util/sha2.h
C++
mit
5,843
/* crypto/sha/sha256.c */ /* ==================================================================== * Copyright (c) 2004 The OpenSSL Project. All rights reserved * according to the OpenSSL license [found in ../../LICENSE]. * ==================================================================== */ # include <stdlib.h> # include <string.h> # include <util/sha2.h> # define OPENSSL_VERSION_TEXT "OpenSSL 1.0.2a 19 Mar 2015" # define OPENSSL_VERSION_PTEXT " part of " OPENSSL_VERSION_TEXT const char SHA256_version[] = "SHA-256" OPENSSL_VERSION_PTEXT; /* mem_clr.c */ unsigned static char cleanse_ctr = 0; static void OPENSSL_cleanse(void *ptr, size_t len) { unsigned char *p = ptr; size_t loop = len, ctr = cleanse_ctr; while (loop--) { *(p++) = (unsigned char)ctr; ctr += (17 + ((size_t)p & 0xF)); } p = memchr(ptr, (unsigned char)ctr, len); if (p) ctr += (63 + (size_t)p); cleanse_ctr = (unsigned char)ctr; } fips_md_init_ctx(SHA224, SHA256) { memset(c, 0, sizeof(*c)); c->h[0] = 0xc1059ed8UL; c->h[1] = 0x367cd507UL; c->h[2] = 0x3070dd17UL; c->h[3] = 0xf70e5939UL; c->h[4] = 0xffc00b31UL; c->h[5] = 0x68581511UL; c->h[6] = 0x64f98fa7UL; c->h[7] = 0xbefa4fa4UL; c->md_len = SHA224_DIGEST_LENGTH; return 1; } fips_md_init(SHA256) { memset(c, 0, sizeof(*c)); c->h[0] = 0x6a09e667UL; c->h[1] = 0xbb67ae85UL; c->h[2] = 0x3c6ef372UL; c->h[3] = 0xa54ff53aUL; c->h[4] = 0x510e527fUL; c->h[5] = 0x9b05688cUL; c->h[6] = 0x1f83d9abUL; c->h[7] = 0x5be0cd19UL; c->md_len = SHA256_DIGEST_LENGTH; return 1; } unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md) { SHA256_CTX c; static unsigned char m[SHA224_DIGEST_LENGTH]; if (md == NULL) md = m; SHA224_Init(&c); SHA256_Update(&c, d, n); SHA256_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); return (md); } unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md) { SHA256_CTX c; static unsigned char m[SHA256_DIGEST_LENGTH]; if (md == NULL) md = m; SHA256_Init(&c); SHA256_Update(&c, d, n); SHA256_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); return (md); } int SHA224_Update(SHA256_CTX *c, const void *data, size_t len) { return SHA256_Update(c, data, len); } int SHA224_Final(unsigned char *md, SHA256_CTX *c) { return SHA256_Final(md, c); } # define DATA_ORDER_IS_BIG_ENDIAN # define HASH_LONG SHA_LONG # define HASH_CTX SHA256_CTX # define HASH_CBLOCK SHA_CBLOCK /* * Note that FIPS180-2 discusses "Truncation of the Hash Function Output." * default: case below covers for it. It's not clear however if it's * permitted to truncate to amount of bytes not divisible by 4. I bet not, * but if it is, then default: case shall be extended. For reference. * Idea behind separate cases for pre-defined lenghts is to let the * compiler decide if it's appropriate to unroll small loops. */ # define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ unsigned int nn; \ switch ((c)->md_len) \ { case SHA224_DIGEST_LENGTH: \ for (nn=0;nn<SHA224_DIGEST_LENGTH/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ case SHA256_DIGEST_LENGTH: \ for (nn=0;nn<SHA256_DIGEST_LENGTH/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ default: \ if ((c)->md_len > SHA256_DIGEST_LENGTH) \ return 0; \ for (nn=0;nn<(c)->md_len/4;nn++) \ { ll=(c)->h[nn]; (void)HOST_l2c(ll,(s)); } \ break; \ } \ } while (0) # define HASH_UPDATE SHA256_Update # define HASH_TRANSFORM SHA256_Transform # define HASH_FINAL SHA256_Final # define HASH_BLOCK_DATA_ORDER sha256_block_data_order # ifndef SHA256_ASM static # endif void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num); # include "md32_common.h" # ifndef SHA256_ASM static const SHA_LONG K256[64] = { 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL }; /* * FIPS specification refers to right rotations, while our ROTATE macro * is left one. This is why you might notice that rotation coefficients * differ from those observed in FIPS document by 32-N... */ # define Sigma0(x) (ROTATE((x),30) ^ ROTATE((x),19) ^ ROTATE((x),10)) # define Sigma1(x) (ROTATE((x),26) ^ ROTATE((x),21) ^ ROTATE((x),7)) # define sigma0(x) (ROTATE((x),25) ^ ROTATE((x),14) ^ ((x)>>3)) # define sigma1(x) (ROTATE((x),15) ^ ROTATE((x),13) ^ ((x)>>10)) # define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) # define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) # ifdef OPENSSL_SMALL_FOOTPRINT static void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num) { unsigned MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1, T2; SHA_LONG X[16], l; int i; const unsigned char *data = in; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; for (i = 0; i < 16; i++) { HOST_c2l(data, l); T1 = X[i] = l; T1 += h + Sigma1(e) + Ch(e, f, g) + K256[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } for (; i < 64; i++) { s0 = X[(i + 1) & 0x0f]; s0 = sigma0(s0); s1 = X[(i + 14) & 0x0f]; s1 = sigma1(s1); T1 = X[i & 0xf] += s0 + s1 + X[(i + 9) & 0xf]; T1 += h + Sigma1(e) + Ch(e, f, g) + K256[i]; T2 = Sigma0(a) + Maj(a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; } } # else # define ROUND_00_15(i,a,b,c,d,e,f,g,h) do { \ T1 += h + Sigma1(e) + Ch(e,f,g) + K256[i]; \ h = Sigma0(a) + Maj(a,b,c); \ d += T1; h += T1; } while (0) # define ROUND_16_63(i,a,b,c,d,e,f,g,h,X) do { \ s0 = X[(i+1)&0x0f]; s0 = sigma0(s0); \ s1 = X[(i+14)&0x0f]; s1 = sigma1(s1); \ T1 = X[(i)&0x0f] += s0 + s1 + X[(i+9)&0x0f]; \ ROUND_00_15(i,a,b,c,d,e,f,g,h); } while (0) static void sha256_block_data_order(SHA256_CTX *ctx, const void *in, size_t num) { unsigned MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1; SHA_LONG X[16]; int i; const unsigned char *data = in; const union { long one; char little; } is_endian = { 1 }; while (num--) { a = ctx->h[0]; b = ctx->h[1]; c = ctx->h[2]; d = ctx->h[3]; e = ctx->h[4]; f = ctx->h[5]; g = ctx->h[6]; h = ctx->h[7]; if (!is_endian.little && sizeof(SHA_LONG) == 4 && ((size_t)in % 4) == 0) { const SHA_LONG *W = (const SHA_LONG *)data; T1 = X[0] = W[0]; ROUND_00_15(0, a, b, c, d, e, f, g, h); T1 = X[1] = W[1]; ROUND_00_15(1, h, a, b, c, d, e, f, g); T1 = X[2] = W[2]; ROUND_00_15(2, g, h, a, b, c, d, e, f); T1 = X[3] = W[3]; ROUND_00_15(3, f, g, h, a, b, c, d, e); T1 = X[4] = W[4]; ROUND_00_15(4, e, f, g, h, a, b, c, d); T1 = X[5] = W[5]; ROUND_00_15(5, d, e, f, g, h, a, b, c); T1 = X[6] = W[6]; ROUND_00_15(6, c, d, e, f, g, h, a, b); T1 = X[7] = W[7]; ROUND_00_15(7, b, c, d, e, f, g, h, a); T1 = X[8] = W[8]; ROUND_00_15(8, a, b, c, d, e, f, g, h); T1 = X[9] = W[9]; ROUND_00_15(9, h, a, b, c, d, e, f, g); T1 = X[10] = W[10]; ROUND_00_15(10, g, h, a, b, c, d, e, f); T1 = X[11] = W[11]; ROUND_00_15(11, f, g, h, a, b, c, d, e); T1 = X[12] = W[12]; ROUND_00_15(12, e, f, g, h, a, b, c, d); T1 = X[13] = W[13]; ROUND_00_15(13, d, e, f, g, h, a, b, c); T1 = X[14] = W[14]; ROUND_00_15(14, c, d, e, f, g, h, a, b); T1 = X[15] = W[15]; ROUND_00_15(15, b, c, d, e, f, g, h, a); data += SHA256_CBLOCK; } else { SHA_LONG l; HOST_c2l(data, l); T1 = X[0] = l; ROUND_00_15(0, a, b, c, d, e, f, g, h); HOST_c2l(data, l); T1 = X[1] = l; ROUND_00_15(1, h, a, b, c, d, e, f, g); HOST_c2l(data, l); T1 = X[2] = l; ROUND_00_15(2, g, h, a, b, c, d, e, f); HOST_c2l(data, l); T1 = X[3] = l; ROUND_00_15(3, f, g, h, a, b, c, d, e); HOST_c2l(data, l); T1 = X[4] = l; ROUND_00_15(4, e, f, g, h, a, b, c, d); HOST_c2l(data, l); T1 = X[5] = l; ROUND_00_15(5, d, e, f, g, h, a, b, c); HOST_c2l(data, l); T1 = X[6] = l; ROUND_00_15(6, c, d, e, f, g, h, a, b); HOST_c2l(data, l); T1 = X[7] = l; ROUND_00_15(7, b, c, d, e, f, g, h, a); HOST_c2l(data, l); T1 = X[8] = l; ROUND_00_15(8, a, b, c, d, e, f, g, h); HOST_c2l(data, l); T1 = X[9] = l; ROUND_00_15(9, h, a, b, c, d, e, f, g); HOST_c2l(data, l); T1 = X[10] = l; ROUND_00_15(10, g, h, a, b, c, d, e, f); HOST_c2l(data, l); T1 = X[11] = l; ROUND_00_15(11, f, g, h, a, b, c, d, e); HOST_c2l(data, l); T1 = X[12] = l; ROUND_00_15(12, e, f, g, h, a, b, c, d); HOST_c2l(data, l); T1 = X[13] = l; ROUND_00_15(13, d, e, f, g, h, a, b, c); HOST_c2l(data, l); T1 = X[14] = l; ROUND_00_15(14, c, d, e, f, g, h, a, b); HOST_c2l(data, l); T1 = X[15] = l; ROUND_00_15(15, b, c, d, e, f, g, h, a); } for (i = 16; i < 64; i += 8) { ROUND_16_63(i + 0, a, b, c, d, e, f, g, h, X); ROUND_16_63(i + 1, h, a, b, c, d, e, f, g, X); ROUND_16_63(i + 2, g, h, a, b, c, d, e, f, X); ROUND_16_63(i + 3, f, g, h, a, b, c, d, e, X); ROUND_16_63(i + 4, e, f, g, h, a, b, c, d, X); ROUND_16_63(i + 5, d, e, f, g, h, a, b, c, X); ROUND_16_63(i + 6, c, d, e, f, g, h, a, b, X); ROUND_16_63(i + 7, b, c, d, e, f, g, h, a, X); } ctx->h[0] += a; ctx->h[1] += b; ctx->h[2] += c; ctx->h[3] += d; ctx->h[4] += e; ctx->h[5] += f; ctx->h[6] += g; ctx->h[7] += h; } } # endif # endif /* SHA256_ASM */
pgimeno/minetest
src/util/sha256.c
C++
mit
12,823
/* * Secure Remote Password 6a implementation * https://github.com/est31/csrp-gmp * * The MIT License (MIT) * * Copyright (c) 2010, 2013 Tom Cocagne, 2015 est31 <MTest31@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ // clang-format off #include <cstddef> #ifdef WIN32 #include <windows.h> #include <wincrypt.h> #else #include <ctime> #endif // clang-format on #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdint> #include <config.h> #if USE_SYSTEM_GMP #include <gmp.h> #else #include <mini-gmp.h> #endif #include <util/sha2.h> #include "srp.h" //#define CSRP_USE_SHA1 #define CSRP_USE_SHA256 #define srp_dbg_data(data, datalen, prevtext) ; /*void srp_dbg_data(unsigned char * data, size_t datalen, char * prevtext) { printf(prevtext); size_t i; for (i = 0; i < datalen; i++) { printf("%02X", data[i]); } printf("\n"); }*/ static int g_initialized = 0; #define RAND_BUFF_MAX 128 static unsigned int g_rand_idx; static unsigned char g_rand_buff[RAND_BUFF_MAX]; void *(*srp_alloc)(size_t) = &malloc; void *(*srp_realloc)(void *, size_t) = &realloc; void (*srp_free)(void *) = &free; // clang-format off void srp_set_memory_functions( void *(*new_srp_alloc)(size_t), void *(*new_srp_realloc)(void *, size_t), void (*new_srp_free)(void *)) { srp_alloc = new_srp_alloc; srp_realloc = new_srp_realloc; srp_free = new_srp_free; } // clang-format on typedef struct { mpz_t N; mpz_t g; } NGConstant; struct NGHex { const char *n_hex; const char *g_hex; }; /* All constants here were pulled from Appendix A of RFC 5054 */ static struct NGHex global_Ng_constants[] = { {/* 1024 */ "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" "FD5138FE8376435B9FC61D2FC0EB06E3", "2"}, {/* 2048 */ "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" "9E4AFF73", "2"}, {/* 4096 */ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" "FFFFFFFFFFFFFFFF", "5"}, {/* 8192 */ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", "13"}, {0, 0} /* null sentinel */ }; static void delete_ng(NGConstant *ng) { if (ng) { mpz_clear(ng->N); mpz_clear(ng->g); srp_free(ng); } } static NGConstant *new_ng(SRP_NGType ng_type, const char *n_hex, const char *g_hex) { NGConstant *ng = (NGConstant *)srp_alloc(sizeof(NGConstant)); if (!ng) return 0; mpz_init(ng->N); mpz_init(ng->g); if (ng_type != SRP_NG_CUSTOM) { n_hex = global_Ng_constants[ng_type].n_hex; g_hex = global_Ng_constants[ng_type].g_hex; } int rv = 0; rv = mpz_set_str(ng->N, n_hex, 16); rv = rv | mpz_set_str(ng->g, g_hex, 16); if (rv) { delete_ng(ng); return 0; } return ng; } typedef union { SHA_CTX sha; SHA256_CTX sha256; // SHA512_CTX sha512; } HashCTX; struct SRPVerifier { SRP_HashAlgorithm hash_alg; NGConstant *ng; char *username; unsigned char *bytes_B; int authenticated; unsigned char M[SHA512_DIGEST_LENGTH]; unsigned char H_AMK[SHA512_DIGEST_LENGTH]; unsigned char session_key[SHA512_DIGEST_LENGTH]; }; struct SRPUser { SRP_HashAlgorithm hash_alg; NGConstant *ng; mpz_t a; mpz_t A; mpz_t S; unsigned char *bytes_A; int authenticated; char *username; char *username_verifier; unsigned char *password; size_t password_len; unsigned char M[SHA512_DIGEST_LENGTH]; unsigned char H_AMK[SHA512_DIGEST_LENGTH]; unsigned char session_key[SHA512_DIGEST_LENGTH]; }; // clang-format off static int hash_init(SRP_HashAlgorithm alg, HashCTX *c) { switch (alg) { #ifdef CSRP_USE_SHA1 case SRP_SHA1: return SHA1_Init(&c->sha); #endif /* case SRP_SHA224: return SHA224_Init(&c->sha256); */ #ifdef CSRP_USE_SHA256 case SRP_SHA256: return SHA256_Init(&c->sha256); #endif /* case SRP_SHA384: return SHA384_Init(&c->sha512); case SRP_SHA512: return SHA512_Init(&c->sha512); */ default: return -1; }; } static int hash_update( SRP_HashAlgorithm alg, HashCTX *c, const void *data, size_t len ) { switch (alg) { #ifdef CSRP_USE_SHA1 case SRP_SHA1: return SHA1_Update(&c->sha, data, len); #endif /* case SRP_SHA224: return SHA224_Update(&c->sha256, data, len); */ #ifdef CSRP_USE_SHA256 case SRP_SHA256: return SHA256_Update(&c->sha256, data, len); #endif /* case SRP_SHA384: return SHA384_Update(&c->sha512, data, len); case SRP_SHA512: return SHA512_Update(&c->sha512, data, len); */ default: return -1; }; } static int hash_final( SRP_HashAlgorithm alg, HashCTX *c, unsigned char *md ) { switch (alg) { #ifdef CSRP_USE_SHA1 case SRP_SHA1: return SHA1_Final(md, &c->sha); #endif /* case SRP_SHA224: return SHA224_Final(md, &c->sha256); */ #ifdef CSRP_USE_SHA256 case SRP_SHA256: return SHA256_Final(md, &c->sha256); #endif /* case SRP_SHA384: return SHA384_Final(md, &c->sha512); case SRP_SHA512: return SHA512_Final(md, &c->sha512); */ default: return -1; }; } static unsigned char *hash(SRP_HashAlgorithm alg, const unsigned char *d, size_t n, unsigned char *md) { switch (alg) { #ifdef CSRP_USE_SHA1 case SRP_SHA1: return SHA1(d, n, md); #endif /* case SRP_SHA224: return SHA224( d, n, md ); */ #ifdef CSRP_USE_SHA256 case SRP_SHA256: return SHA256(d, n, md); #endif /* case SRP_SHA384: return SHA384( d, n, md ); case SRP_SHA512: return SHA512( d, n, md ); */ default: return 0; }; } static size_t hash_length(SRP_HashAlgorithm alg) { switch (alg) { #ifdef CSRP_USE_SHA1 case SRP_SHA1: return SHA_DIGEST_LENGTH; #endif /* case SRP_SHA224: return SHA224_DIGEST_LENGTH; */ #ifdef CSRP_USE_SHA256 case SRP_SHA256: return SHA256_DIGEST_LENGTH; #endif /* case SRP_SHA384: return SHA384_DIGEST_LENGTH; case SRP_SHA512: return SHA512_DIGEST_LENGTH; */ default: return -1; }; } // clang-format on inline static int mpz_num_bytes(const mpz_t op) { return (mpz_sizeinbase(op, 2) + 7) / 8; } inline static void mpz_to_bin(const mpz_t op, unsigned char *to) { mpz_export(to, NULL, 1, 1, 1, 0, op); } inline static void mpz_from_bin(const unsigned char *s, size_t len, mpz_t ret) { mpz_import(ret, len, 1, 1, 1, 0, s); } // set op to (op1 * op2) mod d, using tmp for the calculation inline static void mpz_mulm( mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_mul(tmp, op1, op2); mpz_mod(op, tmp, d); } // set op to (op1 + op2) mod d, using tmp for the calculation inline static void mpz_addm( mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_add(tmp, op1, op2); mpz_mod(op, tmp, d); } // set op to (op1 - op2) mod d, using tmp for the calculation inline static void mpz_subm( mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_sub(tmp, op1, op2); mpz_mod(op, tmp, d); } static SRP_Result H_nn( mpz_t result, SRP_HashAlgorithm alg, const mpz_t N, const mpz_t n1, const mpz_t n2) { unsigned char buff[SHA512_DIGEST_LENGTH]; size_t len_N = mpz_num_bytes(N); size_t len_n1 = mpz_num_bytes(n1); size_t len_n2 = mpz_num_bytes(n2); size_t nbytes = len_N + len_N; unsigned char *bin = (unsigned char *)srp_alloc(nbytes); if (!bin) return SRP_ERR; if (len_n1 > len_N || len_n2 > len_N) { srp_free(bin); return SRP_ERR; } memset(bin, 0, nbytes); mpz_to_bin(n1, bin + (len_N - len_n1)); mpz_to_bin(n2, bin + (len_N + len_N - len_n2)); hash(alg, bin, nbytes, buff); srp_free(bin); mpz_from_bin(buff, hash_length(alg), result); return SRP_OK; } static SRP_Result H_ns(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *n, size_t len_n, const unsigned char *bytes, uint32_t len_bytes) { unsigned char buff[SHA512_DIGEST_LENGTH]; size_t nbytes = len_n + len_bytes; unsigned char *bin = (unsigned char *)srp_alloc(nbytes); if (!bin) return SRP_ERR; memcpy(bin, n, len_n); memcpy(bin + len_n, bytes, len_bytes); hash(alg, bin, nbytes, buff); srp_free(bin); mpz_from_bin(buff, hash_length(alg), result); return SRP_OK; } static int calculate_x(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *salt, size_t salt_len, const char *username, const unsigned char *password, size_t password_len) { unsigned char ucp_hash[SHA512_DIGEST_LENGTH]; HashCTX ctx; hash_init(alg, &ctx); srp_dbg_data((char *)username, strlen(username), "Username for x: "); srp_dbg_data((char *)password, password_len, "Password for x: "); hash_update(alg, &ctx, username, strlen(username)); hash_update(alg, &ctx, ":", 1); hash_update(alg, &ctx, password, password_len); hash_final(alg, &ctx, ucp_hash); return H_ns(result, alg, salt, salt_len, ucp_hash, hash_length(alg)); } static SRP_Result update_hash_n(SRP_HashAlgorithm alg, HashCTX *ctx, const mpz_t n) { size_t len = mpz_num_bytes(n); unsigned char *n_bytes = (unsigned char *)srp_alloc(len); if (!n_bytes) return SRP_ERR; mpz_to_bin(n, n_bytes); hash_update(alg, ctx, n_bytes, len); srp_free(n_bytes); return SRP_OK; } static SRP_Result hash_num(SRP_HashAlgorithm alg, const mpz_t n, unsigned char *dest) { int nbytes = mpz_num_bytes(n); unsigned char *bin = (unsigned char *)srp_alloc(nbytes); if (!bin) return SRP_ERR; mpz_to_bin(n, bin); hash(alg, bin, nbytes, dest); srp_free(bin); return SRP_OK; } static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned char *dest, const char *I, const unsigned char *s_bytes, size_t s_len, const mpz_t A, const mpz_t B, const unsigned char *K) { unsigned char H_N[SHA512_DIGEST_LENGTH]; unsigned char H_g[SHA512_DIGEST_LENGTH]; unsigned char H_I[SHA512_DIGEST_LENGTH]; unsigned char H_xor[SHA512_DIGEST_LENGTH]; HashCTX ctx; size_t i = 0; size_t hash_len = hash_length(alg); if (!hash_num(alg, ng->N, H_N)) return SRP_ERR; if (!hash_num(alg, ng->g, H_g)) return SRP_ERR; hash(alg, (const unsigned char *)I, strlen(I), H_I); for (i = 0; i < hash_len; i++) H_xor[i] = H_N[i] ^ H_g[i]; hash_init(alg, &ctx); hash_update(alg, &ctx, H_xor, hash_len); hash_update(alg, &ctx, H_I, hash_len); hash_update(alg, &ctx, s_bytes, s_len); if (!update_hash_n(alg, &ctx, A)) return SRP_ERR; if (!update_hash_n(alg, &ctx, B)) return SRP_ERR; hash_update(alg, &ctx, K, hash_len); hash_final(alg, &ctx, dest); return SRP_OK; } static SRP_Result calculate_H_AMK(SRP_HashAlgorithm alg, unsigned char *dest, const mpz_t A, const unsigned char *M, const unsigned char *K) { HashCTX ctx; hash_init(alg, &ctx); if (!update_hash_n(alg, &ctx, A)) return SRP_ERR; hash_update(alg, &ctx, M, hash_length(alg)); hash_update(alg, &ctx, K, hash_length(alg)); hash_final(alg, &ctx, dest); return SRP_OK; } static SRP_Result fill_buff() { g_rand_idx = 0; #ifdef WIN32 HCRYPTPROV wctx; #else FILE *fp = 0; #endif #ifdef WIN32 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return SRP_ERR; if (!CryptGenRandom(wctx, sizeof(g_rand_buff), (BYTE *)g_rand_buff)) return SRP_ERR; if (!CryptReleaseContext(wctx, 0)) return SRP_ERR; #else fp = fopen("/dev/urandom", "r"); if (!fp) return SRP_ERR; if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { fclose(fp); return SRP_ERR; } if (fclose(fp)) return SRP_ERR; #endif return SRP_OK; } static SRP_Result mpz_fill_random(mpz_t num) { // was call: BN_rand(num, 256, -1, 0); if (RAND_BUFF_MAX - g_rand_idx < 32) if (fill_buff() != SRP_OK) return SRP_ERR; mpz_from_bin((const unsigned char *)(&g_rand_buff[g_rand_idx]), 32, num); g_rand_idx += 32; return SRP_OK; } static SRP_Result init_random() { if (g_initialized) return SRP_OK; SRP_Result ret = fill_buff(); g_initialized = (ret == SRP_OK); return ret; } #define srp_dbg_num(num, text) ; /*void srp_dbg_num(mpz_t num, char * prevtext) { int len_num = mpz_num_bytes(num); char *bytes_num = (char*) srp_alloc(len_num); mpz_to_bin(num, (unsigned char *) bytes_num); srp_dbg_data(bytes_num, len_num, prevtext); srp_free(bytes_num); }*/ /*********************************************************************************************************** * * Exported Functions * ***********************************************************************************************************/ // clang-format off SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username_for_verifier, const unsigned char *password, size_t len_password, unsigned char **bytes_s, size_t *len_s, unsigned char **bytes_v, size_t *len_v, const char *n_hex, const char *g_hex ) { SRP_Result ret = SRP_OK; mpz_t v; mpz_init(v); mpz_t x; mpz_init(x); // clang-format on NGConstant *ng = new_ng(ng_type, n_hex, g_hex); if (!ng) goto error_and_exit; if (init_random() != SRP_OK) /* Only happens once */ goto error_and_exit; if (*bytes_s == NULL) { size_t size_to_fill = 16; *len_s = size_to_fill; if (RAND_BUFF_MAX - g_rand_idx < size_to_fill) if (fill_buff() != SRP_OK) goto error_and_exit; *bytes_s = (unsigned char *)srp_alloc(size_to_fill); if (!*bytes_s) goto error_and_exit; memcpy(*bytes_s, &g_rand_buff[g_rand_idx], size_to_fill); g_rand_idx += size_to_fill; } if (!calculate_x( x, alg, *bytes_s, *len_s, username_for_verifier, password, len_password)) goto error_and_exit; srp_dbg_num(x, "Server calculated x: "); mpz_powm(v, ng->g, x, ng->N); *len_v = mpz_num_bytes(v); *bytes_v = (unsigned char *)srp_alloc(*len_v); if (!*bytes_v) goto error_and_exit; mpz_to_bin(v, *bytes_v); cleanup_and_exit: delete_ng(ng); mpz_clear(v); mpz_clear(x); return ret; error_and_exit: ret = SRP_ERR; goto cleanup_and_exit; } // clang-format off /* Out: bytes_B, len_B. * * On failure, bytes_B will be set to NULL and len_B will be set to 0 */ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username, const unsigned char *bytes_s, size_t len_s, const unsigned char *bytes_v, size_t len_v, const unsigned char *bytes_A, size_t len_A, const unsigned char *bytes_b, size_t len_b, unsigned char **bytes_B, size_t *len_B, const char *n_hex, const char *g_hex ) { mpz_t v; mpz_init(v); mpz_from_bin(bytes_v, len_v, v); mpz_t A; mpz_init(A); mpz_from_bin(bytes_A, len_A, A); mpz_t u; mpz_init(u); mpz_t B; mpz_init(B); mpz_t S; mpz_init(S); mpz_t b; mpz_init(b); mpz_t k; mpz_init(k); mpz_t tmp1; mpz_init(tmp1); mpz_t tmp2; mpz_init(tmp2); mpz_t tmp3; mpz_init(tmp3); // clang-format on size_t ulen = strlen(username) + 1; NGConstant *ng = new_ng(ng_type, n_hex, g_hex); struct SRPVerifier *ver = 0; *len_B = 0; *bytes_B = 0; if (!ng) goto cleanup_and_exit; ver = (struct SRPVerifier *)srp_alloc(sizeof(struct SRPVerifier)); if (!ver) goto cleanup_and_exit; if (init_random() != SRP_OK) { /* Only happens once */ srp_free(ver); ver = 0; goto cleanup_and_exit; } ver->username = (char *)srp_alloc(ulen); ver->hash_alg = alg; ver->ng = ng; if (!ver->username) { srp_free(ver); ver = 0; goto cleanup_and_exit; } memcpy(ver->username, username, ulen); ver->authenticated = 0; /* SRP-6a safety check */ mpz_mod(tmp1, A, ng->N); if (mpz_sgn(tmp1) != 0) { if (bytes_b) { mpz_from_bin(bytes_b, len_b, b); } else { if (!mpz_fill_random(b)) goto ver_cleanup_and_exit; } if (!H_nn(k, alg, ng->N, ng->N, ng->g)) goto ver_cleanup_and_exit; /* B = kv + g^b */ mpz_mulm(tmp1, k, v, ng->N, tmp3); mpz_powm(tmp2, ng->g, b, ng->N); mpz_addm(B, tmp1, tmp2, ng->N, tmp3); if (!H_nn(u, alg, ng->N, A, B)) goto ver_cleanup_and_exit; srp_dbg_num(u, "Server calculated u: "); /* S = (A *(v^u)) ^ b */ mpz_powm(tmp1, v, u, ng->N); mpz_mulm(tmp2, A, tmp1, ng->N, tmp3); mpz_powm(S, tmp2, b, ng->N); if (!hash_num(alg, S, ver->session_key)) goto ver_cleanup_and_exit; if (!calculate_M( alg, ng, ver->M, username, bytes_s, len_s, A, B, ver->session_key)) { goto ver_cleanup_and_exit; } if (!calculate_H_AMK(alg, ver->H_AMK, A, ver->M, ver->session_key)) { goto ver_cleanup_and_exit; } *len_B = mpz_num_bytes(B); *bytes_B = (unsigned char *)srp_alloc(*len_B); if (!*bytes_B) { *len_B = 0; goto ver_cleanup_and_exit; } mpz_to_bin(B, *bytes_B); ver->bytes_B = *bytes_B; } else { srp_free(ver); ver = 0; } cleanup_and_exit: mpz_clear(v); mpz_clear(A); mpz_clear(u); mpz_clear(k); mpz_clear(B); mpz_clear(S); mpz_clear(b); mpz_clear(tmp1); mpz_clear(tmp2); mpz_clear(tmp3); return ver; ver_cleanup_and_exit: srp_free(ver->username); srp_free(ver); ver = 0; goto cleanup_and_exit; } void srp_verifier_delete(struct SRPVerifier *ver) { if (ver) { delete_ng(ver->ng); srp_free(ver->username); srp_free(ver->bytes_B); memset(ver, 0, sizeof(*ver)); srp_free(ver); } } int srp_verifier_is_authenticated(struct SRPVerifier *ver) { return ver->authenticated; } const char *srp_verifier_get_username(struct SRPVerifier *ver) { return ver->username; } const unsigned char *srp_verifier_get_session_key( struct SRPVerifier *ver, size_t *key_length) { if (key_length) *key_length = hash_length(ver->hash_alg); return ver->session_key; } size_t srp_verifier_get_session_key_length(struct SRPVerifier *ver) { return hash_length(ver->hash_alg); } /* user_M must be exactly SHA512_DIGEST_LENGTH bytes in size */ void srp_verifier_verify_session( struct SRPVerifier *ver, const unsigned char *user_M, unsigned char **bytes_HAMK) { if (memcmp(ver->M, user_M, hash_length(ver->hash_alg)) == 0) { ver->authenticated = 1; *bytes_HAMK = ver->H_AMK; } else *bytes_HAMK = NULL; } /*******************************************************************************/ struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username, const char *username_for_verifier, const unsigned char *bytes_password, size_t len_password, const char *n_hex, const char *g_hex) { struct SRPUser *usr = (struct SRPUser *)srp_alloc(sizeof(struct SRPUser)); size_t ulen = strlen(username) + 1; size_t uvlen = strlen(username_for_verifier) + 1; if (!usr) goto err_exit; if (init_random() != SRP_OK) /* Only happens once */ goto err_exit; usr->hash_alg = alg; usr->ng = new_ng(ng_type, n_hex, g_hex); mpz_init(usr->a); mpz_init(usr->A); mpz_init(usr->S); if (!usr->ng) goto err_exit; usr->username = (char *)srp_alloc(ulen); usr->username_verifier = (char *)srp_alloc(uvlen); usr->password = (unsigned char *)srp_alloc(len_password); usr->password_len = len_password; if (!usr->username || !usr->password || !usr->username_verifier) goto err_exit; memcpy(usr->username, username, ulen); memcpy(usr->username_verifier, username_for_verifier, uvlen); memcpy(usr->password, bytes_password, len_password); usr->authenticated = 0; usr->bytes_A = 0; return usr; err_exit: if (usr) { mpz_clear(usr->a); mpz_clear(usr->A); mpz_clear(usr->S); delete_ng(usr->ng); srp_free(usr->username); srp_free(usr->username_verifier); if (usr->password) { memset(usr->password, 0, usr->password_len); srp_free(usr->password); } srp_free(usr); } return 0; } void srp_user_delete(struct SRPUser *usr) { if (usr) { mpz_clear(usr->a); mpz_clear(usr->A); mpz_clear(usr->S); delete_ng(usr->ng); memset(usr->password, 0, usr->password_len); srp_free(usr->username); srp_free(usr->username_verifier); srp_free(usr->password); if (usr->bytes_A) srp_free(usr->bytes_A); memset(usr, 0, sizeof(*usr)); srp_free(usr); } } int srp_user_is_authenticated(struct SRPUser *usr) { return usr->authenticated; } const char *srp_user_get_username(struct SRPUser *usr) { return usr->username; } const unsigned char *srp_user_get_session_key(struct SRPUser *usr, size_t *key_length) { if (key_length) *key_length = hash_length(usr->hash_alg); return usr->session_key; } size_t srp_user_get_session_key_length(struct SRPUser *usr) { return hash_length(usr->hash_alg); } // clang-format off /* Output: username, bytes_A, len_A */ SRP_Result srp_user_start_authentication(struct SRPUser *usr, char **username, const unsigned char *bytes_a, size_t len_a, unsigned char **bytes_A, size_t *len_A) { // clang-format on if (bytes_a) { mpz_from_bin(bytes_a, len_a, usr->a); } else { if (!mpz_fill_random(usr->a)) goto error_and_exit; } mpz_powm(usr->A, usr->ng->g, usr->a, usr->ng->N); *len_A = mpz_num_bytes(usr->A); *bytes_A = (unsigned char *)srp_alloc(*len_A); if (!*bytes_A) goto error_and_exit; mpz_to_bin(usr->A, *bytes_A); usr->bytes_A = *bytes_A; if (username) *username = usr->username; return SRP_OK; error_and_exit: *len_A = 0; *bytes_A = 0; *username = 0; return SRP_ERR; } // clang-format off /* Output: bytes_M. Buffer length is SHA512_DIGEST_LENGTH */ void srp_user_process_challenge(struct SRPUser *usr, const unsigned char *bytes_s, size_t len_s, const unsigned char *bytes_B, size_t len_B, unsigned char **bytes_M, size_t *len_M) { mpz_t B; mpz_init(B); mpz_from_bin(bytes_B, len_B, B); mpz_t u; mpz_init(u); mpz_t x; mpz_init(x); mpz_t k; mpz_init(k); mpz_t v; mpz_init(v); mpz_t tmp1; mpz_init(tmp1); mpz_t tmp2; mpz_init(tmp2); mpz_t tmp3; mpz_init(tmp3); mpz_t tmp4; mpz_init(tmp4); // clang-format on *len_M = 0; *bytes_M = 0; if (!H_nn(u, usr->hash_alg, usr->ng->N, usr->A, B)) goto cleanup_and_exit; srp_dbg_num(u, "Client calculated u: "); if (!calculate_x(x, usr->hash_alg, bytes_s, len_s, usr->username_verifier, usr->password, usr->password_len)) goto cleanup_and_exit; srp_dbg_num(x, "Client calculated x: "); if (!H_nn(k, usr->hash_alg, usr->ng->N, usr->ng->N, usr->ng->g)) goto cleanup_and_exit; /* SRP-6a safety check */ if (mpz_sgn(B) != 0 && mpz_sgn(u) != 0) { mpz_powm(v, usr->ng->g, x, usr->ng->N); srp_dbg_num(v, "Client calculated v: "); // clang-format off /* S = (B - k*(g^x)) ^ (a + ux) */ mpz_mul(tmp1, u, x); mpz_add(tmp2, usr->a, tmp1); /* tmp2 = (a + ux) */ mpz_powm(tmp1, usr->ng->g, x, usr->ng->N); /* tmp1 = g^x */ mpz_mulm(tmp3, k, tmp1, usr->ng->N, tmp4); /* tmp3 = k*(g^x) */ mpz_subm(tmp1, B, tmp3, usr->ng->N, tmp4); /* tmp1 = (B - K*(g^x)) */ mpz_powm(usr->S, tmp1, tmp2, usr->ng->N); // clang-format on if (!hash_num(usr->hash_alg, usr->S, usr->session_key)) goto cleanup_and_exit; if (!calculate_M(usr->hash_alg, usr->ng, usr->M, usr->username, bytes_s, len_s, usr->A, B, usr->session_key)) goto cleanup_and_exit; if (!calculate_H_AMK(usr->hash_alg, usr->H_AMK, usr->A, usr->M, usr->session_key)) goto cleanup_and_exit; *bytes_M = usr->M; if (len_M) *len_M = hash_length(usr->hash_alg); } else { *bytes_M = NULL; if (len_M) *len_M = 0; } cleanup_and_exit: mpz_clear(B); mpz_clear(u); mpz_clear(x); mpz_clear(k); mpz_clear(v); mpz_clear(tmp1); mpz_clear(tmp2); mpz_clear(tmp3); mpz_clear(tmp4); } void srp_user_verify_session(struct SRPUser *usr, const unsigned char *bytes_HAMK) { if (memcmp(usr->H_AMK, bytes_HAMK, hash_length(usr->hash_alg)) == 0) usr->authenticated = 1; }
pgimeno/minetest
src/util/srp.cpp
C++
mit
27,795
/* * Secure Remote Password 6a implementation * https://github.com/est31/csrp-gmp * * The MIT License (MIT) * * Copyright (c) 2010, 2013 Tom Cocagne, 2015 est31 <MTest31@outlook.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ /* * * Purpose: This is a direct implementation of the Secure Remote Password * Protocol version 6a as described by * http://srp.stanford.edu/design.html * * Author: tom.cocagne@gmail.com (Tom Cocagne) * * Dependencies: LibGMP * * Usage: Refer to test_srp.c for a demonstration * * Notes: * This library allows multiple combinations of hashing algorithms and * prime number constants. For authentication to succeed, the hash and * prime number constants must match between * srp_create_salted_verification_key(), srp_user_new(), * and srp_verifier_new(). A recommended approach is to determine the * desired level of security for an application and globally define the * hash and prime number constants to the predetermined values. * * As one might suspect, more bits means more security. As one might also * suspect, more bits also means more processing time. The test_srp.c * program can be easily modified to profile various combinations of * hash & prime number pairings. */ #pragma once struct SRPVerifier; struct SRPUser; typedef enum { SRP_NG_1024, SRP_NG_2048, SRP_NG_4096, SRP_NG_8192, SRP_NG_CUSTOM } SRP_NGType; typedef enum { /*SRP_SHA1,*/ /*SRP_SHA224,*/ SRP_SHA256, /*SRP_SHA384, SRP_SHA512*/ } SRP_HashAlgorithm; typedef enum { SRP_ERR, SRP_OK, } SRP_Result; // clang-format off /* Sets the memory functions used by srp. * Note: this doesn't set the memory functions used by gmp, * but it is supported to have different functions for srp and gmp. * Don't call this after you have already allocated srp structures. */ void srp_set_memory_functions( void *(*new_srp_alloc) (size_t), void *(*new_srp_realloc) (void *, size_t), void (*new_srp_free) (void *)); /* Out: bytes_v, len_v * * The caller is responsible for freeing the memory allocated for bytes_v * * The n_hex and g_hex parameters should be 0 unless SRP_NG_CUSTOM is used for ng_type. * If provided, they must contain ASCII text of the hexidecimal notation. * * If bytes_s == NULL, it is filled with random data. * The caller is responsible for freeing. * * Returns SRP_OK on success, and SRP_ERR on error. * bytes_s might be in this case invalid, don't free it. */ SRP_Result srp_create_salted_verification_key(SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username_for_verifier, const unsigned char *password, size_t len_password, unsigned char **bytes_s, size_t *len_s, unsigned char **bytes_v, size_t *len_v, const char *n_hex, const char *g_hex); /* Out: bytes_B, len_B. * * On failure, bytes_B will be set to NULL and len_B will be set to 0 * * The n_hex and g_hex parameters should be 0 unless SRP_NG_CUSTOM is used for ng_type * * If bytes_b == NULL, random data is used for b. * * Returns pointer to SRPVerifier on success, and NULL on error. */ struct SRPVerifier* srp_verifier_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username, const unsigned char *bytes_s, size_t len_s, const unsigned char *bytes_v, size_t len_v, const unsigned char *bytes_A, size_t len_A, const unsigned char *bytes_b, size_t len_b, unsigned char** bytes_B, size_t *len_B, const char* n_hex, const char* g_hex); // clang-format on void srp_verifier_delete(struct SRPVerifier *ver); // srp_verifier_verify_session must have been called before int srp_verifier_is_authenticated(struct SRPVerifier *ver); const char *srp_verifier_get_username(struct SRPVerifier *ver); /* key_length may be null */ const unsigned char *srp_verifier_get_session_key( struct SRPVerifier *ver, size_t *key_length); size_t srp_verifier_get_session_key_length(struct SRPVerifier *ver); /* Verifies session, on success, it writes bytes_HAMK. * user_M must be exactly srp_verifier_get_session_key_length() bytes in size */ void srp_verifier_verify_session( struct SRPVerifier *ver, const unsigned char *user_M, unsigned char **bytes_HAMK); /*******************************************************************************/ /* The n_hex and g_hex parameters should be 0 unless SRP_NG_CUSTOM is used for ng_type */ struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, const char *username, const char *username_for_verifier, const unsigned char *bytes_password, size_t len_password, const char *n_hex, const char *g_hex); void srp_user_delete(struct SRPUser *usr); int srp_user_is_authenticated(struct SRPUser *usr); const char *srp_user_get_username(struct SRPUser *usr); /* key_length may be null */ const unsigned char *srp_user_get_session_key(struct SRPUser *usr, size_t *key_length); size_t srp_user_get_session_key_length(struct SRPUser *usr); // clang-format off /* Output: username, bytes_A, len_A. * If you don't want it get written, set username to NULL. * If bytes_a == NULL, random data is used for a. */ SRP_Result srp_user_start_authentication(struct SRPUser* usr, char **username, const unsigned char *bytes_a, size_t len_a, unsigned char **bytes_A, size_t* len_A); /* Output: bytes_M, len_M (len_M may be null and will always be * srp_user_get_session_key_length() bytes in size) */ void srp_user_process_challenge(struct SRPUser *usr, const unsigned char *bytes_s, size_t len_s, const unsigned char *bytes_B, size_t len_B, unsigned char **bytes_M, size_t *len_M); // clang-format on /* bytes_HAMK must be exactly srp_user_get_session_key_length() bytes in size */ void srp_user_verify_session(struct SRPUser *usr, const unsigned char *bytes_HAMK);
pgimeno/minetest
src/util/srp.h
C++
mit
6,840
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> template <typename T> class BasicStrfnd { typedef std::basic_string<T> String; String str; size_t pos; public: BasicStrfnd(const String &s) : str(s), pos(0) {} void start(const String &s) { str = s; pos = 0; } size_t where() { return pos; } void to(size_t i) { pos = i; } bool at_end() { return pos >= str.size(); } String what() { return str; } String next(const String &sep) { if (pos >= str.size()) return String(); size_t n; if (sep.empty() || (n = str.find(sep, pos)) == String::npos) { n = str.size(); } String ret = str.substr(pos, n - pos); pos = n + sep.size(); return ret; } // Returns substr up to the next occurence of sep that isn't escaped with esc ('\\') String next_esc(const String &sep, T esc=static_cast<T>('\\')) { if (pos >= str.size()) return String(); size_t n, old_p = pos; do { if (sep.empty() || (n = str.find(sep, pos)) == String::npos) { pos = n = str.size(); break; } pos = n + sep.length(); } while (n > 0 && str[n - 1] == esc); return str.substr(old_p, n - old_p); } void skip_over(const String &chars) { size_t p = str.find_first_not_of(chars, pos); if (p != String::npos) pos = p; } }; typedef BasicStrfnd<char> Strfnd; typedef BasicStrfnd<wchar_t> WStrfnd;
pgimeno/minetest
src/util/strfnd.h
C++
mit
2,092
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "string.h" #include "pointer.h" #include "numeric.h" #include "log.h" #include "hex.h" #include "porting.h" #include "translation.h" #include <algorithm> #include <sstream> #include <iomanip> #include <map> #ifndef _WIN32 #include <iconv.h> #else #define _WIN32_WINNT 0x0501 #include <windows.h> #endif #if defined(_ICONV_H_) && (defined(__FreeBSD__) || defined(__NetBSD__) || \ defined(__OpenBSD__) || defined(__DragonFly__)) #define BSD_ICONV_USED #endif static bool parseHexColorString(const std::string &value, video::SColor &color, unsigned char default_alpha = 0xff); static bool parseNamedColorString(const std::string &value, video::SColor &color); #ifndef _WIN32 bool convert(const char *to, const char *from, char *outbuf, size_t outbuf_size, char *inbuf, size_t inbuf_size) { iconv_t cd = iconv_open(to, from); #ifdef BSD_ICONV_USED const char *inbuf_ptr = inbuf; #else char *inbuf_ptr = inbuf; #endif char *outbuf_ptr = outbuf; size_t *inbuf_left_ptr = &inbuf_size; size_t *outbuf_left_ptr = &outbuf_size; size_t old_size = inbuf_size; while (inbuf_size > 0) { iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_left_ptr); if (inbuf_size == old_size) { iconv_close(cd); return false; } old_size = inbuf_size; } iconv_close(cd); return true; } std::wstring utf8_to_wide(const std::string &input) { size_t inbuf_size = input.length() + 1; // maximum possible size, every character is sizeof(wchar_t) bytes size_t outbuf_size = (input.length() + 1) * sizeof(wchar_t); char *inbuf = new char[inbuf_size]; memcpy(inbuf, input.c_str(), inbuf_size); char *outbuf = new char[outbuf_size]; memset(outbuf, 0, outbuf_size); if (!convert("WCHAR_T", "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size)) { infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input) << " into wstring" << std::endl; delete[] inbuf; delete[] outbuf; return L"<invalid UTF-8 string>"; } std::wstring out((wchar_t *)outbuf); delete[] inbuf; delete[] outbuf; return out; } #ifdef __ANDROID__ // TODO: this is an ugly fix for wide_to_utf8 somehow not working on android std::string wide_to_utf8(const std::wstring &input) { return wide_to_narrow(input); } #else std::string wide_to_utf8(const std::wstring &input) { size_t inbuf_size = (input.length() + 1) * sizeof(wchar_t); // maximum possible size: utf-8 encodes codepoints using 1 up to 6 bytes size_t outbuf_size = (input.length() + 1) * 6; char *inbuf = new char[inbuf_size]; memcpy(inbuf, input.c_str(), inbuf_size); char *outbuf = new char[outbuf_size]; memset(outbuf, 0, outbuf_size); if (!convert("UTF-8", "WCHAR_T", outbuf, outbuf_size, inbuf, inbuf_size)) { infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size) << " into UTF-8 string" << std::endl; delete[] inbuf; delete[] outbuf; return "<invalid wstring>"; } std::string out(outbuf); delete[] inbuf; delete[] outbuf; return out; } #endif #else // _WIN32 std::wstring utf8_to_wide(const std::string &input) { size_t outbuf_size = input.size() + 1; wchar_t *outbuf = new wchar_t[outbuf_size]; memset(outbuf, 0, outbuf_size * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(), outbuf, outbuf_size); std::wstring out(outbuf); delete[] outbuf; return out; } std::string wide_to_utf8(const std::wstring &input) { size_t outbuf_size = (input.size() + 1) * 6; char *outbuf = new char[outbuf_size]; memset(outbuf, 0, outbuf_size); WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(), outbuf, outbuf_size, NULL, NULL); std::string out(outbuf); delete[] outbuf; return out; } #endif // _WIN32 // You must free the returned string! // The returned string is allocated using new wchar_t *utf8_to_wide_c(const char *str) { std::wstring ret = utf8_to_wide(std::string(str)); size_t len = ret.length(); wchar_t *ret_c = new wchar_t[len + 1]; memset(ret_c, 0, (len + 1) * sizeof(wchar_t)); memcpy(ret_c, ret.c_str(), len * sizeof(wchar_t)); return ret_c; } // You must free the returned string! // The returned string is allocated using new wchar_t *narrow_to_wide_c(const char *str) { wchar_t *nstr = NULL; #if defined(_WIN32) int nResult = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, 0, 0); if (nResult == 0) { errorstream<<"gettext: MultiByteToWideChar returned null"<<std::endl; } else { nstr = new wchar_t[nResult]; MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, (WCHAR *) nstr, nResult); } #else size_t len = strlen(str); nstr = new wchar_t[len + 1]; std::wstring intermediate = narrow_to_wide(str); memset(nstr, 0, (len + 1) * sizeof(wchar_t)); memcpy(nstr, intermediate.c_str(), len * sizeof(wchar_t)); #endif return nstr; } #ifdef __ANDROID__ const wchar_t* wide_chars = L" !\"#$%&'()*+,-./0123456789:;<=>?@" L"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" L"abcdefghijklmnopqrstuvwxyz{|}~"; int wctomb(char *s, wchar_t wc) { for (unsigned int j = 0; j < (sizeof(wide_chars)/sizeof(wchar_t));j++) { if (wc == wide_chars[j]) { *s = (char) (j+32); return 1; } else if (wc == L'\n') { *s = '\n'; return 1; } } return -1; } int mbtowc(wchar_t *pwc, const char *s, size_t n) { std::wstring intermediate = narrow_to_wide(s); if (intermediate.length() > 0) { *pwc = intermediate[0]; return 1; } else { return -1; } } std::wstring narrow_to_wide(const std::string &mbs) { size_t wcl = mbs.size(); std::wstring retval = L""; for (unsigned int i = 0; i < wcl; i++) { if (((unsigned char) mbs[i] >31) && ((unsigned char) mbs[i] < 127)) { retval += wide_chars[(unsigned char) mbs[i] -32]; } //handle newline else if (mbs[i] == '\n') { retval += L'\n'; } } return retval; } #else // not Android std::wstring narrow_to_wide(const std::string &mbs) { size_t wcl = mbs.size(); Buffer<wchar_t> wcs(wcl + 1); size_t len = mbstowcs(*wcs, mbs.c_str(), wcl); if (len == (size_t)(-1)) return L"<invalid multibyte string>"; wcs[len] = 0; return *wcs; } #endif #ifdef __ANDROID__ std::string wide_to_narrow(const std::wstring &wcs) { size_t mbl = wcs.size()*4; std::string retval = ""; for (unsigned int i = 0; i < wcs.size(); i++) { wchar_t char1 = (wchar_t) wcs[i]; if (char1 == L'\n') { retval += '\n'; continue; } for (unsigned int j = 0; j < wcslen(wide_chars);j++) { wchar_t char2 = (wchar_t) wide_chars[j]; if (char1 == char2) { char toadd = (j+32); retval += toadd; break; } } } return retval; } #else // not Android std::string wide_to_narrow(const std::wstring &wcs) { size_t mbl = wcs.size() * 4; SharedBuffer<char> mbs(mbl+1); size_t len = wcstombs(*mbs, wcs.c_str(), mbl); if (len == (size_t)(-1)) return "Character conversion failed!"; mbs[len] = 0; return *mbs; } #endif std::string urlencode(const std::string &str) { // Encodes non-unreserved URI characters by a percent sign // followed by two hex digits. See RFC 3986, section 2.3. static const char url_hex_chars[] = "0123456789ABCDEF"; std::ostringstream oss(std::ios::binary); for (unsigned char c : str) { if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { oss << c; } else { oss << "%" << url_hex_chars[(c & 0xf0) >> 4] << url_hex_chars[c & 0x0f]; } } return oss.str(); } std::string urldecode(const std::string &str) { // Inverse of urlencode std::ostringstream oss(std::ios::binary); for (u32 i = 0; i < str.size(); i++) { unsigned char highvalue, lowvalue; if (str[i] == '%' && hex_digit_decode(str[i+1], highvalue) && hex_digit_decode(str[i+2], lowvalue)) { oss << (char) ((highvalue << 4) | lowvalue); i += 2; } else { oss << str[i]; } } return oss.str(); } u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask) { u32 result = 0; u32 mask = 0; char *s = &str[0]; char *flagstr; char *strpos = NULL; while ((flagstr = strtok_r(s, ",", &strpos))) { s = NULL; while (*flagstr == ' ' || *flagstr == '\t') flagstr++; bool flagset = true; if (!strncasecmp(flagstr, "no", 2)) { flagset = false; flagstr += 2; } for (int i = 0; flagdesc[i].name; i++) { if (!strcasecmp(flagstr, flagdesc[i].name)) { mask |= flagdesc[i].flag; if (flagset) result |= flagdesc[i].flag; break; } } } if (flagmask) *flagmask = mask; return result; } std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask) { std::string result; for (int i = 0; flagdesc[i].name; i++) { if (flagmask & flagdesc[i].flag) { if (!(flags & flagdesc[i].flag)) result += "no"; result += flagdesc[i].name; result += ", "; } } size_t len = result.length(); if (len >= 2) result.erase(len - 2, 2); return result; } size_t mystrlcpy(char *dst, const char *src, size_t size) { size_t srclen = strlen(src) + 1; size_t copylen = MYMIN(srclen, size); if (copylen > 0) { memcpy(dst, src, copylen); dst[copylen - 1] = '\0'; } return srclen; } char *mystrtok_r(char *s, const char *sep, char **lasts) { char *t; if (!s) s = *lasts; while (*s && strchr(sep, *s)) s++; if (!*s) return NULL; t = s; while (*t) { if (strchr(sep, *t)) { *t++ = '\0'; break; } t++; } *lasts = t; return s; } u64 read_seed(const char *str) { char *endptr; u64 num; if (str[0] == '0' && str[1] == 'x') num = strtoull(str, &endptr, 16); else num = strtoull(str, &endptr, 10); if (*endptr) num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337); return num; } bool parseColorString(const std::string &value, video::SColor &color, bool quiet, unsigned char default_alpha) { bool success; if (value[0] == '#') success = parseHexColorString(value, color, default_alpha); else success = parseNamedColorString(value, color); if (!success && !quiet) errorstream << "Invalid color: \"" << value << "\"" << std::endl; return success; } static bool parseHexColorString(const std::string &value, video::SColor &color, unsigned char default_alpha) { unsigned char components[] = { 0x00, 0x00, 0x00, default_alpha }; // R,G,B,A if (value[0] != '#') return false; size_t len = value.size(); bool short_form; if (len == 9 || len == 7) // #RRGGBBAA or #RRGGBB short_form = false; else if (len == 5 || len == 4) // #RGBA or #RGB short_form = true; else return false; bool success = true; for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) { assert(cc < sizeof components / sizeof components[0]); if (short_form) { unsigned char d; if (!hex_digit_decode(value[pos], d)) { success = false; break; } components[cc] = (d & 0xf) << 4 | (d & 0xf); } else { unsigned char d1, d2; if (!hex_digit_decode(value[pos], d1) || !hex_digit_decode(value[pos+1], d2)) { success = false; break; } components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf); pos++; // skip the second digit -- it's already used } } if (success) { color.setRed(components[0]); color.setGreen(components[1]); color.setBlue(components[2]); color.setAlpha(components[3]); } return success; } struct ColorContainer { ColorContainer(); std::map<const std::string, u32> colors; }; ColorContainer::ColorContainer() { colors["aliceblue"] = 0xf0f8ff; colors["antiquewhite"] = 0xfaebd7; colors["aqua"] = 0x00ffff; colors["aquamarine"] = 0x7fffd4; colors["azure"] = 0xf0ffff; colors["beige"] = 0xf5f5dc; colors["bisque"] = 0xffe4c4; colors["black"] = 00000000; colors["blanchedalmond"] = 0xffebcd; colors["blue"] = 0x0000ff; colors["blueviolet"] = 0x8a2be2; colors["brown"] = 0xa52a2a; colors["burlywood"] = 0xdeb887; colors["cadetblue"] = 0x5f9ea0; colors["chartreuse"] = 0x7fff00; colors["chocolate"] = 0xd2691e; colors["coral"] = 0xff7f50; colors["cornflowerblue"] = 0x6495ed; colors["cornsilk"] = 0xfff8dc; colors["crimson"] = 0xdc143c; colors["cyan"] = 0x00ffff; colors["darkblue"] = 0x00008b; colors["darkcyan"] = 0x008b8b; colors["darkgoldenrod"] = 0xb8860b; colors["darkgray"] = 0xa9a9a9; colors["darkgreen"] = 0x006400; colors["darkgrey"] = 0xa9a9a9; colors["darkkhaki"] = 0xbdb76b; colors["darkmagenta"] = 0x8b008b; colors["darkolivegreen"] = 0x556b2f; colors["darkorange"] = 0xff8c00; colors["darkorchid"] = 0x9932cc; colors["darkred"] = 0x8b0000; colors["darksalmon"] = 0xe9967a; colors["darkseagreen"] = 0x8fbc8f; colors["darkslateblue"] = 0x483d8b; colors["darkslategray"] = 0x2f4f4f; colors["darkslategrey"] = 0x2f4f4f; colors["darkturquoise"] = 0x00ced1; colors["darkviolet"] = 0x9400d3; colors["deeppink"] = 0xff1493; colors["deepskyblue"] = 0x00bfff; colors["dimgray"] = 0x696969; colors["dimgrey"] = 0x696969; colors["dodgerblue"] = 0x1e90ff; colors["firebrick"] = 0xb22222; colors["floralwhite"] = 0xfffaf0; colors["forestgreen"] = 0x228b22; colors["fuchsia"] = 0xff00ff; colors["gainsboro"] = 0xdcdcdc; colors["ghostwhite"] = 0xf8f8ff; colors["gold"] = 0xffd700; colors["goldenrod"] = 0xdaa520; colors["gray"] = 0x808080; colors["green"] = 0x008000; colors["greenyellow"] = 0xadff2f; colors["grey"] = 0x808080; colors["honeydew"] = 0xf0fff0; colors["hotpink"] = 0xff69b4; colors["indianred"] = 0xcd5c5c; colors["indigo"] = 0x4b0082; colors["ivory"] = 0xfffff0; colors["khaki"] = 0xf0e68c; colors["lavender"] = 0xe6e6fa; colors["lavenderblush"] = 0xfff0f5; colors["lawngreen"] = 0x7cfc00; colors["lemonchiffon"] = 0xfffacd; colors["lightblue"] = 0xadd8e6; colors["lightcoral"] = 0xf08080; colors["lightcyan"] = 0xe0ffff; colors["lightgoldenrodyellow"] = 0xfafad2; colors["lightgray"] = 0xd3d3d3; colors["lightgreen"] = 0x90ee90; colors["lightgrey"] = 0xd3d3d3; colors["lightpink"] = 0xffb6c1; colors["lightsalmon"] = 0xffa07a; colors["lightseagreen"] = 0x20b2aa; colors["lightskyblue"] = 0x87cefa; colors["lightslategray"] = 0x778899; colors["lightslategrey"] = 0x778899; colors["lightsteelblue"] = 0xb0c4de; colors["lightyellow"] = 0xffffe0; colors["lime"] = 0x00ff00; colors["limegreen"] = 0x32cd32; colors["linen"] = 0xfaf0e6; colors["magenta"] = 0xff00ff; colors["maroon"] = 0x800000; colors["mediumaquamarine"] = 0x66cdaa; colors["mediumblue"] = 0x0000cd; colors["mediumorchid"] = 0xba55d3; colors["mediumpurple"] = 0x9370db; colors["mediumseagreen"] = 0x3cb371; colors["mediumslateblue"] = 0x7b68ee; colors["mediumspringgreen"] = 0x00fa9a; colors["mediumturquoise"] = 0x48d1cc; colors["mediumvioletred"] = 0xc71585; colors["midnightblue"] = 0x191970; colors["mintcream"] = 0xf5fffa; colors["mistyrose"] = 0xffe4e1; colors["moccasin"] = 0xffe4b5; colors["navajowhite"] = 0xffdead; colors["navy"] = 0x000080; colors["oldlace"] = 0xfdf5e6; colors["olive"] = 0x808000; colors["olivedrab"] = 0x6b8e23; colors["orange"] = 0xffa500; colors["orangered"] = 0xff4500; colors["orchid"] = 0xda70d6; colors["palegoldenrod"] = 0xeee8aa; colors["palegreen"] = 0x98fb98; colors["paleturquoise"] = 0xafeeee; colors["palevioletred"] = 0xdb7093; colors["papayawhip"] = 0xffefd5; colors["peachpuff"] = 0xffdab9; colors["peru"] = 0xcd853f; colors["pink"] = 0xffc0cb; colors["plum"] = 0xdda0dd; colors["powderblue"] = 0xb0e0e6; colors["purple"] = 0x800080; colors["red"] = 0xff0000; colors["rosybrown"] = 0xbc8f8f; colors["royalblue"] = 0x4169e1; colors["saddlebrown"] = 0x8b4513; colors["salmon"] = 0xfa8072; colors["sandybrown"] = 0xf4a460; colors["seagreen"] = 0x2e8b57; colors["seashell"] = 0xfff5ee; colors["sienna"] = 0xa0522d; colors["silver"] = 0xc0c0c0; colors["skyblue"] = 0x87ceeb; colors["slateblue"] = 0x6a5acd; colors["slategray"] = 0x708090; colors["slategrey"] = 0x708090; colors["snow"] = 0xfffafa; colors["springgreen"] = 0x00ff7f; colors["steelblue"] = 0x4682b4; colors["tan"] = 0xd2b48c; colors["teal"] = 0x008080; colors["thistle"] = 0xd8bfd8; colors["tomato"] = 0xff6347; colors["turquoise"] = 0x40e0d0; colors["violet"] = 0xee82ee; colors["wheat"] = 0xf5deb3; colors["white"] = 0xffffff; colors["whitesmoke"] = 0xf5f5f5; colors["yellow"] = 0xffff00; colors["yellowgreen"] = 0x9acd32; } static const ColorContainer named_colors; static bool parseNamedColorString(const std::string &value, video::SColor &color) { std::string color_name; std::string alpha_string; /* If the string has a # in it, assume this is the start of a specified * alpha value (if it isn't the string is invalid and the error will be * caught later on, either because the color name won't be found or the * alpha value will fail conversion) */ size_t alpha_pos = value.find('#'); if (alpha_pos != std::string::npos) { color_name = value.substr(0, alpha_pos); alpha_string = value.substr(alpha_pos + 1); } else { color_name = value; } color_name = lowercase(value); std::map<const std::string, unsigned>::const_iterator it; it = named_colors.colors.find(color_name); if (it == named_colors.colors.end()) return false; u32 color_temp = it->second; /* An empty string for alpha is ok (none of the color table entries * have an alpha value either). Color strings without an alpha specified * are interpreted as fully opaque * * For named colors the supplied alpha string (representing a hex value) * must be exactly two digits. For example: colorname#08 */ if (!alpha_string.empty()) { if (alpha_string.length() != 2) return false; unsigned char d1, d2; if (!hex_digit_decode(alpha_string.at(0), d1) || !hex_digit_decode(alpha_string.at(1), d2)) return false; color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24; } else { color_temp |= 0xff << 24; // Fully opaque } color = video::SColor(color_temp); return true; } void str_replace(std::string &str, char from, char to) { std::replace(str.begin(), str.end(), from, to); } /* Translated strings have the following format: * \x1bT marks the beginning of a translated string * \x1bE marks its end * * \x1bF marks the beginning of an argument, and \x1bE its end. * * Arguments are *not* translated, as they may contain escape codes. * Thus, if you want a translated argument, it should be inside \x1bT/\x1bE tags as well. * * This representation is chosen so that clients ignoring escape codes will * see untranslated strings. * * For instance, suppose we have a string such as "@1 Wool" with the argument "White" * The string will be sent as "\x1bT\x1bF\x1bTWhite\x1bE\x1bE Wool\x1bE" * To translate this string, we extract what is inside \x1bT/\x1bE tags. * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end tag, * translating it as well. * We get the argument "White", translated, and create a template string with "@1" instead of it. * We finally get the template "@1 Wool" that was used in the beginning, which we translate * before filling it again. */ void translate_all(const std::wstring &s, size_t &i, std::wstring &res); void translate_string(const std::wstring &s, const std::wstring &textdomain, size_t &i, std::wstring &res) { std::wostringstream output; std::vector<std::wstring> args; int arg_number = 1; while (i < s.length()) { // Not an escape sequence: just add the character. if (s[i] != '\x1b') { output.put(s[i]); // The character is a literal '@'; add it twice // so that it is not mistaken for an argument. if (s[i] == L'@') output.put(L'@'); ++i; continue; } // We have an escape sequence: locate it and its data // It is either a single character, or it begins with '(' // and extends up to the following ')', with '\' as an escape character. ++i; size_t start_index = i; size_t length; if (i == s.length()) { length = 0; } else if (s[i] == L'(') { ++i; ++start_index; while (i < s.length() && s[i] != L')') { if (s[i] == L'\\') ++i; ++i; } length = i - start_index; ++i; if (i > s.length()) i = s.length(); } else { ++i; length = 1; } std::wstring escape_sequence(s, start_index, length); // The escape sequence is now reconstructed. std::vector<std::wstring> parts = split(escape_sequence, L'@'); if (parts[0] == L"E") { // "End of translation" escape sequence. We are done locating the string to translate. break; } else if (parts[0] == L"F") { // "Start of argument" escape sequence. // Recursively translate the argument, and add it to the argument list. // Add an "@n" instead of the argument to the template to translate. if (arg_number >= 10) { errorstream << "Ignoring too many arguments to translation" << std::endl; std::wstring arg; translate_all(s, i, arg); args.push_back(arg); continue; } output.put(L'@'); output << arg_number; ++arg_number; std::wstring arg; translate_all(s, i, arg); args.push_back(arg); } else { // This is an escape sequence *inside* the template string to translate itself. // This should not happen, show an error message. errorstream << "Ignoring escape sequence '" << wide_to_narrow(escape_sequence) << "' in translation" << std::endl; } } // Translate the template. std::wstring toutput = g_translations->getTranslation(textdomain, output.str()); // Put back the arguments in the translated template. std::wostringstream result; size_t j = 0; while (j < toutput.length()) { // Normal character, add it to output and continue. if (toutput[j] != L'@' || j == toutput.length() - 1) { result.put(toutput[j]); ++j; continue; } ++j; // Literal escape for '@'. if (toutput[j] == L'@') { result.put(L'@'); ++j; continue; } // Here we have an argument; get its index and add the translated argument to the output. int arg_index = toutput[j] - L'1'; ++j; if (0 <= arg_index && (size_t)arg_index < args.size()) { result << args[arg_index]; } else { // This is not allowed: show an error message errorstream << "Ignoring out-of-bounds argument escape sequence in translation" << std::endl; } } res = result.str(); } void translate_all(const std::wstring &s, size_t &i, std::wstring &res) { std::wostringstream output; while (i < s.length()) { // Not an escape sequence: just add the character. if (s[i] != '\x1b') { output.put(s[i]); ++i; continue; } // We have an escape sequence: locate it and its data // It is either a single character, or it begins with '(' // and extends up to the following ')', with '\' as an escape character. size_t escape_start = i; ++i; size_t start_index = i; size_t length; if (i == s.length()) { length = 0; } else if (s[i] == L'(') { ++i; ++start_index; while (i < s.length() && s[i] != L')') { if (s[i] == L'\\') { ++i; } ++i; } length = i - start_index; ++i; if (i > s.length()) i = s.length(); } else { ++i; length = 1; } std::wstring escape_sequence(s, start_index, length); // The escape sequence is now reconstructed. std::vector<std::wstring> parts = split(escape_sequence, L'@'); if (parts[0] == L"E") { // "End of argument" escape sequence. Exit. break; } else if (parts[0] == L"T") { // Beginning of translated string. std::wstring textdomain; if (parts.size() > 1) textdomain = parts[1]; std::wstring translated; translate_string(s, textdomain, i, translated); output << translated; } else { // Another escape sequence, such as colors. Preserve it. output << std::wstring(s, escape_start, i - escape_start); } } res = output.str(); } std::wstring translate_string(const std::wstring &s) { size_t i = 0; std::wstring res; translate_all(s, i, res); return res; }
pgimeno/minetest
src/util/string.cpp
C++
mit
26,347
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include <cstdlib> #include <string> #include <cstring> #include <vector> #include <map> #include <sstream> #include <iomanip> #include <cctype> #include <unordered_map> #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) // Checks whether a value is an ASCII printable character #define IS_ASCII_PRINTABLE_CHAR(x) \ (((unsigned int)(x) >= 0x20) && \ ( (unsigned int)(x) <= 0x7e)) // Checks whether a byte is an inner byte for an utf-8 multibyte sequence #define IS_UTF8_MULTB_INNER(x) \ (((unsigned char)(x) >= 0x80) && \ ( (unsigned char)(x) <= 0xbf)) // Checks whether a byte is a start byte for an utf-8 multibyte sequence #define IS_UTF8_MULTB_START(x) \ (((unsigned char)(x) >= 0xc2) && \ ( (unsigned char)(x) <= 0xf4)) // Given a start byte x for an utf-8 multibyte sequence // it gives the length of the whole sequence in bytes. #define UTF8_MULTB_START_LEN(x) \ (((unsigned char)(x) < 0xe0) ? 2 : \ (((unsigned char)(x) < 0xf0) ? 3 : 4)) typedef std::unordered_map<std::string, std::string> StringMap; struct FlagDesc { const char *name; u32 flag; }; // try not to convert between wide/utf8 encodings; this can result in data loss // try to only convert between them when you need to input/output stuff via Irrlicht std::wstring utf8_to_wide(const std::string &input); std::string wide_to_utf8(const std::wstring &input); wchar_t *utf8_to_wide_c(const char *str); // NEVER use those two functions unless you have a VERY GOOD reason to // they just convert between wide and multibyte encoding // multibyte encoding depends on current locale, this is no good, especially on Windows // You must free the returned string! // The returned string is allocated using new wchar_t *narrow_to_wide_c(const char *str); std::wstring narrow_to_wide(const std::string &mbs); std::string wide_to_narrow(const std::wstring &wcs); std::string urlencode(const std::string &str); std::string urldecode(const std::string &str); u32 readFlagString(std::string str, const FlagDesc *flagdesc, u32 *flagmask); std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask); size_t mystrlcpy(char *dst, const char *src, size_t size); char *mystrtok_r(char *s, const char *sep, char **lasts); u64 read_seed(const char *str); bool parseColorString(const std::string &value, video::SColor &color, bool quiet, unsigned char default_alpha = 0xff); /** * Returns a copy of \p str with spaces inserted at the right hand side to ensure * that the string is \p len characters in length. If \p str is <= \p len then the * returned string will be identical to str. */ inline std::string padStringRight(std::string str, size_t len) { if (len > str.size()) str.insert(str.end(), len - str.size(), ' '); return str; } /** * Returns a version of \p str with the first occurrence of a string * contained within ends[] removed from the end of the string. * * @param str * @param ends A NULL- or ""- terminated array of strings to remove from s in * the copy produced. Note that once one of these strings is removed * that no further postfixes contained within this array are removed. * * @return If no end could be removed then "" is returned. */ inline std::string removeStringEnd(const std::string &str, const char *ends[]) { const char **p = ends; for (; *p && (*p)[0] != '\0'; p++) { std::string end = *p; if (str.size() < end.size()) continue; if (str.compare(str.size() - end.size(), end.size(), end) == 0) return str.substr(0, str.size() - end.size()); } return ""; } /** * Check two strings for equivalence. If \p case_insensitive is true * then the case of the strings is ignored (default is false). * * @param s1 * @param s2 * @param case_insensitive * @return true if the strings match */ template <typename T> inline bool str_equal(const std::basic_string<T> &s1, const std::basic_string<T> &s2, bool case_insensitive = false) { if (!case_insensitive) return s1 == s2; if (s1.size() != s2.size()) return false; for (size_t i = 0; i < s1.size(); ++i) if(tolower(s1[i]) != tolower(s2[i])) return false; return true; } /** * Check whether \p str begins with the string prefix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param prefix * @param case_insensitive * @return true if the str begins with prefix */ template <typename T> inline bool str_starts_with(const std::basic_string<T> &str, const std::basic_string<T> &prefix, bool case_insensitive = false) { if (str.size() < prefix.size()) return false; if (!case_insensitive) return str.compare(0, prefix.size(), prefix) == 0; for (size_t i = 0; i < prefix.size(); ++i) if (tolower(str[i]) != tolower(prefix[i])) return false; return true; } /** * Check whether \p str begins with the string prefix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param prefix * @param case_insensitive * @return true if the str begins with prefix */ template <typename T> inline bool str_starts_with(const std::basic_string<T> &str, const T *prefix, bool case_insensitive = false) { return str_starts_with(str, std::basic_string<T>(prefix), case_insensitive); } /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param suffix * @param case_insensitive * @return true if the str begins with suffix */ template <typename T> inline bool str_ends_with(const std::basic_string<T> &str, const std::basic_string<T> &suffix, bool case_insensitive = false) { if (str.size() < suffix.size()) return false; size_t start = str.size() - suffix.size(); if (!case_insensitive) return str.compare(start, suffix.size(), suffix) == 0; for (size_t i = 0; i < suffix.size(); ++i) if (tolower(str[start + i]) != tolower(suffix[i])) return false; return true; } /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is * significant). * * @param str * @param suffix * @param case_insensitive * @return true if the str begins with suffix */ template <typename T> inline bool str_ends_with(const std::basic_string<T> &str, const T *suffix, bool case_insensitive = false) { return str_ends_with(str, std::basic_string<T>(suffix), case_insensitive); } /** * Splits a string into its component parts separated by the character * \p delimiter. * * @return An std::vector<std::basic_string<T> > of the component parts */ template <typename T> inline std::vector<std::basic_string<T> > str_split( const std::basic_string<T> &str, T delimiter) { std::vector<std::basic_string<T> > parts; std::basic_stringstream<T> sstr(str); std::basic_string<T> part; while (std::getline(sstr, part, delimiter)) parts.push_back(part); return parts; } /** * @param str * @return A copy of \p str converted to all lowercase characters. */ inline std::string lowercase(const std::string &str) { std::string s2; s2.reserve(str.size()); for (char i : str) s2 += tolower(i); return s2; } /** * @param str * @return A copy of \p str with leading and trailing whitespace removed. */ inline std::string trim(const std::string &str) { size_t front = 0; while (std::isspace(str[front])) ++front; size_t back = str.size(); while (back > front && std::isspace(str[back - 1])) --back; return str.substr(front, back - front); } /** * Returns whether \p str should be regarded as (bool) true. Case and leading * and trailing whitespace are ignored. Values that will return * true are "y", "yes", "true" and any number that is not 0. * @param str */ inline bool is_yes(const std::string &str) { std::string s2 = lowercase(trim(str)); return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0; } /** * Converts the string \p str to a signed 32-bit integer. The converted value * is constrained so that min <= value <= max. * * @see atoi(3) for limitations * * @param str * @param min Range minimum * @param max Range maximum * @return The value converted to a signed 32-bit integer and constrained * within the range defined by min and max (inclusive) */ inline s32 mystoi(const std::string &str, s32 min, s32 max) { s32 i = atoi(str.c_str()); if (i < min) i = min; if (i > max) i = max; return i; } // MSVC2010 includes it's own versions of these //#if !defined(_MSC_VER) || _MSC_VER < 1600 /** * Returns a 32-bit value reprensented by the string \p str (decimal). * @see atoi(3) for further limitations */ inline s32 mystoi(const std::string &str) { return atoi(str.c_str()); } /** * Returns s 32-bit value represented by the wide string \p str (decimal). * @see atoi(3) for further limitations */ inline s32 mystoi(const std::wstring &str) { return mystoi(wide_to_narrow(str)); } /** * Returns a float reprensented by the string \p str (decimal). * @see atof(3) */ inline float mystof(const std::string &str) { return atof(str.c_str()); } //#endif #define stoi mystoi #define stof mystof /// Returns a value represented by the string \p val. template <typename T> inline T from_string(const std::string &str) { std::stringstream tmp(str); T t; tmp >> t; return t; } /// Returns a 64-bit signed value represented by the string \p str (decimal). inline s64 stoi64(const std::string &str) { return from_string<s64>(str); } #if __cplusplus < 201103L namespace std { /// Returns a string representing the value \p val. template <typename T> inline string to_string(T val) { ostringstream oss; oss << val; return oss.str(); } #define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \ template <> \ inline string to_string<T>(T val) \ { \ ostringstream oss; \ oss << std::fixed \ << std::setprecision(6) \ << val; \ return oss.str(); \ } DEFINE_STD_TOSTRING_FLOATINGPOINT(float) DEFINE_STD_TOSTRING_FLOATINGPOINT(double) DEFINE_STD_TOSTRING_FLOATINGPOINT(long double) #undef DEFINE_STD_TOSTRING_FLOATINGPOINT /// Returns a wide string representing the value \p val template <typename T> inline wstring to_wstring(T val) { return utf8_to_wide(to_string(val)); } } #endif /// Returns a string representing the decimal value of the 32-bit value \p i. inline std::string itos(s32 i) { return std::to_string(i); } /// Returns a string representing the decimal value of the 64-bit value \p i. inline std::string i64tos(s64 i) { return std::to_string(i); } // std::to_string uses the '%.6f' conversion, which is inconsistent with // std::ostream::operator<<() and impractical too. ftos() uses the // more generic and std::ostream::operator<<()-compatible '%G' format. /// Returns a string representing the decimal value of the float value \p f. inline std::string ftos(float f) { std::ostringstream oss; oss << f; return oss.str(); } /** * Replace all occurrences of \p pattern in \p str with \p replacement. * * @param str String to replace pattern with replacement within. * @param pattern The pattern to replace. * @param replacement What to replace the pattern with. */ inline void str_replace(std::string &str, const std::string &pattern, const std::string &replacement) { std::string::size_type start = str.find(pattern, 0); while (start != str.npos) { str.replace(start, pattern.size(), replacement); start = str.find(pattern, start + replacement.size()); } } /** * Escapes characters [ ] \ , ; that can not be used in formspecs */ inline void str_formspec_escape(std::string &str) { str_replace(str, "\\", "\\\\"); str_replace(str, "]", "\\]"); str_replace(str, "[", "\\["); str_replace(str, ";", "\\;"); str_replace(str, ",", "\\,"); } /** * Replace all occurrences of the character \p from in \p str with \p to. * * @param str The string to (potentially) modify. * @param from The character in str to replace. * @param to The replacement character. */ void str_replace(std::string &str, char from, char to); /** * Check that a string only contains whitelisted characters. This is the * opposite of string_allowed_blacklist(). * * @param str The string to be checked. * @param allowed_chars A string containing permitted characters. * @return true if the string is allowed, otherwise false. * * @see string_allowed_blacklist() */ inline bool string_allowed(const std::string &str, const std::string &allowed_chars) { return str.find_first_not_of(allowed_chars) == str.npos; } /** * Check that a string contains no blacklisted characters. This is the * opposite of string_allowed(). * * @param str The string to be checked. * @param blacklisted_chars A string containing prohibited characters. * @return true if the string is allowed, otherwise false. * @see string_allowed() */ inline bool string_allowed_blacklist(const std::string &str, const std::string &blacklisted_chars) { return str.find_first_of(blacklisted_chars) == str.npos; } /** * Create a string based on \p from where a newline is forcefully inserted * every \p row_len characters. * * @note This function does not honour word wraps and blindy inserts a newline * every \p row_len characters whether it breaks a word or not. It is * intended to be used for, for example, showing paths in the GUI. * * @note This function doesn't wrap inside utf-8 multibyte sequences and also * counts multibyte sequences correcly as single characters. * * @param from The (utf-8) string to be wrapped into rows. * @param row_len The row length (in characters). * @return A new string with the wrapping applied. */ inline std::string wrap_rows(const std::string &from, unsigned row_len) { std::string to; size_t character_idx = 0; for (size_t i = 0; i < from.size(); i++) { if (!IS_UTF8_MULTB_INNER(from[i])) { // Wrap string after last inner byte of char if (character_idx > 0 && character_idx % row_len == 0) to += '\n'; character_idx++; } to += from[i]; } return to; } /** * Removes backslashes from an escaped string (FormSpec strings) */ template <typename T> inline std::basic_string<T> unescape_string(const std::basic_string<T> &s) { std::basic_string<T> res; for (size_t i = 0; i < s.length(); i++) { if (s[i] == '\\') { i++; if (i >= s.length()) break; } res += s[i]; } return res; } /** * Remove all escape sequences in \p s. * * @param s The string in which to remove escape sequences. * @return \p s, with escape sequences removed. */ template <typename T> std::basic_string<T> unescape_enriched(const std::basic_string<T> &s) { std::basic_string<T> output; size_t i = 0; while (i < s.length()) { if (s[i] == '\x1b') { ++i; if (i == s.length()) continue; if (s[i] == '(') { ++i; while (i < s.length() && s[i] != ')') { if (s[i] == '\\') { ++i; } ++i; } ++i; } else { ++i; } continue; } output += s[i]; ++i; } return output; } template <typename T> std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim) { std::vector<std::basic_string<T> > tokens; std::basic_string<T> current; bool last_was_escape = false; for (size_t i = 0; i < s.length(); i++) { T si = s[i]; if (last_was_escape) { current += '\\'; current += si; last_was_escape = false; } else { if (si == delim) { tokens.push_back(current); current = std::basic_string<T>(); last_was_escape = false; } else if (si == '\\') { last_was_escape = true; } else { current += si; last_was_escape = false; } } } //push last element tokens.push_back(current); return tokens; } std::wstring translate_string(const std::wstring &s); inline std::wstring unescape_translate(const std::wstring &s) { return unescape_enriched(translate_string(s)); } /** * Checks that all characters in \p to_check are a decimal digits. * * @param to_check * @return true if to_check is not empty and all characters in to_check are * decimal digits, otherwise false */ inline bool is_number(const std::string &to_check) { for (char i : to_check) if (!std::isdigit(i)) return false; return !to_check.empty(); } /** * Returns a C-string, either "true" or "false", corresponding to \p val. * * @return If \p val is true, then "true" is returned, otherwise "false". */ inline const char *bool_to_cstr(bool val) { return val ? "true" : "false"; } inline const std::string duration_to_string(int sec) { int min = sec / 60; sec %= 60; int hour = min / 60; min %= 60; std::stringstream ss; if (hour > 0) { ss << hour << "h "; } if (min > 0) { ss << min << "m "; } if (sec > 0) { ss << sec << "s "; } return ss.str(); } /** * Joins a vector of strings by the string \p delimiter. * * @return A std::string */ inline std::string str_join(const std::vector<std::string> &list, const std::string &delimiter) { std::ostringstream oss; bool first = true; for (const auto &part : list) { if (!first) oss << delimiter; oss << part; first = false; } return oss.str(); }
pgimeno/minetest
src/util/string.h
C++
mit
18,124
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "threading/thread.h" #include "threading/mutex_auto_lock.h" #include "porting.h" #include "log.h" #include "container.h" template<typename T> class MutexedVariable { public: MutexedVariable(const T &value): m_value(value) {} T get() { MutexAutoLock lock(m_mutex); return m_value; } void set(const T &value) { MutexAutoLock lock(m_mutex); m_value = value; } // You pretty surely want to grab the lock when accessing this T m_value; private: std::mutex m_mutex; }; /* A single worker thread - multiple client threads queue framework. */ template<typename Key, typename T, typename Caller, typename CallerData> class GetResult { public: Key key; T item; std::pair<Caller, CallerData> caller; }; template<typename Key, typename T, typename Caller, typename CallerData> class ResultQueue : public MutexedQueue<GetResult<Key, T, Caller, CallerData> > { }; template<typename Caller, typename Data, typename Key, typename T> class CallerInfo { public: Caller caller; Data data; ResultQueue<Key, T, Caller, Data> *dest; }; template<typename Key, typename T, typename Caller, typename CallerData> class GetRequest { public: GetRequest() = default; ~GetRequest() = default; GetRequest(const Key &a_key): key(a_key) { } Key key; std::list<CallerInfo<Caller, CallerData, Key, T> > callers; }; /** * Notes for RequestQueue usage * @param Key unique key to identify a request for a specific resource * @param T ? * @param Caller unique id of calling thread * @param CallerData data passed back to caller */ template<typename Key, typename T, typename Caller, typename CallerData> class RequestQueue { public: bool empty() { return m_queue.empty(); } void add(const Key &key, Caller caller, CallerData callerdata, ResultQueue<Key, T, Caller, CallerData> *dest) { typename std::deque<GetRequest<Key, T, Caller, CallerData> >::iterator i; typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator j; { MutexAutoLock lock(m_queue.getMutex()); /* If the caller is already on the list, only update CallerData */ for (i = m_queue.getQueue().begin(); i != m_queue.getQueue().end(); ++i) { GetRequest<Key, T, Caller, CallerData> &request = *i; if (request.key != key) continue; for (j = request.callers.begin(); j != request.callers.end(); ++j) { CallerInfo<Caller, CallerData, Key, T> &ca = *j; if (ca.caller == caller) { ca.data = callerdata; return; } } CallerInfo<Caller, CallerData, Key, T> ca; ca.caller = caller; ca.data = callerdata; ca.dest = dest; request.callers.push_back(ca); return; } } /* Else add a new request to the queue */ GetRequest<Key, T, Caller, CallerData> request; request.key = key; CallerInfo<Caller, CallerData, Key, T> ca; ca.caller = caller; ca.data = callerdata; ca.dest = dest; request.callers.push_back(ca); m_queue.push_back(request); } GetRequest<Key, T, Caller, CallerData> pop(unsigned int timeout_ms) { return m_queue.pop_front(timeout_ms); } GetRequest<Key, T, Caller, CallerData> pop() { return m_queue.pop_frontNoEx(); } void pushResult(GetRequest<Key, T, Caller, CallerData> req, T res) { for (typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator i = req.callers.begin(); i != req.callers.end(); ++i) { CallerInfo<Caller, CallerData, Key, T> &ca = *i; GetResult<Key,T,Caller,CallerData> result; result.key = req.key; result.item = res; result.caller.first = ca.caller; result.caller.second = ca.data; ca.dest->push_back(result); } } private: MutexedQueue<GetRequest<Key, T, Caller, CallerData> > m_queue; }; class UpdateThread : public Thread { public: UpdateThread(const std::string &name) : Thread(name + "Update") {} ~UpdateThread() = default; void deferUpdate() { m_update_sem.post(); } void stop() { Thread::stop(); // give us a nudge m_update_sem.post(); } void *run() { BEGIN_DEBUG_EXCEPTION_HANDLER while (!stopRequested()) { m_update_sem.wait(); // Set semaphore to 0 while (m_update_sem.wait(0)); if (stopRequested()) break; doUpdate(); } END_DEBUG_EXCEPTION_HANDLER return NULL; } protected: virtual void doUpdate() = 0; private: Semaphore m_update_sem; };
pgimeno/minetest
src/util/thread.h
C++
mit
5,156
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "timetaker.h" #include "porting.h" #include "log.h" #include <ostream> TimeTaker::TimeTaker(const std::string &name, u64 *result, TimePrecision prec) { m_name = name; m_result = result; m_precision = prec; m_time1 = porting::getTime(prec); } u64 TimeTaker::stop(bool quiet) { if (m_running) { u64 dtime = porting::getTime(m_precision) - m_time1; if (m_result != nullptr) { (*m_result) += dtime; } else { if (!quiet) { static const char* const units[] = { "s" /* PRECISION_SECONDS */, "ms" /* PRECISION_MILLI */, "us" /* PRECISION_MICRO */, "ns" /* PRECISION_NANO */, }; infostream << m_name << " took " << dtime << units[m_precision] << std::endl; } } m_running = false; return dtime; } return 0; } u64 TimeTaker::getTimerTime() { return porting::getTime(m_precision) - m_time1; }
pgimeno/minetest
src/util/timetaker.cpp
C++
mit
1,670
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "gettime.h" /* TimeTaker */ class TimeTaker { public: TimeTaker(const std::string &name, u64 *result=nullptr, TimePrecision prec=PRECISION_MILLI); ~TimeTaker() { stop(); } u64 stop(bool quiet=false); u64 getTimerTime(); private: std::string m_name; u64 m_time1; bool m_running = true; TimePrecision m_precision; u64 *m_result = nullptr; };
pgimeno/minetest
src/util/timetaker.h
C++
mit
1,202
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "version.h" #include "config.h" #if defined(__ANDROID__) #include "android_version.h" #include "android_version_githash.h" #elif defined(USE_CMAKE_CONFIG_H) #include "cmake_config_githash.h" #endif #ifndef VERSION_GITHASH #define VERSION_GITHASH VERSION_STRING #endif const char *g_version_string = VERSION_STRING; const char *g_version_hash = VERSION_GITHASH; const char *g_build_info = BUILD_INFO;
pgimeno/minetest
src/version.cpp
C++
mit
1,201
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once extern const char *g_version_string; extern const char *g_version_hash; extern const char *g_build_info;
pgimeno/minetest
src/version.h
C++
mit
904
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "voxel.h" #include "map.h" #include "gettime.h" #include "nodedef.h" #include "util/directiontables.h" #include "util/timetaker.h" #include <cstring> // memcpy, memset /* Debug stuff */ u64 addarea_time = 0; u64 emerge_time = 0; u64 emerge_load_time = 0; u64 clearflag_time = 0; VoxelManipulator::~VoxelManipulator() { clear(); } void VoxelManipulator::clear() { // Reset area to volume=0 m_area = VoxelArea(); delete[] m_data; m_data = nullptr; delete[] m_flags; m_flags = nullptr; } void VoxelManipulator::print(std::ostream &o, const NodeDefManager *ndef, VoxelPrintMode mode) { const v3s16 &em = m_area.getExtent(); v3s16 of = m_area.MinEdge; o<<"size: "<<em.X<<"x"<<em.Y<<"x"<<em.Z <<" offset: ("<<of.X<<","<<of.Y<<","<<of.Z<<")"<<std::endl; for(s32 y=m_area.MaxEdge.Y; y>=m_area.MinEdge.Y; y--) { if(em.X >= 3 && em.Y >= 3) { if (y==m_area.MinEdge.Y+2) o<<"^ "; else if(y==m_area.MinEdge.Y+1) o<<"| "; else if(y==m_area.MinEdge.Y+0) o<<"y x-> "; else o<<" "; } for(s32 z=m_area.MinEdge.Z; z<=m_area.MaxEdge.Z; z++) { for(s32 x=m_area.MinEdge.X; x<=m_area.MaxEdge.X; x++) { u8 f = m_flags[m_area.index(x,y,z)]; char c; if(f & VOXELFLAG_NO_DATA) c = 'N'; else { c = 'X'; MapNode n = m_data[m_area.index(x,y,z)]; content_t m = n.getContent(); u8 pr = n.param2; if(mode == VOXELPRINT_MATERIAL) { if(m <= 9) c = m + '0'; } else if(mode == VOXELPRINT_WATERPRESSURE) { if(ndef->get(m).isLiquid()) { c = 'w'; if(pr <= 9) c = pr + '0'; } else if(m == CONTENT_AIR) { c = ' '; } else { c = '#'; } } else if(mode == VOXELPRINT_LIGHT_DAY) { if(ndef->get(m).light_source != 0) c = 'S'; else if(!ndef->get(m).light_propagates) c = 'X'; else { u8 light = n.getLight(LIGHTBANK_DAY, ndef); if(light < 10) c = '0' + light; else c = 'a' + (light-10); } } } o<<c; } o<<' '; } o<<std::endl; } } void VoxelManipulator::addArea(const VoxelArea &area) { // Cancel if requested area has zero volume if (area.hasEmptyExtent()) return; // Cancel if m_area already contains the requested area if(m_area.contains(area)) return; TimeTaker timer("addArea", &addarea_time); // Calculate new area VoxelArea new_area; // New area is the requested area if m_area has zero volume if(m_area.hasEmptyExtent()) { new_area = area; } // Else add requested area to m_area else { new_area = m_area; new_area.addArea(area); } s32 new_size = new_area.getVolume(); /*dstream<<"adding area "; area.print(dstream); dstream<<", old area "; m_area.print(dstream); dstream<<", new area "; new_area.print(dstream); dstream<<", new_size="<<new_size; dstream<<std::endl;*/ // Allocate new data and clear flags MapNode *new_data = new MapNode[new_size]; assert(new_data); u8 *new_flags = new u8[new_size]; assert(new_flags); memset(new_flags, VOXELFLAG_NO_DATA, new_size); // Copy old data s32 old_x_width = m_area.MaxEdge.X - m_area.MinEdge.X + 1; for(s32 z=m_area.MinEdge.Z; z<=m_area.MaxEdge.Z; z++) for(s32 y=m_area.MinEdge.Y; y<=m_area.MaxEdge.Y; y++) { unsigned int old_index = m_area.index(m_area.MinEdge.X,y,z); unsigned int new_index = new_area.index(m_area.MinEdge.X,y,z); memcpy(&new_data[new_index], &m_data[old_index], old_x_width * sizeof(MapNode)); memcpy(&new_flags[new_index], &m_flags[old_index], old_x_width * sizeof(u8)); } // Replace area, data and flags m_area = new_area; MapNode *old_data = m_data; u8 *old_flags = m_flags; /*dstream<<"old_data="<<(int)old_data<<", new_data="<<(int)new_data <<", old_flags="<<(int)m_flags<<", new_flags="<<(int)new_flags<<std::endl;*/ m_data = new_data; m_flags = new_flags; delete[] old_data; delete[] old_flags; //dstream<<"addArea done"<<std::endl; } void VoxelManipulator::copyFrom(MapNode *src, const VoxelArea& src_area, v3s16 from_pos, v3s16 to_pos, const v3s16 &size) { /* The reason for this optimised code is that we're a member function * and the data type/layout of m_data is know to us: it's stored as * [z*h*w + y*h + x]. Therefore we can take the calls to m_area index * (which performs the preceding mapping/indexing of m_data) out of the * inner loop and calculate the next index as we're iterating to gain * performance. * * src_step and dest_step is the amount required to be added to our index * every time y increments. Because the destination area may be larger * than the source area we need one additional variable (otherwise we could * just continue adding dest_step as is done for the source data): dest_mod. * dest_mod is the difference in size between a "row" in the source data * and a "row" in the destination data (I am using the term row loosely * and for illustrative purposes). E.g. * * src <-------------------->|'''''' dest mod '''''''' * dest <---------------------------------------------> * * dest_mod (it's essentially a modulus) is added to the destination index * after every full iteration of the y span. * * This method falls under the category "linear array and incrementing * index". */ s32 src_step = src_area.getExtent().X; s32 dest_step = m_area.getExtent().X; s32 dest_mod = m_area.index(to_pos.X, to_pos.Y, to_pos.Z + 1) - m_area.index(to_pos.X, to_pos.Y, to_pos.Z) - dest_step * size.Y; s32 i_src = src_area.index(from_pos.X, from_pos.Y, from_pos.Z); s32 i_local = m_area.index(to_pos.X, to_pos.Y, to_pos.Z); for (s16 z = 0; z < size.Z; z++) { for (s16 y = 0; y < size.Y; y++) { memcpy(&m_data[i_local], &src[i_src], size.X * sizeof(*m_data)); memset(&m_flags[i_local], 0, size.X); i_src += src_step; i_local += dest_step; } i_local += dest_mod; } } void VoxelManipulator::copyTo(MapNode *dst, const VoxelArea& dst_area, v3s16 dst_pos, v3s16 from_pos, const v3s16 &size) { for(s16 z=0; z<size.Z; z++) for(s16 y=0; y<size.Y; y++) { s32 i_dst = dst_area.index(dst_pos.X, dst_pos.Y+y, dst_pos.Z+z); s32 i_local = m_area.index(from_pos.X, from_pos.Y+y, from_pos.Z+z); for (s16 x = 0; x < size.X; x++) { if (m_data[i_local].getContent() != CONTENT_IGNORE) dst[i_dst] = m_data[i_local]; i_dst++; i_local++; } } } /* Algorithms ----------------------------------------------------- */ void VoxelManipulator::clearFlag(u8 flags) { // 0-1ms on moderate area TimeTaker timer("clearFlag", &clearflag_time); //v3s16 s = m_area.getExtent(); /*dstream<<"clearFlag clearing area of size " <<""<<s.X<<"x"<<s.Y<<"x"<<s.Z<<"" <<std::endl;*/ //s32 count = 0; /*for(s32 z=m_area.MinEdge.Z; z<=m_area.MaxEdge.Z; z++) for(s32 y=m_area.MinEdge.Y; y<=m_area.MaxEdge.Y; y++) for(s32 x=m_area.MinEdge.X; x<=m_area.MaxEdge.X; x++) { u8 f = m_flags[m_area.index(x,y,z)]; m_flags[m_area.index(x,y,z)] &= ~flags; if(m_flags[m_area.index(x,y,z)] != f) count++; }*/ s32 volume = m_area.getVolume(); for(s32 i=0; i<volume; i++) { m_flags[i] &= ~flags; } /*s32 volume = m_area.getVolume(); for(s32 i=0; i<volume; i++) { u8 f = m_flags[i]; m_flags[i] &= ~flags; if(m_flags[i] != f) count++; } dstream<<"clearFlag changed "<<count<<" flags out of " <<volume<<" nodes"<<std::endl;*/ } const MapNode VoxelManipulator::ContentIgnoreNode = MapNode(CONTENT_IGNORE); //END
pgimeno/minetest
src/voxel.cpp
C++
mit
8,345
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "irr_v3d.h" #include <iostream> #include <cassert> #include "exceptions.h" #include "mapnode.h" #include <set> #include <list> #include "util/basic_macros.h" class NodeDefManager; // For VC++ #undef min #undef max /* A fast voxel manipulator class. In normal operation, it fetches more map when it is requested. It can also be used so that all allowed area is fetched at the start, using ManualMapVoxelManipulator. Not thread-safe. */ /* Debug stuff */ extern u64 emerge_time; extern u64 emerge_load_time; /* This class resembles aabbox3d<s16> a lot, but has inclusive edges for saner handling of integer sizes */ class VoxelArea { public: // Starts as zero sized VoxelArea() = default; VoxelArea(const v3s16 &min_edge, const v3s16 &max_edge): MinEdge(min_edge), MaxEdge(max_edge) { cacheExtent(); } VoxelArea(const v3s16 &p): MinEdge(p), MaxEdge(p) { cacheExtent(); } /* Modifying methods */ void addArea(const VoxelArea &a) { if (hasEmptyExtent()) { *this = a; return; } if(a.MinEdge.X < MinEdge.X) MinEdge.X = a.MinEdge.X; if(a.MinEdge.Y < MinEdge.Y) MinEdge.Y = a.MinEdge.Y; if(a.MinEdge.Z < MinEdge.Z) MinEdge.Z = a.MinEdge.Z; if(a.MaxEdge.X > MaxEdge.X) MaxEdge.X = a.MaxEdge.X; if(a.MaxEdge.Y > MaxEdge.Y) MaxEdge.Y = a.MaxEdge.Y; if(a.MaxEdge.Z > MaxEdge.Z) MaxEdge.Z = a.MaxEdge.Z; cacheExtent(); } void addPoint(const v3s16 &p) { if(hasEmptyExtent()) { MinEdge = p; MaxEdge = p; cacheExtent(); return; } if(p.X < MinEdge.X) MinEdge.X = p.X; if(p.Y < MinEdge.Y) MinEdge.Y = p.Y; if(p.Z < MinEdge.Z) MinEdge.Z = p.Z; if(p.X > MaxEdge.X) MaxEdge.X = p.X; if(p.Y > MaxEdge.Y) MaxEdge.Y = p.Y; if(p.Z > MaxEdge.Z) MaxEdge.Z = p.Z; cacheExtent(); } // Pad with d nodes void pad(const v3s16 &d) { MinEdge -= d; MaxEdge += d; } /* const methods */ const v3s16 &getExtent() const { return m_cache_extent; } /* Because MaxEdge and MinEdge are included in the voxel area an empty extent * is not represented by (0, 0, 0), but instead (-1, -1, -1) */ bool hasEmptyExtent() const { return MaxEdge - MinEdge == v3s16(-1, -1, -1); } s32 getVolume() const { return (s32)m_cache_extent.X * (s32)m_cache_extent.Y * (s32)m_cache_extent.Z; } bool contains(const VoxelArea &a) const { // No area contains an empty area // NOTE: Algorithms depend on this, so do not change. if(a.hasEmptyExtent()) return false; return( a.MinEdge.X >= MinEdge.X && a.MaxEdge.X <= MaxEdge.X && a.MinEdge.Y >= MinEdge.Y && a.MaxEdge.Y <= MaxEdge.Y && a.MinEdge.Z >= MinEdge.Z && a.MaxEdge.Z <= MaxEdge.Z ); } bool contains(v3s16 p) const { return( p.X >= MinEdge.X && p.X <= MaxEdge.X && p.Y >= MinEdge.Y && p.Y <= MaxEdge.Y && p.Z >= MinEdge.Z && p.Z <= MaxEdge.Z ); } bool contains(s32 i) const { return (i >= 0 && i < getVolume()); } bool operator==(const VoxelArea &other) const { return (MinEdge == other.MinEdge && MaxEdge == other.MaxEdge); } VoxelArea operator+(const v3s16 &off) const { return {MinEdge+off, MaxEdge+off}; } VoxelArea operator-(const v3s16 &off) const { return {MinEdge-off, MaxEdge-off}; } /* Returns 0-6 non-overlapping areas that can be added to a to make up this area. a: area inside *this */ void diff(const VoxelArea &a, std::list<VoxelArea> &result) { /* This can result in a maximum of 6 areas */ // If a is an empty area, return the current area as a whole if(a.getExtent() == v3s16(0,0,0)) { VoxelArea b = *this; if(b.getVolume() != 0) result.push_back(b); return; } assert(contains(a)); // pre-condition // Take back area, XY inclusive { v3s16 min(MinEdge.X, MinEdge.Y, a.MaxEdge.Z+1); v3s16 max(MaxEdge.X, MaxEdge.Y, MaxEdge.Z); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } // Take front area, XY inclusive { v3s16 min(MinEdge.X, MinEdge.Y, MinEdge.Z); v3s16 max(MaxEdge.X, MaxEdge.Y, a.MinEdge.Z-1); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } // Take top area, X inclusive { v3s16 min(MinEdge.X, a.MaxEdge.Y+1, a.MinEdge.Z); v3s16 max(MaxEdge.X, MaxEdge.Y, a.MaxEdge.Z); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } // Take bottom area, X inclusive { v3s16 min(MinEdge.X, MinEdge.Y, a.MinEdge.Z); v3s16 max(MaxEdge.X, a.MinEdge.Y-1, a.MaxEdge.Z); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } // Take left area, non-inclusive { v3s16 min(MinEdge.X, a.MinEdge.Y, a.MinEdge.Z); v3s16 max(a.MinEdge.X-1, a.MaxEdge.Y, a.MaxEdge.Z); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } // Take right area, non-inclusive { v3s16 min(a.MaxEdge.X+1, a.MinEdge.Y, a.MinEdge.Z); v3s16 max(MaxEdge.X, a.MaxEdge.Y, a.MaxEdge.Z); VoxelArea b(min, max); if(b.getVolume() != 0) result.push_back(b); } } /* Translates position from virtual coordinates to array index */ s32 index(s16 x, s16 y, s16 z) const { s32 i = (s32)(z - MinEdge.Z) * m_cache_extent.Y * m_cache_extent.X + (y - MinEdge.Y) * m_cache_extent.X + (x - MinEdge.X); return i; } s32 index(v3s16 p) const { return index(p.X, p.Y, p.Z); } /** * Translate index in the X coordinate */ static void add_x(const v3s16 &extent, u32 &i, s16 a) { i += a; } /** * Translate index in the Y coordinate */ static void add_y(const v3s16 &extent, u32 &i, s16 a) { i += a * extent.X; } /** * Translate index in the Z coordinate */ static void add_z(const v3s16 &extent, u32 &i, s16 a) { i += a * extent.X * extent.Y; } /** * Translate index in space */ static void add_p(const v3s16 &extent, u32 &i, v3s16 a) { i += a.Z * extent.X * extent.Y + a.Y * extent.X + a.X; } /* Print method for debugging */ void print(std::ostream &o) const { o << PP(MinEdge) << PP(MaxEdge) << "=" << m_cache_extent.X << "x" << m_cache_extent.Y << "x" << m_cache_extent.Z << "=" << getVolume(); } // Edges are inclusive v3s16 MinEdge = v3s16(1,1,1); v3s16 MaxEdge; private: void cacheExtent() { m_cache_extent = MaxEdge - MinEdge + v3s16(1,1,1); } v3s16 m_cache_extent = v3s16(0,0,0); }; // unused #define VOXELFLAG_UNUSED (1 << 0) // no data about that node #define VOXELFLAG_NO_DATA (1 << 1) // Algorithm-dependent #define VOXELFLAG_CHECKED1 (1 << 2) // Algorithm-dependent #define VOXELFLAG_CHECKED2 (1 << 3) // Algorithm-dependent #define VOXELFLAG_CHECKED3 (1 << 4) // Algorithm-dependent #define VOXELFLAG_CHECKED4 (1 << 5) enum VoxelPrintMode { VOXELPRINT_NOTHING, VOXELPRINT_MATERIAL, VOXELPRINT_WATERPRESSURE, VOXELPRINT_LIGHT_DAY, }; class VoxelManipulator { public: VoxelManipulator() = default; virtual ~VoxelManipulator(); /* These are a bit slow and shouldn't be used internally. Use m_data[m_area.index(p)] instead. */ MapNode getNode(const v3s16 &p) { VoxelArea voxel_area(p); addArea(voxel_area); if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) { /*dstream<<"EXCEPT: VoxelManipulator::getNode(): " <<"p=("<<p.X<<","<<p.Y<<","<<p.Z<<")" <<", index="<<m_area.index(p) <<", flags="<<(int)m_flags[m_area.index(p)] <<" is inexistent"<<std::endl;*/ throw InvalidPositionException ("VoxelManipulator: getNode: inexistent"); } return m_data[m_area.index(p)]; } MapNode getNodeNoEx(const v3s16 &p) { VoxelArea voxel_area(p); addArea(voxel_area); if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) { return {CONTENT_IGNORE}; } return m_data[m_area.index(p)]; } MapNode getNodeNoExNoEmerge(const v3s16 &p) { if (!m_area.contains(p)) return {CONTENT_IGNORE}; if (m_flags[m_area.index(p)] & VOXELFLAG_NO_DATA) return {CONTENT_IGNORE}; return m_data[m_area.index(p)]; } // Stuff explodes if non-emerged area is touched with this. // Emerge first, and check VOXELFLAG_NO_DATA if appropriate. MapNode & getNodeRefUnsafe(const v3s16 &p) { return m_data[m_area.index(p)]; } const MapNode & getNodeRefUnsafeCheckFlags(const v3s16 &p) { s32 index = m_area.index(p); if (m_flags[index] & VOXELFLAG_NO_DATA) return ContentIgnoreNode; return m_data[index]; } u8 & getFlagsRefUnsafe(const v3s16 &p) { return m_flags[m_area.index(p)]; } bool exists(const v3s16 &p) { return m_area.contains(p) && !(getFlagsRefUnsafe(p) & VOXELFLAG_NO_DATA); } void setNode(const v3s16 &p, const MapNode &n) { VoxelArea voxel_area(p); addArea(voxel_area); m_data[m_area.index(p)] = n; m_flags[m_area.index(p)] &= ~VOXELFLAG_NO_DATA; } // TODO: Should be removed and replaced with setNode void setNodeNoRef(const v3s16 &p, const MapNode &n) { setNode(p, n); } /* Set stuff if available without an emerge. Return false if failed. This is convenient but slower than playing around directly with the m_data table with indices. */ bool setNodeNoEmerge(const v3s16 &p, MapNode n) { if(!m_area.contains(p)) return false; m_data[m_area.index(p)] = n; return true; } /* Control */ virtual void clear(); void print(std::ostream &o, const NodeDefManager *nodemgr, VoxelPrintMode mode=VOXELPRINT_MATERIAL); void addArea(const VoxelArea &area); /* Copy data and set flags to 0 dst_area.getExtent() <= src_area.getExtent() */ void copyFrom(MapNode *src, const VoxelArea& src_area, v3s16 from_pos, v3s16 to_pos, const v3s16 &size); // Copy data void copyTo(MapNode *dst, const VoxelArea& dst_area, v3s16 dst_pos, v3s16 from_pos, const v3s16 &size); /* Algorithms */ void clearFlag(u8 flag); /* Member variables */ /* The area that is stored in m_data. addInternalBox should not be used if getExtent() == v3s16(0,0,0) MaxEdge is 1 higher than maximum allowed position */ VoxelArea m_area; /* nullptr if data size is 0 (extent (0,0,0)) Data is stored as [z*h*w + y*h + x] */ MapNode *m_data = nullptr; /* Flags of all nodes */ u8 *m_flags = nullptr; static const MapNode ContentIgnoreNode; };
pgimeno/minetest
src/voxel.h
C++
mit
10,952
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "voxelalgorithms.h" #include "nodedef.h" #include "mapblock.h" #include "map.h" namespace voxalgo { /*! * A direction. * 0=X+ * 1=Y+ * 2=Z+ * 3=Z- * 4=Y- * 5=X- * 6=no direction * Two directions are opposite only if their sum is 5. */ typedef u8 direction; /*! * Relative node position. * This represents a node's position in its map block. * All coordinates must be between 0 and 15. */ typedef v3s16 relative_v3; /*! * Position of a map block (block coordinates). * One block_pos unit is as long as 16 node position units. */ typedef v3s16 mapblock_v3; //! Contains information about a node whose light is about to change. struct ChangingLight { //! Relative position of the node in its map block. relative_v3 rel_position; //! Position of the node's block. mapblock_v3 block_position; //! Pointer to the node's block. MapBlock *block = NULL; /*! * Direction from the node that caused this node's changing * to this node. */ direction source_direction = 6; ChangingLight() = default; ChangingLight(const relative_v3 &rel_pos, const mapblock_v3 &block_pos, MapBlock *b, direction source_dir) : rel_position(rel_pos), block_position(block_pos), block(b), source_direction(source_dir) {} }; /*! * A fast, priority queue-like container to contain ChangingLights. * The ChangingLights are ordered by the given light levels. * The brightest ChangingLight is returned first. */ struct LightQueue { //! For each light level there is a vector. std::vector<ChangingLight> lights[LIGHT_SUN + 1]; //! Light of the brightest ChangingLight in the queue. u8 max_light; /*! * Creates a LightQueue. * \param reserve for each light level that many slots are reserved. */ LightQueue(size_t reserve) { max_light = LIGHT_SUN; for (u8 i = 0; i <= LIGHT_SUN; i++) { lights[i].reserve(reserve); } } /*! * Returns the next brightest ChangingLight and * removes it from the queue. * If there were no elements in the queue, the given parameters * remain unmodified. * \param light light level of the popped ChangingLight * \param data the ChangingLight that was popped * \returns true if there was a ChangingLight in the queue. */ bool next(u8 &light, ChangingLight &data) { while (lights[max_light].empty()) { if (max_light == 0) { return false; } max_light--; } light = max_light; data = lights[max_light].back(); lights[max_light].pop_back(); return true; } /*! * Adds an element to the queue. * The parameters are the same as in ChangingLight's constructor. * \param light light level of the ChangingLight */ inline void push(u8 light, const relative_v3 &rel_pos, const mapblock_v3 &block_pos, MapBlock *block, direction source_dir) { assert(light <= LIGHT_SUN); lights[light].emplace_back(rel_pos, block_pos, block, source_dir); } }; /*! * This type of light queue is for unlighting. * A node can be pushed in it only if its raw light is zero. * This prevents pushing nodes twice into this queue. * The light of the pushed ChangingLight must be the * light of the node before unlighting it. */ typedef LightQueue UnlightQueue; /*! * This type of light queue is for spreading lights. * While spreading lights, all the nodes in it must * have the same light as the light level the ChangingLights * were pushed into this queue with. This prevents unnecessary * re-pushing of the nodes into the queue. * If a node doesn't let light trough but emits light, it can be added * too. */ typedef LightQueue ReLightQueue; /*! * neighbor_dirs[i] points towards * the direction i. * See the definition of the type "direction" */ const static v3s16 neighbor_dirs[6] = { v3s16(1, 0, 0), // right v3s16(0, 1, 0), // top v3s16(0, 0, 1), // back v3s16(0, 0, -1), // front v3s16(0, -1, 0), // bottom v3s16(-1, 0, 0), // left }; /*! * Transforms the given map block offset by one node towards * the specified direction. * \param dir the direction of the transformation * \param rel_pos the node's relative position in its map block * \param block_pos position of the node's block */ bool step_rel_block_pos(direction dir, relative_v3 &rel_pos, mapblock_v3 &block_pos) { switch (dir) { case 0: if (rel_pos.X < MAP_BLOCKSIZE - 1) { rel_pos.X++; } else { rel_pos.X = 0; block_pos.X++; return true; } break; case 1: if (rel_pos.Y < MAP_BLOCKSIZE - 1) { rel_pos.Y++; } else { rel_pos.Y = 0; block_pos.Y++; return true; } break; case 2: if (rel_pos.Z < MAP_BLOCKSIZE - 1) { rel_pos.Z++; } else { rel_pos.Z = 0; block_pos.Z++; return true; } break; case 3: if (rel_pos.Z > 0) { rel_pos.Z--; } else { rel_pos.Z = MAP_BLOCKSIZE - 1; block_pos.Z--; return true; } break; case 4: if (rel_pos.Y > 0) { rel_pos.Y--; } else { rel_pos.Y = MAP_BLOCKSIZE - 1; block_pos.Y--; return true; } break; case 5: if (rel_pos.X > 0) { rel_pos.X--; } else { rel_pos.X = MAP_BLOCKSIZE - 1; block_pos.X--; return true; } break; } return false; } /* * Removes all light that is potentially emitted by the specified * light sources. These nodes will have zero light. * Returns all nodes whose light became zero but should be re-lighted. * * \param bank the light bank in which the procedure operates * \param from_nodes nodes whose light is removed * \param light_sources nodes that should be re-lighted * \param modified_blocks output, all modified map blocks are added to this */ void unspread_light(Map *map, const NodeDefManager *nodemgr, LightBank bank, UnlightQueue &from_nodes, ReLightQueue &light_sources, std::map<v3s16, MapBlock*> &modified_blocks) { // Stores data popped from from_nodes u8 current_light; ChangingLight current; // Data of the current neighbor mapblock_v3 neighbor_block_pos; relative_v3 neighbor_rel_pos; // A dummy boolean bool is_valid_position; // Direction of the brightest neighbor of the node direction source_dir; while (from_nodes.next(current_light, current)) { // For all nodes that need unlighting // There is no brightest neighbor source_dir = 6; // The current node const MapNode &node = current.block->getNodeNoCheck( current.rel_position, &is_valid_position); const ContentFeatures &f = nodemgr->get(node); // If the node emits light, it behaves like it had a // brighter neighbor. u8 brightest_neighbor_light = f.light_source + 1; for (direction i = 0; i < 6; i++) { //For each neighbor // The node that changed this node has already zero light // and it can't give light to this node if (current.source_direction + i == 5) { continue; } // Get the neighbor's position and block neighbor_rel_pos = current.rel_position; neighbor_block_pos = current.block_position; MapBlock *neighbor_block; if (step_rel_block_pos(i, neighbor_rel_pos, neighbor_block_pos)) { neighbor_block = map->getBlockNoCreateNoEx(neighbor_block_pos); if (neighbor_block == NULL) { current.block->setLightingComplete(bank, i, false); continue; } } else { neighbor_block = current.block; } // Get the neighbor itself MapNode neighbor = neighbor_block->getNodeNoCheck(neighbor_rel_pos, &is_valid_position); const ContentFeatures &neighbor_f = nodemgr->get( neighbor.getContent()); u8 neighbor_light = neighbor.getLightRaw(bank, neighbor_f); // If the neighbor has at least as much light as this node, then // it won't lose its light, since it should have been added to // from_nodes earlier, so its light would be zero. if (neighbor_f.light_propagates && neighbor_light < current_light) { // Unlight, but only if the node has light. if (neighbor_light > 0) { neighbor.setLight(bank, 0, neighbor_f); neighbor_block->setNodeNoCheck(neighbor_rel_pos, neighbor); from_nodes.push(neighbor_light, neighbor_rel_pos, neighbor_block_pos, neighbor_block, i); // The current node was modified earlier, so its block // is in modified_blocks. if (current.block != neighbor_block) { modified_blocks[neighbor_block_pos] = neighbor_block; } } } else { // The neighbor can light up this node. if (neighbor_light < neighbor_f.light_source) { neighbor_light = neighbor_f.light_source; } if (brightest_neighbor_light < neighbor_light) { brightest_neighbor_light = neighbor_light; source_dir = i; } } } // If the brightest neighbor is able to light up this node, // then add this node to the output nodes. if (brightest_neighbor_light > 1 && f.light_propagates) { brightest_neighbor_light--; light_sources.push(brightest_neighbor_light, current.rel_position, current.block_position, current.block, (source_dir == 6) ? 6 : 5 - source_dir /* with opposite direction*/); } } } /* * Spreads light from the specified starting nodes. * * Before calling this procedure, make sure that all ChangingLights * in light_sources have as much light on the map as they have in * light_sources (if the queue contains a node multiple times, the brightest * occurrence counts). * * \param bank the light bank in which the procedure operates * \param light_sources starting nodes * \param modified_blocks output, all modified map blocks are added to this */ void spread_light(Map *map, const NodeDefManager *nodemgr, LightBank bank, LightQueue &light_sources, std::map<v3s16, MapBlock*> &modified_blocks) { // The light the current node can provide to its neighbors. u8 spreading_light; // The ChangingLight for the current node. ChangingLight current; // Position of the current neighbor. mapblock_v3 neighbor_block_pos; relative_v3 neighbor_rel_pos; // A dummy boolean. bool is_valid_position; while (light_sources.next(spreading_light, current)) { spreading_light--; for (direction i = 0; i < 6; i++) { // This node can't light up its light source if (current.source_direction + i == 5) { continue; } // Get the neighbor's position and block neighbor_rel_pos = current.rel_position; neighbor_block_pos = current.block_position; MapBlock *neighbor_block; if (step_rel_block_pos(i, neighbor_rel_pos, neighbor_block_pos)) { neighbor_block = map->getBlockNoCreateNoEx(neighbor_block_pos); if (neighbor_block == NULL) { current.block->setLightingComplete(bank, i, false); continue; } } else { neighbor_block = current.block; } // Get the neighbor itself MapNode neighbor = neighbor_block->getNodeNoCheck(neighbor_rel_pos, &is_valid_position); const ContentFeatures &f = nodemgr->get(neighbor.getContent()); if (f.light_propagates) { // Light up the neighbor, if it has less light than it should. u8 neighbor_light = neighbor.getLightRaw(bank, f); if (neighbor_light < spreading_light) { neighbor.setLight(bank, spreading_light, f); neighbor_block->setNodeNoCheck(neighbor_rel_pos, neighbor); light_sources.push(spreading_light, neighbor_rel_pos, neighbor_block_pos, neighbor_block, i); // The current node was modified earlier, so its block // is in modified_blocks. if (current.block != neighbor_block) { modified_blocks[neighbor_block_pos] = neighbor_block; } } } } } } struct SunlightPropagationUnit{ v2s16 relative_pos; bool is_sunlit; SunlightPropagationUnit(v2s16 relpos, bool sunlit): relative_pos(relpos), is_sunlit(sunlit) {} }; struct SunlightPropagationData{ std::vector<SunlightPropagationUnit> data; v3s16 target_block; }; /*! * Returns true if the node gets sunlight from the * node above it. * * \param pos position of the node. */ bool is_sunlight_above(Map *map, v3s16 pos, const NodeDefManager *ndef) { bool sunlight = true; mapblock_v3 source_block_pos; relative_v3 source_rel_pos; getNodeBlockPosWithOffset(pos + v3s16(0, 1, 0), source_block_pos, source_rel_pos); // If the node above has sunlight, this node also can get it. MapBlock *source_block = map->getBlockNoCreateNoEx(source_block_pos); if (source_block == NULL) { // But if there is no node above, then use heuristics MapBlock *node_block = map->getBlockNoCreateNoEx(getNodeBlockPos(pos)); if (node_block == NULL) { sunlight = false; } else { sunlight = !node_block->getIsUnderground(); } } else { bool is_valid_position; MapNode above = source_block->getNodeNoCheck(source_rel_pos, &is_valid_position); if (is_valid_position) { if (above.getContent() == CONTENT_IGNORE) { // Trust heuristics if (source_block->getIsUnderground()) { sunlight = false; } } else if (above.getLight(LIGHTBANK_DAY, ndef) != LIGHT_SUN) { // If the node above doesn't have sunlight, this // node is in shadow. sunlight = false; } } } return sunlight; } static const LightBank banks[] = { LIGHTBANK_DAY, LIGHTBANK_NIGHT }; void update_lighting_nodes(Map *map, std::vector<std::pair<v3s16, MapNode> > &oldnodes, std::map<v3s16, MapBlock*> &modified_blocks) { const NodeDefManager *ndef = map->getNodeDefManager(); // For node getter functions bool is_valid_position; // Process each light bank separately for (LightBank bank : banks) { UnlightQueue disappearing_lights(256); ReLightQueue light_sources(256); // Nodes that are brighter than the brightest modified node was // won't change, since they didn't get their light from a // modified node. u8 min_safe_light = 0; for (std::vector<std::pair<v3s16, MapNode> >::iterator it = oldnodes.begin(); it < oldnodes.end(); ++it) { u8 old_light = it->second.getLight(bank, ndef); if (old_light > min_safe_light) { min_safe_light = old_light; } } // If only one node changed, even nodes with the same brightness // didn't get their light from the changed node. if (oldnodes.size() > 1) { min_safe_light++; } // For each changed node process sunlight and initialize for (std::vector<std::pair<v3s16, MapNode> >::iterator it = oldnodes.begin(); it < oldnodes.end(); ++it) { // Get position and block of the changed node v3s16 p = it->first; relative_v3 rel_pos; mapblock_v3 block_pos; getNodeBlockPosWithOffset(p, block_pos, rel_pos); MapBlock *block = map->getBlockNoCreateNoEx(block_pos); if (block == NULL || block->isDummy()) { continue; } // Get the new node MapNode n = block->getNodeNoCheck(rel_pos, &is_valid_position); if (!is_valid_position) { break; } // Light of the old node u8 old_light = it->second.getLight(bank, ndef); // Add the block of the added node to modified_blocks modified_blocks[block_pos] = block; // Get new light level of the node u8 new_light = 0; if (ndef->get(n).light_propagates) { if (bank == LIGHTBANK_DAY && ndef->get(n).sunlight_propagates && is_sunlight_above(map, p, ndef)) { new_light = LIGHT_SUN; } else { new_light = ndef->get(n).light_source; for (const v3s16 &neighbor_dir : neighbor_dirs) { v3s16 p2 = p + neighbor_dir; bool is_valid; MapNode n2 = map->getNodeNoEx(p2, &is_valid); if (is_valid) { u8 spread = n2.getLight(bank, ndef); // If it is sure that the neighbor won't be // unlighted, its light can spread to this node. if (spread > new_light && spread >= min_safe_light) { new_light = spread - 1; } } } } } else { // If this is an opaque node, it still can emit light. new_light = ndef->get(n).light_source; } if (new_light > 0) { light_sources.push(new_light, rel_pos, block_pos, block, 6); } if (new_light < old_light) { // The node became opaque or doesn't provide as much // light as the previous one, so it must be unlighted. // Add to unlight queue n.setLight(bank, 0, ndef); block->setNodeNoCheck(rel_pos, n); disappearing_lights.push(old_light, rel_pos, block_pos, block, 6); // Remove sunlight, if there was any if (bank == LIGHTBANK_DAY && old_light == LIGHT_SUN) { for (s16 y = p.Y - 1;; y--) { v3s16 n2pos(p.X, y, p.Z); MapNode n2; n2 = map->getNodeNoEx(n2pos, &is_valid_position); if (!is_valid_position) break; // If this node doesn't have sunlight, the nodes below // it don't have too. if (n2.getLight(LIGHTBANK_DAY, ndef) != LIGHT_SUN) { break; } // Remove sunlight and add to unlight queue. n2.setLight(LIGHTBANK_DAY, 0, ndef); map->setNode(n2pos, n2); relative_v3 rel_pos2; mapblock_v3 block_pos2; getNodeBlockPosWithOffset(n2pos, block_pos2, rel_pos2); MapBlock *block2 = map->getBlockNoCreateNoEx( block_pos2); disappearing_lights.push(LIGHT_SUN, rel_pos2, block_pos2, block2, 4 /* The node above caused the change */); } } } else if (new_light > old_light) { // It is sure that the node provides more light than the previous // one, unlighting is not necessary. // Propagate sunlight if (bank == LIGHTBANK_DAY && new_light == LIGHT_SUN) { for (s16 y = p.Y - 1;; y--) { v3s16 n2pos(p.X, y, p.Z); MapNode n2; n2 = map->getNodeNoEx(n2pos, &is_valid_position); if (!is_valid_position) break; // This should not happen, but if the node has sunlight // then the iteration should stop. if (n2.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN) { break; } // If the node terminates sunlight, stop. if (!ndef->get(n2).sunlight_propagates) { break; } relative_v3 rel_pos2; mapblock_v3 block_pos2; getNodeBlockPosWithOffset(n2pos, block_pos2, rel_pos2); MapBlock *block2 = map->getBlockNoCreateNoEx( block_pos2); // Mark node for lighting. light_sources.push(LIGHT_SUN, rel_pos2, block_pos2, block2, 4); } } } } // Remove lights unspread_light(map, ndef, bank, disappearing_lights, light_sources, modified_blocks); // Initialize light values for light spreading. for (u8 i = 0; i <= LIGHT_SUN; i++) { const std::vector<ChangingLight> &lights = light_sources.lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid_position); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, light_sources, modified_blocks); } } /*! * Borders of a map block in relative node coordinates. * Compatible with type 'direction'. */ const VoxelArea block_borders[] = { VoxelArea(v3s16(15, 0, 0), v3s16(15, 15, 15)), //X+ VoxelArea(v3s16(0, 15, 0), v3s16(15, 15, 15)), //Y+ VoxelArea(v3s16(0, 0, 15), v3s16(15, 15, 15)), //Z+ VoxelArea(v3s16(0, 0, 0), v3s16(15, 15, 0)), //Z- VoxelArea(v3s16(0, 0, 0), v3s16(15, 0, 15)), //Y- VoxelArea(v3s16(0, 0, 0), v3s16(0, 15, 15)) //X- }; /*! * Returns true if: * -the node has unloaded neighbors * -the node doesn't have light * -the node's light is the same as the maximum of * its light source and its brightest neighbor minus one. * . */ bool is_light_locally_correct(Map *map, const NodeDefManager *ndef, LightBank bank, v3s16 pos) { bool is_valid_position; MapNode n = map->getNodeNoEx(pos, &is_valid_position); const ContentFeatures &f = ndef->get(n); if (f.param_type != CPT_LIGHT) { return true; } u8 light = n.getLightNoChecks(bank, &f); assert(f.light_source <= LIGHT_MAX); u8 brightest_neighbor = f.light_source + 1; for (const v3s16 &neighbor_dir : neighbor_dirs) { MapNode n2 = map->getNodeNoEx(pos + neighbor_dir, &is_valid_position); u8 light2 = n2.getLight(bank, ndef); if (brightest_neighbor < light2) { brightest_neighbor = light2; } } assert(light <= LIGHT_SUN); return brightest_neighbor == light + 1; } void update_block_border_lighting(Map *map, MapBlock *block, std::map<v3s16, MapBlock*> &modified_blocks) { const NodeDefManager *ndef = map->getNodeDefManager(); bool is_valid_position; for (LightBank bank : banks) { // Since invalid light is not common, do not allocate // memory if not needed. UnlightQueue disappearing_lights(0); ReLightQueue light_sources(0); // Get incorrect lights for (direction d = 0; d < 6; d++) { // For each direction // Get neighbor block v3s16 otherpos = block->getPos() + neighbor_dirs[d]; MapBlock *other = map->getBlockNoCreateNoEx(otherpos); if (other == NULL) { continue; } // Only update if lighting was not completed. if (block->isLightingComplete(bank, d) && other->isLightingComplete(bank, 5 - d)) continue; // Reset flags block->setLightingComplete(bank, d, true); other->setLightingComplete(bank, 5 - d, true); // The two blocks and their connecting surfaces MapBlock *blocks[] = {block, other}; VoxelArea areas[] = {block_borders[d], block_borders[5 - d]}; // For both blocks for (u8 blocknum = 0; blocknum < 2; blocknum++) { MapBlock *b = blocks[blocknum]; VoxelArea a = areas[blocknum]; // For all nodes for (s32 x = a.MinEdge.X; x <= a.MaxEdge.X; x++) for (s32 z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) for (s32 y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { MapNode n = b->getNodeNoCheck(x, y, z, &is_valid_position); u8 light = n.getLight(bank, ndef); // Sunlight is fixed if (light < LIGHT_SUN) { // Unlight if not correct if (!is_light_locally_correct(map, ndef, bank, v3s16(x, y, z) + b->getPosRelative())) { // Initialize for unlighting n.setLight(bank, 0, ndef); b->setNodeNoCheck(x, y, z, n); modified_blocks[b->getPos()]=b; disappearing_lights.push(light, relative_v3(x, y, z), b->getPos(), b, 6); } } } } } // Remove lights unspread_light(map, ndef, bank, disappearing_lights, light_sources, modified_blocks); // Initialize light values for light spreading. for (u8 i = 0; i <= LIGHT_SUN; i++) { const std::vector<ChangingLight> &lights = light_sources.lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid_position); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, light_sources, modified_blocks); } } /*! * Resets the lighting of the given VoxelManipulator to * complete darkness and full sunlight. * Operates in one map sector. * * \param offset contains the least x and z node coordinates * of the map sector. * \param light incoming sunlight, light[x][z] is true if there * is sunlight above the voxel manipulator at the given x-z coordinates. * The array's indices are relative node coordinates in the sector. * After the procedure returns, this contains outgoing light at * the bottom of the voxel manipulator. */ void fill_with_sunlight(MMVManip *vm, const NodeDefManager *ndef, v2s16 offset, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { // Distance in array between two nodes on top of each other. s16 ystride = vm->m_area.getExtent().X; // Cache the ignore node. MapNode ignore = MapNode(CONTENT_IGNORE); // For each column of nodes: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // Position of the column on the map. v2s16 realpos = offset + v2s16(x, z); // Array indices in the voxel manipulator s32 maxindex = vm->m_area.index(realpos.X, vm->m_area.MaxEdge.Y, realpos.Y); s32 minindex = vm->m_area.index(realpos.X, vm->m_area.MinEdge.Y, realpos.Y); // True if the current node has sunlight. bool lig = light[z][x]; // For each node, downwards: for (s32 i = maxindex; i >= minindex; i -= ystride) { MapNode *n; if (vm->m_flags[i] & VOXELFLAG_NO_DATA) n = &ignore; else n = &vm->m_data[i]; // Ignore IGNORE nodes, these are not generated yet. if(n->getContent() == CONTENT_IGNORE) continue; const ContentFeatures &f = ndef->get(n->getContent()); if (lig && !f.sunlight_propagates) // Sunlight is stopped. lig = false; // Reset light n->setLight(LIGHTBANK_DAY, lig ? 15 : 0, f); n->setLight(LIGHTBANK_NIGHT, 0, f); } // Output outgoing light. light[z][x] = lig; } } /*! * Returns incoming sunlight for one map block. * If block above is not found, it is loaded. * * \param pos position of the map block that gets the sunlight. * \param light incoming sunlight, light[z][x] is true if there * is sunlight above the block at the given z-x relative * node coordinates. */ void is_sunlight_above_block(ServerMap *map, mapblock_v3 pos, const NodeDefManager *ndef, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { mapblock_v3 source_block_pos = pos + v3s16(0, 1, 0); // Get or load source block. // It might take a while to load, but correcting incorrect // sunlight may be even slower. MapBlock *source_block = map->emergeBlock(source_block_pos, false); // Trust only generated blocks. if (source_block == NULL || source_block->isDummy() || !source_block->isGenerated()) { // But if there is no block above, then use heuristics bool sunlight = true; MapBlock *node_block = map->getBlockNoCreateNoEx(pos); if (node_block == NULL) // This should not happen. sunlight = false; else sunlight = !node_block->getIsUnderground(); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) light[z][x] = sunlight; } else { // Dummy boolean, the position is valid. bool is_valid_position; // For each column: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // Get the bottom block. MapNode above = source_block->getNodeNoCheck(x, 0, z, &is_valid_position); light[z][x] = above.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN; } } } /*! * Propagates sunlight down in a given map block. * * \param data contains incoming sunlight and shadow and * the coordinates of the target block. * \param unlight propagated shadow is inserted here * \param relight propagated sunlight is inserted here * * \returns true if the block was modified, false otherwise. */ bool propagate_block_sunlight(Map *map, const NodeDefManager *ndef, SunlightPropagationData *data, UnlightQueue *unlight, ReLightQueue *relight) { bool modified = false; // Get the block. MapBlock *block = map->getBlockNoCreateNoEx(data->target_block); if (block == NULL || block->isDummy()) { // The work is done if the block does not contain data. data->data.clear(); return false; } // Dummy boolean bool is_valid; // For each changing column of nodes: size_t index; for (index = 0; index < data->data.size(); index++) { SunlightPropagationUnit it = data->data[index]; // Relative position of the currently inspected node. relative_v3 current_pos(it.relative_pos.X, MAP_BLOCKSIZE - 1, it.relative_pos.Y); if (it.is_sunlit) { // Propagate sunlight. // For each node downwards: for (; current_pos.Y >= 0; current_pos.Y--) { MapNode n = block->getNodeNoCheck(current_pos, &is_valid); const ContentFeatures &f = ndef->get(n); if (n.getLightRaw(LIGHTBANK_DAY, f) < LIGHT_SUN && f.sunlight_propagates) { // This node gets sunlight. n.setLight(LIGHTBANK_DAY, LIGHT_SUN, f); block->setNodeNoCheck(current_pos, n); modified = true; relight->push(LIGHT_SUN, current_pos, data->target_block, block, 4); } else { // Light already valid, propagation stopped. break; } } } else { // Propagate shadow. // For each node downwards: for (; current_pos.Y >= 0; current_pos.Y--) { MapNode n = block->getNodeNoCheck(current_pos, &is_valid); const ContentFeatures &f = ndef->get(n); if (n.getLightRaw(LIGHTBANK_DAY, f) == LIGHT_SUN) { // The sunlight is no longer valid. n.setLight(LIGHTBANK_DAY, 0, f); block->setNodeNoCheck(current_pos, n); modified = true; unlight->push(LIGHT_SUN, current_pos, data->target_block, block, 4); } else { // Reached shadow, propagation stopped. break; } } } if (current_pos.Y >= 0) { // Propagation stopped, remove from data. data->data[index] = data->data.back(); data->data.pop_back(); index--; } } return modified; } /*! * Borders of a map block in relative node coordinates. * The areas do not overlap. * Compatible with type 'direction'. */ const VoxelArea block_pad[] = { VoxelArea(v3s16(15, 0, 0), v3s16(15, 15, 15)), //X+ VoxelArea(v3s16(1, 15, 0), v3s16(14, 15, 15)), //Y+ VoxelArea(v3s16(1, 1, 15), v3s16(14, 14, 15)), //Z+ VoxelArea(v3s16(1, 1, 0), v3s16(14, 14, 0)), //Z- VoxelArea(v3s16(1, 0, 0), v3s16(14, 0, 15)), //Y- VoxelArea(v3s16(0, 0, 0), v3s16(0, 15, 15)) //X- }; /*! * The common part of bulk light updates - it is always executed. * The procedure takes the nodes that should be unlit, and the * full modified area. * * The procedure handles the correction of all lighting except * direct sunlight spreading. * * \param minblock least coordinates of the changed area in block * coordinates * \param maxblock greatest coordinates of the changed area in block * coordinates * \param unlight the first queue is for day light, the second is for * night light. Contains all nodes on the borders that need to be unlit. * \param relight the first queue is for day light, the second is for * night light. Contains nodes that were not modified, but got sunlight * because the changes. * \param modified_blocks the procedure adds all modified blocks to * this map */ void finish_bulk_light_update(Map *map, mapblock_v3 minblock, mapblock_v3 maxblock, UnlightQueue unlight[2], ReLightQueue relight[2], std::map<v3s16, MapBlock*> *modified_blocks) { const NodeDefManager *ndef = map->getNodeDefManager(); // dummy boolean bool is_valid; // --- STEP 1: Do unlighting for (size_t bank = 0; bank < 2; bank++) { LightBank b = banks[bank]; unspread_light(map, ndef, b, unlight[bank], relight[bank], *modified_blocks); } // --- STEP 2: Get all newly inserted light sources // For each block: v3s16 blockpos; v3s16 relpos; for (blockpos.X = minblock.X; blockpos.X <= maxblock.X; blockpos.X++) for (blockpos.Y = minblock.Y; blockpos.Y <= maxblock.Y; blockpos.Y++) for (blockpos.Z = minblock.Z; blockpos.Z <= maxblock.Z; blockpos.Z++) { MapBlock *block = map->getBlockNoCreateNoEx(blockpos); if (!block || block->isDummy()) // Skip not existing blocks continue; // For each node in the block: for (relpos.X = 0; relpos.X < MAP_BLOCKSIZE; relpos.X++) for (relpos.Z = 0; relpos.Z < MAP_BLOCKSIZE; relpos.Z++) for (relpos.Y = 0; relpos.Y < MAP_BLOCKSIZE; relpos.Y++) { MapNode node = block->getNodeNoCheck(relpos.X, relpos.Y, relpos.Z, &is_valid); const ContentFeatures &f = ndef->get(node); // For each light bank for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; u8 light = f.param_type == CPT_LIGHT ? node.getLightNoChecks(bank, &f): f.light_source; if (light > 1) relight[b].push(light, relpos, blockpos, block, 6); } // end of banks } // end of nodes } // end of blocks // --- STEP 3: do light spreading // For each light bank: for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; // Sunlight is already initialized. u8 maxlight = (b == 0) ? LIGHT_MAX : LIGHT_SUN; // Initialize light values for light spreading. for (u8 i = 0; i <= maxlight; i++) { const std::vector<ChangingLight> &lights = relight[b].lights[i]; for (std::vector<ChangingLight>::const_iterator it = lights.begin(); it < lights.end(); ++it) { MapNode n = it->block->getNodeNoCheck(it->rel_position, &is_valid); n.setLight(bank, i, ndef); it->block->setNodeNoCheck(it->rel_position, n); } } // Spread lights. spread_light(map, ndef, bank, relight[b], *modified_blocks); } } void blit_back_with_light(ServerMap *map, MMVManip *vm, std::map<v3s16, MapBlock*> *modified_blocks) { const NodeDefManager *ndef = map->getNodeDefManager(); mapblock_v3 minblock = getNodeBlockPos(vm->m_area.MinEdge); mapblock_v3 maxblock = getNodeBlockPos(vm->m_area.MaxEdge); // First queue is for day light, second is for night light. UnlightQueue unlight[] = { UnlightQueue(256), UnlightQueue(256) }; ReLightQueue relight[] = { ReLightQueue(256), ReLightQueue(256) }; // Will hold sunlight data. bool lights[MAP_BLOCKSIZE][MAP_BLOCKSIZE]; SunlightPropagationData data; // Dummy boolean. bool is_valid; // --- STEP 1: reset everything to sunlight // For each map block: for (s16 x = minblock.X; x <= maxblock.X; x++) for (s16 z = minblock.Z; z <= maxblock.Z; z++) { // Extract sunlight above. is_sunlight_above_block(map, v3s16(x, maxblock.Y, z), ndef, lights); v2s16 offset(x, z); offset *= MAP_BLOCKSIZE; // Reset the voxel manipulator. fill_with_sunlight(vm, ndef, offset, lights); // Copy sunlight data data.target_block = v3s16(x, minblock.Y - 1, z); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) data.data.emplace_back(v2s16(x, z), lights[z][x]); // Propagate sunlight and shadow below the voxel manipulator. while (!data.data.empty()) { if (propagate_block_sunlight(map, ndef, &data, &unlight[0], &relight[0])) (*modified_blocks)[data.target_block] = map->getBlockNoCreateNoEx(data.target_block); // Step downwards. data.target_block.Y--; } } // --- STEP 2: Get nodes from borders to unlight v3s16 blockpos; v3s16 relpos; // In case there are unloaded holes in the voxel manipulator // unlight each block. // For each block: for (blockpos.X = minblock.X; blockpos.X <= maxblock.X; blockpos.X++) for (blockpos.Y = minblock.Y; blockpos.Y <= maxblock.Y; blockpos.Y++) for (blockpos.Z = minblock.Z; blockpos.Z <= maxblock.Z; blockpos.Z++) { MapBlock *block = map->getBlockNoCreateNoEx(blockpos); if (!block || block->isDummy()) // Skip not existing blocks. continue; v3s16 offset = block->getPosRelative(); // For each border of the block: for (const VoxelArea &a : block_pad) { // For each node of the border: for (relpos.X = a.MinEdge.X; relpos.X <= a.MaxEdge.X; relpos.X++) for (relpos.Z = a.MinEdge.Z; relpos.Z <= a.MaxEdge.Z; relpos.Z++) for (relpos.Y = a.MinEdge.Y; relpos.Y <= a.MaxEdge.Y; relpos.Y++) { // Get old and new node MapNode oldnode = block->getNodeNoCheck(relpos, &is_valid); const ContentFeatures &oldf = ndef->get(oldnode); MapNode newnode = vm->getNodeNoExNoEmerge(relpos + offset); const ContentFeatures &newf = oldnode == newnode ? oldf : ndef->get(newnode); // For each light bank for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; u8 oldlight = oldf.param_type == CPT_LIGHT ? oldnode.getLightNoChecks(bank, &oldf): LIGHT_SUN; // no light information, force unlighting u8 newlight = newf.param_type == CPT_LIGHT ? newnode.getLightNoChecks(bank, &newf): newf.light_source; // If the new node is dimmer, unlight. if (oldlight > newlight) { unlight[b].push( oldlight, relpos, blockpos, block, 6); } } // end of banks } // end of nodes } // end of borders } // end of blocks // --- STEP 3: All information extracted, overwrite vm->blitBackAll(modified_blocks, true); // --- STEP 4: Finish light update finish_bulk_light_update(map, minblock, maxblock, unlight, relight, modified_blocks); } /*! * Resets the lighting of the given map block to * complete darkness and full sunlight. * * \param light incoming sunlight, light[x][z] is true if there * is sunlight above the map block at the given x-z coordinates. * The array's indices are relative node coordinates in the block. * After the procedure returns, this contains outgoing light at * the bottom of the map block. */ void fill_with_sunlight(MapBlock *block, const NodeDefManager *ndef, bool light[MAP_BLOCKSIZE][MAP_BLOCKSIZE]) { if (block->isDummy()) return; // dummy boolean bool is_valid; // For each column of nodes: for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { // True if the current node has sunlight. bool lig = light[z][x]; // For each node, downwards: for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) { MapNode n = block->getNodeNoCheck(x, y, z, &is_valid); // Ignore IGNORE nodes, these are not generated yet. if (n.getContent() == CONTENT_IGNORE) continue; const ContentFeatures &f = ndef->get(n.getContent()); if (lig && !f.sunlight_propagates) { // Sunlight is stopped. lig = false; } // Reset light n.setLight(LIGHTBANK_DAY, lig ? 15 : 0, f); n.setLight(LIGHTBANK_NIGHT, 0, f); block->setNodeNoCheck(x, y, z, n); } // Output outgoing light. light[z][x] = lig; } } void repair_block_light(ServerMap *map, MapBlock *block, std::map<v3s16, MapBlock*> *modified_blocks) { if (!block || block->isDummy()) return; const NodeDefManager *ndef = map->getNodeDefManager(); // First queue is for day light, second is for night light. UnlightQueue unlight[] = { UnlightQueue(256), UnlightQueue(256) }; ReLightQueue relight[] = { ReLightQueue(256), ReLightQueue(256) }; // Will hold sunlight data. bool lights[MAP_BLOCKSIZE][MAP_BLOCKSIZE]; SunlightPropagationData data; // Dummy boolean. bool is_valid; // --- STEP 1: reset everything to sunlight mapblock_v3 blockpos = block->getPos(); (*modified_blocks)[blockpos] = block; // For each map block: // Extract sunlight above. is_sunlight_above_block(map, blockpos, ndef, lights); // Reset the voxel manipulator. fill_with_sunlight(block, ndef, lights); // Copy sunlight data data.target_block = v3s16(blockpos.X, blockpos.Y - 1, blockpos.Z); for (s16 z = 0; z < MAP_BLOCKSIZE; z++) for (s16 x = 0; x < MAP_BLOCKSIZE; x++) { data.data.emplace_back(v2s16(x, z), lights[z][x]); } // Propagate sunlight and shadow below the voxel manipulator. while (!data.data.empty()) { if (propagate_block_sunlight(map, ndef, &data, &unlight[0], &relight[0])) (*modified_blocks)[data.target_block] = map->getBlockNoCreateNoEx(data.target_block); // Step downwards. data.target_block.Y--; } // --- STEP 2: Get nodes from borders to unlight // For each border of the block: for (const VoxelArea &a : block_pad) { v3s16 relpos; // For each node of the border: for (relpos.X = a.MinEdge.X; relpos.X <= a.MaxEdge.X; relpos.X++) for (relpos.Z = a.MinEdge.Z; relpos.Z <= a.MaxEdge.Z; relpos.Z++) for (relpos.Y = a.MinEdge.Y; relpos.Y <= a.MaxEdge.Y; relpos.Y++) { // Get node MapNode node = block->getNodeNoCheck(relpos, &is_valid); const ContentFeatures &f = ndef->get(node); // For each light bank for (size_t b = 0; b < 2; b++) { LightBank bank = banks[b]; u8 light = f.param_type == CPT_LIGHT ? node.getLightNoChecks(bank, &f): f.light_source; // If the new node is dimmer than sunlight, unlight. // (if it has maximal light, it is pointless to remove // surrounding light, as it can only become brighter) if (LIGHT_SUN > light) { unlight[b].push( LIGHT_SUN, relpos, blockpos, block, 6); } } // end of banks } // end of nodes } // end of borders // STEP 3: Remove and spread light finish_bulk_light_update(map, blockpos, blockpos, unlight, relight, modified_blocks); } VoxelLineIterator::VoxelLineIterator(const v3f &start_position, const v3f &line_vector) : m_start_position(start_position), m_line_vector(line_vector) { m_current_node_pos = floatToInt(m_start_position, 1); m_start_node_pos = m_current_node_pos; m_last_index = getIndex(floatToInt(start_position + line_vector, 1)); if (m_line_vector.X > 0) { m_next_intersection_multi.X = (floorf(m_start_position.X - 0.5) + 1.5 - m_start_position.X) / m_line_vector.X; m_intersection_multi_inc.X = 1 / m_line_vector.X; } else if (m_line_vector.X < 0) { m_next_intersection_multi.X = (floorf(m_start_position.X - 0.5) - m_start_position.X + 0.5) / m_line_vector.X; m_intersection_multi_inc.X = -1 / m_line_vector.X; m_step_directions.X = -1; } if (m_line_vector.Y > 0) { m_next_intersection_multi.Y = (floorf(m_start_position.Y - 0.5) + 1.5 - m_start_position.Y) / m_line_vector.Y; m_intersection_multi_inc.Y = 1 / m_line_vector.Y; } else if (m_line_vector.Y < 0) { m_next_intersection_multi.Y = (floorf(m_start_position.Y - 0.5) - m_start_position.Y + 0.5) / m_line_vector.Y; m_intersection_multi_inc.Y = -1 / m_line_vector.Y; m_step_directions.Y = -1; } if (m_line_vector.Z > 0) { m_next_intersection_multi.Z = (floorf(m_start_position.Z - 0.5) + 1.5 - m_start_position.Z) / m_line_vector.Z; m_intersection_multi_inc.Z = 1 / m_line_vector.Z; } else if (m_line_vector.Z < 0) { m_next_intersection_multi.Z = (floorf(m_start_position.Z - 0.5) - m_start_position.Z + 0.5) / m_line_vector.Z; m_intersection_multi_inc.Z = -1 / m_line_vector.Z; m_step_directions.Z = -1; } } void VoxelLineIterator::next() { m_current_index++; if ((m_next_intersection_multi.X < m_next_intersection_multi.Y) && (m_next_intersection_multi.X < m_next_intersection_multi.Z)) { m_next_intersection_multi.X += m_intersection_multi_inc.X; m_current_node_pos.X += m_step_directions.X; } else if ((m_next_intersection_multi.Y < m_next_intersection_multi.Z)) { m_next_intersection_multi.Y += m_intersection_multi_inc.Y; m_current_node_pos.Y += m_step_directions.Y; } else { m_next_intersection_multi.Z += m_intersection_multi_inc.Z; m_current_node_pos.Z += m_step_directions.Z; } } s16 VoxelLineIterator::getIndex(v3s16 voxel){ return abs(voxel.X - m_start_node_pos.X) + abs(voxel.Y - m_start_node_pos.Y) + abs(voxel.Z - m_start_node_pos.Z); } } // namespace voxalgo
pgimeno/minetest
src/voxelalgorithms.cpp
C++
mit
42,894
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "voxel.h" #include "mapnode.h" #include "util/container.h" class Map; class ServerMap; class MapBlock; class MMVManip; namespace voxalgo { /*! * Updates the lighting on the map. * The result will be correct only if * no nodes were changed except the given ones. * Before calling this procedure make sure that all new nodes on * the map have zero light level! * * \param oldnodes contains the MapNodes that were replaced by the new * MapNodes and their positions * \param modified_blocks output, contains all map blocks that * the function modified */ void update_lighting_nodes( Map *map, std::vector<std::pair<v3s16, MapNode> > &oldnodes, std::map<v3s16, MapBlock*> &modified_blocks); /*! * Updates borders of the given mapblock. * Only updates if the block was marked with incomplete * lighting and the neighbor is also loaded. * * \param block the block to update * \param modified_blocks output, contains all map blocks that * the function modified */ void update_block_border_lighting(Map *map, MapBlock *block, std::map<v3s16, MapBlock*> &modified_blocks); /*! * Copies back nodes from a voxel manipulator * to the map and updates lighting. * For server use only. * * \param modified_blocks output, contains all map blocks that * the function modified */ void blit_back_with_light(ServerMap *map, MMVManip *vm, std::map<v3s16, MapBlock*> *modified_blocks); /*! * Corrects the light in a map block. * For server use only. * * \param block the block to update */ void repair_block_light(ServerMap *map, MapBlock *block, std::map<v3s16, MapBlock*> *modified_blocks); /*! * This class iterates trough voxels that intersect with * a line. The collision detection does not see nodeboxes, * every voxel is a cube and is returned. * This iterator steps to all nodes exactly once. */ struct VoxelLineIterator { public: //! Starting position of the line in world coordinates. v3f m_start_position; //! Direction and length of the line in world coordinates. v3f m_line_vector; /*! * Each component stores the next smallest positive number, by * which multiplying the line's vector gives a vector that ends * on the intersection of two nodes. */ v3f m_next_intersection_multi { 10000.0f, 10000.0f, 10000.0f }; /*! * Each component stores the smallest positive number, by which * m_next_intersection_multi's components can be increased. */ v3f m_intersection_multi_inc { 10000.0f, 10000.0f, 10000.0f }; /*! * Direction of the line. Each component can be -1 or 1 (if a * component of the line's vector is 0, then there will be 1). */ v3s16 m_step_directions { 1, 1, 1 }; //! Position of the current node. v3s16 m_current_node_pos; //! Index of the current node s16 m_current_index = 0; //! Position of the start node. v3s16 m_start_node_pos; //! Index of the last node s16 m_last_index; /*! * Creates a voxel line iterator with the given line. * @param start_position starting point of the line * in voxel coordinates * @param line_vector length and direction of the * line in voxel coordinates. start_position+line_vector * is the end of the line */ VoxelLineIterator(const v3f &start_position,const v3f &line_vector); /*! * Steps to the next voxel. * Updates m_current_node_pos and * m_previous_node_pos. * Note that it works even if hasNext() is false, * continuing the line as a ray. */ void next(); /*! * Returns true if the next voxel intersects the given line. */ inline bool hasNext() const { return m_current_index < m_last_index; } /*! * Returns how many times next() must be called until * voxel==m_current_node_pos. * If voxel does not intersect with the line, * the result is undefined. */ s16 getIndex(v3s16 voxel); }; } // namespace voxalgo
pgimeno/minetest
src/voxelalgorithms.h
C++
mit
4,608
Put your texture pack folders in this folder. Textures in the "server" pack will be used by the server.
pgimeno/minetest
textures/texture_packs_here.txt
Text
mit
104
#!/bin/bash set -e dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if [ $# -ne 1 ]; then echo "Usage: $0 <build directory>" exit 1 fi builddir=$1 mkdir -p $builddir builddir="$( cd "$builddir" && pwd )" packagedir=$builddir/packages libdir=$builddir/libs toolchain_file=$dir/toolchain_mingw.cmake irrlicht_version=1.8.4 ogg_version=1.3.2 vorbis_version=1.3.5 curl_version=7.64.0 gettext_version=0.19.8.1 freetype_version=2.9.1 sqlite3_version=3.27.2 luajit_version=2.1.0-beta3 leveldb_version=1.20 zlib_version=1.2.11 mkdir -p $packagedir mkdir -p $libdir cd $builddir # Get stuff [ -e $packagedir/irrlicht-$irrlicht_version.zip ] || wget http://minetest.kitsunemimi.pw/irrlicht-$irrlicht_version-win32.zip \ -c -O $packagedir/irrlicht-$irrlicht_version.zip [ -e $packagedir/zlib-$zlib_version.zip ] || wget http://minetest.kitsunemimi.pw/zlib-$zlib_version-win32.zip \ -c -O $packagedir/zlib-$zlib_version.zip [ -e $packagedir/libogg-$ogg_version.zip ] || wget http://minetest.kitsunemimi.pw/libogg-$ogg_version-win32.zip \ -c -O $packagedir/libogg-$ogg_version.zip [ -e $packagedir/libvorbis-$vorbis_version.zip ] || wget http://minetest.kitsunemimi.pw/libvorbis-$vorbis_version-win32.zip \ -c -O $packagedir/libvorbis-$vorbis_version.zip [ -e $packagedir/curl-$curl_version.zip ] || wget http://minetest.kitsunemimi.pw/curl-$curl_version-win32.zip \ -c -O $packagedir/curl-$curl_version.zip [ -e $packagedir/gettext-$gettext_version.zip ] || wget http://minetest.kitsunemimi.pw/gettext-$gettext_version-win32.zip \ -c -O $packagedir/gettext-$gettext_version.zip [ -e $packagedir/freetype2-$freetype_version.zip ] || wget http://minetest.kitsunemimi.pw/freetype2-$freetype_version-win32.zip \ -c -O $packagedir/freetype2-$freetype_version.zip [ -e $packagedir/sqlite3-$sqlite3_version.zip ] || wget http://minetest.kitsunemimi.pw/sqlite3-$sqlite3_version-win32.zip \ -c -O $packagedir/sqlite3-$sqlite3_version.zip [ -e $packagedir/luajit-$luajit_version.zip ] || wget http://minetest.kitsunemimi.pw/luajit-$luajit_version-win32.zip \ -c -O $packagedir/luajit-$luajit_version.zip [ -e $packagedir/libleveldb-$leveldb_version.zip ] || wget http://minetest.kitsunemimi.pw/libleveldb-$leveldb_version-win32.zip \ -c -O $packagedir/libleveldb-$leveldb_version.zip [ -e $packagedir/openal_stripped.zip ] || wget http://minetest.kitsunemimi.pw/openal_stripped.zip \ -c -O $packagedir/openal_stripped.zip # Extract stuff cd $libdir [ -d irrlicht ] || unzip -o $packagedir/irrlicht-$irrlicht_version.zip -d irrlicht [ -d zlib ] || unzip -o $packagedir/zlib-$zlib_version.zip -d zlib [ -d libogg ] || unzip -o $packagedir/libogg-$ogg_version.zip -d libogg [ -d libvorbis ] || unzip -o $packagedir/libvorbis-$vorbis_version.zip -d libvorbis [ -d libcurl ] || unzip -o $packagedir/curl-$curl_version.zip -d libcurl [ -d gettext ] || unzip -o $packagedir/gettext-$gettext_version.zip -d gettext [ -d freetype ] || unzip -o $packagedir/freetype2-$freetype_version.zip -d freetype [ -d sqlite3 ] || unzip -o $packagedir/sqlite3-$sqlite3_version.zip -d sqlite3 [ -d openal_stripped ] || unzip -o $packagedir/openal_stripped.zip [ -d luajit ] || unzip -o $packagedir/luajit-$luajit_version.zip -d luajit [ -d leveldb ] || unzip -o $packagedir/libleveldb-$leveldb_version.zip -d leveldb # Get minetest cd $builddir if [ ! "x$EXISTING_MINETEST_DIR" = "x" ]; then ln -s $EXISTING_MINETEST_DIR minetest else [ -d minetest ] && (cd minetest && git pull) || (git clone https://github.com/minetest/minetest) fi cd minetest git_hash=$(git rev-parse --short HEAD) # Get minetest_game cd games if [ "x$NO_MINETEST_GAME" = "x" ]; then [ -d minetest_game ] && (cd minetest_game && git pull) || (git clone https://github.com/minetest/minetest_game) fi cd ../.. # Build the thing cd minetest [ -d _build ] && rm -Rf _build/ mkdir _build cd _build cmake .. \ -DCMAKE_INSTALL_PREFIX=/tmp \ -DVERSION_EXTRA=$git_hash \ -DBUILD_CLIENT=1 -DBUILD_SERVER=0 \ -DCMAKE_TOOLCHAIN_FILE=$toolchain_file \ \ -DENABLE_SOUND=1 \ -DENABLE_CURL=1 \ -DENABLE_GETTEXT=1 \ -DENABLE_FREETYPE=1 \ -DENABLE_LEVELDB=1 \ \ -DIRRLICHT_INCLUDE_DIR=$libdir/irrlicht/include \ -DIRRLICHT_LIBRARY=$libdir/irrlicht/lib/Win32-gcc/libIrrlicht.dll.a \ -DIRRLICHT_DLL=$libdir/irrlicht/bin/Win32-gcc/Irrlicht.dll \ \ -DZLIB_INCLUDE_DIR=$libdir/zlib/include \ -DZLIB_LIBRARIES=$libdir/zlib/lib/libz.dll.a \ -DZLIB_DLL=$libdir/zlib/bin/zlib1.dll \ \ -DLUA_INCLUDE_DIR=$libdir/luajit/include \ -DLUA_LIBRARY=$libdir/luajit/libluajit.a \ \ -DOGG_INCLUDE_DIR=$libdir/libogg/include \ -DOGG_LIBRARY=$libdir/libogg/lib/libogg.dll.a \ -DOGG_DLL=$libdir/libogg/bin/libogg-0.dll \ \ -DVORBIS_INCLUDE_DIR=$libdir/libvorbis/include \ -DVORBIS_LIBRARY=$libdir/libvorbis/lib/libvorbis.dll.a \ -DVORBIS_DLL=$libdir/libvorbis/bin/libvorbis-0.dll \ -DVORBISFILE_LIBRARY=$libdir/libvorbis/lib/libvorbisfile.dll.a \ -DVORBISFILE_DLL=$libdir/libvorbis/bin/libvorbisfile-3.dll \ \ -DOPENAL_INCLUDE_DIR=$libdir/openal_stripped/include/AL \ -DOPENAL_LIBRARY=$libdir/openal_stripped/lib/libOpenAL32.dll.a \ -DOPENAL_DLL=$libdir/openal_stripped/bin/OpenAL32.dll \ \ -DCURL_DLL=$libdir/libcurl/bin/libcurl-4.dll \ -DCURL_INCLUDE_DIR=$libdir/libcurl/include \ -DCURL_LIBRARY=$libdir/libcurl/lib/libcurl.dll.a \ \ -DGETTEXT_MSGFMT=`which msgfmt` \ -DGETTEXT_DLL=$libdir/gettext/bin/libintl-8.dll \ -DGETTEXT_ICONV_DLL=$libdir/gettext/bin/libiconv-2.dll \ -DGETTEXT_INCLUDE_DIR=$libdir/gettext/include \ -DGETTEXT_LIBRARY=$libdir/gettext/lib/libintl.dll.a \ \ -DFREETYPE_INCLUDE_DIR_freetype2=$libdir/freetype/include/freetype2 \ -DFREETYPE_INCLUDE_DIR_ft2build=$libdir/freetype/include/freetype2 \ -DFREETYPE_LIBRARY=$libdir/freetype/lib/libfreetype.dll.a \ -DFREETYPE_DLL=$libdir/freetype/bin/libfreetype-6.dll \ \ -DSQLITE3_INCLUDE_DIR=$libdir/sqlite3/include \ -DSQLITE3_LIBRARY=$libdir/sqlite3/lib/libsqlite3.dll.a \ -DSQLITE3_DLL=$libdir/sqlite3/bin/libsqlite3-0.dll \ \ -DLEVELDB_INCLUDE_DIR=$libdir/leveldb/include \ -DLEVELDB_LIBRARY=$libdir/leveldb/lib/libleveldb.dll.a \ -DLEVELDB_DLL=$libdir/leveldb/bin/libleveldb.dll make -j2 [ "x$NO_PACKAGE" = "x" ] && make package exit 0 # EOF
pgimeno/minetest
util/buildbot/buildwin32.sh
Shell
mit
6,194
#!/bin/bash set -e dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if [ $# -ne 1 ]; then echo "Usage: $0 <build directory>" exit 1 fi builddir=$1 mkdir -p $builddir builddir="$( cd "$builddir" && pwd )" packagedir=$builddir/packages libdir=$builddir/libs toolchain_file=$dir/toolchain_mingw64.cmake irrlicht_version=1.8.4 ogg_version=1.3.2 vorbis_version=1.3.5 curl_version=7.64.0 gettext_version=0.19.8.1 freetype_version=2.9.1 sqlite3_version=3.27.2 luajit_version=2.1.0-beta3 leveldb_version=1.20 zlib_version=1.2.11 mkdir -p $packagedir mkdir -p $libdir cd $builddir # Get stuff [ -e $packagedir/irrlicht-$irrlicht_version.zip ] || wget http://minetest.kitsunemimi.pw/irrlicht-$irrlicht_version-win64.zip \ -c -O $packagedir/irrlicht-$irrlicht_version.zip [ -e $packagedir/zlib-$zlib_version.zip ] || wget http://minetest.kitsunemimi.pw/zlib-$zlib_version-win64.zip \ -c -O $packagedir/zlib-$zlib_version.zip [ -e $packagedir/libogg-$ogg_version.zip ] || wget http://minetest.kitsunemimi.pw/libogg-$ogg_version-win64.zip \ -c -O $packagedir/libogg-$ogg_version.zip [ -e $packagedir/libvorbis-$vorbis_version.zip ] || wget http://minetest.kitsunemimi.pw/libvorbis-$vorbis_version-win64.zip \ -c -O $packagedir/libvorbis-$vorbis_version.zip [ -e $packagedir/curl-$curl_version.zip ] || wget http://minetest.kitsunemimi.pw/curl-$curl_version-win64.zip \ -c -O $packagedir/curl-$curl_version.zip [ -e $packagedir/gettext-$gettext_version.zip ] || wget http://minetest.kitsunemimi.pw/gettext-$gettext_version-win64.zip \ -c -O $packagedir/gettext-$gettext_version.zip [ -e $packagedir/freetype2-$freetype_version.zip ] || wget http://minetest.kitsunemimi.pw/freetype2-$freetype_version-win64.zip \ -c -O $packagedir/freetype2-$freetype_version.zip [ -e $packagedir/sqlite3-$sqlite3_version.zip ] || wget http://minetest.kitsunemimi.pw/sqlite3-$sqlite3_version-win64.zip \ -c -O $packagedir/sqlite3-$sqlite3_version.zip [ -e $packagedir/luajit-$luajit_version.zip ] || wget http://minetest.kitsunemimi.pw/luajit-$luajit_version-win64.zip \ -c -O $packagedir/luajit-$luajit_version.zip [ -e $packagedir/libleveldb-$leveldb_version.zip ] || wget http://minetest.kitsunemimi.pw/libleveldb-$leveldb_version-win64.zip \ -c -O $packagedir/libleveldb-$leveldb_version.zip [ -e $packagedir/openal_stripped.zip ] || wget http://minetest.kitsunemimi.pw/openal_stripped64.zip \ -c -O $packagedir/openal_stripped.zip # Extract stuff cd $libdir [ -d irrlicht ] || unzip -o $packagedir/irrlicht-$irrlicht_version.zip -d irrlicht [ -d zlib ] || unzip -o $packagedir/zlib-$zlib_version.zip -d zlib [ -d libogg ] || unzip -o $packagedir/libogg-$ogg_version.zip -d libogg [ -d libvorbis ] || unzip -o $packagedir/libvorbis-$vorbis_version.zip -d libvorbis [ -d libcurl ] || unzip -o $packagedir/curl-$curl_version.zip -d libcurl [ -d gettext ] || unzip -o $packagedir/gettext-$gettext_version.zip -d gettext [ -d freetype ] || unzip -o $packagedir/freetype2-$freetype_version.zip -d freetype [ -d sqlite3 ] || unzip -o $packagedir/sqlite3-$sqlite3_version.zip -d sqlite3 [ -d openal_stripped ] || unzip -o $packagedir/openal_stripped.zip [ -d luajit ] || unzip -o $packagedir/luajit-$luajit_version.zip -d luajit [ -d leveldb ] || unzip -o $packagedir/libleveldb-$leveldb_version.zip -d leveldb # Get minetest cd $builddir if [ ! "x$EXISTING_MINETEST_DIR" = "x" ]; then ln -s $EXISTING_MINETEST_DIR minetest else [ -d minetest ] && (cd minetest && git pull) || (git clone https://github.com/minetest/minetest) fi cd minetest git_hash=$(git rev-parse --short HEAD) # Get minetest_game cd games if [ "x$NO_MINETEST_GAME" = "x" ]; then [ -d minetest_game ] && (cd minetest_game && git pull) || (git clone https://github.com/minetest/minetest_game) fi cd ../.. # Build the thing cd minetest [ -d _build ] && rm -Rf _build/ mkdir _build cd _build cmake .. \ -DCMAKE_TOOLCHAIN_FILE=$toolchain_file \ -DCMAKE_INSTALL_PREFIX=/tmp \ -DVERSION_EXTRA=$git_hash \ -DBUILD_CLIENT=1 -DBUILD_SERVER=0 \ \ -DENABLE_SOUND=1 \ -DENABLE_CURL=1 \ -DENABLE_GETTEXT=1 \ -DENABLE_FREETYPE=1 \ -DENABLE_LEVELDB=1 \ \ -DIRRLICHT_INCLUDE_DIR=$libdir/irrlicht/include \ -DIRRLICHT_LIBRARY=$libdir/irrlicht/lib/Win64-gcc/libIrrlicht.dll.a \ -DIRRLICHT_DLL=$libdir/irrlicht/bin/Win64-gcc/Irrlicht.dll \ \ -DZLIB_INCLUDE_DIR=$libdir/zlib/include \ -DZLIB_LIBRARIES=$libdir/zlib/lib/libz.dll.a \ -DZLIB_DLL=$libdir/zlib/bin/zlib1.dll \ \ -DLUA_INCLUDE_DIR=$libdir/luajit/include \ -DLUA_LIBRARY=$libdir/luajit/libluajit.a \ \ -DOGG_INCLUDE_DIR=$libdir/libogg/include \ -DOGG_LIBRARY=$libdir/libogg/lib/libogg.dll.a \ -DOGG_DLL=$libdir/libogg/bin/libogg-0.dll \ \ -DVORBIS_INCLUDE_DIR=$libdir/libvorbis/include \ -DVORBIS_LIBRARY=$libdir/libvorbis/lib/libvorbis.dll.a \ -DVORBIS_DLL=$libdir/libvorbis/bin/libvorbis-0.dll \ -DVORBISFILE_LIBRARY=$libdir/libvorbis/lib/libvorbisfile.dll.a \ -DVORBISFILE_DLL=$libdir/libvorbis/bin/libvorbisfile-3.dll \ \ -DOPENAL_INCLUDE_DIR=$libdir/openal_stripped/include/AL \ -DOPENAL_LIBRARY=$libdir/openal_stripped/lib/libOpenAL32.dll.a \ -DOPENAL_DLL=$libdir/openal_stripped/bin/OpenAL32.dll \ \ -DCURL_DLL=$libdir/libcurl/bin/libcurl-4.dll \ -DCURL_INCLUDE_DIR=$libdir/libcurl/include \ -DCURL_LIBRARY=$libdir/libcurl/lib/libcurl.dll.a \ \ -DGETTEXT_MSGFMT=`which msgfmt` \ -DGETTEXT_DLL=$libdir/gettext/bin/libintl-8.dll \ -DGETTEXT_ICONV_DLL=$libdir/gettext/bin/libiconv-2.dll \ -DGETTEXT_INCLUDE_DIR=$libdir/gettext/include \ -DGETTEXT_LIBRARY=$libdir/gettext/lib/libintl.dll.a \ \ -DFREETYPE_INCLUDE_DIR_freetype2=$libdir/freetype/include/freetype2 \ -DFREETYPE_INCLUDE_DIR_ft2build=$libdir/freetype/include/freetype2 \ -DFREETYPE_LIBRARY=$libdir/freetype/lib/libfreetype.dll.a \ -DFREETYPE_DLL=$libdir/freetype/bin/libfreetype-6.dll \ \ -DSQLITE3_INCLUDE_DIR=$libdir/sqlite3/include \ -DSQLITE3_LIBRARY=$libdir/sqlite3/lib/libsqlite3.dll.a \ -DSQLITE3_DLL=$libdir/sqlite3/bin/libsqlite3-0.dll \ \ -DLEVELDB_INCLUDE_DIR=$libdir/leveldb/include \ -DLEVELDB_LIBRARY=$libdir/leveldb/lib/libleveldb.dll.a \ -DLEVELDB_DLL=$libdir/leveldb/bin/libleveldb.dll make -j2 [ "x$NO_PACKAGE" = "x" ] && make package exit 0 # EOF
pgimeno/minetest
util/buildbot/buildwin64.sh
Shell
mit
6,199
# name of the target operating system SET(CMAKE_SYSTEM_NAME Windows) # which compilers to use for C and C++ SET(CMAKE_C_COMPILER i586-mingw32msvc-gcc) SET(CMAKE_CXX_COMPILER i586-mingw32msvc-g++) SET(CMAKE_RC_COMPILER i586-mingw32msvc-windres) # here is the target environment located SET(CMAKE_FIND_ROOT_PATH /usr/i586-mingw32msvc) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
pgimeno/minetest
util/buildbot/toolchain_mingw.cmake
CMake
mit
628
# name of the target operating system SET(CMAKE_SYSTEM_NAME Windows) # which compilers to use for C and C++ SET(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) SET(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++) SET(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres) # here is the target environment located SET(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
pgimeno/minetest
util/buildbot/toolchain_mingw64.cmake
CMake
mit
636
#!/bin/bash -e prompt_for_number() { local prompt_text=$1 local default_value=$2 local tmp="" while true; do read -p "$prompt_text [$default_value]: " tmp if [ "$tmp" = "" ]; then echo "$default_value"; return elif echo "$tmp" | grep -q -E '^[0-9]+$'; then echo "$tmp"; return fi done } # On a release the following actions are performed # * DEVELOPMENT_BUILD is set to false # * android versionCode is bumped # * appdata release version and date are updated # * Commit the changes # * Tag with current version perform_release() { sed -i -re "s/^set\(DEVELOPMENT_BUILD TRUE\)$/set(DEVELOPMENT_BUILD FALSE)/" CMakeLists.txt sed -i -re "s/versionCode [0-9]+$/versionCode $NEW_ANDROID_VERSION_CODE/" build/android/build.gradle sed -i '/\<release/s/\(version\)="[^"]*"/\1="'"$RELEASE_VERSION"'"/' misc/net.minetest.minetest.appdata.xml RELEASE_DATE=`date +%Y-%m-%d` sed -i 's/\(<release date\)="[^"]*"/\1="'"$RELEASE_DATE"'"/' misc/net.minetest.minetest.appdata.xml git add -f CMakeLists.txt build/android/build.gradle misc/net.minetest.minetest.appdata.xml git commit -m "Bump version to $RELEASE_VERSION" echo "Tagging $RELEASE_VERSION" git tag -a "$RELEASE_VERSION" -m "$RELEASE_VERSION" } # After release # * Set DEVELOPMENT_BUILD to true # * Bump version in CMakeLists and docs # * Commit the changes back_to_devel() { echo 'Creating "return back to development" commit' sed -i -re 's/^set\(DEVELOPMENT_BUILD FALSE\)$/set(DEVELOPMENT_BUILD TRUE)/' CMakeLists.txt sed -i -re "s/^set\(VERSION_MAJOR [0-9]+\)$/set(VERSION_MAJOR $NEXT_VERSION_MAJOR)/" CMakeLists.txt sed -i -re "s/^set\(VERSION_MINOR [0-9]+\)$/set(VERSION_MINOR $NEXT_VERSION_MINOR)/" CMakeLists.txt sed -i -re "s/^set\(VERSION_PATCH [0-9]+\)$/set(VERSION_PATCH $NEXT_VERSION_PATCH)/" CMakeLists.txt sed -i -re "1s/[0-9]+\.[0-9]+\.[0-9]+/$NEXT_VERSION/g" doc/menu_lua_api.txt sed -i -re "1s/[0-9]+\.[0-9]+\.[0-9]+/$NEXT_VERSION/g" doc/client_lua_api.txt git add -f CMakeLists.txt doc/menu_lua_api.txt doc/client_lua_api.txt git commit -m "Continue with $NEXT_VERSION-dev" } ################################## # Switch to top minetest directory ################################## cd ${0%/*}/.. ####################### # Determine old version ####################### # Make sure all the files we need exist grep -q -E '^set\(VERSION_MAJOR [0-9]+\)$' CMakeLists.txt grep -q -E '^set\(VERSION_MINOR [0-9]+\)$' CMakeLists.txt grep -q -E '^set\(VERSION_PATCH [0-9]+\)$' CMakeLists.txt grep -q -E 'versionCode [0-9]+$' build/android/build.gradle VERSION_MAJOR=$(grep -E '^set\(VERSION_MAJOR [0-9]+\)$' CMakeLists.txt | tr -dC 0-9) VERSION_MINOR=$(grep -E '^set\(VERSION_MINOR [0-9]+\)$' CMakeLists.txt | tr -dC 0-9) VERSION_PATCH=$(grep -E '^set\(VERSION_PATCH [0-9]+\)$' CMakeLists.txt | tr -dC 0-9) ANDROID_VERSION_CODE=$(grep -E 'versionCode [0-9]+$' build/android/build.gradle | tr -dC 0-9) RELEASE_VERSION="$VERSION_MAJOR.$VERSION_MINOR.$VERSION_PATCH" echo "Current Minetest version: $RELEASE_VERSION" echo "Current Android version code: $ANDROID_VERSION_CODE" NEW_ANDROID_VERSION_CODE=$(expr $ANDROID_VERSION_CODE + 1) NEW_ANDROID_VERSION_CODE=$(prompt_for_number "Set android version code" $NEW_ANDROID_VERSION_CODE) echo echo "New android version code: $NEW_ANDROID_VERSION_CODE" ######################## # Perform release ######################## perform_release ######################## # Prompt for next version ######################## NEXT_VERSION_MAJOR=$VERSION_MAJOR NEXT_VERSION_MINOR=$VERSION_MINOR NEXT_VERSION_PATCH=$(expr $VERSION_PATCH + 1) NEXT_VERSION_MAJOR=$(prompt_for_number "Set next major" $NEXT_VERSION_MAJOR) if [ "$NEXT_VERSION_MAJOR" != "$VERSION_MAJOR" ]; then NEXT_VERSION_MINOR=0 NEXT_VERSION_PATCH=0 fi NEXT_VERSION_MINOR=$(prompt_for_number "Set next minor" $NEXT_VERSION_MINOR) if [ "$NEXT_VERSION_MINOR" != "$VERSION_MINOR" ]; then NEXT_VERSION_PATCH=0 fi NEXT_VERSION_PATCH=$(prompt_for_number "Set next patch" $NEXT_VERSION_PATCH) NEXT_VERSION="$NEXT_VERSION_MAJOR.$NEXT_VERSION_MINOR.$NEXT_VERSION_PATCH" echo echo "New version: $NEXT_VERSION" ######################## # Return back to devel ######################## back_to_devel
pgimeno/minetest
util/bump_version.sh
Shell
mit
4,212
#!/bin/bash # This script generates normalmaps using The GIMP to do the heavy lifting. # give any unrecognized switch (say, -h) for usage info. rm /tmp/normals_filelist.txt numprocs=6 skiptools=false skipinventory=false invresolution=64 dryrun=false pattern="*.png *.jpg" filter=0 scale=8 wrap=0 heightsource=0 conversion=0 invertx=0 inverty=0 while test -n "$1"; do case "$1" in --scale|-s) if [ -z "$2" ] ; then echo "Missing scale parameter"; exit 1; fi scale=$2 shift shift ;; --pattern|-p) if [ -z "$2" ] ; then echo "Missing pattern parameter"; exit 1; fi pattern=$2 shift shift ;; --skiptools|-t) skiptools=true shift ;; --skipinventory|-i) if [[ $2 =~ ^[0-9]+$ ]]; then invresolution=$2 shift fi skipinventory=true shift ;; --filter|-f) if [ -z "$2" ] ; then echo "Missing filter parameter"; exit 1; fi case "$2" in sobel3|1) filter=1 ;; sobel5|2) filter=2 ;; prewitt3|3) filter=3 ;; prewitt5|4) filter=4 ;; 3x3|5) filter=5 ;; 5x5|6) filter=6 ;; 7x7|7) filter=7 ;; 9x9|8) filter=8 ;; *) filter=0 ;; esac shift shift ;; --heightalpha|-a) heightsource=1 shift ;; --conversion|-c) if [ -z "$2" ] ; then echo "Missing conversion parameter"; exit 1; fi case "$2" in biased|1) conversion=1 ;; red|2) conversion=2 ;; green|3) conversion=3 ;; blue|4) conversion=4 ;; maxrgb|5) conversion=5 ;; minrgb|6) conversion=6 ;; colorspace|7) conversion=7 ;; normalize-only|8) conversion=8 ;; heightmap|9) conversion=9 ;; *) conversion=0 ;; esac shift shift ;; --wrap|-w) wrap=1 shift ;; --invertx|-x) invertx=1 shift ;; --inverty|-y) inverty=1 shift ;; --dryrun|-d) dryrun=true shift ;; *) echo -e "\nUsage:\n" echo "`basename $0` [--scale|-s <value>] [--filter|-f <string>]" echo " [--wrap|-w] [--heightalpha|-a] [--invertx|-x] [--inverty|-y]" echo " [--conversion|-c <string>] [--skiptools|-t] [--skipinventory|-i [<value>]]" echo " [--dryrun|-d] [--pattern|-p <pattern>]" echo -e "\nDefaults to a scale of 8, checking all files in the current directory, and not" echo "skipping apparent tools or inventory images. Filter, if specified, may be one" echo "of: sobel3, sobel5, prewitt3, prewitt5, 3x3, 5x5, 7x7, or 9x9, or a value 1" echo "through 8 (1=sobel3, 2=sobel5, etc.). Defaults to 0 (four-sample). The height" echo "source is taken from the image's alpha channel if heightalpha is specified.\n" echo "" echo "If inventory skip is specified, an optional resolution may also be included" echo "(default is 64). Conversion can be one of: biased, red, green, blue, maxrgb," echo "minrgb, colorspace, normalize-only, heightmap or a value from 1 to 9" echo "corresponding respectively to those keywords. Defaults to 0 (simple" echo "normalize) if not specified. Wrap, if specified, enables wrapping of the" echo "normalmap around the edges of the texture (defaults to no). Invert X/Y" echo "reverses the calculated gradients for the X and/or Y dimensions represented" echo "by the normalmap (both default to non-inverted)." echo "" echo "The pattern, can be an escaped pattern string such as \*apple\* or" echo "default_\*.png or similar (defaults to all PNG and JPG images in the current" echo "directory that do not contain \"_normal\" or \"_specular\" in their filenames)." echo "" echo "If set for dry-run, the actions this script will take will be printed, but no" echo "images will be generated. Passing an invalid value to a switch will generally" echo "cause that switch to revert to its default value." echo "" exit 1 ;; esac done echo -e "\nProcessing files based on pattern \"$pattern\" ..." normalMap() { out=`echo "$1" | sed 's/.png/_normal.png/' | sed 's/.jpg/_normal.png/'` echo "Launched process to generate normalmap: \"$1\" --> \"$out\"" >&2 gimp -i -b " (define (normalMap-fbx-conversion fileName newFileName filter nscale wrap heightsource conversion invertx inverty) (let* ( (image (car (gimp-file-load RUN-NONINTERACTIVE fileName fileName))) (drawable (car (gimp-image-get-active-layer image))) (drawable (car (gimp-image-flatten image))) ) (if (> (car (gimp-drawable-type drawable)) 1) (gimp-convert-rgb image) () ) (plug-in-normalmap RUN-NONINTERACTIVE image drawable filter 0.0 nscale wrap heightsource 0 conversion 0 invertx inverty 0 0.0 drawable) (gimp-file-save RUN-NONINTERACTIVE image drawable newFileName newFileName) (gimp-image-delete image) ) ) (normalMap-fbx-conversion \"$1\" \"$out\" $2 $3 $4 $5 $6 $7 $8)" -b '(gimp-quit 0)' } export -f normalMap for file in `ls $pattern |grep -v "_normal.png"|grep -v "_specular"` ; do invtest=`file "$file" |grep "$invresolution x $invresolution"` if $skipinventory && [ -n "$invtest" ] ; then echo "Skipped presumed "$invresolution"px inventory image: $file" >&2 continue fi tooltest=`echo "$file" \ | grep -v "_tool" \ | grep -v "_shovel" \ | grep -v "_pick" \ | grep -v "_axe" \ | grep -v "_sword" \ | grep -v "_hoe" \ | grep -v "bucket_"` if $skiptools && [ -z "$tooltest" ] ; then echo "Skipped presumed tool image: $file" >&2 continue fi if $dryrun ; then echo "Would have generated a normalmap for $file" >&2 continue else echo \"$file\" $filter $scale $wrap $heightsource $conversion $invertx $inverty fi done | xargs -P $numprocs -n 8 -I{} bash -c normalMap\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}
pgimeno/minetest
util/generate-texture-normals.sh
Shell
mit
5,955
#!/bin/bash dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" gameid=minimal minetest=$dir/../bin/minetest testspath=$dir/../tests worldpath=$testspath/testworld_$gameid configpath=$testspath/configs logpath=$testspath/log conf_server=$configpath/minetest.conf.multi.server conf_client1=$configpath/minetest.conf.multi.client1 conf_client2=$configpath/minetest.conf.multi.client2 log_server=$logpath/server.log log_client1=$logpath/client1.log log_client2=$logpath/client2.log mkdir -p $worldpath mkdir -p $configpath mkdir -p $logpath echo -ne 'client1::shout,interact,settime,teleport,give client2::shout,interact,settime,teleport,give ' > $worldpath/auth.txt echo -ne '' > $conf_server echo -ne '# client 1 config screenW=500 screenH=380 name=client1 viewing_range_nodes_min=10 ' > $conf_client1 echo -ne '# client 2 config screenW=500 screenH=380 name=client2 viewing_range_nodes_min=10 ' > $conf_client2 echo $(sleep 1; $minetest --disable-unittests --logfile $log_client1 --config $conf_client1 --go --address localhost) & echo $(sleep 2; $minetest --disable-unittests --logfile $log_client2 --config $conf_client2 --go --address localhost) & $minetest --disable-unittests --server --logfile $log_server --config $conf_server --world $worldpath --gameid $gameid
pgimeno/minetest
util/test_multiplayer.sh
Shell
mit
1,281
#!/bin/bash -e echo "Preparing for $TRAVIS_COMMIT_RANGE" . util/travis/common.sh if [[ ! -z "${CLANG_FORMAT}" ]]; then exit 0 fi needs_compile || exit 0 if [[ $PLATFORM == "Unix" ]] || [[ ! -z "${CLANG_TIDY}" ]]; then if [[ $TRAVIS_OS_NAME == "linux" ]] || [[ ! -z "${CLANG_TIDY}" ]]; then install_linux_deps else install_macosx_deps fi elif [[ $PLATFORM == "Win32" ]]; then sudo apt-get update sudo apt-get install p7zip-full wget http://minetest.kitsunemimi.pw/mingw-w64-i686_7.1.1_ubuntu14.04.7z -O mingw.7z sed -e "s|%PREFIX%|i686-w64-mingw32|" \ -e "s|%ROOTPATH%|/usr/i686-w64-mingw32|" \ < util/travis/toolchain_mingw.cmake.in > util/buildbot/toolchain_mingw.cmake sudo 7z x -y -o/usr mingw.7z elif [[ $PLATFORM == "Win64" ]]; then sudo apt-get update sudo apt-get install p7zip-full wget http://minetest.kitsunemimi.pw/mingw-w64-x86_64_7.1.1_ubuntu14.04.7z -O mingw.7z sed -e "s|%PREFIX%|x86_64-w64-mingw32|" \ -e "s|%ROOTPATH%|/usr/x86_64-w64-mingw32|" \ < util/travis/toolchain_mingw.cmake.in > util/buildbot/toolchain_mingw64.cmake sudo 7z x -y -o/usr mingw.7z fi
pgimeno/minetest
util/travis/before_install.sh
Shell
mit
1,105
src/activeobject.h src/ban.cpp src/camera.cpp src/camera.h src/chat.cpp src/chat.h src/chat_interface.h src/client/clientlauncher.cpp src/client/clientlauncher.h src/client/sound_openal.cpp src/client.cpp src/clientenvironment.cpp src/clientenvironment.h src/client/gameui.cpp src/client.h src/client/hud.cpp src/client/hud.h src/clientiface.cpp src/clientiface.h src/client/joystick_controller.cpp src/client/joystick_controller.h src/clientmap.cpp src/clientmap.h src/clientmedia.cpp src/clientmedia.h src/clientobject.cpp src/clientobject.h src/client/render/core.cpp src/client/renderingengine.cpp src/client/render/interlaced.cpp src/client/render/plain.cpp src/client/render/sidebyside.cpp src/client/render/stereo.cpp src/client/tile.cpp src/client/tile.h src/client/fontengine.h src/client/clientenvironment.cpp src/client/mapblock_mesh.cpp src/client/sound_openal.h src/client/clouds.cpp src/client/fontengine.cpp src/client/camera.h src/client/hud.cpp src/client/clientmap.cpp src/client/sound_openal.cpp src/client/minimap.h src/client/content_cao.cpp src/client/localplayer.h src/client/mapblock_mesh.h src/client/mesh.cpp src/client/sound.cpp src/client/guiscalingfilter.cpp src/client/content_cso.cpp src/client/gameui.cpp src/client/wieldmesh.cpp src/client/clientmedia.h src/client/game.cpp src/client/keys.h src/client/client.h src/client/shader.cpp src/client/clientmap.h src/client/inputhandler.h src/client/content_mapblock.h src/client/game.h src/client/mesh.h src/client/camera.cpp src/client/sky.h src/client/mesh_generator_thread.cpp src/client/guiscalingfilter.h src/client/clientobject.cpp src/client/tile.cpp src/client/hud.h src/client/inputhandler.cpp src/client/clientevent.h src/client/gameui.h src/client/content_cso.h src/client/sky.cpp src/client/localplayer.cpp src/client/content_mapblock.cpp src/client/clientobject.h src/client/filecache.cpp src/client/particles.h src/client/clientenvironment.h src/client/imagefilters.h src/client/renderingengine.cpp src/client/tile.h src/client/clientmedia.cpp src/client/event_manager.h src/client/joystick_controller.h src/client/clouds.h src/client/clientlauncher.h src/client/content_cao.h src/client/minimap.cpp src/client/sound.h src/client/keycode.cpp src/client/particles.cpp src/client/joystick_controller.cpp src/client/keycode.h src/client/wieldmesh.h src/client/filecache.h src/client/shader.h src/client/mesh_generator_thread.h src/client/renderingengine.h src/client/client.cpp src/client/imagefilters.cpp src/client/clientlauncher.cpp src/clouds.cpp src/clouds.h src/collision.cpp src/collision.h src/config.h src/content_cao.cpp src/content_cao.h src/content_cso.cpp src/content_cso.h src/content_mapblock.cpp src/content_mapblock.h src/content_mapnode.cpp src/content_nodemeta.cpp src/content_nodemeta.h src/content_sao.cpp src/content_sao.h src/convert_json.cpp src/convert_json.h src/craftdef.cpp src/craftdef.h src/database/database.cpp src/database/database-dummy.cpp src/database/database-files.cpp src/database/database-leveldb.cpp src/database/database-postgresql.cpp src/database/database-postgresql.h src/database/database-redis.cpp src/database/database-sqlite3.cpp src/database/database-sqlite3.h src/daynightratio.h src/debug.cpp src/debug.h src/defaultsettings.cpp src/emerge.cpp src/emerge.h src/environment.cpp src/exceptions.h src/face_position_cache.cpp src/face_position_cache.h src/filecache.cpp src/filesys.cpp src/filesys.h src/fontengine.cpp src/fontengine.h src/game.cpp src/gamedef.h src/game.h src/genericobject.cpp src/genericobject.h src/gettext.cpp src/gettext.h src/gui/guiChatConsole.cpp src/gui/guiChatConsole.h src/gui/guiConfirmRegistration.cpp src/gui/guiEditBoxWithScrollbar.cpp src/gui/guiEditBoxWithScrollbar.h src/gui/guiEngine.cpp src/gui/guiEngine.h src/gui/guiFormSpecMenu.cpp src/gui/guiFormSpecMenu.h src/gui/guiKeyChangeMenu.cpp src/gui/guiMainMenu.h src/gui/guiPasswordChange.cpp src/gui/guiPathSelectMenu.cpp src/gui/guiPathSelectMenu.h src/gui/guiTable.cpp src/gui/guiTable.h src/gui/guiVolumeChange.cpp src/gui/guiVolumeChange.h src/gui/intlGUIEditBox.cpp src/gui/intlGUIEditBox.h src/gui/mainmenumanager.h src/gui/modalMenu.h src/guiscalingfilter.cpp src/guiscalingfilter.h src/gui/touchscreengui.cpp src/httpfetch.cpp src/hud.cpp src/hud.h src/imagefilters.cpp src/imagefilters.h src/inventory.cpp src/inventory.h src/inventorymanager.cpp src/inventorymanager.h src/irrlicht_changes/CGUITTFont.cpp src/irrlicht_changes/CGUITTFont.h src/irrlicht_changes/irrUString.h src/irrlicht_changes/static_text.cpp src/irrlicht_changes/static_text.h src/irrlichttypes.h src/itemdef.cpp src/itemdef.h src/itemstackmetadata.cpp src/keycode.cpp src/light.cpp src/localplayer.cpp src/log.cpp src/log.h src/main.cpp src/mapblock.cpp src/mapblock.h src/mapblock_mesh.cpp src/mapblock_mesh.h src/map.cpp src/mapgen/cavegen.cpp src/mapgen/cavegen.h src/mapgen/dungeongen.cpp src/mapgen/dungeongen.h src/mapgen/mapgen_carpathian.cpp src/mapgen/mapgen_carpathian.h src/mapgen/mapgen.cpp src/mapgen/mapgen_flat.cpp src/mapgen/mapgen_flat.h src/mapgen/mapgen_fractal.cpp src/mapgen/mapgen_fractal.h src/mapgen/mapgen.h src/mapgen/mapgen_singlenode.cpp src/mapgen/mapgen_singlenode.h src/mapgen/mapgen_v5.cpp src/mapgen/mapgen_v5.h src/mapgen/mapgen_v6.cpp src/mapgen/mapgen_v6.h src/mapgen/mapgen_v7.cpp src/mapgen/mapgen_v7.h src/mapgen/mapgen_valleys.cpp src/mapgen/mapgen_valleys.h src/mapgen/mg_biome.cpp src/mapgen/mg_biome.h src/mapgen/mg_decoration.cpp src/mapgen/mg_decoration.h src/mapgen/mg_ore.cpp src/mapgen/mg_ore.h src/mapgen/mg_schematic.cpp src/mapgen/mg_schematic.h src/mapgen/treegen.cpp src/mapgen/treegen.h src/map.h src/mapnode.cpp src/mapnode.h src/mapsector.cpp src/mapsector.h src/map_settings_manager.cpp src/map_settings_manager.h src/mesh.cpp src/mesh_generator_thread.cpp src/mesh.h src/metadata.h src/minimap.cpp src/minimap.h src/mods.cpp src/mods.h src/network/address.cpp src/network/clientopcodes.cpp src/network/clientopcodes.h src/network/clientpackethandler.cpp src/network/connection.cpp src/network/connection.h src/network/connectionthreads.cpp src/network/networkpacket.cpp src/network/networkprotocol.h src/network/serveropcodes.cpp src/network/serveropcodes.h src/network/serverpackethandler.cpp src/nodedef.cpp src/nodedef.h src/nodemetadata.cpp src/nodemetadata.h src/nodetimer.cpp src/nodetimer.h src/noise.cpp src/noise.h src/objdef.cpp src/objdef.h src/object_properties.cpp src/object_properties.h src/particles.cpp src/particles.h src/pathfinder.cpp src/pathfinder.h src/player.cpp src/player.h src/porting_android.cpp src/porting_android.h src/porting.cpp src/porting.h src/profiler.h src/quicktune.cpp src/quicktune.h src/quicktune_shortcutter.h src/raycast.cpp src/raycast.h src/reflowscan.cpp src/reflowscan.h src/remoteplayer.cpp src/rollback.cpp src/rollback.h src/rollback_interface.cpp src/rollback_interface.h src/script/common/c_content.cpp src/script/common/c_content.h src/script/common/c_converter.cpp src/script/common/c_converter.h src/script/common/c_internal.cpp src/script/common/c_internal.h src/script/common/c_types.cpp src/script/common/c_types.h src/script/cpp_api/s_async.cpp src/script/cpp_api/s_async.h src/script/cpp_api/s_base.cpp src/script/cpp_api/s_base.h src/script/cpp_api/s_client.cpp src/script/cpp_api/s_entity.cpp src/script/cpp_api/s_entity.h src/script/cpp_api/s_env.cpp src/script/cpp_api/s_env.h src/script/cpp_api/s_internal.h src/script/cpp_api/s_inventory.cpp src/script/cpp_api/s_inventory.h src/script/cpp_api/s_item.cpp src/script/cpp_api/s_item.h src/script/cpp_api/s_mainmenu.h src/script/cpp_api/s_node.cpp src/script/cpp_api/s_node.h src/script/cpp_api/s_nodemeta.cpp src/script/cpp_api/s_nodemeta.h src/script/cpp_api/s_player.cpp src/script/cpp_api/s_player.h src/script/cpp_api/s_security.cpp src/script/cpp_api/s_security.h src/script/cpp_api/s_server.cpp src/script/cpp_api/s_server.h src/script/lua_api/l_areastore.cpp src/script/lua_api/l_base.cpp src/script/lua_api/l_base.h src/script/lua_api/l_craft.cpp src/script/lua_api/l_craft.h src/script/lua_api/l_env.cpp src/script/lua_api/l_env.h src/script/lua_api/l_http.cpp src/script/lua_api/l_http.h src/script/lua_api/l_internal.h src/script/lua_api/l_inventory.cpp src/script/lua_api/l_inventory.h src/script/lua_api/l_item.cpp src/script/lua_api/l_item.h src/script/lua_api/l_itemstackmeta.cpp src/script/lua_api/l_itemstackmeta.h src/script/lua_api/l_localplayer.cpp src/script/lua_api/l_mainmenu.cpp src/script/lua_api/l_mainmenu.h src/script/lua_api/l_mapgen.cpp src/script/lua_api/l_mapgen.h src/script/lua_api/l_metadata.cpp src/script/lua_api/l_minimap.cpp src/script/lua_api/l_nodemeta.cpp src/script/lua_api/l_nodemeta.h src/script/lua_api/l_nodetimer.cpp src/script/lua_api/l_noise.cpp src/script/lua_api/l_object.cpp src/script/lua_api/l_object.h src/script/lua_api/l_particles.cpp src/script/lua_api/l_particles.h src/script/lua_api/l_particles_local.cpp src/script/lua_api/l_rollback.cpp src/script/lua_api/l_rollback.h src/script/lua_api/l_server.cpp src/script/lua_api/l_settings.cpp src/script/lua_api/l_sound.cpp src/script/lua_api/l_storage.cpp src/script/lua_api/l_util.cpp src/script/lua_api/l_vmanip.cpp src/script/scripting_client.cpp src/script/scripting_client.h src/script/scripting_mainmenu.cpp src/script/scripting_mainmenu.h src/script/scripting_server.cpp src/script/scripting_server.h src/serialization.cpp src/serialization.h src/serveractiveobjectmap.cpp src/serveractiveobjectmap.h src/server.cpp src/serverenvironment.cpp src/serverenvironment.h src/server.h src/serverlist.cpp src/serverlist.h src/serverobject.cpp src/serverobject.h src/settings.cpp src/settings.h src/settings_translation_file.cpp src/shader.cpp src/shader.h src/sky.cpp src/sound.cpp src/staticobject.cpp src/staticobject.h src/subgame.cpp src/subgame.h src/terminal_chat_console.cpp src/terminal_chat_console.h src/threading/atomic.h src/threading/event.cpp src/threading/mutex_auto_lock.h src/threading/mutex.cpp src/threading/mutex.h src/threading/semaphore.cpp src/threading/thread.cpp src/threading/thread.h src/threads.h src/tileanimation.cpp src/tool.cpp src/tool.h src/translation.cpp src/unittest/test_areastore.cpp src/unittest/test_collision.cpp src/unittest/test_compression.cpp src/unittest/test_connection.cpp src/unittest/test.cpp src/unittest/test_filepath.cpp src/unittest/test.h src/unittest/test_inventory.cpp src/unittest/test_keycode.cpp src/unittest/test_map_settings_manager.cpp src/unittest/test_noderesolver.cpp src/unittest/test_noise.cpp src/unittest/test_random.cpp src/unittest/test_schematic.cpp src/unittest/test_serialization.cpp src/unittest/test_settings.cpp src/unittest/test_socket.cpp src/unittest/test_threading.cpp src/unittest/test_utilities.cpp src/unittest/test_voxelalgorithms.cpp src/unittest/test_voxelmanipulator.cpp src/util/areastore.cpp src/util/areastore.h src/util/auth.cpp src/util/auth.h src/util/base64.cpp src/util/base64.h src/util/basic_macros.h src/util/container.h src/util/directiontables.cpp src/util/directiontables.h src/util/enriched_string.cpp src/util/enriched_string.h src/util/md32_common.h src/util/numeric.cpp src/util/numeric.h src/util/pointedthing.cpp src/util/pointedthing.h src/util/pointer.h src/util/serialize.cpp src/util/serialize.h src/util/sha1.cpp src/util/srp.cpp src/util/srp.h src/util/strfnd.h src/util/string.cpp src/util/string.h src/util/thread.h src/util/timetaker.cpp src/util/timetaker.h src/version.cpp src/version.h src/voxelalgorithms.cpp src/voxelalgorithms.h src/voxel.cpp src/voxel.h src/wieldmesh.cpp
pgimeno/minetest
util/travis/clang-format-whitelist.txt
Text
mit
11,582