From 52ba1f867e5edb579a59a44fbb8286d4f1e54931 Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Sun, 1 Jan 2017 16:13:01 +0100 Subject: Breath cheat fix: server side Breath is now handled server side. Changing this behaviour required some modifications to core: * Ignore TOSERVER_BREATH package, marking it as obsolete * Clients doesn't send the breath to server anymore * Use PlayerSAO pointer instead of peer_id in Server::SendPlayerBreath to prevent a useless lookup (little perf gain) * drop a useless static_cast in emergePlayer --- src/unittest/test_player.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/unittest') diff --git a/src/unittest/test_player.cpp b/src/unittest/test_player.cpp index 85fbc8b2d..655ee08fd 100644 --- a/src/unittest/test_player.cpp +++ b/src/unittest/test_player.cpp @@ -49,7 +49,7 @@ void TestPlayer::testSave(IGameDef *gamedef) PlayerSAO sao(NULL, 1, false); sao.initialize(&rplayer, std::set()); rplayer.setPlayerSAO(&sao); - sao.setBreath(10); + sao.setBreath(10, false); sao.setHPRaw(8); sao.setYaw(0.1f); sao.setPitch(0.6f); @@ -64,7 +64,7 @@ void TestPlayer::testLoad(IGameDef *gamedef) PlayerSAO sao(NULL, 1, false); sao.initialize(&rplayer, std::set()); rplayer.setPlayerSAO(&sao); - sao.setBreath(10); + sao.setBreath(10, false); sao.setHPRaw(8); sao.setYaw(0.1f); sao.setPitch(0.6f); -- cgit v1.2.3 From 3f8261830e0503cd59d8713d5c9aab12fc1491db Mon Sep 17 00:00:00 2001 From: Dániel Juhász Date: Wed, 4 Jan 2017 19:18:40 +0100 Subject: Improve getPointedThing() (#4346) * Improved getPointedThing() The new algorithm checks every node exactly once. Now the point and normal vector of the collision is also returned in the PointedThing (currently they are not used outside of the function). Now the CNodeDefManager keeps the union of all possible nodeboxes, so the raycast won't miss any nodes. Also if there are only small nodeboxes, getPointedThing() is exceptionally fast. Also adds unit test for VoxelLineIterator. * Cleanup, code move This commit moves getPointedThing() and Client::getSelectedActiveObject() to ClientEnvironment. The map nodes now can decide which neighbors they are connecting to (MapNode::getNeighbors()). --- src/CMakeLists.txt | 1 + src/client.cpp | 39 +--- src/client.h | 8 - src/clientmap.cpp | 33 ++- src/environment.cpp | 241 +++++++++++++++++++++ src/environment.h | 36 ++++ src/game.cpp | 392 ++++++++++------------------------ src/map.cpp | 91 ++++---- src/map.h | 5 + src/mapnode.cpp | 46 ++++ src/mapnode.h | 8 + src/nodedef.cpp | 141 ++++++++++++ src/nodedef.h | 6 + src/raycast.cpp | 89 ++++++++ src/raycast.h | 38 ++++ src/unittest/test_voxelalgorithms.cpp | 59 +++++ src/util/pointedthing.cpp | 75 +++---- src/util/pointedthing.h | 40 ++++ src/voxelalgorithms.cpp | 68 ++++++ src/voxelalgorithms.h | 61 ++++++ 20 files changed, 1045 insertions(+), 432 deletions(-) create mode 100644 src/raycast.cpp create mode 100644 src/raycast.h (limited to 'src/unittest') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 51cf88063..507624753 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -447,6 +447,7 @@ set(common_SRCS quicktune.cpp reflowscan.cpp remoteplayer.cpp + raycast.cpp rollback.cpp rollback_interface.cpp serialization.cpp diff --git a/src/client.cpp b/src/client.cpp index 1446ebad8..693a90604 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -53,6 +53,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database-sqlite3.h" #include "serialization.h" #include "guiscalingfilter.h" +#include "raycast.h" extern gui::IGUIEnvironment* guienv; @@ -1500,44 +1501,6 @@ void Client::inventoryAction(InventoryAction *a) delete a; } -ClientActiveObject * Client::getSelectedActiveObject( - f32 max_d, - v3f from_pos_f_on_map, - core::line3d shootline_on_map - ) -{ - std::vector objects; - - m_env.getActiveObjects(from_pos_f_on_map, max_d, objects); - - // Sort them. - // After this, the closest object is the first in the array. - std::sort(objects.begin(), objects.end()); - - for(unsigned int i=0; igetSelectionBox(); - if(selection_box == NULL) - continue; - - v3f pos = obj->getPosition(); - - aabb3f offsetted_box( - selection_box->MinEdge + pos, - selection_box->MaxEdge + pos - ); - - if(offsetted_box.intersectsWithLine(shootline_on_map)) - { - return obj; - } - } - - return NULL; -} - float Client::getAnimationTime() { return m_animation_time; diff --git a/src/client.h b/src/client.h index 9f5bda059..891fe62f8 100644 --- a/src/client.h +++ b/src/client.h @@ -445,14 +445,6 @@ public: Inventory* getInventory(const InventoryLocation &loc); void inventoryAction(InventoryAction *a); - // Gets closest object pointed by the shootline - // Returns NULL if not found - ClientActiveObject * getSelectedActiveObject( - f32 max_d, - v3f from_pos_f_on_map, - core::line3d shootline_on_map - ); - const std::list &getConnectedPlayerNames() { return m_env.getPlayerNames(); diff --git a/src/clientmap.cpp b/src/clientmap.cpp index 7d76e6e8b..542eb03e8 100644 --- a/src/clientmap.cpp +++ b/src/clientmap.cpp @@ -172,8 +172,6 @@ void ClientMap::updateDrawList(video::IVideoDriver* driver) ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG); g_profiler->add("CM::updateDrawList() count", 1); - INodeDefManager *nodemgr = m_gamedef->ndef(); - for (std::map::iterator i = m_drawlist.begin(); i != m_drawlist.end(); ++i) { MapBlock *block = i->second; @@ -219,7 +217,7 @@ void ClientMap::updateDrawList(video::IVideoDriver* driver) if (g_settings->getBool("free_move")) { MapNode n = getNodeNoEx(cam_pos_nodes); if (n.getContent() == CONTENT_IGNORE || - nodemgr->get(n).solidness == 2) + m_nodedef->get(n).solidness == 2) occlusion_culling_enabled = false; } @@ -297,23 +295,23 @@ void ClientMap::updateDrawList(video::IVideoDriver* driver) if (occlusion_culling_enabled && // For the central point of the mapblock 'endoff' can be halved isOccluded(this, spn, cpn, - step, stepfac, startoff, endoff / 2.0f, needed_count, nodemgr) && + step, stepfac, startoff, endoff / 2.0f, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr) && + step, stepfac, startoff, endoff, needed_count, m_nodedef) && isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2), - step, stepfac, startoff, endoff, needed_count, nodemgr)) { + step, stepfac, startoff, endoff, needed_count, m_nodedef)) { blocks_occlusion_culled++; continue; } @@ -656,7 +654,6 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, int oldvalue, bool *sunlight_seen_result) { const bool debugprint = false; - INodeDefManager *ndef = m_gamedef->ndef(); static v3f z_directions[50] = { v3f(-100, 0, 0) }; @@ -694,7 +691,7 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, float off = step * z_offsets[i]; bool sunlight_seen_now = false; bool ok = getVisibleBrightness(this, m_camera_position, dir, - step, 1.0, max_d*0.6+off, max_d, ndef, daylight_factor, + step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor, sunlight_min_d, &br, &sunlight_seen_now); if(sunlight_seen_now) @@ -734,8 +731,8 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, int ret = 0; if(brightness_count == 0){ MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS)); - if(ndef->get(n).param_type == CPT_LIGHT){ - ret = decode_light(n.getLightBlend(daylight_factor, ndef)); + if(m_nodedef->get(n).param_type == CPT_LIGHT){ + ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef)); } else { ret = oldvalue; } @@ -758,8 +755,6 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, void ClientMap::renderPostFx(CameraMode cam_mode) { - INodeDefManager *nodemgr = m_gamedef->ndef(); - // Sadly ISceneManager has no "post effects" render pass, in that case we // could just register for that and handle it in renderMap(). @@ -768,7 +763,7 @@ void ClientMap::renderPostFx(CameraMode cam_mode) // - If the player is in a solid node, make everything black. // - If the player is in liquid, draw a semi-transparent overlay. // - Do not if player is in third person mode - const ContentFeatures& features = nodemgr->get(n); + const ContentFeatures& features = m_nodedef->get(n); video::SColor post_effect_color = features.post_effect_color; if(features.solidness == 2 && !(g_settings->getBool("noclip") && m_gamedef->checkLocalPrivilege("noclip")) && diff --git a/src/environment.cpp b/src/environment.cpp index ac9b5b079..8c0daf87b 100644 --- a/src/environment.cpp +++ b/src/environment.cpp @@ -43,8 +43,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "daynightratio.h" #include "map.h" #include "emerge.h" +#include "raycast.h" +#include "voxelalgorithms.h" #include "util/serialize.h" #include "util/basic_macros.h" +#include "util/pointedthing.h" #include "threading/mutex_auto_lock.h" #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:" @@ -2848,4 +2851,242 @@ ClientEnvEvent ClientEnvironment::getClientEvent() return event; } +ClientActiveObject * ClientEnvironment::getSelectedActiveObject( + const core::line3d &shootline_on_map, v3f *intersection_point, + v3s16 *intersection_normal) +{ + std::vector objects; + getActiveObjects(shootline_on_map.start, + shootline_on_map.getLength() + 3, objects); + const v3f line_vector = shootline_on_map.getVector(); + + // Sort them. + // After this, the closest object is the first in the array. + std::sort(objects.begin(), objects.end()); + + /* Because objects can have different nodebox sizes, + * the object whose center is the nearest isn't necessarily + * the closest one. If an object is found, don't stop + * immediately. */ + + f32 d_min = shootline_on_map.getLength(); + ClientActiveObject *nearest_obj = NULL; + for (u32 i = 0; i < objects.size(); i++) { + ClientActiveObject *obj = objects[i].obj; + + aabb3f *selection_box = obj->getSelectionBox(); + if (selection_box == NULL) + continue; + + v3f pos = obj->getPosition(); + + aabb3f offsetted_box(selection_box->MinEdge + pos, + selection_box->MaxEdge + pos); + + if (offsetted_box.getCenter().getDistanceFrom( + shootline_on_map.start) > d_min + 9.6f*BS) { + // Probably there is no active object that has bigger nodebox than + // (-5.5,-5.5,-5.5,5.5,5.5,5.5) + // 9.6 > 5.5*sqrt(3) + break; + } + + v3f current_intersection; + v3s16 current_normal; + if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector, + ¤t_intersection, ¤t_normal)) { + f32 d_current = current_intersection.getDistanceFrom( + shootline_on_map.start); + if (d_current <= d_min) { + d_min = d_current; + nearest_obj = obj; + *intersection_point = current_intersection; + *intersection_normal = current_normal; + } + } + } + + return nearest_obj; +} + +/* + Check if a node is pointable +*/ +static inline bool isPointableNode(const MapNode &n, + INodeDefManager *ndef, bool liquids_pointable) +{ + const ContentFeatures &features = ndef->get(n); + return features.pointable || + (liquids_pointable && features.isLiquid()); +} + +PointedThing ClientEnvironment::getPointedThing( + core::line3d shootline, + bool liquids_pointable, + bool look_for_object) +{ + PointedThing result; + + INodeDefManager *nodedef = m_map->getNodeDefManager(); + + core::aabbox3d maximal_exceed = nodedef->getSelectionBoxIntUnion(); + // The code needs to search these nodes + core::aabbox3d search_range(-maximal_exceed.MaxEdge, + -maximal_exceed.MinEdge); + // If a node is found, there might be a larger node behind. + // To find it, we have to go further. + s16 maximal_overcheck = + std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X)) + + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y)) + + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z)); + + const v3f original_vector = shootline.getVector(); + const f32 original_length = original_vector.getLength(); + + f32 min_distance = original_length; + + // First try to find an active object + if (look_for_object) { + ClientActiveObject *selected_object = getSelectedActiveObject( + shootline, &result.intersection_point, + &result.intersection_normal); + + if (selected_object != NULL) { + min_distance = + (result.intersection_point - shootline.start).getLength(); + + result.type = POINTEDTHING_OBJECT; + result.object_id = selected_object->getId(); + } + } + + // Reduce shootline + if (original_length > 0) { + shootline.end = shootline.start + + shootline.getVector() / original_length * min_distance; + } + + // Try to find a node that is closer than the selected active + // object (if it exists). + + voxalgo::VoxelLineIterator iterator(shootline.start / BS, + shootline.getVector() / BS); + v3s16 oldnode = iterator.m_current_node_pos; + // Indicates that a node was found. + bool is_node_found = false; + // If a node is found, it is possible that there's a node + // behind it with a large nodebox, so continue the search. + u16 node_foundcounter = 0; + // If a node is found, this is the center of the + // first nodebox the shootline meets. + v3f found_boxcenter(0, 0, 0); + // The untested nodes are in this range. + core::aabbox3d new_nodes; + while (true) { + // Test the nodes around the current node in search_range. + new_nodes = search_range; + new_nodes.MinEdge += iterator.m_current_node_pos; + new_nodes.MaxEdge += iterator.m_current_node_pos; + + // Only check new nodes + v3s16 delta = iterator.m_current_node_pos - oldnode; + if (delta.X > 0) + new_nodes.MinEdge.X = new_nodes.MaxEdge.X; + else if (delta.X < 0) + new_nodes.MaxEdge.X = new_nodes.MinEdge.X; + else if (delta.Y > 0) + new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y; + else if (delta.Y < 0) + new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y; + else if (delta.Z > 0) + new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z; + else if (delta.Z < 0) + new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z; + + // For each untested node + for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) { + for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) { + for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) { + MapNode n; + v3s16 np(x, y, z); + bool is_valid_position; + + n = m_map->getNodeNoEx(np, &is_valid_position); + if (!(is_valid_position && + isPointableNode(n, nodedef, liquids_pointable))) { + continue; + } + std::vector boxes; + n.getSelectionBoxes(nodedef, &boxes, + n.getNeighbors(np, m_map)); + + v3f npf = intToFloat(np, BS); + for (std::vector::const_iterator i = boxes.begin(); + i != boxes.end(); ++i) { + aabb3f box = *i; + box.MinEdge += npf; + box.MaxEdge += npf; + v3f intersection_point; + v3s16 intersection_normal; + if (!boxLineCollision(box, shootline.start, shootline.getVector(), + &intersection_point, &intersection_normal)) { + continue; + } + f32 distance = (intersection_point - shootline.start).getLength(); + if (distance >= min_distance) { + continue; + } + result.type = POINTEDTHING_NODE; + result.node_undersurface = np; + result.intersection_point = intersection_point; + result.intersection_normal = intersection_normal; + found_boxcenter = box.getCenter(); + min_distance = distance; + is_node_found = true; + } + } + } + } + if (is_node_found) { + node_foundcounter++; + if (node_foundcounter > maximal_overcheck) { + break; + } + } + // Next node + if (iterator.hasNext()) { + oldnode = iterator.m_current_node_pos; + iterator.next(); + } else { + break; + } + } + + if (is_node_found) { + // Set undersurface and abovesurface nodes + f32 d = 0.002 * BS; + v3f fake_intersection = result.intersection_point; + // Move intersection towards its source block. + if (fake_intersection.X < found_boxcenter.X) + fake_intersection.X += d; + else + fake_intersection.X -= d; + + if (fake_intersection.Y < found_boxcenter.Y) + fake_intersection.Y += d; + else + fake_intersection.Y -= d; + + if (fake_intersection.Z < found_boxcenter.Z) + fake_intersection.Z += d; + else + fake_intersection.Z -= d; + + result.node_real_undersurface = floatToInt(fake_intersection, BS); + result.node_abovesurface = result.node_real_undersurface + + result.intersection_normal; + } + return result; +} + #endif // #ifndef SERVER diff --git a/src/environment.h b/src/environment.h index 4bee40e57..84805b462 100644 --- a/src/environment.h +++ b/src/environment.h @@ -55,6 +55,7 @@ class GameScripting; class Player; class RemotePlayer; class PlayerSAO; +class PointedThing; class Environment { @@ -627,6 +628,41 @@ public: // Get event from queue. CEE_NONE is returned if queue is empty. ClientEnvEvent getClientEvent(); + /*! + * Gets closest object pointed by the shootline. + * Returns NULL if not found. + * + * \param[in] shootline_on_map the shootline for + * the test in world coordinates + * \param[out] intersection_point the first point where + * the shootline meets the object. Valid only if + * not NULL is returned. + * \param[out] intersection_normal the normal vector of + * the intersection, pointing outwards. Zero vector if + * the shootline starts in an active object. + * Valid only if not NULL is returned. + */ + ClientActiveObject * getSelectedActiveObject( + const core::line3d &shootline_on_map, + v3f *intersection_point, + v3s16 *intersection_normal + ); + + /*! + * Performs a raycast on the world. + * Returns the first thing the shootline meets. + * + * @param[in] shootline the shootline, starting from + * the camera position. This also gives the maximal distance + * of the search. + * @param[in] liquids_pointable if false, liquids are ignored + * @param[in] look_for_object if false, objects are ignored + */ + PointedThing getPointedThing( + core::line3d shootline, + bool liquids_pointable, + bool look_for_object); + u16 attachement_parent_ids[USHRT_MAX + 1]; const std::list &getPlayerNames() { return m_player_names; } diff --git a/src/game.cpp b/src/game.cpp index 5bdbea617..cfa6234ff 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -265,271 +265,6 @@ public: Client *m_client; }; -/* - Check if a node is pointable -*/ -inline bool isPointableNode(const MapNode &n, - Client *client, bool liquids_pointable) -{ - const ContentFeatures &features = client->getNodeDefManager()->get(n); - return features.pointable || - (liquids_pointable && features.isLiquid()); -} - -static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef, - ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors) -{ - MapNode n2 = map->getNodeNoEx(p); - if (nodedef->nodeboxConnects(n, n2, bitmask)) - *neighbors |= bitmask; -} - -static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n) -{ - u8 neighbors = 0; - const ContentFeatures &f = nodedef->get(n); - // locate possible neighboring nodes to connect to - if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) { - v3s16 p2 = p; - - p2.Y++; - getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors); - - p2 = p; - p2.Y--; - getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors); - - p2 = p; - p2.Z--; - getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors); - - p2 = p; - p2.X--; - getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors); - - p2 = p; - p2.Z++; - getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors); - - p2 = p; - p2.X++; - getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors); - } - - return neighbors; -} - -/* - Find what the player is pointing at -*/ -PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position, - const v3f &camera_direction, const v3f &camera_position, - core::line3d shootline, f32 d, bool liquids_pointable, - bool look_for_object, const v3s16 &camera_offset, - ClientActiveObject *&selected_object) -{ - PointedThing result; - - std::vector *selectionboxes = hud->getSelectionBoxes(); - selectionboxes->clear(); - static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox"); - - selected_object = NULL; - - INodeDefManager *nodedef = client->getNodeDefManager(); - ClientMap &map = client->getEnv().getClientMap(); - - f32 min_distance = BS * 1001; - - // First try to find a pointed at active object - if (look_for_object) { - selected_object = client->getSelectedActiveObject(d * BS, - camera_position, shootline); - - if (selected_object != NULL) { - if (show_entity_selectionbox && - selected_object->doShowSelectionBox()) { - aabb3f *selection_box = selected_object->getSelectionBox(); - // Box should exist because object was - // returned in the first place - assert(selection_box); - - v3f pos = selected_object->getPosition(); - selectionboxes->push_back(aabb3f( - selection_box->MinEdge, selection_box->MaxEdge)); - hud->setSelectionPos(pos, camera_offset); - } - - min_distance = (selected_object->getPosition() - camera_position).getLength(); - - hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0)); - result.type = POINTEDTHING_OBJECT; - result.object_id = selected_object->getId(); - } - } - - // That didn't work, try to find a pointed at node - - v3s16 pos_i = floatToInt(player_position, BS); - - /*infostream<<"pos_i=("< 0 ? a : 1); - s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1); - s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1); - - // Prevent signed number overflow - if (yend == 32767) - yend = 32766; - - if (zend == 32767) - zend = 32766; - - if (xend == 32767) - xend = 32766; - - v3s16 pointed_pos(0, 0, 0); - - for (s16 y = ystart; y <= yend; y++) { - for (s16 z = zstart; z <= zend; z++) { - for (s16 x = xstart; x <= xend; x++) { - MapNode n; - bool is_valid_position; - v3s16 p(x, y, z); - - n = map.getNodeNoEx(p, &is_valid_position); - if (!is_valid_position) { - continue; - } - if (!isPointableNode(n, client, liquids_pointable)) { - continue; - } - - std::vector boxes; - n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n)); - - v3s16 np(x, y, z); - v3f npf = intToFloat(np, BS); - for (std::vector::const_iterator - i = boxes.begin(); - i != boxes.end(); ++i) { - aabb3f box = *i; - box.MinEdge += npf; - box.MaxEdge += npf; - - v3f centerpoint = box.getCenter(); - f32 distance = (centerpoint - camera_position).getLength(); - if (distance >= min_distance) { - continue; - } - if (!box.intersectsWithLine(shootline)) { - continue; - } - result.type = POINTEDTHING_NODE; - min_distance = distance; - pointed_pos = np; - } - } - } - } - - if (result.type == POINTEDTHING_NODE) { - f32 d = 0.001 * BS; - MapNode n = map.getNodeNoEx(pointed_pos); - v3f npf = intToFloat(pointed_pos, BS); - std::vector boxes; - n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n)); - f32 face_min_distance = 1000 * BS; - for (std::vector::const_iterator - i = boxes.begin(); - i != boxes.end(); ++i) { - aabb3f box = *i; - box.MinEdge += npf; - box.MaxEdge += npf; - for (u16 j = 0; j < 6; j++) { - v3s16 facedir = g_6dirs[j]; - aabb3f facebox = box; - if (facedir.X > 0) { - facebox.MinEdge.X = facebox.MaxEdge.X - d; - } else if (facedir.X < 0) { - facebox.MaxEdge.X = facebox.MinEdge.X + d; - } else if (facedir.Y > 0) { - facebox.MinEdge.Y = facebox.MaxEdge.Y - d; - } else if (facedir.Y < 0) { - facebox.MaxEdge.Y = facebox.MinEdge.Y + d; - } else if (facedir.Z > 0) { - facebox.MinEdge.Z = facebox.MaxEdge.Z - d; - } else if (facedir.Z < 0) { - facebox.MaxEdge.Z = facebox.MinEdge.Z + d; - } - v3f centerpoint = facebox.getCenter(); - f32 distance = (centerpoint - camera_position).getLength(); - if (distance >= face_min_distance) - continue; - if (!facebox.intersectsWithLine(shootline)) - continue; - result.node_abovesurface = pointed_pos + facedir; - hud->setSelectedFaceNormal(v3f(facedir.X, facedir.Y, facedir.Z)); - face_min_distance = distance; - } - } - selectionboxes->clear(); - for (std::vector::const_iterator - i = boxes.begin(); - i != boxes.end(); ++i) { - aabb3f box = *i; - box.MinEdge += v3f(-d, -d, -d); - box.MaxEdge += v3f(d, d, d); - selectionboxes->push_back(box); - } - hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset); - result.node_undersurface = pointed_pos; - } - - // Update selection mesh light level and vertex colors - if (selectionboxes->size() > 0) { - v3f pf = hud->getSelectionPos(); - v3s16 p = floatToInt(pf, BS); - - // Get selection mesh light level - MapNode n = map.getNodeNoEx(p); - u16 node_light = getInteriorLight(n, -1, nodedef); - u16 light_level = node_light; - - for (u8 i = 0; i < 6; i++) { - n = map.getNodeNoEx(p + g_6dirs[i]); - node_light = getInteriorLight(n, -1, nodedef); - if (node_light > light_level) - light_level = node_light; - } - - video::SColor c = MapBlock_LightColor(255, light_level, 0); - u8 day = c.getRed(); - u8 night = c.getGreen(); - u32 daynight_ratio = client->getEnv().getDayNightRatio(); - finalColorBlend(c, day, night, daynight_ratio); - - // Modify final color a bit with time - u32 timer = porting::getTimeMs() % 5000; - float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5)); - float sin_r = 0.08 * sin(timerf); - float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5); - float sin_b = 0.08 * sin(timerf + irr::core::PI); - c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255)); - c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255)); - c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255)); - - // Set mesh final color - hud->setSelectionMeshColor(c); - } - return result; -} - /* Profiler display */ void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe, @@ -1668,6 +1403,23 @@ protected: void updateSound(f32 dtime); void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud, bool show_debug); + /*! + * Returns the object or node the player is pointing at. + * Also updates the selected thing in the Hud. + * + * @param[in] shootline the shootline, starting from + * the camera position. This also gives the maximal distance + * of the search. + * @param[in] liquids_pointable if false, liquids are ignored + * @param[in] look_for_object if false, objects are ignored + * @param[in] camera_offset offset of the camera + * @param[out] selected_object the selected object or + * NULL if not found + */ + PointedThing updatePointedThing( + const core::line3d &shootline, bool liquids_pointable, + bool look_for_object, const v3s16 &camera_offset, + ClientActiveObject *&selected_object); void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem); void handlePointingAtNode(GameRunData *runData, const PointedThing &pointed, const ItemDefinition &playeritem_def, @@ -3823,14 +3575,11 @@ void Game::processPlayerInteraction(GameRunData *runData, core::line3d shootline; if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) { - shootline = core::line3d(camera_position, - camera_position + camera_direction * BS * (d + 1)); - + camera_position + camera_direction * BS * d); } else { // prevent player pointing anything in front-view - if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) - shootline = core::line3d(0, 0, 0, 0, 0, 0); + shootline = core::line3d(camera_position,camera_position); } #ifdef HAVE_TOUCHSCREENGUI @@ -3843,10 +3592,7 @@ void Game::processPlayerInteraction(GameRunData *runData, #endif - PointedThing pointed = getPointedThing( - // input - client, hud, player_position, camera_direction, - camera_position, shootline, d, + PointedThing pointed = updatePointedThing(shootline, playeritem_def.liquids_pointable, !runData->ldown_for_dig, camera_offset, @@ -3940,6 +3686,104 @@ void Game::processPlayerInteraction(GameRunData *runData, } +PointedThing Game::updatePointedThing( + const core::line3d &shootline, + bool liquids_pointable, + bool look_for_object, + const v3s16 &camera_offset, + ClientActiveObject *&selected_object) +{ + std::vector *selectionboxes = hud->getSelectionBoxes(); + selectionboxes->clear(); + static const bool show_entity_selectionbox = g_settings->getBool( + "show_entity_selectionbox"); + + ClientMap &map = client->getEnv().getClientMap(); + INodeDefManager *nodedef=client->getNodeDefManager(); + + selected_object = NULL; + + PointedThing result=client->getEnv().getPointedThing( + shootline, liquids_pointable, look_for_object); + if (result.type == POINTEDTHING_OBJECT) { + selected_object = client->getEnv().getActiveObject(result.object_id); + if (show_entity_selectionbox && selected_object->doShowSelectionBox()) { + aabb3f *selection_box = selected_object->getSelectionBox(); + + // Box should exist because object was + // returned in the first place + + assert(selection_box); + + v3f pos = selected_object->getPosition(); + selectionboxes->push_back(aabb3f( + selection_box->MinEdge, selection_box->MaxEdge)); + selectionboxes->push_back( + aabb3f(selection_box->MinEdge, selection_box->MaxEdge)); + hud->setSelectionPos(pos, camera_offset); + } + } else if (result.type == POINTEDTHING_NODE) { + // Update selection boxes + MapNode n = map.getNodeNoEx(result.node_undersurface); + std::vector boxes; + n.getSelectionBoxes(nodedef, &boxes, + n.getNeighbors(result.node_undersurface, &map)); + + f32 d = 0.002 * BS; + for (std::vector::const_iterator i = boxes.begin(); + i != boxes.end(); ++i) { + aabb3f box = *i; + box.MinEdge -= v3f(d, d, d); + box.MaxEdge += v3f(d, d, d); + selectionboxes->push_back(box); + } + hud->setSelectionPos(intToFloat(result.node_undersurface, BS), + camera_offset); + } + + // Update selection mesh light level and vertex colors + if (selectionboxes->size() > 0) { + v3f pf = hud->getSelectionPos(); + v3s16 p = floatToInt(pf, BS); + + // Get selection mesh light level + MapNode n = map.getNodeNoEx(p); + u16 node_light = getInteriorLight(n, -1, nodedef); + u16 light_level = node_light; + + for (u8 i = 0; i < 6; i++) { + n = map.getNodeNoEx(p + g_6dirs[i]); + node_light = getInteriorLight(n, -1, nodedef); + if (node_light > light_level) + light_level = node_light; + } + + video::SColor c = MapBlock_LightColor(255, light_level, 0); + u8 day = c.getRed(); + u8 night = c.getGreen(); + u32 daynight_ratio = client->getEnv().getDayNightRatio(); + finalColorBlend(c, day, night, daynight_ratio); + + // Modify final color a bit with time + u32 timer = porting::getTimeMs() % 5000; + float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5)); + float sin_r = 0.08 * sin(timerf); + float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5); + float sin_b = 0.08 * sin(timerf + irr::core::PI); + c.setRed( + core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255)); + c.setGreen( + core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255)); + c.setBlue( + core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255)); + + // Set mesh final color + hud->setSelectionMeshColor(c); + } + return result; +} + + void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem) { infostream << "Right Clicked in Air" << std::endl; diff --git a/src/map.cpp b/src/map.cpp index c3b62ded0..53657ce6b 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -66,6 +66,7 @@ Map::Map(std::ostream &dout, IGameDef *gamedef): m_dout(dout), m_gamedef(gamedef), m_sector_cache(NULL), + m_nodedef(gamedef->ndef()), m_transforming_liquid_loop_count_multiplier(1.0f), m_unprocessed_count(0), m_inc_trending_up_start_time(0), @@ -227,7 +228,7 @@ void Map::setNode(v3s16 p, MapNode & n) bool temp_bool; errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE" <<" while trying to replace \"" - <ndef()->get(block->getNodeNoCheck(relpos, &temp_bool)).name + <get(block->getNodeNoCheck(relpos, &temp_bool)).name <<"\" at "< & light_sources, std::map & modified_blocks) { - INodeDefManager *nodemgr = m_gamedef->ndef(); - v3s16 dirs[6] = { v3s16(0,0,1), // back v3s16(0,1,0), // top @@ -353,20 +352,20 @@ void Map::unspreadLight(enum LightBank bank, If the neighbor is dimmer than what was specified as oldlight (the light of the previous node) */ - if(n2.getLight(bank, nodemgr) < oldlight) + if(n2.getLight(bank, m_nodedef) < oldlight) { /* And the neighbor is transparent and it has some light */ - if(nodemgr->get(n2).light_propagates - && n2.getLight(bank, nodemgr) != 0) + if(m_nodedef->get(n2).light_propagates + && n2.getLight(bank, m_nodedef) != 0) { /* Set light to 0 and add to queue */ - u8 current_light = n2.getLight(bank, nodemgr); - n2.setLight(bank, 0, nodemgr); + u8 current_light = n2.getLight(bank, m_nodedef); + n2.setLight(bank, 0, m_nodedef); block->setNode(relpos, n2); unlighted_nodes[n2pos] = current_light; @@ -421,8 +420,6 @@ void Map::spreadLight(enum LightBank bank, std::set & from_nodes, std::map & modified_blocks) { - INodeDefManager *nodemgr = m_gamedef->ndef(); - const v3s16 dirs[6] = { v3s16(0,0,1), // back v3s16(0,1,0), // top @@ -476,7 +473,7 @@ void Map::spreadLight(enum LightBank bank, bool is_valid_position; MapNode n = block->getNode(relpos, &is_valid_position); - u8 oldlight = is_valid_position ? n.getLight(bank, nodemgr) : 0; + u8 oldlight = is_valid_position ? n.getLight(bank, m_nodedef) : 0; u8 newlight = diminish_light(oldlight); // Loop through 6 neighbors @@ -512,7 +509,7 @@ void Map::spreadLight(enum LightBank bank, If the neighbor is brighter than the current node, add to list (it will light up this node on its turn) */ - if(n2.getLight(bank, nodemgr) > undiminish_light(oldlight)) + if(n2.getLight(bank, m_nodedef) > undiminish_light(oldlight)) { lighted_nodes.insert(n2pos); changed = true; @@ -521,11 +518,11 @@ void Map::spreadLight(enum LightBank bank, If the neighbor is dimmer than how much light this node would spread on it, add to list */ - if(n2.getLight(bank, nodemgr) < newlight) + if(n2.getLight(bank, m_nodedef) < newlight) { - if(nodemgr->get(n2).light_propagates) + if(m_nodedef->get(n2).light_propagates) { - n2.setLight(bank, newlight, nodemgr); + n2.setLight(bank, newlight, m_nodedef); block->setNode(relpos, n2); lighted_nodes.insert(n2pos); changed = true; @@ -558,8 +555,6 @@ void Map::updateLighting(enum LightBank bank, std::map & a_blocks, std::map & modified_blocks) { - INodeDefManager *nodemgr = m_gamedef->ndef(); - /*m_dout<<"Map::updateLighting(): " <setNode(p, n); // If node sources light, add to list - u8 source = nodemgr->get(n).light_source; + u8 source = m_nodedef->get(n).light_source; if(source != 0) light_sources.insert(p + posnodes); @@ -810,8 +805,6 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, std::map &modified_blocks, bool remove_metadata) { - INodeDefManager *ndef = m_gamedef->ndef(); - // Collect old node for rollback RollbackNode rollback_oldnode(this, p, m_gamedef); @@ -825,14 +818,14 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, // Set the node on the map // Ignore light (because calling voxalgo::update_lighting_nodes) - n.setLight(LIGHTBANK_DAY, 0, ndef); - n.setLight(LIGHTBANK_NIGHT, 0, ndef); + n.setLight(LIGHTBANK_DAY, 0, m_nodedef); + n.setLight(LIGHTBANK_NIGHT, 0, m_nodedef); setNode(p, n); // Update lighting std::vector > oldnodes; oldnodes.push_back(std::pair(p, oldnode)); - voxalgo::update_lighting_nodes(this, ndef, oldnodes, modified_blocks); + voxalgo::update_lighting_nodes(this, m_nodedef, oldnodes, modified_blocks); for(std::map::iterator i = modified_blocks.begin(); @@ -869,11 +862,10 @@ void Map::addNodeAndUpdate(v3s16 p, MapNode n, bool is_valid_position; MapNode n2 = getNodeNoEx(p2, &is_valid_position); - if(is_valid_position - && (ndef->get(n2).isLiquid() || n2.getContent() == CONTENT_AIR)) - { + if(is_valid_position && + (m_nodedef->get(n2).isLiquid() || + n2.getContent() == CONTENT_AIR)) m_transforming_liquid.push_back(p2); - } } } @@ -1213,9 +1205,6 @@ s32 Map::transforming_liquid_size() { void Map::transformLiquids(std::map &modified_blocks) { - - INodeDefManager *nodemgr = m_gamedef->ndef(); - DSTACK(FUNCTION_NAME); //TimeTaker timer("transformLiquids()"); @@ -1275,12 +1264,12 @@ void Map::transformLiquids(std::map &modified_blocks) // The node which will be placed there if liquid // can't flow into this node. content_t floodable_node = CONTENT_AIR; - const ContentFeatures &cf = nodemgr->get(n0); + const ContentFeatures &cf = m_nodedef->get(n0); LiquidType liquid_type = cf.liquid_type; switch (liquid_type) { case LIQUID_SOURCE: liquid_level = LIQUID_LEVEL_SOURCE; - liquid_kind = nodemgr->getId(cf.liquid_alternative_flowing); + liquid_kind = m_nodedef->getId(cf.liquid_alternative_flowing); break; case LIQUID_FLOWING: liquid_level = (n0.param2 & LIQUID_LEVEL_MASK); @@ -1322,8 +1311,8 @@ void Map::transformLiquids(std::map &modified_blocks) } v3s16 npos = p0 + dirs[i]; NodeNeighbor nb(getNodeNoEx(npos), nt, npos); - const ContentFeatures &cfnb = nodemgr->get(nb.n); - switch (nodemgr->get(nb.n.getContent()).liquid_type) { + const ContentFeatures &cfnb = m_nodedef->get(nb.n); + switch (m_nodedef->get(nb.n.getContent()).liquid_type) { case LIQUID_NONE: if (cfnb.floodable) { airs[num_airs++] = nb; @@ -1351,8 +1340,8 @@ void Map::transformLiquids(std::map &modified_blocks) case LIQUID_SOURCE: // if this node is not (yet) of a liquid type, choose the first liquid type we encounter if (liquid_kind == CONTENT_AIR) - liquid_kind = nodemgr->getId(cfnb.liquid_alternative_flowing); - if (nodemgr->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { + liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing); + if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { neutrals[num_neutrals++] = nb; } else { // Do not count bottom source, it will screw things up @@ -1363,8 +1352,8 @@ void Map::transformLiquids(std::map &modified_blocks) case LIQUID_FLOWING: // if this node is not (yet) of a liquid type, choose the first liquid type we encounter if (liquid_kind == CONTENT_AIR) - liquid_kind = nodemgr->getId(cfnb.liquid_alternative_flowing); - if (nodemgr->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { + liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing); + if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) { neutrals[num_neutrals++] = nb; } else { flows[num_flows++] = nb; @@ -1382,15 +1371,15 @@ void Map::transformLiquids(std::map &modified_blocks) s8 new_node_level = -1; s8 max_node_level = -1; - u8 range = nodemgr->get(liquid_kind).liquid_range; + u8 range = m_nodedef->get(liquid_kind).liquid_range; if (range > LIQUID_LEVEL_MAX + 1) range = LIQUID_LEVEL_MAX + 1; - if ((num_sources >= 2 && nodemgr->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) { + if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) { // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid) // or the flowing alternative of the first of the surrounding sources (if it's air), so // it's perfectly safe to use liquid_kind here to determine the new node content. - new_node_content = nodemgr->getId(nodemgr->get(liquid_kind).liquid_alternative_source); + new_node_content = m_nodedef->getId(m_nodedef->get(liquid_kind).liquid_alternative_source); } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) { // liquid_kind is set properly, see above max_node_level = new_node_level = LIQUID_LEVEL_MAX; @@ -1427,7 +1416,7 @@ void Map::transformLiquids(std::map &modified_blocks) } } - u8 viscosity = nodemgr->get(liquid_kind).liquid_viscosity; + u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity; if (viscosity > 1 && max_node_level != liquid_level) { // amount to gain, limited by viscosity // must be at least 1 in absolute value @@ -1455,7 +1444,7 @@ void Map::transformLiquids(std::map &modified_blocks) check if anything has changed. if not, just continue with the next node. */ if (new_node_content == n0.getContent() && - (nodemgr->get(n0.getContent()).liquid_type != LIQUID_FLOWING || + (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING || ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK) == flowing_down))) @@ -1467,7 +1456,7 @@ void Map::transformLiquids(std::map &modified_blocks) */ MapNode n00 = n0; //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK)); - if (nodemgr->get(new_node_content).liquid_type == LIQUID_FLOWING) { + if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) { // set level to last 3 bits, flowing down bit to 4th bit n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK); } else { @@ -1477,8 +1466,8 @@ void Map::transformLiquids(std::map &modified_blocks) n0.setContent(new_node_content); // Ignore light (because calling voxalgo::update_lighting_nodes) - n0.setLight(LIGHTBANK_DAY, 0, nodemgr); - n0.setLight(LIGHTBANK_NIGHT, 0, nodemgr); + n0.setLight(LIGHTBANK_DAY, 0, m_nodedef); + n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef); // Find out whether there is a suspect for this action std::string suspect; @@ -1512,7 +1501,7 @@ void Map::transformLiquids(std::map &modified_blocks) /* enqueue neighbors for update if neccessary */ - switch (nodemgr->get(n0.getContent()).liquid_type) { + switch (m_nodedef->get(n0.getContent()).liquid_type) { case LIQUID_SOURCE: case LIQUID_FLOWING: // make sure source flows into all neighboring nodes @@ -1535,7 +1524,7 @@ void Map::transformLiquids(std::map &modified_blocks) for (std::deque::iterator iter = must_reflow.begin(); iter != must_reflow.end(); ++iter) m_transforming_liquid.push_back(*iter); - voxalgo::update_lighting_nodes(this, nodemgr, changed_nodes, modified_blocks); + voxalgo::update_lighting_nodes(this, m_nodedef, changed_nodes, modified_blocks); /* ---------------------------------------------------------------------- @@ -1900,7 +1889,7 @@ bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) data->blockpos_min = bpmin; data->blockpos_max = bpmax; data->blockpos_requested = blockpos; - data->nodedef = m_gamedef->ndef(); + data->nodedef = m_nodedef; /* Create the whole area of this and the neighboring blocks diff --git a/src/map.h b/src/map.h index e8d40e982..19c94ee80 100644 --- a/src/map.h +++ b/src/map.h @@ -193,6 +193,8 @@ public: virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true) { return getBlockNoCreateNoEx(p); } + inline INodeDefManager * getNodeDefManager() { return m_nodedef; } + // Returns InvalidPositionException if not found bool isNodeUnderground(v3s16 p); @@ -346,6 +348,9 @@ protected: // Queued transforming water nodes UniqueQueue m_transforming_liquid; + // This stores the properties of the nodes on the map. + INodeDefManager *m_nodedef; + private: f32 m_transforming_liquid_loop_count_multiplier; u32 m_unprocessed_count; diff --git a/src/mapnode.cpp b/src/mapnode.cpp index 5efebf3d8..f1a7f3e61 100644 --- a/src/mapnode.cpp +++ b/src/mapnode.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapnode.h" #include "porting.h" #include "nodedef.h" +#include "map.h" #include "content_mapnode.h" // For mapnode_translate_*_internal #include "serialization.h" // For ser_ver_supported #include "util/serialize.h" @@ -453,6 +454,51 @@ void transformNodeBox(const MapNode &n, const NodeBox &nodebox, } } +static inline void getNeighborConnectingFace( + v3s16 p, INodeDefManager *nodedef, + Map *map, MapNode n, u8 bitmask, u8 *neighbors) +{ + MapNode n2 = map->getNodeNoEx(p); + if (nodedef->nodeboxConnects(n, n2, bitmask)) + *neighbors |= bitmask; +} + +u8 MapNode::getNeighbors(v3s16 p, Map *map) +{ + INodeDefManager *nodedef=map->getNodeDefManager(); + u8 neighbors = 0; + const ContentFeatures &f = nodedef->get(*this); + // locate possible neighboring nodes to connect to + if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) { + v3s16 p2 = p; + + p2.Y++; + getNeighborConnectingFace(p2, nodedef, map, *this, 1, &neighbors); + + p2 = p; + p2.Y--; + getNeighborConnectingFace(p2, nodedef, map, *this, 2, &neighbors); + + p2 = p; + p2.Z--; + getNeighborConnectingFace(p2, nodedef, map, *this, 4, &neighbors); + + p2 = p; + p2.X--; + getNeighborConnectingFace(p2, nodedef, map, *this, 8, &neighbors); + + p2 = p; + p2.Z++; + getNeighborConnectingFace(p2, nodedef, map, *this, 16, &neighbors); + + p2 = p; + p2.X++; + getNeighborConnectingFace(p2, nodedef, map, *this, 32, &neighbors); + } + + return neighbors; +} + void MapNode::getNodeBoxes(INodeDefManager *nodemgr, std::vector *boxes, u8 neighbors) { const ContentFeatures &f = nodemgr->get(*this); diff --git a/src/mapnode.h b/src/mapnode.h index 0bd61c554..a3c20e8ff 100644 --- a/src/mapnode.h +++ b/src/mapnode.h @@ -28,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include class INodeDefManager; +class Map; /* Naming scheme: @@ -246,6 +247,13 @@ struct MapNode void rotateAlongYAxis(INodeDefManager *nodemgr, Rotation rot); + /*! + * Checks which neighbors does this node connect to. + * + * \param p coordinates of the node + */ + u8 getNeighbors(v3s16 p, Map *map); + /* Gets list of node boxes (used for rendering (NDT_NODEBOX)) */ diff --git a/src/nodedef.cpp b/src/nodedef.cpp index 92cdf738e..dbbdf95d2 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -790,9 +790,18 @@ public: virtual void resetNodeResolveState(); virtual void mapNodeboxConnections(); virtual bool nodeboxConnects(MapNode from, MapNode to, u8 connect_face); + virtual core::aabbox3d getSelectionBoxIntUnion() const + { + return m_selection_box_int_union; + } private: void addNameIdMapping(content_t i, std::string name); + /*! + * Recalculates m_selection_box_int_union based on + * m_selection_box_union. + */ + void fixSelectionBoxIntUnion(); // Features indexed by id std::vector m_content_features; @@ -819,6 +828,14 @@ private: // True when all nodes have been registered bool m_node_registration_complete; + + //! The union of all nodes' selection boxes. + aabb3f m_selection_box_union; + /*! + * The smallest box in node coordinates that + * contains all nodes' selection boxes. + */ + core::aabbox3d m_selection_box_int_union; }; @@ -849,6 +866,8 @@ void CNodeDefManager::clear() m_name_id_mapping_with_aliases.clear(); m_group_to_items.clear(); m_next_id = 0; + m_selection_box_union.reset(0,0,0); + m_selection_box_int_union.reset(0,0,0); resetNodeResolveState(); @@ -1007,6 +1026,123 @@ content_t CNodeDefManager::allocateId() } +/*! + * Returns the smallest box that contains all boxes + * in the vector. Box_union is expanded. + * @param[in] boxes the vector containing the boxes + * @param[in, out] box_union the union of the arguments + */ +void boxVectorUnion(const std::vector &boxes, aabb3f *box_union) +{ + for (std::vector::const_iterator it = boxes.begin(); + it != boxes.end(); ++it) { + box_union->addInternalBox(*it); + } +} + + +/*! + * Returns a box that contains the nodebox in every case. + * The argument node_union is expanded. + * @param[in] nodebox the nodebox to be measured + * @param[in] features used to decide whether the nodebox + * can be rotated + * @param[in, out] box_union the union of the arguments + */ +void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features, + aabb3f *box_union) +{ + switch(nodebox.type) { + case NODEBOX_FIXED: + case NODEBOX_LEVELED: { + // Raw union + aabb3f half_processed(0, 0, 0, 0, 0, 0); + boxVectorUnion(nodebox.fixed, &half_processed); + // Set leveled boxes to maximal + if (nodebox.type == NODEBOX_LEVELED) { + half_processed.MaxEdge.Y = +BS / 2; + } + if (features.param_type_2 == CPT2_FACEDIR) { + // Get maximal coordinate + f32 coords[] = { + fabsf(half_processed.MinEdge.X), + fabsf(half_processed.MinEdge.Y), + fabsf(half_processed.MinEdge.Z), + fabsf(half_processed.MaxEdge.X), + fabsf(half_processed.MaxEdge.Y), + fabsf(half_processed.MaxEdge.Z) }; + f32 max = 0; + for (int i = 0; i < 6; i++) { + if (max < coords[i]) { + max = coords[i]; + } + } + // Add the union of all possible rotated boxes + box_union->addInternalPoint(-max, -max, -max); + box_union->addInternalPoint(+max, +max, +max); + } else { + box_union->addInternalBox(half_processed); + } + break; + } + case NODEBOX_WALLMOUNTED: { + // Add fix boxes + box_union->addInternalBox(nodebox.wall_top); + box_union->addInternalBox(nodebox.wall_bottom); + // Find maximal coordinate in the X-Z plane + f32 coords[] = { + fabsf(nodebox.wall_side.MinEdge.X), + fabsf(nodebox.wall_side.MinEdge.Z), + fabsf(nodebox.wall_side.MaxEdge.X), + fabsf(nodebox.wall_side.MaxEdge.Z) }; + f32 max = 0; + for (int i = 0; i < 4; i++) { + if (max < coords[i]) { + max = coords[i]; + } + } + // Add the union of all possible rotated boxes + box_union->addInternalPoint(-max, nodebox.wall_side.MinEdge.Y, -max); + box_union->addInternalPoint(max, nodebox.wall_side.MaxEdge.Y, max); + break; + } + case NODEBOX_CONNECTED: { + // Add all possible connected boxes + boxVectorUnion(nodebox.fixed, box_union); + boxVectorUnion(nodebox.connect_top, box_union); + boxVectorUnion(nodebox.connect_bottom, box_union); + boxVectorUnion(nodebox.connect_front, box_union); + boxVectorUnion(nodebox.connect_left, box_union); + boxVectorUnion(nodebox.connect_back, box_union); + boxVectorUnion(nodebox.connect_right, box_union); + break; + } + default: { + // NODEBOX_REGULAR + box_union->addInternalPoint(-BS / 2, -BS / 2, -BS / 2); + box_union->addInternalPoint(+BS / 2, +BS / 2, +BS / 2); + } + } +} + + +inline void CNodeDefManager::fixSelectionBoxIntUnion() +{ + m_selection_box_int_union.MinEdge.X = floorf( + m_selection_box_union.MinEdge.X / BS + 0.5f); + m_selection_box_int_union.MinEdge.Y = floorf( + m_selection_box_union.MinEdge.Y / BS + 0.5f); + m_selection_box_int_union.MinEdge.Z = floorf( + m_selection_box_union.MinEdge.Z / BS + 0.5f); + m_selection_box_int_union.MaxEdge.X = ceilf( + m_selection_box_union.MaxEdge.X / BS - 0.5f); + m_selection_box_int_union.MaxEdge.Y = ceilf( + m_selection_box_union.MaxEdge.Y / BS - 0.5f); + m_selection_box_int_union.MaxEdge.Z = ceilf( + m_selection_box_union.MaxEdge.Z / BS - 0.5f); +} + + // IWritableNodeDefManager content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def) { @@ -1037,6 +1173,8 @@ content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &d verbosestream << "NodeDefManager: registering content id \"" << id << "\": name=\"" << def.name << "\""< getSelectionBoxIntUnion() const=0; }; class IWritableNodeDefManager : public INodeDefManager { @@ -406,6 +411,7 @@ public: virtual void runNodeResolveCallbacks()=0; virtual void resetNodeResolveState()=0; virtual void mapNodeboxConnections()=0; + virtual core::aabbox3d getSelectionBoxIntUnion() const=0; }; IWritableNodeDefManager *createNodeDefManager(); diff --git a/src/raycast.cpp b/src/raycast.cpp new file mode 100644 index 000000000..58102c993 --- /dev/null +++ b/src/raycast.cpp @@ -0,0 +1,89 @@ +/* +Minetest +Copyright (C) 2016 juhdanad, Daniel Juhasz + +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 "irr_v3d.h" +#include "irr_aabb3d.h" + +bool boxLineCollision(const aabb3f &box, const v3f &start, + const v3f &dir, v3f *collision_point, v3s16 *collision_normal) { + if (box.isPointInside(start)) { + *collision_point = start; + collision_normal->set(0, 0, 0); + return true; + } + float m = 0; + + // Test X collision + if (dir.X != 0) { + if (dir.X > 0) + m = (box.MinEdge.X - start.X) / dir.X; + else + m = (box.MaxEdge.X - start.X) / dir.X; + + if (m >= 0 && m <= 1) { + *collision_point = start + dir * m; + if ((collision_point->Y >= box.MinEdge.Y) + && (collision_point->Y <= box.MaxEdge.Y) + && (collision_point->Z >= box.MinEdge.Z) + && (collision_point->Z <= box.MaxEdge.Z)) { + collision_normal->set((dir.X > 0) ? -1 : 1, 0, 0); + return true; + } + } + } + + // Test Y collision + if (dir.Y != 0) { + if (dir.Y > 0) + m = (box.MinEdge.Y - start.Y) / dir.Y; + else + m = (box.MaxEdge.Y - start.Y) / dir.Y; + + if (m >= 0 && m <= 1) { + *collision_point = start + dir * m; + if ((collision_point->X >= box.MinEdge.X) + && (collision_point->X <= box.MaxEdge.X) + && (collision_point->Z >= box.MinEdge.Z) + && (collision_point->Z <= box.MaxEdge.Z)) { + collision_normal->set(0, (dir.Y > 0) ? -1 : 1, 0); + return true; + } + } + } + + // Test Z collision + if (dir.Z != 0) { + if (dir.Z > 0) + m = (box.MinEdge.Z - start.Z) / dir.Z; + else + m = (box.MaxEdge.Z - start.Z) / dir.Z; + + if (m >= 0 && m <= 1) { + *collision_point = start + dir * m; + if ((collision_point->X >= box.MinEdge.X) + && (collision_point->X <= box.MaxEdge.X) + && (collision_point->Y >= box.MinEdge.Y) + && (collision_point->Y <= box.MaxEdge.Y)) { + collision_normal->set(0, 0, (dir.Z > 0) ? -1 : 1); + return true; + } + } + } + return false; +} diff --git a/src/raycast.h b/src/raycast.h new file mode 100644 index 000000000..d7ec8c843 --- /dev/null +++ b/src/raycast.h @@ -0,0 +1,38 @@ +/* +Minetest +Copyright (C) 2016 juhdanad, Daniel Juhasz + +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. +*/ + +#ifndef SRC_RAYCAST_H_ +#define SRC_RAYCAST_H_ + + +/*! + * Checks if a line and a box intersects. + * @param[in] box box to test collision + * @param[in] start starting point of the line + * @param[in] dir direction and length of the line + * @param[out] collision_point first point of the collision + * @param[out] collision_normal normal vector at the collision, points + * outwards of the surface. If start is in the box, zero vector. + * @returns true if a collision point was found + */ +bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir, + v3f *collision_point, v3s16 *collision_normal); + + +#endif /* SRC_RAYCAST_H_ */ diff --git a/src/unittest/test_voxelalgorithms.cpp b/src/unittest/test_voxelalgorithms.cpp index 31b9cadd5..fd83844af 100644 --- a/src/unittest/test_voxelalgorithms.cpp +++ b/src/unittest/test_voxelalgorithms.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gamedef.h" #include "voxelalgorithms.h" +#include "util/numeric.h" class TestVoxelAlgorithms : public TestBase { public: @@ -31,6 +32,7 @@ public: void testPropogateSunlight(INodeDefManager *ndef); void testClearLightAndCollectSources(INodeDefManager *ndef); + void testVoxelLineIterator(INodeDefManager *ndef); }; static TestVoxelAlgorithms g_test_instance; @@ -41,6 +43,7 @@ void TestVoxelAlgorithms::runTests(IGameDef *gamedef) TEST(testPropogateSunlight, ndef); TEST(testClearLightAndCollectSources, ndef); + TEST(testVoxelLineIterator, ndef); } //////////////////////////////////////////////////////////////////////////////// @@ -202,3 +205,59 @@ void TestVoxelAlgorithms::testClearLightAndCollectSources(INodeDefManager *ndef) UASSERT(unlight_from.size() == 1); } } + +void TestVoxelAlgorithms::testVoxelLineIterator(INodeDefManager *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 > 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.push_back(core::line3d(-x, -y, -z, x, y, z)); + } + } + } + lines.push_back(core::line3d(0, 0, 0, 0, 0, 0)); + // Test every line + std::vector >::iterator it = lines.begin(); + for (; it < lines.end(); it++) { + core::line3d 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); + } +} diff --git a/src/util/pointedthing.cpp b/src/util/pointedthing.cpp index cd13000b5..ed3d4bb67 100644 --- a/src/util/pointedthing.cpp +++ b/src/util/pointedthing.cpp @@ -27,29 +27,25 @@ PointedThing::PointedThing(): type(POINTEDTHING_NOTHING), node_undersurface(0,0,0), node_abovesurface(0,0,0), + node_real_undersurface(0,0,0), + intersection_point(0,0,0), + intersection_normal(0,0,0), object_id(-1) {} std::string PointedThing::dump() const { std::ostringstream os(std::ios::binary); - if(type == POINTEDTHING_NOTHING) - { + if (type == POINTEDTHING_NOTHING) { os<<"[nothing]"; - } - else if(type == POINTEDTHING_NODE) - { + } else if (type == POINTEDTHING_NODE) { const v3s16 &u = node_undersurface; const v3s16 &a = node_abovesurface; os<<"[node under="< 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; + } + + m_has_next = (m_next_intersection_multi.X <= 1) + || (m_next_intersection_multi.Y <= 1) + || (m_next_intersection_multi.Z <= 1); +} + +void VoxelLineIterator::next() +{ + 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; + } + + m_has_next = (m_next_intersection_multi.X <= 1) + || (m_next_intersection_multi.Y <= 1) + || (m_next_intersection_multi.Z <= 1); +} + } // namespace voxalgo diff --git a/src/voxelalgorithms.h b/src/voxelalgorithms.h index 3632546dd..5eff8f7ac 100644 --- a/src/voxelalgorithms.h +++ b/src/voxelalgorithms.h @@ -73,7 +73,68 @@ void update_lighting_nodes( std::vector > &oldnodes, std::map &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; + /*! + * Each component stores the smallest positive number, by which + * m_next_intersection_multi's components can be increased. + */ + v3f m_intersection_multi_inc; + /*! + * 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; + //! Position of the current node. + v3s16 m_current_node_pos; + //! If true, the next node will intersect the line, too. + bool m_has_next; + + /*! + * 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_has_next; } +}; + } // namespace voxalgo + + #endif -- cgit v1.2.3 From c435eabf3ffb77eab955d5faeb5450da1befc149 Mon Sep 17 00:00:00 2001 From: red-001 Date: Sat, 3 Dec 2016 11:38:07 +0000 Subject: Extend minetest.is_yes() --- src/unittest/test_utilities.cpp | 2 ++ src/util/string.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'src/unittest') diff --git a/src/unittest/test_utilities.cpp b/src/unittest/test_utilities.cpp index d73975b9f..58412dd85 100644 --- a/src/unittest/test_utilities.cpp +++ b/src/unittest/test_utilities.cpp @@ -147,6 +147,8 @@ void TestUtilities::testIsYes() UASSERT(is_yes("0") == false); UASSERT(is_yes("1") == true); UASSERT(is_yes("2") == true); + UASSERT(is_yes("on") == true); + UASSERT(is_yes("off") == false); } diff --git a/src/util/string.h b/src/util/string.h index 572c37150..ba3c09e51 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -272,7 +272,7 @@ 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; + return s2 == "y" || s2 == "yes" || s2 == "true" || s2 == "on" || atoi(s2.c_str()) != 0; } -- cgit v1.2.3 From ce106a4113de048718ab9f396db3d368c35218fc Mon Sep 17 00:00:00 2001 From: sfan5 Date: Sat, 7 Jan 2017 11:05:05 +0100 Subject: Revert "Extend minetest.is_yes()" This reverts commit c435eabf3ffb77eab955d5faeb5450da1befc149. --- src/unittest/test_utilities.cpp | 2 -- src/util/string.h | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) (limited to 'src/unittest') diff --git a/src/unittest/test_utilities.cpp b/src/unittest/test_utilities.cpp index 58412dd85..d73975b9f 100644 --- a/src/unittest/test_utilities.cpp +++ b/src/unittest/test_utilities.cpp @@ -147,8 +147,6 @@ void TestUtilities::testIsYes() UASSERT(is_yes("0") == false); UASSERT(is_yes("1") == true); UASSERT(is_yes("2") == true); - UASSERT(is_yes("on") == true); - UASSERT(is_yes("off") == false); } diff --git a/src/util/string.h b/src/util/string.h index ba3c09e51..572c37150 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -272,7 +272,7 @@ inline bool is_yes(const std::string &str) { std::string s2 = lowercase(trim(str)); - return s2 == "y" || s2 == "yes" || s2 == "true" || s2 == "on" || atoi(s2.c_str()) != 0; + return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0; } -- cgit v1.2.3 From c93f7f5ceaf255bc9314be022b7bebb55b1d0605 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Sat, 28 Jan 2017 17:02:43 -0500 Subject: Fix synchronization issue at thread start If a newly spawned thread called getThreadId or getThreadHandle before the spawning thread finished saving the thread handle, then the handle/id would be used uninitialized. This would cause the threading tests to fail since isCurrentThread would return false, and if Minetest is built with C++11 support the std::thread object pointer would be dereferenced while ininitialized, causing a segmentation fault. This fixes the issue by using a mutex to force the spawned thread to wait for the spawning thread to finish initializing the thread object. An alternative way to handle this would be to also set the thread handle/id in the started thread but this wouldn't work for C++11 builds because there's no way to get the partially constructed object. --- src/threading/mutex.cpp | 9 +++++++++ src/threading/mutex.h | 2 ++ src/threading/thread.cpp | 15 +++++++++++++++ src/threading/thread.h | 1 + src/unittest/test_threading.cpp | 2 -- 5 files changed, 27 insertions(+), 2 deletions(-) (limited to 'src/unittest') diff --git a/src/threading/mutex.cpp b/src/threading/mutex.cpp index 0908b5d37..d864f12c5 100644 --- a/src/threading/mutex.cpp +++ b/src/threading/mutex.cpp @@ -88,6 +88,15 @@ void Mutex::lock() #endif } +bool Mutex::try_lock() +{ +#if USE_WIN_MUTEX + return TryEnterCriticalSection(&mutex) != 0; +#else + return pthread_mutex_trylock(&mutex) == 0; +#endif +} + void Mutex::unlock() { #if USE_WIN_MUTEX diff --git a/src/threading/mutex.h b/src/threading/mutex.h index fb5c029fc..6feb23c25 100644 --- a/src/threading/mutex.h +++ b/src/threading/mutex.h @@ -56,6 +56,8 @@ public: void lock(); void unlock(); + bool try_lock(); + protected: Mutex(bool recursive); void init_mutex(bool recursive); diff --git a/src/threading/thread.cpp b/src/threading/thread.cpp index fbe4ba1f3..4f4c9474a 100644 --- a/src/threading/thread.cpp +++ b/src/threading/thread.cpp @@ -101,6 +101,11 @@ Thread::Thread(const std::string &name) : Thread::~Thread() { kill(); + + // Make sure start finished mutex is unlocked before it's destroyed + m_start_finished_mutex.try_lock(); + m_start_finished_mutex.unlock(); + } @@ -113,6 +118,9 @@ bool Thread::start() m_request_stop = false; + // The mutex may already be locked if the thread is being restarted + m_start_finished_mutex.try_lock(); + #if USE_CPP11_THREADS try { @@ -135,6 +143,9 @@ bool Thread::start() #endif + // Allow spawned thread to continue + m_start_finished_mutex.unlock(); + while (!m_running) sleep_ms(1); @@ -249,6 +260,10 @@ DWORD WINAPI Thread::threadProc(LPVOID param) g_logger.registerThread(thr->m_name); thr->m_running = true; + // Wait for the thread that started this one to finish initializing the + // thread handle so that getThreadId/getThreadHandle will work. + thr->m_start_finished_mutex.lock(); + thr->m_retval = thr->run(); thr->m_running = false; diff --git a/src/threading/thread.h b/src/threading/thread.h index 14a0e13ab..4785d3e03 100644 --- a/src/threading/thread.h +++ b/src/threading/thread.h @@ -153,6 +153,7 @@ private: Atomic m_request_stop; Atomic m_running; Mutex m_mutex; + Mutex m_start_finished_mutex; #if USE_CPP11_THREADS std::thread *m_thread_obj; diff --git a/src/unittest/test_threading.cpp b/src/unittest/test_threading.cpp index cdbf9674e..e1e1d3660 100644 --- a/src/unittest/test_threading.cpp +++ b/src/unittest/test_threading.cpp @@ -39,9 +39,7 @@ static TestThreading g_test_instance; void TestThreading::runTests(IGameDef *gamedef) { -#if !(defined(__MACH__) && defined(__APPLE__)) TEST(testStartStopWait); -#endif TEST(testThreadKill); TEST(testAtomicSemaphoreThread); } -- cgit v1.2.3 From 2efae3ffd720095222c800e016286a45c9fe1e5c Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Sat, 21 Jan 2017 15:02:08 +0100 Subject: [CSM] Client side modding * rename GameScripting to ServerScripting * Make getBuiltinLuaPath static serverside * Add on_shutdown callback * Add on_receiving_chat_message & on_sending_chat_message callbacks * ScriptApiBase: use IGameDef instead of Server This permits to share common attribute between client & server * Enable mod security in client side modding without conditions --- builtin/client/init.lua | 22 +++++++ builtin/client/register.lua | 62 +++++++++++++++++++ builtin/init.lua | 3 + src/client.cpp | 45 +++++++++++--- src/client.h | 10 +++ src/content_abm.cpp | 2 +- src/content_sao.cpp | 2 +- src/emerge.cpp | 2 +- src/environment.cpp | 2 +- src/game.cpp | 2 + src/gamedef.h | 7 ++- src/guiFormSpecMenu.cpp | 2 +- src/inventorymanager.cpp | 2 +- src/network/clientpackethandler.cpp | 6 +- src/network/serverpackethandler.cpp | 2 +- src/script/CMakeLists.txt | 7 ++- src/script/clientscripting.cpp | 54 ++++++++++++++++ src/script/clientscripting.h | 40 ++++++++++++ src/script/cpp_api/CMakeLists.txt | 1 + src/script/cpp_api/s_base.cpp | 21 +++++-- src/script/cpp_api/s_base.h | 14 ++++- src/script/cpp_api/s_client.cpp | 61 ++++++++++++++++++ src/script/cpp_api/s_client.h | 36 +++++++++++ src/script/cpp_api/s_security.cpp | 12 ++-- src/script/lua_api/CMakeLists.txt | 1 + src/script/lua_api/l_client.cpp | 33 ++++++++++ src/script/lua_api/l_client.h | 36 +++++++++++ src/script/lua_api/l_env.cpp | 6 +- src/script/lua_api/l_env.h | 2 +- src/script/lua_api/l_object.cpp | 2 +- src/script/scripting_game.cpp | 119 ------------------------------------ src/script/scripting_game.h | 57 ----------------- src/script/serverscripting.cpp | 119 ++++++++++++++++++++++++++++++++++++ src/script/serverscripting.h | 57 +++++++++++++++++ src/server.cpp | 6 +- src/server.h | 10 +-- src/serverenvironment.cpp | 4 +- src/serverenvironment.h | 8 +-- src/unittest/test.cpp | 9 ++- 39 files changed, 655 insertions(+), 231 deletions(-) create mode 100644 builtin/client/init.lua create mode 100644 builtin/client/register.lua create mode 100644 src/script/clientscripting.cpp create mode 100644 src/script/clientscripting.h create mode 100644 src/script/cpp_api/s_client.cpp create mode 100644 src/script/cpp_api/s_client.h create mode 100644 src/script/lua_api/l_client.cpp create mode 100644 src/script/lua_api/l_client.h delete mode 100644 src/script/scripting_game.cpp delete mode 100644 src/script/scripting_game.h create mode 100644 src/script/serverscripting.cpp create mode 100644 src/script/serverscripting.h (limited to 'src/unittest') diff --git a/builtin/client/init.lua b/builtin/client/init.lua new file mode 100644 index 000000000..d14301ade --- /dev/null +++ b/builtin/client/init.lua @@ -0,0 +1,22 @@ +-- Minetest: builtin/client/init.lua +local scriptpath = core.get_builtin_path()..DIR_DELIM +local clientpath = scriptpath.."client"..DIR_DELIM + +dofile(clientpath .. "register.lua") + +-- This is an example function to ensure it's working properly, should be removed before merge +core.register_on_shutdown(function() + print("shutdown client") +end) + +-- This is an example function to ensure it's working properly, should be removed before merge +core.register_on_receiving_chat_messages(function(message) + print("Received message " .. message) + return false +end) + +-- This is an example function to ensure it's working properly, should be removed before merge +core.register_on_sending_chat_messages(function(message) + print("Sending message " .. message) + return false +end) diff --git a/builtin/client/register.lua b/builtin/client/register.lua new file mode 100644 index 000000000..c793195a1 --- /dev/null +++ b/builtin/client/register.lua @@ -0,0 +1,62 @@ + +core.callback_origins = {} + +function core.run_callbacks(callbacks, mode, ...) + assert(type(callbacks) == "table") + local cb_len = #callbacks + if cb_len == 0 then + if mode == 2 or mode == 3 then + return true + elseif mode == 4 or mode == 5 then + return false + end + end + local ret + for i = 1, cb_len do + local cb_ret = callbacks[i](...) + + if mode == 0 and i == 1 or mode == 1 and i == cb_len then + ret = cb_ret + elseif mode == 2 then + if not cb_ret or i == 1 then + ret = cb_ret + end + elseif mode == 3 then + if cb_ret then + return cb_ret + end + ret = cb_ret + elseif mode == 4 then + if (cb_ret and not ret) or i == 1 then + ret = cb_ret + end + elseif mode == 5 and cb_ret then + return cb_ret + end + end + return ret +end + +-- +-- Callback registration +-- + +local function make_registration() + local t = {} + local registerfunc = function(func) + t[#t + 1] = func + core.callback_origins[func] = { + mod = core.get_current_modname() or "??", + name = debug.getinfo(1, "n").name or "??" + } + --local origin = core.callback_origins[func] + --print(origin.name .. ": " .. origin.mod .. " registering cbk " .. tostring(func)) + end + return t, registerfunc +end + +core.registered_on_shutdown, core.register_on_shutdown = make_registration() +core.registered_on_receiving_chat_messages, core.register_on_receiving_chat_messages = make_registration() +core.registered_on_sending_chat_messages, core.register_on_sending_chat_messages = make_registration() + + diff --git a/builtin/init.lua b/builtin/init.lua index b34ad14a0..590f7fa8c 100644 --- a/builtin/init.lua +++ b/builtin/init.lua @@ -27,6 +27,7 @@ minetest = core -- Load other files local scriptdir = core.get_builtin_path() .. DIR_DELIM local gamepath = scriptdir .. "game" .. DIR_DELIM +local clientpath = scriptdir .. "client" .. DIR_DELIM local commonpath = scriptdir .. "common" .. DIR_DELIM local asyncpath = scriptdir .. "async" .. DIR_DELIM @@ -45,6 +46,8 @@ elseif INIT == "mainmenu" then end elseif INIT == "async" then dofile(asyncpath .. "init.lua") +elseif INIT == "client" then + dofile(clientpath .. "init.lua") else error(("Unrecognized builtin initialization type %s!"):format(tostring(INIT))) end diff --git a/src/client.cpp b/src/client.cpp index 30058a2b0..faf454b35 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -32,28 +32,20 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client.h" #include "network/clientopcodes.h" #include "filesys.h" -#include "porting.h" #include "mapblock_mesh.h" #include "mapblock.h" #include "minimap.h" -#include "settings.h" +#include "mods.h" #include "profiler.h" #include "gettext.h" -#include "log.h" -#include "nodemetadata.h" -#include "itemdef.h" -#include "shader.h" #include "clientmap.h" #include "clientmedia.h" -#include "sound.h" -#include "IMeshCache.h" -#include "config.h" #include "version.h" #include "drawscene.h" #include "database-sqlite3.h" #include "serialization.h" #include "guiscalingfilter.h" -#include "raycast.h" +#include "script/clientscripting.h" extern gui::IGUIEnvironment* guienv; @@ -269,10 +261,36 @@ Client::Client( m_cache_use_tangent_vertices = m_cache_enable_shaders && ( g_settings->getBool("enable_bumpmapping") || g_settings->getBool("enable_parallax_occlusion")); + + m_script = new ClientScripting(this); +} + +void Client::initMods() +{ + std::string script_path = getBuiltinLuaPath() + DIR_DELIM "init.lua"; + + m_script->loadMod(script_path, BUILTIN_MOD_NAME); +} + +const std::string Client::getBuiltinLuaPath() +{ + return porting::path_share + DIR_DELIM + "builtin"; +} + +const std::vector& Client::getMods() const +{ + static std::vector client_modspec_temp; + return client_modspec_temp; +} + +const ModSpec* Client::getModSpec(const std::string &modname) const +{ + return NULL; } void Client::Stop() { + m_script->on_shutdown(); //request all client managed threads to stop m_mesh_update_thread.stop(); // Save local server map @@ -280,6 +298,8 @@ void Client::Stop() infostream << "Local map saving ended." << std::endl; m_localdb->endSave(); } + + delete m_script; } bool Client::isShutdown() @@ -1553,6 +1573,11 @@ void Client::typeChatMessage(const std::wstring &message) if(message == L"") return; + // If message was ate by script API, don't send it to server + if (m_script->on_sending_message(wide_to_utf8(message))) { + return; + } + // Send to others sendChatMessage(message); diff --git a/src/client.h b/src/client.h index b33358d94..2fdade61a 100644 --- a/src/client.h +++ b/src/client.h @@ -305,6 +305,8 @@ private: std::map m_packets; }; +class ClientScripting; + class Client : public con::PeerHandler, public InventoryManager, public IGameDef { public: @@ -328,6 +330,8 @@ public: ~Client(); + void initMods(); + /* request all threads managed by client to be stopped */ @@ -428,6 +432,10 @@ public: ClientEnvironment& getEnv() { return m_env; } ITextureSource *tsrc() { return getTextureSource(); } ISoundManager *sound() { return getSoundManager(); } + static const std::string getBuiltinLuaPath(); + + virtual const std::vector &getMods() const; + virtual const ModSpec* getModSpec(const std::string &modname) const; // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent) void removeNode(v3s16 p); @@ -692,6 +700,8 @@ private: bool m_cache_enable_shaders; bool m_cache_use_tangent_vertices; + ClientScripting *m_script; + DISABLE_CLASS_COPY(Client); }; diff --git a/src/content_abm.cpp b/src/content_abm.cpp index ee444ae77..2ab3a968c 100644 --- a/src/content_abm.cpp +++ b/src/content_abm.cpp @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "mapblock.h" // For getNodeBlockPos #include "map.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "log.h" void add_legacy_abms(ServerEnvironment *env, INodeDefManager *nodedef) { diff --git a/src/content_sao.cpp b/src/content_sao.cpp index d4a218505..93662b035 100644 --- a/src/content_sao.cpp +++ b/src/content_sao.cpp @@ -26,7 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "remoteplayer.h" #include "server.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "genericobject.h" std::map ServerActiveObject::m_types; diff --git a/src/emerge.cpp b/src/emerge.cpp index 1c9719c48..8719a9eb3 100644 --- a/src/emerge.cpp +++ b/src/emerge.cpp @@ -40,7 +40,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_schematic.h" #include "nodedef.h" #include "profiler.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "server.h" #include "serverobject.h" #include "settings.h" diff --git a/src/environment.cpp b/src/environment.cpp index 8c1aad9d3..737d93ecd 100644 --- a/src/environment.cpp +++ b/src/environment.cpp @@ -21,7 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "environment.h" #include "collision.h" #include "serverobject.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "server.h" #include "daynightratio.h" #include "emerge.h" diff --git a/src/game.cpp b/src/game.cpp index 55b2ccec9..9868142f7 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -2222,6 +2222,8 @@ bool Game::connectToServer(const std::string &playername, fps_control.last_time = device->getTimer()->getTime(); + client->initMods(); + while (device->run()) { limitFps(&fps_control, &dtime); diff --git a/src/gamedef.h b/src/gamedef.h index cb624bd6a..16b53e24f 100644 --- a/src/gamedef.h +++ b/src/gamedef.h @@ -39,6 +39,7 @@ namespace irr { namespace scene { class ISceneManager; }} +struct ModSpec; /* An interface for fetching game-global definitions like tool and mapnode properties @@ -68,7 +69,11 @@ public: ICraftDefManager *cdef() { return getCraftDefManager(); } MtEventManager *event() { return getEventManager(); } - IRollbackManager *rollback() { return getRollbackManager();} + IRollbackManager *rollback() { return getRollbackManager(); } + + virtual const std::vector &getMods() const = 0; + virtual const ModSpec* getModSpec(const std::string &modname) const = 0; + virtual std::string getWorldPath() const { return ""; } }; #endif diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index ae3fad7c6..19cac6241 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -42,7 +42,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "filesys.h" #include "gettime.h" #include "gettext.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "porting.h" #include "settings.h" #include "client.h" diff --git a/src/inventorymanager.cpp b/src/inventorymanager.cpp index 469e7396b..6ebc2994b 100644 --- a/src/inventorymanager.cpp +++ b/src/inventorymanager.cpp @@ -20,7 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "log.h" #include "serverenvironment.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "serverobject.h" #include "settings.h" #include "craftdef.h" diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index b11f73e86..f1c44c7d8 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "util/strfnd.h" #include "network/clientopcodes.h" +#include "script/clientscripting.h" #include "util/serialize.h" #include "util/srp.h" #include "tileanimation.h" @@ -411,7 +412,10 @@ void Client::handleCommand_ChatMessage(NetworkPacket* pkt) message += (wchar_t)read_wchar; } - m_chat_queue.push(message); + // If chat message not consummed by client lua API + if (!m_script->on_receiving_message(wide_to_utf8(message))) { + m_chat_queue.push(message); + } } void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt) diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index ac428e8ed..b707c6fad 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -27,7 +27,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "player.h" #include "rollback_interface.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "settings.h" #include "tool.h" #include "version.h" diff --git a/src/script/CMakeLists.txt b/src/script/CMakeLists.txt index 5ef672ca9..c96ccc816 100644 --- a/src/script/CMakeLists.txt +++ b/src/script/CMakeLists.txt @@ -3,16 +3,17 @@ add_subdirectory(cpp_api) add_subdirectory(lua_api) # Used by server and client -set(common_SCRIPT_SRCS - ${CMAKE_CURRENT_SOURCE_DIR}/scripting_game.cpp +set(common_SCRIPT_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/serverscripting.cpp ${common_SCRIPT_COMMON_SRCS} ${common_SCRIPT_CPP_API_SRCS} ${common_SCRIPT_LUA_API_SRCS} PARENT_SCOPE) # Used by client only -set(client_SCRIPT_SRCS +set(client_SCRIPT_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/scripting_mainmenu.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/clientscripting.cpp ${client_SCRIPT_COMMON_SRCS} ${client_SCRIPT_CPP_API_SRCS} ${client_SCRIPT_LUA_API_SRCS} diff --git a/src/script/clientscripting.cpp b/src/script/clientscripting.cpp new file mode 100644 index 000000000..43bc6f94e --- /dev/null +++ b/src/script/clientscripting.cpp @@ -0,0 +1,54 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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 "clientscripting.h" +#include "client.h" +#include "cpp_api/s_internal.h" +#include "lua_api/l_client.h" +#include "lua_api/l_util.h" + +ClientScripting::ClientScripting(Client *client): + ScriptApiBase() +{ + setGameDef(client); + + SCRIPTAPI_PRECHECKHEADER + + // Security is mandatory client side + initializeSecurity(); + + lua_getglobal(L, "core"); + int top = lua_gettop(L); + + InitializeModApi(L, top); + lua_pop(L, 1); + + // Push builtin initialization type + lua_pushstring(L, "client"); + lua_setglobal(L, "INIT"); + + infostream << "SCRIPTAPI: Initialized client game modules" << std::endl; +} + +void ClientScripting::InitializeModApi(lua_State *L, int top) +{ + ModApiUtil::Initialize(L, top); + ModApiClient::Initialize(L, top); +} diff --git a/src/script/clientscripting.h b/src/script/clientscripting.h new file mode 100644 index 000000000..e2a91f695 --- /dev/null +++ b/src/script/clientscripting.h @@ -0,0 +1,40 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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. +*/ + +#ifndef CLIENT_SCRIPTING_H_ +#define CLIENT_SCRIPTING_H_ + +#include "cpp_api/s_base.h" +#include "cpp_api/s_client.h" +#include "cpp_api/s_security.h" + +class Client; +class ClientScripting: + virtual public ScriptApiBase, + public ScriptApiSecurity, + public ScriptApiClient +{ +public: + ClientScripting(Client *client); + +private: + virtual void InitializeModApi(lua_State *L, int top); +}; +#endif diff --git a/src/script/cpp_api/CMakeLists.txt b/src/script/cpp_api/CMakeLists.txt index be4d0131e..4b13356a8 100644 --- a/src/script/cpp_api/CMakeLists.txt +++ b/src/script/cpp_api/CMakeLists.txt @@ -13,6 +13,7 @@ set(common_SCRIPT_CPP_API_SRCS PARENT_SCOPE) set(client_SCRIPT_CPP_API_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/s_client.cpp ${CMAKE_CURRENT_SOURCE_DIR}/s_mainmenu.cpp PARENT_SCOPE) diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index cbe5735a7..6a843810f 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -23,12 +23,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_object.h" #include "common/c_converter.h" #include "serverobject.h" -#include "debug.h" #include "filesys.h" -#include "log.h" #include "mods.h" #include "porting.h" #include "util/string.h" +#include "server.h" +#ifndef SERVER +#include "client.h" +#endif extern "C" { @@ -69,7 +71,8 @@ public: */ ScriptApiBase::ScriptApiBase() : - m_luastackmutex() + m_luastackmutex(), + m_gamedef(NULL) { #ifdef SCRIPTAPI_LOCK_DEBUG m_lock_recursion_count = 0; @@ -113,7 +116,6 @@ ScriptApiBase::ScriptApiBase() : // Default to false otherwise m_secure = false; - m_server = NULL; m_environment = NULL; m_guiengine = NULL; } @@ -333,3 +335,14 @@ void ScriptApiBase::objectrefGet(lua_State *L, u16 id) lua_remove(L, -2); // object_refs lua_remove(L, -2); // core } + +Server* ScriptApiBase::getServer() +{ + return dynamic_cast(m_gamedef); +} +#ifndef SERVER +Client* ScriptApiBase::getClient() +{ + return dynamic_cast(m_gamedef); +} +#endif diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index c27235255..19d71df65 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -55,6 +55,10 @@ extern "C" { setOriginFromTableRaw(index, __FUNCTION__) class Server; +#ifndef SERVER +class Client; +#endif +class IGameDef; class Environment; class GUIEngine; class ServerActiveObject; @@ -75,7 +79,11 @@ public: void addObjectReference(ServerActiveObject *cobj); void removeObjectReference(ServerActiveObject *cobj); - Server* getServer() { return m_server; } + IGameDef *getGameDef() { return m_gamedef; } + Server* getServer(); +#ifndef SERVER + Client* getClient(); +#endif std::string getOrigin() { return m_last_run_mod; } void setOriginDirect(const char *origin); @@ -98,7 +106,7 @@ protected: void scriptError(int result, const char *fxn); void stackDump(std::ostream &o); - void setServer(Server* server) { m_server = server; } + void setGameDef(IGameDef* gamedef) { m_gamedef = gamedef; } Environment* getEnv() { return m_environment; } void setEnv(Environment* env) { m_environment = env; } @@ -122,7 +130,7 @@ private: lua_State* m_luastack; - Server* m_server; + IGameDef* m_gamedef; Environment* m_environment; GUIEngine* m_guiengine; }; diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp new file mode 100644 index 000000000..08af8ebdc --- /dev/null +++ b/src/script/cpp_api/s_client.cpp @@ -0,0 +1,61 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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 "s_client.h" +#include "s_internal.h" + +void ScriptApiClient::on_shutdown() +{ + SCRIPTAPI_PRECHECKHEADER + + // Get registered shutdown hooks + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_shutdown"); + // Call callbacks + runCallbacks(0, RUN_CALLBACKS_MODE_FIRST); +} + +bool ScriptApiClient::on_sending_message(const std::string &message) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_chat_messages + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_sending_chat_messages"); + // Call callbacks + lua_pushstring(L, message.c_str()); + runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC); + bool ate = lua_toboolean(L, -1); + return ate; +} + +bool ScriptApiClient::on_receiving_message(const std::string &message) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_chat_messages + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_receiving_chat_messages"); + // Call callbacks + lua_pushstring(L, message.c_str()); + runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC); + bool ate = lua_toboolean(L, -1); + return ate; +} diff --git a/src/script/cpp_api/s_client.h b/src/script/cpp_api/s_client.h new file mode 100644 index 000000000..08fdd8fc0 --- /dev/null +++ b/src/script/cpp_api/s_client.h @@ -0,0 +1,36 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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. +*/ + +#ifndef S_CLIENT_H_ +#define S_CLIENT_H_ + +#include "cpp_api/s_base.h" + +class ScriptApiClient: virtual public ScriptApiBase +{ +public: + // Calls on_shutdown handlers + void on_shutdown(); + + // Chat message handlers + bool on_sending_message(const std::string &message); + bool on_receiving_message(const std::string &message); +}; +#endif diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index be2b884cc..f85cd0c9c 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -382,9 +382,9 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1); lua_pop(L, 1); - const Server *server = script->getServer(); - - if (!server) return false; + const IGameDef *gamedef = script->getGameDef(); + if (!gamedef) + return false; // Get mod name lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); @@ -400,7 +400,7 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, // Allow paths in mod path // Don't bother if write access isn't important, since it will be handled later if (write_required || write_allowed != NULL) { - const ModSpec *mod = server->getModSpec(mod_name); + const ModSpec *mod = gamedef->getModSpec(mod_name); if (mod) { str = fs::AbsolutePath(mod->path); if (!str.empty() && fs::PathStartsWith(abs_path, str)) { @@ -414,7 +414,7 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, // Allow read-only access to all mod directories if (!write_required) { - const std::vector mods = server->getMods(); + const std::vector mods = gamedef->getMods(); for (size_t i = 0; i < mods.size(); ++i) { str = fs::AbsolutePath(mods[i].path); if (!str.empty() && fs::PathStartsWith(abs_path, str)) { @@ -423,7 +423,7 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, } } - str = fs::AbsolutePath(server->getWorldPath()); + str = fs::AbsolutePath(gamedef->getWorldPath()); if (!str.empty()) { // Don't allow access to other paths in the world mod/game path. // These have to be blocked so you can't override a trusted mod diff --git a/src/script/lua_api/CMakeLists.txt b/src/script/lua_api/CMakeLists.txt index e82560696..ea3d75ffa 100644 --- a/src/script/lua_api/CMakeLists.txt +++ b/src/script/lua_api/CMakeLists.txt @@ -23,5 +23,6 @@ set(common_SCRIPT_LUA_API_SRCS PARENT_SCOPE) set(client_SCRIPT_LUA_API_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/l_client.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_mainmenu.cpp PARENT_SCOPE) diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp new file mode 100644 index 000000000..9c478602a --- /dev/null +++ b/src/script/lua_api/l_client.cpp @@ -0,0 +1,33 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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 "l_client.h" +#include "l_internal.h" + +int ModApiClient::l_get_current_modname(lua_State *L) +{ + lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); + return 1; +} + +void ModApiClient::Initialize(lua_State *L, int top) +{ + API_FCT(get_current_modname); +} diff --git a/src/script/lua_api/l_client.h b/src/script/lua_api/l_client.h new file mode 100644 index 000000000..332f00132 --- /dev/null +++ b/src/script/lua_api/l_client.h @@ -0,0 +1,36 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola +Copyright (C) 2017 nerzhul, Loic Blot + +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. +*/ + +#ifndef L_CLIENT_H_ +#define L_CLIENT_H_ + +#include "lua_api/l_base.h" + +class ModApiClient : public ModApiBase +{ +private: + // get_current_modname() + static int l_get_current_modname(lua_State *L); + +public: + static void Initialize(lua_State *L, int top); +}; + +#endif diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 2722e35a4..442c4b99a 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_vmanip.h" #include "common/c_converter.h" #include "common/c_content.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "environment.h" #include "server.h" #include "nodedef.h" @@ -49,7 +49,7 @@ struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider) { - GameScripting *scriptIface = env->getScriptIface(); + ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); lua_State *L = scriptIface->getStack(); @@ -92,7 +92,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n) { - GameScripting *scriptIface = env->getScriptIface(); + ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); lua_State *L = scriptIface->getStack(); diff --git a/src/script/lua_api/l_env.h b/src/script/lua_api/l_env.h index 21b235f84..322959411 100644 --- a/src/script/lua_api/l_env.h +++ b/src/script/lua_api/l_env.h @@ -242,7 +242,7 @@ public: }; struct ScriptCallbackState { - GameScripting *script; + ServerScripting *script; int callback_ref; int args_ref; unsigned int refcount; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 9352812ab..be454ad45 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -29,7 +29,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "content_sao.h" #include "server.h" #include "hud.h" -#include "scripting_game.h" +#include "serverscripting.h" struct EnumString es_HudElementType[] = { diff --git a/src/script/scripting_game.cpp b/src/script/scripting_game.cpp deleted file mode 100644 index 4da752263..000000000 --- a/src/script/scripting_game.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -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 "scripting_game.h" -#include "server.h" -#include "log.h" -#include "settings.h" -#include "cpp_api/s_internal.h" -#include "lua_api/l_areastore.h" -#include "lua_api/l_base.h" -#include "lua_api/l_craft.h" -#include "lua_api/l_env.h" -#include "lua_api/l_inventory.h" -#include "lua_api/l_item.h" -#include "lua_api/l_itemstackmeta.h" -#include "lua_api/l_mapgen.h" -#include "lua_api/l_nodemeta.h" -#include "lua_api/l_nodetimer.h" -#include "lua_api/l_noise.h" -#include "lua_api/l_object.h" -#include "lua_api/l_particles.h" -#include "lua_api/l_rollback.h" -#include "lua_api/l_server.h" -#include "lua_api/l_util.h" -#include "lua_api/l_vmanip.h" -#include "lua_api/l_settings.h" -#include "lua_api/l_http.h" -#include "lua_api/l_storage.h" - -extern "C" { -#include "lualib.h" -} - -GameScripting::GameScripting(Server* server) -{ - setServer(server); - - // setEnv(env) is called by ScriptApiEnv::initializeEnvironment() - // once the environment has been created - - SCRIPTAPI_PRECHECKHEADER - - if (g_settings->getBool("secure.enable_security")) { - initializeSecurity(); - } - - lua_getglobal(L, "core"); - int top = lua_gettop(L); - - lua_newtable(L); - lua_setfield(L, -2, "object_refs"); - - lua_newtable(L); - lua_setfield(L, -2, "luaentities"); - - // Initialize our lua_api modules - InitializeModApi(L, top); - lua_pop(L, 1); - - // Push builtin initialization type - lua_pushstring(L, "game"); - lua_setglobal(L, "INIT"); - - infostream << "SCRIPTAPI: Initialized game modules" << std::endl; -} - -void GameScripting::InitializeModApi(lua_State *L, int top) -{ - // Initialize mod api modules - ModApiCraft::Initialize(L, top); - ModApiEnvMod::Initialize(L, top); - ModApiInventory::Initialize(L, top); - ModApiItemMod::Initialize(L, top); - ModApiMapgen::Initialize(L, top); - ModApiParticles::Initialize(L, top); - ModApiRollback::Initialize(L, top); - ModApiServer::Initialize(L, top); - ModApiUtil::Initialize(L, top); - ModApiHttp::Initialize(L, top); - ModApiStorage::Initialize(L, top); - - // Register reference classes (userdata) - InvRef::Register(L); - ItemStackMetaRef::Register(L); - LuaAreaStore::Register(L); - LuaItemStack::Register(L); - LuaPerlinNoise::Register(L); - LuaPerlinNoiseMap::Register(L); - LuaPseudoRandom::Register(L); - LuaPcgRandom::Register(L); - LuaSecureRandom::Register(L); - LuaVoxelManip::Register(L); - NodeMetaRef::Register(L); - NodeTimerRef::Register(L); - ObjectRef::Register(L); - LuaSettings::Register(L); - StorageRef::Register(L); -} - -void log_deprecated(const std::string &message) -{ - log_deprecated(NULL, message); -} diff --git a/src/script/scripting_game.h b/src/script/scripting_game.h deleted file mode 100644 index 970b3e80d..000000000 --- a/src/script/scripting_game.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -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. -*/ - -#ifndef SCRIPTING_GAME_H_ -#define SCRIPTING_GAME_H_ - -#include "cpp_api/s_base.h" -#include "cpp_api/s_entity.h" -#include "cpp_api/s_env.h" -#include "cpp_api/s_inventory.h" -#include "cpp_api/s_node.h" -#include "cpp_api/s_player.h" -#include "cpp_api/s_server.h" -#include "cpp_api/s_security.h" - -/*****************************************************************************/ -/* Scripting <-> Game Interface */ -/*****************************************************************************/ - -class GameScripting : - virtual public ScriptApiBase, - public ScriptApiDetached, - public ScriptApiEntity, - public ScriptApiEnv, - public ScriptApiNode, - public ScriptApiPlayer, - public ScriptApiServer, - public ScriptApiSecurity -{ -public: - GameScripting(Server* server); - - // use ScriptApiBase::loadMod() to load mods - -private: - void InitializeModApi(lua_State *L, int top); -}; - -void log_deprecated(const std::string &message); - -#endif /* SCRIPTING_GAME_H_ */ diff --git a/src/script/serverscripting.cpp b/src/script/serverscripting.cpp new file mode 100644 index 000000000..215b2cfd7 --- /dev/null +++ b/src/script/serverscripting.cpp @@ -0,0 +1,119 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +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 "serverscripting.h" +#include "server.h" +#include "log.h" +#include "settings.h" +#include "cpp_api/s_internal.h" +#include "lua_api/l_areastore.h" +#include "lua_api/l_base.h" +#include "lua_api/l_craft.h" +#include "lua_api/l_env.h" +#include "lua_api/l_inventory.h" +#include "lua_api/l_item.h" +#include "lua_api/l_itemstackmeta.h" +#include "lua_api/l_mapgen.h" +#include "lua_api/l_nodemeta.h" +#include "lua_api/l_nodetimer.h" +#include "lua_api/l_noise.h" +#include "lua_api/l_object.h" +#include "lua_api/l_particles.h" +#include "lua_api/l_rollback.h" +#include "lua_api/l_server.h" +#include "lua_api/l_util.h" +#include "lua_api/l_vmanip.h" +#include "lua_api/l_settings.h" +#include "lua_api/l_http.h" +#include "lua_api/l_storage.h" + +extern "C" { +#include "lualib.h" +} + +ServerScripting::ServerScripting(Server* server) +{ + setGameDef(server); + + // setEnv(env) is called by ScriptApiEnv::initializeEnvironment() + // once the environment has been created + + SCRIPTAPI_PRECHECKHEADER + + if (g_settings->getBool("secure.enable_security")) { + initializeSecurity(); + } + + lua_getglobal(L, "core"); + int top = lua_gettop(L); + + lua_newtable(L); + lua_setfield(L, -2, "object_refs"); + + lua_newtable(L); + lua_setfield(L, -2, "luaentities"); + + // Initialize our lua_api modules + InitializeModApi(L, top); + lua_pop(L, 1); + + // Push builtin initialization type + lua_pushstring(L, "game"); + lua_setglobal(L, "INIT"); + + infostream << "SCRIPTAPI: Initialized game modules" << std::endl; +} + +void ServerScripting::InitializeModApi(lua_State *L, int top) +{ + // Initialize mod api modules + ModApiCraft::Initialize(L, top); + ModApiEnvMod::Initialize(L, top); + ModApiInventory::Initialize(L, top); + ModApiItemMod::Initialize(L, top); + ModApiMapgen::Initialize(L, top); + ModApiParticles::Initialize(L, top); + ModApiRollback::Initialize(L, top); + ModApiServer::Initialize(L, top); + ModApiUtil::Initialize(L, top); + ModApiHttp::Initialize(L, top); + ModApiStorage::Initialize(L, top); + + // Register reference classes (userdata) + InvRef::Register(L); + ItemStackMetaRef::Register(L); + LuaAreaStore::Register(L); + LuaItemStack::Register(L); + LuaPerlinNoise::Register(L); + LuaPerlinNoiseMap::Register(L); + LuaPseudoRandom::Register(L); + LuaPcgRandom::Register(L); + LuaSecureRandom::Register(L); + LuaVoxelManip::Register(L); + NodeMetaRef::Register(L); + NodeTimerRef::Register(L); + ObjectRef::Register(L); + LuaSettings::Register(L); + StorageRef::Register(L); +} + +void log_deprecated(const std::string &message) +{ + log_deprecated(NULL, message); +} diff --git a/src/script/serverscripting.h b/src/script/serverscripting.h new file mode 100644 index 000000000..fd97ea40b --- /dev/null +++ b/src/script/serverscripting.h @@ -0,0 +1,57 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +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. +*/ + +#ifndef SERVER_SCRIPTING_H_ +#define SERVER_SCRIPTING_H_ + +#include "cpp_api/s_base.h" +#include "cpp_api/s_entity.h" +#include "cpp_api/s_env.h" +#include "cpp_api/s_inventory.h" +#include "cpp_api/s_node.h" +#include "cpp_api/s_player.h" +#include "cpp_api/s_server.h" +#include "cpp_api/s_security.h" + +/*****************************************************************************/ +/* Scripting <-> Server Game Interface */ +/*****************************************************************************/ + +class ServerScripting: + virtual public ScriptApiBase, + public ScriptApiDetached, + public ScriptApiEntity, + public ScriptApiEnv, + public ScriptApiNode, + public ScriptApiPlayer, + public ScriptApiServer, + public ScriptApiSecurity +{ +public: + ServerScripting(Server* server); + + // use ScriptApiBase::loadMod() to load mods + +private: + void InitializeModApi(lua_State *L, int top); +}; + +void log_deprecated(const std::string &message); + +#endif /* SCRIPTING_GAME_H_ */ diff --git a/src/server.cpp b/src/server.cpp index 8b9f46f85..3adbf40cc 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -38,7 +38,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "profiler.h" #include "log.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "nodedef.h" #include "itemdef.h" #include "craftdef.h" @@ -269,7 +269,7 @@ Server::Server( // Initialize scripting infostream<<"Server: Initializing Lua"< &modlist) modlist.push_back(it->name); } -std::string Server::getBuiltinLuaPath() +const std::string Server::getBuiltinLuaPath() { return porting::path_share + DIR_DELIM + "builtin"; } diff --git a/src/server.h b/src/server.h index 3eee67b78..417d31bd8 100644 --- a/src/server.h +++ b/src/server.h @@ -53,7 +53,7 @@ class PlayerSAO; class IRollbackManager; struct RollbackAction; class EmergeManager; -class GameScripting; +class ServerScripting; class ServerEnvironment; struct SimpleSoundSpec; class ServerThread; @@ -274,7 +274,7 @@ public: Inventory* createDetachedInventory(const std::string &name, const std::string &player=""); // Envlock and conlock should be locked when using scriptapi - GameScripting *getScriptIface(){ return m_script; } + ServerScripting *getScriptIface(){ return m_script; } // actions: time-reversed list // Return value: success/failure @@ -295,8 +295,8 @@ public: IWritableNodeDefManager* getWritableNodeDefManager(); IWritableCraftDefManager* getWritableCraftDefManager(); - const std::vector &getMods() const { return m_mods; } - const ModSpec* getModSpec(const std::string &modname) const; + virtual const std::vector &getMods() const { return m_mods; } + virtual const ModSpec* getModSpec(const std::string &modname) const; void getModNames(std::vector &modlist); std::string getBuiltinLuaPath(); inline const std::string &getWorldPath() const { return m_path_world; } @@ -540,7 +540,7 @@ private: // Scripting // Envlock and conlock should be locked when using Lua - GameScripting *m_script; + ServerScripting *m_script; // Item definition manager IWritableItemDefManager *m_itemdef; diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index f3f489092..ecc7c3150 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "profiler.h" #include "raycast.h" #include "remoteplayer.h" -#include "scripting_game.h" +#include "serverscripting.h" #include "server.h" #include "voxelalgorithms.h" #include "util/serialize.h" @@ -352,7 +352,7 @@ void ActiveBlockList::update(std::vector &active_positions, */ ServerEnvironment::ServerEnvironment(ServerMap *map, - GameScripting *scriptIface, Server *server, + ServerScripting *scriptIface, Server *server, const std::string &path_world) : m_map(map), m_script(scriptIface), diff --git a/src/serverenvironment.h b/src/serverenvironment.h index b7056c00c..b7796b5f1 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -33,7 +33,7 @@ class ServerEnvironment; class ActiveBlockModifier; class ServerActiveObject; class Server; -class GameScripting; +class ServerScripting; /* {Active, Loading} block modifier interface. @@ -194,7 +194,7 @@ typedef UNORDERED_MAP ActiveObjectMap; class ServerEnvironment : public Environment { public: - ServerEnvironment(ServerMap *map, GameScripting *scriptIface, + ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, Server *server, const std::string &path_world); ~ServerEnvironment(); @@ -203,7 +203,7 @@ public: ServerMap & getServerMap(); //TODO find way to remove this fct! - GameScripting* getScriptIface() + ServerScripting* getScriptIface() { return m_script; } Server *getGameDef() @@ -381,7 +381,7 @@ private: // The map ServerMap *m_map; // Lua state - GameScripting* m_script; + ServerScripting* m_script; // Server definition Server *m_server; // World path diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 41ccf0d2d..9beb0afa6 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -19,10 +19,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "test.h" -#include "log.h" #include "nodedef.h" #include "itemdef.h" #include "gamedef.h" +#include "mods.h" content_t t_CONTENT_STONE; content_t t_CONTENT_GRASS; @@ -59,6 +59,13 @@ public: void defineSomeNodes(); + virtual const std::vector &getMods() const + { + static std::vector testmodspec; + return testmodspec; + } + virtual const ModSpec* getModSpec(const std::string &modname) const { return NULL; } + private: IItemDefManager *m_itemdef; INodeDefManager *m_nodedef; -- cgit v1.2.3 From eb88e5dd4b181a90b382c036cf6c4f42e63e8cc2 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Thu, 16 Mar 2017 07:53:39 +0100 Subject: Add ModStorageAPI to client side modding (#5396) mod storage is located into user_path / client / mod_storage --- clientmods/preview/init.lua | 3 +++ src/client.cpp | 43 +++++++++++++++++++++++++++++++++++++++- src/client.h | 6 ++++++ src/gamedef.h | 4 ++++ src/script/clientscripting.cpp | 1 + src/script/lua_api/l_storage.cpp | 11 +++++----- src/server.h | 8 ++++---- src/unittest/test.cpp | 3 +++ 8 files changed, 68 insertions(+), 11 deletions(-) (limited to 'src/unittest') diff --git a/clientmods/preview/init.lua b/clientmods/preview/init.lua index 2ca4594d3..60dccf304 100644 --- a/clientmods/preview/init.lua +++ b/clientmods/preview/init.lua @@ -1,4 +1,5 @@ local modname = core.get_current_modname() or "??" +local modstorage = core.get_mod_storage() -- This is an example function to ensure it's working properly, should be removed before merge core.register_on_shutdown(function() @@ -49,6 +50,8 @@ core.register_chatcommand("test_node", { core.after(2, function() print("[PREVIEW] loaded " .. modname .. " mod") + modstorage:set_string("current_mod", modname) + print(modstorage:get_string("current_mod")) end) core.register_on_dignode(function(pos, node) diff --git a/src/client.cpp b/src/client.cpp index 4ddabd814..567ee6dd7 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -249,7 +249,8 @@ Client::Client( m_removed_sounds_check_timer(0), m_state(LC_Created), m_localdb(NULL), - m_script(NULL) + m_script(NULL), + m_mod_storage_save_timer(10.0f) { // Add local player m_env.setLocalPlayer(new LocalPlayer(this, playername)); @@ -730,6 +731,18 @@ void Client::step(float dtime) } } + m_mod_storage_save_timer -= dtime; + if (m_mod_storage_save_timer <= 0.0f) { + verbosestream << "Saving registered mod storages." << std::endl; + m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval"); + for (UNORDERED_MAP::const_iterator + it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) { + if (it->second->isModified()) { + it->second->save(getModStoragePath()); + } + } + } + // Write server map if (m_localdb && m_localdb_save_interval.step(dtime, m_cache_save_interval)) { @@ -1998,3 +2011,31 @@ scene::IAnimatedMesh* Client::getMesh(const std::string &filename) smgr->getMeshCache()->removeMesh(mesh); return mesh; } + +bool Client::registerModStorage(ModMetadata *storage) +{ + if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) { + errorstream << "Unable to register same mod storage twice. Storage name: " + << storage->getModName() << std::endl; + return false; + } + + m_mod_storages[storage->getModName()] = storage; + return true; +} + +void Client::unregisterModStorage(const std::string &name) +{ + UNORDERED_MAP::const_iterator it = m_mod_storages.find(name); + if (it != m_mod_storages.end()) { + // Save unconditionaly on unregistration + it->second->save(getModStoragePath()); + m_mod_storages.erase(name); + } +} + +std::string Client::getModStoragePath() const +{ + return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage"; +} + diff --git a/src/client.h b/src/client.h index 7f9cc559b..d72249315 100644 --- a/src/client.h +++ b/src/client.h @@ -554,6 +554,10 @@ public: { return checkPrivilege(priv); } virtual scene::IAnimatedMesh* getMesh(const std::string &filename); + virtual std::string getModStoragePath() const; + virtual bool registerModStorage(ModMetadata *meta); + virtual void unregisterModStorage(const std::string &name); + // The following set of functions is used by ClientMediaDownloader // Insert a media file appropriately into the appropriate manager bool loadMedia(const std::string &data, const std::string &filename); @@ -724,6 +728,8 @@ private: ClientScripting *m_script; bool m_modding_enabled; + UNORDERED_MAP m_mod_storages; + float m_mod_storage_save_timer; DISABLE_CLASS_COPY(Client); }; diff --git a/src/gamedef.h b/src/gamedef.h index 593d27e30..6cd01305f 100644 --- a/src/gamedef.h +++ b/src/gamedef.h @@ -34,6 +34,7 @@ class MtEventManager; class IRollbackManager; class EmergeManager; class Camera; +class ModMetadata; namespace irr { namespace scene { class IAnimatedMesh; @@ -75,6 +76,9 @@ public: virtual const std::vector &getMods() const = 0; virtual const ModSpec* getModSpec(const std::string &modname) const = 0; virtual std::string getWorldPath() const { return ""; } + virtual std::string getModStoragePath() const = 0; + virtual bool registerModStorage(ModMetadata *storage) = 0; + virtual void unregisterModStorage(const std::string &name) = 0; }; #endif diff --git a/src/script/clientscripting.cpp b/src/script/clientscripting.cpp index c1e308012..ccdcb928d 100644 --- a/src/script/clientscripting.cpp +++ b/src/script/clientscripting.cpp @@ -58,4 +58,5 @@ void ClientScripting::InitializeModApi(lua_State *L, int top) ModApiStorage::Initialize(L, top); LuaItemStack::Register(L); + StorageRef::Register(L); } diff --git a/src/script/lua_api/l_storage.cpp b/src/script/lua_api/l_storage.cpp index 42928255f..867ab9c8d 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -33,10 +33,9 @@ int ModApiStorage::l_get_mod_storage(lua_State *L) std::string mod_name = lua_tostring(L, -1); ModMetadata *store = new ModMetadata(mod_name); - // For server side - if (Server *server = getServer(L)) { - store->load(server->getModStoragePath()); - server->registerModStorage(store); + if (IGameDef *gamedef = getGameDef(L)) { + store->load(gamedef->getModStoragePath()); + gamedef->registerModStorage(store); } else { assert(false); // this should not happen } @@ -70,8 +69,8 @@ int StorageRef::gc_object(lua_State *L) { StorageRef *o = *(StorageRef **)(lua_touserdata(L, 1)); // Server side - if (Server *server = getServer(L)) - server->unregisterModStorage(getobject(o)->getModName()); + if (IGameDef *gamedef = getGameDef(L)) + gamedef->unregisterModStorage(getobject(o)->getModName()); delete o; return 0; } diff --git a/src/server.h b/src/server.h index f0bab1bbf..e1e8f84dc 100644 --- a/src/server.h +++ b/src/server.h @@ -299,8 +299,8 @@ public: virtual const ModSpec* getModSpec(const std::string &modname) const; void getModNames(std::vector &modlist); std::string getBuiltinLuaPath(); - std::string getWorldPath() const { return m_path_world; } - std::string getModStoragePath() const; + virtual std::string getWorldPath() const { return m_path_world; } + virtual std::string getModStoragePath() const; inline bool isSingleplayer() { return m_simple_singleplayer_mode; } @@ -361,8 +361,8 @@ public: void SendInventory(PlayerSAO* playerSAO); void SendMovePlayer(u16 peer_id); - bool registerModStorage(ModMetadata *storage); - void unregisterModStorage(const std::string &name); + virtual bool registerModStorage(ModMetadata *storage); + virtual void unregisterModStorage(const std::string &name); // Bind address Address m_bind_addr; diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 9beb0afa6..9d223b82d 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -65,6 +65,9 @@ public: 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) {} private: IItemDefManager *m_itemdef; -- cgit v1.2.3 From 91a9382c25328075d1a27593b22b0a75863951e1 Mon Sep 17 00:00:00 2001 From: Loïc Blot Date: Sun, 23 Apr 2017 09:52:40 +0200 Subject: Pass clang-format on various cpp/header files (#5559) --- src/ban.h | 2 +- src/cavegen.h | 45 +++++++++++++++++----------------- src/constants.h | 8 +++--- src/content_abm.cpp | 4 +-- src/database-dummy.h | 1 - src/defaultsettings.h | 1 - src/environment.h | 6 ++--- src/guiKeyChangeMenu.h | 18 ++++++-------- src/guiPasswordChange.h | 16 +++++------- src/irrlichttypes_bloated.h | 1 - src/irrlichttypes_extrabloated.h | 1 - src/itemgroup.h | 6 ++--- src/keycode.h | 7 +++--- src/light.h | 31 ++++++++++++----------- src/localplayer.h | 36 ++++++++++++--------------- src/mapgen_flat.h | 7 +++--- src/mapgen_fractal.h | 7 +++--- src/mapgen_singlenode.h | 6 +++-- src/mapgen_v5.h | 8 +++--- src/metadata.cpp | 9 +++---- src/modifiedstate.h | 1 - src/nameidmapping.cpp | 12 ++++----- src/nameidmapping.h | 30 +++++++++++++---------- src/script/cpp_api/s_mainmenu.cpp | 8 +++--- src/unittest/test_mapnode.cpp | 3 ++- src/unittest/test_nodedef.cpp | 5 ++-- src/unittest/test_objdef.cpp | 4 +-- src/unittest/test_player.cpp | 3 ++- src/unittest/test_profiler.cpp | 3 ++- util/travis/clang-format-whitelist.txt | 32 ------------------------ 30 files changed, 138 insertions(+), 183 deletions(-) (limited to 'src/unittest') diff --git a/src/ban.h b/src/ban.h index d1a49cb15..e35bd0e10 100644 --- a/src/ban.h +++ b/src/ban.h @@ -41,12 +41,12 @@ public: void add(const std::string &ip, const std::string &name); void remove(const std::string &ip_or_name); bool isModified(); + private: Mutex m_mutex; std::string m_banfilepath; StringMap m_ips; bool m_modified; - }; #endif diff --git a/src/cavegen.h b/src/cavegen.h index e322c181c..a1140594e 100644 --- a/src/cavegen.h +++ b/src/cavegen.h @@ -37,11 +37,12 @@ class GenerateNotifier; TODO(hmmmm): Remove dependency on biomes TODO(hmmmm): Find alternative to overgeneration as solution for sunlight issue */ -class CavesNoiseIntersection { +class CavesNoiseIntersection +{ public: CavesNoiseIntersection(INodeDefManager *nodedef, BiomeManager *biomemgr, - v3s16 chunksize, NoiseParams *np_cave1, NoiseParams *np_cave2, - s32 seed, float cave_width); + v3s16 chunksize, NoiseParams *np_cave1, NoiseParams *np_cave2, + s32 seed, float cave_width); ~CavesNoiseIntersection(); void generateCaves(MMVManip *vm, v3s16 nmin, v3s16 nmax, u8 *biomemap); @@ -65,10 +66,12 @@ private: /* CavernsNoise is a cave digging algorithm */ -class CavernsNoise { +class CavernsNoise +{ public: CavernsNoise(INodeDefManager *nodedef, v3s16 chunksize, NoiseParams *np_cavern, - s32 seed, float cavern_limit, float cavern_taper, float cavern_threshold); + s32 seed, float cavern_limit, float cavern_taper, + float cavern_threshold); ~CavernsNoise(); bool generateCaverns(MMVManip *vm, v3s16 nmin, v3s16 nmax); @@ -105,7 +108,8 @@ private: This algorithm is very fast, executing in less than 1ms on average for an 80x80x80 chunk of map on a modern processor. */ -class CavesRandomWalk { +class CavesRandomWalk +{ public: MMVManip *vm; INodeDefManager *ndef; @@ -150,18 +154,16 @@ public: // ndef is a mandatory parameter. // If gennotify is NULL, generation events are not logged. - CavesRandomWalk(INodeDefManager *ndef, - GenerateNotifier *gennotify = NULL, - s32 seed = 0, - int water_level = 1, - content_t water_source = CONTENT_IGNORE, - content_t lava_source = CONTENT_IGNORE); + CavesRandomWalk(INodeDefManager *ndef, GenerateNotifier *gennotify = NULL, + s32 seed = 0, int water_level = 1, + content_t water_source = CONTENT_IGNORE, + content_t lava_source = CONTENT_IGNORE); // vm and ps are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to // be water_level. void makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, - bool is_large_cave, int max_stone_height, s16 *heightmap); + bool is_large_cave, int max_stone_height, s16 *heightmap); private: void makeTunnel(bool dirswitch); @@ -183,7 +185,8 @@ private: tl;dr, *** DO NOT TOUCH THIS CLASS UNLESS YOU KNOW WHAT YOU ARE DOING *** */ -class CavesV6 { +class CavesV6 +{ public: MMVManip *vm; INodeDefManager *ndef; @@ -222,18 +225,16 @@ public: // ndef is a mandatory parameter. // If gennotify is NULL, generation events are not logged. - CavesV6(INodeDefManager *ndef, - GenerateNotifier *gennotify = NULL, - int water_level = 1, - content_t water_source = CONTENT_IGNORE, - content_t lava_source = CONTENT_IGNORE); + CavesV6(INodeDefManager *ndef, GenerateNotifier *gennotify = NULL, + int water_level = 1, content_t water_source = CONTENT_IGNORE, + content_t lava_source = CONTENT_IGNORE); // vm, ps, and ps2 are mandatory parameters. // If heightmap is NULL, the surface level at all points is assumed to // be water_level. - void makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, - PseudoRandom *ps, PseudoRandom *ps2, - bool is_large_cave, int max_stone_height, s16 *heightmap = NULL); + void makeCave(MMVManip *vm, v3s16 nmin, v3s16 nmax, PseudoRandom *ps, + PseudoRandom *ps2, bool is_large_cave, int max_stone_height, + s16 *heightmap = NULL); private: void makeTunnel(bool dirswitch); diff --git a/src/constants.h b/src/constants.h index 55ae9daf3..fb9e97cb3 100644 --- a/src/constants.h +++ b/src/constants.h @@ -85,7 +85,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ // Size of player's main inventory -#define PLAYER_INVENTORY_SIZE (8*4) +#define PLAYER_INVENTORY_SIZE (8 * 4) // Maximum hit points of a player #define PLAYER_MAX_HP 20 @@ -110,10 +110,10 @@ with this program; if not, write to the Free Software Foundation, Inc., // TODO: implement dpi-based scaling for windows and remove this hack #if defined(_WIN32) - #define TTF_DEFAULT_FONT_SIZE (18) +#define TTF_DEFAULT_FONT_SIZE (18) #else - #define TTF_DEFAULT_FONT_SIZE (16) +#define TTF_DEFAULT_FONT_SIZE (16) #endif -#define DEFAULT_FONT_SIZE (10) +#define DEFAULT_FONT_SIZE (10) #endif diff --git a/src/content_abm.cpp b/src/content_abm.cpp index 2ab3a968c..1e175c64f 100644 --- a/src/content_abm.cpp +++ b/src/content_abm.cpp @@ -29,6 +29,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverscripting.h" #include "log.h" -void add_legacy_abms(ServerEnvironment *env, INodeDefManager *nodedef) { - +void add_legacy_abms(ServerEnvironment *env, INodeDefManager *nodedef) +{ } diff --git a/src/database-dummy.h b/src/database-dummy.h index 72100edd0..9083850cb 100644 --- a/src/database-dummy.h +++ b/src/database-dummy.h @@ -38,4 +38,3 @@ private: }; #endif - diff --git a/src/defaultsettings.h b/src/defaultsettings.h index 20274a003..21c51396f 100644 --- a/src/defaultsettings.h +++ b/src/defaultsettings.h @@ -36,4 +36,3 @@ void set_default_settings(Settings *settings); void override_default_settings(Settings *settings, Settings *from); #endif - diff --git a/src/environment.h b/src/environment.h index 52f369817..1de13e9ed 100644 --- a/src/environment.h +++ b/src/environment.h @@ -58,7 +58,7 @@ public: */ virtual void step(f32 dtime) = 0; - virtual Map & getMap() = 0; + virtual Map &getMap() = 0; u32 getDayNightRatio(); @@ -78,7 +78,7 @@ public: // counter used internally when triggering ABMs u32 m_added_objects; - IGameDef* getGameDef() { return m_gamedef; } + IGameDef *getGameDef() { return m_gamedef; } protected: GenericAtomic m_time_of_day_speed; @@ -117,6 +117,7 @@ protected: float m_cache_nodetimer_interval; IGameDef *m_gamedef; + private: Mutex m_time_lock; @@ -124,4 +125,3 @@ private: }; #endif - diff --git a/src/guiKeyChangeMenu.h b/src/guiKeyChangeMenu.h index 19a07620d..1aa400632 100644 --- a/src/guiKeyChangeMenu.h +++ b/src/guiKeyChangeMenu.h @@ -30,7 +30,8 @@ #include #include -struct key_setting { +struct key_setting +{ int id; const wchar_t *button_name; KeyPress key; @@ -38,12 +39,11 @@ struct key_setting { gui::IGUIButton *button; }; - -class GUIKeyChangeMenu: public GUIModalMenu +class GUIKeyChangeMenu : public GUIModalMenu { public: - GUIKeyChangeMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, - s32 id, IMenuManager *menumgr); + GUIKeyChangeMenu(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, + IMenuManager *menumgr); ~GUIKeyChangeMenu(); void removeChildren(); @@ -56,10 +56,9 @@ public: bool acceptInput(); - bool OnEvent(const SEvent& event); + bool OnEvent(const SEvent &event); private: - void init_keys(); bool resetMenu(); @@ -67,13 +66,12 @@ private: void add_key(int id, const wchar_t *button_name, const std::string &setting_name); bool shift_down; - + s32 activeKey; - + std::vector key_used; gui::IGUIStaticText *key_used_text; std::vector key_settings; }; #endif - diff --git a/src/guiPasswordChange.h b/src/guiPasswordChange.h index aecc7076f..cf81389eb 100644 --- a/src/guiPasswordChange.h +++ b/src/guiPasswordChange.h @@ -27,12 +27,10 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. class GUIPasswordChange : public GUIModalMenu { public: - GUIPasswordChange(gui::IGUIEnvironment* env, - gui::IGUIElement* parent, s32 id, - IMenuManager *menumgr, - Client* client); + GUIPasswordChange(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, + IMenuManager *menumgr, Client *client); ~GUIPasswordChange(); - + void removeChildren(); /* Remove and re-add (or reposition) stuff @@ -43,12 +41,10 @@ public: bool acceptInput(); - bool OnEvent(const SEvent& event); - -private: - Client* m_client; + bool OnEvent(const SEvent &event); +private: + Client *m_client; }; #endif - diff --git a/src/irrlichttypes_bloated.h b/src/irrlichttypes_bloated.h index 77aba350c..2caca6fc4 100644 --- a/src/irrlichttypes_bloated.h +++ b/src/irrlichttypes_bloated.h @@ -29,4 +29,3 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #endif - diff --git a/src/irrlichttypes_extrabloated.h b/src/irrlichttypes_extrabloated.h index cd6cb1d2c..464ee7904 100644 --- a/src/irrlichttypes_extrabloated.h +++ b/src/irrlichttypes_extrabloated.h @@ -36,4 +36,3 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif #endif - diff --git a/src/itemgroup.h b/src/itemgroup.h index f91ccc221..2206857fd 100644 --- a/src/itemgroup.h +++ b/src/itemgroup.h @@ -25,14 +25,12 @@ with this program; if not, write to the Free Software Foundation, Inc., typedef UNORDERED_MAP ItemGroupList; -static inline int itemgroup_get(const ItemGroupList &groups, - const std::string &name) +static inline int itemgroup_get(const ItemGroupList &groups, const std::string &name) { ItemGroupList::const_iterator i = groups.find(name); - if(i == groups.end()) + if (i == groups.end()) return 0; return i->second; } #endif - diff --git a/src/keycode.h b/src/keycode.h index 4d66cf7b5..4cd0b707e 100644 --- a/src/keycode.h +++ b/src/keycode.h @@ -34,16 +34,16 @@ public: KeyPress(); KeyPress(const char *name); - KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character=false); + KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character = false); bool operator==(const KeyPress &o) const { - return (Char > 0 && Char == o.Char) || - (valid_kcode(Key) && Key == o.Key); + return (Char > 0 && Char == o.Char) || (valid_kcode(Key) && Key == o.Key); } const char *sym() const; const char *name() const; + protected: static bool valid_kcode(irr::EKEY_CODE k) { @@ -68,4 +68,3 @@ void clearKeyCache(); irr::EKEY_CODE keyname_to_keycode(const char *name); #endif - diff --git a/src/light.h b/src/light.h index 984e6d7c2..30a647581 100644 --- a/src/light.h +++ b/src/light.h @@ -38,30 +38,30 @@ with this program; if not, write to the Free Software Foundation, Inc., inline u8 diminish_light(u8 light) { - if(light == 0) + if (light == 0) return 0; - if(light >= LIGHT_MAX) + if (light >= LIGHT_MAX) return LIGHT_MAX - 1; - + return light - 1; } inline u8 diminish_light(u8 light, u8 distance) { - if(distance >= light) + if (distance >= light) return 0; - return light - distance; + return light - distance; } inline u8 undiminish_light(u8 light) { // We don't know if light should undiminish from this particular 0. // Thus, keep it at 0. - if(light == 0) + if (light == 0) return 0; - if(light == LIGHT_MAX) + if (light == LIGHT_MAX) return light; - + return light + 1; } @@ -85,9 +85,9 @@ extern const u8 *light_decode_table; // 0 <= return value <= 255 inline u8 decode_light(u8 light) { - if(light > LIGHT_MAX) + if (light > LIGHT_MAX) light = LIGHT_MAX; - + return light_decode_table[light]; } @@ -97,12 +97,12 @@ inline float decode_light_f(float light_f) { s32 i = (u32)(light_f * LIGHT_MAX + 0.5); - if(i <= 0) + if (i <= 0) return (float)light_decode_table[0] / 255.0; - if(i >= LIGHT_MAX) + if (i >= LIGHT_MAX) return (float)light_decode_table[LIGHT_MAX] / 255.0; - float v1 = (float)light_decode_table[i-1] / 255.0; + float v1 = (float)light_decode_table[i - 1] / 255.0; float v2 = (float)light_decode_table[i] / 255.0; float f0 = (float)i - 0.5; float f = light_f * LIGHT_MAX - f0; @@ -119,11 +119,10 @@ void set_light_table(float gamma); inline u8 blend_light(u32 daylight_factor, u8 lightday, u8 lightnight) { u32 c = 1000; - u32 l = ((daylight_factor * lightday + (c-daylight_factor) * lightnight))/c; - if(l > LIGHT_SUN) + u32 l = ((daylight_factor * lightday + (c - daylight_factor) * lightnight)) / c; + if (l > LIGHT_SUN) l = LIGHT_SUN; return l; } #endif - diff --git a/src/localplayer.h b/src/localplayer.h index 01e859bf0..d8d2f310b 100644 --- a/src/localplayer.h +++ b/src/localplayer.h @@ -30,7 +30,13 @@ class GenericCAO; class ClientActiveObject; class IGameDef; -enum LocalPlayerAnimations {NO_ANIM, WALK_ANIM, DIG_ANIM, WD_ANIM}; // no local animation, walking, digging, both +enum LocalPlayerAnimations +{ + NO_ANIM, + WALK_ANIM, + DIG_ANIM, + WD_ANIM +}; // no local animation, walking, digging, both class LocalPlayer : public Player { @@ -97,12 +103,11 @@ public: float hurt_tilt_timer; float hurt_tilt_strength; - GenericCAO* getCAO() const { - return m_cao; - } + GenericCAO *getCAO() const { return m_cao; } - void setCAO(GenericCAO* toset) { - assert( m_cao == NULL ); // Pre-condition + void setCAO(GenericCAO *toset) + { + assert(m_cao == NULL); // Pre-condition m_cao = toset; } @@ -113,28 +118,20 @@ public: v3s16 getLightPosition() const; - void setYaw(f32 yaw) - { - m_yaw = yaw; - } + void setYaw(f32 yaw) { m_yaw = yaw; } f32 getYaw() const { return m_yaw; } - void setPitch(f32 pitch) - { - m_pitch = pitch; - } + void setPitch(f32 pitch) { m_pitch = pitch; } f32 getPitch() const { return m_pitch; } - void setPosition(const v3f &position) - { - m_position = position; - } + void setPosition(const v3f &position) { m_position = position; } v3f getPosition() const { return m_position; } v3f getEyePosition() const { return m_position + getEyeOffset(); } v3f getEyeOffset() const; + private: void accelerateHorizontal(const v3f &target_speed, const f32 max_increase); void accelerateVertical(const v3f &target_speed, const f32 max_increase); @@ -169,9 +166,8 @@ private: bool camera_barely_in_ceiling; aabb3f m_collisionbox; - GenericCAO* m_cao; + GenericCAO *m_cao; Client *m_client; }; #endif - diff --git a/src/mapgen_flat.h b/src/mapgen_flat.h index 8b3de2bcf..7a6696329 100644 --- a/src/mapgen_flat.h +++ b/src/mapgen_flat.h @@ -31,8 +31,8 @@ class BiomeManager; extern FlagDesc flagdesc_mapgen_flat[]; - -struct MapgenFlatParams : public MapgenParams { +struct MapgenFlatParams : public MapgenParams +{ u32 spflags; s16 ground_level; s16 large_cave_depth; @@ -53,7 +53,8 @@ struct MapgenFlatParams : public MapgenParams { void writeParams(Settings *settings) const; }; -class MapgenFlat : public MapgenBasic { +class MapgenFlat : public MapgenBasic +{ public: MapgenFlat(int mapgenid, MapgenFlatParams *params, EmergeManager *emerge); ~MapgenFlat(); diff --git a/src/mapgen_fractal.h b/src/mapgen_fractal.h index 3331848bc..d049724b4 100644 --- a/src/mapgen_fractal.h +++ b/src/mapgen_fractal.h @@ -32,8 +32,8 @@ class BiomeManager; extern FlagDesc flagdesc_mapgen_fractal[]; - -struct MapgenFractalParams : public MapgenParams { +struct MapgenFractalParams : public MapgenParams +{ u32 spflags; float cave_width; u16 fractal; @@ -57,7 +57,8 @@ struct MapgenFractalParams : public MapgenParams { void writeParams(Settings *settings) const; }; -class MapgenFractal : public MapgenBasic { +class MapgenFractal : public MapgenBasic +{ public: MapgenFractal(int mapgenid, MapgenFractalParams *params, EmergeManager *emerge); ~MapgenFractal(); diff --git a/src/mapgen_singlenode.h b/src/mapgen_singlenode.h index 07520134d..55a503374 100644 --- a/src/mapgen_singlenode.h +++ b/src/mapgen_singlenode.h @@ -22,7 +22,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen.h" -struct MapgenSinglenodeParams : public MapgenParams { +struct MapgenSinglenodeParams : public MapgenParams +{ MapgenSinglenodeParams() {} ~MapgenSinglenodeParams() {} @@ -30,7 +31,8 @@ struct MapgenSinglenodeParams : public MapgenParams { void writeParams(Settings *settings) const {} }; -class MapgenSinglenode : public Mapgen { +class MapgenSinglenode : public Mapgen +{ public: u32 flags; content_t c_node; diff --git a/src/mapgen_v5.h b/src/mapgen_v5.h index 034d53560..1cdb33683 100644 --- a/src/mapgen_v5.h +++ b/src/mapgen_v5.h @@ -32,8 +32,8 @@ class BiomeManager; extern FlagDesc flagdesc_mapgen_v5[]; - -struct MapgenV5Params : public MapgenParams { +struct MapgenV5Params : public MapgenParams +{ u32 spflags; float cave_width; s16 cavern_limit; @@ -55,8 +55,8 @@ struct MapgenV5Params : public MapgenParams { void writeParams(Settings *settings) const; }; - -class MapgenV5 : public MapgenBasic { +class MapgenV5 : public MapgenBasic +{ public: MapgenV5(int mapgenid, MapgenV5Params *params, EmergeManager *emerge); ~MapgenV5(); diff --git a/src/metadata.cpp b/src/metadata.cpp index 2ce9af5af..833735464 100644 --- a/src/metadata.cpp +++ b/src/metadata.cpp @@ -64,8 +64,7 @@ bool Metadata::operator==(const Metadata &other) const return true; } -const std::string &Metadata::getString(const std::string &name, - u16 recursion) const +const std::string &Metadata::getString(const std::string &name, u16 recursion) const { StringMap::const_iterator it = m_stringvars.find(name); if (it == m_stringvars.end()) { @@ -99,11 +98,9 @@ bool Metadata::setString(const std::string &name, const std::string &var) return true; } -const std::string &Metadata::resolveString(const std::string &str, - u16 recursion) const +const std::string &Metadata::resolveString(const std::string &str, u16 recursion) const { - if (recursion <= 1 && - str.substr(0, 2) == "${" && str[str.length() - 1] == '}') { + if (recursion <= 1 && str.substr(0, 2) == "${" && str[str.length() - 1] == '}') { return getString(str.substr(2, str.length() - 3), recursion + 1); } else { return str; diff --git a/src/modifiedstate.h b/src/modifiedstate.h index 75518f2f5..576c3c576 100644 --- a/src/modifiedstate.h +++ b/src/modifiedstate.h @@ -34,4 +34,3 @@ enum ModifiedState }; #endif - diff --git a/src/nameidmapping.cpp b/src/nameidmapping.cpp index 2af8befff..d031f0808 100644 --- a/src/nameidmapping.cpp +++ b/src/nameidmapping.cpp @@ -25,27 +25,25 @@ void NameIdMapping::serialize(std::ostream &os) const { writeU8(os, 0); // version writeU16(os, m_id_to_name.size()); - for(UNORDERED_MAP::const_iterator - i = m_id_to_name.begin(); - i != m_id_to_name.end(); ++i){ + for (UNORDERED_MAP::const_iterator i = m_id_to_name.begin(); + i != m_id_to_name.end(); ++i) { writeU16(os, i->first); - os<second); + os << serializeString(i->second); } } void NameIdMapping::deSerialize(std::istream &is) { int version = readU8(is); - if(version != 0) + if (version != 0) throw SerializationError("unsupported NameIdMapping version"); u32 count = readU16(is); m_id_to_name.clear(); m_name_to_id.clear(); - for(u32 i=0; i::const_iterator i; i = m_id_to_name.find(id); - if(i == m_id_to_name.end()) + if (i == m_id_to_name.end()) return false; result = i->second; return true; } - bool getId(const std::string &name, u16 &result) const{ + bool getId(const std::string &name, u16 &result) const + { UNORDERED_MAP::const_iterator i; i = m_name_to_id.find(name); - if(i == m_name_to_id.end()) + if (i == m_name_to_id.end()) return false; result = i->second; return true; } - u16 size() const{ - return m_id_to_name.size(); - } + u16 size() const { return m_id_to_name.size(); } private: UNORDERED_MAP m_id_to_name; UNORDERED_MAP m_name_to_id; }; #endif - diff --git a/src/script/cpp_api/s_mainmenu.cpp b/src/script/cpp_api/s_mainmenu.cpp index e9a7a13b9..1e9ba3a41 100644 --- a/src/script/cpp_api/s_mainmenu.cpp +++ b/src/script/cpp_api/s_mainmenu.cpp @@ -34,8 +34,7 @@ void ScriptApiMainMenu::setMainMenuData(MainMenuDataForScript *data) lua_pushnil(L); } lua_settable(L, gamedata_idx); - setboolfield(L, gamedata_idx, "reconnect_requested", - data->reconnect_requested); + setboolfield(L, gamedata_idx, "reconnect_requested", data->reconnect_requested); lua_pop(L, 1); } @@ -58,7 +57,7 @@ void ScriptApiMainMenu::handleMainMenuEvent(std::string text) // Call it lua_pushstring(L, text.c_str()); PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } void ScriptApiMainMenu::handleMainMenuButtons(const StringMap &fields) @@ -90,6 +89,5 @@ void ScriptApiMainMenu::handleMainMenuButtons(const StringMap &fields) // Call it PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } - diff --git a/src/unittest/test_mapnode.cpp b/src/unittest/test_mapnode.cpp index 9ecc2f82d..70e7d42cf 100644 --- a/src/unittest/test_mapnode.cpp +++ b/src/unittest/test_mapnode.cpp @@ -23,7 +23,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "content_mapnode.h" -class TestMapNode : public TestBase { +class TestMapNode : public TestBase +{ public: TestMapNode() { TestManager::registerTestModule(this); } const char *getName() { return "TestMapNode"; } diff --git a/src/unittest/test_nodedef.cpp b/src/unittest/test_nodedef.cpp index 85093f52f..cb99ae854 100644 --- a/src/unittest/test_nodedef.cpp +++ b/src/unittest/test_nodedef.cpp @@ -25,7 +25,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "network/networkprotocol.h" -class TestNodeDef : public TestBase { +class TestNodeDef : public TestBase +{ public: TestNodeDef() { TestManager::registerTestModule(this); } const char *getName() { return "TestNodeDef"; } @@ -55,7 +56,7 @@ void TestNodeDef::testContentFeaturesSerialization() std::ostringstream os(std::ios::binary); f.serialize(os, LATEST_PROTOCOL_VERSION); - //verbosestream<<"Test ContentFeatures size: "< Date: Sun, 23 Apr 2017 14:35:08 +0200 Subject: Player data to Database (#5475) * Player data to Database Add player data into databases (SQLite3 & PG only) PostgreSQL & SQLite: better POO Design for databases Add --migrate-players argument to server + deprecation warning * Remove players directory if empty --- build/android/jni/Android.mk | 1 + builtin/game/chatcommands.lua | 25 +++ doc/lua_api.txt | 2 + src/CMakeLists.txt | 1 + src/client.cpp | 2 +- src/client.h | 4 +- src/content_sao.cpp | 7 +- src/content_sao.h | 4 +- src/database-dummy.h | 9 +- src/database-files.cpp | 179 +++++++++++++++ src/database-files.h | 46 ++++ src/database-leveldb.h | 4 +- src/database-postgresql.cpp | 470 ++++++++++++++++++++++++++++++++++------ src/database-postgresql.h | 115 +++++++--- src/database-redis.h | 2 +- src/database-sqlite3.cpp | 399 +++++++++++++++++++++++++++++++--- src/database-sqlite3.h | 158 ++++++++++++-- src/database.cpp | 4 +- src/database.h | 24 +- src/main.cpp | 21 +- src/map.cpp | 13 +- src/map.h | 8 +- src/remoteplayer.cpp | 48 ---- src/remoteplayer.h | 2 +- src/script/lua_api/l_server.cpp | 17 ++ src/script/lua_api/l_server.h | 3 + src/server.cpp | 50 +---- src/server.h | 3 +- src/serverenvironment.cpp | 234 ++++++++++++++++---- src/serverenvironment.h | 13 +- src/unittest/test_player.cpp | 49 ----- 31 files changed, 1547 insertions(+), 370 deletions(-) create mode 100644 src/database-files.cpp create mode 100644 src/database-files.h (limited to 'src/unittest') diff --git a/build/android/jni/Android.mk b/build/android/jni/Android.mk index 2929eaba1..b652c6b5e 100644 --- a/build/android/jni/Android.mk +++ b/build/android/jni/Android.mk @@ -134,6 +134,7 @@ LOCAL_SRC_FILES := \ jni/src/convert_json.cpp \ jni/src/craftdef.cpp \ jni/src/database-dummy.cpp \ + jni/src/database-files.cpp \ jni/src/database-sqlite3.cpp \ jni/src/database.cpp \ jni/src/debug.cpp \ diff --git a/builtin/game/chatcommands.lua b/builtin/game/chatcommands.lua index 84f2c3fed..cbf75c1bc 100644 --- a/builtin/game/chatcommands.lua +++ b/builtin/game/chatcommands.lua @@ -279,6 +279,31 @@ core.register_chatcommand("auth_reload", { end, }) +core.register_chatcommand("remove_player", { + params = "", + description = "Remove player data", + privs = {server=true}, + func = function(name, param) + local toname = param + if toname == "" then + return false, "Name field required" + end + + local rc = core.remove_player(toname) + + if rc == 0 then + core.log("action", name .. " removed player data of " .. toname .. ".") + return true, "Player \"" .. toname .. "\" removed." + elseif rc == 1 then + return true, "No such player \"" .. toname .. "\" to remove." + elseif rc == 2 then + return true, "Player \"" .. toname .. "\" is connected, cannot remove." + end + + return false, "Unhandled remove_player return code " .. rc .. "" + end, +}) + core.register_chatcommand("teleport", { params = ",, | | ,, | ", description = "Teleport to player or position", diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 33254fb2a..c3d8d2bf6 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -2599,6 +2599,8 @@ These functions return the leftover itemstack. * `minetest.cancel_shutdown_requests()`: cancel current delayed shutdown * `minetest.get_server_status()`: returns server status string * `minetest.get_server_uptime()`: returns the server uptime in seconds +* `minetest.remove_player(name)`: remove player from database (if he is not connected). + * Returns a code (0: successful, 1: no such player, 2: player is connected) ### Bans * `minetest.get_ban_list()`: returns the ban list (same as `minetest.get_ban_description("")`) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 37f72a44d..7f779db10 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -377,6 +377,7 @@ set(common_SRCS convert_json.cpp craftdef.cpp database-dummy.cpp + database-files.cpp database-leveldb.cpp database-postgresql.cpp database-redis.cpp diff --git a/src/client.cpp b/src/client.cpp index ce42d025e..94c808a57 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -770,7 +770,7 @@ void Client::initLocalMapSaving(const Address &address, fs::CreateAllDirs(world_path); - m_localdb = new Database_SQLite3(world_path); + m_localdb = new MapDatabaseSQLite3(world_path); m_localdb->beginSave(); actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl; } diff --git a/src/client.h b/src/client.h index 5dc3f9bc8..328a24f90 100644 --- a/src/client.h +++ b/src/client.h @@ -49,7 +49,7 @@ class ClientMediaDownloader; struct MapDrawControl; class MtEventManager; struct PointedThing; -class Database; +class MapDatabase; class Minimap; struct MinimapMapblock; class Camera; @@ -645,7 +645,7 @@ private: LocalClientState m_state; // Used for saving server map to disk client-side - Database *m_localdb; + MapDatabase *m_localdb; IntervalLimiter m_localdb_save_interval; u16 m_cache_save_interval; diff --git a/src/content_sao.cpp b/src/content_sao.cpp index 355453fc9..caf6dcbab 100644 --- a/src/content_sao.cpp +++ b/src/content_sao.cpp @@ -764,9 +764,10 @@ bool LuaEntitySAO::collideWithObjects() const // No prototype, PlayerSAO does not need to be deserialized -PlayerSAO::PlayerSAO(ServerEnvironment *env_, u16 peer_id_, bool is_singleplayer): +PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, u16 peer_id_, + bool is_singleplayer): UnitSAO(env_, v3f(0,0,0)), - m_player(NULL), + m_player(player_), m_peer_id(peer_id_), m_inventory(NULL), m_damage(0), @@ -819,7 +820,7 @@ PlayerSAO::~PlayerSAO() delete m_inventory; } -void PlayerSAO::initialize(RemotePlayer *player, const std::set &privs) +void PlayerSAO::finalize(RemotePlayer *player, const std::set &privs) { assert(player); m_player = player; diff --git a/src/content_sao.h b/src/content_sao.h index e53e8ecce..e08795579 100644 --- a/src/content_sao.h +++ b/src/content_sao.h @@ -194,7 +194,7 @@ class RemotePlayer; class PlayerSAO : public UnitSAO { public: - PlayerSAO(ServerEnvironment *env_, u16 peer_id_, bool is_singleplayer); + PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, u16 peer_id_, bool is_singleplayer); ~PlayerSAO(); ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_PLAYER; } @@ -349,7 +349,7 @@ public: bool getCollisionBox(aabb3f *toset) const; bool collideWithObjects() const { return true; } - void initialize(RemotePlayer *player, const std::set &privs); + void finalize(RemotePlayer *player, const std::set &privs); v3f getEyePosition() const { return m_base_position + getEyeOffset(); } v3f getEyeOffset() const; diff --git a/src/database-dummy.h b/src/database-dummy.h index 9083850cb..7d1cb2279 100644 --- a/src/database-dummy.h +++ b/src/database-dummy.h @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database.h" #include "irrlichttypes.h" -class Database_Dummy : public Database +class Database_Dummy : public MapDatabase, public PlayerDatabase { public: bool saveBlock(const v3s16 &pos, const std::string &data); @@ -33,6 +33,13 @@ public: bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector &dst); + void savePlayer(RemotePlayer *player) {} + bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) { return true; } + bool removePlayer(const std::string &name) { return true; } + void listPlayers(std::vector &) {} + + void beginSave() {} + void endSave() {} private: std::map m_database; }; diff --git a/src/database-files.cpp b/src/database-files.cpp new file mode 100644 index 000000000..08a1f2d03 --- /dev/null +++ b/src/database-files.cpp @@ -0,0 +1,179 @@ +/* +Minetest +Copyright (C) 2017 nerzhul, Loic Blot + +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 +#include +#include "database-files.h" +#include "content_sao.h" +#include "remoteplayer.h" +#include "settings.h" +#include "porting.h" +#include "filesys.h" + +// !!! WARNING !!! +// This backend is intended to be used on Minetest 0.4.16 only for the transition backend for +// player files + +void PlayerDatabaseFiles::serialize(std::ostringstream &os, RemotePlayer *player) +{ + // Utilize a Settings object for storing values + Settings args; + args.setS32("version", 1); + args.set("name", player->getName()); + + sanity_check(player->getPlayerSAO()); + args.setS32("hp", player->getPlayerSAO()->getHP()); + args.setV3F("position", player->getPlayerSAO()->getBasePosition()); + args.setFloat("pitch", player->getPlayerSAO()->getPitch()); + args.setFloat("yaw", player->getPlayerSAO()->getYaw()); + args.setS32("breath", player->getPlayerSAO()->getBreath()); + + std::string extended_attrs = ""; + player->serializeExtraAttributes(extended_attrs); + args.set("extended_attributes", extended_attrs); + + args.writeLines(os); + + os << "PlayerArgsEnd\n"; + + player->inventory.serialize(os); +} + +void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) +{ + std::string savedir = m_savedir + DIR_DELIM; + std::string path = savedir + player->getName(); + bool path_found = false; + RemotePlayer testplayer("", NULL); + + for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES && !path_found; i++) { + if (!fs::PathExists(path)) { + path_found = true; + continue; + } + + // Open and deserialize file to check player name + std::ifstream is(path.c_str(), std::ios_base::binary); + if (!is.good()) { + errorstream << "Failed to open " << path << std::endl; + return; + } + + testplayer.deSerialize(is, path, NULL); + is.close(); + if (strcmp(testplayer.getName(), player->getName()) == 0) { + path_found = true; + continue; + } + + path = savedir + player->getName() + itos(i); + } + + if (!path_found) { + errorstream << "Didn't find free file for player " << player->getName() + << std::endl; + return; + } + + // Open and serialize file + std::ostringstream ss(std::ios_base::binary); + serialize(ss, player); + if (!fs::safeWriteToFile(path, ss.str())) { + infostream << "Failed to write " << path << std::endl; + } + player->setModified(false); +} + +bool PlayerDatabaseFiles::removePlayer(const std::string &name) +{ + std::string players_path = m_savedir + DIR_DELIM; + std::string path = players_path + name; + + RemotePlayer temp_player("", NULL); + for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { + // Open file and deserialize + std::ifstream is(path.c_str(), std::ios_base::binary); + if (!is.good()) + continue; + + temp_player.deSerialize(is, path, NULL); + is.close(); + + if (temp_player.getName() == name) { + fs::DeleteSingleFileOrEmptyDirectory(path); + return true; + } + + path = players_path + name + itos(i); + } + + return false; +} + +bool PlayerDatabaseFiles::loadPlayer(RemotePlayer *player, PlayerSAO *sao) +{ + std::string players_path = m_savedir + DIR_DELIM; + std::string path = players_path + player->getName(); + + const std::string player_to_load = player->getName(); + for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { + // Open file and deserialize + std::ifstream is(path.c_str(), std::ios_base::binary); + if (!is.good()) + continue; + + player->deSerialize(is, path, sao); + is.close(); + + if (player->getName() == player_to_load) + return true; + + path = players_path + player_to_load + itos(i); + } + + infostream << "Player file for player " << player_to_load << " not found" << std::endl; + return false; +} + +void PlayerDatabaseFiles::listPlayers(std::vector &res) +{ + std::vector files = fs::GetDirListing(m_savedir); + // list files into players directory + for (std::vector::const_iterator it = files.begin(); it != + files.end(); ++it) { + // Ignore directories + if (it->dir) + continue; + + const std::string &filename = it->name; + std::string full_path = m_savedir + DIR_DELIM + filename; + std::ifstream is(full_path.c_str(), std::ios_base::binary); + if (!is.good()) + continue; + + RemotePlayer player(filename.c_str(), NULL); + // Null env & dummy peer_id + PlayerSAO playerSAO(NULL, &player, 15789, false); + + player.deSerialize(is, "", &playerSAO); + is.close(); + + res.push_back(player.getName()); + } +} diff --git a/src/database-files.h b/src/database-files.h new file mode 100644 index 000000000..d23069c2a --- /dev/null +++ b/src/database-files.h @@ -0,0 +1,46 @@ +/* +Minetest +Copyright (C) 2017 nerzhul, Loic Blot + +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. +*/ + +#ifndef DATABASE_FILES_HEADER +#define DATABASE_FILES_HEADER + +// !!! WARNING !!! +// This backend is intended to be used on Minetest 0.4.16 only for the transition backend for +// player files + +#include "database.h" + +class PlayerDatabaseFiles : public PlayerDatabase +{ +public: + PlayerDatabaseFiles(const std::string &savedir) : m_savedir(savedir) {} + virtual ~PlayerDatabaseFiles() {} + + void savePlayer(RemotePlayer *player); + bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); + bool removePlayer(const std::string &name); + void listPlayers(std::vector &res); + +private: + void serialize(std::ostringstream &os, RemotePlayer *player); + + std::string m_savedir; +}; + +#endif diff --git a/src/database-leveldb.h b/src/database-leveldb.h index 171946741..52ccebe70 100644 --- a/src/database-leveldb.h +++ b/src/database-leveldb.h @@ -28,7 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "database.h" #include "leveldb/db.h" -class Database_LevelDB : public Database +class Database_LevelDB : public MapDatabase { public: Database_LevelDB(const std::string &savedir); @@ -39,6 +39,8 @@ public: bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector &dst); + void beginSave() {} + void endSave() {} private: leveldb::DB *m_database; }; diff --git a/src/database-postgresql.cpp b/src/database-postgresql.cpp index 83678fd52..a6b62bad5 100644 --- a/src/database-postgresql.cpp +++ b/src/database-postgresql.cpp @@ -39,13 +39,15 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "exceptions.h" #include "settings.h" +#include "content_sao.h" +#include "remoteplayer.h" -Database_PostgreSQL::Database_PostgreSQL(const Settings &conf) : - m_connect_string(""), +Database_PostgreSQL::Database_PostgreSQL(const std::string &connect_string) : + m_connect_string(connect_string), m_conn(NULL), m_pgversion(0) { - if (!conf.getNoEx("pgsql_connection", m_connect_string)) { + if (m_connect_string.empty()) { throw SettingNotFoundException( "Set pgsql_connection string in world.mt to " "use the postgresql backend\n" @@ -57,8 +59,6 @@ Database_PostgreSQL::Database_PostgreSQL(const Settings &conf) : "DELETE rights on the database.\n" "Don't create mt_user as a SUPERUSER!"); } - - connectToDatabase(); } Database_PostgreSQL::~Database_PostgreSQL() @@ -118,40 +118,6 @@ bool Database_PostgreSQL::initialized() const return (PQstatus(m_conn) == CONNECTION_OK); } -void Database_PostgreSQL::initStatements() -{ - prepareStatement("read_block", - "SELECT data FROM blocks " - "WHERE posX = $1::int4 AND posY = $2::int4 AND " - "posZ = $3::int4"); - - if (m_pgversion < 90500) { - prepareStatement("write_block_insert", - "INSERT INTO blocks (posX, posY, posZ, data) SELECT " - "$1::int4, $2::int4, $3::int4, $4::bytea " - "WHERE NOT EXISTS (SELECT true FROM blocks " - "WHERE posX = $1::int4 AND posY = $2::int4 AND " - "posZ = $3::int4)"); - - prepareStatement("write_block_update", - "UPDATE blocks SET data = $4::bytea " - "WHERE posX = $1::int4 AND posY = $2::int4 AND " - "posZ = $3::int4"); - } else { - prepareStatement("write_block", - "INSERT INTO blocks (posX, posY, posZ, data) VALUES " - "($1::int4, $2::int4, $3::int4, $4::bytea) " - "ON CONFLICT ON CONSTRAINT blocks_pkey DO " - "UPDATE SET data = $4::bytea"); - } - - prepareStatement("delete_block", "DELETE FROM blocks WHERE " - "posX = $1::int4 AND posY = $2::int4 AND posZ = $3::int4"); - - prepareStatement("list_all_loadable_blocks", - "SELECT posX, posY, posZ FROM blocks"); -} - PGresult *Database_PostgreSQL::checkResults(PGresult *result, bool clear) { ExecStatusType statusType = PQresultStatus(result); @@ -173,30 +139,21 @@ PGresult *Database_PostgreSQL::checkResults(PGresult *result, bool clear) return result; } -void Database_PostgreSQL::createDatabase() +void Database_PostgreSQL::createTableIfNotExists(const std::string &table_name, + const std::string &definition) { - PGresult *result = checkResults(PQexec(m_conn, - "SELECT relname FROM pg_class WHERE relname='blocks';"), - false); + std::string sql_check_table = "SELECT relname FROM pg_class WHERE relname='" + + table_name + "';"; + PGresult *result = checkResults(PQexec(m_conn, sql_check_table.c_str()), false); // If table doesn't exist, create it if (!PQntuples(result)) { - static const char* dbcreate_sql = "CREATE TABLE blocks (" - "posX INT NOT NULL," - "posY INT NOT NULL," - "posZ INT NOT NULL," - "data BYTEA," - "PRIMARY KEY (posX,posY,posZ)" - ");"; - checkResults(PQexec(m_conn, dbcreate_sql)); + checkResults(PQexec(m_conn, definition.c_str())); } PQclear(result); - - infostream << "PostgreSQL: Game Database was inited." << std::endl; } - void Database_PostgreSQL::beginSave() { verifyDatabase(); @@ -208,14 +165,70 @@ void Database_PostgreSQL::endSave() checkResults(PQexec(m_conn, "COMMIT;")); } -bool Database_PostgreSQL::saveBlock(const v3s16 &pos, - const std::string &data) +MapDatabasePostgreSQL::MapDatabasePostgreSQL(const std::string &connect_string): + Database_PostgreSQL(connect_string), + MapDatabase() +{ + connectToDatabase(); +} + + +void MapDatabasePostgreSQL::createDatabase() +{ + createTableIfNotExists("blocks", + "CREATE TABLE blocks (" + "posX INT NOT NULL," + "posY INT NOT NULL," + "posZ INT NOT NULL," + "data BYTEA," + "PRIMARY KEY (posX,posY,posZ)" + ");" + ); + + infostream << "PostgreSQL: Map Database was initialized." << std::endl; +} + +void MapDatabasePostgreSQL::initStatements() +{ + prepareStatement("read_block", + "SELECT data FROM blocks " + "WHERE posX = $1::int4 AND posY = $2::int4 AND " + "posZ = $3::int4"); + + if (getPGVersion() < 90500) { + prepareStatement("write_block_insert", + "INSERT INTO blocks (posX, posY, posZ, data) SELECT " + "$1::int4, $2::int4, $3::int4, $4::bytea " + "WHERE NOT EXISTS (SELECT true FROM blocks " + "WHERE posX = $1::int4 AND posY = $2::int4 AND " + "posZ = $3::int4)"); + + prepareStatement("write_block_update", + "UPDATE blocks SET data = $4::bytea " + "WHERE posX = $1::int4 AND posY = $2::int4 AND " + "posZ = $3::int4"); + } else { + prepareStatement("write_block", + "INSERT INTO blocks (posX, posY, posZ, data) VALUES " + "($1::int4, $2::int4, $3::int4, $4::bytea) " + "ON CONFLICT ON CONSTRAINT blocks_pkey DO " + "UPDATE SET data = $4::bytea"); + } + + prepareStatement("delete_block", "DELETE FROM blocks WHERE " + "posX = $1::int4 AND posY = $2::int4 AND posZ = $3::int4"); + + prepareStatement("list_all_loadable_blocks", + "SELECT posX, posY, posZ FROM blocks"); +} + +bool MapDatabasePostgreSQL::saveBlock(const v3s16 &pos, const std::string &data) { // Verify if we don't overflow the platform integer with the mapblock size if (data.size() > INT_MAX) { errorstream << "Database_PostgreSQL::saveBlock: Data truncation! " - << "data.size() over 0xFFFF (== " << data.size() - << ")" << std::endl; + << "data.size() over 0xFFFFFFFF (== " << data.size() + << ")" << std::endl; return false; } @@ -232,7 +245,7 @@ bool Database_PostgreSQL::saveBlock(const v3s16 &pos, }; const int argFmt[] = { 1, 1, 1, 1 }; - if (m_pgversion < 90500) { + if (getPGVersion() < 90500) { execPrepared("write_block_update", ARRLEN(args), args, argLen, argFmt); execPrepared("write_block_insert", ARRLEN(args), args, argLen, argFmt); } else { @@ -241,8 +254,7 @@ bool Database_PostgreSQL::saveBlock(const v3s16 &pos, return true; } -void Database_PostgreSQL::loadBlock(const v3s16 &pos, - std::string *block) +void MapDatabasePostgreSQL::loadBlock(const v3s16 &pos, std::string *block) { verifyDatabase(); @@ -256,19 +268,17 @@ void Database_PostgreSQL::loadBlock(const v3s16 &pos, const int argFmt[] = { 1, 1, 1 }; PGresult *results = execPrepared("read_block", ARRLEN(args), args, - argLen, argFmt, false); + argLen, argFmt, false); *block = ""; - if (PQntuples(results)) { - *block = std::string(PQgetvalue(results, 0, 0), - PQgetlength(results, 0, 0)); - } + if (PQntuples(results)) + *block = std::string(PQgetvalue(results, 0, 0), PQgetlength(results, 0, 0)); PQclear(results); } -bool Database_PostgreSQL::deleteBlock(const v3s16 &pos) +bool MapDatabasePostgreSQL::deleteBlock(const v3s16 &pos) { verifyDatabase(); @@ -286,18 +296,338 @@ bool Database_PostgreSQL::deleteBlock(const v3s16 &pos) return true; } -void Database_PostgreSQL::listAllLoadableBlocks(std::vector &dst) +void MapDatabasePostgreSQL::listAllLoadableBlocks(std::vector &dst) { verifyDatabase(); PGresult *results = execPrepared("list_all_loadable_blocks", 0, - NULL, NULL, NULL, false, false); + NULL, NULL, NULL, false, false); int numrows = PQntuples(results); - for (int row = 0; row < numrows; ++row) { + for (int row = 0; row < numrows; ++row) dst.push_back(pg_to_v3s16(results, 0, 0)); + + PQclear(results); +} + +/* + * Player Database + */ +PlayerDatabasePostgreSQL::PlayerDatabasePostgreSQL(const std::string &connect_string): + Database_PostgreSQL(connect_string), + PlayerDatabase() +{ + connectToDatabase(); +} + + +void PlayerDatabasePostgreSQL::createDatabase() +{ + createTableIfNotExists("player", + "CREATE TABLE player (" + "name VARCHAR(60) NOT NULL," + "pitch NUMERIC(15, 7) NOT NULL," + "yaw NUMERIC(15, 7) NOT NULL," + "posX NUMERIC(15, 7) NOT NULL," + "posY NUMERIC(15, 7) NOT NULL," + "posZ NUMERIC(15, 7) NOT NULL," + "hp INT NOT NULL," + "breath INT NOT NULL," + "creation_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," + "modification_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," + "PRIMARY KEY (name)" + ");" + ); + + createTableIfNotExists("player_inventories", + "CREATE TABLE player_inventories (" + "player VARCHAR(60) NOT NULL," + "inv_id INT NOT NULL," + "inv_width INT NOT NULL," + "inv_name TEXT NOT NULL DEFAULT ''," + "inv_size INT NOT NULL," + "PRIMARY KEY(player, inv_id)," + "CONSTRAINT player_inventories_fkey FOREIGN KEY (player) REFERENCES " + "player (name) ON DELETE CASCADE" + ");" + ); + + createTableIfNotExists("player_inventory_items", + "CREATE TABLE player_inventory_items (" + "player VARCHAR(60) NOT NULL," + "inv_id INT NOT NULL," + "slot_id INT NOT NULL," + "item TEXT NOT NULL DEFAULT ''," + "PRIMARY KEY(player, inv_id, slot_id)," + "CONSTRAINT player_inventory_items_fkey FOREIGN KEY (player) REFERENCES " + "player (name) ON DELETE CASCADE" + ");" + ); + + createTableIfNotExists("player_metadata", + "CREATE TABLE player_metadata (" + "player VARCHAR(60) NOT NULL," + "attr VARCHAR(256) NOT NULL," + "value TEXT," + "PRIMARY KEY(player, attr)," + "CONSTRAINT player_metadata_fkey FOREIGN KEY (player) REFERENCES " + "player (name) ON DELETE CASCADE" + ");" + ); + + infostream << "PostgreSQL: Player Database was inited." << std::endl; +} + +void PlayerDatabasePostgreSQL::initStatements() +{ + if (getPGVersion() < 90500) { + prepareStatement("create_player", + "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " + "($1, $2, $3, $4, $5, $6, $7::int, $8::int)"); + + prepareStatement("update_player", + "UPDATE SET pitch = $2, yaw = $3, posX = $4, posY = $5, posZ = $6, hp = $7::int, " + "breath = $8::int, modification_date = NOW() WHERE name = $1"); + } else { + prepareStatement("save_player", + "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " + "($1, $2, $3, $4, $5, $6, $7::int, $8::int)" + "ON CONFLICT ON CONSTRAINT player_pkey DO UPDATE SET pitch = $2, yaw = $3, " + "posX = $4, posY = $5, posZ = $6, hp = $7::int, breath = $8::int, " + "modification_date = NOW()"); + } + + prepareStatement("remove_player", "DELETE FROM player WHERE name = $1"); + + prepareStatement("load_player_list", "SELECT name FROM player"); + + prepareStatement("remove_player_inventories", + "DELETE FROM player_inventories WHERE player = $1"); + + prepareStatement("remove_player_inventory_items", + "DELETE FROM player_inventory_items WHERE player = $1"); + + prepareStatement("add_player_inventory", + "INSERT INTO player_inventories (player, inv_id, inv_width, inv_name, inv_size) VALUES " + "($1, $2::int, $3::int, $4, $5::int)"); + + prepareStatement("add_player_inventory_item", + "INSERT INTO player_inventory_items (player, inv_id, slot_id, item) VALUES " + "($1, $2::int, $3::int, $4)"); + + prepareStatement("load_player_inventories", + "SELECT inv_id, inv_width, inv_name, inv_size FROM player_inventories " + "WHERE player = $1 ORDER BY inv_id"); + + prepareStatement("load_player_inventory_items", + "SELECT slot_id, item FROM player_inventory_items WHERE " + "player = $1 AND inv_id = $2::int"); + + prepareStatement("load_player", + "SELECT pitch, yaw, posX, posY, posZ, hp, breath FROM player WHERE name = $1"); + + prepareStatement("remove_player_metadata", + "DELETE FROM player_metadata WHERE player = $1"); + + prepareStatement("save_player_metadata", + "INSERT INTO player_metadata (player, attr, value) VALUES ($1, $2, $3)"); + + prepareStatement("load_player_metadata", + "SELECT attr, value FROM player_metadata WHERE player = $1"); + +} + +bool PlayerDatabasePostgreSQL::playerDataExists(const std::string &playername) +{ + verifyDatabase(); + + const char *values[] = { playername.c_str() }; + PGresult *results = execPrepared("load_player", 1, values, false); + + bool res = (PQntuples(results) > 0); + PQclear(results); + return res; +} + +void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) +{ + PlayerSAO* sao = player->getPlayerSAO(); + if (!sao) + return; + + verifyDatabase(); + + v3f pos = sao->getBasePosition(); + std::string pitch = ftos(sao->getPitch()); + std::string yaw = ftos(sao->getYaw()); + std::string posx = ftos(pos.X); + std::string posy = ftos(pos.Y); + std::string posz = ftos(pos.Z); + std::string hp = itos(sao->getHP()); + std::string breath = itos(sao->getBreath()); + const char *values[] = { + player->getName(), + pitch.c_str(), + yaw.c_str(), + posx.c_str(), posy.c_str(), posz.c_str(), + hp.c_str(), + breath.c_str() + }; + + const char* rmvalues[] = { player->getName() }; + beginSave(); + + if (getPGVersion() < 90500) { + if (!playerDataExists(player->getName())) + execPrepared("create_player", 8, values, true, false); + else + execPrepared("update_player", 8, values, true, false); + } + else + execPrepared("save_player", 8, values, true, false); + + // Write player inventories + execPrepared("remove_player_inventories", 1, rmvalues); + execPrepared("remove_player_inventory_items", 1, rmvalues); + + std::vector inventory_lists = sao->getInventory()->getLists(); + for (u16 i = 0; i < inventory_lists.size(); i++) { + const InventoryList* list = inventory_lists[i]; + std::string name = list->getName(), width = itos(list->getWidth()), + inv_id = itos(i), lsize = itos(list->getSize()); + + const char* inv_values[] = { + player->getName(), + inv_id.c_str(), + width.c_str(), + name.c_str(), + lsize.c_str() + }; + execPrepared("add_player_inventory", 5, inv_values); + + for (u32 j = 0; j < list->getSize(); j++) { + std::ostringstream os; + list->getItem(j).serialize(os); + std::string itemStr = os.str(), slotId = itos(j); + + const char* invitem_values[] = { + player->getName(), + inv_id.c_str(), + slotId.c_str(), + itemStr.c_str() + }; + execPrepared("add_player_inventory_item", 4, invitem_values); + } + } + + execPrepared("remove_player_metadata", 1, rmvalues); + const PlayerAttributes &attrs = sao->getExtendedAttributes(); + for (PlayerAttributes::const_iterator it = attrs.begin(); it != attrs.end(); ++it) { + const char *meta_values[] = { + player->getName(), + it->first.c_str(), + it->second.c_str() + }; + execPrepared("save_player_metadata", 3, meta_values); } + endSave(); +} + +bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) +{ + sanity_check(sao); + verifyDatabase(); + + const char *values[] = { player->getName() }; + PGresult *results = execPrepared("load_player", 1, values, false, false); + + // Player not found, return not found + if (!PQntuples(results)) { + PQclear(results); + return false; + } + + sao->setPitch(pg_to_float(results, 0, 0)); + sao->setYaw(pg_to_float(results, 0, 1)); + sao->setBasePosition(v3f( + pg_to_float(results, 0, 2), + pg_to_float(results, 0, 3), + pg_to_float(results, 0, 4)) + ); + sao->setHPRaw((s16) pg_to_int(results, 0, 5)); + sao->setBreath((u16) pg_to_int(results, 0, 6), false); + + PQclear(results); + + // Load inventory + results = execPrepared("load_player_inventories", 1, values, false, false); + + int resultCount = PQntuples(results); + + for (int row = 0; row < resultCount; ++row) { + InventoryList* invList = player->inventory. + addList(PQgetvalue(results, row, 2), pg_to_uint(results, row, 3)); + invList->setWidth(pg_to_uint(results, row, 1)); + + u32 invId = pg_to_uint(results, row, 0); + std::string invIdStr = itos(invId); + + const char* values2[] = { + player->getName(), + invIdStr.c_str() + }; + PGresult *results2 = execPrepared("load_player_inventory_items", 2, + values2, false, false); + + int resultCount2 = PQntuples(results2); + for (int row2 = 0; row2 < resultCount2; row2++) { + const std::string itemStr = PQgetvalue(results2, row2, 1); + if (itemStr.length() > 0) { + ItemStack stack; + stack.deSerialize(itemStr); + invList->addItem(pg_to_uint(results2, row2, 0), stack); + } + } + PQclear(results2); + } + + PQclear(results); + + results = execPrepared("load_player_metadata", 1, values, false); + + int numrows = PQntuples(results); + for (int row = 0; row < numrows; row++) { + sao->setExtendedAttribute(PQgetvalue(results, row, 0),PQgetvalue(results, row, 1)); + } + + PQclear(results); + + return true; +} + +bool PlayerDatabasePostgreSQL::removePlayer(const std::string &name) +{ + if (!playerDataExists(name)) + return false; + + verifyDatabase(); + + const char *values[] = { name.c_str() }; + execPrepared("remove_player", 1, values); + + return true; +} + +void PlayerDatabasePostgreSQL::listPlayers(std::vector &res) +{ + verifyDatabase(); + + PGresult *results = execPrepared("load_player_list", 0, NULL, false); + + int numrows = PQntuples(results); + for (int row = 0; row < numrows; row++) + res.push_back(PQgetvalue(results, row, 0)); PQclear(results); } diff --git a/src/database-postgresql.h b/src/database-postgresql.h index 1cfa544e3..d6f208fd9 100644 --- a/src/database-postgresql.h +++ b/src/database-postgresql.h @@ -27,53 +27,33 @@ with this program; if not, write to the Free Software Foundation, Inc., class Settings; -class Database_PostgreSQL : public Database +class Database_PostgreSQL: public Database { public: - Database_PostgreSQL(const Settings &conf); + Database_PostgreSQL(const std::string &connect_string); ~Database_PostgreSQL(); void beginSave(); void endSave(); - bool saveBlock(const v3s16 &pos, const std::string &data); - void loadBlock(const v3s16 &pos, std::string *block); - bool deleteBlock(const v3s16 &pos); - void listAllLoadableBlocks(std::vector &dst); bool initialized() const; -private: - // Database initialization - void connectToDatabase(); - void initStatements(); - void createDatabase(); - inline void prepareStatement(const std::string &name, const std::string &sql) +protected: + // Conversion helpers + inline int pg_to_int(PGresult *res, int row, int col) { - checkResults(PQprepare(m_conn, name.c_str(), sql.c_str(), 0, NULL)); + return atoi(PQgetvalue(res, row, col)); } - // Database connectivity checks - void ping(); - void verifyDatabase(); - - // Database usage - PGresult *checkResults(PGresult *res, bool clear = true); - - inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, - const void **params, - const int *paramsLengths = NULL, const int *paramsFormats = NULL, - bool clear = true, bool nobinary = true) + inline u32 pg_to_uint(PGresult *res, int row, int col) { - return checkResults(PQexecPrepared(m_conn, stmtName, paramsNumber, - (const char* const*) params, paramsLengths, paramsFormats, - nobinary ? 1 : 0), clear); + return (u32) atoi(PQgetvalue(res, row, col)); } - // Conversion helpers - inline int pg_to_int(PGresult *res, int row, int col) + inline float pg_to_float(PGresult *res, int row, int col) { - return atoi(PQgetvalue(res, row, col)); + return (float) atof(PQgetvalue(res, row, col)); } inline v3s16 pg_to_v3s16(PGresult *res, int row, int col) @@ -85,11 +65,86 @@ private: ); } + inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, + const void **params, + const int *paramsLengths = NULL, const int *paramsFormats = NULL, + bool clear = true, bool nobinary = true) + { + return checkResults(PQexecPrepared(m_conn, stmtName, paramsNumber, + (const char* const*) params, paramsLengths, paramsFormats, + nobinary ? 1 : 0), clear); + } + + inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, + const char **params, bool clear = true, bool nobinary = true) + { + return execPrepared(stmtName, paramsNumber, + (const void **)params, NULL, NULL, clear, nobinary); + } + + void createTableIfNotExists(const std::string &table_name, const std::string &definition); + void verifyDatabase(); + + // Database initialization + void connectToDatabase(); + virtual void createDatabase() = 0; + virtual void initStatements() = 0; + inline void prepareStatement(const std::string &name, const std::string &sql) + { + checkResults(PQprepare(m_conn, name.c_str(), sql.c_str(), 0, NULL)); + } + + const int getPGVersion() const { return m_pgversion; } +private: + // Database connectivity checks + void ping(); + + // Database usage + PGresult *checkResults(PGresult *res, bool clear = true); + // Attributes std::string m_connect_string; PGconn *m_conn; int m_pgversion; }; +class MapDatabasePostgreSQL : private Database_PostgreSQL, public MapDatabase +{ +public: + MapDatabasePostgreSQL(const std::string &connect_string); + virtual ~MapDatabasePostgreSQL() {} + + bool saveBlock(const v3s16 &pos, const std::string &data); + void loadBlock(const v3s16 &pos, std::string *block); + bool deleteBlock(const v3s16 &pos); + void listAllLoadableBlocks(std::vector &dst); + + void beginSave() { Database_PostgreSQL::beginSave(); } + void endSave() { Database_PostgreSQL::endSave(); } + +protected: + virtual void createDatabase(); + virtual void initStatements(); +}; + +class PlayerDatabasePostgreSQL : private Database_PostgreSQL, public PlayerDatabase +{ +public: + PlayerDatabasePostgreSQL(const std::string &connect_string); + virtual ~PlayerDatabasePostgreSQL() {} + + void savePlayer(RemotePlayer *player); + bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); + bool removePlayer(const std::string &name); + void listPlayers(std::vector &res); + +protected: + virtual void createDatabase(); + virtual void initStatements(); + +private: + bool playerDataExists(const std::string &playername); +}; + #endif diff --git a/src/database-redis.h b/src/database-redis.h index 214bc8dd6..fa15dd8a7 100644 --- a/src/database-redis.h +++ b/src/database-redis.h @@ -30,7 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class Settings; -class Database_Redis : public Database +class Database_Redis : public MapDatabase { public: Database_Redis(Settings &conf); diff --git a/src/database-sqlite3.cpp b/src/database-sqlite3.cpp index 095d485c0..714f56c39 100644 --- a/src/database-sqlite3.cpp +++ b/src/database-sqlite3.cpp @@ -33,6 +33,8 @@ SQLite format specification: #include "settings.h" #include "porting.h" #include "util/string.h" +#include "content_sao.h" +#include "remoteplayer.h" #include @@ -111,27 +113,26 @@ int Database_SQLite3::busyHandler(void *data, int count) } -Database_SQLite3::Database_SQLite3(const std::string &savedir) : +Database_SQLite3::Database_SQLite3(const std::string &savedir, const std::string &dbname) : + m_database(NULL), m_initialized(false), m_savedir(savedir), - m_database(NULL), - m_stmt_read(NULL), - m_stmt_write(NULL), - m_stmt_list(NULL), - m_stmt_delete(NULL), + m_dbname(dbname), m_stmt_begin(NULL), m_stmt_end(NULL) { } -void Database_SQLite3::beginSave() { +void Database_SQLite3::beginSave() +{ verifyDatabase(); SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE, "Failed to start SQLite3 transaction"); sqlite3_reset(m_stmt_begin); } -void Database_SQLite3::endSave() { +void Database_SQLite3::endSave() +{ verifyDatabase(); SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE, "Failed to commit SQLite3 transaction"); @@ -142,7 +143,7 @@ void Database_SQLite3::openDatabase() { if (m_database) return; - std::string dbp = m_savedir + DIR_DELIM + "map.sqlite"; + std::string dbp = m_savedir + DIR_DELIM + m_dbname + ".sqlite"; // Open the database connection @@ -170,6 +171,8 @@ void Database_SQLite3::openDatabase() + itos(g_settings->getU16("sqlite_synchronous")); SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL), "Failed to modify sqlite3 synchronous mode"); + SQLOK(sqlite3_exec(m_database, "PRAGMA foreign_keys = ON", NULL, NULL, NULL), + "Failed to enable sqlite3 foreign key support"); } void Database_SQLite3::verifyDatabase() @@ -178,8 +181,61 @@ void Database_SQLite3::verifyDatabase() openDatabase(); - PREPARE_STATEMENT(begin, "BEGIN"); - PREPARE_STATEMENT(end, "COMMIT"); + PREPARE_STATEMENT(begin, "BEGIN;"); + PREPARE_STATEMENT(end, "COMMIT;"); + + initStatements(); + + m_initialized = true; +} + +Database_SQLite3::~Database_SQLite3() +{ + FINALIZE_STATEMENT(m_stmt_begin) + FINALIZE_STATEMENT(m_stmt_end) + + SQLOK_ERRSTREAM(sqlite3_close(m_database), "Failed to close database"); +} + +/* + * Map database + */ + +MapDatabaseSQLite3::MapDatabaseSQLite3(const std::string &savedir): + Database_SQLite3(savedir, "map"), + MapDatabase(), + m_stmt_read(NULL), + m_stmt_write(NULL), + m_stmt_list(NULL), + m_stmt_delete(NULL) +{ + +} + +MapDatabaseSQLite3::~MapDatabaseSQLite3() +{ + FINALIZE_STATEMENT(m_stmt_read) + FINALIZE_STATEMENT(m_stmt_write) + FINALIZE_STATEMENT(m_stmt_list) + FINALIZE_STATEMENT(m_stmt_delete) +} + + +void MapDatabaseSQLite3::createDatabase() +{ + assert(m_database); // Pre-condition + + SQLOK(sqlite3_exec(m_database, + "CREATE TABLE IF NOT EXISTS `blocks` (\n" + " `pos` INT PRIMARY KEY,\n" + " `data` BLOB\n" + ");\n", + NULL, NULL, NULL), + "Failed to create database table"); +} + +void MapDatabaseSQLite3::initStatements() +{ PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1"); #ifdef __ANDROID__ PREPARE_STATEMENT(write, "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); @@ -189,18 +245,16 @@ void Database_SQLite3::verifyDatabase() PREPARE_STATEMENT(delete, "DELETE FROM `blocks` WHERE `pos` = ?"); PREPARE_STATEMENT(list, "SELECT `pos` FROM `blocks`"); - m_initialized = true; - verbosestream << "ServerMap: SQLite3 database opened." << std::endl; } -inline void Database_SQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index) +inline void MapDatabaseSQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index) { SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)), "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__)); } -bool Database_SQLite3::deleteBlock(const v3s16 &pos) +bool MapDatabaseSQLite3::deleteBlock(const v3s16 &pos) { verifyDatabase(); @@ -216,7 +270,7 @@ bool Database_SQLite3::deleteBlock(const v3s16 &pos) return good; } -bool Database_SQLite3::saveBlock(const v3s16 &pos, const std::string &data) +bool MapDatabaseSQLite3::saveBlock(const v3s16 &pos, const std::string &data) { verifyDatabase(); @@ -243,7 +297,7 @@ bool Database_SQLite3::saveBlock(const v3s16 &pos, const std::string &data) return true; } -void Database_SQLite3::loadBlock(const v3s16 &pos, std::string *block) +void MapDatabaseSQLite3::loadBlock(const v3s16 &pos, std::string *block) { verifyDatabase(); @@ -264,37 +318,312 @@ void Database_SQLite3::loadBlock(const v3s16 &pos, std::string *block) sqlite3_reset(m_stmt_read); } -void Database_SQLite3::createDatabase() +void MapDatabaseSQLite3::listAllLoadableBlocks(std::vector &dst) +{ + verifyDatabase(); + + while (sqlite3_step(m_stmt_list) == SQLITE_ROW) + dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0))); + + sqlite3_reset(m_stmt_list); +} + +/* + * Player Database + */ + +PlayerDatabaseSQLite3::PlayerDatabaseSQLite3(const std::string &savedir): + Database_SQLite3(savedir, "players"), + PlayerDatabase(), + m_stmt_player_load(NULL), + m_stmt_player_add(NULL), + m_stmt_player_update(NULL), + m_stmt_player_remove(NULL), + m_stmt_player_list(NULL), + m_stmt_player_load_inventory(NULL), + m_stmt_player_load_inventory_items(NULL), + m_stmt_player_add_inventory(NULL), + m_stmt_player_add_inventory_items(NULL), + m_stmt_player_remove_inventory(NULL), + m_stmt_player_remove_inventory_items(NULL), + m_stmt_player_metadata_load(NULL), + m_stmt_player_metadata_remove(NULL), + m_stmt_player_metadata_add(NULL) +{ + +} +PlayerDatabaseSQLite3::~PlayerDatabaseSQLite3() +{ + FINALIZE_STATEMENT(m_stmt_player_load) + FINALIZE_STATEMENT(m_stmt_player_add) + FINALIZE_STATEMENT(m_stmt_player_update) + FINALIZE_STATEMENT(m_stmt_player_remove) + FINALIZE_STATEMENT(m_stmt_player_list) + FINALIZE_STATEMENT(m_stmt_player_add_inventory) + FINALIZE_STATEMENT(m_stmt_player_add_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_remove_inventory) + FINALIZE_STATEMENT(m_stmt_player_remove_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_load_inventory) + FINALIZE_STATEMENT(m_stmt_player_load_inventory_items) + FINALIZE_STATEMENT(m_stmt_player_metadata_load) + FINALIZE_STATEMENT(m_stmt_player_metadata_add) + FINALIZE_STATEMENT(m_stmt_player_metadata_remove) +}; + + +void PlayerDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition + SQLOK(sqlite3_exec(m_database, - "CREATE TABLE IF NOT EXISTS `blocks` (\n" - " `pos` INT PRIMARY KEY,\n" - " `data` BLOB\n" - ");\n", + "CREATE TABLE IF NOT EXISTS `player` (" + "`name` VARCHAR(50) NOT NULL," + "`pitch` NUMERIC(11, 4) NOT NULL," + "`yaw` NUMERIC(11, 4) NOT NULL," + "`posX` NUMERIC(11, 4) NOT NULL," + "`posY` NUMERIC(11, 4) NOT NULL," + "`posZ` NUMERIC(11, 4) NOT NULL," + "`hp` INT NOT NULL," + "`breath` INT NOT NULL," + "`creation_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + "`modification_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`name`));", NULL, NULL, NULL), - "Failed to create database table"); + "Failed to create player table"); + + SQLOK(sqlite3_exec(m_database, + "CREATE TABLE IF NOT EXISTS `player_metadata` (" + " `player` VARCHAR(50) NOT NULL," + " `metadata` VARCHAR(256) NOT NULL," + " `value` TEXT," + " PRIMARY KEY(`player`, `metadata`)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player metadata table"); + + SQLOK(sqlite3_exec(m_database, + "CREATE TABLE IF NOT EXISTS `player_inventories` (" + " `player` VARCHAR(50) NOT NULL," + " `inv_id` INT NOT NULL," + " `inv_width` INT NOT NULL," + " `inv_name` TEXT NOT NULL DEFAULT ''," + " `inv_size` INT NOT NULL," + " PRIMARY KEY(player, inv_id)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player inventory table"); + + SQLOK(sqlite3_exec(m_database, + "CREATE TABLE `player_inventory_items` (" + " `player` VARCHAR(50) NOT NULL," + " `inv_id` INT NOT NULL," + " `slot_id` INT NOT NULL," + " `item` TEXT NOT NULL DEFAULT ''," + " PRIMARY KEY(player, inv_id, slot_id)," + " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", + NULL, NULL, NULL), + "Failed to create player inventory items table"); } -void Database_SQLite3::listAllLoadableBlocks(std::vector &dst) +void PlayerDatabaseSQLite3::initStatements() +{ + PREPARE_STATEMENT(player_load, "SELECT `pitch`, `yaw`, `posX`, `posY`, `posZ`, `hp`, " + "`breath`" + "FROM `player` WHERE `name` = ?") + PREPARE_STATEMENT(player_add, "INSERT INTO `player` (`name`, `pitch`, `yaw`, `posX`, " + "`posY`, `posZ`, `hp`, `breath`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + PREPARE_STATEMENT(player_update, "UPDATE `player` SET `pitch` = ?, `yaw` = ?, " + "`posX` = ?, `posY` = ?, `posZ` = ?, `hp` = ?, `breath` = ?, " + "`modification_date` = CURRENT_TIMESTAMP WHERE `name` = ?") + PREPARE_STATEMENT(player_remove, "DELETE FROM `player` WHERE `name` = ?") + PREPARE_STATEMENT(player_list, "SELECT `name` FROM `player`") + + PREPARE_STATEMENT(player_add_inventory, "INSERT INTO `player_inventories` " + "(`player`, `inv_id`, `inv_width`, `inv_name`, `inv_size`) VALUES (?, ?, ?, ?, ?)") + PREPARE_STATEMENT(player_add_inventory_items, "INSERT INTO `player_inventory_items` " + "(`player`, `inv_id`, `slot_id`, `item`) VALUES (?, ?, ?, ?)") + PREPARE_STATEMENT(player_remove_inventory, "DELETE FROM `player_inventories` " + "WHERE `player` = ?") + PREPARE_STATEMENT(player_remove_inventory_items, "DELETE FROM `player_inventory_items` " + "WHERE `player` = ?") + PREPARE_STATEMENT(player_load_inventory, "SELECT `inv_id`, `inv_width`, `inv_name`, " + "`inv_size` FROM `player_inventories` WHERE `player` = ? ORDER BY inv_id") + PREPARE_STATEMENT(player_load_inventory_items, "SELECT `slot_id`, `item` " + "FROM `player_inventory_items` WHERE `player` = ? AND `inv_id` = ?") + + PREPARE_STATEMENT(player_metadata_load, "SELECT `metadata`, `value` FROM " + "`player_metadata` WHERE `player` = ?") + PREPARE_STATEMENT(player_metadata_add, "INSERT INTO `player_metadata` " + "(`player`, `metadata`, `value`) VALUES (?, ?, ?)") + PREPARE_STATEMENT(player_metadata_remove, "DELETE FROM `player_metadata` " + "WHERE `player` = ?") + verbosestream << "ServerEnvironment: SQLite3 database opened (players)." << std::endl; +} + +bool PlayerDatabaseSQLite3::playerDataExists(const std::string &name) { verifyDatabase(); + str_to_sqlite(m_stmt_player_load, 1, name); + bool res = (sqlite3_step(m_stmt_player_load) == SQLITE_ROW); + sqlite3_reset(m_stmt_player_load); + return res; +} - while (sqlite3_step(m_stmt_list) == SQLITE_ROW) { - dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0))); +void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player) +{ + PlayerSAO* sao = player->getPlayerSAO(); + sanity_check(sao); + + const v3f &pos = sao->getBasePosition(); + // Begin save in brace is mandatory + if (!playerDataExists(player->getName())) { + beginSave(); + str_to_sqlite(m_stmt_player_add, 1, player->getName()); + double_to_sqlite(m_stmt_player_add, 2, sao->getPitch()); + double_to_sqlite(m_stmt_player_add, 3, sao->getYaw()); + double_to_sqlite(m_stmt_player_add, 4, pos.X); + double_to_sqlite(m_stmt_player_add, 5, pos.Y); + double_to_sqlite(m_stmt_player_add, 6, pos.Z); + int64_to_sqlite(m_stmt_player_add, 7, sao->getHP()); + int64_to_sqlite(m_stmt_player_add, 8, sao->getBreath()); + + sqlite3_vrfy(sqlite3_step(m_stmt_player_add), SQLITE_DONE); + sqlite3_reset(m_stmt_player_add); + } else { + beginSave(); + double_to_sqlite(m_stmt_player_update, 1, sao->getPitch()); + double_to_sqlite(m_stmt_player_update, 2, sao->getYaw()); + double_to_sqlite(m_stmt_player_update, 3, pos.X); + double_to_sqlite(m_stmt_player_update, 4, pos.Y); + double_to_sqlite(m_stmt_player_update, 5, pos.Z); + int64_to_sqlite(m_stmt_player_update, 6, sao->getHP()); + int64_to_sqlite(m_stmt_player_update, 7, sao->getBreath()); + str_to_sqlite(m_stmt_player_update, 8, player->getName()); + + sqlite3_vrfy(sqlite3_step(m_stmt_player_update), SQLITE_DONE); + sqlite3_reset(m_stmt_player_update); } - sqlite3_reset(m_stmt_list); + + // Write player inventories + str_to_sqlite(m_stmt_player_remove_inventory, 1, player->getName()); + sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory), SQLITE_DONE); + sqlite3_reset(m_stmt_player_remove_inventory); + + str_to_sqlite(m_stmt_player_remove_inventory_items, 1, player->getName()); + sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory_items), SQLITE_DONE); + sqlite3_reset(m_stmt_player_remove_inventory_items); + + std::vector inventory_lists = sao->getInventory()->getLists(); + for (u16 i = 0; i < inventory_lists.size(); i++) { + const InventoryList* list = inventory_lists[i]; + + str_to_sqlite(m_stmt_player_add_inventory, 1, player->getName()); + int_to_sqlite(m_stmt_player_add_inventory, 2, i); + int_to_sqlite(m_stmt_player_add_inventory, 3, list->getWidth()); + str_to_sqlite(m_stmt_player_add_inventory, 4, list->getName()); + int_to_sqlite(m_stmt_player_add_inventory, 5, list->getSize()); + sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory), SQLITE_DONE); + sqlite3_reset(m_stmt_player_add_inventory); + + for (u32 j = 0; j < list->getSize(); j++) { + std::ostringstream os; + list->getItem(j).serialize(os); + std::string itemStr = os.str(); + + str_to_sqlite(m_stmt_player_add_inventory_items, 1, player->getName()); + int_to_sqlite(m_stmt_player_add_inventory_items, 2, i); + int_to_sqlite(m_stmt_player_add_inventory_items, 3, j); + str_to_sqlite(m_stmt_player_add_inventory_items, 4, itemStr); + sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory_items), SQLITE_DONE); + sqlite3_reset(m_stmt_player_add_inventory_items); + } + } + + str_to_sqlite(m_stmt_player_metadata_remove, 1, player->getName()); + sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_remove), SQLITE_DONE); + sqlite3_reset(m_stmt_player_metadata_remove); + + const PlayerAttributes &attrs = sao->getExtendedAttributes(); + for (PlayerAttributes::const_iterator it = attrs.begin(); it != attrs.end(); ++it) { + str_to_sqlite(m_stmt_player_metadata_add, 1, player->getName()); + str_to_sqlite(m_stmt_player_metadata_add, 2, it->first); + str_to_sqlite(m_stmt_player_metadata_add, 3, it->second); + sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_add), SQLITE_DONE); + sqlite3_reset(m_stmt_player_metadata_add); + } + + endSave(); } -Database_SQLite3::~Database_SQLite3() +bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao) { - FINALIZE_STATEMENT(m_stmt_read) - FINALIZE_STATEMENT(m_stmt_write) - FINALIZE_STATEMENT(m_stmt_list) - FINALIZE_STATEMENT(m_stmt_begin) - FINALIZE_STATEMENT(m_stmt_end) - FINALIZE_STATEMENT(m_stmt_delete) + verifyDatabase(); - SQLOK_ERRSTREAM(sqlite3_close(m_database), "Failed to close database"); + str_to_sqlite(m_stmt_player_load, 1, player->getName()); + if (sqlite3_step(m_stmt_player_load) != SQLITE_ROW) { + sqlite3_reset(m_stmt_player_load); + return false; + } + sao->setPitch(sqlite_to_float(m_stmt_player_load, 0)); + sao->setYaw(sqlite_to_float(m_stmt_player_load, 1)); + sao->setBasePosition(sqlite_to_v3f(m_stmt_player_load, 2)); + sao->setHPRaw((s16) MYMIN(sqlite_to_int(m_stmt_player_load, 5), S16_MAX)); + sao->setBreath((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 6), U16_MAX), false); + sqlite3_reset(m_stmt_player_load); + + // Load inventory + str_to_sqlite(m_stmt_player_load_inventory, 1, player->getName()); + while (sqlite3_step(m_stmt_player_load_inventory) == SQLITE_ROW) { + InventoryList *invList = player->inventory.addList( + sqlite_to_string(m_stmt_player_load_inventory, 2), + sqlite_to_uint(m_stmt_player_load_inventory, 3)); + invList->setWidth(sqlite_to_uint(m_stmt_player_load_inventory, 1)); + + u32 invId = sqlite_to_uint(m_stmt_player_load_inventory, 0); + + str_to_sqlite(m_stmt_player_load_inventory_items, 1, player->getName()); + int_to_sqlite(m_stmt_player_load_inventory_items, 2, invId); + while (sqlite3_step(m_stmt_player_load_inventory_items) == SQLITE_ROW) { + const std::string itemStr = sqlite_to_string(m_stmt_player_load_inventory_items, 1); + if (itemStr.length() > 0) { + ItemStack stack; + stack.deSerialize(itemStr); + invList->addItem(sqlite_to_uint(m_stmt_player_load_inventory_items, 0), stack); + } + } + sqlite3_reset(m_stmt_player_load_inventory_items); + } + + sqlite3_reset(m_stmt_player_load_inventory); + + str_to_sqlite(m_stmt_player_metadata_load, 1, sao->getPlayer()->getName()); + while (sqlite3_step(m_stmt_player_metadata_load) == SQLITE_ROW) { + std::string attr = sqlite_to_string(m_stmt_player_metadata_load, 0); + std::string value = sqlite_to_string(m_stmt_player_metadata_load, 1); + + sao->setExtendedAttribute(attr, value); + } + sqlite3_reset(m_stmt_player_metadata_load); + return true; +} + +bool PlayerDatabaseSQLite3::removePlayer(const std::string &name) +{ + if (!playerDataExists(name)) + return false; + + str_to_sqlite(m_stmt_player_remove, 1, name); + sqlite3_vrfy(sqlite3_step(m_stmt_player_remove), SQLITE_DONE); + sqlite3_reset(m_stmt_player_remove); + return true; } +void PlayerDatabaseSQLite3::listPlayers(std::vector &res) +{ + verifyDatabase(); + + while (sqlite3_step(m_stmt_player_list) == SQLITE_ROW) + res.push_back(sqlite_to_string(m_stmt_player_list, 0)); + + sqlite3_reset(m_stmt_player_list); +} diff --git a/src/database-sqlite3.h b/src/database-sqlite3.h index 2ab4c8ee9..3244facc9 100644 --- a/src/database-sqlite3.h +++ b/src/database-sqlite3.h @@ -20,8 +20,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef DATABASE_SQLITE3_HEADER #define DATABASE_SQLITE3_HEADER +#include #include #include "database.h" +#include "exceptions.h" extern "C" { #include "sqlite3.h" @@ -30,37 +32,97 @@ extern "C" { class Database_SQLite3 : public Database { public: - Database_SQLite3(const std::string &savedir); - ~Database_SQLite3(); + virtual ~Database_SQLite3(); void beginSave(); void endSave(); - bool saveBlock(const v3s16 &pos, const std::string &data); - void loadBlock(const v3s16 &pos, std::string *block); - bool deleteBlock(const v3s16 &pos); - void listAllLoadableBlocks(std::vector &dst); bool initialized() const { return m_initialized; } +protected: + Database_SQLite3(const std::string &savedir, const std::string &dbname); -private: - // Open the database - void openDatabase(); - // Create the database structure - void createDatabase(); // Open and initialize the database if needed void verifyDatabase(); - void bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index = 1); + // Convertors + inline void str_to_sqlite(sqlite3_stmt *s, int iCol, const std::string &str) const + { + sqlite3_vrfy(sqlite3_bind_text(s, iCol, str.c_str(), str.size(), NULL)); + } + + inline void str_to_sqlite(sqlite3_stmt *s, int iCol, const char *str) const + { + sqlite3_vrfy(sqlite3_bind_text(s, iCol, str, strlen(str), NULL)); + } + + inline void int_to_sqlite(sqlite3_stmt *s, int iCol, int val) const + { + sqlite3_vrfy(sqlite3_bind_int(s, iCol, val)); + } + + inline void int64_to_sqlite(sqlite3_stmt *s, int iCol, s64 val) const + { + sqlite3_vrfy(sqlite3_bind_int64(s, iCol, (sqlite3_int64) val)); + } + + inline void double_to_sqlite(sqlite3_stmt *s, int iCol, double val) const + { + sqlite3_vrfy(sqlite3_bind_double(s, iCol, val)); + } + + inline std::string sqlite_to_string(sqlite3_stmt *s, int iCol) + { + const char* text = reinterpret_cast(sqlite3_column_text(s, iCol)); + return std::string(text ? text : ""); + } + + inline s32 sqlite_to_int(sqlite3_stmt *s, int iCol) + { + return sqlite3_column_int(s, iCol); + } + + inline u32 sqlite_to_uint(sqlite3_stmt *s, int iCol) + { + return (u32) sqlite3_column_int(s, iCol); + } + + inline float sqlite_to_float(sqlite3_stmt *s, int iCol) + { + return (float) sqlite3_column_double(s, iCol); + } + + inline const v3f sqlite_to_v3f(sqlite3_stmt *s, int iCol) + { + return v3f(sqlite_to_float(s, iCol), sqlite_to_float(s, iCol + 1), + sqlite_to_float(s, iCol + 2)); + } + + // Query verifiers helpers + inline void sqlite3_vrfy(int s, const std::string &m = "", int r = SQLITE_OK) const + { + if (s != r) + throw DatabaseException(m + ": " + sqlite3_errmsg(m_database)); + } + + inline void sqlite3_vrfy(const int s, const int r, const std::string &m = "") const + { + sqlite3_vrfy(s, m, r); + } + + // Create the database structure + virtual void createDatabase() = 0; + virtual void initStatements() = 0; + + sqlite3 *m_database; +private: + // Open the database + void openDatabase(); bool m_initialized; std::string m_savedir; + std::string m_dbname; - sqlite3 *m_database; - sqlite3_stmt *m_stmt_read; - sqlite3_stmt *m_stmt_write; - sqlite3_stmt *m_stmt_list; - sqlite3_stmt *m_stmt_delete; sqlite3_stmt *m_stmt_begin; sqlite3_stmt *m_stmt_end; @@ -69,4 +131,66 @@ private: static int busyHandler(void *data, int count); }; +class MapDatabaseSQLite3 : private Database_SQLite3, public MapDatabase +{ +public: + MapDatabaseSQLite3(const std::string &savedir); + virtual ~MapDatabaseSQLite3(); + + bool saveBlock(const v3s16 &pos, const std::string &data); + void loadBlock(const v3s16 &pos, std::string *block); + bool deleteBlock(const v3s16 &pos); + void listAllLoadableBlocks(std::vector &dst); + + void beginSave() { Database_SQLite3::beginSave(); } + void endSave() { Database_SQLite3::endSave(); } +protected: + virtual void createDatabase(); + virtual void initStatements(); + +private: + void bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index = 1); + + // Map + sqlite3_stmt *m_stmt_read; + sqlite3_stmt *m_stmt_write; + sqlite3_stmt *m_stmt_list; + sqlite3_stmt *m_stmt_delete; +}; + +class PlayerDatabaseSQLite3 : private Database_SQLite3, public PlayerDatabase +{ +public: + PlayerDatabaseSQLite3(const std::string &savedir); + virtual ~PlayerDatabaseSQLite3(); + + void savePlayer(RemotePlayer *player); + bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); + bool removePlayer(const std::string &name); + void listPlayers(std::vector &res); + +protected: + virtual void createDatabase(); + virtual void initStatements(); + +private: + bool playerDataExists(const std::string &name); + + // Players + sqlite3_stmt *m_stmt_player_load; + sqlite3_stmt *m_stmt_player_add; + sqlite3_stmt *m_stmt_player_update; + sqlite3_stmt *m_stmt_player_remove; + sqlite3_stmt *m_stmt_player_list; + sqlite3_stmt *m_stmt_player_load_inventory; + sqlite3_stmt *m_stmt_player_load_inventory_items; + sqlite3_stmt *m_stmt_player_add_inventory; + sqlite3_stmt *m_stmt_player_add_inventory_items; + sqlite3_stmt *m_stmt_player_remove_inventory; + sqlite3_stmt *m_stmt_player_remove_inventory_items; + sqlite3_stmt *m_stmt_player_metadata_load; + sqlite3_stmt *m_stmt_player_metadata_remove; + sqlite3_stmt *m_stmt_player_metadata_add; +}; + #endif diff --git a/src/database.cpp b/src/database.cpp index 262d475ec..8e1483893 100644 --- a/src/database.cpp +++ b/src/database.cpp @@ -48,7 +48,7 @@ static inline s64 pythonmodulo(s64 i, s16 mod) } -s64 Database::getBlockAsInteger(const v3s16 &pos) +s64 MapDatabase::getBlockAsInteger(const v3s16 &pos) { return (u64) pos.Z * 0x1000000 + (u64) pos.Y * 0x1000 + @@ -56,7 +56,7 @@ s64 Database::getBlockAsInteger(const v3s16 &pos) } -v3s16 Database::getIntegerAsBlock(s64 i) +v3s16 MapDatabase::getIntegerAsBlock(s64 i) { v3s16 pos; pos.X = unsigned_to_signed(pythonmodulo(i, 4096), 2048); diff --git a/src/database.h b/src/database.h index 7213f088a..5a2b844fd 100644 --- a/src/database.h +++ b/src/database.h @@ -29,10 +29,15 @@ with this program; if not, write to the Free Software Foundation, Inc., class Database { public: - virtual ~Database() {} + virtual void beginSave() = 0; + virtual void endSave() = 0; + virtual bool initialized() const { return true; } +}; - virtual void beginSave() {} - virtual void endSave() {} +class MapDatabase : public Database +{ +public: + virtual ~MapDatabase() {} virtual bool saveBlock(const v3s16 &pos, const std::string &data) = 0; virtual void loadBlock(const v3s16 &pos, std::string *block) = 0; @@ -42,8 +47,19 @@ public: static v3s16 getIntegerAsBlock(s64 i); virtual void listAllLoadableBlocks(std::vector &dst) = 0; +}; - virtual bool initialized() const { return true; } +class PlayerSAO; +class RemotePlayer; + +class PlayerDatabase +{ +public: + virtual ~PlayerDatabase() {} + virtual void savePlayer(RemotePlayer *player) = 0; + virtual bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) = 0; + virtual bool removePlayer(const std::string &name) = 0; + virtual void listPlayers(std::vector &res) = 0; }; #endif diff --git a/src/main.cpp b/src/main.cpp index 1ec278981..2ad4e2780 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,6 +47,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #endif #ifndef SERVER #include "client/clientlauncher.h" + #endif #ifdef HAVE_TOUCHSCREENGUI @@ -102,7 +103,7 @@ static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_a static bool determine_subgame(GameParams *game_params); static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args); -static bool migrate_database(const GameParams &game_params, const Settings &cmd_args); +static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args); /**********************************************************************/ @@ -292,6 +293,8 @@ static void set_allowed_options(OptionList *allowed_options) _("Set gameid (\"--gameid list\" prints available ones)")))); allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING, _("Migrate from current map backend to another (Only works when using minetestserver or with --server)")))); + allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING, + _("Migrate from current players backend to another (Only works when using minetestserver or with --server)")))); allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG, _("Feature an interactive terminal (Only works when using minetestserver or with --server)")))); #ifndef SERVER @@ -332,7 +335,7 @@ static void print_allowed_options(const OptionList &allowed_options) if (i->second.type != VALUETYPE_FLAG) os1 << _(" "); - std::cout << padStringRight(os1.str(), 24); + std::cout << padStringRight(os1.str(), 30); if (i->second.help != NULL) std::cout << i->second.help; @@ -828,7 +831,9 @@ static bool run_dedicated_server(const GameParams &game_params, const Settings & // Database migration if (cmd_args.exists("migrate")) - return migrate_database(game_params, cmd_args); + return migrate_map_database(game_params, cmd_args); + else if (cmd_args.exists("migrate-players")) + return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args); if (cmd_args.exists("terminal")) { #if USE_CURSES @@ -912,7 +917,7 @@ static bool run_dedicated_server(const GameParams &game_params, const Settings & return true; } -static bool migrate_database(const GameParams &game_params, const Settings &cmd_args) +static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate"); Settings world_mt; @@ -921,20 +926,23 @@ static bool migrate_database(const GameParams &game_params, const Settings &cmd_ errorstream << "Cannot read world.mt!" << std::endl; return false; } + if (!world_mt.exists("backend")) { errorstream << "Please specify your current backend in world.mt:" << std::endl - << " backend = {sqlite3|leveldb|redis|dummy}" + << " backend = {sqlite3|leveldb|redis|dummy|postgresql}" << std::endl; return false; } + std::string backend = world_mt.get("backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" << " as the old one" << std::endl; return false; } - Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt), + + MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt), *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt); u32 count = 0; @@ -976,4 +984,3 @@ static bool migrate_database(const GameParams &game_params, const Settings &cmd_ return true; } - diff --git a/src/map.cpp b/src/map.cpp index 75dcee350..c148c51f1 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -2286,13 +2286,13 @@ bool ServerMap::loadSectorFull(v2s16 p2d) } #endif -Database *ServerMap::createDatabase( +MapDatabase *ServerMap::createDatabase( const std::string &name, const std::string &savedir, Settings &conf) { if (name == "sqlite3") - return new Database_SQLite3(savedir); + return new MapDatabaseSQLite3(savedir); if (name == "dummy") return new Database_Dummy(); #if USE_LEVELDB @@ -2304,8 +2304,11 @@ Database *ServerMap::createDatabase( return new Database_Redis(conf); #endif #if USE_POSTGRESQL - else if (name == "postgresql") - return new Database_PostgreSQL(conf); + else if (name == "postgresql") { + std::string connect_string = ""; + conf.getNoEx("pgsql_connection", connect_string); + return new MapDatabasePostgreSQL(connect_string); + } #endif else throw BaseException(std::string("Database backend ") + name + " not supported."); @@ -2326,7 +2329,7 @@ bool ServerMap::saveBlock(MapBlock *block) return saveBlock(block, dbase); } -bool ServerMap::saveBlock(MapBlock *block, Database *db) +bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db) { v3s16 p3d = block->getPos(); diff --git a/src/map.h b/src/map.h index 4d7079823..7e597bef6 100644 --- a/src/map.h +++ b/src/map.h @@ -37,7 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "map_settings_manager.h" class Settings; -class Database; +class MapDatabase; class ClientMap; class MapSector; class ServerMapSector; @@ -430,7 +430,7 @@ public: /* Database functions */ - static Database *createDatabase(const std::string &name, const std::string &savedir, Settings &conf); + static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf); // Returns true if the database file does not exist bool loadFromFolders(); @@ -458,7 +458,7 @@ public: bool loadSectorMeta(v2s16 p2d); bool saveBlock(MapBlock *block); - static bool saveBlock(MapBlock *block, Database *db); + static bool saveBlock(MapBlock *block, MapDatabase *db); // This will generate a sector with getSector if not found. void loadBlock(const std::string §ordir, const std::string &blockfile, MapSector *sector, bool save_after_load=false); @@ -510,7 +510,7 @@ private: This is reset to false when written on disk. */ bool m_map_metadata_changed; - Database *dbase; + MapDatabase *dbase; }; diff --git a/src/remoteplayer.cpp b/src/remoteplayer.cpp index c8e5b9132..2dbfe9d9d 100644 --- a/src/remoteplayer.cpp +++ b/src/remoteplayer.cpp @@ -67,54 +67,6 @@ RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef): movement_gravity = g_settings->getFloat("movement_gravity") * BS; } -void RemotePlayer::save(std::string savedir, IGameDef *gamedef) -{ - /* - * We have to open all possible player files in the players directory - * and check their player names because some file systems are not - * case-sensitive and player names are case-sensitive. - */ - - // A player to deserialize files into to check their names - RemotePlayer testplayer("", gamedef->idef()); - - savedir += DIR_DELIM; - std::string path = savedir + m_name; - for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { - if (!fs::PathExists(path)) { - // Open file and serialize - std::ostringstream ss(std::ios_base::binary); - serialize(ss); - if (!fs::safeWriteToFile(path, ss.str())) { - infostream << "Failed to write " << path << std::endl; - } - setModified(false); - return; - } - // Open file and deserialize - std::ifstream is(path.c_str(), std::ios_base::binary); - if (!is.good()) { - infostream << "Failed to open " << path << std::endl; - return; - } - testplayer.deSerialize(is, path, NULL); - is.close(); - if (strcmp(testplayer.getName(), m_name) == 0) { - // Open file and serialize - std::ostringstream ss(std::ios_base::binary); - serialize(ss); - if (!fs::safeWriteToFile(path, ss.str())) { - infostream << "Failed to write " << path << std::endl; - } - setModified(false); - return; - } - path = savedir + m_name + itos(i); - } - - infostream << "Didn't find free file for player " << m_name << std::endl; -} - void RemotePlayer::serializeExtraAttributes(std::string &output) { assert(m_sao); diff --git a/src/remoteplayer.h b/src/remoteplayer.h index 9d123393f..ce7db5608 100644 --- a/src/remoteplayer.h +++ b/src/remoteplayer.h @@ -37,11 +37,11 @@ enum RemotePlayerChatResult */ class RemotePlayer : public Player { + friend class PlayerDatabaseFiles; public: RemotePlayer(const char *name, IItemDefManager *idef); virtual ~RemotePlayer() {} - void save(std::string savedir, IGameDef *gamedef); void deSerialize(std::istream &is, const std::string &playername, PlayerSAO *sao); PlayerSAO *getPlayerSAO() { return m_sao; } diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index 6ac4bb653..d94f3e31d 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -334,6 +334,22 @@ int ModApiServer::l_kick_player(lua_State *L) return 1; } +int ModApiServer::l_remove_player(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + std::string name = luaL_checkstring(L, 1); + ServerEnvironment *s_env = dynamic_cast(getEnv(L)); + assert(s_env); + + RemotePlayer *player = s_env->getPlayer(name.c_str()); + if (!player) + lua_pushinteger(L, s_env->removePlayerFromDatabase(name) ? 0 : 1); + else + lua_pushinteger(L, 2); + + return 1; +} + // unban_player_or_ip() int ModApiServer::l_unban_player_or_ip(lua_State *L) { @@ -510,6 +526,7 @@ void ModApiServer::Initialize(lua_State *L, int top) API_FCT(get_ban_description); API_FCT(ban_player); API_FCT(kick_player); + API_FCT(remove_player); API_FCT(unban_player_or_ip); API_FCT(notify_authentication_modified); diff --git a/src/script/lua_api/l_server.h b/src/script/lua_api/l_server.h index 008810784..e6c0df978 100644 --- a/src/script/lua_api/l_server.h +++ b/src/script/lua_api/l_server.h @@ -92,6 +92,9 @@ private: // kick_player(name, [message]) -> success static int l_kick_player(lua_State *L); + // remove_player(name) + static int l_remove_player(lua_State *L); + // notify_authentication_modified(name) static int l_notify_authentication_modified(lua_State *L); diff --git a/src/server.cpp b/src/server.cpp index ac6265d09..4c7e60286 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -60,6 +60,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/base64.h" #include "util/sha1.h" #include "util/hex.h" +#include "database.h" class ClientNotFoundException : public BaseException { @@ -2618,9 +2619,8 @@ void Server::RespawnPlayer(u16 peer_id) bool repositioned = m_script->on_respawnplayer(playersao); if (!repositioned) { - v3f pos = findSpawnPos(); // setPos will send the new position to client - playersao->setPos(pos); + playersao->setPos(findSpawnPos()); } SendPlayerHP(peer_id); @@ -3442,8 +3442,8 @@ v3f Server::findSpawnPos() s32 range = 1 + i; // We're going to try to throw the player to this position v2s16 nodepos2d = v2s16( - -range + (myrand() % (range * 2)), - -range + (myrand() % (range * 2))); + -range + (myrand() % (range * 2)), + -range + (myrand() % (range * 2))); // Get spawn level at point s16 spawn_level = m_emerge->getSpawnLevelAtPoint(nodepos2d); @@ -3516,8 +3516,6 @@ void Server::requestShutdown(const std::string &msg, bool reconnect, float delay PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id, u16 proto_version) { - bool newplayer = false; - /* Try to get an existing player */ @@ -3538,44 +3536,18 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id, u16 proto_version return NULL; } - // Create a new player active object - PlayerSAO *playersao = new PlayerSAO(m_env, peer_id, isSingleplayer()); - player = m_env->loadPlayer(name, playersao); - - // Create player if it doesn't exist if (!player) { - newplayer = true; - player = new RemotePlayer(name, this->idef()); - // Set player position - infostream<<"Server: Finding spawn place for player \"" - <setBasePosition(findSpawnPos()); - - // Make sure the player is saved - player->setModified(true); - - // Add player to environment - m_env->addPlayer(player); - } else { - // If the player exists, ensure that they respawn inside legal bounds - // This fixes an assert crash when the player can't be added - // to the environment - if (objectpos_over_limit(playersao->getBasePosition())) { - actionstream << "Respawn position for player \"" - << name << "\" outside limits, resetting" << std::endl; - playersao->setBasePosition(findSpawnPos()); - } + player = new RemotePlayer(name, idef()); } - playersao->initialize(player, getPlayerEffectivePrivs(player->getName())); - - player->protocol_version = proto_version; + bool newplayer = false; - /* Clean up old HUD elements from previous sessions */ - player->clearHud(); + // Load player + PlayerSAO *playersao = m_env->loadPlayer(player, &newplayer, peer_id, isSingleplayer()); - /* Add object to environment */ - m_env->addActiveObject(playersao); + // Complete init with server parts + playersao->finalize(player, getPlayerEffectivePrivs(player->getName())); + player->protocol_version = proto_version; /* Run scripts */ if (newplayer) { diff --git a/src/server.h b/src/server.h index 4183bcda1..948fb8fc2 100644 --- a/src/server.h +++ b/src/server.h @@ -306,6 +306,7 @@ public: bool showFormspec(const char *name, const std::string &formspec, const std::string &formname); Map & getMap() { return m_env->getMap(); } ServerEnvironment & getEnv() { return *m_env; } + v3f findSpawnPos(); u32 hudAdd(RemotePlayer *player, HudElement *element); bool hudRemove(RemotePlayer *player, u32 id); @@ -472,8 +473,6 @@ private: RemotePlayer *player = NULL); void handleAdminChat(const ChatEventChat *evt); - v3f findSpawnPos(); - // When called, connection mutex should be locked RemoteClient* getClient(u16 peer_id,ClientState state_min=CS_Active); RemoteClient* getClientNoEx(u16 peer_id,ClientState state_min=CS_Active); diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index e09c7da16..c0dc0e0ea 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -36,6 +36,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/pointedthing.h" #include "threading/mutex_auto_lock.h" #include "filesys.h" +#include "gameparams.h" +#include "database-dummy.h" +#include "database-files.h" +#include "database-sqlite3.h" +#if USE_POSTGRESQL +#include "database-postgresql.h" +#endif #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:" @@ -365,8 +372,30 @@ ServerEnvironment::ServerEnvironment(ServerMap *map, m_game_time_fraction_counter(0), m_last_clear_objects_time(0), m_recommended_send_interval(0.1), - m_max_lag_estimate(0.1) + m_max_lag_estimate(0.1), + m_player_database(NULL) { + // Determine which database backend to use + std::string conf_path = path_world + DIR_DELIM + "world.mt"; + Settings conf; + bool succeeded = conf.readConfigFile(conf_path.c_str()); + if (!succeeded || !conf.exists("player_backend")) { + // fall back to files + conf.set("player_backend", "files"); + warningstream << "/!\\ You are using old player file backend. " + << "This backend is deprecated and will be removed in next release /!\\" + << std::endl << "Switching to SQLite3 or PostgreSQL is advised, " + << "please read http://wiki.minetest.net/Database_backends." << std::endl; + + if (!conf.updateConfigFile(conf_path.c_str())) { + errorstream << "ServerEnvironment::ServerEnvironment(): " + << "Failed to update world.mt!" << std::endl; + } + } + + std::string name = ""; + conf.getNoEx("player_backend", name); + m_player_database = openPlayerDatabase(name, path_world, conf); } ServerEnvironment::~ServerEnvironment() @@ -392,6 +421,8 @@ ServerEnvironment::~ServerEnvironment() i != m_players.end(); ++i) { delete (*i); } + + delete m_player_database; } Map & ServerEnvironment::getMap() @@ -455,6 +486,11 @@ void ServerEnvironment::removePlayer(RemotePlayer *player) } } +bool ServerEnvironment::removePlayerFromDatabase(const std::string &name) +{ + return m_player_database->removePlayer(name); +} + bool ServerEnvironment::line_of_sight(v3f pos1, v3f pos2, float stepsize, v3s16 *p) { float distance = pos1.getDistanceFrom(pos2); @@ -495,7 +531,7 @@ void ServerEnvironment::kickAllPlayers(AccessDeniedCode reason, void ServerEnvironment::saveLoadedPlayers() { - std::string players_path = m_path_world + DIR_DELIM "players"; + std::string players_path = m_path_world + DIR_DELIM + "players"; fs::CreateDir(players_path); for (std::vector::iterator it = m_players.begin(); @@ -503,63 +539,63 @@ void ServerEnvironment::saveLoadedPlayers() ++it) { if ((*it)->checkModified() || ((*it)->getPlayerSAO() && (*it)->getPlayerSAO()->extendedAttributesModified())) { - (*it)->save(players_path, m_server); + try { + m_player_database->savePlayer(*it); + } catch (DatabaseException &e) { + errorstream << "Failed to save player " << (*it)->getName() << " exception: " + << e.what() << std::endl; + throw; + } } } } void ServerEnvironment::savePlayer(RemotePlayer *player) { - std::string players_path = m_path_world + DIR_DELIM "players"; - fs::CreateDir(players_path); - - player->save(players_path, m_server); + try { + m_player_database->savePlayer(player); + } catch (DatabaseException &e) { + errorstream << "Failed to save player " << player->getName() << " exception: " + << e.what() << std::endl; + throw; + } } -RemotePlayer *ServerEnvironment::loadPlayer(const std::string &playername, PlayerSAO *sao) +PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player, + u16 peer_id, bool is_singleplayer) { - bool newplayer = false; - bool found = false; - std::string players_path = m_path_world + DIR_DELIM "players" DIR_DELIM; - std::string path = players_path + playername; - - RemotePlayer *player = getPlayer(playername.c_str()); - if (!player) { - player = new RemotePlayer("", m_server->idef()); - newplayer = true; - } - - for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { - //// Open file and deserialize - std::ifstream is(path.c_str(), std::ios_base::binary); - if (!is.good()) - continue; - - player->deSerialize(is, path, sao); - is.close(); - - if (player->getName() == playername) { - found = true; - break; + PlayerSAO *playersao = new PlayerSAO(this, player, peer_id, is_singleplayer); + // Create player if it doesn't exist + if (!m_player_database->loadPlayer(player, playersao)) { + *new_player = true; + // Set player position + infostream << "Server: Finding spawn place for player \"" + << player->getName() << "\"" << std::endl; + playersao->setBasePosition(m_server->findSpawnPos()); + + // Make sure the player is saved + player->setModified(true); + } else { + // If the player exists, ensure that they respawn inside legal bounds + // This fixes an assert crash when the player can't be added + // to the environment + if (objectpos_over_limit(playersao->getBasePosition())) { + actionstream << "Respawn position for player \"" + << player->getName() << "\" outside limits, resetting" << std::endl; + playersao->setBasePosition(m_server->findSpawnPos()); } - - path = players_path + playername + itos(i); } - if (!found) { - infostream << "Player file for player " << playername - << " not found" << std::endl; - if (newplayer) - delete player; + // Add player to environment + addPlayer(player); - return NULL; - } + /* Clean up old HUD elements from previous sessions */ + player->clearHud(); - if (newplayer) { - addPlayer(player); - } - player->setModified(false); - return player; + /* Add object to environment */ + addActiveObject(playersao); + + return playersao; } void ServerEnvironment::saveMeta() @@ -2173,3 +2209,111 @@ void ServerEnvironment::deactivateFarObjects(bool _force_delete) m_active_objects.erase(*i); } } + +PlayerDatabase *ServerEnvironment::openPlayerDatabase(const std::string &name, + const std::string &savedir, const Settings &conf) +{ + + if (name == "sqlite3") + return new PlayerDatabaseSQLite3(savedir); + else if (name == "dummy") + return new Database_Dummy(); +#if USE_POSTGRESQL + else if (name == "postgresql") { + std::string connect_string = ""; + conf.getNoEx("pgsql_player_connection", connect_string); + return new PlayerDatabasePostgreSQL(connect_string); + } +#endif + else if (name == "files") + return new PlayerDatabaseFiles(savedir + DIR_DELIM + "players"); + else + throw BaseException(std::string("Database backend ") + name + " not supported."); +} + +bool ServerEnvironment::migratePlayersDatabase(const GameParams &game_params, + const Settings &cmd_args) +{ + std::string migrate_to = cmd_args.get("migrate-players"); + Settings world_mt; + std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt"; + if (!world_mt.readConfigFile(world_mt_path.c_str())) { + errorstream << "Cannot read world.mt!" << std::endl; + return false; + } + + if (!world_mt.exists("player_backend")) { + errorstream << "Please specify your current backend in world.mt:" + << std::endl + << " player_backend = {files|sqlite3|postgresql}" + << std::endl; + return false; + } + + std::string backend = world_mt.get("player_backend"); + if (backend == migrate_to) { + errorstream << "Cannot migrate: new backend is same" + << " as the old one" << std::endl; + return false; + } + + const std::string players_backup_path = game_params.world_path + DIR_DELIM + + "players.bak"; + + if (backend == "files") { + // Create backup directory + fs::CreateDir(players_backup_path); + } + + try { + PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase(backend, + game_params.world_path, world_mt); + PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase(migrate_to, + game_params.world_path, world_mt); + + std::vector player_list; + srcdb->listPlayers(player_list); + for (std::vector::const_iterator it = player_list.begin(); + it != player_list.end(); ++it) { + actionstream << "Migrating player " << it->c_str() << std::endl; + RemotePlayer player(it->c_str(), NULL); + PlayerSAO playerSAO(NULL, &player, 15000, false); + + srcdb->loadPlayer(&player, &playerSAO); + + playerSAO.finalize(&player, std::set()); + player.setPlayerSAO(&playerSAO); + + dstdb->savePlayer(&player); + + // For files source, move player files to backup dir + if (backend == "files") { + fs::Rename( + game_params.world_path + DIR_DELIM + "players" + DIR_DELIM + (*it), + players_backup_path + DIR_DELIM + (*it)); + } + } + + actionstream << "Successfully migrated " << player_list.size() << " players" + << std::endl; + world_mt.set("player_backend", migrate_to); + if (!world_mt.updateConfigFile(world_mt_path.c_str())) + errorstream << "Failed to update world.mt!" << std::endl; + else + actionstream << "world.mt updated" << std::endl; + + // When migration is finished from file backend, remove players directory if empty + if (backend == "files") { + fs::DeleteSingleFileOrEmptyDirectory(game_params.world_path + DIR_DELIM + + "players"); + } + + delete srcdb; + delete dstdb; + + } catch (BaseException &e) { + errorstream << "An error occured during migration: " << e.what() << std::endl; + return false; + } + return true; +} diff --git a/src/serverenvironment.h b/src/serverenvironment.h index 99110542a..0e31aa41a 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -27,7 +27,9 @@ with this program; if not, write to the Free Software Foundation, Inc., class IGameDef; class ServerMap; +struct GameParams; class RemotePlayer; +class PlayerDatabase; class PlayerSAO; class ServerEnvironment; class ActiveBlockModifier; @@ -217,9 +219,11 @@ public: // Save players void saveLoadedPlayers(); void savePlayer(RemotePlayer *player); - RemotePlayer *loadPlayer(const std::string &playername, PlayerSAO *sao); + PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, u16 peer_id, + bool is_singleplayer); void addPlayer(RemotePlayer *player); void removePlayer(RemotePlayer *player); + bool removePlayerFromDatabase(const std::string &name); /* Save and load time of day and game timer @@ -334,8 +338,13 @@ public: RemotePlayer *getPlayer(const u16 peer_id); RemotePlayer *getPlayer(const char* name); + + static bool migratePlayersDatabase(const GameParams &game_params, + const Settings &cmd_args); private: + static PlayerDatabase *openPlayerDatabase(const std::string &name, + const std::string &savedir, const Settings &conf); /* Internal ActiveObject interface ------------------------------------------- @@ -419,6 +428,8 @@ private: // peer_ids in here should be unique, except that there may be many 0s std::vector m_players; + PlayerDatabase *m_player_database; + // Particles IntervalLimiter m_particle_management_interval; UNORDERED_MAP m_particle_spawners; diff --git a/src/unittest/test_player.cpp b/src/unittest/test_player.cpp index b639878b2..e2b1cd855 100644 --- a/src/unittest/test_player.cpp +++ b/src/unittest/test_player.cpp @@ -31,59 +31,10 @@ public: const char *getName() { return "TestPlayer"; } void runTests(IGameDef *gamedef); - - void testSave(IGameDef *gamedef); - void testLoad(IGameDef *gamedef); }; static TestPlayer g_test_instance; void TestPlayer::runTests(IGameDef *gamedef) { - TEST(testSave, gamedef); - TEST(testLoad, gamedef); -} - -void TestPlayer::testSave(IGameDef *gamedef) -{ - RemotePlayer rplayer("testplayer_save", gamedef->idef()); - PlayerSAO sao(NULL, 1, false); - sao.initialize(&rplayer, std::set()); - rplayer.setPlayerSAO(&sao); - sao.setBreath(10, false); - sao.setHPRaw(8); - sao.setYaw(0.1f); - sao.setPitch(0.6f); - sao.setBasePosition(v3f(450.2f, -15.7f, 68.1f)); - rplayer.save(".", gamedef); - UASSERT(fs::PathExists("testplayer_save")); -} - -void TestPlayer::testLoad(IGameDef *gamedef) -{ - RemotePlayer rplayer("testplayer_load", gamedef->idef()); - PlayerSAO sao(NULL, 1, false); - sao.initialize(&rplayer, std::set()); - rplayer.setPlayerSAO(&sao); - sao.setBreath(10, false); - sao.setHPRaw(8); - sao.setYaw(0.1f); - sao.setPitch(0.6f); - sao.setBasePosition(v3f(450.2f, -15.7f, 68.1f)); - rplayer.save(".", gamedef); - UASSERT(fs::PathExists("testplayer_load")); - - RemotePlayer rplayer_load("testplayer_load", gamedef->idef()); - PlayerSAO sao_load(NULL, 2, false); - std::ifstream is("testplayer_load", std::ios_base::binary); - UASSERT(is.good()); - rplayer_load.deSerialize(is, "testplayer_load", &sao_load); - is.close(); - - UASSERT(strcmp(rplayer_load.getName(), "testplayer_load") == 0); - UASSERT(sao_load.getBreath() == 10); - UASSERT(sao_load.getHP() == 8); - UASSERT(sao_load.getYaw() == 0.1f); - UASSERT(sao_load.getPitch() == 0.6f); - UASSERT(sao_load.getBasePosition() == v3f(450.2f, -15.7f, 68.1f)); } -- cgit v1.2.3 From f727f54192644f6427ac1b2c86df8c64c7c5fdf0 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Sat, 29 Apr 2017 14:36:55 +0200 Subject: Fix Travis/unittest broken since b662a45 --- src/client.cpp | 4 ++-- src/network/connection.cpp | 15 ++++++++------- src/network/connection.h | 2 +- src/unittest/test_connection.cpp | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) (limited to 'src/unittest') diff --git a/src/client.cpp b/src/client.cpp index 43b58d819..48ebd2f2c 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -769,7 +769,7 @@ void Client::initLocalMapSaving(const Address &address, void Client::ReceiveAll() { DSTACK(FUNCTION_NAME); - u32 start_ms = porting::getTimeMs(); + u64 start_ms = porting::getTimeMs(); for(;;) { // Limit time even if there would be huge amounts of data to @@ -1631,7 +1631,7 @@ void texture_update_progress(void *args, u32 progress, u32 max_progress) // update the loading menu -- if neccessary bool do_draw = false; - u32 time_ms = targs->last_time_ms; + u64 time_ms = targs->last_time_ms; if (cur_percent != targs->last_percent) { targs->last_percent = cur_percent; time_ms = porting::getTimeMs(); diff --git a/src/network/connection.cpp b/src/network/connection.cpp index f9a4821a6..fb3ba92ae 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -54,7 +54,8 @@ Mutex log_message_mutex; #endif -static inline float CALC_DTIME(unsigned int lasttime, unsigned int curtime) { +static inline float CALC_DTIME(u64 lasttime, u64 curtime) +{ float value = ( curtime - lasttime) / 1000.0; return MYMAX(MYMIN(value,0.1),0.0); } @@ -981,7 +982,7 @@ void Peer::RTTStatistics(float rtt, const std::string &profiler_id, bool Peer::isTimedOut(float timeout) { MutexAutoLock lock(m_exclusive_access_mutex); - u32 current_time = porting::getTimeMs(); + u64 current_time = porting::getTimeMs(); float dtime = CALC_DTIME(m_last_timeout_check,current_time); m_last_timeout_check = current_time; @@ -1276,8 +1277,8 @@ void * ConnectionSendThread::run() LOG(dout_con<getDesc() <<"ConnectionSend thread started"<getDesc() << "]"); @@ -2046,8 +2047,8 @@ void * ConnectionReceiveThread::run() PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]"); #ifdef DEBUG_CONNECTION_KBPS - u32 curtime = porting::getTimeMs(); - u32 lasttime = curtime; + u64 curtime = porting::getTimeMs(); + u64 lasttime = curtime; float debug_print_timer = 0.0; #endif @@ -2390,7 +2391,7 @@ SharedBuffer ConnectionReceiveThread::processPacket(Channel *channel, // only calculate rtt from straight sent packets if (p.resend_count == 0) { // Get round trip time - unsigned int current_time = porting::getTimeMs(); + u64 current_time = porting::getTimeMs(); // a overflow is quite unlikely but as it'd result in major // rtt miscalculation we handle it here diff --git a/src/network/connection.h b/src/network/connection.h index dc86d2293..3a8388522 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -175,7 +175,7 @@ struct BufferedPacket Buffer data; // Data of the packet, including headers float time; // Seconds from buffering the packet or re-sending float totaltime; // Seconds from buffering the packet - unsigned int absolute_send_time; + u64 absolute_send_time; Address address; // Sender or destination unsigned int resend_count; }; diff --git a/src/unittest/test_connection.cpp b/src/unittest/test_connection.cpp index 49e412fc8..d63322d69 100644 --- a/src/unittest/test_connection.cpp +++ b/src/unittest/test_connection.cpp @@ -305,7 +305,7 @@ void TestConnection::testConnectSendReceive() u16 peer_id = 132; u16 size = 0; bool received = false; - u32 timems0 = porting::getTimeMs(); + u64 timems0 = porting::getTimeMs(); for (;;) { if (porting::getTimeMs() - timems0 > 5000 || received) break; -- cgit v1.2.3 From 77597c4ff3b666cc37dd257952938df48d7e6f09 Mon Sep 17 00:00:00 2001 From: ShadowNinja Date: Mon, 6 Jul 2015 12:53:30 -0400 Subject: Clean up numeric.h and split FacePositionCache from it I also optiized FacePositionCache a bit: I removed a map lookup and vector copy from both branches of getFacePosition. --- build/android/jni/Android.mk | 1 + src/CMakeLists.txt | 1 + src/clientenvironment.cpp | 1 + src/clientiface.cpp | 2 +- src/content_cao.cpp | 1 + src/face_position_cache.cpp | 110 +++++++++++++++++++++++++++++++++ src/face_position_cache.h | 44 +++++++++++++ src/mg_decoration.cpp | 2 + src/mg_ore.cpp | 3 +- src/script/lua_api/l_env.cpp | 1 + src/script/lua_api/l_server.cpp | 1 + src/unittest/test_noderesolver.cpp | 2 + src/util/basic_macros.h | 3 +- src/util/numeric.cpp | 93 +--------------------------- src/util/numeric.h | 94 ++++++++++------------------ src/util/string.cpp | 1 + util/travis/clang-format-whitelist.txt | 2 + 17 files changed, 205 insertions(+), 157 deletions(-) create mode 100644 src/face_position_cache.cpp create mode 100644 src/face_position_cache.h (limited to 'src/unittest') diff --git a/build/android/jni/Android.mk b/build/android/jni/Android.mk index d4a8d988f..44d98fada 100644 --- a/build/android/jni/Android.mk +++ b/build/android/jni/Android.mk @@ -143,6 +143,7 @@ LOCAL_SRC_FILES := \ jni/src/dungeongen.cpp \ jni/src/emerge.cpp \ jni/src/environment.cpp \ + jni/src/face_position_cache.cpp \ jni/src/filecache.cpp \ jni/src/filesys.cpp \ jni/src/fontengine.cpp \ diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4c705cec8..7c1a4eee0 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -388,6 +388,7 @@ set(common_SRCS dungeongen.cpp emerge.cpp environment.cpp + face_position_cache.cpp filesys.cpp genericobject.cpp gettext.cpp diff --git a/src/clientenvironment.cpp b/src/clientenvironment.cpp index 36e4437b6..47df49b84 100644 --- a/src/clientenvironment.cpp +++ b/src/clientenvironment.cpp @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "raycast.h" #include "voxelalgorithms.h" #include "settings.h" +#include /* ClientEnvironment diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 7f476f0ea..78339055f 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -20,7 +20,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "clientiface.h" -#include "util/numeric.h" #include "remoteplayer.h" #include "settings.h" #include "mapblock.h" @@ -32,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "network/serveropcodes.h" #include "util/srp.h" +#include "face_position_cache.h" const char *ClientInterface::statenames[] = { "Invalid", diff --git a/src/content_cao.cpp b/src/content_cao.cpp index d18a0233f..d0d3eb84f 100644 --- a/src/content_cao.cpp +++ b/src/content_cao.cpp @@ -44,6 +44,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "camera.h" // CameraModes #include "wieldmesh.h" #include "log.h" +#include class Settings; struct ToolCapabilities; diff --git a/src/face_position_cache.cpp b/src/face_position_cache.cpp new file mode 100644 index 000000000..f57e75da9 --- /dev/null +++ b/src/face_position_cache.cpp @@ -0,0 +1,110 @@ +/* +Minetest +Copyright (C) 2015 Nerzhul, Loic Blot + +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 "face_position_cache.h" +#include "threading/mutex_auto_lock.h" + + +UNORDERED_MAP > FacePositionCache::cache; +Mutex FacePositionCache::cache_mutex; + +// Calculate the borders of a "d-radius" cube +const std::vector &FacePositionCache::getFacePositions(u16 d) +{ + MutexAutoLock lock(cache_mutex); + UNORDERED_MAP >::iterator it = cache.find(d); + if (it != cache.end()) + return it->second; + + return generateFacePosition(d); +} + +const std::vector &FacePositionCache::generateFacePosition(u16 d) +{ + cache[d] = std::vector(); + std::vector &c = cache[d]; + if (d == 0) { + c.push_back(v3s16(0,0,0)); + return c; + } + if (d == 1) { + // This is an optimized sequence of coordinates. + c.push_back(v3s16( 0, 1, 0)); // Top + c.push_back(v3s16( 0, 0, 1)); // Back + c.push_back(v3s16(-1, 0, 0)); // Left + c.push_back(v3s16( 1, 0, 0)); // Right + c.push_back(v3s16( 0, 0,-1)); // Front + c.push_back(v3s16( 0,-1, 0)); // Bottom + // 6 + c.push_back(v3s16(-1, 0, 1)); // Back left + c.push_back(v3s16( 1, 0, 1)); // Back right + c.push_back(v3s16(-1, 0,-1)); // Front left + c.push_back(v3s16( 1, 0,-1)); // Front right + c.push_back(v3s16(-1,-1, 0)); // Bottom left + c.push_back(v3s16( 1,-1, 0)); // Bottom right + c.push_back(v3s16( 0,-1, 1)); // Bottom back + c.push_back(v3s16( 0,-1,-1)); // Bottom front + c.push_back(v3s16(-1, 1, 0)); // Top left + c.push_back(v3s16( 1, 1, 0)); // Top right + c.push_back(v3s16( 0, 1, 1)); // Top back + c.push_back(v3s16( 0, 1,-1)); // Top front + // 18 + c.push_back(v3s16(-1, 1, 1)); // Top back-left + c.push_back(v3s16( 1, 1, 1)); // Top back-right + c.push_back(v3s16(-1, 1,-1)); // Top front-left + c.push_back(v3s16( 1, 1,-1)); // Top front-right + c.push_back(v3s16(-1,-1, 1)); // Bottom back-left + c.push_back(v3s16( 1,-1, 1)); // Bottom back-right + c.push_back(v3s16(-1,-1,-1)); // Bottom front-left + c.push_back(v3s16( 1,-1,-1)); // Bottom front-right + // 26 + return c; + } + + // Take blocks in all sides, starting from y=0 and going +-y + for (s16 y = 0; y <= d - 1; y++) { + // Left and right side, including borders + for (s16 z =- d; z <= d; z++) { + c.push_back(v3s16( d, y, z)); + c.push_back(v3s16(-d, y, z)); + if (y != 0) { + c.push_back(v3s16( d, -y, z)); + c.push_back(v3s16(-d, -y, z)); + } + } + // Back and front side, excluding borders + for (s16 x = -d + 1; x <= d - 1; x++) { + c.push_back(v3s16(x, y, d)); + c.push_back(v3s16(x, y, -d)); + if (y != 0) { + c.push_back(v3s16(x, -y, d)); + c.push_back(v3s16(x, -y, -d)); + } + } + } + + // Take the bottom and top face with borders + // -d < x < d, y = +-d, -d < z < d + for (s16 x = -d; x <= d; x++) + for (s16 z = -d; z <= d; z++) { + c.push_back(v3s16(x, -d, z)); + c.push_back(v3s16(x, d, z)); + } + return c; +} diff --git a/src/face_position_cache.h b/src/face_position_cache.h new file mode 100644 index 000000000..c1d2841c4 --- /dev/null +++ b/src/face_position_cache.h @@ -0,0 +1,44 @@ +/* +Minetest +Copyright (C) 2015 Nerzhul, Loic Blot + +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. +*/ + +#ifndef FACE_POSITION_CACHE_HEADER +#define FACE_POSITION_CACHE_HEADER + +#include "irr_v3d.h" +#include "threading/mutex.h" +#include "util/cpp11_container.h" + +#include +#include + +/* + * This class permits caching getFacePosition call results. + * This reduces CPU usage and vector calls. + */ +class FacePositionCache { +public: + static const std::vector &getFacePositions(u16 d); + +private: + static const std::vector &generateFacePosition(u16 d); + static UNORDERED_MAP > cache; + static Mutex cache_mutex; +}; + +#endif diff --git a/src/mg_decoration.cpp b/src/mg_decoration.cpp index 51e4fbbcc..ec31a9c01 100644 --- a/src/mg_decoration.cpp +++ b/src/mg_decoration.cpp @@ -24,6 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "map.h" #include "log.h" #include "util/numeric.h" +#include + FlagDesc flagdesc_deco[] = { {"place_center_x", DECO_PLACE_CENTER_X}, diff --git a/src/mg_ore.cpp b/src/mg_ore.cpp index d840d745a..c6c1c45a7 100644 --- a/src/mg_ore.cpp +++ b/src/mg_ore.cpp @@ -20,9 +20,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mg_ore.h" #include "mapgen.h" #include "noise.h" -#include "util/numeric.h" #include "map.h" #include "log.h" +#include + FlagDesc flagdesc_ore[] = { {"absheight", OREFLAG_ABSHEIGHT}, diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 0ded12658..b8b6bc5ba 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -35,6 +35,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "treegen.h" #include "emerge.h" #include "pathfinder.h" +#include "face_position_cache.h" struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = { diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index ea993d7b7..a0e475dec 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -26,6 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "environment.h" #include "player.h" #include "log.h" +#include // request_shutdown() int ModApiServer::l_request_shutdown(lua_State *L) diff --git a/src/unittest/test_noderesolver.cpp b/src/unittest/test_noderesolver.cpp index 55acece6a..b009f5d2e 100644 --- a/src/unittest/test_noderesolver.cpp +++ b/src/unittest/test_noderesolver.cpp @@ -24,6 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gamedef.h" #include "nodedef.h" +#include + class TestNodeResolver : public TestBase { public: diff --git a/src/util/basic_macros.h b/src/util/basic_macros.h index bd4b890eb..687d7cf85 100644 --- a/src/util/basic_macros.h +++ b/src/util/basic_macros.h @@ -20,14 +20,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifndef BASICMACROS_HEADER #define BASICMACROS_HEADER -#include - #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 #define CONTAINS(c, v) (std::find((c).begin(), (c).end(), (v)) != (c).end()) // To disable copy constructors and assignment operations for some class diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index 87f1040ea..e6a9cb75e 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -24,100 +24,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../noise.h" // PseudoRandom, PcgRandom #include "../threading/mutex_auto_lock.h" #include -#include -UNORDERED_MAP > FacePositionCache::m_cache; -Mutex FacePositionCache::m_cache_mutex; -// Calculate the borders of a "d-radius" cube -// TODO: Make it work without mutex and data races, probably thread-local -std::vector FacePositionCache::getFacePositions(u16 d) -{ - MutexAutoLock cachelock(m_cache_mutex); - if (m_cache.find(d) != m_cache.end()) - return m_cache[d]; - - generateFacePosition(d); - return m_cache[d]; - -} - -void FacePositionCache::generateFacePosition(u16 d) -{ - m_cache[d] = std::vector(); - if(d == 0) { - m_cache[d].push_back(v3s16(0,0,0)); - return; - } - if(d == 1) { - /* - This is an optimized sequence of coordinates. - */ - m_cache[d].push_back(v3s16( 0, 1, 0)); // top - m_cache[d].push_back(v3s16( 0, 0, 1)); // back - m_cache[d].push_back(v3s16(-1, 0, 0)); // left - m_cache[d].push_back(v3s16( 1, 0, 0)); // right - m_cache[d].push_back(v3s16( 0, 0,-1)); // front - m_cache[d].push_back(v3s16( 0,-1, 0)); // bottom - // 6 - m_cache[d].push_back(v3s16(-1, 0, 1)); // back left - m_cache[d].push_back(v3s16( 1, 0, 1)); // back right - m_cache[d].push_back(v3s16(-1, 0,-1)); // front left - m_cache[d].push_back(v3s16( 1, 0,-1)); // front right - m_cache[d].push_back(v3s16(-1,-1, 0)); // bottom left - m_cache[d].push_back(v3s16( 1,-1, 0)); // bottom right - m_cache[d].push_back(v3s16( 0,-1, 1)); // bottom back - m_cache[d].push_back(v3s16( 0,-1,-1)); // bottom front - m_cache[d].push_back(v3s16(-1, 1, 0)); // top left - m_cache[d].push_back(v3s16( 1, 1, 0)); // top right - m_cache[d].push_back(v3s16( 0, 1, 1)); // top back - m_cache[d].push_back(v3s16( 0, 1,-1)); // top front - // 18 - m_cache[d].push_back(v3s16(-1, 1, 1)); // top back-left - m_cache[d].push_back(v3s16( 1, 1, 1)); // top back-right - m_cache[d].push_back(v3s16(-1, 1,-1)); // top front-left - m_cache[d].push_back(v3s16( 1, 1,-1)); // top front-right - m_cache[d].push_back(v3s16(-1,-1, 1)); // bottom back-left - m_cache[d].push_back(v3s16( 1,-1, 1)); // bottom back-right - m_cache[d].push_back(v3s16(-1,-1,-1)); // bottom front-left - m_cache[d].push_back(v3s16( 1,-1,-1)); // bottom front-right - // 26 - return; - } - // Take blocks in all sides, starting from y=0 and going +-y - for(s16 y=0; y<=d-1; y++) { - // Left and right side, including borders - for(s16 z=-d; z<=d; z++) { - m_cache[d].push_back(v3s16(d,y,z)); - m_cache[d].push_back(v3s16(-d,y,z)); - if(y != 0) { - m_cache[d].push_back(v3s16(d,-y,z)); - m_cache[d].push_back(v3s16(-d,-y,z)); - } - } - // Back and front side, excluding borders - for(s16 x=-d+1; x<=d-1; x++) { - m_cache[d].push_back(v3s16(x,y,d)); - m_cache[d].push_back(v3s16(x,y,-d)); - if(y != 0) { - m_cache[d].push_back(v3s16(x,-y,d)); - m_cache[d].push_back(v3s16(x,-y,-d)); - } - } - } - - // Take the bottom and top face with borders - // -d -#include +#define rangelim(d, min, max) ((d) < (min) ? (min) : ((d) > (max) ? (max) : (d))) +#define myfloor(x) ((x) > 0.0 ? (int)(x) : (int)(x) - 1) +// The naive swap performs better than the xor version +#define SWAP(t, x, y) do { \ + t temp = x; \ + x = y; \ + y = temp; \ +} while (0) -/* - * This class permits to cache getFacePosition call results - * This reduces CPU usage and vector calls - */ -class FacePositionCache -{ -public: - static std::vector getFacePositions(u16 d); -private: - static void generateFacePosition(u16 d); - static UNORDERED_MAP > m_cache; - static Mutex m_cache_mutex; -}; inline s16 getContainerPos(s16 p, s16 d) { - return (p>=0 ? p : p-d+1) / d; + return (p >= 0 ? p : p - d + 1) / d; } inline v2s16 getContainerPos(v2s16 p, s16 d) @@ -130,16 +122,6 @@ inline bool isInArea(v3s16 p, v3s16 d) ); } -#define rangelim(d, min, max) ((d) < (min) ? (min) : ((d)>(max)?(max):(d))) -#define myfloor(x) ((x) > 0.0 ? (int)(x) : (int)(x) - 1) - -// 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 void sortBoxVerticies(v3s16 &p1, v3s16 &p2) { if (p1.X > p2.X) SWAP(s16, p1.X, p2.X); @@ -266,11 +248,10 @@ inline s32 myround(f32 f) */ inline v3s16 floatToInt(v3f p, f32 d) { - v3s16 p2( - (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); - return p2; + 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); } /* @@ -278,34 +259,31 @@ inline v3s16 floatToInt(v3f p, f32 d) */ inline v3f intToFloat(v3s16 p, f32 d) { - v3f p2( + return v3f( (f32)p.X * d, (f32)p.Y * d, (f32)p.Z * d ); - return p2; } // Random helper. Usually d=BS inline aabb3f getNodeBox(v3s16 p, float d) { return aabb3f( - (float)p.X * d - 0.5*d, - (float)p.Y * d - 0.5*d, - (float)p.Z * d - 0.5*d, - (float)p.X * d + 0.5*d, - (float)p.Y * d + 0.5*d, - (float)p.Z * d + 0.5*d + (float)p.X * d - 0.5 * d, + (float)p.Y * d - 0.5 * d, + (float)p.Z * d - 0.5 * d, + (float)p.X * d + 0.5 * d, + (float)p.Y * d + 0.5 * d, + (float)p.Z * d + 0.5 * d ); } + class IntervalLimiter { public: - IntervalLimiter(): - m_accumulator(0) - { - } + IntervalLimiter() : m_accumulator(0) {} /* dtime: time from last call to this method wanted_interval: interval wanted @@ -316,15 +294,17 @@ public: bool step(float dtime, float wanted_interval) { m_accumulator += dtime; - if(m_accumulator < wanted_interval) + if (m_accumulator < wanted_interval) return false; m_accumulator -= wanted_interval; return true; } -protected: + +private: float m_accumulator; }; + /* 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 @@ -340,29 +320,21 @@ protected: */ inline void paging(u32 length, u32 page, u32 pagecount, u32 &minindex, u32 &maxindex) { - if(length < 1 || pagecount < 1 || page < 1 || page > pagecount) - { + if (length < 1 || pagecount < 1 || page < 1 || page > pagecount) { // Special cases or invalid parameters minindex = maxindex = 0; - } - else if(pagecount <= length) - { + } 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 - { + } else { // More pages than entries in the list: // Make sure the empty pages are at the end - if(page < length) - { + if (page < length) { minindex = page-1; maxindex = page; - } - else - { + } else { minindex = 0; maxindex = 0; } @@ -371,14 +343,14 @@ inline void paging(u32 length, u32 page, u32 pagecount, u32 &minindex, u32 &maxi inline float cycle_shift(float value, float by = 0, float max = 1) { - if (value + by < 0) return max + by + value; + 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; + return n != 0 && (n & (n - 1)) == 0; } // Compute next-higher power of 2 efficiently, e.g. for power-of-2 texture sizes. diff --git a/src/util/string.cpp b/src/util/string.cpp index 141068512..d41b91f24 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -25,6 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "hex.h" #include "../porting.h" +#include #include #include #include diff --git a/util/travis/clang-format-whitelist.txt b/util/travis/clang-format-whitelist.txt index cac2faf2d..0b290ae87 100644 --- a/util/travis/clang-format-whitelist.txt +++ b/util/travis/clang-format-whitelist.txt @@ -72,6 +72,8 @@ src/environment.cpp src/event.h src/event_manager.h src/exceptions.h +src/face_position_cache.cpp +src/face_position_cache.h src/filecache.cpp src/filesys.cpp src/filesys.h -- cgit v1.2.3 From d99b6fed5517797bfafe4bbb307963967f0ca749 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Fri, 26 May 2017 14:03:36 +0200 Subject: Time: Change old `u32` timestamps to 64-bit (#5818) MacOSX build fix + cleanups --- src/clientiface.cpp | 4 ++-- src/clientiface.h | 6 +++--- src/guiFormSpecMenu.cpp | 4 ++-- src/guiFormSpecMenu.h | 4 ++-- src/hud.cpp | 2 +- src/intlGUIEditBox.h | 2 +- src/map.cpp | 2 +- src/map.h | 2 +- src/network/connection.h | 2 +- src/profiler.cpp | 30 ++++++++++++++++++++++++++++++ src/profiler.h | 44 ++------------------------------------------ src/touchscreengui.cpp | 4 ++-- src/unittest/test.cpp | 8 ++++---- src/unittest/test.h | 4 ++-- src/util/timetaker.cpp | 23 ++++++++--------------- src/util/timetaker.h | 14 +++++++------- src/voxel.cpp | 12 ++++-------- src/voxel.h | 4 ++-- 18 files changed, 75 insertions(+), 96 deletions(-) (limited to 'src/unittest') diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 356281ca6..68bd4afe7 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -590,9 +590,9 @@ void RemoteClient::notifyEvent(ClientStateEvent event) } } -u32 RemoteClient::uptime() const +u64 RemoteClient::uptime() const { - return porting::getTime(PRECISION_SECONDS) - m_connection_time; + return porting::getTimeS() - m_connection_time; } ClientInterface::ClientInterface(con::Connection* con) diff --git a/src/clientiface.h b/src/clientiface.h index a219ed5fc..d2299c879 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -266,7 +266,7 @@ public: m_version_patch(0), m_full_version("unknown"), m_deployed_compression(0), - m_connection_time(porting::getTime(PRECISION_SECONDS)) + m_connection_time(porting::getTimeS()) { } ~RemoteClient() @@ -345,7 +345,7 @@ public: { serialization_version = m_pending_serialization_version; } /* get uptime */ - u32 uptime() const; + u64 uptime() const; /* set version information */ void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full) @@ -432,7 +432,7 @@ private: /* time this client was created */ - const u32 m_connection_time; + const u64 m_connection_time; }; class ClientInterface { diff --git a/src/guiFormSpecMenu.cpp b/src/guiFormSpecMenu.cpp index 64642cf1f..971d505fd 100644 --- a/src/guiFormSpecMenu.cpp +++ b/src/guiFormSpecMenu.cpp @@ -2658,7 +2658,7 @@ void GUIFormSpecMenu::drawMenu() if (hovered != NULL) { s32 id = hovered->getID(); - u32 delta = 0; + u64 delta = 0; if (id == -1) { m_old_tooltip_id = id; m_old_tooltip = L""; @@ -3247,7 +3247,7 @@ bool GUIFormSpecMenu::DoubleClickDetection(const SEvent event) m_doubleclickdetect[1].time = porting::getTimeMs(); } else if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) { - u32 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_doubleclickdetect[0].time, porting::getTimeMs()); if (delta > 400) { return false; } diff --git a/src/guiFormSpecMenu.h b/src/guiFormSpecMenu.h index 18ccf1c3a..557a1cc9f 100644 --- a/src/guiFormSpecMenu.h +++ b/src/guiFormSpecMenu.h @@ -420,8 +420,8 @@ protected: v2s32 m_old_pointer; // Mouse position after previous mouse event gui::IGUIStaticText *m_tooltip_element; - u32 m_tooltip_show_delay; - s64 m_hovered_time; + u64 m_tooltip_show_delay; + u64 m_hovered_time; s32 m_old_tooltip_id; std::wstring m_old_tooltip; diff --git a/src/hud.cpp b/src/hud.cpp index 3e4162b64..72145b4da 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -626,7 +626,7 @@ void Hud::resizeHotbar() { } struct MeshTimeInfo { - s64 time; + u64 time; scene::IMesh *mesh; }; diff --git a/src/intlGUIEditBox.h b/src/intlGUIEditBox.h index e3ee15a30..bb617476c 100644 --- a/src/intlGUIEditBox.h +++ b/src/intlGUIEditBox.h @@ -155,7 +155,7 @@ namespace gui gui::IGUIFont *OverrideFont, *LastBreakFont; IOSOperator* Operator; - u32 BlinkStartTime; + u64 BlinkStartTime; s32 CursorPos; s32 HScrollPos, VScrollPos; // scroll position in characters u32 Max; diff --git a/src/map.cpp b/src/map.cpp index 63e1e4ccd..641b7d2dd 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -981,7 +981,7 @@ void Map::transformLiquids(std::map &modified_blocks, time_until_purge *= 1000; // seconds -> milliseconds - u32 curr_time = porting::getTime(PRECISION_MILLI); + u64 curr_time = porting::getTimeMs(); u32 prev_unprocessed = m_unprocessed_count; m_unprocessed_count = m_transforming_liquid.size(); diff --git a/src/map.h b/src/map.h index 7e597bef6..41a1a246b 100644 --- a/src/map.h +++ b/src/map.h @@ -343,7 +343,7 @@ protected: private: f32 m_transforming_liquid_loop_count_multiplier; u32 m_unprocessed_count; - u32 m_inc_trending_up_start_time; // milliseconds + u64 m_inc_trending_up_start_time; // milliseconds bool m_queue_size_timer_started; DISABLE_CLASS_COPY(Map); diff --git a/src/network/connection.h b/src/network/connection.h index 3a8388522..8b7ed9773 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -769,7 +769,7 @@ class Peer { // Seconds from last receive float m_timeout_counter; - u32 m_last_timeout_check; + u64 m_last_timeout_check; }; class UDPPeer : public Peer diff --git a/src/profiler.cpp b/src/profiler.cpp index 197e094f6..8e997442c 100644 --- a/src/profiler.cpp +++ b/src/profiler.cpp @@ -21,3 +21,33 @@ with this program; if not, write to the Free Software Foundation, Inc., static Profiler main_profiler; Profiler *g_profiler = &main_profiler; +ScopeProfiler::ScopeProfiler( + Profiler *profiler, const std::string &name, ScopeProfilerType type) + : m_profiler(profiler), m_name(name), m_timer(NULL), m_type(type) +{ + if (m_profiler) + m_timer = new TimeTaker(m_name); +} + +ScopeProfiler::~ScopeProfiler() +{ + if (!m_timer) + return; + + float duration_ms = m_timer->stop(true); + float duration = duration_ms / 1000.0; + if (m_profiler) { + switch (m_type) { + case SPT_ADD: + m_profiler->add(m_name, duration); + break; + case SPT_AVG: + m_profiler->avg(m_name, duration); + break; + case SPT_GRAPH_ADD: + m_profiler->graphAdd(m_name, duration); + break; + } + } + delete m_timer; +} diff --git a/src/profiler.h b/src/profiler.h index 6da115972..ce60c6262 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -193,48 +193,8 @@ class ScopeProfiler { public: ScopeProfiler(Profiler *profiler, const std::string &name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - // name is copied - ScopeProfiler(Profiler *profiler, const char *name, - enum ScopeProfilerType type = SPT_ADD): - m_profiler(profiler), - m_name(name), - m_timer(NULL), - m_type(type) - { - if(m_profiler) - m_timer = new TimeTaker(m_name.c_str()); - } - ~ScopeProfiler() - { - if(m_timer) - { - float duration_ms = m_timer->stop(true); - float duration = duration_ms / 1000.0; - if(m_profiler){ - switch(m_type){ - case SPT_ADD: - m_profiler->add(m_name, duration); - break; - case SPT_AVG: - m_profiler->avg(m_name, duration); - break; - case SPT_GRAPH_ADD: - m_profiler->graphAdd(m_name, duration); - break; - } - } - delete m_timer; - } - } + ScopeProfilerType type = SPT_ADD); + ~ScopeProfiler(); private: Profiler *m_profiler; std::string m_name; diff --git a/src/touchscreengui.cpp b/src/touchscreengui.cpp index f32679ca4..0139b8c4f 100644 --- a/src/touchscreengui.cpp +++ b/src/touchscreengui.cpp @@ -922,7 +922,7 @@ bool TouchScreenGUI::doubleTapDetection() m_key_events[1].x = m_move_downlocation.X; m_key_events[1].y = m_move_downlocation.Y; - u32 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_key_events[0].down_time, porting::getTimeMs()); if (delta > 400) return false; @@ -1006,7 +1006,7 @@ void TouchScreenGUI::step(float dtime) (!m_move_has_really_moved) && (!m_move_sent_as_mouse_event)) { - u32 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); + u64 delta = porting::getDeltaMs(m_move_downtime, porting::getTimeMs()); if (delta > MIN_DIG_TIME_MS) { m_shootline = m_device diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 9d223b82d..570807ba7 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -229,7 +229,7 @@ bool run_tests() { DSTACK(FUNCTION_NAME); - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); TestGameDef gamedef; g_logger.setLevelSilenced(LL_ERROR, true); @@ -246,7 +246,7 @@ bool run_tests() num_total_tests_run += testmods[i]->num_tests_run; } - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; g_logger.setLevelSilenced(LL_ERROR, false); @@ -273,12 +273,12 @@ bool run_tests() bool TestBase::testModule(IGameDef *gamedef) { rawstream << "======== Testing module " << getName() << std::endl; - u32 t1 = porting::getTime(PRECISION_MILLI); + u64 t1 = porting::getTimeMs(); runTests(gamedef); - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; + u64 tdiff = porting::getTimeMs() - t1; rawstream << "======== Module " << getName() << " " << (num_tests_failed ? "failed" : "passed") << " (" << num_tests_failed << " failures / " << num_tests_run << " tests) - " << tdiff diff --git a/src/unittest/test.h b/src/unittest/test.h index e60e657cc..bf76e8bb2 100644 --- a/src/unittest/test.h +++ b/src/unittest/test.h @@ -33,7 +33,7 @@ class TestFailedException : public std::exception { // Runs a unit test and reports results #define TEST(fxn, ...) do { \ - u32 t1 = porting::getTime(PRECISION_MILLI); \ + u64 t1 = porting::getTimeMs(); \ try { \ fxn(__VA_ARGS__); \ rawstream << "[PASS] "; \ @@ -46,7 +46,7 @@ class TestFailedException : public std::exception { num_tests_failed++; \ } \ num_tests_run++; \ - u32 tdiff = porting::getTime(PRECISION_MILLI) - t1; \ + u64 tdiff = porting::getTimeMs() - t1; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ } while (0) diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index 0e92696ac..ac686c3a3 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../log.h" #include -TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) +TimeTaker::TimeTaker(const std::string &name, u64 *result, TimePrecision prec) { m_name = name; m_result = result; @@ -32,18 +32,13 @@ TimeTaker::TimeTaker(const char *name, u32 *result, TimePrecision prec) m_time1 = porting::getTime(prec); } -u32 TimeTaker::stop(bool quiet) +u64 TimeTaker::stop(bool quiet) { - if(m_running) - { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - if(m_result != NULL) - { + if (m_running) { + u64 dtime = porting::getTime(m_precision) - m_time1; + if (m_result != NULL) { (*m_result) += dtime; - } - else - { + } else { if (!quiet) { static const char* const units[] = { "s" /* PRECISION_SECONDS */, @@ -62,10 +57,8 @@ u32 TimeTaker::stop(bool quiet) return 0; } -u32 TimeTaker::getTimerTime() +u64 TimeTaker::getTimerTime() { - u32 time2 = porting::getTime(m_precision); - u32 dtime = time2 - m_time1; - return dtime; + return porting::getTime(m_precision) - m_time1; } diff --git a/src/util/timetaker.h b/src/util/timetaker.h index 5512c205f..c10f4f535 100644 --- a/src/util/timetaker.h +++ b/src/util/timetaker.h @@ -30,24 +30,24 @@ with this program; if not, write to the Free Software Foundation, Inc., class TimeTaker { public: - TimeTaker(const char *name, u32 *result=NULL, - TimePrecision=PRECISION_MILLI); + TimeTaker(const std::string &name, u64 *result=NULL, + TimePrecision prec=PRECISION_MILLI); ~TimeTaker() { stop(); } - u32 stop(bool quiet=false); + u64 stop(bool quiet=false); - u32 getTimerTime(); + u64 getTimerTime(); private: - const char *m_name; - u32 m_time1; + std::string m_name; + u64 m_time1; bool m_running; TimePrecision m_precision; - u32 *m_result; + u64 *m_result; }; #endif diff --git a/src/voxel.cpp b/src/voxel.cpp index 87773b240..78efde5bb 100644 --- a/src/voxel.cpp +++ b/src/voxel.cpp @@ -27,14 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Debug stuff */ -u32 addarea_time = 0; -u32 emerge_time = 0; -u32 emerge_load_time = 0; -u32 clearflag_time = 0; -//u32 getwaterpressure_time = 0; -//u32 spreadwaterpressure_time = 0; -u32 updateareawaterpressure_time = 0; -u32 flowwater_pre_time = 0; +u64 addarea_time = 0; +u64 emerge_time = 0; +u64 emerge_load_time = 0; +u64 clearflag_time = 0; VoxelManipulator::VoxelManipulator(): diff --git a/src/voxel.h b/src/voxel.h index 58ad39be4..3a64ccc79 100644 --- a/src/voxel.h +++ b/src/voxel.h @@ -49,8 +49,8 @@ class INodeDefManager; /* Debug stuff */ -extern u32 emerge_time; -extern u32 emerge_load_time; +extern u64 emerge_time; +extern u64 emerge_load_time; /* This class resembles aabbox3d a lot, but has inclusive -- cgit v1.2.3