From 687a82886f5c42ee055941a56302312ee44996ec Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 25 Oct 2015 01:38:30 +0300 Subject: [PATCH 01/53] cleanup CTypeList interface --- lib/Connection.cpp | 8 ++-- lib/Connection.h | 98 +++++++++++++++++++--------------------------- 2 files changed, 45 insertions(+), 61 deletions(-) diff --git a/lib/Connection.cpp b/lib/Connection.cpp index 0f6ca2ee2..4dc857cc1 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -448,7 +448,7 @@ CTypeList::TypeInfoPtr CTypeList::registerType( const std::type_info *type ) return newType; } -ui16 CTypeList::getTypeID( const std::type_info *type ) +ui16 CTypeList::getTypeID(const std::type_info * type) const { auto i = typeInfos.find(type); if(i != typeInfos.end()) @@ -457,7 +457,7 @@ ui16 CTypeList::getTypeID( const std::type_info *type ) return 0; } -std::vector CTypeList::castSequence(TypeInfoPtr from, TypeInfoPtr to) +std::vector CTypeList::castSequence(TypeInfoPtr from, TypeInfoPtr to) const { if(from == to) return std::vector(); @@ -510,7 +510,7 @@ std::vector CTypeList::castSequence(TypeInfoPtr from, Ty return ret; } -std::vector CTypeList::castSequence(const std::type_info *from, const std::type_info *to) +std::vector CTypeList::castSequence(const std::type_info *from, const std::type_info *to) const { //This additional if is needed because getTypeDescriptor might fail if type is not registered // (and if casting is not needed, then registereing should no be required) @@ -520,7 +520,7 @@ std::vector CTypeList::castSequence(const std::type_info return castSequence(getTypeDescriptor(from), getTypeDescriptor(to)); } -CTypeList::TypeInfoPtr CTypeList::getTypeDescriptor(const std::type_info *type, bool throws) +CTypeList::TypeInfoPtr CTypeList::getTypeDescriptor(const std::type_info *type, bool throws) const { auto i = typeInfos.find(type); if(i != typeInfos.end()) diff --git a/lib/Connection.h b/lib/Connection.h index ee07bf9aa..61eb654ad 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -136,7 +136,7 @@ struct PointerCaster : IPointerCaster // } }; -class DLL_LINKAGE CTypeList +class DLL_LINKAGE CTypeList: public boost::noncopyable { public: struct TypeDescriptor; @@ -152,58 +152,14 @@ private: std::map typeInfos; std::map, std::unique_ptr> casters; //for each pair we provide a caster (each registered relations creates a single entry here) - CTypeList(CTypeList &) - { - // This type is non-copyable. - // Unfortunately on Windows it is required for DLL_EXPORT-ed type to provide copy c-tor, so we can't =delete it. - assert(0); - } - CTypeList &operator=(CTypeList &) - { - // As above. - assert(0); - return *this; - } -public: - - CTypeList(); - - TypeInfoPtr registerType(const std::type_info *type); - - - template - void registerType(const Base * b = nullptr, const Derived * d = nullptr) - { - static_assert(std::is_base_of::value, "First registerType template parameter needs to ba a base class of the second one."); - static_assert(std::has_virtual_destructor::value, "Base class needs to have a virtual destructor."); - static_assert(!std::is_same::value, "Parameters of registerTypes should be two diffrenet types."); - auto bt = getTypeInfo(b), dt = getTypeInfo(d); //obtain std::type_info - auto bti = registerType(bt), dti = registerType(dt); //obtain our TypeDescriptor - - // register the relation between classes - bti->children.push_back(dti); - dti->parents.push_back(bti); - casters[std::make_pair(bti, dti)] = make_unique>(); - casters[std::make_pair(dti, bti)] = make_unique>(); - } - - ui16 getTypeID(const std::type_info *type); - TypeInfoPtr getTypeDescriptor(const std::type_info *type, bool throws = true); //if not throws, failure returns nullptr - - template - ui16 getTypeID(const T * t = nullptr) - { - return getTypeID(getTypeInfo(t)); - } - - - // Returns sequence of types starting from "from" and ending on "to". Every next type is derived from the previous. - // Throws if there is no link registered. - std::vector castSequence(TypeInfoPtr from, TypeInfoPtr to); - std::vector castSequence(const std::type_info *from, const std::type_info *to); + /// Returns sequence of types starting from "from" and ending on "to". Every next type is derived from the previous. + /// Throws if there is no link registered. + std::vector castSequence(TypeInfoPtr from, TypeInfoPtr to) const; + std::vector castSequence(const std::type_info *from, const std::type_info *to) const; + template - boost::any castHelper(boost::any inputPtr, const std::type_info *fromArg, const std::type_info *toArg) + boost::any castHelper(boost::any inputPtr, const std::type_info *fromArg, const std::type_info *toArg) const { auto typesSequence = castSequence(fromArg, toArg); @@ -223,8 +179,37 @@ public: return ptr; } + TypeInfoPtr registerType(const std::type_info *type); +public: + CTypeList(); + + template + void registerType(const Base * b = nullptr, const Derived * d = nullptr) + { + static_assert(std::is_base_of::value, "First registerType template parameter needs to ba a base class of the second one."); + static_assert(std::has_virtual_destructor::value, "Base class needs to have a virtual destructor."); + static_assert(!std::is_same::value, "Parameters of registerTypes should be two diffrenet types."); + auto bt = getTypeInfo(b), dt = getTypeInfo(d); //obtain std::type_info + auto bti = registerType(bt), dti = registerType(dt); //obtain our TypeDescriptor + + // register the relation between classes + bti->children.push_back(dti); + dti->parents.push_back(bti); + casters[std::make_pair(bti, dti)] = make_unique>(); + casters[std::make_pair(dti, bti)] = make_unique>(); + } + + ui16 getTypeID(const std::type_info *type) const; + TypeInfoPtr getTypeDescriptor(const std::type_info *type, bool throws = true) const; //if not throws, failure returns nullptr + + template + ui16 getTypeID(const T * t = nullptr) const + { + return getTypeID(getTypeInfo(t)); + } + template - void *castToMostDerived(const TInput *inputPtr) + void * castToMostDerived(const TInput * inputPtr) const { auto &baseType = typeid(typename std::remove_cv::type); auto derivedType = getTypeInfo(inputPtr); @@ -236,7 +221,7 @@ public: } template - boost::any castSharedToMostDerived(const std::shared_ptr inputPtr) + boost::any castSharedToMostDerived(const std::shared_ptr inputPtr) const { auto &baseType = typeid(typename std::remove_cv::type); auto derivedType = getTypeInfo(inputPtr.get()); @@ -247,17 +232,16 @@ public: return castHelper<&IPointerCaster::castSharedPtr>(inputPtr, &baseType, derivedType); } - void* castRaw(void *inputPtr, const std::type_info *from, const std::type_info *to) + void * castRaw(void *inputPtr, const std::type_info *from, const std::type_info *to) const { return boost::any_cast(castHelper<&IPointerCaster::castRawPtr>(inputPtr, from, to)); } - boost::any castShared(boost::any inputPtr, const std::type_info *from, const std::type_info *to) + boost::any castShared(boost::any inputPtr, const std::type_info *from, const std::type_info *to) const { return castHelper<&IPointerCaster::castSharedPtr>(inputPtr, from, to); } - - template const std::type_info * getTypeInfo(const T * t = nullptr) + template const std::type_info * getTypeInfo(const T * t = nullptr) const { if(t) return &typeid(*t); From 0f9de1c560fa93591f456f24db027c4a9eacedef Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 25 Oct 2015 03:26:48 +0300 Subject: [PATCH 02/53] Made CTypeList threadsafe --- lib/Connection.cpp | 1 + lib/Connection.h | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/Connection.cpp b/lib/Connection.cpp index 4dc857cc1..d88326017 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -450,6 +450,7 @@ CTypeList::TypeInfoPtr CTypeList::registerType( const std::type_info *type ) ui16 CTypeList::getTypeID(const std::type_info * type) const { + TSharedLock lock(mx); auto i = typeInfos.find(type); if(i != typeInfos.end()) return i->second->typeID; diff --git a/lib/Connection.h b/lib/Connection.h index 61eb654ad..bf12e07f4 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -147,7 +147,11 @@ public: const char *name; std::vector children, parents; }; + typedef boost::shared_mutex TMutex; + typedef boost::unique_lock TUniqueLock; + typedef boost::shared_lock TSharedLock; private: + mutable TMutex mx; std::map typeInfos; std::map, std::unique_ptr> casters; //for each pair we provide a caster (each registered relations creates a single entry here) @@ -161,6 +165,7 @@ private: template boost::any castHelper(boost::any inputPtr, const std::type_info *fromArg, const std::type_info *toArg) const { + TSharedLock lock(mx); auto typesSequence = castSequence(fromArg, toArg); boost::any ptr = inputPtr; @@ -179,13 +184,16 @@ private: return ptr; } - TypeInfoPtr registerType(const std::type_info *type); + TypeInfoPtr getTypeDescriptor(const std::type_info *type, bool throws = true) const; //if not throws, failure returns nullptr + + TypeInfoPtr registerType(const std::type_info *type); public: CTypeList(); template void registerType(const Base * b = nullptr, const Derived * d = nullptr) { + TUniqueLock lock(mx); static_assert(std::is_base_of::value, "First registerType template parameter needs to ba a base class of the second one."); static_assert(std::has_virtual_destructor::value, "Base class needs to have a virtual destructor."); static_assert(!std::is_same::value, "Parameters of registerTypes should be two diffrenet types."); @@ -200,7 +208,6 @@ public: } ui16 getTypeID(const std::type_info *type) const; - TypeInfoPtr getTypeDescriptor(const std::type_info *type, bool throws = true) const; //if not throws, failure returns nullptr template ui16 getTypeID(const T * t = nullptr) const From cfb58536891869d4dd7cddb3e6fb12e38e63dd24 Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 25 Oct 2015 03:29:16 +0300 Subject: [PATCH 03/53] Just a bit of black magic --- lib/NetPacks.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/NetPacks.h b/lib/NetPacks.h index cdbe3ebe9..e788fd9b2 100644 --- a/lib/NetPacks.h +++ b/lib/NetPacks.h @@ -331,9 +331,6 @@ struct SetAvailableHeroes : public CPackForClient //113 for (int i = 0; i < GameConstants::AVAILABLE_HEROES_PER_PLAYER; i++) army[i].clear(); } - ~SetAvailableHeroes() - { - } void applyCl(CClient *cl); DLL_LINKAGE void applyGs(CGameState *gs); From 79fb5b0c7bcc7c3b847a65b62df36bd051c90d03 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sun, 25 Oct 2015 13:04:21 +0300 Subject: [PATCH 04/53] Fix typeid ordering bug on MacOSX --- lib/Connection.cpp | 49 ++++++++++++----------- lib/Connection.h | 96 ++++++++++++++++++++++++---------------------- 2 files changed, 74 insertions(+), 71 deletions(-) diff --git a/lib/Connection.cpp b/lib/Connection.cpp index d88326017..0fce3d2c3 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -68,7 +68,7 @@ void CConnection::init() } CConnection::CConnection(std::string host, std::string port, std::string Name) -:iser(this), oser(this), io_service(new asio::io_service), name(Name) +:iser(this), oser(this), io_service(new asio::io_service), name(Name) { int i; boost::system::error_code error = asio::error::host_not_found; @@ -119,7 +119,7 @@ connerror1: else logNetwork->errorStream() << "No error info. "; delete io_service; - //delete socket; + //delete socket; throw std::runtime_error("Can't establish connection :("); } CConnection::CConnection(TSocket * Socket, std::string Name ) @@ -134,10 +134,10 @@ CConnection::CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_servi socket = new tcp::socket(*io_service); acceptor->accept(*socket,error); if (error) - { + { logNetwork->errorStream() << "Error on accepting: " << error; - delete socket; - throw std::runtime_error("Can't establish connection :("); + delete socket; + throw std::runtime_error("Can't establish connection :("); } init(); } @@ -238,12 +238,12 @@ void CConnection::sendPackToServer(const CPack &pack, PlayerColor player, ui32 r void CConnection::disableStackSendingByID() { - CSerializer::sendStackInstanceByIds = false; + CSerializer::sendStackInstanceByIds = false; } void CConnection::enableStackSendingByID() { - CSerializer::sendStackInstanceByIds = true; + CSerializer::sendStackInstanceByIds = true; } void CConnection::disableSmartPointerSerialization() @@ -283,7 +283,7 @@ void CConnection::enableSmartVectorMemberSerializatoin() CSerializer::smartVectorMembersSerialization = true; } -CSaveFile::CSaveFile( const std::string &fname ): serializer(this) +CSaveFile::CSaveFile( const std::string &fname ): serializer(this) { registerTypes(serializer); openNextFile(fname); @@ -377,7 +377,7 @@ void CLoadFile::openNextFile(const boost::filesystem::path & fname, int minimalV if(std::memcmp(buffer,"VCMI",4)) THROW_FORMAT("Error: not a VCMI file(%s)!", fName); - serializer >> serializer.fileVersion; + serializer >> serializer.fileVersion; if(serializer.fileVersion < minimalVersion) THROW_FORMAT("Error: too old file format (%s)!", fName); @@ -435,7 +435,7 @@ CTypeList::CTypeList() } CTypeList::TypeInfoPtr CTypeList::registerType( const std::type_info *type ) -{ +{ if(auto typeDescr = getTypeDescriptor(type, false)) return typeDescr; //type found, return ptr to structure @@ -448,14 +448,14 @@ CTypeList::TypeInfoPtr CTypeList::registerType( const std::type_info *type ) return newType; } -ui16 CTypeList::getTypeID(const std::type_info * type) const -{ - TSharedLock lock(mx); - auto i = typeInfos.find(type); - if(i != typeInfos.end()) - return i->second->typeID; - else +ui16 CTypeList::getTypeID( const std::type_info *type, bool throws ) const +{ + auto descriptor = getTypeDescriptor(type, throws); + if (descriptor == nullptr) + { return 0; + } + return descriptor->typeID; } std::vector CTypeList::castSequence(TypeInfoPtr from, TypeInfoPtr to) const @@ -483,7 +483,7 @@ std::vector CTypeList::castSequence(TypeInfoPtr from, Ty } } } - + std::vector ret; if(!previous.count(from)) @@ -525,7 +525,7 @@ CTypeList::TypeInfoPtr CTypeList::getTypeDescriptor(const std::type_info *type, { auto i = typeInfos.find(type); if(i != typeInfos.end()) - return i->second; //type found, return ptr to structure + return i->second; //type found, return ptr to structure if(!throws) return nullptr; @@ -552,19 +552,19 @@ CSerializer::CSerializer() void CSerializer::addStdVecItems(CGameState *gs, LibClasses *lib) { - registerVectoredType(&gs->map->objects, + registerVectoredType(&gs->map->objects, [](const CGObjectInstance &obj){ return obj.id; }); - registerVectoredType(&lib->heroh->heroes, + registerVectoredType(&lib->heroh->heroes, [](const CHero &h){ return h.ID; }); registerVectoredType(&gs->map->allHeroes, [](const CGHeroInstance &h){ return h.type->ID; }); - registerVectoredType(&lib->creh->creatures, + registerVectoredType(&lib->creh->creatures, [](const CCreature &cre){ return cre.idNumber; }); registerVectoredType(&lib->arth->artifacts, [](const CArtifact &art){ return art.id; }); - registerVectoredType(&gs->map->artInstances, + registerVectoredType(&gs->map->artInstances, [](const CArtifactInstance &artInst){ return artInst.id; }); - registerVectoredType(&gs->map->quests, + registerVectoredType(&gs->map->quests, [](const CQuest &q){ return q.qid; }); smartVectorMembersSerialization = true; @@ -645,4 +645,3 @@ CMemorySerializer::CMemorySerializer(): iser(this), oser(this) registerTypes(iser); registerTypes(oser); } - diff --git a/lib/Connection.h b/lib/Connection.h index bf12e07f4..b27a77c50 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -81,10 +81,14 @@ enum SerializationLvl struct TypeComparer { - bool operator()(const std::type_info *a, const std::type_info *b) const - { - return a->before(*b); - } + bool operator()(const std::type_info *a, const std::type_info *b) const + { + #ifndef __APPLE__ + return a->before(*b); + #else + return std::string(a->name()) < std::string(b->name()); + #endif + } }; struct IPointerCaster @@ -160,7 +164,7 @@ private: /// Throws if there is no link registered. std::vector castSequence(TypeInfoPtr from, TypeInfoPtr to) const; std::vector castSequence(const std::type_info *from, const std::type_info *to) const; - + template boost::any castHelper(boost::any inputPtr, const std::type_info *fromArg, const std::type_info *toArg) const @@ -207,12 +211,12 @@ public: casters[std::make_pair(dti, bti)] = make_unique>(); } - ui16 getTypeID(const std::type_info *type) const; + ui16 getTypeID(const std::type_info *type, bool throws = false) const; template - ui16 getTypeID(const T * t = nullptr) const + ui16 getTypeID(const T * t = nullptr, bool throws = false) const { - return getTypeID(getTypeInfo(t)); + return getTypeID(getTypeInfo(t), throws); } template @@ -435,13 +439,13 @@ public: virtual int write(const void * data, unsigned size) = 0; }; -class DLL_LINKAGE CSaverBase +class DLL_LINKAGE CSaverBase { protected: IBinaryWriter * writer; public: CSaverBase(IBinaryWriter * w): writer(w){}; - + inline int write(const void * data, unsigned size) { return writer->write(data, size); @@ -577,15 +581,15 @@ struct LoadIfStackInstance class DLL_LINKAGE COSer : public CSaverBase { public: - + struct SaveBoolean { static void invoke(COSer &s, const bool &data) { s.saveBoolean(data); } - }; - + }; + struct SaveBooleanVector { static void invoke(COSer &s, const std::vector &data) @@ -620,7 +624,7 @@ public: s.saveEnum(data); } }; - + template struct SavePointer { @@ -629,7 +633,7 @@ public: s.savePointer(data); } }; - + template struct SaveArray { @@ -646,9 +650,9 @@ public: { throw std::runtime_error("Wrong save serialization call!"); } - }; - - template + }; + + template class CPointerSaver : public CBasicPointerSaver { public: @@ -660,8 +664,8 @@ public: //T is most derived known type, it's time to call actual serialize const_cast(*ptr).serialize(s,version); } - }; - + }; + bool saving; std::map savers; // typeID => CPointerSaver @@ -955,13 +959,13 @@ public: virtual int read(void * data, unsigned size) = 0; }; -class DLL_LINKAGE CLoaderBase +class DLL_LINKAGE CLoaderBase { protected: IBinaryReader * reader; public: CLoaderBase(IBinaryReader * r): reader(r){}; - + inline int read(void * data, unsigned size) { return reader->read(data, size); @@ -1006,15 +1010,15 @@ public: s.loadBoolean(data); } }; - + struct LoadBooleanVector { static void invoke(CISer &s, std::vector &data) { s.loadBooleanVector(data); } - }; - + }; + template struct LoadEnum { @@ -1031,7 +1035,7 @@ public: { s.loadPrimitive(data); } - }; + }; template struct LoadPointer @@ -1040,8 +1044,8 @@ public: { s.loadPointer(data); } - }; - + }; + template struct LoadArray { @@ -1067,8 +1071,8 @@ public: { throw std::runtime_error("Wrong load serialization call!"); } - }; - + }; + template class CPointerLoader : public CBasicPointerLoader { public: @@ -1085,8 +1089,8 @@ public: ptr->serialize(s,version); return &typeid(T); } - }; - + }; + bool saving; std::map loaders; // typeID => CPointerSaver si32 fileVersion; @@ -1530,9 +1534,9 @@ class DLL_LINKAGE CSaveFile :public IBinaryWriter { public: - + COSer serializer; - + std::string fName; unique_ptr sfile; @@ -1545,13 +1549,13 @@ public: void reportState(CLogger * out) override; void putMagicBytes(const std::string &text); - + template CSaveFile & operator<<(const T &t) { serializer << t; return * this; - } + } }; class DLL_LINKAGE CLoadFile @@ -1559,7 +1563,7 @@ class DLL_LINKAGE CLoadFile { public: CISer serializer; - + std::string fName; unique_ptr sfile; @@ -1572,20 +1576,20 @@ public: void reportState(CLogger * out) override; void checkMagicBytes(const std::string & text); - + template CLoadFile & operator>>(T &t) { serializer >> t; return * this; - } + } }; -class DLL_LINKAGE CLoadIntegrityValidator +class DLL_LINKAGE CLoadIntegrityValidator : public IBinaryReader { public: - CISer serializer; + CISer serializer; unique_ptr primaryFile, controlFile; bool foundDesync; @@ -1611,7 +1615,7 @@ class DLL_LINKAGE CConnection public: CISer iser; COSer oser; - + boost::mutex *rmx, *wmx; // read/write mutexes TSocket * socket; bool logging; @@ -1649,14 +1653,14 @@ public: void prepareForSendingHeroes(); //disables sending vectorised, enables smart pointer serialization, clears saved/loaded ptr cache void enterPregameConnectionMode(); - + template CConnection & operator>>(T &t) { iser >> t; return * this; - } - + } + template CConnection & operator<<(const T &t) { @@ -1678,7 +1682,7 @@ class DLL_LINKAGE CMemorySerializer public: CISer iser; COSer oser; - + int read(void * data, unsigned size) override; //throws! int write(const void * data, unsigned size) override; From c5ebec0d1fcb182688de33d76d9c870c6ea9b5d1 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Tue, 27 Oct 2015 09:09:42 +0300 Subject: [PATCH 05/53] Fix the second crash (dynamic_cast failure) --- client/Client.cpp | 53 +++++++++++++++++++++++----------------------- lib/Connection.cpp | 4 ++-- lib/Connection.h | 39 ++++++++++++++++++++++------------ 3 files changed, 54 insertions(+), 42 deletions(-) diff --git a/client/Client.cpp b/client/Client.cpp index dabe2209f..0471204ae 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -59,8 +59,8 @@ template class CApplyOnCL; class CBaseForCLApply { public: - virtual void applyOnClAfter(CClient *cl, void *pack) const =0; - virtual void applyOnClBefore(CClient *cl, void *pack) const =0; + virtual void applyOnClAfter(CClient *cl, void *pack) const =0; + virtual void applyOnClBefore(CClient *cl, void *pack) const =0; virtual ~CBaseForCLApply(){} template static CBaseForCLApply *getApplier(const U * t=nullptr) @@ -144,7 +144,7 @@ void CClient::waitForMoveAndSend(PlayerColor color) { logNetwork->traceStream() << "Send battle action to server: " << ba; MakeAction temp_action(ba); - sendRequest(&temp_action, color); + sendRequest(&temp_action, color); } return; } @@ -169,8 +169,8 @@ void CClient::run() while(!terminate) { CPack *pack = serv->retreivePack(); //get the package from the server - - if (terminate) + + if (terminate) { vstd::clear_pointer(pack); break; @@ -178,10 +178,10 @@ void CClient::run() handlePack(pack); } - } + } //catch only asio exceptions catch (const boost::system::system_error& e) - { + { logNetwork->errorStream() << "Lost connection to server, ending listening thread!"; logNetwork->errorStream() << e.what(); if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected @@ -313,7 +313,7 @@ void CClient::loadGame(const std::string & fname, const bool server, const std:: *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player *serv << fname; *serv >> pom8; - if(pom8) + if(pom8) throw std::runtime_error("Server cannot open the savegame!"); else logNetwork->infoStream() << "Server opened savegame properly."; @@ -369,7 +369,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) { enum {SINGLE, HOST, GUEST} networkMode = SINGLE; - if (con == nullptr) + if (con == nullptr) { CServerHandler sh; serv = sh.connectToServer(); @@ -452,7 +452,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive; installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color); } - else + else { installNewPlayerInterface(make_shared(color), color); humanPlayers++; @@ -495,7 +495,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) // nm->giveActionCB(this); // nm->giveInfoCB(this); // nm->init(); -// +// // erm = nm; //something tells me that there'll at most one module and it'll be ERM // } } @@ -503,7 +503,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) void CClient::serialize(COSer & h, const int version) { assert(h.saving); - h & hotSeat; + h & hotSeat; { ui8 players = playerint.size(); h & players; @@ -513,7 +513,7 @@ void CClient::serialize(COSer & h, const int version) LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first); assert(i->first == i->second->playerID); h & i->first & i->second->dllName & i->second->human; - i->second->saveGame(h, version); + i->second->saveGame(h, version); } } } @@ -529,7 +529,7 @@ void CClient::serialize(CISer & h, const int version) for(int i=0; i < players; i++) { std::string dllname; - PlayerColor pid; + PlayerColor pid; bool isHuman = false; h & pid & dllname & isHuman; @@ -541,7 +541,7 @@ void CClient::serialize(CISer & h, const int version) if(pid == PlayerColor::NEUTRAL) { installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid); - //TODO? consider serialization + //TODO? consider serialization continue; } else @@ -582,7 +582,7 @@ void CClient::serialize(COSer & h, const int version, const std::setfirst); assert(i->first == i->second->playerID); h & i->first & i->second->dllName & i->second->human; - i->second->saveGame(h, version); + i->second->saveGame(h, version); } } } @@ -598,7 +598,7 @@ void CClient::serialize(CISer & h, const int version, const std::setloadGame(h, version); + nInt->loadGame(h, version); } if(playerIDs.count(PlayerColor::NEUTRAL)) @@ -707,7 +707,7 @@ void CClient::battleStarted(const BattleInfo * info) { for(auto &battleCb : battleCallbacks) { - if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; }) + if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; }) || battleCb.first >= PlayerColor::PLAYER_LIMIT) { battleCb.second->setBattle(info); @@ -735,7 +735,7 @@ void CClient::battleStarted(const BattleInfo * info) { boost::unique_lock un(*LOCPLINT->pim); auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, - Rect((screen->w - 800)/2, + Rect((screen->w - 800)/2, (screen->h - 600)/2, 800, 600), att, def); GH.pushInt(bi); @@ -798,7 +798,7 @@ void CClient::commenceTacticPhaseForInt(shared_ptr battleI catch(...) { handleException(); - } + } } void CClient::invalidatePaths() @@ -822,7 +822,6 @@ const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h) int CClient::sendRequest(const CPack *request, PlayerColor player) { static ui32 requestCounter = 0; - ui32 requestID = requestCounter++; logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.") % typeid(*request).name() % requestID; @@ -882,7 +881,7 @@ void CClient::installNewBattleInterface(shared_ptr battleI boost::unique_lock un(*LOCPLINT->pim); PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE); - if(!color) + if(!color) privilagedBattleEventReceivers.push_back(battleInterface); battleints[colorUsed] = battleInterface; @@ -954,7 +953,7 @@ CConnection * CServerHandler::connectToServer() #endif th.update(); //put breakpoint here to attach to server before it does something stupid - + CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port); if(verbose) @@ -1015,8 +1014,8 @@ CConnection * CServerHandler::justConnectToServer(const std::string &host, const try { logNetwork->infoStream() << "Establishing connection..."; - ret = new CConnection( host.size() ? host : settings["server"]["server"].String(), - port.size() ? port : boost::lexical_cast(settings["server"]["port"].Float()), + ret = new CConnection( host.size() ? host : settings["server"]["server"].String(), + port.size() ? port : boost::lexical_cast(settings["server"]["port"].Float()), NAME); } catch(...) diff --git a/lib/Connection.cpp b/lib/Connection.cpp index 0fce3d2c3..1fd56c26f 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -460,7 +460,7 @@ ui16 CTypeList::getTypeID( const std::type_info *type, bool throws ) const std::vector CTypeList::castSequence(TypeInfoPtr from, TypeInfoPtr to) const { - if(from == to) + if(!strcmp(from->name, to->name)) return std::vector(); // Perform a simple BFS in the class hierarchy. @@ -515,7 +515,7 @@ std::vector CTypeList::castSequence(const std::type_info { //This additional if is needed because getTypeDescriptor might fail if type is not registered // (and if casting is not needed, then registereing should no be required) - if(*from == *to) + if(!strcmp(from->name(), to->name())) return std::vector(); return castSequence(getTypeDescriptor(from), getTypeDescriptor(to)); diff --git a/lib/Connection.h b/lib/Connection.h index b27a77c50..73f9a43e7 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -86,7 +86,7 @@ struct TypeComparer #ifndef __APPLE__ return a->before(*b); #else - return std::string(a->name()) < std::string(b->name()); + return strcmp(a->name(), b->name()) < 0; #endif } }; @@ -106,6 +106,11 @@ struct PointerCaster : IPointerCaster { From * from = (From*)boost::any_cast(ptr); To * ret = dynamic_cast(from); + if (ret == nullptr) + { + // Last resort when RTTI goes mad + ret = static_cast(from); + } return (void*)ret; } @@ -117,6 +122,11 @@ struct PointerCaster : IPointerCaster { auto from = boost::any_cast(ptr); auto ret = std::dynamic_pointer_cast(from); + if (!ret) + { + // Last resort when RTTI goes mad + ret = std::static_pointer_cast(from); + } return ret; } catch(std::exception &e) @@ -173,7 +183,7 @@ private: auto typesSequence = castSequence(fromArg, toArg); boost::any ptr = inputPtr; - for(int i = 0; i < (int)typesSequence.size() - 1; i++) + for(int i = 0; i < static_cast(typesSequence.size()) - 1; i++) { auto &from = typesSequence[i]; auto &to = typesSequence[i + 1]; @@ -182,7 +192,7 @@ private: THROW_FORMAT("Cannot find caster for conversion %s -> %s which is needed to cast %s -> %s", from->name % to->name % fromArg->name() % toArg->name()); auto &caster = casters.at(castingPair); - ptr = (*caster.*CastingFunction)(ptr); //Why does unique_ptr does not have operator->* ..? + ptr = (*caster.*CastingFunction)(ptr); //Why does unique_ptr not have operator->* ..? } return ptr; @@ -225,10 +235,14 @@ public: auto &baseType = typeid(typename std::remove_cv::type); auto derivedType = getTypeInfo(inputPtr); - if(baseType == *derivedType) - return (void*)inputPtr; + if (!strcmp(baseType.name(), derivedType->name())) + { + return const_cast(reinterpret_cast(inputPtr)); + } - return boost::any_cast(castHelper<&IPointerCaster::castRawPtr>((void*)inputPtr, &baseType, derivedType)); + return boost::any_cast(castHelper<&IPointerCaster::castRawPtr>( + const_cast(reinterpret_cast(inputPtr)), &baseType, + derivedType)); } template @@ -237,7 +251,7 @@ public: auto &baseType = typeid(typename std::remove_cv::type); auto derivedType = getTypeInfo(inputPtr.get()); - if(baseType == *derivedType) + if (!strcmp(baseType.name(), derivedType->name())) return inputPtr; return castHelper<&IPointerCaster::castSharedPtr>(inputPtr, &baseType, derivedType); @@ -653,16 +667,15 @@ public: }; template - class CPointerSaver : public CBasicPointerSaver + class CPointerSaver : public CBasicPointerSaver { public: void savePtr(CSaverBase &ar, const void *data) const override - { + { COSer &s = static_cast(ar); - const T *ptr = static_cast(data); - + const T *ptr = static_cast(data); //T is most derived known type, it's time to call actual serialize - const_cast(*ptr).serialize(s,version); + const_cast(ptr)->serialize(s,version); } }; @@ -772,7 +785,7 @@ public: //write type identifier ui16 tid = typeList.getTypeID(data); - *this << tid; + *this << tid; this->savePointerHlp(tid, data); } From 68cc86013319148137e1f488826addb90e836160 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Wed, 28 Oct 2015 23:53:44 +0300 Subject: [PATCH 06/53] Fix dynamic_cast on MacOSX in CQuery.cpp --- server/CGameHandler.cpp | 92 ++++++++++++++++++++--------------------- server/CQuery.cpp | 47 +++++++++++---------- server/StdInc.h | 14 +++++++ 3 files changed, 85 insertions(+), 68 deletions(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 17b0f7ed6..9a13c3285 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -65,14 +65,14 @@ class ServerSpellCastEnvironment: public SpellCastEnvironment public: ServerSpellCastEnvironment(CGameHandler * gh); ~ServerSpellCastEnvironment(){}; - void sendAndApply(CPackForClient * info) const override; + void sendAndApply(CPackForClient * info) const override; CRandomGenerator & getRandomGenerator() const override; void complain(const std::string & problem) const override; const CMap * getMap() const override; const CGameInfoCallback * getCb() const override; - bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) const override; + bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) const override; private: - mutable CGameHandler * gh; + mutable CGameHandler * gh; }; CondSh battleMadeAction; @@ -102,7 +102,7 @@ public: } }; -template <> +template <> class CApplyOnGH : public CBaseForGHApply { public: @@ -799,15 +799,15 @@ void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CSt const Bonus * bonus = att->getBonusLocalFirst(Selector::type(Bonus::SPELL_LIKE_ATTACK)); if (bonus && (bat.shot())) //TODO: make it work in melee? - { + { //this is need for displaying hit animation bat.flags |= BattleAttack::SPELL_LIKE; bat.spellID = SpellID(bonus->subtype); - + //TODO: should spell override creature`s projectile? - + std::set attackedCreatures = SpellID(bonus->subtype).toSpell()->getAffectedStacks(gs->curB, ECastingMode::SPELL_LIKE_ATTACK, att->owner, bonus->val, targetHex, att); - + //TODO: get exact attacked hex for defender for(const CStack * stack : attackedCreatures) @@ -817,7 +817,7 @@ void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CSt applyBattleEffects(bat, att, stack, distance, true); } } - + //now add effect info for all attacked stacks for(BattleStackAttacked & bsa : bat.bsa) { @@ -828,7 +828,7 @@ void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CSt bsa.spellID = SpellID(bonus->subtype); } } - + } } void CGameHandler::applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary) //helper function for prepareAttack @@ -917,7 +917,7 @@ void CGameHandler::handleConnection(std::set players, CConnection & c << &applied; }; - CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object + CBaseForGHApply *apply = applier->apps[packType]; //and appropriate applier object if(isBlockedByQueries(pack, player)) { sendPackageResponse(false); @@ -1026,7 +1026,7 @@ int CGameHandler::moveStack(int stack, BattleHex dest) int v = path.first.size()-1; bool stackIsMoving = true; - + while(stackIsMoving) { if(vstopsMovement() || !curStack->alive()) stackIsMoving = false; - obs.reset(); + obs.reset(); } }; - + processObstacle(obstacle); if(curStack->alive()) processObstacle(obstacle2); @@ -1105,14 +1105,14 @@ int CGameHandler::moveStack(int stack, BattleHex dest) if(curStack->alive() && curStack->doubleWide()) { BattleHex otherHex = curStack->occupiedHex(curStack->position); - + if(otherHex.isValid()) if(auto theLastObstacle = battleGetObstacleOnPos(otherHex, false)) { //two hex creature hit obstacle by backside handleDamageFromObstacle(*theLastObstacle, curStack); } - } + } return ret; } @@ -1125,7 +1125,7 @@ CGameHandler::CGameHandler(void) registerTypesServerPacks(*applier); visitObjectAfterVictory = false; queries.gh = this; - + spellEnv = new ServerSpellCastEnvironment(this); } @@ -3907,8 +3907,8 @@ bool CGameHandler::makeBattleAction( BattleAction &ba ) complain("That stack can't cast spells!"); else { - const CSpell * spell = SpellID(spellID).toSpell(); - BattleSpellCastParameters parameters(gs->curB, stack, spell); + const CSpell * spell = SpellID(spellID).toSpell(); + BattleSpellCastParameters parameters(gs->curB, stack, spell); parameters.spellLvl = 0; if (spellcaster) vstd::amax(parameters.spellLvl, spellcaster->val); @@ -3940,12 +3940,12 @@ void CGameHandler::playerMessage( PlayerColor player, const std::string &message { SetMana sm; GiveBonus giveBonus(GiveBonus::HERO); - + CGHeroInstance *h = gs->getHero(currObj); if(!h && complain("Cannot realize cheat, no hero selected!")) return; sm.hid = h->id; - + giveBonus.id = h->id.getNum(); //give all spells with bonus (to allow banned spells) @@ -4107,11 +4107,11 @@ bool CGameHandler::makeCustomAction( BattleAction &ba ) } const CSpell * s = SpellID(ba.additionalInfo).toSpell(); - + BattleSpellCastParameters parameters(gs->curB, h, s); parameters.aimToHex(ba.destinationTile);//todo: allow multiple destinations parameters.mode = ECastingMode::HERO_CASTING; - parameters.selectedStack = gs->curB->battleGetStackByID(ba.selectedStack, false); + parameters.selectedStack = gs->curB->battleGetStackByID(ba.selectedStack, false); ESpellCastProblem::ESpellCastProblem escp = gs->curB->battleCanCastThisSpell(h, s, ECastingMode::HERO_CASTING);//todo: should we check aimed cast(battleCanCastThisSpellHere)? if(escp != ESpellCastProblem::OK) @@ -4123,9 +4123,9 @@ bool CGameHandler::makeCustomAction( BattleAction &ba ) StartAction start_action(ba); sendAndApply(&start_action); //start spell casting - + s->battleCast(spellEnv, parameters); - + sendAndApply(&end_action); if( !gs->curB->battleGetStackByID(gs->curB->activeStack, true)) { @@ -4255,8 +4255,8 @@ void CGameHandler::stackTurnTrigger(const CStack * st) auto bonus = *RandomGeneratorUtil::nextItem(bl, gs->getRandomGenerator()); auto spellID = SpellID(bonus->subtype); const CSpell * spell = SpellID(spellID).toSpell(); - bl.remove_if([&bonus](Bonus * b){return b==bonus;}); - + bl.remove_if([&bonus](Bonus * b){return b==bonus;}); + if (gs->curB->battleCanCastThisSpell(st, spell, ECastingMode::ENCHANTER_CASTING) == ESpellCastProblem::OK) { BattleSpellCastParameters parameters(gs->curB, st, spell); @@ -4265,8 +4265,8 @@ void CGameHandler::stackTurnTrigger(const CStack * st) parameters.aimToHex(BattleHex::INVALID); parameters.mode = ECastingMode::ENCHANTER_CASTING; parameters.selectedStack = nullptr; - - spell->battleCast(spellEnv, parameters); + + spell->battleCast(spellEnv, parameters); //todo: move to mechanics BattleSetStackProperty ssp; @@ -4275,9 +4275,9 @@ void CGameHandler::stackTurnTrigger(const CStack * st) ssp.val = bonus->additionalInfo; //increase cooldown counter ssp.stackID = st->ID; sendAndApply(&ssp); - + cast = true; - } + } }; } bl = *(st->getBonuses(Selector::type(Bonus::ENCHANTED))); @@ -4383,7 +4383,7 @@ void CGameHandler::handleTimeEvents() while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day) { CMapEvent ev = gs->map->events.front(); - + for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++) { auto color = PlayerColor(player); @@ -4973,7 +4973,7 @@ void CGameHandler::attackCasting(const BattleAttack & bat, Bonus::BonusType atta parameters.mode = ECastingMode::AFTER_ATTACK_CASTING; parameters.selectedStack = nullptr; - spell->battleCast(spellEnv, parameters); + spell->battleCast(spellEnv, parameters); } } } @@ -4990,7 +4990,7 @@ void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat ) const CStack * attacker = gs->curB->battleGetStackByID(bat.stackAttacking); if (!attacker) //could be already dead return; - + auto cast = [=](SpellID spellID, int power) { const CSpell * spell = SpellID(spellID).toSpell(); @@ -4999,13 +4999,13 @@ void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat ) parameters.spellLvl = 0; parameters.effectLevel = 0; parameters.aimToStack(gs->curB->battleGetStackByID(bat.bsa.at(0).stackAttacked)); - parameters.effectPower = power; + parameters.effectPower = power; parameters.mode = ECastingMode::AFTER_ATTACK_CASTING; parameters.selectedStack = nullptr; - spell->battleCast(this->spellEnv, parameters); - }; - + spell->battleCast(this->spellEnv, parameters); + }; + attackCasting(bat, Bonus::SPELL_AFTER_ATTACK, attacker); if(bat.bsa.at(0).newAmount <= 0) @@ -5056,11 +5056,11 @@ void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat ) bool CGameHandler::castSpell(const CGHeroInstance *h, SpellID spellID, const int3 &pos) { const CSpell *s = spellID.toSpell(); - + AdventureSpellCastParameters p; p.caster = h; p.pos = pos; - + return s->adventureCast(spellEnv, p); } @@ -5298,8 +5298,8 @@ void CGameHandler::runBattle() auto h = gs->curB->battleGetFightingHero(i); if(h && h->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL)) { - TBonusListPtr bl = h->getBonuses(Selector::type(Bonus::OPENING_BATTLE_SPELL)); - + TBonusListPtr bl = h->getBonuses(Selector::type(Bonus::OPENING_BATTLE_SPELL)); + for (Bonus *b : *bl) { const CSpell * spell = SpellID(b->subtype).toSpell(); @@ -5308,7 +5308,7 @@ void CGameHandler::runBattle() parameters.effectLevel = 3; parameters.aimToHex(BattleHex::INVALID); parameters.mode = ECastingMode::PASSIVE_CASTING; - parameters.selectedStack = nullptr; + parameters.selectedStack = nullptr; parameters.enchantPower = b->val; spell->battleCast(spellEnv, parameters); } @@ -5347,7 +5347,6 @@ void CGameHandler::runBattle() const CStack *next; while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove()) { - //check for bad morale => freeze int nextStackMorale = next->MoraleVal(); if( nextStackMorale < 0 && @@ -5483,7 +5482,7 @@ void CGameHandler::runBattle() { logGlobal->traceStream() << "Activating " << next->nodeName(); auto nextId = next->ID; - BattleSetActiveStack sas; + BattleSetActiveStack sas; sas.stack = nextId; sendAndApply(&sas); @@ -5900,7 +5899,7 @@ CGameHandler::FinishingBattleHelper::FinishingBattleHelper() ///ServerSpellCastEnvironment ServerSpellCastEnvironment::ServerSpellCastEnvironment(CGameHandler * gh): gh(gh) { - + } void ServerSpellCastEnvironment::sendAndApply(CPackForClient * info) const @@ -5933,4 +5932,3 @@ bool ServerSpellCastEnvironment::moveHero(ObjectInstanceID hid, int3 dst, ui8 te { return gh->moveHero(hid, dst, teleporting, false, asker); } - diff --git a/server/CQuery.cpp b/server/CQuery.cpp index f03e50e63..e3d36b52d 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -97,11 +97,11 @@ CObjectVisitQuery::CObjectVisitQuery(const CGObjectInstance *Obj, const CGHeroIn addPlayer(Hero->tempOwner); } -bool CObjectVisitQuery::blocksPack(const CPack *pack) const +bool CObjectVisitQuery::blocksPack(const CPack *pack) const { //During the visit itself ALL actions are blocked. //(However, the visit may trigger a query above that'll pass some.) - return true; + return true; } void CObjectVisitQuery::onRemoval(CGameHandler *gh, PlayerColor color) @@ -220,7 +220,7 @@ std::vector> Queries::allQueries() return ret; } -void CBattleQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const +void CBattleQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { assert(result); objectVisit.visitedObject->battleFinished(objectVisit.visitingHero, *result); @@ -242,9 +242,14 @@ CBattleQuery::CBattleQuery() } -bool CBattleQuery::blocksPack(const CPack *pack) const +bool CBattleQuery::blocksPack(const CPack *pack) const { - return !dynamic_cast(pack) && !dynamic_cast(pack); + #ifndef __APPLE__ + bool dynamic_success = !dynamic_cast(pack) && !dynamic_cast(pack); + #else + const char * name = typeid(*pack).name(); + return strcmp(name, typeid(MakeAction).name()) && strcmp(name, typeid(MakeCustomAction).name()); + #endif } void CBattleQuery::onRemoval(CGameHandler *gh, PlayerColor color) @@ -252,7 +257,7 @@ void CBattleQuery::onRemoval(CGameHandler *gh, PlayerColor color) gh->battleAfterLevelUp(*result); } -void CGarrisonDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const +void CGarrisonDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { objectVisit.visitedObject->garrisonDialogClosed(objectVisit.visitingHero); } @@ -266,18 +271,18 @@ CGarrisonDialogQuery::CGarrisonDialogQuery(const CArmedInstance *up, const CArme addPlayer(down->tempOwner); } -bool CGarrisonDialogQuery::blocksPack(const CPack *pack) const +bool CGarrisonDialogQuery::blocksPack(const CPack *pack) const { std::set ourIds; ourIds.insert(this->exchangingArmies[0]->id); ourIds.insert(this->exchangingArmies[1]->id); - - if (auto stacks = dynamic_cast(pack)) + if (auto stacks = dynamic_ptr_cast(pack)) { return !vstd::contains(ourIds, stacks->id1) || !vstd::contains(ourIds, stacks->id2); } - if (auto arts = dynamic_cast(pack)) + + if (auto arts = dynamic_ptr_cast(pack)) { if(auto id1 = boost::apply_visitor(GetEngagedHeroIds(), arts->src.artHolder)) if(!vstd::contains(ourIds, *id1)) @@ -288,24 +293,24 @@ bool CGarrisonDialogQuery::blocksPack(const CPack *pack) const return true; return false; } - if (auto dismiss = dynamic_cast(pack)) + if (auto dismiss = dynamic_ptr_cast(pack)) { return !vstd::contains(ourIds, dismiss->id); } - if (auto dismiss = dynamic_cast(pack)) + if (auto dismiss = dynamic_ptr_cast(pack)) { return !vstd::contains(ourIds, dismiss->heroID); } - - if(auto upgrade = dynamic_cast(pack)) + + if(auto upgrade = dynamic_ptr_cast(pack)) { return !vstd::contains(ourIds, upgrade->id); } return CDialogQuery::blocksPack(pack); } -void CBlockingDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const +void CBlockingDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { assert(answer); objectVisit.visitedObject->blockingDialogAnswered(objectVisit.visitingHero, *answer); @@ -319,7 +324,7 @@ CBlockingDialogQuery::CBlockingDialogQuery(const BlockingDialog &bd) void CTeleportDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { - auto obj = dynamic_cast(objectVisit.visitedObject); + auto obj = dynamic_ptr_cast(objectVisit.visitedObject); obj->teleportDialogAnswered(objectVisit.visitingHero, *answer, td.exits); } @@ -342,7 +347,7 @@ void CHeroLevelUpDialogQuery::onRemoval(CGameHandler *gh, PlayerColor color) gh->levelUpHero(hlu.hero, hlu.skills[*answer]); } -void CHeroLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const +void CHeroLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { objectVisit.visitedObject->heroLevelUpDone(objectVisit.visitingHero); } @@ -360,20 +365,20 @@ void CCommanderLevelUpDialogQuery::onRemoval(CGameHandler *gh, PlayerColor color gh->levelUpCommander(clu.hero->commander, clu.skills[*answer]); } -void CCommanderLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const +void CCommanderLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { objectVisit.visitedObject->heroLevelUpDone(objectVisit.visitingHero); } -bool CDialogQuery::endsByPlayerAnswer() const +bool CDialogQuery::endsByPlayerAnswer() const { return true; } -bool CDialogQuery::blocksPack(const CPack *pack) const +bool CDialogQuery::blocksPack(const CPack *pack) const { //We accept only query replies from correct player - if(auto reply = dynamic_cast(pack)) + if(auto reply = dynamic_ptr_cast(pack)) { return !vstd::contains(players, reply->player); } diff --git a/server/StdInc.h b/server/StdInc.h index 7418241e0..e2e51512e 100644 --- a/server/StdInc.h +++ b/server/StdInc.h @@ -8,3 +8,17 @@ #include #include #include + +template +inline const T * dynamic_ptr_cast(const F * ptr) +{ + #ifndef __APPLE__ + return dynamic_cast(ptr); + #else + if (!strcmp(typeid(*ptr).name(), typeid(T).name())) + { + return static_cast(ptr); + } + return nullptr; + #endif +} From fa8a2826963b3089a758beea6e61af0a660bdbf6 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sat, 31 Oct 2015 18:04:06 +0300 Subject: [PATCH 07/53] Fix pthread_mutex_lock abort() in requestActionASAP impl --- AI/VCAI/VCAI.cpp | 35 ++++++++++++++--------------------- server/CGameHandler.cpp | 4 ++-- server/CVCMIServer.cpp | 32 ++++++++++++++++---------------- server/NetPacksServer.cpp | 16 ++++++++-------- server/StdInc.h | 14 ++++++++++++++ 5 files changed, 54 insertions(+), 47 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 6048e6487..b42d9eb64 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -822,7 +822,7 @@ void VCAI::makeTurnInternal() { if (h->movement) logAi->warnStream() << boost::format("hero %s has %d MP left") % h->name % h->movement; - } + } } catch(boost::thread_interrupted &e) { @@ -891,7 +891,7 @@ bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * sourc const CArmedInstance *armies[] = {army, source}; - + //we calculate total strength for each creature type available in armies std::map creToPower; for(auto armyPtr : armies) @@ -988,7 +988,7 @@ void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * } void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other) -{ +{ auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void { bool changeMade = false; @@ -2059,7 +2059,7 @@ void VCAI::tryRealize(Goals::CollectRes & g) cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive); if(cb->getResourceAmount(static_cast(g.resID)) >= g.value) return; - } + } throw cannotFulfillGoalException("I cannot get needed resources by trade!"); } @@ -2277,7 +2277,7 @@ Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool on completeGoal (goal); //completed goal was main goal //TODO: find better condition if (ultimateGoal->fulfillsMe(goal) || maxGoals > searchDepth2) - return sptr(Goals::Invalid()); + return sptr(Goals::Invalid()); } catch(std::exception &e) { @@ -2530,7 +2530,7 @@ int3 VCAI::explorationDesperate(HeroPtr h) //logAi->debugStream() << "Looking for an another place for exploration..."; SectorMap sm(h); int radius = h->getSightRadious(); - + std::vector > tiles; //tiles[distance_to_fow] tiles.resize(radius); @@ -2660,19 +2660,13 @@ void VCAI::finish() void VCAI::requestActionASAP(std::function whatToDo) { -// static boost::mutex m; -// boost::unique_lock mylock(m); - - boost::barrier b(2); - boost::thread newThread([&b,this,whatToDo]() + boost::thread newThread([this, whatToDo]() { - setThreadName("VCAI::requestActionASAP::helper"); + setThreadName("VCAI::requestActionASAP::whatToDo"); SET_GLOBAL_STATE(this); boost::shared_lock gsLock(cb->getGsMutex()); - b.wait(); whatToDo(); }); - b.wait(); } void VCAI::lostHero(HeroPtr h) @@ -2867,8 +2861,8 @@ void AIStatus::heroVisit(const CGObjectInstance *obj, bool started) objectsBeingVisited.push_back(obj); else { - // There can be more than one object visited at the time (eg. hero visits Subterranean Gate - // causing visit to hero on the other side. + // There can be more than one object visited at the time (eg. hero visits Subterranean Gate + // causing visit to hero on the other side. // However, we are guaranteed that start/end visit notification maintain stack order. assert(!objectsBeingVisited.empty()); objectsBeingVisited.pop_back(); @@ -2980,7 +2974,7 @@ void SectorMap::exploreNewSector(crint3 pos, int num, CCallback * cbp) s.embarkmentPoints.push_back(neighPos); } }); - + if(t->visitable) { auto obj = t->visitableObjects.front(); @@ -3036,7 +3030,7 @@ bool isWeeklyRevisitable (const CGObjectInstance * obj) bool shouldVisit(HeroPtr h, const CGObjectInstance * obj) { switch (obj->ID) - { + { case Obj::TOWN: case Obj::HERO: //never visit our heroes at random return obj->tempOwner != h->tempOwner; //do not visit our towns at random @@ -3087,7 +3081,7 @@ bool shouldVisit(HeroPtr h, const CGObjectInstance * obj) return canRecruitCreatures; } case Obj::HILL_FORT: - { + { for (auto slot : h->Slots()) { if (slot.second->type->upgrades.size()) @@ -3386,7 +3380,7 @@ void SectorMap::makeParentBFS(crint3 source) ui8 &sec = retreiveTile(curPos); assert(sec == mySector); //consider only tiles from the same sector UNUSED(sec); - + foreach_neighbour(curPos, [&](crint3 neighPos) { if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos)) @@ -3405,4 +3399,3 @@ unsigned char & SectorMap::retreiveTile(crint3 pos) { return retreiveTileN(sector, pos); } - diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 9a13c3285..3529c7d0b 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -5688,7 +5688,7 @@ bool CGameHandler::isValidObject(const CGObjectInstance *obj) const bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player) { - if(dynamic_cast(pack)) + if(!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name())) return false; auto query = queries.topQuery(player); @@ -5826,7 +5826,7 @@ CasualtiesAfterBattle::CasualtiesAfterBattle(const CArmedInstance *army, BattleI auto warMachine = VLC->arth->creatureToMachineID(st->type->idNumber); if (warMachine != ArtifactID::NONE) { - auto hero = dynamic_cast (army); + auto hero = dynamic_ptr_cast (army); if (hero) removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true))); } diff --git a/server/CVCMIServer.cpp b/server/CVCMIServer.cpp index 1dc10fe67..cb8b690f8 100644 --- a/server/CVCMIServer.cpp +++ b/server/CVCMIServer.cpp @@ -86,8 +86,8 @@ void CPregameServer::handleConnection(CConnection *cpc) logNetwork->infoStream() << "Got package to announce " << typeid(*cpfs).name() << " from " << *cpc; boost::unique_lock queueLock(mx); - bool quitting = dynamic_cast(cpfs), - startingGame = dynamic_cast(cpfs); + bool quitting = dynamic_ptr_cast(cpfs), + startingGame = dynamic_ptr_cast(cpfs); if(quitting || startingGame) //host leaves main menu or wants to start game -> we end { cpc->receivedStop = true; @@ -258,11 +258,11 @@ void CPregameServer::sendPack(CConnection * pc, const CPackForSelectionScreen & *pc << &pack; } - if(dynamic_cast(&pack)) + if(dynamic_ptr_cast(&pack)) { pc->sendStop = true; } - else if(dynamic_cast(&pack)) + else if(dynamic_ptr_cast(&pack)) { pc->sendStop = true; } @@ -270,25 +270,25 @@ void CPregameServer::sendPack(CConnection * pc, const CPackForSelectionScreen & void CPregameServer::processPack(CPackForSelectionScreen * pack) { - if(dynamic_cast(pack)) + if(dynamic_ptr_cast(pack)) { sendPack(host, *pack); } - else if(SelectMap *sm = dynamic_cast(pack)) + else if(SelectMap *sm = dynamic_ptr_cast(pack)) { vstd::clear_pointer(curmap); curmap = sm->mapInfo; sm->free = false; announcePack(*pack); } - else if(UpdateStartOptions *uso = dynamic_cast(pack)) + else if(UpdateStartOptions *uso = dynamic_ptr_cast(pack)) { vstd::clear_pointer(curStartInfo); curStartInfo = uso->options; uso->free = false; announcePack(*pack); } - else if(dynamic_cast(pack)) + else if(dynamic_ptr_cast(pack)) { state = ENDING_AND_STARTING_GAME; announcePack(*pack); @@ -307,7 +307,7 @@ void CPregameServer::initConnection(CConnection *c) } void CPregameServer::startListeningThread(CConnection * pc) -{ +{ listeningThreads++; pc->enterPregameConnectionMode(); pc->handler = new boost::thread(&CPregameServer::handleConnection, this, pc); @@ -355,7 +355,7 @@ void CVCMIServer::newGame() { CConnection &c = *firstConnection; ui8 clients; - c >> clients; //how many clients should be connected + c >> clients; //how many clients should be connected assert(clients == 1); //multi goes now by newPregame, TODO: custom lobbies CGameHandler *gh = initGhFromHostingConnection(c); @@ -469,14 +469,14 @@ void CVCMIServer::loadGame() // char sig[8]; // CMapHeader dum; // StartInfo *si; -// +// // CLoadFile lf(CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::LIB_SAVEGAME))); // lf >> sig >> dum >> si; // logNetwork->infoStream() <<"Reading save signature"; -// +// // lf >> *VLC; // logNetwork->infoStream() <<"Reading handlers"; -// +// // lf >> (gh.gs); // c.addStdVecItems(gh.gs); // logNetwork->infoStream() <<"Reading gamestate"; @@ -493,7 +493,7 @@ void CVCMIServer::loadGame() CConnection* cc; //tcp::socket * ss; for(int i=0; iteleportHero(hid,dest,source,gh->getPlayerAt(c)); } @@ -126,7 +126,7 @@ bool GarrisonHeroSwap::applyGh( CGameHandler *gh ) { const CGTownInstance * town = gh->getTown(tid); if (!PLAYER_OWNS(tid) && !( town->garrisonHero && PLAYER_OWNS(town->garrisonHero->id) ) ) - ERROR_AND_RETURN;//neither town nor garrisoned hero (if present) is ours + ERROR_AND_RETURN;//neither town nor garrisoned hero (if present) is ours return gh->garrisonSwap(tid); } @@ -201,7 +201,7 @@ bool TradeOnMarketplace::applyGh( CGameHandler *gh ) } bool SetFormation::applyGh( CGameHandler *gh ) -{ +{ ERROR_IF_NOT_OWNS(hid); return gh->setFormation(hid,formation); } @@ -209,7 +209,7 @@ bool SetFormation::applyGh( CGameHandler *gh ) bool HireHero::applyGh( CGameHandler *gh ) { const CGObjectInstance *obj = gh->getObj(tid); - const CGTownInstance *town = dynamic_cast(obj); + const CGTownInstance *town = dynamic_ptr_cast(obj); if(town && PlayerRelations::ENEMIES == gh->getPlayerRelations(obj->tempOwner, gh->getPlayerAt(c))) COMPLAIN_AND_RETURN("Can't buy hero in enemy town!"); @@ -240,16 +240,16 @@ bool MakeAction::applyGh( CGameHandler *gh ) { const BattleInfo *b = GS(gh)->curB; if(!b) ERROR_AND_RETURN; - + if(b->tacticDistance) { - if(ba.actionType != Battle::WALK && ba.actionType != Battle::END_TACTIC_PHASE + if(ba.actionType != Battle::WALK && ba.actionType != Battle::END_TACTIC_PHASE && ba.actionType != Battle::RETREAT && ba.actionType != Battle::SURRENDER) ERROR_AND_RETURN; - if(gh->connections[b->sides[b->tacticsSide].color] != c) + if(gh->connections[b->sides[b->tacticsSide].color] != c) ERROR_AND_RETURN; } - else if(gh->connections[b->battleGetStackByID(b->activeStack)->owner] != c) + else if(gh->connections[b->battleGetStackByID(b->activeStack)->owner] != c) ERROR_AND_RETURN; return gh->makeBattleAction(ba); diff --git a/server/StdInc.h b/server/StdInc.h index e2e51512e..08c4b8424 100644 --- a/server/StdInc.h +++ b/server/StdInc.h @@ -22,3 +22,17 @@ inline const T * dynamic_ptr_cast(const F * ptr) return nullptr; #endif } + +template +inline T * dynamic_ptr_cast(F * ptr) +{ + #ifndef __APPLE__ + return dynamic_cast(ptr); + #else + if (!strcmp(typeid(*ptr).name(), typeid(T).name())) + { + return static_cast(ptr); + } + return nullptr; + #endif +} From e6e975e9ef0c1d74db4ccc01a54ebf9634edb649 Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sat, 31 Oct 2015 20:23:13 +0300 Subject: [PATCH 08/53] Fix adventure map movement segfault in some scenarios --- client/windows/CAdvmapInterface.cpp | 35 +++++++++++++++-------------- lib/CGameState.cpp | 10 ++++----- lib/CGameStateFwd.h | 2 +- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/client/windows/CAdvmapInterface.cpp b/client/windows/CAdvmapInterface.cpp index e1b96e049..92622c738 100644 --- a/client/windows/CAdvmapInterface.cpp +++ b/client/windows/CAdvmapInterface.cpp @@ -62,9 +62,9 @@ CAdvMapInt *adventureInt; CTerrainRect::CTerrainRect() - : fadeSurface(nullptr), + : fadeSurface(nullptr), fadeAnim(new CFadeAnimation()), - curHoveredTile(-1,-1,-1), + curHoveredTile(-1,-1,-1), currentPath(nullptr) { tilesw=(ADVOPT.advmapW+31)/32; @@ -283,7 +283,7 @@ void CTerrainRect::show(SDL_Surface * to) info.heroAnim = adventureInt->heroAnim; if (ADVOPT.smoothMove) info.movement = int3(moveX, moveY, 0); - + lastRedrawStatus = CGI->mh->drawTerrainRectNew(to, &info); if (fadeAnim->isFading()) { @@ -316,7 +316,7 @@ void CTerrainRect::showAll(SDL_Surface * to) } void CTerrainRect::showAnim(SDL_Surface * to) -{ +{ if (fadeAnim->isFading()) show(to); else if (lastRedrawStatus == EMapAnimRedrawStatus::REDRAW_REQUESTED) @@ -357,7 +357,7 @@ void CTerrainRect::fadeFromCurrentView() return; if (adventureInt->mode == EAdvMapMode::WORLD_VIEW) return; - + if (!fadeSurface) fadeSurface = CSDL_Ext::newSurface(pos.w, pos.h); SDL_BlitSurface(screen, &pos, fadeSurface, nullptr); @@ -502,10 +502,10 @@ CAdvMapInt::CAdvMapInt(): endTurn = makeButton(302, std::bind(&CAdvMapInt::fendTurn,this), ADVOPT.endTurn, SDLK_e); int panelSpaceBottom = screen->h - resdatabar.pos.h - 4; - + panelMain = new CAdvMapPanel(nullptr, Point(0, 0)); // TODO correct drawing position - panelWorldView = new CAdvMapWorldViewPanel(bgWorldView, Point(heroList.pos.x - 2, 195), panelSpaceBottom, LOCPLINT->playerID); + panelWorldView = new CAdvMapWorldViewPanel(bgWorldView, Point(heroList.pos.x - 2, 195), panelSpaceBottom, LOCPLINT->playerID); panelMain->addChildColorableButton(kingOverview); panelMain->addChildColorableButton(underground); @@ -593,7 +593,7 @@ CAdvMapInt::CAdvMapInt(): Colors::WHITE, CGI->generaltexth->allTexts[618])); activeMapPanel = panelMain; - + changeMode(EAdvMapMode::NORMAL); underground->block(!CGI->mh->map->twoLevel); @@ -966,7 +966,7 @@ void CAdvMapInt::show(SDL_Surface * to) for(int i=0;i<4;i++) blitAt(gems[i]->ourImages[LOCPLINT->playerID.getNum()].bitmap,ADVOPT.gemX[i],ADVOPT.gemY[i],to); } - + infoBar.show(to); statusbar.showAll(to); } @@ -981,7 +981,7 @@ void CAdvMapInt::selectionChanged() void CAdvMapInt::centerOn(int3 on, bool fade /* = false */) { bool switchedLevels = on.z != position.z; - + if (fade) { terrain.fadeFromCurrentView(); @@ -1534,7 +1534,9 @@ void CAdvMapInt::tileHovered(const int3 &mapPos) } else if(const CGHeroInstance *h = curHero()) { - const CGPathNode *pnode = LOCPLINT->cb->getPathsInfo(h)->getPathInfo(mapPos); + int3 mapPosCopy = mapPos; + const CGPathNode *pnode = LOCPLINT->cb->getPathsInfo(h)->getPathInfo(mapPosCopy); + assert(pnode); int turns = pnode->turns; vstd::amin(turns, 3); @@ -1780,9 +1782,9 @@ void CAdvMapInt::changeMode(EAdvMapMode newMode, float newScale /* = 0.4f */) townList.activate(); heroList.activate(); infoBar.activate(); - + worldViewOptions.clear(); - + break; case EAdvMapMode::WORLD_VIEW: panelMain->deactivate(); @@ -1852,14 +1854,13 @@ CAdvMapInt::WorldViewOptions::WorldViewOptions() void CAdvMapInt::WorldViewOptions::clear() { showAllTerrain = false; - + iconPositions.clear(); } void CAdvMapInt::WorldViewOptions::adjustDrawingInfo(MapDrawingInfo& info) { info.showAllTerrain = showAllTerrain; - - info.additionalIcons = &iconPositions; -} + info.additionalIcons = &iconPositions; +} diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 41b138b08..51f8e8bd5 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -674,8 +674,8 @@ void CGameState::randomizeObject(CGObjectInstance *cur) } else { - cur->setType(ran.first, ran.second); - } + cur->setType(ran.first, ran.second); + } } int CGameState::getDate(Date::EDateType mode) const @@ -2899,11 +2899,11 @@ bool CGPathNode::reachable() const return turns < 255; } -const CGPathNode * CPathsInfo::getPathInfo( int3 tile ) const +const CGPathNode * CPathsInfo::getPathInfo( const int3& tile ) const { boost::unique_lock pathLock(pathMx); - - if (tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z) + if (tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z || + tile.x < 0 || tile.y < 0 || tile.z < 0) return nullptr; return &nodes[tile.x][tile.y][tile.z]; } diff --git a/lib/CGameStateFwd.h b/lib/CGameStateFwd.h index 5dc1672b6..8e6196ef1 100644 --- a/lib/CGameStateFwd.h +++ b/lib/CGameStateFwd.h @@ -158,7 +158,7 @@ struct DLL_LINKAGE CPathsInfo int3 sizes; CGPathNode ***nodes; //[w][h][level] - const CGPathNode * getPathInfo( int3 tile ) const; + const CGPathNode * getPathInfo( const int3& tile ) const; bool getPath(const int3 &dst, CGPath &out) const; int getDistance( int3 tile ) const; CPathsInfo(const int3 &Sizes); From 5c623868bf814cecb160d7cf92a0ab0c8f54a78c Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sat, 31 Oct 2015 23:01:22 +0300 Subject: [PATCH 09/53] Fix invalid dynamic_cast replacement --- server/CQuery.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/CQuery.cpp b/server/CQuery.cpp index e3d36b52d..7e1a53433 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -324,7 +324,7 @@ CBlockingDialogQuery::CBlockingDialogQuery(const BlockingDialog &bd) void CTeleportDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { - auto obj = dynamic_ptr_cast(objectVisit.visitedObject); + auto obj = dynamic_cast(objectVisit.visitedObject); obj->teleportDialogAnswered(objectVisit.visitingHero, *answer, td.exits); } From 1bcfa986e4243bb4a17b3d6d632e04011fc7cf93 Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 1 Nov 2015 01:52:43 +0300 Subject: [PATCH 10/53] Apply fixes to pathfinder --- lib/CPathfinder.cpp | 5 +++-- lib/CPathfinder.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 2eae0500c..df7fadb53 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -479,11 +479,12 @@ CPathsInfo::~CPathsInfo() delete [] nodes; } -const CGPathNode * CPathsInfo::getPathInfo( int3 tile ) const +const CGPathNode * CPathsInfo::getPathInfo(const int3& tile) const { boost::unique_lock pathLock(pathMx); - if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z) + if(tile.x >= sizes.x || tile.y >= sizes.y || tile.z >= sizes.z + || tile.x < 0 || tile.y < 0 || tile.z < 0) return nullptr; return &nodes[tile.x][tile.y][tile.z]; } diff --git a/lib/CPathfinder.h b/lib/CPathfinder.h index 38d13821e..43615456d 100644 --- a/lib/CPathfinder.h +++ b/lib/CPathfinder.h @@ -61,7 +61,7 @@ struct DLL_LINKAGE CPathsInfo CPathsInfo(const int3 &Sizes); ~CPathsInfo(); - const CGPathNode * getPathInfo( int3 tile ) const; + const CGPathNode * getPathInfo(const int3& tile) const; bool getPath(const int3 &dst, CGPath &out) const; int getDistance( int3 tile ) const; }; From 05a34fb417f8ac5ddc9c222bd1ef9c39fd2ff2cd Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Sun, 6 Dec 2015 02:23:41 +0300 Subject: [PATCH 11/53] Use "Favorable" instead of "Favourable" everywhere for consistency Original game of course used american english version so we stick to it. --- client/mapHandler.cpp | 2 +- lib/BattleState.cpp | 2 +- lib/CGameState.cpp | 2 +- lib/CPathfinder.cpp | 2 +- lib/GameConstants.h | 4 ++-- lib/mapping/CMap.cpp | 2 +- lib/mapping/CMapDefines.h | 4 ++-- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/client/mapHandler.cpp b/client/mapHandler.cpp index e50d4a959..28ae41067 100644 --- a/client/mapHandler.cpp +++ b/client/mapHandler.cpp @@ -1576,7 +1576,7 @@ void CMapHandler::getTerrainDescr( const int3 &pos, std::string & out, bool terN } } - if(t.hasFavourableWinds()) + if(t.hasFavorableWinds()) out = CGI->objtypeh->getObjectName(Obj::FAVORABLE_WINDS); else if(terName) { diff --git a/lib/BattleState.cpp b/lib/BattleState.cpp index e0cf02c99..e7a0d4783 100644 --- a/lib/BattleState.cpp +++ b/lib/BattleState.cpp @@ -719,7 +719,7 @@ BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldTy {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD}, {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND}, {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG}, - {BFieldType::FAVOURABLE_WINDS, BattlefieldBI::NONE}, + {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE}, {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS}, {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND}, {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS}, diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 505b78133..1fb50596d 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -1939,7 +1939,7 @@ BFieldType CGameState::battleGetBattlefieldType(int3 tile) case Obj::EVIL_FOG: return BFieldType::EVIL_FOG; case Obj::FAVORABLE_WINDS: - return BFieldType::FAVOURABLE_WINDS; + return BFieldType::FAVORABLE_WINDS; case Obj::FIERY_FIELDS: return BFieldType::FIERY_FIELDS; case Obj::HOLY_GROUNDS: diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 2af70b48a..b59e30e00 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -987,7 +987,7 @@ int CPathfinderHelper::getMovementCost(const CGHeroInstance * h, const int3 & sr } else if(dt->terType == ETerrainType::WATER) { - if(h->boat && ct->hasFavourableWinds() && dt->hasFavourableWinds()) //Favourable Winds + if(h->boat && ct->hasFavorableWinds() && dt->hasFavorableWinds()) ret *= 0.666; else if(!h->boat && ti->hasBonusOfType(Bonus::WATER_WALKING)) { diff --git a/lib/GameConstants.h b/lib/GameConstants.h index ad13b9a7c..6756e6689 100644 --- a/lib/GameConstants.h +++ b/lib/GameConstants.h @@ -837,10 +837,10 @@ public: // 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines //8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields //15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog - //21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship + //21. "favorable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship enum EBFieldType {NONE = -1, NONE2, SAND_SHORE, SAND_MESAS, DIRT_BIRCHES, DIRT_HILLS, DIRT_PINES, GRASS_HILLS, GRASS_PINES, LAVA, MAGIC_PLAINS, SNOW_MOUNTAINS, SNOW_TREES, SUBTERRANEAN, SWAMP_TREES, FIERY_FIELDS, - ROCKLANDS, MAGIC_CLOUDS, LUCID_POOLS, HOLY_GROUND, CLOVER_FIELD, EVIL_FOG, FAVOURABLE_WINDS, CURSED_GROUND, + ROCKLANDS, MAGIC_CLOUDS, LUCID_POOLS, HOLY_GROUND, CLOVER_FIELD, EVIL_FOG, FAVORABLE_WINDS, CURSED_GROUND, ROUGH, SHIP_TO_SHIP, SHIP }; diff --git a/lib/mapping/CMap.cpp b/lib/mapping/CMap.cpp index ddc620332..cdf968035 100644 --- a/lib/mapping/CMap.cpp +++ b/lib/mapping/CMap.cpp @@ -158,7 +158,7 @@ EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const return EDiggingStatus::CAN_DIG; } -bool TerrainTile::hasFavourableWinds() const +bool TerrainTile::hasFavorableWinds() const { return extTileFlags & 128; } diff --git a/lib/mapping/CMapDefines.h b/lib/mapping/CMapDefines.h index 77f9bf0be..aff08b444 100644 --- a/lib/mapping/CMapDefines.h +++ b/lib/mapping/CMapDefines.h @@ -72,7 +72,7 @@ struct DLL_LINKAGE TerrainTile bool isWater() const; bool isCoastal() const; EDiggingStatus getDiggingStatus(const bool excludeTop = true) const; - bool hasFavourableWinds() const; + bool hasFavorableWinds() const; ETerrainType terType; ui8 terView; @@ -81,7 +81,7 @@ struct DLL_LINKAGE TerrainTile ERoadType::ERoadType roadType; ui8 roadDir; /// first two bits - how to rotate terrain graphic (next two - river graphic, next two - road); - /// 7th bit - whether tile is coastal (allows disembarking if land or block movement if water); 8th bit - Favourable Winds effect + /// 7th bit - whether tile is coastal (allows disembarking if land or block movement if water); 8th bit - Favorable Winds effect ui8 extTileFlags; bool visitable; bool blocked; From e872b400b7ce5ec4778225a3a8e8fbd2ce4b8745 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Sun, 6 Dec 2015 02:51:54 +0300 Subject: [PATCH 12/53] Comments save format backward compatability code as Ivan suggested Also we should always handle RumorState::TYPE_NONE in getTavernRumor properly anyway. --- lib/CGameInfoCallback.cpp | 2 +- lib/CGameState.h | 2 +- lib/mapObjects/CGHeroInstance.h | 2 +- lib/spells/CSpellHandler.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/CGameInfoCallback.cpp b/lib/CGameInfoCallback.cpp index 249b6fe8b..66080b7aa 100644 --- a/lib/CGameInfoCallback.cpp +++ b/lib/CGameInfoCallback.cpp @@ -577,7 +577,7 @@ EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bo std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const { std::string text = "", extraText = ""; - if(gs->rumor.type == RumorState::TYPE_NONE) // (version < 755 backward compatability + if(gs->rumor.type == RumorState::TYPE_NONE) return text; auto rumor = gs->rumor.last[gs->rumor.type]; diff --git a/lib/CGameState.h b/lib/CGameState.h index b91f4e106..e7ddb89ee 100644 --- a/lib/CGameState.h +++ b/lib/CGameState.h @@ -249,7 +249,7 @@ public: template void serialize(Handler &h, const int version) { h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects & rand; - if(version >= 755) + if(version >= 755) //save format backward compatibility { h & rumor; } diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index 16d0ae633..a6cc59cb1 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -79,7 +79,7 @@ public: template void serialize(Handler &h, const int version) { h & patrolling; - if(version >= 755) + if(version >= 755) //save format backward compatibility { h & initialPos; } diff --git a/lib/spells/CSpellHandler.h b/lib/spells/CSpellHandler.h index 332b7396e..71c36ddcc 100644 --- a/lib/spells/CSpellHandler.h +++ b/lib/spells/CSpellHandler.h @@ -75,7 +75,7 @@ public: template void serialize(Handler & h, const int version) { h & resourceName & verticalPosition; - if(version >= 754) + if(version >= 754) //save format backward compatibility { h & pause; } From 807fd6391b8aedc31899bdc54e14eac33bf817ec Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Sun, 6 Dec 2015 03:12:39 +0300 Subject: [PATCH 13/53] CAdvMapInt: block spellbook button when no hero selected --- client/windows/CAdvmapInterface.cpp | 7 +++++++ client/windows/CAdvmapInterface.h | 1 + 2 files changed, 8 insertions(+) diff --git a/client/windows/CAdvmapInterface.cpp b/client/windows/CAdvmapInterface.cpp index 940a1a655..77483bf99 100644 --- a/client/windows/CAdvmapInterface.cpp +++ b/client/windows/CAdvmapInterface.cpp @@ -767,6 +767,11 @@ void CAdvMapInt::updateMoveHero(const CGHeroInstance *h, tribool hasPath) moveHero->block(!hasPath || (h->movement == 0)); } +void CAdvMapInt::updateSpellbook(const CGHeroInstance *h) +{ + spellbook->block(!h); +} + int CAdvMapInt::getNextHeroIndex(int startIndex) { if (LOCPLINT->wanderingHeroes.size() == 0) @@ -1262,6 +1267,7 @@ void CAdvMapInt::select(const CArmedInstance *sel, bool centerView /*= true*/) updateSleepWake(nullptr); updateMoveHero(nullptr); + updateSpellbook(nullptr); } else //hero selected { @@ -1275,6 +1281,7 @@ void CAdvMapInt::select(const CArmedInstance *sel, bool centerView /*= true*/) updateSleepWake(hero); updateMoveHero(hero); + updateSpellbook(hero); } townList.redraw(); heroList.redraw(); diff --git a/client/windows/CAdvmapInterface.h b/client/windows/CAdvmapInterface.h index b5cb39a05..72f8fbdbf 100644 --- a/client/windows/CAdvmapInterface.h +++ b/client/windows/CAdvmapInterface.h @@ -235,6 +235,7 @@ public: //button updates void updateSleepWake(const CGHeroInstance *h); void updateMoveHero(const CGHeroInstance *h, tribool hasPath = boost::logic::indeterminate); + void updateSpellbook(const CGHeroInstance *h); void updateNextHero(const CGHeroInstance *h); /// changes current adventure map mode; used to switch between default view and world view; scale is ignored if EAdvMapMode == NORMAL From 03e9dd3bab27d951b0a9c3acbe1fead2836d71ee Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Mon, 7 Dec 2015 00:13:58 +0300 Subject: [PATCH 14/53] Add hero gold cost to GameConstants --- AI/VCAI/AIUtility.h | 1 - AI/VCAI/Goals.cpp | 4 ++-- AI/VCAI/VCAI.cpp | 4 ++-- client/windows/GUIClasses.cpp | 4 ++-- lib/GameConstants.h | 1 + server/CGameHandler.cpp | 5 ++--- 6 files changed, 9 insertions(+), 10 deletions(-) diff --git a/AI/VCAI/AIUtility.h b/AI/VCAI/AIUtility.h index bb551e51b..507b3417c 100644 --- a/AI/VCAI/AIUtility.h +++ b/AI/VCAI/AIUtility.h @@ -23,7 +23,6 @@ class CCallback; typedef const int3& crint3; typedef const std::string& crstring; -const int HERO_GOLD_COST = 2500; const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1; const int ACTUAL_RESOURCE_COUNT = 7; const int ALLOWED_ROAMING_HEROES = 8; diff --git a/AI/VCAI/Goals.cpp b/AI/VCAI/Goals.cpp index 40406f214..dcb4f8ba6 100644 --- a/AI/VCAI/Goals.cpp +++ b/AI/VCAI/Goals.cpp @@ -693,8 +693,8 @@ TSubgoal RecruitHero::whatToDoToAchieve() if(!t) return sptr (Goals::BuildThis(BuildingID::TAVERN)); - if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST) - return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST)); + if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) + return sptr (Goals::CollectRes(Res::GOLD, GameConstants::HERO_GOLD_COST)); return iAmElementar(); } diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index d9cf52f5c..b6ab8a559 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1445,7 +1445,7 @@ bool VCAI::canRecruitAnyHero (const CGTownInstance * t) const if (!t) t = findTownWithTavern(); if (t) - return cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && + return cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size(); else @@ -1530,7 +1530,7 @@ void VCAI::wander(HeroPtr h) } break; } - else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST) + else if(cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST) { std::vector towns = cb->getTownsInfo(); erase_if(towns, [](const CGTownInstance *t) -> bool diff --git a/client/windows/GUIClasses.cpp b/client/windows/GUIClasses.cpp index 79456e908..fecff8783 100644 --- a/client/windows/GUIClasses.cpp +++ b/client/windows/GUIClasses.cpp @@ -704,7 +704,7 @@ CTavernWindow::CTavernWindow(const CGObjectInstance *TavernObj): oldSelected = -1; new CLabel(200, 35, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]); - new CLabel(320, 328, FONT_SMALL, CENTER, Colors::WHITE, "2500"); + new CLabel(320, 328, FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast(GameConstants::HERO_GOLD_COST)); auto rumorText = boost::str(boost::format(CGI->generaltexth->allTexts[216]) % LOCPLINT->cb->getTavernRumor(tavernObj)); new CTextBox(rumorText, Rect(32, 190, 330, 68), 0, FONT_SMALL, CENTER, Colors::WHITE); @@ -714,7 +714,7 @@ CTavernWindow::CTavernWindow(const CGObjectInstance *TavernObj): recruit = new CButton(Point(272, 355), "TPTAV01.DEF", CButton::tooltip(), std::bind(&CTavernWindow::recruitb, this), SDLK_RETURN); thiefGuild = new CButton(Point(22, 428), "TPTAV02.DEF", CButton::tooltip(CGI->generaltexth->tavernInfo[5]), std::bind(&CTavernWindow::thievesguildb, this), SDLK_t); - if(LOCPLINT->cb->getResourceAmount(Res::GOLD) < 2500) //not enough gold + if(LOCPLINT->cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //not enough gold { recruit->addHoverText(CButton::NORMAL, CGI->generaltexth->tavernInfo[0]); //Cannot afford a Hero recruit->block(true); diff --git a/lib/GameConstants.h b/lib/GameConstants.h index 6756e6689..ee103f5a7 100644 --- a/lib/GameConstants.h +++ b/lib/GameConstants.h @@ -33,6 +33,7 @@ namespace GameConstants const int SPELL_SCHOOL_LEVELS = 4; const int CRE_LEVELS = 10; // number of creature experience levels + const int HERO_GOLD_COST = 2500; const int SPELLBOOK_GOLD_COST = 500; const int BATTLE_PENALTY_DISTANCE = 10; //if the distance is > than this, then shooting stack has distance penalty const int ARMY_SIZE = 7; diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 85c1aec3e..4267cef54 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -3313,12 +3313,11 @@ bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor pl { const PlayerState *p = gs->getPlayer(player); const CGTownInstance *t = gs->getTown(obj->id); - static const int GOLD_NEEDED = 2500; //common preconditions // if( (p->resources.at(Res::GOLD)= GameConstants::MAX_HEROES_PER_PLAYER && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))) - if( (p->resources.at(Res::GOLD)resources.at(Res::GOLD) < GameConstants::HERO_GOLD_COST && complain("Not enough gold for buying hero!")) || ((!t) && (getHeroCount(player, false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER && complain("Cannot hire hero, too many wandering heroes already!"))) || ((t) && (getHeroCount(player, true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER && complain("Cannot hire hero, too many heroes garrizoned and wandering already!"))) ) @@ -3377,7 +3376,7 @@ bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor pl SetResource sr; sr.player = player; sr.resid = Res::GOLD; - sr.val = p->resources.at(Res::GOLD) - GOLD_NEEDED; + sr.val = p->resources.at(Res::GOLD) - GameConstants::HERO_GOLD_COST; sendAndApply(&sr); if(t) From cf4cb5c948cae489ed7781fef901de09a0d92fda Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 8 Dec 2015 04:18:31 +0300 Subject: [PATCH 15/53] VCAI: silence callback on visibility check --- AI/VCAI/VCAI.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index b6ab8a559..54e45fbf7 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1697,7 +1697,7 @@ void VCAI::validateVisitableObjs() auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool { if (obj) - return !cb->getObj(obj->id); + return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility else return true; From 07807fb044c5d84674ce800db6344f91b8513df0 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 8 Dec 2015 07:33:13 +0300 Subject: [PATCH 16/53] Client: slience visibility error on shipyard in non-coastal town --- AI/VCAI/VCAI.cpp | 2 +- client/windows/CCastleInterface.cpp | 7 +++++-- lib/mapObjects/CObjectHandler.cpp | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 54e45fbf7..72aa7c2a5 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1784,7 +1784,7 @@ const CGObjectInstance * VCAI::lookForArt(int aid) const { for(const CGObjectInstance *obj : ai->visitableObjs) { - if(obj->ID == 5 && obj->subID == aid) + if(obj->ID == Obj::ARTIFACT && obj->subID == aid) return obj; } diff --git a/client/windows/CCastleInterface.cpp b/client/windows/CCastleInterface.cpp index 9f3ad2438..5f54b8214 100644 --- a/client/windows/CCastleInterface.cpp +++ b/client/windows/CCastleInterface.cpp @@ -230,7 +230,7 @@ std::string CBuildingRect::getSubtitle()//hover text for building } else { - logGlobal->warnStream() << "Problem: dwelling with id " << bid << " offers no creatures!"; + logGlobal->warnStream() << "Problem: dwelling with id " << bid << " offers no creatures!"; return "#ERROR#"; } } @@ -501,7 +501,10 @@ void CCastleBuildings::recreate() if(vstd::contains(town->builtBuildings, BuildingID::SHIPYARD)) { - std::vector vobjs = LOCPLINT->cb->getVisitableObjs(town->bestLocation()); + auto bayPos = town->bestLocation(); + if(!bayPos.valid()) + logGlobal->warnStream() << "Shipyard in non-coastal town!"; + std::vector vobjs = LOCPLINT->cb->getVisitableObjs(bayPos, false); //there is visitable obj at shipyard output tile and it's a boat or hero (on boat) if(!vobjs.empty() && (vobjs.front()->ID == Obj::BOAT || vobjs.front()->ID == Obj::HERO)) { diff --git a/lib/mapObjects/CObjectHandler.cpp b/lib/mapObjects/CObjectHandler.cpp index 88c7e6bd0..8c785b374 100644 --- a/lib/mapObjects/CObjectHandler.cpp +++ b/lib/mapObjects/CObjectHandler.cpp @@ -330,7 +330,7 @@ int3 IBoatGenerator::bestLocation() const { if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map { - if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat + if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == Obj::BOAT)) //and is water and is not blocked or is blocked by boat return o->pos + offset; } } From 1c0d4e3f6fa4357e1cc58759c58b1ae9482c083f Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 8 Dec 2015 09:53:14 +0300 Subject: [PATCH 17/53] Fix filenames in file headers --- AI/VCAI/VCAI.cpp | 2 +- lib/BattleAction.cpp | 2 +- lib/CConfigHandler.h | 2 +- lib/CStopWatch.h | 2 +- lib/StringConstants.h | 2 +- lib/filesystem/CCompressedStream.h | 2 +- lib/mapObjects/JsonRandom.cpp | 2 +- scripting/erm/ERMScriptModule.h | 4 ++-- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 72aa7c2a5..92fbbac5d 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -13,7 +13,7 @@ /* - * CCreatureHandler.h, part of VCMI engine + * VCAI.cpp, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/BattleAction.cpp b/lib/BattleAction.cpp index 0f93315b4..1107fc07a 100644 --- a/lib/BattleAction.cpp +++ b/lib/BattleAction.cpp @@ -4,7 +4,7 @@ #include "BattleState.h" /* - * BattleAction.h, part of VCMI engine + * BattleAction.cpp, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/CConfigHandler.h b/lib/CConfigHandler.h index 1e85c44e0..7f70d826b 100644 --- a/lib/CConfigHandler.h +++ b/lib/CConfigHandler.h @@ -3,7 +3,7 @@ #include "../lib/JsonNode.h" /* - * CConfighandler.h, part of VCMI engine + * CConfigHandler.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/CStopWatch.h b/lib/CStopWatch.h index 201a0e697..3faf4c69c 100644 --- a/lib/CStopWatch.h +++ b/lib/CStopWatch.h @@ -11,7 +11,7 @@ #endif /* - * timeHandler.h, part of VCMI engine + * CStopWatch.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/StringConstants.h b/lib/StringConstants.h index c8ace79c1..3004d3afa 100644 --- a/lib/StringConstants.h +++ b/lib/StringConstants.h @@ -3,7 +3,7 @@ #include "GameConstants.h" /* - * GameConstants.h, part of VCMI engine + * StringConstants.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/filesystem/CCompressedStream.h b/lib/filesystem/CCompressedStream.h index 372e59152..75684c8d9 100644 --- a/lib/filesystem/CCompressedStream.h +++ b/lib/filesystem/CCompressedStream.h @@ -1,7 +1,7 @@ #pragma once /* - * CLodStream.h, part of VCMI engine + * CCompressedStream.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/lib/mapObjects/JsonRandom.cpp b/lib/mapObjects/JsonRandom.cpp index c3a531689..a64271c1e 100644 --- a/lib/mapObjects/JsonRandom.cpp +++ b/lib/mapObjects/JsonRandom.cpp @@ -1,6 +1,6 @@ /* * - * CRewardableObject.cpp, part of VCMI engine + * JsonRandom.cpp, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * diff --git a/scripting/erm/ERMScriptModule.h b/scripting/erm/ERMScriptModule.h index 63002b2a7..1f9123e58 100644 --- a/scripting/erm/ERMScriptModule.h +++ b/scripting/erm/ERMScriptModule.h @@ -3,7 +3,7 @@ #include "../../lib/CScriptingModule.h" /* - * ERMScriptingModule.cpp, part of VCMI engine + * ERMScriptingModule.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * @@ -14,4 +14,4 @@ extern IGameEventRealizer *acb; -extern CPrivilagedInfoCallback *icb; \ No newline at end of file +extern CPrivilagedInfoCallback *icb; From 2be6818e33a39147bb72474c038fa08b811d7f49 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Wed, 9 Dec 2015 10:02:33 +0300 Subject: [PATCH 18/53] FoWChange::applyGs: correct copy-paste error. Fix issue 2345 --- lib/NetPacksLib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 3c76e3333..4c74a1503 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -223,7 +223,7 @@ DLL_LINKAGE void FoWChange::applyGs( CGameState *gs ) case Obj::TOWN: case Obj::ABANDONED_MINE: if(vstd::contains(team->players, o->tempOwner)) //check owned observators - gs->getTilesInRange(tiles, o->getSightCenter(), o->getSightRadious(), o->tempOwner, 1); + gs->getTilesInRange(tilesRevealed, o->getSightCenter(), o->getSightRadious(), o->tempOwner, 1); break; } } From 9e6f836b2584d4c8c1c8a1b3e816a64ae460d3b9 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Wed, 9 Dec 2015 18:49:22 +0300 Subject: [PATCH 19/53] VCAI::pickBestArtifacts: don't try to move catapult between heroes --- AI/VCAI/VCAI.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 92fbbac5d..1b98c9abf 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1052,6 +1052,10 @@ void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * ot if (location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST) continue; //don't reequip artifact we already wear + if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult + continue; + //FIXME: why do we really attempt to move catapults between heroes in first case? + auto s = location.getSlot(); if (!s || s->locked) //we can't move locks continue; From d900e9bec2ec14f55bfd861745515cb6190cd1ed Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Thu, 10 Dec 2015 12:43:55 +0300 Subject: [PATCH 20/53] CGameHandler: fix hero removal code on player loss. Fix issue 2347 --- server/CGameHandler.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 4267cef54..fc7992f13 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -4827,11 +4827,15 @@ void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player) } else { - //player lost -> all his objects become unflagged (neutral) - for (auto h : p->heroes) //eliminate heroes - if (h.get()) + //copy heroes vector to avoid iterator invalidation as removal change PlayerState + auto hlp = p->heroes; + for(auto h : hlp) //eliminate heroes + { + if(h.get()) removeObject(h); + } + //player lost -> all his objects become unflagged (neutral) for (auto obj : gs->map->objects) //unflag objs { if(obj.get() && obj->tempOwner == player) From 5aadc1ed6f11548a2b8994230c30324db3970601 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Thu, 10 Dec 2015 13:31:03 +0300 Subject: [PATCH 21/53] CasualtiesAfterBattle: dont remove catapult artifact. Fix 2346 issue --- AI/VCAI/VCAI.cpp | 1 - server/CGameHandler.cpp | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 1b98c9abf..d965cebda 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1054,7 +1054,6 @@ void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * ot if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult continue; - //FIXME: why do we really attempt to move catapults between heroes in first case? auto s = location.getSlot(); if (!s || s->locked) //we can't move locks diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index fc7992f13..6a16a3656 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -5846,7 +5846,8 @@ CasualtiesAfterBattle::CasualtiesAfterBattle(const CArmedInstance *army, BattleI if (!st->count && !st->base) //we can imagine stacks of war mahcines that are not spawned by artifacts? { auto warMachine = VLC->arth->creatureToMachineID(st->type->idNumber); - if (warMachine != ArtifactID::NONE) + //catapult artifact remain even if "creature" killed in siege + if(warMachine != ArtifactID::NONE && warMachine != ArtifactID::CATAPULT) { auto hero = dynamic_cast (army); if (hero) From c3e5231146ed1c85a4267fb8e127571e2b0dcdf6 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Thu, 10 Dec 2015 16:51:19 +0300 Subject: [PATCH 22/53] CPathfinder: avoid pathing through hero standing on Subterranean Gate Subterranean Gates unlike Monolith allow to visit hero standing on other exit. So of course pathfinder allowed that, but it's also allowed future movement through that hero which caused infinite loop for AI. --- lib/CPathfinder.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index b59e30e00..2212a482a 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -195,8 +195,15 @@ void CPathfinder::calculatePaths() dp->moveRemains = movement; dp->turns = turn; dp->theNodeBefore = cp; - dp->action = CGPathNode::NORMAL; - pq.push(dp); + + dtObj = gs->map->getTile(neighbour).topVisitableObj(); + if(CGTeleport::isTeleport(dtObj)) + { + dp->action = CGPathNode::NORMAL; + pq.push(dp); + } + else + dp->action = getDestAction(); // TODO: We only need to check for hero on other side, but not for guards. } } } //queue loop From 975e049a3e3b6f0e8b07bcbf83789ea58bd7e270 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Thu, 10 Dec 2015 17:35:46 +0300 Subject: [PATCH 23/53] SectorMap: disable knownSubterraneanGates support to avoid loops --- AI/VCAI/VCAI.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index d965cebda..8a87b858c 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -3245,6 +3245,14 @@ For ship construction etc, another function (goal?) is needed } } + +/* + // TODO: this code need to be rewritten in order to work porperly + // And we need to support teleport channels instead of just gates + // + // At moment it's cause more issues than it's solve so it's disabled. + // Check mantis 2119, 2228 and 2212 (Warmonger posts) + for (auto gate : s->subterraneanGates) { auto gatePair = ai->knownSubterraneanGates.find(gate); @@ -3259,6 +3267,7 @@ For ship construction etc, another function (goal?) is needed } } } +*/ } if(!preds[dest]) @@ -3372,6 +3381,9 @@ For ship construction etc, another function (goal?) is needed //TODO: pop sectors linked by Subterranean Gate in loop +/* + // Same as above, check issues 2119, 2228 + auto firstGate = boost::find_if(src->subterraneanGates, [=](const CGObjectInstance * gate) -> bool { //make sure no hero block the way @@ -3386,6 +3398,7 @@ For ship construction etc, another function (goal?) is needed //TODO: pahtfinder can find path through subterranean gates, but this function only reaches closest gate return (*firstGate)->visitablePos(); } +*/ //TODO //Monolith? Whirlpool? ... return ret; From a430769b44d1178154f6aa32f0c6ed2cbe5e1c86 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 04:00:10 +0300 Subject: [PATCH 24/53] CPathfinder: fix possible crash when using invisible teleport exit This one is similar with FoW bug when hero was covered by FoW while one tile around wasn't. --- lib/CPathfinder.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 2212a482a..32b0d6c74 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -189,6 +189,13 @@ void CPathfinder::calculatePaths() dp = out.getNode(neighbour, cp->layer); if(dp->locked) continue; + /// TODO: We may consider use invisible exits on FoW border in future + /// Useful for AI when at least one tile around exit is visible and passable + /// Objects are usually visible on FoW border anyway so it's not cheating. + /// + /// For now it's disabled as it's will cause crashes in movement code. + if(dp->accessible == CGPathNode::BLOCKED) + continue; if(isBetterWay(movement, turn)) { From ab92123da3843e1f356bcbfbbb99f6657850e51f Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 09:42:30 +0300 Subject: [PATCH 25/53] CPathfinder: improve support for visits and battles in teleports Related movement code for client and AI is plumbed as well. Though at moment code still not finished because it's not teleport hero to the exit tile if he won battle. --- AI/VCAI/VCAI.cpp | 39 ++++++++++++++++++++++---- client/CPlayerInterface.cpp | 43 +++++++++++++++++++++++++---- client/windows/CAdvmapInterface.cpp | 3 ++ lib/CPathfinder.cpp | 27 ++++++++++++------ lib/CPathfinder.h | 6 +++- 5 files changed, 98 insertions(+), 20 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 8a87b858c..915e6ebfe 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1879,6 +1879,7 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst; throw goalFulfilledException (sptr(Goals::VisitTile(dst).sethero(h))); } + int i = path.nodes.size()-1; auto getObj = [&](int3 coord, bool ignoreHero) { @@ -1888,6 +1889,31 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) //return cb->getTile(coord,false)->topVisitableObj(ignoreHero); }; + auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool + { + if(action != CGPathNode::TELEPORT_NORMAL && + action != CGPathNode::TELEPORT_BLOCKING_VISIT && + action != CGPathNode::TELEPORT_BATTLE) + { + return false; + } + + return true; + }; + + auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance * + { + if(CGTeleport::isConnected(currentObject, nextObjectTop)) + return nextObjectTop; + if(nextObjectTop && nextObjectTop->ID == Obj::HERO && + CGTeleport::isConnected(currentObject, nextObject)) + { + return nextObject; + } + + return nullptr; + }; + auto doMovement = [&](int3 dst, bool transit) { cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit); @@ -1918,17 +1944,18 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) doTeleportMovement(currentExit, currentPos); }; - int i=path.nodes.size()-1; for(; i>0; i--) { int3 currentCoord = path.nodes[i].coord; int3 nextCoord = path.nodes[i-1].coord; auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos,false)); - auto nextObject = getObj(nextCoord, false); - if(CGTeleport::isConnected(currentObject, nextObject)) + auto nextObjectTop = getObj(nextCoord, false); + auto nextObject = getObj(nextCoord, true); + auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject); + if(isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr) { //we use special login if hero standing on teleporter it's mean we need - doTeleportMovement(nextObject->id, nextCoord); + doTeleportMovement(destTeleportObj->id, nextCoord); if(teleportChannelProbingList.size()) doChannelProbing(); @@ -1947,8 +1974,8 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) continue; if((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless - && (CGTeleport::isConnected(nextObject, getObj(path.nodes[i-2].coord, false)) - || CGTeleport::isTeleport(nextObject))) + && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false)) + || CGTeleport::isTeleport(nextObjectTop))) { // Hero should be able to go through object if it's allow transit doMovement(endpos, true); } diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index 7eedb4431..b0f4a56a6 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -2629,6 +2629,31 @@ void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path) return cb->getTile(CGHeroInstance::convertPosition(coord,false))->topVisitableObj(ignoreHero); }; + auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool + { + if(action != CGPathNode::TELEPORT_NORMAL && + action != CGPathNode::TELEPORT_BLOCKING_VISIT && + action != CGPathNode::TELEPORT_BATTLE) + { + return false; + } + + return true; + }; + + auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance * + { + if(CGTeleport::isConnected(currentObject, nextObjectTop)) + return nextObjectTop; + if(nextObjectTop && nextObjectTop->ID == Obj::HERO && + CGTeleport::isConnected(currentObject, nextObject)) + { + return nextObject; + } + + return nullptr; + }; + boost::unique_lock un(stillMoveHero.mx); stillMoveHero.data = CONTINUE_MOVE; auto doMovement = [&](int3 dst, bool transit) @@ -2661,13 +2686,21 @@ void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path) int3 currentCoord = path.nodes[i].coord; int3 nextCoord = path.nodes[i-1].coord; - auto nextObject = getObj(nextCoord, nextCoord == h->pos); - if(CGTeleport::isConnected(getObj(currentCoord, currentCoord == h->pos), nextObject)) + auto currentObject = getObj(currentCoord, currentCoord == h->pos); + auto nextObjectTop = getObj(nextCoord, false); + auto nextObject = getObj(nextCoord, true); + auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject); + if(isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr) { CCS->soundh->stopSound(sh); - destinationTeleport = nextObject->id; + destinationTeleport = destTeleportObj->id; destinationTeleportPos = nextCoord; doMovement(h->pos, false); + if(path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT) + { + destinationTeleport = ObjectInstanceID(); + destinationTeleportPos = int3(-1); + } sh = CCS->soundh->playSound(CCS->soundh->horseSounds[currentTerrain], -1); continue; } @@ -2700,8 +2733,8 @@ void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path) bool useTransit = false; if((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless - && (CGTeleport::isConnected(nextObject, getObj(path.nodes[i-2].coord, false)) - || CGTeleport::isTeleport(nextObject))) + && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false)) + || CGTeleport::isTeleport(nextObjectTop))) { // Hero should be able to go through object if it's allow transit useTransit = true; } diff --git a/client/windows/CAdvmapInterface.cpp b/client/windows/CAdvmapInterface.cpp index 77483bf99..2ae8f03a9 100644 --- a/client/windows/CAdvmapInterface.cpp +++ b/client/windows/CAdvmapInterface.cpp @@ -1544,6 +1544,7 @@ void CAdvMapInt::tileHovered(const int3 &mapPos) switch(pnode->action) { case CGPathNode::NORMAL: + case CGPathNode::TELEPORT_NORMAL: if(pnode->layer == EPathfindingLayer::LAND) CCS->curh->changeGraphic(ECursor::ADVENTURE, 4 + turns*6); else @@ -1552,6 +1553,7 @@ void CAdvMapInt::tileHovered(const int3 &mapPos) case CGPathNode::VISIT: case CGPathNode::BLOCKING_VISIT: + case CGPathNode::TELEPORT_BLOCKING_VISIT: if(objAtTile && objAtTile->ID == Obj::HERO) { if(selection == objAtTile) @@ -1566,6 +1568,7 @@ void CAdvMapInt::tileHovered(const int3 &mapPos) break; case CGPathNode::BATTLE: + case CGPathNode::TELEPORT_BATTLE: CCS->curh->changeGraphic(ECursor::ADVENTURE, 5 + turns*6); break; diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 32b0d6c74..8120adfaa 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -199,18 +199,14 @@ void CPathfinder::calculatePaths() if(isBetterWay(movement, turn)) { + dtObj = gs->map->getTile(neighbour).topVisitableObj(); + dp->moveRemains = movement; dp->turns = turn; dp->theNodeBefore = cp; - - dtObj = gs->map->getTile(neighbour).topVisitableObj(); - if(CGTeleport::isTeleport(dtObj)) - { - dp->action = CGPathNode::NORMAL; + dp->action = getTeleportDestAction(); + if(dp->action == CGPathNode::TELEPORT_NORMAL) pq.push(dp); - } - else - dp->action = getDestAction(); // TODO: We only need to check for hero on other side, but not for guards. } } } //queue loop @@ -555,6 +551,21 @@ CGPathNode::ENodeAction CPathfinder::getDestAction() const return action; } +CGPathNode::ENodeAction CPathfinder::getTeleportDestAction() const +{ + CGPathNode::ENodeAction action = CGPathNode::TELEPORT_NORMAL; + if(isDestVisitableObj() && dtObj->ID == Obj::HERO) + { + auto objRel = getPlayerRelations(dtObj->tempOwner, hero->tempOwner); + if(objRel == PlayerRelations::ENEMIES) + action = CGPathNode::TELEPORT_BATTLE; + else + action = CGPathNode::TELEPORT_BLOCKING_VISIT; + } + + return action; +} + bool CPathfinder::isSourceInitialPosition() const { return cp->coord == out.hpos; diff --git a/lib/CPathfinder.h b/lib/CPathfinder.h index e2f55dc37..2333031ee 100644 --- a/lib/CPathfinder.h +++ b/lib/CPathfinder.h @@ -36,7 +36,10 @@ struct DLL_LINKAGE CGPathNode NORMAL, BATTLE, VISIT, - BLOCKING_VISIT + BLOCKING_VISIT, + TELEPORT_NORMAL, + TELEPORT_BLOCKING_VISIT, + TELEPORT_BATTLE }; enum EAccessibility : ui8 @@ -202,6 +205,7 @@ private: bool isMovementToDestPossible() const; bool isMovementAfterDestPossible() const; CGPathNode::ENodeAction getDestAction() const; + CGPathNode::ENodeAction getTeleportDestAction() const; bool isSourceInitialPosition() const; bool isSourceVisitableObj() const; From 8792c2337248d72a2b717345ce7f6e30fcf0b857 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 11:21:35 +0300 Subject: [PATCH 26/53] CPlayerInterface: if autoskip enabled dont center view on town / hero --- client/CPlayerInterface.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index b0f4a56a6..2fe361c89 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -2242,8 +2242,10 @@ CGPath * CPlayerInterface::getAndVerifyPath(const CGHeroInstance * h) void CPlayerInterface::acceptTurn() { + bool centerView = true; if(settings["session"]["autoSkip"].Bool()) { + centerView = false; while(CInfoWindow *iw = dynamic_cast(GH.topInt())) iw->close(); } @@ -2270,10 +2272,10 @@ void CPlayerInterface::acceptTurn() //select first hero if available. if(heroToSelect != nullptr) { - adventureInt->select(heroToSelect); + adventureInt->select(heroToSelect, centerView); } else - adventureInt->select(towns.front()); + adventureInt->select(towns.front(), centerView); //show new day animation and sound on infobar adventureInt->infoBar.showDate(); From 8fb5dacba296588e2a147b38c909d4fea71baba7 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 15:02:36 +0300 Subject: [PATCH 27/53] CBonusSystemNode: get rid of non-const getBonusList --- lib/HeroBonus.cpp | 5 ----- lib/HeroBonus.h | 1 - 2 files changed, 6 deletions(-) diff --git a/lib/HeroBonus.cpp b/lib/HeroBonus.cpp index c054d586a..f0e7c1748 100644 --- a/lib/HeroBonus.cpp +++ b/lib/HeroBonus.cpp @@ -995,11 +995,6 @@ CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const return nodeType; } -BonusList& CBonusSystemNode::getBonusList() -{ - return bonuses; -} - const BonusList& CBonusSystemNode::getBonusList() const { return bonuses; diff --git a/lib/HeroBonus.h b/lib/HeroBonus.h index 2121263de..86a316087 100644 --- a/lib/HeroBonus.h +++ b/lib/HeroBonus.h @@ -694,7 +694,6 @@ public: void exportBonus(Bonus * b); void exportBonuses(); - BonusList &getBonusList(); const BonusList &getBonusList() const; BonusList &getExportedBonusList(); CBonusSystemNode::ENodeTypes getNodeType() const; From 1730a314711cbba143d3026dbda081e3928254a7 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 16:01:51 +0300 Subject: [PATCH 28/53] HeroBonus: get rid of code that used getBonusList --- lib/CCreatureHandler.cpp | 10 ++++++++-- lib/mapObjects/CArmedInstance.cpp | 4 ++-- lib/mapObjects/CGHeroInstance.cpp | 2 +- lib/mapObjects/CGTownInstance.cpp | 2 +- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/CCreatureHandler.cpp b/lib/CCreatureHandler.cpp index 2f30d3c48..dda125f32 100644 --- a/lib/CCreatureHandler.cpp +++ b/lib/CCreatureHandler.cpp @@ -452,8 +452,14 @@ void CCreatureHandler::loadCrExpBon() } do //parse everything that's left { - b.sid = parser.readNumber(); //id = this particular creature ID - loadStackExp(b, creatures[b.sid]->getBonusList(), parser); //add directly to CCreature Node + auto sid = parser.readNumber(); //id = this particular creature ID + b.sid = sid; + bl.clear(); + loadStackExp(b, bl, parser); + for(Bonus * b : bl) + { + creatures[sid]->addNewBonus(b); //add directly to CCreature Node + } } while (parser.endLine()); diff --git a/lib/mapObjects/CArmedInstance.cpp b/lib/mapObjects/CArmedInstance.cpp index adc47a7a5..fad613c81 100644 --- a/lib/mapObjects/CArmedInstance.cpp +++ b/lib/mapObjects/CArmedInstance.cpp @@ -46,7 +46,7 @@ void CArmedInstance::updateMoraleBonusFromArmy() if(!validTypes(false)) //object not randomized, don't bother return; - Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE))); + Bonus *b = getExportedBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE))); if(!b) { b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1); @@ -99,7 +99,7 @@ void CArmedInstance::updateMoraleBonusFromArmy() //-1 modifier for any Undead unit in army const ui8 UNDEAD_MODIFIER_ID = -2; - Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID)); + Bonus *undeadModifier = getExportedBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID)); if(hasUndead) { if(!undeadModifier) diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index cf29848ae..d0896d441 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -818,7 +818,7 @@ void CGHeroInstance::updateSkill(SecondarySkill which, int val) Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN; - if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which) + if(Bonus * b = getExportedBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which) .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus { b->val = skillVal; diff --git a/lib/mapObjects/CGTownInstance.cpp b/lib/mapObjects/CGTownInstance.cpp index ba1b8baca..ab661823e 100644 --- a/lib/mapObjects/CGTownInstance.cpp +++ b/lib/mapObjects/CGTownInstance.cpp @@ -856,7 +856,7 @@ void CGTownInstance::deserializationFix() void CGTownInstance::updateMoraleBonusFromArmy() { - Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE))); + Bonus *b = getExportedBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE))); if(!b) { b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1); From 59199ccdbdd13f26f433546f36d7f29585e51d84 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 11 Dec 2015 16:13:18 +0300 Subject: [PATCH 29/53] Bonus system: add treeHasChanged call where bonus objects changed --- lib/CArtHandler.cpp | 1 + lib/CCreatureHandler.cpp | 1 + lib/mapObjects/CArmedInstance.cpp | 1 + lib/mapObjects/CGHeroInstance.cpp | 2 ++ lib/mapObjects/CGTownInstance.cpp | 3 +++ 5 files changed, 8 insertions(+) diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index ac4a310a9..d40c9b08a 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -694,6 +694,7 @@ void CArtHandler::afterLoadFinalization() bonus->sid = art->id; } } + CBonusSystemNode::treeHasChanged(); for (CArtifact * art : artifacts) { diff --git a/lib/CCreatureHandler.cpp b/lib/CCreatureHandler.cpp index dda125f32..7cc5c6d8a 100644 --- a/lib/CCreatureHandler.cpp +++ b/lib/CCreatureHandler.cpp @@ -140,6 +140,7 @@ void CCreature::setId(CreatureID ID) if(bonus->source == Bonus::CREATURE_ABILITY) bonus->sid = ID; } + CBonusSystemNode::treeHasChanged(); } static void AddAbility(CCreature *cre, const JsonVector &ability_vec) diff --git a/lib/mapObjects/CArmedInstance.cpp b/lib/mapObjects/CArmedInstance.cpp index fad613c81..f35c1b322 100644 --- a/lib/mapObjects/CArmedInstance.cpp +++ b/lib/mapObjects/CArmedInstance.cpp @@ -96,6 +96,7 @@ void CArmedInstance::updateMoraleBonusFromArmy() b->description = b->description.substr(0, b->description.size()-2);//trim value } boost::algorithm::trim(b->description); + CBonusSystemNode::treeHasChanged(); //-1 modifier for any Undead unit in army const ui8 UNDEAD_MODIFIER_ID = -2; diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index d0896d441..c01fa8edf 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -831,6 +831,7 @@ void CGHeroInstance::updateSkill(SecondarySkill which, int val) addNewBonus(bonus); } + CBonusSystemNode::treeHasChanged(); } void CGHeroInstance::setPropertyDer( ui8 what, ui32 val ) { @@ -1365,6 +1366,7 @@ void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si { skill->val += value; } + CBonusSystemNode::treeHasChanged(); } else if(primarySkill == PrimarySkill::EXPERIENCE) { diff --git a/lib/mapObjects/CGTownInstance.cpp b/lib/mapObjects/CGTownInstance.cpp index ab661823e..2e13c5ce2 100644 --- a/lib/mapObjects/CGTownInstance.cpp +++ b/lib/mapObjects/CGTownInstance.cpp @@ -864,7 +864,10 @@ void CGTownInstance::updateMoraleBonusFromArmy() } if (garrisonHero) + { b->val = 0; + CBonusSystemNode::treeHasChanged(); + } else CArmedInstance::updateMoraleBonusFromArmy(); } From 0661aa0e6e26b557e5b023e39062511b5f3ec11b Mon Sep 17 00:00:00 2001 From: Vadim Markovtsev Date: Sun, 13 Dec 2015 11:04:42 +0300 Subject: [PATCH 30/53] Remove undefined behavior in requestActionASAP --- AI/VCAI/VCAI.cpp | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 31915aa57..25e1eb752 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -2705,24 +2705,13 @@ void VCAI::finish() void VCAI::requestActionASAP(std::function whatToDo) { - boost::mutex mutex; - mutex.lock(); - - boost::thread newThread([&mutex,this,whatToDo]() + boost::thread newThread([this,whatToDo]() { setThreadName("VCAI::requestActionASAP::whatToDo"); SET_GLOBAL_STATE(this); boost::shared_lock gsLock(cb->getGsMutex()); - // unlock mutex and allow parent function to exit - mutex.unlock(); whatToDo(); }); - - // wait for mutex to unlock and for thread to initialize properly - mutex.lock(); - - // unlock mutex - boost dislikes destruction of locked mutexes - mutex.unlock(); } void VCAI::lostHero(HeroPtr h) From 9a0161e4e23e026d74e23350fb0d9e712d0eb4c9 Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 13 Dec 2015 15:57:33 +0300 Subject: [PATCH 31/53] Fix and unify CBattleQuery::blocksPack --- server/CQuery.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/server/CQuery.cpp b/server/CQuery.cpp index 0c69bd671..3d07d3af0 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -245,12 +245,8 @@ CBattleQuery::CBattleQuery() bool CBattleQuery::blocksPack(const CPack *pack) const { - #ifndef __APPLE__ - bool dynamic_success = !dynamic_cast(pack) && !dynamic_cast(pack); - #else const char * name = typeid(*pack).name(); return strcmp(name, typeid(MakeAction).name()) && strcmp(name, typeid(MakeCustomAction).name()); - #endif } void CBattleQuery::onRemoval(CGameHandler *gh, PlayerColor color) From 5cd4e852d49a988157d04349db6350322de59342 Mon Sep 17 00:00:00 2001 From: AlexVinS Date: Sun, 13 Dec 2015 15:59:48 +0300 Subject: [PATCH 32/53] Use portable cast in CTeleportDialogQuery also --- server/CQuery.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/CQuery.cpp b/server/CQuery.cpp index 3d07d3af0..aad12a423 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -321,7 +321,7 @@ CBlockingDialogQuery::CBlockingDialogQuery(const BlockingDialog &bd) void CTeleportDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const { - auto obj = dynamic_cast(objectVisit.visitedObject); + auto obj = dynamic_ptr_cast(objectVisit.visitedObject); obj->teleportDialogAnswered(objectVisit.visitingHero, *answer, td.exits); } From 1ec7d1463788b6aa3968dd3e68eeee94ecd9e6f0 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Sun, 13 Dec 2015 22:14:37 +0300 Subject: [PATCH 33/53] Client: add command line options to simplify multi-instance testing Use these when you need to run multiple instances of VCMI simultaneously. --testingport is port used to start server. Override port number from configuration files. --testingfileprefix is prefix for auto save filenames. Both options has to be set in order to work. --- client/CMT.cpp | 37 +++++++++++++++++++++++++------------ client/CPlayerInterface.cpp | 14 ++++++++++---- client/Client.cpp | 36 +++++++++++++++++++++++++++--------- 3 files changed, 62 insertions(+), 25 deletions(-) diff --git a/client/CMT.cpp b/client/CMT.cpp index f9e5a1a08..6a937ac3a 100644 --- a/client/CMT.cpp +++ b/client/CMT.cpp @@ -170,9 +170,9 @@ static void prog_version(void) static void prog_help(const po::options_description &opts) { printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str()); - printf("Copyright (C) 2007-2014 VCMI dev team - see AUTHORS file\n"); - printf("This is free software; see the source for copying conditions. There is NO\n"); - printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"); + printf("Copyright (C) 2007-2016 VCMI dev team - see AUTHORS file\n"); + printf("This is free software; see the source for copying conditions. There is NO\n"); + printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"); printf("\n"); printf("Usage:\n"); std::cout << opts; @@ -244,7 +244,9 @@ int main(int argc, char** argv) ("loadhumanplayerindices",po::value>(),"Indexes of human players (0=Red, etc.)") ("loadplayer", po::value(),"specifies which player we are in multiplayer loaded games (0=Red, etc.)") ("loadserverip",po::value(),"IP for loaded game server") - ("loadserverport",po::value(),"port for loaded game server"); + ("loadserverport",po::value(),"port for loaded game server") + ("testingport",po::value(),"port for testing, override specified in config file") + ("testingfileprefix",po::value(),"prefix for auto save files"); if(argc > 1) { @@ -281,7 +283,7 @@ int main(int argc, char** argv) // it may result in very small \ very fast mouse when game in fullscreen mode putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0"); - // Init old logging system and new (temporary) logging system + // Init old logging system and new (temporary) logging system CStopWatch total, pomtime; std::cout.flags(std::ios::unitbuf); console = new CConsoleHandler; @@ -291,16 +293,25 @@ int main(int argc, char** argv) const bfs::path logPath = VCMIDirs::get().userCachePath() / "VCMI_Client_log.txt"; CBasicLogConfigurator logConfig(logPath, console); - logConfig.configureDefault(); + logConfig.configureDefault(); logGlobal->infoStream() << "Creating console and configuring logger: " << pomtime.getDiff(); logGlobal->infoStream() << "The log file will be saved to " << logPath; - // Init filesystem and settings + // Init filesystem and settings preinitDLL(::console); - settings.init(); + settings.init(); - // Initialize logging based on settings - logConfig.configure(); + // Init special testing settings + Settings testingSettings = settings.write["testing"]; + if(vm.count("testingport") && vm.count("testingfileprefix")) + { + testingSettings["enabled"].Bool() = true; + testingSettings["port"].String() = vm["testingport"].as(); + testingSettings["prefix"].String() = vm["testingfileprefix"].as(); + } + + // Initialize logging based on settings + logConfig.configure(); // Some basic data validation to produce better error messages in cases of incorrect install auto testFile = [](std::string filename, std::string message) -> bool @@ -308,13 +319,15 @@ int main(int argc, char** argv) if (CResourceHandler::get()->existsResource(ResourceID(filename))) return true; - logGlobal->errorStream() << "Error: " << message << " was not found!"; + logGlobal->errorStream() << "Error: " << message << " was not found!"; return false; }; if (!testFile("DATA/HELP.TXT", "Heroes III data") || - !testFile("MODS/VCMI/MOD.JSON", "VCMI data")) + !testFile("MODS/VCMI/MOD.JSON", "VCMI data")) + { exit(1); // These are unrecoverable errors + } // these two are optional + some installs have them on CD and not in data directory testFile("VIDEO/GOOD1A.SMK", "campaign movies"); diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index 2fe361c89..a81750ed9 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -157,24 +157,30 @@ void CPlayerInterface::yourTurn() GH.curInt = this; adventureInt->selection = nullptr; + std::string prefix = ""; + if(settings["testing"]["enabled"].Bool()) + { + prefix = settings["testing"]["prefix"].String(); + } + if(firstCall) { if(howManyPeople == 1) adventureInt->setPlayer(playerID); - autosaveCount = getLastIndex("Autosave_"); + autosaveCount = getLastIndex(prefix + "Autosave_"); if(firstCall > 0) //new game, not loaded { - int index = getLastIndex("Newgame_Autosave_"); + int index = getLastIndex(prefix + "Newgame_"); index %= SAVES_COUNT; - cb->save("Saves/Newgame_Autosave_" + boost::lexical_cast(index + 1)); + cb->save("Saves/" + prefix + "Newgame_Autosave_" + boost::lexical_cast(index + 1)); } firstCall = 0; } else { - LOCPLINT->cb->save("Saves/Autosave_" + boost::lexical_cast(autosaveCount++ + 1)); + LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + boost::lexical_cast(autosaveCount++ + 1)); autosaveCount %= 5; } diff --git a/client/Client.cpp b/client/Client.cpp index dabe2209f..bd8b1f695 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -246,18 +246,25 @@ void CClient::endGame( bool closeConnection /*= true*/ ) #if 1 void CClient::loadGame(const std::string & fname, const bool server, const std::vector& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port) { - PlayerColor player(player_); //intentional shadowing + PlayerColor player(player_); //intentional shadowing + logNetwork->infoStream() << "Loading procedure started!"; - logNetwork->infoStream() <<"Loading procedure started!"; + std::string realPort; + if(settings["testing"]["enabled"].Bool()) + realPort = settings["testing"]["port"].String(); + else if(port.size()) + realPort = port; + else + realPort = boost::lexical_cast(settings["server"]["port"].Float()); CServerHandler sh; - if(server) - sh.startServer(); - else - serv = sh.justConnectToServer(ipaddr,port=="" ? "3030" : port); + if(server) + sh.startServer(); + else + serv = sh.justConnectToServer(ipaddr, realPort); CStopWatch tmh; - unique_ptr loader; + unique_ptr loader; try { std::string clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME)); @@ -967,7 +974,10 @@ CServerHandler::CServerHandler(bool runServer /*= false*/) { serverThread = nullptr; shared = nullptr; - port = boost::lexical_cast(settings["server"]["port"].Float()); + if(settings["testing"]["enabled"].Bool()) + port = settings["testing"]["port"].String(); + else + port = boost::lexical_cast(settings["server"]["port"].Float()); verbose = true; #ifndef VCMI_ANDROID @@ -1009,6 +1019,14 @@ void CServerHandler::callServer() CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port) { + std::string realPort; + if(settings["testing"]["enabled"].Bool()) + realPort = settings["testing"]["port"].String(); + else if(port.size()) + realPort = port; + else + realPort = boost::lexical_cast(settings["server"]["port"].Float()); + CConnection *ret = nullptr; while(!ret) { @@ -1016,7 +1034,7 @@ CConnection * CServerHandler::justConnectToServer(const std::string &host, const { logNetwork->infoStream() << "Establishing connection..."; ret = new CConnection( host.size() ? host : settings["server"]["server"].String(), - port.size() ? port : boost::lexical_cast(settings["server"]["port"].Float()), + realPort, NAME); } catch(...) From 9f565b81e9f3a3fb81f1f2e01fb29b0e374d54bd Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Mon, 14 Dec 2015 11:26:14 +0300 Subject: [PATCH 34/53] CBankInfo: fix huge memory leak that appear in long run --- lib/mapObjects/CommonConstructors.cpp | 6 +++--- lib/mapObjects/CommonConstructors.h | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/mapObjects/CommonConstructors.cpp b/lib/mapObjects/CommonConstructors.cpp index 8016db848..ec4083750 100644 --- a/lib/mapObjects/CommonConstructors.cpp +++ b/lib/mapObjects/CommonConstructors.cpp @@ -325,10 +325,10 @@ void CBankInstanceConstructor::configureObject(CGObjectInstance * object, CRando } } -CBankInfo::CBankInfo(JsonVector config): - config(config) +CBankInfo::CBankInfo(const JsonVector & Config): + config(Config) { - assert(!config.empty()); + assert(!Config.empty()); } static void addStackToArmy(IObjectInfo::CArmyStructure & army, const CCreature * crea, si32 amount) diff --git a/lib/mapObjects/CommonConstructors.h b/lib/mapObjects/CommonConstructors.h index 0cdd7ca98..8533e0ebe 100644 --- a/lib/mapObjects/CommonConstructors.h +++ b/lib/mapObjects/CommonConstructors.h @@ -156,9 +156,9 @@ typedef std::vector> TPossibleGuards class DLL_LINKAGE CBankInfo : public IObjectInfo { - JsonVector config; + const JsonVector & config; public: - CBankInfo(JsonVector config); + CBankInfo(const JsonVector & Config); TPossibleGuards getPossibleGuards() const; From 2724a67a273efbb95d0625266b14d3e4762b9fec Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Mon, 14 Dec 2015 14:33:50 +0300 Subject: [PATCH 35/53] CPathfinder: add border gate support and use passableFor --- lib/CPathfinder.cpp | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 8120adfaa..86ebe942c 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -453,7 +453,7 @@ bool CPathfinder::isMovementAfterDestPossible() const /// Transit over whirlpools only allowed when hero protected return true; } - else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2) + else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2 || dtObj->ID == Obj::BORDER_GATE) { /// Transit via unguarded garrisons is always possible return true; @@ -517,18 +517,33 @@ CGPathNode::ENodeAction CPathfinder::getDestAction() const else action = CGPathNode::BLOCKING_VISIT; } - else if(dtObj->ID == Obj::TOWN && objRel == PlayerRelations::ENEMIES) + else if(dtObj->ID == Obj::TOWN) { - const CGTownInstance * townObj = dynamic_cast(dtObj); - if(townObj->armedGarrison()) + if(dtObj->passableFor(hero->tempOwner)) + action = CGPathNode::VISIT; + else if(objRel == PlayerRelations::ENEMIES) action = CGPathNode::BATTLE; } else if(dtObj->ID == Obj::GARRISON || dtObj->ID == Obj::GARRISON2) { - const CGGarrison * garrisonObj = dynamic_cast(dtObj); - if((garrisonObj->stacksCount() && objRel == PlayerRelations::ENEMIES) || isDestinationGuarded(true)) + if(dtObj->passableFor(hero->tempOwner)) + { + if(isDestinationGuarded(true)) + action = CGPathNode::BATTLE; + } + else if(objRel == PlayerRelations::ENEMIES) action = CGPathNode::BATTLE; } + else if(dtObj->ID == Obj::BORDER_GATE) + { + if(dtObj->passableFor(hero->tempOwner)) + { + if(isDestinationGuarded(true)) + action = CGPathNode::BATTLE; + } + else + action = CGPathNode::BLOCKING_VISIT; + } else if(isDestinationGuardian()) action = CGPathNode::BATTLE; else if(dtObj->blockVisit && !(options.useCastleGate && dtObj->ID == Obj::TOWN)) From bf9ac7318af5e62f5eab2de50b54b78198bc8389 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 15 Dec 2015 19:13:55 +0300 Subject: [PATCH 36/53] CPathfinder: change cost calculation sequence for embark / disembark With old embark cost calculation pathfinder may end up thinking that hero can embark/disembark while have less movement points than base movement cost is. Now hero would be only able to embark / disembark if we have enough movement points to step on that tile. This rule is also valid for situation when hero have Admiral's Hat as in H3 even if hero don't have embark penalty he still use move points for embark and disembark. Problem was found as it's was causing infitite loop in AI. Server of course rejected attempt to embark with less than 100 movement points while pathfinder tell AI that it's can still embark with 93 movement points. --- lib/CPathfinder.cpp | 20 +++++++++++--------- server/CGameHandler.cpp | 2 +- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 86ebe942c..48cb15f0e 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -150,22 +150,24 @@ void CPathfinder::calculatePaths() continue; destAction = getDestAction(); - int cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, ct, dt, movement, hlp->getTurnInfo()); - int remains = movement - cost; - if(destAction == CGPathNode::EMBARK || destAction == CGPathNode::DISEMBARK) - { - remains = hero->movementPointsAfterEmbark(movement, cost, destAction - 1, hlp->getTurnInfo()); - cost = movement - remains; - } - int turnAtNextTile = turn; + int turnAtNextTile = turn, moveAtNextTile = movement; + int cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, ct, dt, moveAtNextTile, hlp->getTurnInfo()); + int remains = moveAtNextTile - cost; if(remains < 0) { //occurs rarely, when hero with low movepoints tries to leave the road hlp->updateTurnInfo(++turnAtNextTile); - int moveAtNextTile = hlp->getMaxMovePoints(i); + moveAtNextTile = hlp->getMaxMovePoints(i); cost = CPathfinderHelper::getMovementCost(hero, cp->coord, dp->coord, ct, dt, moveAtNextTile, hlp->getTurnInfo()); //cost must be updated, movement points changed :( remains = moveAtNextTile - cost; } + if(destAction == CGPathNode::EMBARK || destAction == CGPathNode::DISEMBARK) + { + /// FREE_SHIP_BOARDING bonus only remove additional penalty + /// land <-> sail transition still cost movement points as normal movement + remains = hero->movementPointsAfterEmbark(moveAtNextTile, cost, destAction - 1, hlp->getTurnInfo()); + cost = moveAtNextTile - remains; + } if(isBetterWay(remains, turnAtNextTile) && ((cp->turns == turnAtNextTile && remains) || passOneTurnLimitCheck())) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 6a16a3656..c383aab68 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -1875,7 +1875,7 @@ bool CGameHandler::moveHero( ObjectInstanceID hid, int3 dst, ui8 teleporting, bo { tmh.movePoints = h->movementPointsAfterEmbark(h->movement, cost, false, ti); return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE); - //attack guards on embarking? In H3 creatures on water had no zone of control at all + // In H3 embark ignore guards } if(disembarking) From 9490a5d66d3d2506948521ffe91d6b844c254320 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Wed, 16 Dec 2015 20:14:36 +0300 Subject: [PATCH 37/53] CPathfinder: deny transit to land blockvis objs from water layer When hero is in water walking layer he can only exit to accessible or visitable land tiles, but not objects that have blocking visit and leave hero standing on water. This is different than default flying behaviour because hero in air layer can only transit into accessible land layer without any blocking or visitable objects on them. --- lib/CPathfinder.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 48cb15f0e..5e778e541 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -373,6 +373,16 @@ bool CPathfinder::isLayerTransitionPossible() const return false; } + break; + + case ELayer::WATER: + if(dp->accessible != CGPathNode::ACCESSIBLE && dp->accessible != CGPathNode::VISITABLE) + { + /// Hero that walking on water can transit to accessible and visitable tiles + /// Though hero can't interact with blocking visit objects while standing on water + return false; + } + break; } From b6176649ecad78b8f75defd7603bf8dc060b284a Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Fri, 18 Dec 2015 01:08:19 +0300 Subject: [PATCH 38/53] CGMonolith: avoid crash when all exits are blocked by friendly heroes --- lib/mapObjects/MiscObjects.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index a4a925c5e..325c2ca04 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -940,17 +940,18 @@ void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const { int3 dPos; + auto randomExit = getRandomExit(hero); auto realExits = getAllExits(true); if(!isEntrance() // Do nothing if hero visited exit only object || (!exits.size() && !realExits.size()) // Do nothing if there no exits on this channel - || (!exits.size() && ObjectInstanceID() == getRandomExit(hero))) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate + || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate { return; } else if(vstd::isValidIndex(exits, answer)) dPos = exits[answer].second; else - dPos = CGHeroInstance::convertPosition(cb->getObj(getRandomExit(hero))->visitablePos(), true); + dPos = CGHeroInstance::convertPosition(cb->getObj(randomExit)->visitablePos(), true); cb->moveHero(hero->id, dPos, true); } From 87eaa78ffd78bcbbf9850036e736e62d0319294a Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Sat, 19 Dec 2015 12:12:35 +0300 Subject: [PATCH 39/53] Restore testing option changes overriten by merge --- client/Client.cpp | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/client/Client.cpp b/client/Client.cpp index 347cad243..bd8b1f695 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -246,18 +246,25 @@ void CClient::endGame( bool closeConnection /*= true*/ ) #if 1 void CClient::loadGame(const std::string & fname, const bool server, const std::vector& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port) { - PlayerColor player(player_); //intentional shadowing + PlayerColor player(player_); //intentional shadowing + logNetwork->infoStream() << "Loading procedure started!"; - logNetwork->infoStream() <<"Loading procedure started!"; + std::string realPort; + if(settings["testing"]["enabled"].Bool()) + realPort = settings["testing"]["port"].String(); + else if(port.size()) + realPort = port; + else + realPort = boost::lexical_cast(settings["server"]["port"].Float()); CServerHandler sh; - if(server) - sh.startServer(); - else - serv = sh.justConnectToServer(ipaddr,port=="" ? "3030" : port); + if(server) + sh.startServer(); + else + serv = sh.justConnectToServer(ipaddr, realPort); CStopWatch tmh; - unique_ptr loader; + unique_ptr loader; try { std::string clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME)); @@ -967,7 +974,10 @@ CServerHandler::CServerHandler(bool runServer /*= false*/) { serverThread = nullptr; shared = nullptr; - port = boost::lexical_cast(settings["server"]["port"].Float()); + if(settings["testing"]["enabled"].Bool()) + port = settings["testing"]["port"].String(); + else + port = boost::lexical_cast(settings["server"]["port"].Float()); verbose = true; #ifndef VCMI_ANDROID From 48be566050bb300055264e38b8aec537fa25affe Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Mon, 21 Dec 2015 18:44:21 +0300 Subject: [PATCH 40/53] Dimension Door: fix movement points cost for expert level --- lib/spells/AdventureSpellMechanics.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/spells/AdventureSpellMechanics.cpp b/lib/spells/AdventureSpellMechanics.cpp index c8ac2f9d0..0c838b82b 100644 --- a/lib/spells/AdventureSpellMechanics.cpp +++ b/lib/spells/AdventureSpellMechanics.cpp @@ -148,13 +148,14 @@ ESpellCastResult DimensionDoorMechanics::applyAdventureEffects(const SpellCastEn return ESpellCastResult::ERROR; } - if(parameters.caster->movement <= 0) + if(parameters.caster->movement <= 0) //unlike town portal non-zero MP is enough { env->complain("Hero needs movement points to cast Dimension Door!"); return ESpellCastResult::ERROR; } const int schoolLevel = parameters.caster->getSpellSchoolLevel(owner); + const int movementCost = GameConstants::BASE_MOVEMENT_COST * ((schoolLevel >= 3) ? 2 : 3); if(parameters.caster->getBonusesCount(Bonus::SPELL_EFFECT, SpellID::DIMENSION_DOOR) >= owner->getPower(schoolLevel)) //limit casts per turn { @@ -182,7 +183,7 @@ ESpellCastResult DimensionDoorMechanics::applyAdventureEffects(const SpellCastEn { SetMovePoints smp; smp.hid = parameters.caster->id; - smp.val = std::max(0, parameters.caster->movement - 300); + smp.val = std::max(0, parameters.caster->movement - movementCost); env->sendAndApply(&smp); } return ESpellCastResult::OK; @@ -241,7 +242,7 @@ ESpellCastResult TownPortalMechanics::applyAdventureEffects(const SpellCastEnvir } - const int movementCost = (parameters.caster->getSpellSchoolLevel(owner) >= 3) ? 200 : 300; + const int movementCost = GameConstants::BASE_MOVEMENT_COST * ((parameters.caster->getSpellSchoolLevel(owner) >= 3) ? 2 : 3); if(parameters.caster->movement < movementCost) { From 4124aacac85e5fd7e66a71030da4f2721029e6b2 Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 22 Dec 2015 00:08:49 +0300 Subject: [PATCH 41/53] CMake: add dbghelp to SYSTEM_LIBS for MiniDumpWriteDump. Fix issue 2312 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11262196d..abacac259 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -64,7 +64,7 @@ endif() if (WIN32) add_definitions(-DBOOST_THREAD_USE_LIB) add_definitions(-D_WIN32_WINNT=0x0501) - set(SYSTEM_LIBS ${SYSTEM_LIBS} ole32 oleaut32 ws2_32 mswsock) + set(SYSTEM_LIBS ${SYSTEM_LIBS} ole32 oleaut32 ws2_32 mswsock dbghelp) #delete lib prefix for dlls (libvcmi -> vcmi) set(CMAKE_SHARED_LIBRARY_PREFIX "") From e3f2bb2c99226e40c65040341622bf3e67874b3a Mon Sep 17 00:00:00 2001 From: ArseniyShestakov Date: Tue, 22 Dec 2015 01:57:56 +0300 Subject: [PATCH 42/53] MXE support: avoid conflicts with some macros from headers --- Global.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Global.h b/Global.h index 56a35a9f4..0d8923aab 100644 --- a/Global.h +++ b/Global.h @@ -93,6 +93,7 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size."); #ifdef VCMI_WINDOWS # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - delete this line if something is missing. # define NOMINMAX // Exclude min/max macros from . Use std::[min/max] from instead. +# define _NO_W32_PSEUDO_MODIFIERS // Exclude more macros for compiling with MinGW on Linux. #endif /* ---------------------------------------------------------------------------- */ From be50d699fb8f308f8c8bdad2752ac7971c804180 Mon Sep 17 00:00:00 2001 From: DjWarmonger Date: Wed, 23 Dec 2015 15:23:56 +0100 Subject: [PATCH 43/53] Compile fixes for MSVS --- lib/CGameState.h | 2 +- lib/VCMI_lib.vcxproj | 9 +++++++ lib/VCMI_lib.vcxproj.filters | 39 ++++++++++++++++++++++++++--- lib/mapObjects/CommonConstructors.h | 1 + 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/lib/CGameState.h b/lib/CGameState.h index e7ddb89ee..2dedd638f 100644 --- a/lib/CGameState.h +++ b/lib/CGameState.h @@ -100,7 +100,7 @@ struct DLL_LINKAGE RumorState ERumorType type; std::map> last; - RumorState(){type = TYPE_NONE; last = {};}; + RumorState(){type = TYPE_NONE;}; bool update(int id, int extra); template void serialize(Handler &h, const int version) diff --git a/lib/VCMI_lib.vcxproj b/lib/VCMI_lib.vcxproj index 54b49f248..0d10cf5a2 100644 --- a/lib/VCMI_lib.vcxproj +++ b/lib/VCMI_lib.vcxproj @@ -293,8 +293,10 @@ + + @@ -313,6 +315,7 @@ + @@ -332,12 +335,15 @@ + + + @@ -360,6 +366,7 @@ + @@ -371,7 +378,9 @@ + + diff --git a/lib/VCMI_lib.vcxproj.filters b/lib/VCMI_lib.vcxproj.filters index ca1840e47..9e9089776 100644 --- a/lib/VCMI_lib.vcxproj.filters +++ b/lib/VCMI_lib.vcxproj.filters @@ -155,8 +155,6 @@ registerTypes - - mapObjects @@ -202,7 +200,6 @@ mapObjects - spells @@ -227,6 +224,15 @@ + + registerTypes + + + registerTypes + + + registerTypes + @@ -541,5 +547,32 @@ Header Files + + Header Files + + + mapping + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + mapping + \ No newline at end of file diff --git a/lib/mapObjects/CommonConstructors.h b/lib/mapObjects/CommonConstructors.h index 8533e0ebe..e7cff5ac5 100644 --- a/lib/mapObjects/CommonConstructors.h +++ b/lib/mapObjects/CommonConstructors.h @@ -2,6 +2,7 @@ #include "CObjectClassesHandler.h" #include "../CTownHandler.h" // for building ID-based filters +#include "MapObjects.h" /* * CommonConstructors.h, part of VCMI engine From 9b2cc33f09d68af8c613b4ce7c96a2c3f333f1bc Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Thu, 24 Dec 2015 01:37:16 +0300 Subject: [PATCH 44/53] Added my contact email address --- AUTHORS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 462bdbced..29475cdfd 100644 --- a/AUTHORS +++ b/AUTHORS @@ -52,5 +52,5 @@ Alexey aka Macron1Robot, <> Alexander Shishkin aka alexvins, * MinGW platform support, modding related programming -Arseniy Shestakov aka SXX, +Arseniy Shestakov aka SXX, * pathfinding improvements, programming From a1f5a0a85ca75f2e472a4ad123056bf451429ae6 Mon Sep 17 00:00:00 2001 From: DjWarmonger Date: Thu, 24 Dec 2015 11:28:14 +0100 Subject: [PATCH 45/53] Removed unused code, which is not needed with new Pathfinder. --- AI/VCAI/VCAI.cpp | 52 +----------------------------------------------- 1 file changed, 1 insertion(+), 51 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index 287805383..b3b3f66ee 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -3260,30 +3260,6 @@ For ship construction etc, another function (goal?) is needed sectorQueue.push(neigh); } } - - -/* - // TODO: this code need to be rewritten in order to work porperly - // And we need to support teleport channels instead of just gates - // - // At moment it's cause more issues than it's solve so it's disabled. - // Check mantis 2119, 2228 and 2212 (Warmonger posts) - - for (auto gate : s->subterraneanGates) - { - auto gatePair = ai->knownSubterraneanGates.find(gate); - if (gatePair != ai->knownSubterraneanGates.end()) - { - //check the other side of gate - Sector *neigh = &infoOnSectors[retreiveTile(gatePair->second->visitablePos())]; - if(!preds[neigh]) //if we didn't come into this sector yet - { - preds[neigh] = s; //it becomes our new target sector - sectorQueue.push(neigh); - } - } - } -*/ } if(!preds[dest]) @@ -3389,34 +3365,8 @@ For ship construction etc, another function (goal?) is needed //disembark return ret; } - else //use subterranean gates + else //use subterranean gates - not needed since gates are now handled via Pathfinder { - //auto t = findFirstVisitableTile (h, dst); - //if (t.valid()) - // return t; - - //TODO: pop sectors linked by Subterranean Gate in loop - -/* - // Same as above, check issues 2119, 2228 - - auto firstGate = boost::find_if(src->subterraneanGates, [=](const CGObjectInstance * gate) -> bool - { - //make sure no hero block the way - auto pos = ai->knownSubterraneanGates[gate]->visitablePos(); - const TerrainTile *t = getTile(pos); - return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::SUBTERRANEAN_GATE - && retreiveTile(pos) == sectorToReach->id; - }); - - if(firstGate != src->subterraneanGates.end()) - { - //TODO: pahtfinder can find path through subterranean gates, but this function only reaches closest gate - return (*firstGate)->visitablePos(); - } -*/ - //TODO - //Monolith? Whirlpool? ... return ret; //throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!"); } From 75ca020890a8382780e99697b4b4fcd016c8db59 Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Thu, 24 Dec 2015 21:03:51 +0300 Subject: [PATCH 46/53] CCeatureSet: add getArmyDescription for hover and InfoWindow texts --- lib/CCreatureSet.cpp | 31 ++++++++++++++++++++++++++++--- lib/CCreatureSet.h | 3 ++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/lib/CCreatureSet.cpp b/lib/CCreatureSet.cpp index 954669e7a..2a0d890f1 100644 --- a/lib/CCreatureSet.cpp +++ b/lib/CCreatureSet.cpp @@ -225,14 +225,39 @@ ui64 CCreatureSet::getPower (SlotID slot) const return getStack(slot).getPower(); } -std::string CCreatureSet::getRoughAmount (SlotID slot) const +std::string CCreatureSet::getRoughAmount(SlotID slot, int mode) const { + /// Mode represent return string format + /// "Pack" - 0, "A pack of" - 1, "a pack of" - 2 int quantity = CCreature::getQuantityID(getStackCount(slot)); - if (quantity) - return VLC->generaltexth->arraytxt[174 + 3*CCreature::getQuantityID(getStackCount(slot))]; + if(quantity) + return VLC->generaltexth->arraytxt[(174 + mode) + 3*CCreature::getQuantityID(getStackCount(slot))]; return ""; } +std::string CCreatureSet::getArmyDescription() const +{ + std::string text; + std::vector guards; + for(auto & elem : stacks) + { + auto str = boost::str(boost::format("%s %s") % getRoughAmount(elem.first, 2) % getCreature(elem.first)->namePl); + guards.push_back(str); + } + if(guards.size()) + { + for(int i = 0; i < guards.size(); i++) + { + text += guards[i]; + if(i + 2 < guards.size()) + text += ", "; + else if(i + 2 == guards.size()) + text += VLC->generaltexth->allTexts[237]; + } + } + return text; +} + int CCreatureSet::stacksCount() const { return stacks.size(); diff --git a/lib/CCreatureSet.h b/lib/CCreatureSet.h index 311ebff14..08037f1dd 100644 --- a/lib/CCreatureSet.h +++ b/lib/CCreatureSet.h @@ -200,7 +200,8 @@ public: virtual bool needsLastStack() const; //true if last stack cannot be taken ui64 getArmyStrength() const; //sum of AI values of creatures ui64 getPower (SlotID slot) const; //value of specific stack - std::string getRoughAmount (SlotID slot) const; //rough size of specific stack + std::string getRoughAmount(SlotID slot, int mode = 0) const; //rough size of specific stack + std::string getArmyDescription() const; bool hasStackAtSlot(SlotID slot) const; bool contains(const CStackInstance *stack) const; From 62bab27e7eae76753ec15f2db084c26f91ffdef8 Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Thu, 24 Dec 2015 21:05:02 +0300 Subject: [PATCH 47/53] CGArtifact: show yes/no dialog for guarded artifacts. Fix issue 2095 Also fix hover text for CGMine --- lib/mapObjects/MiscObjects.cpp | 74 +++++++++++++++++++++++----------- 1 file changed, 50 insertions(+), 24 deletions(-) diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index 325c2ca04..47077866f 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -629,7 +629,6 @@ std::string CGMine::getObjectName() const std::string CGMine::getHoverText(PlayerColor player) const { - std::string hoverName = getObjectName(); // Sawmill if (tempOwner != PlayerColor::NEUTRAL) @@ -639,11 +638,12 @@ std::string CGMine::getHoverText(PlayerColor player) const hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")"; } - for (auto & slot : Slots()) // guarded by a few Pikeman + if(stacksCount()) { hoverName += "\n"; - hoverName += getRoughAmount(slot.first); - hoverName += getCreature(slot.first)->namePl; + hoverName += VLC->generaltexth->allTexts[202]; //Guarded by + hoverName += " "; + hoverName += getArmyDescription(); } return hoverName; } @@ -1164,7 +1164,7 @@ std::string CGArtifact::getObjectName() const return VLC->arth->artifacts[subID]->Name(); } -void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const +void CGArtifact::onHeroVisit(const CGHeroInstance * h) const { if(!stacksCount()) { @@ -1175,28 +1175,32 @@ void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const case Obj::ARTIFACT: { iw.soundID = soundBase::treasure; //play sound only for non-scroll arts - iw.components.push_back(Component(Component::ARTIFACT,subID,0,0)); + iw.components.push_back(Component(Component::ARTIFACT, subID, 0, 0)); if(message.length()) - iw.text << message; + iw.text << message; else { - if (VLC->arth->artifacts[subID]->EventText().size()) - iw.text << std::pair (MetaString::ART_EVNTS, subID); + if(VLC->arth->artifacts[subID]->EventText().size()) + iw.text << std::pair(MetaString::ART_EVNTS, subID); else //fix for mod artifacts with no event text { - iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure - iw.text.addReplacement (h->name); + iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure + iw.text.addReplacement(h->name); } - } } break; case Obj::SPELL_SCROLL: { int spellID = storedArtifact->getGivenSpellID(); - iw.components.push_back (Component(Component::SPELL, spellID,0,0)); - iw.text.addTxt (MetaString::ADVOB_TXT,135); - iw.text.addReplacement(MetaString::SPELL_NAME, spellID); + iw.components.push_back(Component(Component::SPELL, spellID, 0, 0)); + if(message.length()) + iw.text << message; + else + { + iw.text.addTxt(MetaString::ADVOB_TXT,135); + iw.text.addReplacement(MetaString::SPELL_NAME, spellID); + } } break; } @@ -1205,16 +1209,38 @@ void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const } else { - if(message.size()) + switch(ID) { - BlockingDialog ynd(true,false); - ynd.player = h->getOwner(); - ynd.text << message; - cb->showBlockingDialog(&ynd); - } - else - { - blockingDialogAnswered(h, true); + case Obj::ARTIFACT: + { + BlockingDialog ynd(true,false); + ynd.player = h->getOwner(); + if(message.length()) + ynd.text << message; + else + { + // TODO: Guard text is more complex in H3, see mantis issue 2325 for details + ynd.text.addTxt(MetaString::GENERAL_TXT, 420); + ynd.text.addReplacement(""); + ynd.text.addReplacement(getArmyDescription()); + ynd.text.addReplacement(MetaString::GENERAL_TXT, 43); // creatures + } + cb->showBlockingDialog(&ynd); + } + break; + case Obj::SPELL_SCROLL: + { + if(message.length()) + { + BlockingDialog ynd(true,false); + ynd.player = h->getOwner(); + ynd.text << message; + cb->showBlockingDialog(&ynd); + } + else + blockingDialogAnswered(h, true); + } + break; } } } From 6f5c52a229a9066eb88e3bed62175fda9f226b0f Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Thu, 24 Dec 2015 21:30:57 +0300 Subject: [PATCH 48/53] Refactoring: use cleaner CCreatureSet::stacksCount everywhere --- AI/VCAI/VCAI.cpp | 4 ++-- client/windows/CTradeWindow.cpp | 2 +- lib/mapObjects/CBank.cpp | 4 ++-- lib/mapObjects/CGHeroInstance.cpp | 2 +- lib/mapObjects/CGPandoraBox.cpp | 14 +++++++------- lib/mapObjects/MiscObjects.cpp | 6 +++--- server/CGameHandler.cpp | 10 +++++----- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index b3b3f66ee..e96ca1baa 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -945,7 +945,7 @@ bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * sourc if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY { //FIXME: line below is useless when simulating exchange between two non-singular armies - if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature + if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature return true; //at least one exchange will be performed else return false; //no further exchange possible @@ -992,7 +992,7 @@ void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * for (int j = 0; j < GameConstants::ARMY_SIZE; j++) { if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst SLOT - if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature + if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i)); } } diff --git a/client/windows/CTradeWindow.cpp b/client/windows/CTradeWindow.cpp index f44edf089..a601d7e33 100644 --- a/client/windows/CTradeWindow.cpp +++ b/client/windows/CTradeWindow.cpp @@ -861,7 +861,7 @@ void CMarketplaceWindow::selectionChanged(bool side) if(itemsType[1] == RESOURCE) newAmount = LOCPLINT->cb->getResourceAmount(static_cast(soldItemId)); else if(itemsType[1] == CREATURE) - newAmount = hero->getStackCount(SlotID(hLeft->serial)) - (hero->Slots().size() == 1 && hero->needsLastStack()); + newAmount = hero->getStackCount(SlotID(hLeft->serial)) - (hero->stacksCount() == 1 && hero->needsLastStack()); else assert(0); diff --git a/lib/mapObjects/CBank.cpp b/lib/mapObjects/CBank.cpp index d50414078..65a4fcd46 100644 --- a/lib/mapObjects/CBank.cpp +++ b/lib/mapObjects/CBank.cpp @@ -292,9 +292,9 @@ void CBank::doVisit(const CGHeroInstance * hero) const loot.addReplacement(*elem.second); } - if (ourArmy.Slots().size()) + if(ourArmy.stacksCount()) { - if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1) + if(ourArmy.stacksCount() == 1 && ourArmy.Slots().begin()->second->count == 1) iw.text.addTxt (MetaString::ADVOB_TXT, 185); else iw.text.addTxt (MetaString::ADVOB_TXT, 186); diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index c01fa8edf..2299c42a0 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -43,7 +43,7 @@ static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 static int lowestSpeed(const CGHeroInstance * chi) { - if(!chi->Slots().size()) + if(!chi->stacksCount()) { logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<name<<") has no army!"; return 20; diff --git a/lib/mapObjects/CGPandoraBox.cpp b/lib/mapObjects/CGPandoraBox.cpp index 2d0b4d321..f512716d6 100644 --- a/lib/mapObjects/CGPandoraBox.cpp +++ b/lib/mapObjects/CGPandoraBox.cpp @@ -235,7 +235,7 @@ void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const iw.components.clear(); iw.text.clear(); - if (creatures.Slots().size()) + if(creatures.stacksCount()) { //this part is taken straight from creature bank MetaString loot; for(auto & elem : creatures.Slots()) @@ -245,7 +245,7 @@ void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const loot.addReplacement(*elem.second); } - if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1) + if(creatures.stacksCount() == 1 && creatures.Slots().begin()->second->count == 1) iw.text.addTxt(MetaString::ADVOB_TXT, 185); else iw.text.addTxt(MetaString::ADVOB_TXT, 186); @@ -303,17 +303,17 @@ void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const { - if (answer) + if(answer) { - if (stacksCount() > 0) //if pandora's box is protected by army + if(stacksCount() > 0) //if pandora's box is protected by army { showInfoDialog(hero,16,0); cb->startBattleI(hero, this); //grants things after battle } - else if (message.size() == 0 && resources.size() == 0 + else if(message.size() == 0 && resources.size() == 0 && primskills.size() == 0 && abilities.size() == 0 - && abilityLevels.size() == 0 && artifacts.size() == 0 - && spells.size() == 0 && creatures.Slots().size() > 0 + && abilityLevels.size() == 0 && artifacts.size() == 0 + && spells.size() == 0 && creatures.stacksCount() > 0 && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle { showInfoDialog(hero,15,0); diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index 47077866f..1da1b784d 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -1126,10 +1126,10 @@ void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer cb->moveHero(hero->id, dPos, true); } -bool CGWhirlpool::isProtected( const CGHeroInstance * h ) +bool CGWhirlpool::isProtected(const CGHeroInstance * h) { - if(h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) - || (h->Slots().size() == 1 && h->Slots().begin()->second->count == 1)) //we can't remove last unit + if(h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION) || + (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1)) //we can't remove last unit { return true; } diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 7bb4c52f0..b47658f51 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -3223,8 +3223,8 @@ bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHero const CStackInstance &s = hero->getStack(slot); - if( s.count < count //can't sell more creatures than have - || (hero->Slots().size() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack + if( s.count < count //can't sell more creatures than have + || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack { COMPLAIN_RET("Not enough creatures in army!"); } @@ -5103,7 +5103,7 @@ bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstanc if(oldCount < count) COMPLAIN_RET("Not enough creatures to sacrifice!") - else if(oldCount == count && hero->Slots().size() == 1 && hero->needsLastStack()) + else if(oldCount == count && hero->stacksCount() == 1 && hero->needsLastStack()) COMPLAIN_RET("Cannot sacrifice last creature!"); int crid = hero->getStack(slot).type->idNumber; @@ -5167,7 +5167,7 @@ bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval/* = fal if(!sl.army->hasStackAtSlot(sl.slot)) COMPLAIN_RET("Cannot find a stack to erase"); - if(sl.army->Slots().size() == 1 //from the last stack + if(sl.army->stacksCount() == 1 //from the last stack && sl.army->needsLastStack() //that must be left && !forceRemoval) //ignore above conditions if we are forcing removal { @@ -5270,7 +5270,7 @@ bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, if(src.army != dst.army //moving away && count == src.army->getStackCount(src.slot) //all creatures - && src.army->Slots().size() == 1 //from the last stack + && src.army->stacksCount() == 1 //from the last stack && src.army->needsLastStack()) //that must be left { COMPLAIN_RET("Cannot move away the last creature!"); From 8eb4f14ff031836eb6160c05fe334838d4760c06 Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Thu, 24 Dec 2015 22:35:32 +0300 Subject: [PATCH 49/53] MoraleLuckBox: handle BLOCK_LUCK bonus. Fix issue 2130 --- client/widgets/MiscWidgets.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/client/widgets/MiscWidgets.cpp b/client/widgets/MiscWidgets.cpp index 5d0036b67..83ba3bacf 100644 --- a/client/widgets/MiscWidgets.cpp +++ b/client/widgets/MiscWidgets.cpp @@ -380,7 +380,16 @@ void MoraleLuckBox::set(const IBonusBearer *node) if (morale && node && (node->hasBonusOfType(Bonus::UNDEAD) || node->hasBonusOfType(Bonus::BLOCK_MORALE) || node->hasBonusOfType(Bonus::NON_LIVING))) - text += CGI->generaltexth->arraytxt[113]; //unaffected by morale + { + text += CGI->generaltexth->arraytxt[113]; //unaffected by morale + bonusValue = 0; + } + else if(!morale && node && node->hasBonusOfType(Bonus::BLOCK_LUCK)) + { + // TODO: there is no text like "Unaffected by luck" so probably we need own text + text += CGI->generaltexth->arraytxt[noneTxtId]; + bonusValue = 0; + } else if(modifierList->empty()) text += CGI->generaltexth->arraytxt[noneTxtId];//no modifiers else From 66e6f15e671e1d5b9ed6b893632230fab619710c Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Fri, 25 Dec 2015 01:46:44 +0300 Subject: [PATCH 50/53] NewTurn::applyGs: update bonuses in beginning. Fix issue 2083 Before bonuses was removed after hero get movement points and mana so affected hero one day more than intended. --- lib/NetPacksLib.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 4c74a1503..7de59201b 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -1010,6 +1010,13 @@ DLL_LINKAGE void SetAvailableArtifacts::applyGs( CGameState *gs ) DLL_LINKAGE void NewTurn::applyGs( CGameState *gs ) { gs->day = day; + + // Update bonuses before doing anything else so hero don't get more MP than needed + gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs + gs->globalEffects.updateBonuses(Bonus::NDays); + gs->globalEffects.updateBonuses(Bonus::OneWeek); + //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...] + for(NewTurn::Hero h : heroes) //give mana/movement point { CGHeroInstance *hero = gs->getHero(h.id); @@ -1026,11 +1033,6 @@ DLL_LINKAGE void NewTurn::applyGs( CGameState *gs ) for(auto creatureSet : cres) //set available creatures in towns creatureSet.second.applyGs(gs); - gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs - gs->globalEffects.updateBonuses(Bonus::NDays); - gs->globalEffects.updateBonuses(Bonus::OneWeek); - //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...] - for(CGTownInstance* t : gs->map->towns) t->builded = 0; From 6985e96f0d28118315d89f6fddf826e5d210c2ba Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Fri, 25 Dec 2015 11:09:06 +0300 Subject: [PATCH 51/53] CGameHandler::newTurn: use next day TurnInfo to set correct hero MP This hotfix actually fix issue 2083, but in future we need to rework new turn code anyway. See issue 2356. --- server/CGameHandler.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index b47658f51..3c1ba73db 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -1331,7 +1331,8 @@ void CGameHandler::newTurn() NewTurn::Hero hth; hth.id = h->id; - hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).terType != ETerrainType::WATER); + // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356 + hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).terType != ETerrainType::WATER, new TurnInfo(h, 1)); if(h->visitedTown && h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1)) //if hero starts turn in town with mage guild hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana From 29a7934a99fb917c14633c17b65770b0f74cf741 Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Tue, 29 Dec 2015 02:14:08 +0300 Subject: [PATCH 52/53] Refactoring: avoid using namespace when it's not absolutely needed --- AI/VCAI/Fuzzy.cpp | 3 +- AI/VCAI/Goals.cpp | 13 ++--- AI/VCAI/VCAI.cpp | 86 ++++++++++++++--------------- client/windows/CAdvmapInterface.cpp | 1 - lib/BattleState.cpp | 4 +- lib/Connection.cpp | 25 ++++----- server/CVCMIServer.cpp | 13 ++--- 7 files changed, 66 insertions(+), 79 deletions(-) diff --git a/AI/VCAI/Fuzzy.cpp b/AI/VCAI/Fuzzy.cpp index 098899b64..18c2fb93f 100644 --- a/AI/VCAI/Fuzzy.cpp +++ b/AI/VCAI/Fuzzy.cpp @@ -31,7 +31,6 @@ class Engine; class InputVariable; class CGTownInstance; -using namespace vstd; //using namespace Goals; FuzzyHelper *fh; @@ -85,7 +84,7 @@ armyStructure evaluateArmyStructure (const CArmedInstance * army) if (walker) walkersStrenght += s.second->getPower(); - amax (maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED)); + vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED)); } armyStructure as; as.walkers = walkersStrenght / totalStrenght; diff --git a/AI/VCAI/Goals.cpp b/AI/VCAI/Goals.cpp index dcb4f8ba6..afafaf094 100644 --- a/AI/VCAI/Goals.cpp +++ b/AI/VCAI/Goals.cpp @@ -19,7 +19,6 @@ extern boost::thread_specific_ptr cb; extern boost::thread_specific_ptr ai; extern FuzzyHelper * fh; //TODO: this logic should be moved inside VCAI -using namespace vstd; using namespace Goals; TSubgoal Goals::sptr(const AbstractGoal & tmp) @@ -575,7 +574,7 @@ TGoalVec Explore::getAllPossibleSubgoals() { //heroes = ai->getUnblockedHeroes(); heroes = cb->getHeroesInfo(); - erase_if (heroes, [](const HeroPtr h) + vstd::erase_if(heroes, [](const HeroPtr h) { if (ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer return true; @@ -747,10 +746,10 @@ TGoalVec VisitTile::getAllPossibleSubgoals() if (ai->canRecruitAnyHero()) ret.push_back (sptr(Goals::RecruitHero())); } - if (ret.empty()) + if(ret.empty()) { - auto obj = frontOrNull(cb->getVisitableObjs(tile)); - if (obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile + auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile)); + if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile { if (hero.get(true) && hero->id == obj->id) //if it's assigned hero, visit tile. If it's different hero, we can't visit tile now ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast(obj)).setisElementar(true))); @@ -767,7 +766,7 @@ TGoalVec VisitTile::getAllPossibleSubgoals() TSubgoal DigAtTile::whatToDoToAchieve() { - const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile)); + const CGObjectInstance *firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile)); if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest { const CGHeroInstance *h = dynamic_cast(firstObj); @@ -1057,7 +1056,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals() auto otherHeroes = cb->getHeroesInfo(); auto heroDummy = hero; - erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h) + vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h) { return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h) || ai->getGoal(h)->goalType == Goals::GATHER_ARMY); diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index e96ca1baa..c1be68c8a 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -29,8 +29,6 @@ class CGVisitableOPW; const double SAFE_ATTACK_CONSTANT = 1.5; const int GOLD_RESERVE = 10000; //when buying creatures we want to keep at least this much gold (10000 so at least we'll be able to reach capitol) -using namespace vstd; - //one thread may be turn of AI and another will be handling a side effect for AI2 boost::thread_specific_ptr cb; boost::thread_specific_ptr ai; @@ -124,8 +122,8 @@ void VCAI::heroMoved(const TryMoveHero & details) { const int3 from = CGHeroInstance::convertPosition(details.start, false), to = CGHeroInstance::convertPosition(details.end, false); - const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)), - *o2 = frontOrNull(cb->getVisitableObjs(to)); + const CGObjectInstance *o1 = vstd::frontOrNull(cb->getVisitableObjs(from)), + *o2 = vstd::frontOrNull(cb->getVisitableObjs(to)); auto t1 = dynamic_cast(o1); auto t2 = dynamic_cast(o2); @@ -394,8 +392,8 @@ void VCAI::objectRemoved(const CGObjectInstance *obj) LOG_TRACE(logAi); NET_EVENT_HANDLER; - erase_if_present(visitableObjs, obj); - erase_if_present(alreadyVisited, obj); + vstd::erase_if_present(visitableObjs, obj); + vstd::erase_if_present(alreadyVisited, obj); for (auto h : cb->getHeroesInfo()) unreserveObject(h, obj); @@ -518,15 +516,15 @@ void VCAI::objectPropertyChanged(const SetObjectProperty * sop) { //we don't want to visit know object twice (do we really?) if(sop->val == playerID.getNum()) - erase_if_present(visitableObjs, myCb->getObj(sop->id)); - else if (myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES) + vstd::erase_if_present(visitableObjs, myCb->getObj(sop->id)); + else if(myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES) { //we want to visit objects owned by oppponents auto obj = myCb->getObj(sop->id, false); if (obj) { addVisitableObj(obj); - erase_if_present(alreadyVisited, obj); + vstd::erase_if_present(alreadyVisited, obj); } } } @@ -738,7 +736,7 @@ void VCAI::makeTurn() if (isWeeklyRevisitable(obj)) { addVisitableObj(obj); - erase_if_present (alreadyVisited, obj); + vstd::erase_if_present(alreadyVisited, obj); } } } @@ -1121,7 +1119,7 @@ void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruit // if(containsSavedRes(c->cost)) // continue; - amin(count, freeResources() / VLC->creh->creatures[creID]->cost); + vstd::amin(count, freeResources() / VLC->creh->creatures[creID]->cost); if(count > 0) cb->recruitCreatures(d, recruiter, creID, count, i); } @@ -1484,7 +1482,7 @@ void VCAI::wander(HeroPtr h) } range::copy(getPossibleDestinations(h), std::back_inserter(dests)); - erase_if(dests, [&](ObjectIdRef obj) -> bool + vstd::erase_if(dests, [&](ObjectIdRef obj) -> bool { return !isSafeToVisit(h, sm->firstTileToGet(h, obj->visitablePos())); }); @@ -1536,7 +1534,7 @@ void VCAI::wander(HeroPtr h) else if(cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST) { std::vector towns = cb->getTownsInfo(); - erase_if(towns, [](const CGTownInstance *t) -> bool + vstd::erase_if(towns, [](const CGTownInstance *t) -> bool { for(const CGHeroInstance *h : cb->getHeroesInfo()) if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t)) @@ -1587,8 +1585,8 @@ void VCAI::wander(HeroPtr h) void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal) { //TODO: check for presence? - if (goal->invalid()) - erase_if_present(lockedHeroes, h); + if(goal->invalid()) + vstd::erase_if_present(lockedHeroes, h); else { lockedHeroes[h] = goal; @@ -1629,7 +1627,7 @@ void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int NET_EVENT_HANDLER; assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE); status.setBattle(ONGOING_BATTLE); - const CGObjectInstance *presumedEnemy = backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit + const CGObjectInstance *presumedEnemy = vstd::backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile); CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side); } @@ -1669,8 +1667,8 @@ void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj) void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance *obj) { - erase_if_present(reservedObjs, obj); //unreserve objects - erase_if_present(reservedHeroesMap[h], obj); + vstd::erase_if_present(reservedObjs, obj); //unreserve objects + vstd::erase_if_present(reservedHeroesMap[h], obj); } void VCAI::markHeroUnableToExplore (HeroPtr h) @@ -1679,7 +1677,7 @@ void VCAI::markHeroUnableToExplore (HeroPtr h) } void VCAI::markHeroAbleToExplore (HeroPtr h) { - erase_if_present(heroesUnableToExplore, h); + vstd::erase_if_present(heroesUnableToExplore, h); } bool VCAI::isAbleToExplore (HeroPtr h) { @@ -1716,25 +1714,25 @@ void VCAI::validateVisitableObjs() //errorMsg is captured by ref so lambda will take the new text errorMsg = " shouldn't be on the visitable objects list!"; - erase_if(visitableObjs, shouldBeErased); + vstd::erase_if(visitableObjs, shouldBeErased); //FIXME: how comes our own heroes become inaccessible? - erase_if(reservedHeroesMap, [](std::pair> hp) -> bool + vstd::erase_if(reservedHeroesMap, [](std::pair> hp) -> bool { return !hp.first.get(true); }); for(auto &p : reservedHeroesMap) { errorMsg = " shouldn't be on list for hero " + p.first->name + "!"; - erase_if(p.second, shouldBeErased); + vstd::erase_if(p.second, shouldBeErased); } errorMsg = " shouldn't be on the reserved objs list!"; - erase_if(reservedObjs, shouldBeErased); + vstd::erase_if(reservedObjs, shouldBeErased); //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game. errorMsg = " shouldn't be on the already visited objs list!"; - erase_if(alreadyVisited, shouldBeErased); + vstd::erase_if(alreadyVisited, shouldBeErased); } void VCAI::retreiveVisitableObjs(std::vector &out, bool includeOwned /*= false*/) const @@ -1765,7 +1763,7 @@ std::vector VCAI::getFlaggedObjects() const { std::vector ret; retreiveVisitableObjs(ret, true); - erase_if(ret, [](const CGObjectInstance *obj) + vstd::erase_if(ret, [](const CGObjectInstance *obj) { return obj->tempOwner != ai->playerID; }); @@ -1993,7 +1991,7 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) } if (h) { - if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting + if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting { if (visitedObject != *h) performObjectInteraction (visitedObject, h); @@ -2004,16 +2002,16 @@ bool VCAI::moveHeroToTile(int3 dst, HeroPtr h) completeGoal (sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway completeGoal (sptr(Goals::ClearWayTo(dst).sethero(h))); - if (!ret) //reserve object we are heading towards + if(!ret) //reserve object we are heading towards { - auto obj = frontOrNull(cb->getVisitableObjs(dst)); - if (obj && obj != *h) + auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst)); + if(obj && obj != *h) reserveObject(h, obj); } - if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target + if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target { - erase_if_present (lockedHeroes, h); //hero seemingly is confused + vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused throw cannotFulfillGoalException("Invalid path found!"); //FIXME: should never happen } logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret; @@ -2320,7 +2318,7 @@ Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool on } else { - erase_if_present (lockedHeroes, goal->hero); // we seemingly don't know what to do with hero + vstd::erase_if_present (lockedHeroes, goal->hero); // we seemingly don't know what to do with hero } } @@ -2575,7 +2573,7 @@ int3 VCAI::explorationNewPoint(HeroPtr h) for (int i = 1; i < radius; i++) { getVisibleNeighbours(tiles[i-1], tiles[i]); - removeDuplicates(tiles[i]); + vstd::removeDuplicates(tiles[i]); for(const int3 &tile : tiles[i]) { @@ -2620,10 +2618,10 @@ int3 VCAI::explorationDesperate(HeroPtr h) ui64 lowestDanger = -1; int3 bestTile(-1,-1,-1); - for (int i = 1; i < radius; i++) + for(int i = 1; i < radius; i++) { getVisibleNeighbours(tiles[i-1], tiles[i]); - removeDuplicates(tiles[i]); + vstd::removeDuplicates(tiles[i]); for(const int3 &tile : tiles[i]) { @@ -2748,13 +2746,13 @@ void VCAI::lostHero(HeroPtr h) { logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name; - erase_if_present(lockedHeroes, h); + vstd::erase_if_present(lockedHeroes, h); for(auto obj : reservedHeroesMap[h]) { - erase_if_present(reservedObjs, obj); //unreserve all objects for that hero + vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero } - erase_if_present(reservedHeroesMap, h); - erase_if_present(cachedSectorMaps, h); + vstd::erase_if_present(reservedHeroesMap, h); + vstd::erase_if_present(cachedSectorMaps, h); } void VCAI::answerQuery(QueryID queryID, int selection) @@ -2795,15 +2793,15 @@ void VCAI::validateObject(const CGObjectInstance *obj) void VCAI::validateObject(ObjectIdRef obj) { - auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; }; + auto matchesId = [&](const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; }; if(!obj) { - erase_if(visitableObjs, matchesId); + vstd::erase_if(visitableObjs, matchesId); for(auto &p : reservedHeroesMap) - erase_if(p.second, matchesId); + vstd::erase_if(p.second, matchesId); - erase_if(reservedObjs, matchesId); + vstd::erase_if(reservedObjs, matchesId); } } @@ -3081,7 +3079,7 @@ void SectorMap::exploreNewSector(crint3 pos, int num, CCallback * cbp) } } - removeDuplicates(s.embarkmentPoints); + vstd::removeDuplicates(s.embarkmentPoints); } void SectorMap::write(crstring fname) diff --git a/client/windows/CAdvmapInterface.cpp b/client/windows/CAdvmapInterface.cpp index 439523fb3..1108a61a2 100644 --- a/client/windows/CAdvmapInterface.cpp +++ b/client/windows/CAdvmapInterface.cpp @@ -55,7 +55,6 @@ */ #define ADVOPT (conf.go()->ac) -using namespace boost::logic; using namespace CSDL_Ext; CAdvMapInt *adventureInt; diff --git a/lib/BattleState.cpp b/lib/BattleState.cpp index e7a0d4783..3892d9aa2 100644 --- a/lib/BattleState.cpp +++ b/lib/BattleState.cpp @@ -201,9 +201,7 @@ void BattleInfo::localInitStack(CStack * s) namespace CGH { - using namespace std; - - static void readBattlePositions(const JsonNode &node, vector< vector > & dest) + static void readBattlePositions(const JsonNode &node, std::vector< std::vector > & dest) { for(const JsonNode &level : node.Vector()) { diff --git a/lib/Connection.cpp b/lib/Connection.cpp index 562fea3f9..b9ae6fd6c 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -17,9 +17,6 @@ * */ -using namespace boost; -using namespace boost::asio::ip; - extern template void registerTypes(CISer & s); extern template void registerTypes(COSer & s); extern template void registerTypes(CTypeList & s); @@ -70,13 +67,13 @@ void CConnection::init() } CConnection::CConnection(std::string host, std::string port, std::string Name) -:iser(this), oser(this), io_service(new asio::io_service), name(Name) +:iser(this), oser(this), io_service(new boost::asio::io_service), name(Name) { int i; - boost::system::error_code error = asio::error::host_not_found; - socket = new tcp::socket(*io_service); - tcp::resolver resolver(*io_service); - tcp::resolver::iterator end, pom, endpoint_iterator = resolver.resolve(tcp::resolver::query(host,port),error); + boost::system::error_code error = boost::asio::error::host_not_found; + socket = new boost::asio::ip::tcp::socket(*io_service); + boost::asio::ip::tcp::resolver resolver(*io_service); + boost::asio::ip::tcp::resolver::iterator end, pom, endpoint_iterator = resolver.resolve(boost::asio::ip::tcp::resolver::query(host,port),error); if(error) { logNetwork->errorStream() << "Problem with resolving: \n" << error; @@ -132,8 +129,8 @@ CConnection::CConnection(TSocket * Socket, std::string Name ) CConnection::CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name) : iser(this), oser(this), name(Name)//, send(this), rec(this) { - boost::system::error_code error = asio::error::host_not_found; - socket = new tcp::socket(*io_service); + boost::system::error_code error = boost::asio::error::host_not_found; + socket = new boost::asio::ip::tcp::socket(*io_service); acceptor->accept(*socket,error); if (error) { @@ -149,7 +146,7 @@ int CConnection::write(const void * data, unsigned size) try { int ret; - ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size))); + ret = boost::asio::write(*socket,boost::asio::const_buffers_1(boost::asio::const_buffer(data,size))); return ret; } catch(...) @@ -164,7 +161,7 @@ int CConnection::read(void * data, unsigned size) //LOG("Receiving " << size << " byte(s) of data" <accept(*s,*error); } @@ -314,7 +311,7 @@ void CPregameServer::startListeningThread(CConnection * pc) } CVCMIServer::CVCMIServer() -: io(new boost::asio::io_service()), acceptor(new TAcceptor(*io, tcp::endpoint(tcp::v4(), port))), firstConnection(nullptr) +: io(new boost::asio::io_service()), acceptor(new TAcceptor(*io, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))), firstConnection(nullptr) { logNetwork->debugStream() << "CVCMIServer created!"; } @@ -414,7 +411,7 @@ void CVCMIServer::start() boost::system::error_code error; logNetwork->infoStream()<<"Listening for connections at port " << acceptor->local_endpoint().port(); - auto s = new tcp::socket(acceptor->get_io_service()); + auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service()); boost::thread acc(std::bind(vaccept,acceptor,s,&error)); #ifndef VCMI_ANDROID sr->setToTrueAndNotify(); @@ -499,7 +496,7 @@ void CVCMIServer::loadGame() } else { - auto s = new tcp::socket(acceptor->get_io_service()); + auto s = new boost::asio::ip::tcp::socket(acceptor->get_io_service()); acceptor->accept(*s,error); if(error) //retry { @@ -610,7 +607,7 @@ int main(int argc, char** argv) srand ( (ui32)time(nullptr) ); try { - io_service io_service; + boost::asio::io_service io_service; CVCMIServer server; try From 9fd1cff090d4ca094f4590a74c4ac2279aa843ee Mon Sep 17 00:00:00 2001 From: Arseniy Shestakov Date: Tue, 29 Dec 2015 05:43:33 +0300 Subject: [PATCH 53/53] Refactoring: always use std prefix for shared_ptr, unique_ptr and make_shared Long time ago it's was used without prefix to make future switch from boost to std version easier. I discusses this with Ivan and decide to drop these using from Global.h now. This change wouldn't break anything because there was already code with prefix for each of three cases. --- AI/BattleAI/BattleAI.cpp | 6 ++-- AI/BattleAI/BattleAI.h | 4 +-- AI/BattleAI/main.cpp | 4 +-- AI/EmptyAI/CEmptyAI.cpp | 2 +- AI/EmptyAI/CEmptyAI.h | 4 +-- AI/EmptyAI/exp_funcs.cpp | 4 +-- AI/StupidAI/StupidAI.cpp | 4 +-- AI/StupidAI/StupidAI.h | 4 +-- AI/StupidAI/main.cpp | 4 +-- AI/VCAI/Fuzzy.cpp | 2 +- AI/VCAI/Fuzzy.h | 2 +- AI/VCAI/Goals.cpp | 2 +- AI/VCAI/Goals.h | 4 +-- AI/VCAI/VCAI.cpp | 2 +- AI/VCAI/VCAI.h | 10 +++---- AI/VCAI/main.cpp | 4 +-- CCallback.cpp | 8 ++--- CCallback.h | 8 ++--- Global.h | 3 -- client/CMusicHandler.cpp | 2 +- client/CMusicHandler.h | 6 ++-- client/CPlayerInterface.cpp | 2 +- client/CPlayerInterface.h | 6 ++-- client/CPreGame.cpp | 6 ++-- client/CPreGame.h | 8 ++--- client/Client.cpp | 32 ++++++++++---------- client/Client.h | 30 +++++++++---------- client/battle/CBattleInterface.cpp | 4 +-- client/battle/CBattleInterface.h | 12 ++++---- client/battle/CCreatureAnimation.h | 2 +- client/windows/CQuestLog.cpp | 4 +-- client/windows/CQuestLog.h | 4 +-- lib/BattleState.cpp | 22 +++++++------- lib/BattleState.h | 4 +-- lib/CArtHandler.cpp | 8 ++--- lib/CArtHandler.h | 4 +-- lib/CBattleCallback.cpp | 10 +++---- lib/CBattleCallback.h | 4 +-- lib/CCreatureHandler.cpp | 2 +- lib/CGameInfoCallback.cpp | 4 +-- lib/CGameInfoCallback.h | 2 +- lib/CGameInterface.cpp | 20 ++++++------- lib/CGameInterface.h | 14 ++++----- lib/CGameState.cpp | 2 +- lib/CGameState.h | 2 +- lib/CPathfinder.h | 4 +-- lib/Connection.cpp | 4 +-- lib/Connection.h | 46 ++++++++++++++--------------- lib/HeroBonus.cpp | 26 ++++++++-------- lib/HeroBonus.h | 6 ++-- lib/JsonNode.cpp | 6 ++-- lib/NetPacks.h | 4 +-- lib/StartInfo.h | 4 +-- lib/logging/CLogger.cpp | 2 +- lib/logging/CLogger.h | 6 ++-- lib/mapObjects/MiscObjects.cpp | 6 ++-- lib/mapObjects/MiscObjects.h | 2 +- lib/mapping/CCampaignHandler.cpp | 4 +-- lib/mapping/CCampaignHandler.h | 6 ++-- lib/mapping/CMap.h | 4 +-- lib/mapping/CMapEditManager.cpp | 6 ++-- lib/mapping/CMapEditManager.h | 10 +++---- lib/mapping/CMapInfo.h | 8 ++--- lib/rmg/CMapGenerator.h | 2 +- lib/rmg/CZoneGraphGenerator.cpp | 2 +- lib/rmg/CZoneGraphGenerator.h | 4 +-- lib/rmg/CZonePlacer.h | 2 +- lib/spells/BattleSpellMechanics.cpp | 2 +- scripting/erm/ERMScriptModule.cpp | 4 +-- server/CGameHandler.cpp | 30 +++++++++---------- server/CGameHandler.h | 6 ++-- server/CQuery.cpp | 8 ++--- server/CQuery.h | 6 ++-- 73 files changed, 257 insertions(+), 260 deletions(-) diff --git a/AI/BattleAI/BattleAI.cpp b/AI/BattleAI/BattleAI.cpp index 91a977d98..e7aa7d9b2 100644 --- a/AI/BattleAI/BattleAI.cpp +++ b/AI/BattleAI/BattleAI.cpp @@ -8,7 +8,7 @@ #include "../../lib/VCMI_Lib.h" using boost::optional; -static shared_ptr cbc; +static std::shared_ptr cbc; #define LOGL(text) print(text) #define LOGFL(text, formattingEl) print(boost::str(boost::format(text) % formattingEl)) @@ -91,7 +91,7 @@ CBattleAI::~CBattleAI(void) } } -void CBattleAI::init(shared_ptr CB) +void CBattleAI::init(std::shared_ptr CB) { print("init called, saving ptr to IBattleCallback"); cbc = cb = CB; @@ -610,7 +610,7 @@ ThreatMap::ThreatMap(const CStack *Endangered) : endangered(Endangered) const TBonusListPtr StackWithBonuses::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/, const std::string &cachingStr /*= ""*/) const { - TBonusListPtr ret = make_shared(); + TBonusListPtr ret = std::make_shared(); const TBonusListPtr originalList = stack->getAllBonuses(selector, limit, root, cachingStr); range::copy(*originalList, std::back_inserter(*ret)); for(auto &bonus : bonusesToAdd) diff --git a/AI/BattleAI/BattleAI.h b/AI/BattleAI/BattleAI.h index 685ca4a47..b6612145d 100644 --- a/AI/BattleAI/BattleAI.h +++ b/AI/BattleAI/BattleAI.h @@ -110,7 +110,7 @@ struct PotentialTargets class CBattleAI : public CBattleGameInterface { int side; - shared_ptr cb; + std::shared_ptr cb; //Previous setting of cb bool wasWaitingForRealize, wasUnlockingGs; @@ -120,7 +120,7 @@ public: CBattleAI(void); ~CBattleAI(void); - void init(shared_ptr CB) override; + void init(std::shared_ptr CB) override; void actionFinished(const BattleAction &action) override;//occurs AFTER every action taken by any stack or by the hero void actionStarted(const BattleAction &action) override;//occurs BEFORE every action taken by any stack or by the hero BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack diff --git a/AI/BattleAI/main.cpp b/AI/BattleAI/main.cpp index fa9b67a7d..b174fe02c 100644 --- a/AI/BattleAI/main.cpp +++ b/AI/BattleAI/main.cpp @@ -25,7 +25,7 @@ extern "C" DLL_EXPORT void GetAiName(char* name) strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName); } -extern "C" DLL_EXPORT void GetNewBattleAI(shared_ptr &out) +extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr &out) { - out = make_shared(); + out = std::make_shared(); } diff --git a/AI/EmptyAI/CEmptyAI.cpp b/AI/EmptyAI/CEmptyAI.cpp index 58d8fa946..8f25dc009 100644 --- a/AI/EmptyAI/CEmptyAI.cpp +++ b/AI/EmptyAI/CEmptyAI.cpp @@ -3,7 +3,7 @@ #include "../../lib/CRandomGenerator.h" -void CEmptyAI::init(shared_ptr CB) +void CEmptyAI::init(std::shared_ptr CB) { cb = CB; human=false; diff --git a/AI/EmptyAI/CEmptyAI.h b/AI/EmptyAI/CEmptyAI.h index 262511a5d..83ad577a7 100644 --- a/AI/EmptyAI/CEmptyAI.h +++ b/AI/EmptyAI/CEmptyAI.h @@ -7,10 +7,10 @@ struct HeroMoveDetails; class CEmptyAI : public CGlobalAI { - shared_ptr cb; + std::shared_ptr cb; public: - void init(shared_ptr CB) override; + void init(std::shared_ptr CB) override; void yourTurn() override; void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector &skills, QueryID queryID) override; void commanderGotLevel (const CCommanderInstance * commander, std::vector skills, QueryID queryID) override; diff --git a/AI/EmptyAI/exp_funcs.cpp b/AI/EmptyAI/exp_funcs.cpp index 3a6f65e77..bc91f5196 100644 --- a/AI/EmptyAI/exp_funcs.cpp +++ b/AI/EmptyAI/exp_funcs.cpp @@ -13,7 +13,7 @@ extern "C" DLL_EXPORT void GetAiName(char* name) strcpy(name,NAME); } -extern "C" DLL_EXPORT void GetNewAI(shared_ptr &out) +extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr &out) { - out = make_shared(); + out = std::make_shared(); } \ No newline at end of file diff --git a/AI/StupidAI/StupidAI.cpp b/AI/StupidAI/StupidAI.cpp index b87b14a8d..8e0557d2d 100644 --- a/AI/StupidAI/StupidAI.cpp +++ b/AI/StupidAI/StupidAI.cpp @@ -5,7 +5,7 @@ #include "../../CCallback.h" #include "../../lib/CCreatureHandler.h" -static shared_ptr cbc; +static std::shared_ptr cbc; CStupidAI::CStupidAI(void) : side(-1) @@ -19,7 +19,7 @@ CStupidAI::~CStupidAI(void) print("destroyed"); } -void CStupidAI::init(shared_ptr CB) +void CStupidAI::init(std::shared_ptr CB) { print("init called, saving ptr to IBattleCallback"); cbc = cb = CB; diff --git a/AI/StupidAI/StupidAI.h b/AI/StupidAI/StupidAI.h index 2d225412a..a8a96e33e 100644 --- a/AI/StupidAI/StupidAI.h +++ b/AI/StupidAI/StupidAI.h @@ -5,14 +5,14 @@ class CStupidAI : public CBattleGameInterface { int side; - shared_ptr cb; + std::shared_ptr cb; void print(const std::string &text) const; public: CStupidAI(void); ~CStupidAI(void); - void init(shared_ptr CB) override; + void init(std::shared_ptr CB) override; void actionFinished(const BattleAction &action) override;//occurs AFTER every action taken by any stack or by the hero void actionStarted(const BattleAction &action) override;//occurs BEFORE every action taken by any stack or by the hero BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack diff --git a/AI/StupidAI/main.cpp b/AI/StupidAI/main.cpp index 70ab20a03..b62f53ba0 100644 --- a/AI/StupidAI/main.cpp +++ b/AI/StupidAI/main.cpp @@ -25,7 +25,7 @@ extern "C" DLL_EXPORT void GetAiName(char* name) strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName); } -extern "C" DLL_EXPORT void GetNewBattleAI(shared_ptr &out) +extern "C" DLL_EXPORT void GetNewBattleAI(std::shared_ptr &out) { - out = make_shared(); + out = std::make_shared(); } diff --git a/AI/VCAI/Fuzzy.cpp b/AI/VCAI/Fuzzy.cpp index 18c2fb93f..fac28819a 100644 --- a/AI/VCAI/Fuzzy.cpp +++ b/AI/VCAI/Fuzzy.cpp @@ -296,7 +296,7 @@ FuzzyHelper::TacticalAdvantage::~TacticalAdvantage() delete threat; } -//shared_ptr chooseSolution (std::vector> & vec) +//std::shared_ptr chooseSolution (std::vector> & vec) Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec) { diff --git a/AI/VCAI/Fuzzy.h b/AI/VCAI/Fuzzy.h index b736c7b4d..7c45e8d63 100644 --- a/AI/VCAI/Fuzzy.h +++ b/AI/VCAI/Fuzzy.h @@ -83,5 +83,5 @@ public: float getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy); //returns factor how many times enemy is stronger than us Goals::TSubgoal chooseSolution (Goals::TGoalVec vec); - //shared_ptr chooseSolution (std::vector> & vec); + //std::shared_ptr chooseSolution (std::vector> & vec); }; diff --git a/AI/VCAI/Goals.cpp b/AI/VCAI/Goals.cpp index afafaf094..6c4f8fdce 100644 --- a/AI/VCAI/Goals.cpp +++ b/AI/VCAI/Goals.cpp @@ -23,7 +23,7 @@ using namespace Goals; TSubgoal Goals::sptr(const AbstractGoal & tmp) { - shared_ptr ptr; + std::shared_ptr ptr; ptr.reset(tmp.clone()); return ptr; } diff --git a/AI/VCAI/Goals.h b/AI/VCAI/Goals.h index 9819b4ba3..ad1835415 100644 --- a/AI/VCAI/Goals.h +++ b/AI/VCAI/Goals.h @@ -107,7 +107,7 @@ public: static TSubgoal tryRecruitHero(); ///Visitor pattern - //TODO: make accept work for shared_ptr... somehow + //TODO: make accept work for std::shared_ptr... somehow virtual void accept (VCAI * ai); //unhandled goal will report standard error virtual float accept (FuzzyHelper * f); @@ -162,7 +162,7 @@ public: TSubgoal iAmElementar() { setisElementar(true); - shared_ptr ptr; + std::shared_ptr ptr; ptr.reset(clone()); return ptr; } diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index c1be68c8a..4510529ef 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -555,7 +555,7 @@ void VCAI::showWorldViewEx(const std::vector & objectPositions) NET_EVENT_HANDLER; } -void VCAI::init(shared_ptr CB) +void VCAI::init(std::shared_ptr CB) { LOG_TRACE(logAi); myCb = CB; diff --git a/AI/VCAI/VCAI.h b/AI/VCAI/VCAI.h index 6963b8c79..d68b15c77 100644 --- a/AI/VCAI/VCAI.h +++ b/AI/VCAI/VCAI.h @@ -93,7 +93,7 @@ struct SectorMap //std::vector>> pathfinderSector; std::map infoOnSectors; - shared_ptr> visibleTiles; + std::shared_ptr> visibleTiles; SectorMap(); SectorMap(HeroPtr h); @@ -129,7 +129,7 @@ public: friend class FuzzyHelper; - std::map > knownTeleportChannels; + std::map > knownTeleportChannels; std::map knownSubterraneanGates; ObjectInstanceID destinationTeleport; int3 destinationTeleportPos; @@ -153,9 +153,9 @@ public: AIStatus status; std::string battlename; - shared_ptr myCb; + std::shared_ptr myCb; - unique_ptr makingTurn; + std::unique_ptr makingTurn; VCAI(void); ~VCAI(void); @@ -180,7 +180,7 @@ public: virtual std::string getBattleAIName() const override; - virtual void init(shared_ptr CB) override; + virtual void init(std::shared_ptr CB) override; virtual void yourTurn() override; virtual void heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector &skills, QueryID queryID) override; //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id diff --git a/AI/VCAI/main.cpp b/AI/VCAI/main.cpp index 04f15137c..26f49cd9e 100644 --- a/AI/VCAI/main.cpp +++ b/AI/VCAI/main.cpp @@ -23,7 +23,7 @@ extern "C" DLL_EXPORT void GetAiName(char* name) strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName); } -extern "C" DLL_EXPORT void GetNewAI(shared_ptr &out) +extern "C" DLL_EXPORT void GetNewAI(std::shared_ptr &out) { - out = make_shared(); + out = std::make_shared(); } diff --git a/CCallback.cpp b/CCallback.cpp index 6b8a28958..576c3cabc 100644 --- a/CCallback.cpp +++ b/CCallback.cpp @@ -333,22 +333,22 @@ int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance return swapCreatures(s1, s2, p1, p2); } -void CCallback::registerGameInterface(shared_ptr gameEvents) +void CCallback::registerGameInterface(std::shared_ptr gameEvents) { cl->additionalPlayerInts[*player].push_back(gameEvents); } -void CCallback::registerBattleInterface(shared_ptr battleEvents) +void CCallback::registerBattleInterface(std::shared_ptr battleEvents) { cl->additionalBattleInts[*player].push_back(battleEvents); } -void CCallback::unregisterGameInterface(shared_ptr gameEvents) +void CCallback::unregisterGameInterface(std::shared_ptr gameEvents) { cl->additionalPlayerInts[*player] -= gameEvents; } -void CCallback::unregisterBattleInterface(shared_ptr battleEvents) +void CCallback::unregisterBattleInterface(std::shared_ptr battleEvents) { cl->additionalBattleInts[*player] -= battleEvents; } diff --git a/CCallback.h b/CCallback.h index 46afc2adf..473055ebc 100644 --- a/CCallback.h +++ b/CCallback.h @@ -110,10 +110,10 @@ public: virtual void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out); //Set of metrhods that allows adding more interfaces for this player that'll receive game event call-ins. - void registerGameInterface(shared_ptr gameEvents); - void registerBattleInterface(shared_ptr battleEvents); - void unregisterGameInterface(shared_ptr gameEvents); - void unregisterBattleInterface(shared_ptr battleEvents); + void registerGameInterface(std::shared_ptr gameEvents); + void registerBattleInterface(std::shared_ptr battleEvents); + void unregisterGameInterface(std::shared_ptr gameEvents); + void unregisterBattleInterface(std::shared_ptr battleEvents); void unregisterAllInterfaces(); //stops delivering information about game events to player interfaces -> can be called ONLY after victory/loss diff --git a/Global.h b/Global.h index 0d8923aab..4089f4425 100644 --- a/Global.h +++ b/Global.h @@ -180,9 +180,6 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size."); /* ---------------------------------------------------------------------------- */ /* Usings */ /* ---------------------------------------------------------------------------- */ -using std::shared_ptr; -using std::unique_ptr; -using std::make_shared; using namespace std::placeholders; namespace range = boost::range; diff --git a/client/CMusicHandler.cpp b/client/CMusicHandler.cpp index 0b800f13e..2bc5853b2 100644 --- a/client/CMusicHandler.cpp +++ b/client/CMusicHandler.cpp @@ -349,7 +349,7 @@ void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loo queueNext(this, "", selectedEntry->second, loop); } -void CMusicHandler::queueNext(unique_ptr queued) +void CMusicHandler::queueNext(std::unique_ptr queued) { if (!initialized) return; diff --git a/client/CMusicHandler.h b/client/CMusicHandler.h index 9d548f489..f0031d56a 100644 --- a/client/CMusicHandler.h +++ b/client/CMusicHandler.h @@ -114,11 +114,11 @@ private: SettingsListener listener; void onVolumeChange(const JsonNode &volumeNode); - unique_ptr current; - unique_ptr next; + std::unique_ptr current; + std::unique_ptr next; void queueNext(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped); - void queueNext(unique_ptr queued); + void queueNext(std::unique_ptr queued); std::map > musicsSet; public: diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index a81750ed9..ffcf90eca 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -133,7 +133,7 @@ CPlayerInterface::~CPlayerInterface() if(LOCPLINT == this) LOCPLINT = nullptr; } -void CPlayerInterface::init(shared_ptr CB) +void CPlayerInterface::init(std::shared_ptr CB) { cb = CB; if(observerInDuelMode) diff --git a/client/CPlayerInterface.h b/client/CPlayerInterface.h index 1d0204d0c..0d6c86e51 100644 --- a/client/CPlayerInterface.h +++ b/client/CPlayerInterface.h @@ -105,7 +105,7 @@ public: static CBattleInterface * battleInt; //nullptr if no battle CInGameConsole * cingconsole; - shared_ptr cb; //to communicate with engine + std::shared_ptr cb; //to communicate with engine const BattleAction *curAction; //during the battle - action currently performed by active stack (or nullptr) std::list dialogs; //queue of dialogs awaiting to be shown (not currently shown!) @@ -116,7 +116,7 @@ public: std::vector sleepingHeroes; //if hero is in here, he's sleeping //During battle is quick combat mode is used - shared_ptr autofightingAI; //AI that makes decisions + std::shared_ptr autofightingAI; //AI that makes decisions bool isAutoFightOn; //Flag, switch it to stop quick combat. Don't touch if there is no battle interface. const CArmedInstance * getSelection(); @@ -236,7 +236,7 @@ public: void openTownWindow(const CGTownInstance * town); //shows townscreen void openHeroWindow(const CGHeroInstance * hero); //shows hero window with given hero void updateInfo(const CGObjectInstance * specific); - void init(shared_ptr CB) override; + void init(std::shared_ptr CB) override; int3 repairScreenPos(int3 pos); //returns position closest to pos we can center screen on // show dialogs diff --git a/client/CPreGame.cpp b/client/CPreGame.cpp index 68b14df70..15ccddc66 100644 --- a/client/CPreGame.cpp +++ b/client/CPreGame.cpp @@ -1918,7 +1918,7 @@ const CMapGenOptions & CRandomMapTab::getMapGenOptions() const return mapGenOptions; } -void CRandomMapTab::setMapGenOptions(shared_ptr opts) +void CRandomMapTab::setMapGenOptions(std::shared_ptr opts) { mapSizeBtnGroup->setSelected(vstd::find_pos(getPossibleMapSizes(), opts->getWidth())); twoLevelsBtn->setSelected(opts->getHasTwoLevels()); @@ -3291,14 +3291,14 @@ void CBonusSelection::init() sFlags = CDefHandler::giveDef("ITGFLAGS.DEF"); } -CBonusSelection::CBonusSelection(shared_ptr _ourCampaign) : ourCampaign(_ourCampaign) +CBonusSelection::CBonusSelection(std::shared_ptr _ourCampaign) : ourCampaign(_ourCampaign) { init(); } CBonusSelection::CBonusSelection(const std::string & campaignFName) { - ourCampaign = make_shared(CCampaignHandler::getCampaign(campaignFName)); + ourCampaign = std::make_shared(CCampaignHandler::getCampaign(campaignFName)); init(); } diff --git a/client/CPreGame.h b/client/CPreGame.h index f277bcbe2..59ac607b6 100644 --- a/client/CPreGame.h +++ b/client/CPreGame.h @@ -300,7 +300,7 @@ public: CFunctionList & getMapInfoChanged(); const CMapInfo * getMapInfo() const; const CMapGenOptions & getMapGenOptions() const; - void setMapGenOptions(shared_ptr opts); + void setMapGenOptions(std::shared_ptr opts); private: void addButtonsToGroup(CToggleGroup * group, const std::vector & defs, int startIndex, int endIndex, int btnWidth, int helpStartIndex) const; @@ -316,7 +316,7 @@ private: * compOnlyTeamsCntGroup, * waterContentGroup, * monsterStrengthGroup; CButton * showRandMaps; CMapGenOptions mapGenOptions; - unique_ptr mapInfo; + std::unique_ptr mapInfo; CFunctionList mapInfoChanged; }; @@ -463,7 +463,7 @@ class CBonusSelection : public CIntObject { public: CBonusSelection(const std::string & campaignFName); - CBonusSelection(shared_ptr _ourCampaign); + CBonusSelection(std::shared_ptr _ourCampaign); ~CBonusSelection(); void showAll(SDL_Surface * to) override; @@ -532,7 +532,7 @@ private: CDefHandler * sFlags; // Data - shared_ptr ourCampaign; + std::shared_ptr ourCampaign; int selectedMap; boost::optional selectedBonus; StartInfo startInfo; diff --git a/client/Client.cpp b/client/Client.cpp index bd8b1f695..8f8ef5be0 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -264,7 +264,7 @@ void CClient::loadGame(const std::string & fname, const bool server, const std:: serv = sh.justConnectToServer(ipaddr, realPort); CStopWatch tmh; - unique_ptr loader; + std::unique_ptr loader; try { std::string clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME)); @@ -461,7 +461,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) } else { - installNewPlayerInterface(make_shared(color), color); + installNewPlayerInterface(std::make_shared(color), color); humanPlayers++; } } @@ -477,7 +477,7 @@ void CClient::newGame( CConnection *con, StartInfo *si ) if(!gNoGUI) { boost::unique_lock un(*LOCPLINT->pim); - auto p = make_shared(PlayerColor::NEUTRAL); + auto p = std::make_shared(PlayerColor::NEUTRAL); p->observerInDuelMode = true; installNewPlayerInterface(p, boost::none); GH.curInt = p.get(); @@ -542,7 +542,7 @@ void CClient::serialize(CISer & h, const int version) h & pid & dllname & isHuman; LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid); - shared_ptr nInt; + std::shared_ptr nInt; if(dllname.length()) { if(pid == PlayerColor::NEUTRAL) @@ -560,7 +560,7 @@ void CClient::serialize(CISer & h, const int version) else { assert(isHuman); - nInt = make_shared(pid); + nInt = std::make_shared(pid); } nInt->dllName = dllname; @@ -611,7 +611,7 @@ void CClient::serialize(CISer & h, const int version, const std::set nInt; + std::shared_ptr nInt; if(dllname.length()) { if(pid == PlayerColor::NEUTRAL) @@ -630,7 +630,7 @@ void CClient::serialize(CISer & h, const int version, const std::set(pid); + nInt = std::make_shared(pid); } nInt->dllName = dllname; @@ -668,11 +668,11 @@ void CClient::handlePack( CPack * pack ) delete pack; } -void CClient::finishCampaign( shared_ptr camp ) +void CClient::finishCampaign( std::shared_ptr camp ) { } -void CClient::proposeNextMission(shared_ptr camp) +void CClient::proposeNextMission(std::shared_ptr camp) { GH.pushInt(new CBonusSelection(camp)); } @@ -724,7 +724,7 @@ void CClient::battleStarted(const BattleInfo * info) // if(battleCallbacks.count(side)) // battleCallbacks[side]->setBattle(info); - shared_ptr att, def; + std::shared_ptr att, def; auto &leftSide = info->sides[0], &rightSide = info->sides[1]; @@ -790,7 +790,7 @@ PlayerColor CClient::getLocalPlayer() const return getCurrentPlayer(); } -void CClient::commenceTacticPhaseForInt(shared_ptr battleInt) +void CClient::commenceTacticPhaseForInt(std::shared_ptr battleInt) { setThreadName("CClient::commenceTacticPhaseForInt"); try @@ -842,7 +842,7 @@ int CClient::sendRequest(const CPack *request, PlayerColor player) return requestID; } -void CClient::campaignMapFinished( shared_ptr camp ) +void CClient::campaignMapFinished( std::shared_ptr camp ) { endGame(false); @@ -865,7 +865,7 @@ void CClient::campaignMapFinished( shared_ptr camp ) } } -void CClient::installNewPlayerInterface(shared_ptr gameInterface, boost::optional color) +void CClient::installNewPlayerInterface(std::shared_ptr gameInterface, boost::optional color) { boost::unique_lock un(*LOCPLINT->pim); PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE); @@ -876,7 +876,7 @@ void CClient::installNewPlayerInterface(shared_ptr gameInterface playerint[colorUsed] = gameInterface; logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed; - auto cb = make_shared(gs, color, this); + auto cb = std::make_shared(gs, color, this); callbacks[colorUsed] = cb; battleCallbacks[colorUsed] = cb; gameInterface->init(cb); @@ -884,7 +884,7 @@ void CClient::installNewPlayerInterface(shared_ptr gameInterface installNewBattleInterface(gameInterface, color, false); } -void CClient::installNewBattleInterface(shared_ptr battleInterface, boost::optional color, bool needCallback /*= true*/) +void CClient::installNewBattleInterface(std::shared_ptr battleInterface, boost::optional color, bool needCallback /*= true*/) { boost::unique_lock un(*LOCPLINT->pim); PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE); @@ -897,7 +897,7 @@ void CClient::installNewBattleInterface(shared_ptr battleI if(needCallback) { logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color; - auto cbc = make_shared(gs, color, this); + auto cbc = std::make_shared(gs, color, this); battleCallbacks[colorUsed] = cbc; battleInterface->init(cbc); } diff --git a/client/Client.h b/client/Client.h index 1f3ef6e2c..e713e8984 100644 --- a/client/Client.h +++ b/client/Client.h @@ -115,17 +115,17 @@ public: /// Class which handles client - server logic class CClient : public IGameCallback { - unique_ptr pathInfo; + std::unique_ptr pathInfo; public: - std::map > callbacks; //callbacks given to player interfaces - std::map > battleCallbacks; //callbacks given to player interfaces - std::vector> privilagedGameEventReceivers; //scripting modules, spectator interfaces - std::vector> privilagedBattleEventReceivers; //scripting modules, spectator interfaces - std::map> playerint; - std::map> battleints; + std::map > callbacks; //callbacks given to player interfaces + std::map > battleCallbacks; //callbacks given to player interfaces + std::vector> privilagedGameEventReceivers; //scripting modules, spectator interfaces + std::vector> privilagedBattleEventReceivers; //scripting modules, spectator interfaces + std::map> playerint; + std::map> battleints; - std::map>> additionalPlayerInts; - std::map>> additionalBattleInts; + std::map>> additionalPlayerInts; + std::map>> additionalBattleInts; bool hotSeat; CConnection *serv; @@ -146,8 +146,8 @@ public: void newGame(CConnection *con, StartInfo *si); //con - connection to server void loadNeutralBattleAI(); - void installNewPlayerInterface(shared_ptr gameInterface, boost::optional color); - void installNewBattleInterface(shared_ptr battleInterface, boost::optional color, bool needCallback = true); + void installNewPlayerInterface(std::shared_ptr gameInterface, boost::optional color); + void installNewBattleInterface(std::shared_ptr battleInterface, boost::optional color, bool needCallback = true); std::string aiNameForPlayer(const PlayerSettings &ps, bool battleAI); //empty means no AI -> human void endGame(bool closeConnection = true); @@ -155,9 +155,9 @@ public: void save(const std::string & fname); void loadGame(const std::string & fname, const bool server = true, const std::vector& humanplayerindices = std::vector(), const int loadnumplayers = 1, int player_ = -1, const std::string & ipaddr = "", const std::string & port = ""); void run(); - void campaignMapFinished( shared_ptr camp ); - void finishCampaign( shared_ptr camp ); - void proposeNextMission(shared_ptr camp); + void campaignMapFinished( std::shared_ptr camp ); + void finishCampaign( std::shared_ptr camp ); + void proposeNextMission(std::shared_ptr camp); void invalidatePaths(); const CPathsInfo * getPathsInfo(const CGHeroInstance *h); @@ -233,7 +233,7 @@ public: void handlePack( CPack * pack ); //applies the given pack and deletes it void battleStarted(const BattleInfo * info); - void commenceTacticPhaseForInt(shared_ptr battleInt); //will be called as separate thread + void commenceTacticPhaseForInt(std::shared_ptr battleInt); //will be called as separate thread void commitPackage(CPackForClient *pack) override; diff --git a/client/battle/CBattleInterface.cpp b/client/battle/CBattleInterface.cpp index 452b41d76..4c2725d9f 100644 --- a/client/battle/CBattleInterface.cpp +++ b/client/battle/CBattleInterface.cpp @@ -95,7 +95,7 @@ void CBattleInterface::addNewAnim(CBattleAnimation * anim) CBattleInterface::CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const SDL_Rect & myRect, - shared_ptr att, shared_ptr defen) + std::shared_ptr att, std::shared_ptr defen) : background(nullptr), queue(nullptr), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0), activeStack(nullptr), mouseHoveredStack(nullptr), stackToActivate(nullptr), selectedStack(nullptr), previouslyHoveredHex(-1), currentlyHoveredHex(-1), attackingHex(-1), stackCanCastSpell(false), creatureCasting(false), spellDestSelectMode(false), spellSelMode(NO_LOCATION), spellToCast(nullptr), sp(nullptr), @@ -3260,7 +3260,7 @@ void CBattleInterface::showStacks(SDL_Surface * to, std::vector } } -void CBattleInterface::showObstacles(SDL_Surface *to, std::vector > &obstacles) +void CBattleInterface::showObstacles(SDL_Surface *to, std::vector > &obstacles) { for (auto & obstacle : obstacles) { diff --git a/client/battle/CBattleInterface.h b/client/battle/CBattleInterface.h index b8c2aedad..1bd38445e 100644 --- a/client/battle/CBattleInterface.h +++ b/client/battle/CBattleInterface.h @@ -79,7 +79,7 @@ struct BattleObjectsByHex typedef std::vector TWallList; typedef std::vector TStackList; typedef std::vector TEffectList; - typedef std::vector > TObstacleList; + typedef std::vector > TObstacleList; struct HexData { @@ -153,7 +153,7 @@ private: BattleHex currentlyHoveredHex; //number of hex that is supposed to be hovered (for a while it may be inappropriately set, but will be renewed soon) int attackingHex; //hex from which the stack would perform attack with current cursor - shared_ptr tacticianInterface; //used during tactics mode, points to the interface of player with higher tactics (can be either attacker or defender in hot-seat), valid onloy for human players + std::shared_ptr tacticianInterface; //used during tactics mode, points to the interface of player with higher tactics (can be either attacker or defender in hot-seat), valid onloy for human players bool tacticsMode; bool stackCanCastSpell; //if true, active stack could possibly cast some target spell bool creatureCasting; //if true, stack currently aims to cats a spell @@ -212,8 +212,8 @@ private: friend class CBattleInterface; } * siegeH; - shared_ptr attackerInt, defenderInt; //because LOCPLINT is not enough in hotSeat - shared_ptr curInt; //current player interface + std::shared_ptr attackerInt, defenderInt; //because LOCPLINT is not enough in hotSeat + std::shared_ptr curInt; //current player interface const CGHeroInstance * getActiveHero(); //returns hero that can currently cast a spell /** Methods for displaying battle screen */ @@ -229,7 +229,7 @@ private: void showAliveStacks(SDL_Surface * to, std::vector stacks); void showStacks(SDL_Surface * to, std::vector stacks); - void showObstacles(SDL_Surface *to, std::vector > &obstacles); + void showObstacles(SDL_Surface *to, std::vector > &obstacles); void showPiecesOfWall(SDL_Surface * to, std::vector pieces); void showBattleEffects(SDL_Surface *to, const std::vector &battleEffects); @@ -249,7 +249,7 @@ public: ui32 animIDhelper; //for giving IDs for animations static CondSh animsAreDisplayed; //for waiting with the end of battle for end of anims - CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const SDL_Rect & myRect, shared_ptr att, shared_ptr defen); //c-tor + CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const SDL_Rect & myRect, std::shared_ptr att, std::shared_ptr defen); //c-tor ~CBattleInterface(); //d-tor //std::vector timeinterested; //animation handling diff --git a/client/battle/CCreatureAnimation.h b/client/battle/CCreatureAnimation.h index 6896ee196..e37d00e66 100644 --- a/client/battle/CCreatureAnimation.h +++ b/client/battle/CCreatureAnimation.h @@ -66,7 +66,7 @@ private: //animation raw data //TODO: use vector instead? - unique_ptr pixelData; + std::unique_ptr pixelData; size_t pixelDataSize; // speed of animation, measure in frames per second diff --git a/client/windows/CQuestLog.cpp b/client/windows/CQuestLog.cpp index 43f547386..7c76de96d 100644 --- a/client/windows/CQuestLog.cpp +++ b/client/windows/CQuestLog.cpp @@ -86,7 +86,7 @@ void CQuestMinimap::addQuestMarks (const QuestInfo * q) if (level != tile.z) setLevel(tile.z); - auto pic = make_shared("VwSymbol.def", 3, x, y); + auto pic = std::make_shared("VwSymbol.def", 3, x, y); pic->moveBy (Point ( -pic->pos.w/2, -pic->pos.h/2)); pic->callback = std::bind (&CQuestMinimap::iconClicked, this); @@ -179,7 +179,7 @@ void CQuestLog::recreateLabelList() else text.addReplacement(quests[i].obj->getObjectName()); //get name of the object } - auto label = make_shared(Rect(13, 195, 149,31), FONT_SMALL, TOPLEFT, Colors::WHITE, text.toString()); + auto label = std::make_shared(Rect(13, 195, 149,31), FONT_SMALL, TOPLEFT, Colors::WHITE, text.toString()); label->disable(); label->callback = std::bind(&CQuestLog::selectQuest, this, i, currentLabel); diff --git a/client/windows/CQuestLog.h b/client/windows/CQuestLog.h index 1beb2e40f..e8e24ffa3 100644 --- a/client/windows/CQuestLog.h +++ b/client/windows/CQuestLog.h @@ -58,7 +58,7 @@ public: class CQuestMinimap : public CMinimap { - std::vector > icons; + std::vector > icons; void clickLeft(tribool down, bool previousState) override{}; //minimap ignores clicking on its surface void iconClicked(); @@ -86,7 +86,7 @@ class CQuestLog : public CWindowObject CLabel * hideCompleteLabel; const std::vector quests; - std::vector > labels; + std::vector > labels; CTextBox * description; CQuestMinimap * minimap; CSlider * slider; //scrolls quests diff --git a/lib/BattleState.cpp b/lib/BattleState.cpp index 3892d9aa2..178f9b961 100644 --- a/lib/BattleState.cpp +++ b/lib/BattleState.cpp @@ -373,7 +373,7 @@ BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldTyp try { - auto obstPtr = make_shared(); + auto obstPtr = std::make_shared(); obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE; obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle); obstPtr->uniqueID = curB->obstacles.size(); @@ -422,7 +422,7 @@ BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldTyp RangeGenerator posgenerator(18, 168, ourRand); - auto obstPtr = make_shared(); + auto obstPtr = std::make_shared(); obstPtr->ID = obid; obstPtr->pos = posgenerator.getSuchNumber(validPosition); obstPtr->uniqueID = curB->obstacles.size(); @@ -539,7 +539,7 @@ BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldTyp } //moat - auto moat = make_shared(); + auto moat = std::make_shared(); moat->ID = curB->town->subID; moat->obstacleType = CObstacleInstance::MOAT; moat->uniqueID = curB->obstacles.size(); @@ -584,19 +584,19 @@ BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldTyp case BFieldType::HOLY_GROUND: { - curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared(EAlignment::GOOD))); - curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared(EAlignment::EVIL))); + curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared(EAlignment::GOOD))); + curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared(EAlignment::EVIL))); break; } case BFieldType::CLOVER_FIELD: { //+2 luck bonus for neutral creatures - curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared(EAlignment::NEUTRAL))); + curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared(EAlignment::NEUTRAL))); break; } case BFieldType::EVIL_FOG: { - curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared(EAlignment::GOOD))); - curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared(EAlignment::EVIL))); + curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared(EAlignment::GOOD))); + curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared(EAlignment::EVIL))); break; } case BFieldType::CURSED_GROUND: @@ -612,7 +612,7 @@ BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldTyp //overlay premies given //native terrain bonuses - auto nativeTerrain = make_shared(curB->terrainType); + auto nativeTerrain = std::make_shared(curB->terrainType); curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain)); curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain)); curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain)); @@ -701,13 +701,13 @@ int BattleInfo::getIdForNewStack() const return 0; } -shared_ptr BattleInfo::getObstacleOnTile(BattleHex tile) const +std::shared_ptr BattleInfo::getObstacleOnTile(BattleHex tile) const { for(auto &obs : obstacles) if(vstd::contains(obs->getAffectedTiles(), tile)) return obs; - return shared_ptr(); + return std::shared_ptr(); } BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType) diff --git a/lib/BattleState.h b/lib/BattleState.h index a06b517cd..e52b4f63d 100644 --- a/lib/BattleState.h +++ b/lib/BattleState.h @@ -83,7 +83,7 @@ struct DLL_LINKAGE BattleInfo : public CBonusSystemNode, public CBattleInfoCallb const CGTownInstance * town; //used during town siege, nullptr if this is not a siege (note that fortless town IS also a siege) int3 tile; //for background and bonuses std::vector stacks; - std::vector > obstacles; + std::vector > obstacles; SiegeInfo si; BFieldType battlefieldType; //like !!BA:B @@ -124,7 +124,7 @@ struct DLL_LINKAGE BattleInfo : public CBonusSystemNode, public CBattleInfoCallb //std::vector getAccessibility(const CStack * stack, bool addOccupiable, std::vector * attackable = nullptr, bool forPassingBy = false) const; //returns vector of accessible tiles (taking into account the creature range) //bool isObstacleVisibleForSide(const CObstacleInstance &obstacle, ui8 side) const; - shared_ptr getObstacleOnTile(BattleHex tile) const; + std::shared_ptr getObstacleOnTile(BattleHex tile) const; std::set getStoppers(bool whichSidePerspective) const; ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg, CRandomGenerator & rand); //charge - number of hexes travelled before attack (for champion's jousting) diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index d40c9b08a..9d89aae60 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -502,7 +502,7 @@ ArtifactID CArtHandler::pickRandomArtifact(CRandomGenerator & rand, int flags) return pickRandomArtifact(rand, flags, [](ArtifactID){ return true;}); } -Bonus *createBonus(Bonus::BonusType type, int val, int subtype, Bonus::ValueType valType, shared_ptr limiter = shared_ptr(), int additionalInfo = 0) +Bonus *createBonus(Bonus::BonusType type, int val, int subtype, Bonus::ValueType valType, std::shared_ptr limiter = std::shared_ptr(), int additionalInfo = 0) { auto added = new Bonus(Bonus::PERMANENT,type,Bonus::ARTIFACT,val,-1,subtype); added->additionalInfo = additionalInfo; @@ -511,7 +511,7 @@ Bonus *createBonus(Bonus::BonusType type, int val, int subtype, Bonus::ValueType return added; } -Bonus *createBonus(Bonus::BonusType type, int val, int subtype, shared_ptr propagator = shared_ptr(), int additionalInfo = 0) +Bonus *createBonus(Bonus::BonusType type, int val, int subtype, std::shared_ptr propagator = std::shared_ptr(), int additionalInfo = 0) { auto added = new Bonus(Bonus::PERMANENT,type,Bonus::ARTIFACT,val,-1,subtype); added->additionalInfo = additionalInfo; @@ -520,12 +520,12 @@ Bonus *createBonus(Bonus::BonusType type, int val, int subtype, shared_ptr limiter, int additionalInfo) +void CArtHandler::giveArtBonus( ArtifactID aid, Bonus::BonusType type, int val, int subtype, Bonus::ValueType valType, std::shared_ptr limiter, int additionalInfo) { giveArtBonus(aid, createBonus(type, val, subtype, valType, limiter, additionalInfo)); } -void CArtHandler::giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype, shared_ptr propagator /*= nullptr*/, int additionalInfo) +void CArtHandler::giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype, std::shared_ptr propagator /*= nullptr*/, int additionalInfo) { giveArtBonus(aid, createBonus(type, val, subtype, propagator, additionalInfo)); } diff --git a/lib/CArtHandler.h b/lib/CArtHandler.h index 5a6f4a841..6a71ac2bf 100644 --- a/lib/CArtHandler.h +++ b/lib/CArtHandler.h @@ -253,8 +253,8 @@ private: void loadComponents(CArtifact * art, const JsonNode & node); void loadGrowingArt(CGrowingArtifact * art, const JsonNode & node); - void giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype = -1, Bonus::ValueType valType = Bonus::BASE_NUMBER, shared_ptr limiter = shared_ptr(), int additionalinfo = 0); - void giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype, shared_ptr propagator, int additionalinfo = 0); + void giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype = -1, Bonus::ValueType valType = Bonus::BASE_NUMBER, std::shared_ptr limiter = std::shared_ptr(), int additionalinfo = 0); + void giveArtBonus(ArtifactID aid, Bonus::BonusType type, int val, int subtype, std::shared_ptr propagator, int additionalinfo = 0); void giveArtBonus(ArtifactID aid, Bonus *bonus); void erasePickedArt(ArtifactID id); diff --git a/lib/CBattleCallback.cpp b/lib/CBattleCallback.cpp index 3116bf818..bdfb2580e 100644 --- a/lib/CBattleCallback.cpp +++ b/lib/CBattleCallback.cpp @@ -130,9 +130,9 @@ BFieldType CBattleInfoEssentials::battleGetBattlefieldType() const return getBattle()->battlefieldType; } -std::vector > CBattleInfoEssentials::battleGetAllObstacles(boost::optional perspective /*= boost::none*/) const +std::vector > CBattleInfoEssentials::battleGetAllObstacles(boost::optional perspective /*= boost::none*/) const { - std::vector > ret; + std::vector > ret; RETURN_IF_NOT_BATTLE(ret); if(!perspective) @@ -1100,9 +1100,9 @@ std::pair CBattleInfoCallback::battleEstimateDamage(const BattleAtta return ret; } -shared_ptr CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const +std::shared_ptr CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const { - RETURN_IF_NOT_BATTLE(shared_ptr()); + RETURN_IF_NOT_BATTLE(std::shared_ptr()); for(auto &obs : battleGetAllObstacles()) { @@ -1113,7 +1113,7 @@ shared_ptr CBattleInfoCallback::battleGetObstacleOnPos( } } - return shared_ptr(); + return std::shared_ptr(); } AccessibilityInfo CBattleInfoCallback::getAccesibility() const diff --git a/lib/CBattleCallback.h b/lib/CBattleCallback.h index 19f5bf1d2..0c7323706 100644 --- a/lib/CBattleCallback.h +++ b/lib/CBattleCallback.h @@ -170,7 +170,7 @@ public: ETerrainType battleTerrainType() const; BFieldType battleGetBattlefieldType() const; - std::vector > battleGetAllObstacles(boost::optional perspective = boost::none) const; //returns all obstacles on the battlefield + std::vector > battleGetAllObstacles(boost::optional perspective = boost::none) const; //returns all obstacles on the battlefield /** @brief Main method for getting battle stacks * @@ -243,7 +243,7 @@ public: //battle boost::optional battleIsFinished() const; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw - shared_ptr battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking = true) const; //blocking obstacles makes tile inaccessible, others cause special effects (like Land Mines, Moat, Quicksands) + std::shared_ptr battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking = true) const; //blocking obstacles makes tile inaccessible, others cause special effects (like Land Mines, Moat, Quicksands) const CStack * battleGetStackByPos(BattleHex pos, bool onlyAlive = true) const; //returns stack info by given pos void battleGetStackQueue(std::vector &out, const int howMany, const int turn = 0, int lastMoved = -1) const; void battleGetStackCountOutsideHexes(bool *ac) const; // returns hexes which when in front of a stack cause us to move the amount box back diff --git a/lib/CCreatureHandler.cpp b/lib/CCreatureHandler.cpp index 7cc5c6d8a..cbde78fe7 100644 --- a/lib/CCreatureHandler.cpp +++ b/lib/CCreatureHandler.cpp @@ -723,7 +723,7 @@ void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode { if (val.Bool() == true) { - bonus->limiter = make_shared(RankRangeLimiter(lowerLimit)); + bonus->limiter = std::make_shared(RankRangeLimiter(lowerLimit)); creature->addNewBonus (new Bonus(*bonus)); //bonuses must be unique objects break; //TODO: allow bonuses to turn off? } diff --git a/lib/CGameInfoCallback.cpp b/lib/CGameInfoCallback.cpp index 66080b7aa..9abf44444 100644 --- a/lib/CGameInfoCallback.cpp +++ b/lib/CGameInfoCallback.cpp @@ -475,7 +475,7 @@ const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const } //TODO: typedef? -shared_ptr> CGameInfoCallback::getAllVisibleTiles() const +std::shared_ptr> CGameInfoCallback::getAllVisibleTiles() const { assert(player.is_initialized()); auto team = getPlayerTeam(player.get()); @@ -496,7 +496,7 @@ shared_ptr> CGameInfoCallback::getAllVisible else tileArray[x][y][z] = nullptr; } - return make_shared>(tileArray); + return std::make_shared>(tileArray); } EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID ) diff --git a/lib/CGameInfoCallback.h b/lib/CGameInfoCallback.h index 20c94db30..81c691e71 100644 --- a/lib/CGameInfoCallback.h +++ b/lib/CGameInfoCallback.h @@ -91,7 +91,7 @@ public: const CMapHeader * getMapHeader()const; int3 getMapSize() const; //returns size of map - z is 1 for one - level map and 2 for two level map const TerrainTile * getTile(int3 tile, bool verbose = true) const; - shared_ptr> getAllVisibleTiles() const; + std::shared_ptr> getAllVisibleTiles() const; bool isInTheMap(const int3 &pos) const; //town diff --git a/lib/CGameInterface.cpp b/lib/CGameInterface.cpp index bef31306e..8896e0965 100644 --- a/lib/CGameInterface.cpp +++ b/lib/CGameInterface.cpp @@ -24,19 +24,19 @@ #ifdef VCMI_ANDROID // we can't use shared libraries on Android so here's a hack extern "C" DLL_EXPORT void VCAI_GetAiName(char* name); -extern "C" DLL_EXPORT void VCAI_GetNewAI(shared_ptr &out); +extern "C" DLL_EXPORT void VCAI_GetNewAI(std::shared_ptr &out); extern "C" DLL_EXPORT void StupidAI_GetAiName(char* name); -extern "C" DLL_EXPORT void StupidAI_GetNewBattleAI(shared_ptr &out); +extern "C" DLL_EXPORT void StupidAI_GetNewBattleAI(std::shared_ptr &out); extern "C" DLL_EXPORT void BattleAI_GetAiName(char* name); -extern "C" DLL_EXPORT void BattleAI_GetNewBattleAI(shared_ptr &out); +extern "C" DLL_EXPORT void BattleAI_GetNewBattleAI(std::shared_ptr &out); #endif template -shared_ptr createAny(const boost::filesystem::path& libpath, const std::string& methodName) +std::shared_ptr createAny(const boost::filesystem::path& libpath, const std::string& methodName) { - typedef void(*TGetAIFun)(shared_ptr&); + typedef void(*TGetAIFun)(std::shared_ptr&); typedef void(*TGetNameFun)(char*); char temp[150]; @@ -102,7 +102,7 @@ shared_ptr createAny(const boost::filesystem::path& libpath, const std::st getName(temp); logGlobal->infoStream() << "Loaded " << temp; - shared_ptr ret; + std::shared_ptr ret; getAI(ret); if(!ret) logGlobal->errorStream() << "Cannot get AI!"; @@ -111,7 +111,7 @@ shared_ptr createAny(const boost::filesystem::path& libpath, const std::st } template -shared_ptr createAnyAI(std::string dllname, const std::string& methodName) +std::shared_ptr createAnyAI(std::string dllname, const std::string& methodName) { logGlobal->infoStream() << "Opening " << dllname; const boost::filesystem::path filePath = @@ -121,17 +121,17 @@ shared_ptr createAnyAI(std::string dllname, const std::string& methodName) return ret; } -shared_ptr CDynLibHandler::getNewAI(std::string dllname) +std::shared_ptr CDynLibHandler::getNewAI(std::string dllname) { return createAnyAI(dllname, "GetNewAI"); } -shared_ptr CDynLibHandler::getNewBattleAI(std::string dllname ) +std::shared_ptr CDynLibHandler::getNewBattleAI(std::string dllname ) { return createAnyAI(dllname, "GetNewBattleAI"); } -shared_ptr CDynLibHandler::getNewScriptingModule(std::string dllname) +std::shared_ptr CDynLibHandler::getNewScriptingModule(std::string dllname) { return createAny(dllname, "GetNewModule"); } diff --git a/lib/CGameInterface.h b/lib/CGameInterface.h index a49b5894f..d3f5e513a 100644 --- a/lib/CGameInterface.h +++ b/lib/CGameInterface.h @@ -67,7 +67,7 @@ public: std::string dllName; virtual ~CBattleGameInterface() {}; - virtual void init(shared_ptr CB){}; + virtual void init(std::shared_ptr CB){}; //battle call-ins virtual BattleAction activeStack(const CStack * stack)=0; //called when it's turn of that stack @@ -82,7 +82,7 @@ public: class DLL_LINKAGE CGameInterface : public CBattleGameInterface, public IGameEventsReceiver { public: - virtual void init(shared_ptr CB){}; + virtual void init(std::shared_ptr CB){}; virtual void yourTurn(){}; //called AFTER playerStartsTurn(player) //pskill is gained primary skill, interface has to choose one of given skills and call callback with selection id @@ -105,9 +105,9 @@ public: class DLL_LINKAGE CDynLibHandler { public: - static shared_ptr getNewAI(std::string dllname); - static shared_ptr getNewBattleAI(std::string dllname); - static shared_ptr getNewScriptingModule(std::string dllname); + static std::shared_ptr getNewAI(std::string dllname); + static std::shared_ptr getNewBattleAI(std::string dllname); + static std::shared_ptr getNewScriptingModule(std::string dllname); }; class DLL_LINKAGE CGlobalAI : public CGameInterface // AI class (to derivate) @@ -123,8 +123,8 @@ class DLL_LINKAGE CAdventureAI : public CGlobalAI public: CAdventureAI() {}; - shared_ptr battleAI; - shared_ptr cbc; + std::shared_ptr battleAI; + std::shared_ptr cbc; virtual std::string getBattleAIName() const = 0; //has to return name of the battle AI to be used diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index cb1c0a6fc..1d534cf24 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -3177,7 +3177,7 @@ DuelParameters DuelParameters::fromJSON(const std::string &fname) for(const JsonNode &n : duelData["obstacles"].Vector()) { - auto oi = make_shared(); + auto oi = std::make_shared(); if(n.getType() == JsonNode::DATA_VECTOR) { oi->ID = n.Vector()[0].Float(); diff --git a/lib/CGameState.h b/lib/CGameState.h index 2dedd638f..783c468c2 100644 --- a/lib/CGameState.h +++ b/lib/CGameState.h @@ -149,7 +149,7 @@ struct DLL_EXPORT DuelParameters } } sides[2]; - std::vector > obstacles; + std::vector > obstacles; static DuelParameters fromJSON(const std::string &fname); diff --git a/lib/CPathfinder.h b/lib/CPathfinder.h index 2333031ee..195eeaf97 100644 --- a/lib/CPathfinder.h +++ b/lib/CPathfinder.h @@ -162,7 +162,7 @@ private: CPathsInfo & out; const CGHeroInstance * hero; const std::vector > > &FoW; - unique_ptr hlp; + std::unique_ptr hlp; enum EPatrolState { PATROL_NONE = 0, @@ -244,7 +244,7 @@ struct DLL_LINKAGE TurnInfo BonusCache(TBonusListPtr bonusList); }; - unique_ptr bonusCache; + std::unique_ptr bonusCache; const CGHeroInstance * hero; TBonusListPtr bonuses; diff --git a/lib/Connection.cpp b/lib/Connection.cpp index b9ae6fd6c..20b113a81 100644 --- a/lib/Connection.cpp +++ b/lib/Connection.cpp @@ -439,7 +439,7 @@ CTypeList::TypeInfoPtr CTypeList::registerType( const std::type_info *type ) return typeDescr; //type found, return ptr to structure //type not found - add it to the list and return given ID - auto newType = make_shared(); + auto newType = std::make_shared(); newType->typeID = typeInfos.size() + 1; newType->name = type->name(); typeInfos[type] = newType; @@ -604,7 +604,7 @@ int CLoadIntegrityValidator::read( void * data, unsigned size ) return ret; } -unique_ptr CLoadIntegrityValidator::decay() +std::unique_ptr CLoadIntegrityValidator::decay() { primaryFile->serializer.loadedPointers = this->serializer.loadedPointers; primaryFile->serializer.loadedPointersTypes = this->serializer.loadedPointersTypes; diff --git a/lib/Connection.h b/lib/Connection.h index c7552ca33..259b9f23f 100644 --- a/lib/Connection.h +++ b/lib/Connection.h @@ -82,12 +82,12 @@ enum SerializationLvl struct TypeComparer { bool operator()(const std::type_info *a, const std::type_info *b) const - { - #ifndef __APPLE__ - return a->before(*b); - #else - return strcmp(a->name(), b->name()) < 0; - #endif + { + #ifndef __APPLE__ + return a->before(*b); + #else + return strcmp(a->name(), b->name()) < 0; + #endif } }; @@ -192,7 +192,7 @@ private: THROW_FORMAT("Cannot find caster for conversion %s -> %s which is needed to cast %s -> %s", from->name % to->name % fromArg->name() % toArg->name()); auto &caster = casters.at(castingPair); - ptr = (*caster.*CastingFunction)(ptr); //Why does unique_ptr not have operator->* ..? + ptr = (*caster.*CastingFunction)(ptr); //Why does std::unique_ptr not have operator->* ..? } return ptr; @@ -667,15 +667,15 @@ public: }; template - class CPointerSaver : public CBasicPointerSaver + class CPointerSaver : public CBasicPointerSaver { public: void savePtr(CSaverBase &ar, const void *data) const override - { + { COSer &s = static_cast(ar); - const T *ptr = static_cast(data); + const T *ptr = static_cast(data); //T is most derived known type, it's time to call actual serialize - const_cast(ptr)->serialize(s,version); + const_cast(ptr)->serialize(s,version); } }; @@ -785,7 +785,7 @@ public: //write type identifier ui16 tid = typeList.getTypeID(data); - *this << tid; + *this << tid; this->savePointerHlp(tid, data); } @@ -849,13 +849,13 @@ public: const_cast(data).serialize(*this,version); } template - void saveSerializable(const shared_ptr &data) + void saveSerializable(const std::shared_ptr &data) { T *internalPtr = data.get(); *this << internalPtr; } template - void saveSerializable(const unique_ptr &data) + void saveSerializable(const std::unique_ptr &data) { T *internalPtr = data.get(); *this << internalPtr; @@ -1332,7 +1332,7 @@ public: template - void loadSerializable(shared_ptr &data) + void loadSerializable(std::shared_ptr &data) { typedef typename boost::remove_const::type NonConstT; NonConstT *internalPtr; @@ -1353,7 +1353,7 @@ public: auto typeWeNeedToReturn = typeList.getTypeInfo(); if(*actualType == *typeWeNeedToReturn) { - // No casting needed, just unpack already stored shared_ptr and return it + // No casting needed, just unpack already stored std::shared_ptr and return it data = boost::any_cast>(itr->second); } else @@ -1383,7 +1383,7 @@ public: data.reset(); } template - void loadSerializable(unique_ptr &data) + void loadSerializable(std::unique_ptr &data) { T *internalPtr; *this >> internalPtr; @@ -1551,7 +1551,7 @@ public: COSer serializer; std::string fName; - unique_ptr sfile; + std::unique_ptr sfile; CSaveFile(const std::string &fname); //throws! ~CSaveFile(); @@ -1578,7 +1578,7 @@ public: CISer serializer; std::string fName; - unique_ptr sfile; + std::unique_ptr sfile; CLoadFile(const boost::filesystem::path & fname, int minimalVersion = version); //throws! ~CLoadFile(); @@ -1603,7 +1603,7 @@ class DLL_LINKAGE CLoadIntegrityValidator { public: CISer serializer; - unique_ptr primaryFile, controlFile; + std::unique_ptr primaryFile, controlFile; bool foundDesync; CLoadIntegrityValidator(const std::string &primaryFileName, const std::string &controlFileName, int minimalVersion = version); //throws! @@ -1611,7 +1611,7 @@ public: int read( void * data, unsigned size) override; //throws! void checkMagicBytes(const std::string &text); - unique_ptr decay(); //returns primary file. CLoadIntegrityValidator stops being usable anymore + std::unique_ptr decay(); //returns primary file. CLoadIntegrityValidator stops being usable anymore }; typedef boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service > TSocket; @@ -1702,12 +1702,12 @@ public: CMemorySerializer(); template - static unique_ptr deepCopy(const T &data) + static std::unique_ptr deepCopy(const T &data) { CMemorySerializer mem; mem.oser << &data; - unique_ptr ret; + std::unique_ptr ret; mem.iser >> ret; return ret; } diff --git a/lib/HeroBonus.cpp b/lib/HeroBonus.cpp index f0e7c1748..dc51e877a 100644 --- a/lib/HeroBonus.cpp +++ b/lib/HeroBonus.cpp @@ -64,19 +64,19 @@ const std::map bonusLimitEffect = const std::map bonusLimiterMap = { - {"SHOOTER_ONLY", make_shared(Bonus::SHOOTER)}, - {"DRAGON_NATURE", make_shared(Bonus::DRAGON_NATURE)}, - {"IS_UNDEAD", make_shared(Bonus::UNDEAD)} + {"SHOOTER_ONLY", std::make_shared(Bonus::SHOOTER)}, + {"DRAGON_NATURE", std::make_shared(Bonus::DRAGON_NATURE)}, + {"IS_UNDEAD", std::make_shared(Bonus::UNDEAD)} }; const std::map bonusPropagatorMap = { - {"BATTLE_WIDE", make_shared(CBonusSystemNode::BATTLE)}, - {"VISITED_TOWN_AND_VISITOR", make_shared(CBonusSystemNode::TOWN_AND_VISITOR)}, - {"PLAYER_PROPAGATOR", make_shared(CBonusSystemNode::PLAYER)}, - {"HERO", make_shared(CBonusSystemNode::HERO)}, - {"TEAM_PROPAGATOR", make_shared(CBonusSystemNode::TEAM)}, //untested - {"GLOBAL_EFFECT", make_shared(CBonusSystemNode::GLOBAL_EFFECTS)} + {"BATTLE_WIDE", std::make_shared(CBonusSystemNode::BATTLE)}, + {"VISITED_TOWN_AND_VISITOR", std::make_shared(CBonusSystemNode::TOWN_AND_VISITOR)}, + {"PLAYER_PROPAGATOR", std::make_shared(CBonusSystemNode::PLAYER)}, + {"HERO", std::make_shared(CBonusSystemNode::HERO)}, + {"TEAM_PROPAGATOR", std::make_shared(CBonusSystemNode::TEAM)}, //untested + {"GLOBAL_EFFECT", std::make_shared(CBonusSystemNode::GLOBAL_EFFECTS)} }; //untested @@ -651,7 +651,7 @@ const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, c //We still don't have the bonuses (didn't returned them from cache) //Perform bonus selection - auto ret = make_shared(); + auto ret = std::make_shared(); cachedBonuses.getBonuses(*ret, selector, limit); // Save the results in the cache @@ -668,7 +668,7 @@ const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, c const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/) const { - auto ret = make_shared(); + auto ret = std::make_shared(); // Get bonus results without caching enabled. BonusList beforeLimiting, afterLimiting; @@ -1067,7 +1067,7 @@ void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const { - auto ret = make_shared(); + auto ret = std::make_shared(); limitBonuses(allBonuses, *ret); return ret; } @@ -1318,7 +1318,7 @@ Bonus * Bonus::addLimiter(TLimiterPtr Limiter) if(!limiterList) { //Create a new limiter list with old limiter and the new one will be pushed later - limiterList = make_shared(); + limiterList = std::make_shared(); limiterList->add(limiter); limiter = limiterList; } diff --git a/lib/HeroBonus.h b/lib/HeroBonus.h index 86a316087..82f1756dc 100644 --- a/lib/HeroBonus.h +++ b/lib/HeroBonus.h @@ -20,9 +20,9 @@ class ILimiter; class IPropagator; class BonusList; -typedef shared_ptr TBonusListPtr; -typedef shared_ptr TLimiterPtr; -typedef shared_ptr TPropagatorPtr; +typedef std::shared_ptr TBonusListPtr; +typedef std::shared_ptr TLimiterPtr; +typedef std::shared_ptr TPropagatorPtr; typedef std::set TNodes; typedef std::set TCNodes; typedef std::vector TNodesVector; diff --git a/lib/JsonNode.cpp b/lib/JsonNode.cpp index e2ca8a08e..c9ea181b2 100644 --- a/lib/JsonNode.cpp +++ b/lib/JsonNode.cpp @@ -483,10 +483,10 @@ Bonus * JsonUtils::parseBonus (const JsonNode &ability) break; case JsonNode::DATA_STRUCT: //customizable limiters { - shared_ptr l; + std::shared_ptr l; if (limiter["type"].String() == "CREATURE_TYPE_LIMITER") { - shared_ptr l2 = make_shared(); //TODO: How the hell resolve pointer to creature? + std::shared_ptr l2 = std::make_shared(); //TODO: How the hell resolve pointer to creature? const JsonVector vec = limiter["parameters"].Vector(); VLC->modh->identifiers.requestIdentifier("creature", vec[0], [=](si32 creature) { @@ -503,7 +503,7 @@ Bonus * JsonUtils::parseBonus (const JsonNode &ability) } if (limiter["type"].String() == "HAS_ANOTHER_BONUS_LIMITER") { - shared_ptr l2 = make_shared(); + std::shared_ptr l2 = std::make_shared(); const JsonVector vec = limiter["parameters"].Vector(); std::string anotherBonusType = vec[0].String(); diff --git a/lib/NetPacks.h b/lib/NetPacks.h index 06bdbf014..26e75cc1e 100644 --- a/lib/NetPacks.h +++ b/lib/NetPacks.h @@ -443,7 +443,7 @@ struct UpdateCampaignState : public CPackForClient //119 type = 119; } - shared_ptr camp; + std::shared_ptr camp; void applyCl(CClient *cl); template void serialize(Handler &h, const int version) @@ -1681,7 +1681,7 @@ struct BattleObstaclePlaced : public CPackForClient //3020 DLL_LINKAGE void applyGs(CGameState *gs); //effect void applyCl(CClient *cl); //play animations & stuff - shared_ptr obstacle; + std::shared_ptr obstacle; template void serialize(Handler &h, const int version) { diff --git a/lib/StartInfo.h b/lib/StartInfo.h index 8d54faa70..c45df434b 100644 --- a/lib/StartInfo.h +++ b/lib/StartInfo.h @@ -82,9 +82,9 @@ struct StartInfo ui8 turnTime; //in minutes, 0=unlimited std::string mapname; // empty for random map, otherwise name of the map or savegame bool createRandomMap() const { return mapGenOptions.get() != nullptr; } - shared_ptr mapGenOptions; + std::shared_ptr mapGenOptions; - shared_ptr campState; + std::shared_ptr campState; PlayerSettings & getIthPlayersSettings(PlayerColor no) { diff --git a/lib/logging/CLogger.cpp b/lib/logging/CLogger.cpp index d93506622..6ad8715cc 100644 --- a/lib/logging/CLogger.cpp +++ b/lib/logging/CLogger.cpp @@ -134,7 +134,7 @@ void CLogger::setLevel(ELogLevel::ELogLevel level) const CLoggerDomain & CLogger::getDomain() const { return domain; } -void CLogger::addTarget(unique_ptr && target) +void CLogger::addTarget(std::unique_ptr && target) { TLockGuard _(mx); targets.push_back(std::move(target)); diff --git a/lib/logging/CLogger.h b/lib/logging/CLogger.h index e26529390..e4ceaf866 100644 --- a/lib/logging/CLogger.h +++ b/lib/logging/CLogger.h @@ -105,7 +105,7 @@ public: inline void log(ELogLevel::ELogLevel level, const std::string & message) const; - void addTarget(unique_ptr && target); + void addTarget(std::unique_ptr && target); void clearTargets(); /// Returns true if a debug/trace log message will be logged, false if not. @@ -121,7 +121,7 @@ private: CLoggerDomain domain; CLogger * parent; ELogLevel::ELogLevel level; - std::vector > targets; + std::vector > targets; mutable boost::mutex mx; static boost::recursive_mutex smx; }; @@ -149,7 +149,7 @@ private: /// the first statement in the function. Logging traces via this macro have almost no impact when the trace is disabled. /// #define RAII_TRACE(logger, onEntry, onLeave) \ - unique_ptr ctl00; \ + std::unique_ptr ctl00; \ if(logger->isTraceEnabled()) \ ctl00 = make_unique(logger, onEntry, onLeave); diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index 1da1b784d..814e64af3 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -874,12 +874,12 @@ std::vector CGTeleport::getPassableExits(CGameState * gs, cons return exits; } -void CGTeleport::addToChannel(std::map > &channelsList, const CGTeleport * obj) +void CGTeleport::addToChannel(std::map > &channelsList, const CGTeleport * obj) { - shared_ptr tc; + std::shared_ptr tc; if(channelsList.find(obj->channel) == channelsList.end()) { - tc = make_shared(); + tc = std::make_shared(); channelsList.insert(std::make_pair(obj->channel, tc)); } else diff --git a/lib/mapObjects/MiscObjects.h b/lib/mapObjects/MiscObjects.h index 6abf94bc7..4d84766f9 100644 --- a/lib/mapObjects/MiscObjects.h +++ b/lib/mapObjects/MiscObjects.h @@ -291,7 +291,7 @@ public: static bool isTeleport(const CGObjectInstance * dst); static bool isConnected(const CGTeleport * src, const CGTeleport * dst); static bool isConnected(const CGObjectInstance * src, const CGObjectInstance * dst); - static void addToChannel(std::map > &channelsList, const CGTeleport * obj); + static void addToChannel(std::map > &channelsList, const CGTeleport * obj); static std::vector getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector exits); static bool isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj); diff --git a/lib/mapping/CCampaignHandler.cpp b/lib/mapping/CCampaignHandler.cpp index 93f40e524..dbeb96df0 100644 --- a/lib/mapping/CCampaignHandler.cpp +++ b/lib/mapping/CCampaignHandler.cpp @@ -40,7 +40,7 @@ CCampaignHeader CCampaignHandler::getHeader( const std::string & name) return ret; } -unique_ptr CCampaignHandler::getCampaign( const std::string & name ) +std::unique_ptr CCampaignHandler::getCampaign( const std::string & name ) { auto ret = make_unique(); @@ -411,7 +411,7 @@ CCampaignState::CCampaignState() } -CCampaignState::CCampaignState( unique_ptr _camp ) : camp(std::move(_camp)) +CCampaignState::CCampaignState( std::unique_ptr _camp ) : camp(std::move(_camp)) { for(int i = 0; i < camp->scenarios.size(); i++) { diff --git a/lib/mapping/CCampaignHandler.h b/lib/mapping/CCampaignHandler.h index 23f894d77..78a4b1917 100644 --- a/lib/mapping/CCampaignHandler.h +++ b/lib/mapping/CCampaignHandler.h @@ -144,7 +144,7 @@ public: class DLL_LINKAGE CCampaignState { public: - unique_ptr camp; + std::unique_ptr camp; std::string campaignName; std::vector mapsConquered, mapsRemaining; boost::optional currentMap; @@ -159,7 +159,7 @@ public: ui8 currentBonusID() const; CCampaignState(); - CCampaignState(unique_ptr _camp); + CCampaignState(std::unique_ptr _camp); ~CCampaignState(){}; template void serialize(Handler &h, const int version) @@ -184,5 +184,5 @@ public: static CCampaignHeader getHeader( const std::string & name); //name - name of appropriate file - static unique_ptr getCampaign(const std::string & name); //name - name of appropriate file + static std::unique_ptr getCampaign(const std::string & name); //name - name of appropriate file }; diff --git a/lib/mapping/CMap.h b/lib/mapping/CMap.h index 8fea38cf3..b45b05e21 100644 --- a/lib/mapping/CMap.h +++ b/lib/mapping/CMap.h @@ -317,12 +317,12 @@ public: //Helper lists std::vector< ConstTransitivePtr > heroesOnMap; - std::map > teleportChannels; + std::map > teleportChannels; /// associative list to identify which hero/creature id belongs to which object id(index for objects) std::map questIdentifierToId; - unique_ptr editManager; + std::unique_ptr editManager; int3 ***guardingCreaturePositions; diff --git a/lib/mapping/CMapEditManager.cpp b/lib/mapping/CMapEditManager.cpp index 8f5648c83..ec629b883 100644 --- a/lib/mapping/CMapEditManager.cpp +++ b/lib/mapping/CMapEditManager.cpp @@ -189,7 +189,7 @@ const CMapOperation * CMapUndoManager::peekUndo() const return peek(undoStack); } -void CMapUndoManager::addOperation(unique_ptr && operation) +void CMapUndoManager::addOperation(std::unique_ptr && operation) { undoStack.push_front(std::move(operation)); if(undoStack.size() > undoRedoLimit) undoStack.pop_back(); @@ -252,7 +252,7 @@ void CMapEditManager::insertObject(CGObjectInstance * obj, const int3 & pos) execute(make_unique(map, obj, pos)); } -void CMapEditManager::execute(unique_ptr && operation) +void CMapEditManager::execute(std::unique_ptr && operation) { operation->execute(); undoManager.addOperation(std::move(operation)); @@ -302,7 +302,7 @@ void CComposedOperation::redo() } } -void CComposedOperation::addOperation(unique_ptr && operation) +void CComposedOperation::addOperation(std::unique_ptr && operation) { operations.push_back(std::move(operation)); } diff --git a/lib/mapping/CMapEditManager.h b/lib/mapping/CMapEditManager.h index 97e5ecd8f..b24cb9262 100644 --- a/lib/mapping/CMapEditManager.h +++ b/lib/mapping/CMapEditManager.h @@ -144,10 +144,10 @@ public: const CMapOperation * peekRedo() const; const CMapOperation * peekUndo() const; - void addOperation(unique_ptr && operation); /// Client code does not need to call this method. + void addOperation(std::unique_ptr && operation); /// Client code does not need to call this method. private: - typedef std::list > TStack; + typedef std::list > TStack; void doOperation(TStack & fromStack, TStack & toStack, bool doUndo); const CMapOperation * peek(const TStack & stack) const; @@ -182,7 +182,7 @@ public: CMapUndoManager & getUndoManager(); private: - void execute(unique_ptr && operation); + void execute(std::unique_ptr && operation); CMap * map; CMapUndoManager undoManager; @@ -205,10 +205,10 @@ public: void undo() override; void redo() override; - void addOperation(unique_ptr && operation); + void addOperation(std::unique_ptr && operation); private: - std::list > operations; + std::list > operations; }; namespace ETerrainGroup diff --git a/lib/mapping/CMapInfo.h b/lib/mapping/CMapInfo.h index 3befecd4b..2e204e84b 100644 --- a/lib/mapping/CMapInfo.h +++ b/lib/mapping/CMapInfo.h @@ -1,8 +1,8 @@ #pragma once // Forward class declarations aren't enough here. The compiler -// generated CMapInfo d-tor, generates the unique_ptr d-tor as well here -// as a inline method. The unique_ptr d-tor requires a complete type. Defining +// generated CMapInfo d-tor, generates the std::unique_ptr d-tor as well here +// as a inline method. The std::unique_ptr d-tor requires a complete type. Defining // the CMapInfo d-tor to let the compiler add the d-tor stuff in the .cpp file // would work with one exception. It prevents the generation of the move // constructor which is needed. (Writing such a c-tor is nasty.) With the @@ -20,8 +20,8 @@ struct StartInfo; class DLL_LINKAGE CMapInfo { public: - unique_ptr mapHeader; //may be nullptr if campaign - unique_ptr campaignHeader; //may be nullptr if scenario + std::unique_ptr mapHeader; //may be nullptr if campaign + std::unique_ptr campaignHeader; //may be nullptr if scenario StartInfo * scenarioOpts; //options with which scenario has been started (used only with saved games) std::string fileURI; std::string date; diff --git a/lib/rmg/CMapGenerator.h b/lib/rmg/CMapGenerator.h index bdf340afe..1ea3e87ed 100644 --- a/lib/rmg/CMapGenerator.h +++ b/lib/rmg/CMapGenerator.h @@ -52,7 +52,7 @@ class DLL_LINKAGE CMapGenerator { public: explicit CMapGenerator(); - ~CMapGenerator(); // required due to unique_ptr + ~CMapGenerator(); // required due to std::unique_ptr std::unique_ptr generate(CMapGenOptions * mapGenOptions, int RandomSeed = std::time(nullptr)); diff --git a/lib/rmg/CZoneGraphGenerator.cpp b/lib/rmg/CZoneGraphGenerator.cpp index 48aa6a989..ce83c7e19 100644 --- a/lib/rmg/CZoneGraphGenerator.cpp +++ b/lib/rmg/CZoneGraphGenerator.cpp @@ -28,7 +28,7 @@ CZoneGraphGenerator::CZoneGraphGenerator()// : gen(nullptr) } -unique_ptr CZoneGraphGenerator::generate(const CMapGenOptions & options, CRandomGenerator * gen) +std::unique_ptr CZoneGraphGenerator::generate(const CMapGenOptions & options, CRandomGenerator * gen) { return make_unique(); } diff --git a/lib/rmg/CZoneGraphGenerator.h b/lib/rmg/CZoneGraphGenerator.h index f3669feed..02e111f61 100644 --- a/lib/rmg/CZoneGraphGenerator.h +++ b/lib/rmg/CZoneGraphGenerator.h @@ -40,9 +40,9 @@ class CZoneGraphGenerator public: CZoneGraphGenerator(); - unique_ptr generate(const CMapGenOptions & options, CRandomGenerator * gen); + std::unique_ptr generate(const CMapGenOptions & options, CRandomGenerator * gen); private: - unique_ptr graph; + std::unique_ptr graph; //CRandomGenerator * gen; }; diff --git a/lib/rmg/CZonePlacer.h b/lib/rmg/CZonePlacer.h index 2bd35d407..2dfc5ca83 100644 --- a/lib/rmg/CZonePlacer.h +++ b/lib/rmg/CZonePlacer.h @@ -50,6 +50,6 @@ private: float scaleY; //float a1, b1, c1, a2, b2, c2; //CMap * map; - //unique_ptr graph; + //std::unique_ptr graph; CMapGenerator * gen; }; diff --git a/lib/spells/BattleSpellMechanics.cpp b/lib/spells/BattleSpellMechanics.cpp index 14b946c56..ac6007b7f 100644 --- a/lib/spells/BattleSpellMechanics.cpp +++ b/lib/spells/BattleSpellMechanics.cpp @@ -374,7 +374,7 @@ void ObstacleMechanics::applyBattleEffects(const SpellCastEnvironment * env, con ? (parameters.cb->obstacles.back()->uniqueID+1) : 0; - auto obstacle = make_shared(); + auto obstacle = std::make_shared(); switch(owner->id) // :/ { case SpellID::QUICKSAND: diff --git a/scripting/erm/ERMScriptModule.cpp b/scripting/erm/ERMScriptModule.cpp index 4a4f3323f..587945b52 100644 --- a/scripting/erm/ERMScriptModule.cpp +++ b/scripting/erm/ERMScriptModule.cpp @@ -28,7 +28,7 @@ extern "C" DLL_EXPORT void GetAiName(char* name) strcpy_s(name, strlen(g_cszAiName) + 1, g_cszAiName); } -extern "C" DLL_EXPORT void GetNewModule(shared_ptr &out) +extern "C" DLL_EXPORT void GetNewModule(std::shared_ptr &out) { - out = make_shared(); + out = std::make_shared(); } \ No newline at end of file diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 3c1ba73db..1be4bd9e1 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -225,7 +225,7 @@ void CGameHandler::levelUpHero(const CGHeroInstance * hero) } else if(hlu.skills.size() > 1) { - auto levelUpQuery = make_shared(hlu); + auto levelUpQuery = std::make_shared(hlu); hlu.queryID = levelUpQuery->queryID; queries.addQuery(levelUpQuery); sendAndApply(&hlu); @@ -363,7 +363,7 @@ void CGameHandler::levelUpCommander(const CCommanderInstance * c) } else if(skillAmount > 1) //apply and ask for secondary skill { - auto commanderLevelUp = make_shared(clu); + auto commanderLevelUp = std::make_shared(clu); clu.queryID = commanderLevelUp->queryID; queries.addQuery(commanderLevelUp); sendAndApply(&clu); @@ -471,7 +471,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer const CArmedInstance *bEndArmy2 = gs->curB->sides.at(1).armyObject; const BattleResult::EResult result = battleResult.get()->result; - auto findBattleQuery = [this] () -> shared_ptr + auto findBattleQuery = [this] () -> std::shared_ptr { for(auto &q : queries.allQueries()) { @@ -479,7 +479,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer if(bq->bi == gs->curB) return bq; } - return shared_ptr(); + return std::shared_ptr(); }; auto battleQuery = findBattleQuery(); @@ -488,7 +488,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHer logGlobal->errorStream() << "Cannot find battle query!"; if(gs->initialOpts->mode == StartInfo::DUEL) { - battleQuery = make_shared(gs->curB); + battleQuery = std::make_shared(gs->curB); } } if(battleQuery != queries.topQuery(gs->curB->sides[0].color)) @@ -1020,7 +1020,7 @@ int CGameHandler::moveStack(int stack, BattleHex dest) } else //for non-flying creatures { - shared_ptr obstacle, obstacle2; //obstacle that interrupted movement + std::shared_ptr obstacle, obstacle2; //obstacle that interrupted movement std::vector tiles; const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0); int v = path.first.size()-1; @@ -1069,7 +1069,7 @@ int CGameHandler::moveStack(int stack, BattleHex dest) //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end if(curStack->position != dest) { - auto processObstacle = [&](shared_ptr & obs) + auto processObstacle = [&](std::shared_ptr & obs) { if(obs) { @@ -1825,7 +1825,7 @@ bool CGameHandler::moveHero( ObjectInstanceID hid, int3 dst, ui8 teleporting, bo { LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->name % tmh.start % tmh.end); - auto moveQuery = make_shared(tmh, h); + auto moveQuery = std::make_shared(tmh, h); queries.addQuery(moveQuery); if(leavingTile == LEAVING_TILE) @@ -2000,7 +2000,7 @@ void CGameHandler::setOwner(const CGObjectInstance * obj, PlayerColor owner) void CGameHandler::showBlockingDialog( BlockingDialog *iw ) { - auto dialogQuery = make_shared(*iw); + auto dialogQuery = std::make_shared(*iw); queries.addQuery(dialogQuery); iw->queryID = dialogQuery->queryID; sendToAllClients(iw); @@ -2008,7 +2008,7 @@ void CGameHandler::showBlockingDialog( BlockingDialog *iw ) void CGameHandler::showTeleportDialog( TeleportDialog *iw ) { - auto dialogQuery = make_shared(*iw); + auto dialogQuery = std::make_shared(*iw); queries.addQuery(dialogQuery); iw->queryID = dialogQuery->queryID; sendToAllClients(iw); @@ -2135,7 +2135,7 @@ void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedI setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces - auto battleQuery = make_shared(gs->curB); + auto battleQuery = std::make_shared(gs->curB); queries.addQuery(battleQuery); boost::thread(&CGameHandler::runBattle, this); @@ -2302,7 +2302,7 @@ void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) if( gameState()->getPlayerRelations(h1->getOwner(), h2->getOwner())) { - auto exchange = make_shared(h1, h2); + auto exchange = std::make_shared(h1, h2); ExchangeDialog hex; hex.queryID = exchange->queryID; hex.heroes[0] = getHero(hero1); @@ -4563,7 +4563,7 @@ void CGameHandler::showGarrisonDialog( ObjectInstanceID upobj, ObjectInstanceID assert(lowerArmy); assert(upperArmy); - auto garrisonQuery = make_shared(upperArmy, lowerArmy); + auto garrisonQuery = std::make_shared(upperArmy, lowerArmy); queries.addQuery(garrisonQuery); GarrisonDialog gd; @@ -4634,7 +4634,7 @@ bool CGameHandler::isAllowedExchange( ObjectInstanceID id1, ObjectInstanceID id2 void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h ) { logGlobal->debugStream() << h->nodeName() << " visits " << obj->getObjectName() << "(" << obj->ID << ":" << obj->subID << ")"; - auto visitQuery = make_shared(obj, h, obj->visitablePos()); + auto visitQuery = std::make_shared(obj, h, obj->visitablePos()); queries.addQuery(visitQuery); //TODO real visit pos HeroVisit hv; @@ -5899,7 +5899,7 @@ void CasualtiesAfterBattle::takeFromArmy(CGameHandler *gh) } } -CGameHandler::FinishingBattleHelper::FinishingBattleHelper(shared_ptr Query, bool Duel, int RemainingBattleQueriesCount) +CGameHandler::FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr Query, bool Duel, int RemainingBattleQueriesCount) { assert(Query->result); assert(Query->bi); diff --git a/server/CGameHandler.h b/server/CGameHandler.h index 4370e6aec..104979140 100644 --- a/server/CGameHandler.h +++ b/server/CGameHandler.h @@ -258,9 +258,9 @@ public: struct FinishingBattleHelper { FinishingBattleHelper(); - FinishingBattleHelper(shared_ptr Query, bool Duel, int RemainingBattleQueriesCount); + FinishingBattleHelper(std::shared_ptr Query, bool Duel, int RemainingBattleQueriesCount); - //shared_ptr query; + //std::shared_ptr query; const CGHeroInstance *winnerHero, *loserHero; PlayerColor victor, loser; bool duel; @@ -273,7 +273,7 @@ public: } }; - unique_ptr finishingBattle; + std::unique_ptr finishingBattle; void battleAfterLevelUp(const BattleResult &result); diff --git a/server/CQuery.cpp b/server/CQuery.cpp index aad12a423..834db4e38 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -200,9 +200,9 @@ void Queries::popIfTop(const CQuery &query) popQuery(color, topQuery(color)); } -std::vector> Queries::allQueries() const +std::vector> Queries::allQueries() const { - std::vector> ret; + std::vector> ret; for(auto &playerQueries : queries) for(auto &query : playerQueries.second) ret.push_back(query); @@ -210,10 +210,10 @@ std::vector> Queries::allQueries() const return ret; } -std::vector> Queries::allQueries() +std::vector> Queries::allQueries() { //TODO code duplication with const function :( - std::vector> ret; + std::vector> ret; for(auto &playerQueries : queries) for(auto &query : playerQueries.second) ret.push_back(query); diff --git a/server/CQuery.h b/server/CQuery.h index 23e6bffe6..5ba354591 100644 --- a/server/CQuery.h +++ b/server/CQuery.h @@ -10,7 +10,7 @@ class CGameHandler; class CObjectVisitQuery; class CQuery; -typedef shared_ptr QueryPtr; +typedef std::shared_ptr QueryPtr; // This class represents any kind of prolonged interaction that may need to do something special after it is over. // It does not necessarily has to be "query" requiring player action, it can be also used internally within server. @@ -183,8 +183,8 @@ public: QueryPtr topQuery(PlayerColor player); - std::vector> allQueries() const; - std::vector> allQueries(); + std::vector> allQueries() const; + std::vector> allQueries(); //void removeQuery };