/* Minetest Copyright (C) 2010-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 "inventory.h" #include "serialization.h" #include "debug.h" #include #include "log.h" #include "itemdef.h" #include "util/strfnd.h" #include "content_mapnode.h" // For loading legacy MaterialItems #include "nameidmapping.h" // For loading legacy MaterialItems #include "util/serialize.h" #include "util/string.h" /* ItemStack */ static content_t content_translate_from_19_to_internal(content_t c_from) { for (const auto &tt : trans_table_19) { if(tt[1] == c_from) { return tt[0]; } } return c_from; } ItemStack::ItemStack(const std::string &name_, u16 count_, u16 wear_, IItemDefManager *itemdef) : name(itemdef->getAlias(name_)), count(count_), wear(wear_) { if (name.empty() || count == 0) clear(); else if (itemdef->get(name).type == ITEM_TOOL) count = 1; } void ItemStack::serialize(std::ostream &os) const { DSTACK(FUNCTION_NAME); if(empty()) return; // Check how many parts of the itemstring are needed int parts = 1; if(count != 1) parts = 2; if(wear != 0) parts = 3; if (!metadata.empty()) parts = 4; os<= 2) os<<" "<= 3) os<<" "<= 4) { os << " "; metadata.serialize(os); } } void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef) { DSTACK(FUNCTION_NAME); clear(); // Read name name = deSerializeJsonStringIfNeeded(is); // Skip space std::string tmp; std::getline(is, tmp, ' '); if(!tmp.empty()) throw SerializationError("Unexpected text after item name"); if(name == "MaterialItem") { // Obsoleted on 2011-07-30 u16 material; is>>material; u16 materialcount; is>>materialcount; // Convert old materials if(material <= 0xff) material = content_translate_from_19_to_internal(material); if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "MaterialItem2") { // Obsoleted on 2011-11-16 u16 material; is>>material; u16 materialcount; is>>materialcount; if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name.empty()) name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "node" || name == "NodeItem" || name == "MaterialItem3" || name == "craft" || name == "CraftItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); count = stoi(trim(fnd.next(""))); if(count == 0) count = 1; } else if(name == "MBOItem") { // Obsoleted on 2011-10-14 throw SerializationError("MBOItem not supported anymore"); } else if(name == "tool" || name == "ToolItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } count = 1; // Then read wear fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); wear = stoi(trim(fnd.next(""))); } else { do // This loop is just to allow "break;" { // The real thing // Apply item aliases if (itemdef) name = itemdef->getAlias(name); // Read the count std::string count_str; std::getline(is, count_str, ' '); if (count_str.empty()) { count = 1; break; } count = stoi(count_str); // Read the wear std::string wear_str; std::getline(is, wear_str, ' '); if(wear_str.empty()) break; wear = stoi(wear_str); // Read metadata metadata.deSerialize(is); // In case fields are added after metadata, skip space here: //std::getline(is, tmp, ' '); //if(!tmp.empty()) // throw SerializationError("Unexpected text after metadata"); } while(false); } if (name.empty() || count == 0) clear(); else if (itemdef && itemdef->get(name).type == ITEM_TOOL) count = 1; } void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef) { std::istringstream is(str, std::ios::binary); deSerialize(is, itemdef); } std::string ItemStack::getItemString() const { std::ostringstream os(std::ios::binary); serialize(os); return os.str(); } ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef) { // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { const u16 stackMax = newitem.getStackMax(itemdef); *this = newitem; // If the item fits fully, delete it if (count <= stackMax) { newitem.clear(); } else { // Else the item does not fit fully. Return the rest. count = stackMax; newitem.remove(count); } } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, add counter and delete it else if(newitem.count <= freeSpace(itemdef)) { add(newitem.count); newitem.clear(); } // Else the item does not fit fully. Add all that fits and return // the rest. else { u16 freespace = freeSpace(itemdef); add(freespace); newitem.remove(freespace); } return newitem; } bool ItemStack::itemFits(ItemStack newitem, ItemStack *restitem, IItemDefManager *itemdef) const { // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { const u16 stackMax = newitem.getStackMax(itemdef); // If the item fits fully, delete it if (newitem.count <= stackMax) { newitem.clear(); } else { // Else the item does not fit fully. Return the rest. newitem.remove(stackMax); } } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, delete it else if(newitem.count <= freeSpace(itemdef)) { newitem.clear(); } // Else the item does not fit fully. Return the rest. else { u16 freespace = freeSpace(itemdef); newitem.remove(freespace); } if(restitem) *restitem = newitem; return newitem.empty(); } ItemStack ItemStack::takeItem(u32 takecount) { if(takecount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(takecount >= count) { // Take all clear(); } else { // Take part remove(takecount); result.count = takecount; } return result; } ItemStack ItemStack::peekItem(u32 peekcount) const { if(peekcount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(peekcount < count) result.coun This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "util/basic_macros.h" #include <string> #include <atomic> #include <thread> #include <mutex> #ifdef _AIX #include <sys/thread.h> // for tid_t #endif /* * On platforms using pthreads, these five priority classes correlate to * even divisions between the minimum and maximum reported thread priority. */ #if !defined(_WIN32) #define THREAD_PRIORITY_LOWEST 0 #define THREAD_PRIORITY_BELOW_NORMAL 1 #define THREAD_PRIORITY_NORMAL 2 #define THREAD_PRIORITY_ABOVE_NORMAL 3 #define THREAD_PRIORITY_HIGHEST 4 #endif class Thread { public: Thread(const std::string &name=""); virtual ~Thread(); DISABLE_CLASS_COPY(Thread) /* * Begins execution of a new thread at the pure virtual method Thread::run(). * Execution of the thread is guaranteed to have started after this function * returns. */ bool start(); /* * Requests that the thread exit gracefully. * Returns immediately; thread execution is guaranteed to be complete after * a subsequent call to Thread::wait. */ bool stop(); /* * Immediately terminates the thread. * This should be used with extreme caution, as the thread will not have * any opportunity to release resources it may be holding (such as memory * or locks). */ bool kill(); /* * Waits for thread to finish. * Note: This does not stop a thread, you have to do this on your own. * Returns false immediately if the thread is not started or has been waited * on before. */ bool wait(); /* * Returns true if the calling thread is this Thread object. */ bool isCurrentThread() { return std::this_thread::get_id() == getThreadId(); } bool isRunning() { return m_running; } bool stopRequested() { return m_request_stop; } std::thread::id getThreadId() { return m_thread_obj->get_id(); } /* * Gets the thread return value. * Returns true if the thread has exited and the return value was available, * or false if the thread has yet to finish. */ bool getReturnValue(void **ret); /* * Binds (if possible, otherwise sets the affinity of) the thread to the * specific processor specified by proc_number. */ bool bindToProcessor(unsigned int proc_number); /* * Sets the thread priority to the specified priority. * * prio can be one of: THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, * THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST. * On Windows, any of the other priorites as defined by SetThreadPriority * are supported as well. * * Note that it may be necessary to first set the threading policy or * scheduling algorithm to one that supports thread priorities if not * supported by default, otherwise this call will have no effect. */ bool setPriority(int prio); /* * Sets the currently executing thread's name to where supported; useful * for debugging. */ static void setName(const std::string &name); /* * Returns the number of processors/cores configured and active on this machine. */ static unsigned int getNumberOfProcessors(); protected: std::string m_name; virtual void *run() = 0; private: std::thread::native_handle_type getThreadHandle() { return m_thread_obj->native_handle(); } static void threadProc(Thread *thr); void *m_retval = nullptr; bool m_joinable = false; std::atomic<bool> m_request_stop; std::atomic<