diff --git a/AI/BattleAI/BattleAI.cpp b/AI/BattleAI/BattleAI.cpp index 5584304df..3db147573 100644 --- a/AI/BattleAI/BattleAI.cpp +++ b/AI/BattleAI/BattleAI.cpp @@ -134,7 +134,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) //evaluate casting spell for spellcasting stack - boost::optional bestSpellcast(boost::none); + std::optional bestSpellcast(std::nullopt); //TODO: faerie dragon type spell should be selected by server SpellID creatureSpellToCast = cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), stack, CBattleInfoCallback::RANDOM_AIMED); if(stack->hasBonusOfType(Bonus::SPELLCASTER) && stack->canCast() && creatureSpellToCast != SpellID::NONE) @@ -157,7 +157,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) std::sort(possibleCasts.begin(), possibleCasts.end(), [&](const PossibleSpellcast & lhs, const PossibleSpellcast & rhs) { return lhs.value > rhs.value; }); if(!possibleCasts.empty() && possibleCasts.front().value > 0) { - bestSpellcast = boost::optional(possibleCasts.front()); + bestSpellcast = std::optional(possibleCasts.front()); } } } @@ -180,7 +180,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) auto & bestAttack = evaluationResult.bestAttack; //TODO: consider more complex spellcast evaluation, f.e. because "re-retaliation" during enemy move in same turn for melee attack etc. - if(bestSpellcast.is_initialized() && bestSpellcast->value > bestAttack.damageDiff()) + if(bestSpellcast.has_value() && bestSpellcast->value > bestAttack.damageDiff()) { // return because spellcast value is damage dealt and score is dps reduce movesSkippedByDefense = 0; @@ -219,7 +219,7 @@ BattleAction CBattleAI::activeStack( const CStack * stack ) ); } } - else if(bestSpellcast.is_initialized()) + else if(bestSpellcast.has_value()) { movesSkippedByDefense = 0; return BattleAction::makeCreatureSpellcast(stack, bestSpellcast->dest, bestSpellcast->spell->id); @@ -801,7 +801,7 @@ void CBattleAI::print(const std::string &text) const logAi->trace("%s Battle AI[%p]: %s", playerID.getStr(), this, text); } -boost::optional CBattleAI::considerFleeingOrSurrendering() +std::optional CBattleAI::considerFleeingOrSurrendering() { BattleStateInfoForRetreat bs; @@ -829,7 +829,7 @@ boost::optional CBattleAI::considerFleeingOrSurrendering() if(!bs.canFlee || !bs.canSurrender) { - return boost::none; + return std::nullopt; } auto result = cb->makeSurrenderRetreatDecision(bs); diff --git a/AI/BattleAI/BattleAI.h b/AI/BattleAI/BattleAI.h index a816bfde4..f9a877206 100644 --- a/AI/BattleAI/BattleAI.h +++ b/AI/BattleAI/BattleAI.h @@ -73,7 +73,7 @@ public: BattleAction activeStack(const CStack * stack) override; //called when it's turn of that stack - boost::optional considerFleeingOrSurrendering(); + std::optional considerFleeingOrSurrendering(); void print(const std::string &text) const; BattleAction useCatapult(const CStack *stack); diff --git a/AI/Nullkiller/AIGateway.cpp b/AI/Nullkiller/AIGateway.cpp index 54a74857d..598be14ad 100644 --- a/AI/Nullkiller/AIGateway.cpp +++ b/AI/Nullkiller/AIGateway.cpp @@ -501,8 +501,7 @@ void AIGateway::showWorldViewEx(const std::vector & objectPositio NET_EVENT_HANDLER; } -boost::optional AIGateway::makeSurrenderRetreatDecision( - const BattleStateInfoForRetreat & battleState) +std::optional AIGateway::makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) { LOG_TRACE(logAi); NET_EVENT_HANDLER; @@ -516,7 +515,7 @@ boost::optional AIGateway::makeSurrenderRetreatDecision( return BattleAction::makeRetreat(battleState.ourSide); } - return boost::none; + return std::nullopt; } diff --git a/AI/Nullkiller/AIGateway.h b/AI/Nullkiller/AIGateway.h index 584d25873..a3115e3e6 100644 --- a/AI/Nullkiller/AIGateway.h +++ b/AI/Nullkiller/AIGateway.h @@ -166,7 +166,7 @@ public: void heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain) override; void showMarketWindow(const IMarket * market, const CGHeroInstance * visitor) override; void showWorldViewEx(const std::vector & objectPositions, bool showTerrain) override; - boost::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; + std::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; void battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side) override; void battleEnd(const BattleResult * br, QueryID queryID) override; diff --git a/AI/Nullkiller/Goals/Build.cpp b/AI/Nullkiller/Goals/Build.cpp index e59c877eb..f5180e491 100644 --- a/AI/Nullkiller/Goals/Build.cpp +++ b/AI/Nullkiller/Goals/Build.cpp @@ -42,10 +42,10 @@ TGoalVec Build::getAllPossibleSubgoals() auto expensiveBuilding = ai->ah->expensiveBuilding(); //handling for early town development to save money and focus on income - if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.is_initialized()) + if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.has_value()) { - auto potentialBuilding = expensiveBuilding.get(); - switch(expensiveBuilding.get().bid) + auto potentialBuilding = expensiveBuilding.value(); + switch(expensiveBuilding.value().bid) { case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: @@ -61,15 +61,15 @@ TGoalVec Build::getAllPossibleSubgoals() } } - if(immediateBuilding.is_initialized()) + if(immediateBuilding.has_value()) { - ret.push_back(sptr(BuildThis(immediateBuilding.get().bid, t).setpriority(2))); //prioritize buildings we can build quick + ret.push_back(sptr(BuildThis(immediateBuilding.value().bid, t).setpriority(2))); //prioritize buildings we can build quick } else //try build later { - if(expensiveBuilding.is_initialized()) + if(expensiveBuilding.has_value()) { - auto potentialBuilding = expensiveBuilding.get(); //gather resources for any we can't afford + auto potentialBuilding = expensiveBuilding.value(); //gather resources for any we can't afford auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5))); ret.push_back(goal); } diff --git a/AI/Nullkiller/Goals/GatherArmy.cpp b/AI/Nullkiller/Goals/GatherArmy.cpp index b4ac7ae77..4551e322f 100644 --- a/AI/Nullkiller/Goals/GatherArmy.cpp +++ b/AI/Nullkiller/Goals/GatherArmy.cpp @@ -97,7 +97,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals() //Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm /*auto bid = ai->ah->canBuildAnyStructure(t, std::vector(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 1); - if (bid.is_initialized()) + if (bid.has_value()) { auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority)); if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice diff --git a/AI/Nullkiller/Pathfinding/AINodeStorage.cpp b/AI/Nullkiller/Pathfinding/AINodeStorage.cpp index 8fd97a975..7467845d8 100644 --- a/AI/Nullkiller/Pathfinding/AINodeStorage.cpp +++ b/AI/Nullkiller/Pathfinding/AINodeStorage.cpp @@ -120,7 +120,7 @@ void AINodeStorage::clear() turnDistanceLimit[HeroRole::SCOUT] = 255; } -boost::optional AINodeStorage::getOrCreateNode( +std::optional AINodeStorage::getOrCreateNode( const int3 & pos, const EPathfindingLayer layer, const ChainActor * actor) @@ -131,7 +131,7 @@ boost::optional AINodeStorage::getOrCreateNode( if(chains[0].blocked()) { - return boost::none; + return std::nullopt; } for(auto i = AIPathfinding::BUCKET_SIZE - 1; i >= 0; i--) @@ -151,7 +151,7 @@ boost::optional AINodeStorage::getOrCreateNode( } } - return boost::none; + return std::nullopt; } std::vector AINodeStorage::getInitialNodes() @@ -175,7 +175,7 @@ std::vector AINodeStorage::getInitialNodes() if(!allocated) continue; - AIPathNode * initialNode = allocated.get(); + AIPathNode * initialNode = allocated.value(); initialNode->inPQ = false; initialNode->pq = nullptr; @@ -289,10 +289,10 @@ std::vector AINodeStorage::calculateNeighbours( { auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor); - if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET) + if(!nextNode || nextNode.value()->accessible == CGPathNode::NOT_SET) continue; - neighbours.push_back(nextNode.get()); + neighbours.push_back(nextNode.value()); } } @@ -722,7 +722,7 @@ void HeroChainCalculationTask::addHeroChain(const std::vector continue; } - auto exchangeNode = chainNodeOptional.get(); + auto exchangeNode = chainNodeOptional.value(); if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN) { @@ -946,7 +946,7 @@ std::vector AINodeStorage::calculateTeleportations( if(!node) continue; - neighbours.push_back(node.get()); + neighbours.push_back(node.value()); } } @@ -1017,19 +1017,19 @@ struct TowmPortalFinder return nullptr; } - boost::optional createTownPortalNode(const CGTownInstance * targetTown) + std::optional createTownPortalNode(const CGTownInstance * targetTown) { auto bestNode = getBestInitialNodeForTownPortal(targetTown); if(!bestNode) - return boost::none; + return std::nullopt; auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor); if(!nodeOptional) - return boost::none; + return std::nullopt; - AIPathNode * node = nodeOptional.get(); + AIPathNode * node = nodeOptional.value(); float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND); movementCost += bestNode->getCost(); @@ -1095,7 +1095,7 @@ void AINodeStorage::calculateTownPortal( #if NKAI_PATHFINDER_TRACE_LEVEL >= 1 logAi->trace("Adding town portal node at %s", targetTown->name); #endif - output.push_back(nodeOptional.get()); + output.push_back(nodeOptional.value()); } } } diff --git a/AI/Nullkiller/Pathfinding/AINodeStorage.h b/AI/Nullkiller/Pathfinding/AINodeStorage.h index c1420afa5..2f77422d8 100644 --- a/AI/Nullkiller/Pathfinding/AINodeStorage.h +++ b/AI/Nullkiller/Pathfinding/AINodeStorage.h @@ -232,7 +232,7 @@ public: const AIPathNode * destinationNode, const NodeRange & chains) const; - boost::optional getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor); + std::optional getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, const ChainActor * actor); std::vector getChainInfo(const int3 & pos, bool isOnLand) const; bool isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const; void setHeroes(std::map heroes); diff --git a/AI/Nullkiller/Pathfinding/Rules/AILayerTransitionRule.cpp b/AI/Nullkiller/Pathfinding/Rules/AILayerTransitionRule.cpp index bce2a4284..4871501aa 100644 --- a/AI/Nullkiller/Pathfinding/Rules/AILayerTransitionRule.cpp +++ b/AI/Nullkiller/Pathfinding/Rules/AILayerTransitionRule.cpp @@ -131,7 +131,7 @@ namespace AIPathfinding if(boatNodeOptional) { - AIPathNode * boatNode = boatNodeOptional.get(); + AIPathNode * boatNode = boatNodeOptional.value(); if(boatNode->action == CGPathNode::UNKNOWN) { diff --git a/AI/Nullkiller/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp b/AI/Nullkiller/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp index 45fd896bd..032ecd946 100644 --- a/AI/Nullkiller/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp +++ b/AI/Nullkiller/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp @@ -139,17 +139,17 @@ namespace AIPathfinding { if(!destinationNode->actor->allowUseResources) { - boost::optional questNode = nodeStorage->getOrCreateNode( + std::optional questNode = nodeStorage->getOrCreateNode( destination.coord, destination.node->layer, destinationNode->actor->resourceActor); - if(!questNode || questNode.get()->getCost() < destination.cost) + if(!questNode || questNode.value()->getCost() < destination.cost) { return false; } - destination.node = questNode.get(); + destination.node = questNode.value(); nodeStorage->commit(destination, source); AIPreviousNodeRule(nodeStorage).process(source, destination, pathfinderConfig, pathfinderHelper); @@ -259,7 +259,7 @@ namespace AIPathfinding return false; } - AIPathNode * battleNode = battleNodeOptional.get(); + auto * battleNode = battleNodeOptional.value(); if(battleNode->locked) { diff --git a/AI/VCAI/AIhelper.cpp b/AI/VCAI/AIhelper.cpp index 75fca29b2..60c769445 100644 --- a/AI/VCAI/AIhelper.cpp +++ b/AI/VCAI/AIhelper.cpp @@ -50,17 +50,17 @@ BuildingID AIhelper::getMaxPossibleGoldBuilding(const CGTownInstance * t) return buildingManager->getMaxPossibleGoldBuilding(t); } -boost::optional AIhelper::immediateBuilding() const +std::optional AIhelper::immediateBuilding() const { return buildingManager->immediateBuilding(); } -boost::optional AIhelper::expensiveBuilding() const +std::optional AIhelper::expensiveBuilding() const { return buildingManager->expensiveBuilding(); } -boost::optional AIhelper::canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const +std::optional AIhelper::canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const { return buildingManager->canBuildAnyStructure(t, buildList, maxDays); } diff --git a/AI/VCAI/AIhelper.h b/AI/VCAI/AIhelper.h index 1a33025f0..87bac3e29 100644 --- a/AI/VCAI/AIhelper.h +++ b/AI/VCAI/AIhelper.h @@ -52,9 +52,9 @@ public: bool getBuildingOptions(const CGTownInstance * t) override; BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t); - boost::optional immediateBuilding() const override; - boost::optional expensiveBuilding() const override; - boost::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays = 7) const override; + std::optional immediateBuilding() const override; + std::optional expensiveBuilding() const override; + std::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays = 7) const override; Goals::TGoalVec howToVisitTile(const HeroPtr & hero, const int3 & tile, bool allowGatherArmy = true) const override; Goals::TGoalVec howToVisitObj(const HeroPtr & hero, ObjectIdRef obj, bool allowGatherArmy = true) const override; diff --git a/AI/VCAI/BuildingManager.cpp b/AI/VCAI/BuildingManager.cpp index a63f0b2ca..083abe9c4 100644 --- a/AI/VCAI/BuildingManager.cpp +++ b/AI/VCAI/BuildingManager.cpp @@ -99,7 +99,7 @@ bool BuildingManager::tryBuildAnyStructure(const CGTownInstance * t, std::vector return false; //Can't build anything } -boost::optional BuildingManager::canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const +std::optional BuildingManager::canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const { for (const auto & building : buildList) { @@ -109,11 +109,11 @@ boost::optional BuildingManager::canBuildAnyStructure(const CGTownIn { case EBuildingState::ALLOWED: case EBuildingState::NO_RESOURCES: //TODO: allow this via optional parameter? - return boost::optional(building); + return std::optional(building); break; } } - return boost::optional(); //Can't build anything + return std::optional(); //Can't build anything } bool BuildingManager::tryBuildNextStructure(const CGTownInstance * t, std::vector buildList, unsigned int maxDays) @@ -240,18 +240,18 @@ BuildingID BuildingManager::getMaxPossibleGoldBuilding(const CGTownInstance * t) return BuildingID::VILLAGE_HALL; } -boost::optional BuildingManager::immediateBuilding() const +std::optional BuildingManager::immediateBuilding() const { if (immediateBuildings.size()) - return boost::optional(immediateBuildings.front()); //back? whatever + return std::optional(immediateBuildings.front()); //back? whatever else - return boost::optional(); + return std::optional(); } -boost::optional BuildingManager::expensiveBuilding() const +std::optional BuildingManager::expensiveBuilding() const { if (expensiveBuildings.size()) - return boost::optional(expensiveBuildings.front()); + return std::optional(expensiveBuildings.front()); else - return boost::optional(); + return std::optional(); } diff --git a/AI/VCAI/BuildingManager.h b/AI/VCAI/BuildingManager.h index 03a30db6b..3eb88605e 100644 --- a/AI/VCAI/BuildingManager.h +++ b/AI/VCAI/BuildingManager.h @@ -33,9 +33,9 @@ public: virtual void setAI(VCAI * AI) = 0; virtual bool getBuildingOptions(const CGTownInstance * t) = 0; - virtual boost::optional immediateBuilding() const = 0; - virtual boost::optional expensiveBuilding() const = 0; - virtual boost::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const = 0; + virtual std::optional immediateBuilding() const = 0; + virtual std::optional expensiveBuilding() const = 0; + virtual std::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays) const = 0; }; class DLL_EXPORT BuildingManager : public IBuildingManager @@ -52,9 +52,9 @@ public: //try build anything in given town, and execute resulting Goal if any bool getBuildingOptions(const CGTownInstance * t) override; BuildingID getMaxPossibleGoldBuilding(const CGTownInstance * t); - boost::optional immediateBuilding() const override; - boost::optional expensiveBuilding() const override; - boost::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays = 7) const override; + std::optional immediateBuilding() const override; + std::optional expensiveBuilding() const override; + std::optional canBuildAnyStructure(const CGTownInstance * t, const std::vector & buildList, unsigned int maxDays = 7) const override; protected: diff --git a/AI/VCAI/FuzzyEngines.cpp b/AI/VCAI/FuzzyEngines.cpp index a0251e3db..631727977 100644 --- a/AI/VCAI/FuzzyEngines.cpp +++ b/AI/VCAI/FuzzyEngines.cpp @@ -399,12 +399,12 @@ float VisitObjEngine::evaluate(Goals::VisitObj & goal) return -100; // FIXME: Added check when goal was used for hero instead of VisitHero, but crashes are bad anyway } - boost::optional objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj); + std::optional objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj); int objValue = 0; - if(objValueKnownByAI != boost::none) //consider adding value manipulation based on object instances on map + if(objValueKnownByAI != std::nullopt) //consider adding value manipulation based on object instances on map { - objValue = std::min(std::max(objValueKnownByAI.get(), 0), 20000); + objValue = std::min(std::max(objValueKnownByAI.value(), 0), 20000); } else { diff --git a/AI/VCAI/Goals/Build.cpp b/AI/VCAI/Goals/Build.cpp index 140f7e99f..66eb13f40 100644 --- a/AI/VCAI/Goals/Build.cpp +++ b/AI/VCAI/Goals/Build.cpp @@ -39,10 +39,10 @@ TGoalVec Build::getAllPossibleSubgoals() auto expensiveBuilding = ai->ah->expensiveBuilding(); //handling for early town development to save money and focus on income - if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.is_initialized()) + if(!t->hasBuilt(ai->ah->getMaxPossibleGoldBuilding(t)) && expensiveBuilding.has_value()) { - auto potentialBuilding = expensiveBuilding.get(); - switch(expensiveBuilding.get().bid) + auto potentialBuilding = expensiveBuilding.value(); + switch(expensiveBuilding.value().bid) { case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: @@ -58,15 +58,15 @@ TGoalVec Build::getAllPossibleSubgoals() } } - if(immediateBuilding.is_initialized()) + if(immediateBuilding.has_value()) { - ret.push_back(sptr(BuildThis(immediateBuilding.get().bid, t).setpriority(2))); //prioritize buildings we can build quick + ret.push_back(sptr(BuildThis(immediateBuilding.value().bid, t).setpriority(2))); //prioritize buildings we can build quick } else //try build later { - if(expensiveBuilding.is_initialized()) + if(expensiveBuilding.has_value()) { - auto potentialBuilding = expensiveBuilding.get(); //gather resources for any we can't afford + auto potentialBuilding = expensiveBuilding.value(); //gather resources for any we can't afford auto goal = ai->ah->whatToDo(potentialBuilding.price, sptr(BuildThis(potentialBuilding.bid, t).setpriority(0.5))); ret.push_back(goal); } diff --git a/AI/VCAI/Goals/GatherArmy.cpp b/AI/VCAI/Goals/GatherArmy.cpp index fce982594..34c6c78d5 100644 --- a/AI/VCAI/Goals/GatherArmy.cpp +++ b/AI/VCAI/Goals/GatherArmy.cpp @@ -94,7 +94,7 @@ TGoalVec GatherArmy::getAllPossibleSubgoals() //Do not use below code for now, rely on generic Build. Code below needs to know a lot of town/resource context to do more good than harm /*auto bid = ai->ah->canBuildAnyStructure(t, std::vector(unitsSource, unitsSource + std::size(unitsSource)), 1); - if (bid.is_initialized()) + if (bid.has_value()) { auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority)); if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice diff --git a/AI/VCAI/Goals/GatherTroops.cpp b/AI/VCAI/Goals/GatherTroops.cpp index 70447826e..d4c884c71 100644 --- a/AI/VCAI/Goals/GatherTroops.cpp +++ b/AI/VCAI/Goals/GatherTroops.cpp @@ -96,7 +96,18 @@ TGoalVec GatherTroops::getAllPossibleSubgoals() auto creature = VLC->creatures()->getByIndex(objid); if(t->subID == creature->getFaction()) //TODO: how to force AI to build unupgraded creatures? :O { - auto creatures = vstd::tryAt(t->town->creatures, creature->getLevel() - 1); + auto tryFindCreature = [&]() -> std::optional> + { + if(vstd::isValidIndex(t->town->creatures, creature->getLevel() - 1)) + { + auto itr = t->town->creatures.begin(); + std::advance(itr, creature->getLevel() - 1); + return make_optional(*itr); + } + return std::nullopt; + }; + + auto creatures = tryFindCreature(); if(!creatures) continue; diff --git a/AI/VCAI/MapObjectsEvaluator.cpp b/AI/VCAI/MapObjectsEvaluator.cpp index 83595b8b4..1fb638d39 100644 --- a/AI/VCAI/MapObjectsEvaluator.cpp +++ b/AI/VCAI/MapObjectsEvaluator.cpp @@ -28,9 +28,9 @@ MapObjectsEvaluator::MapObjectsEvaluator() auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID); if(handler && !handler->isStaticObject()) { - if(handler->getAiValue() != boost::none) + if(handler->getAiValue() != std::nullopt) { - objectDatabase[CompoundMapObjectID(primaryID, secondaryID)] = handler->getAiValue().get(); + objectDatabase[CompoundMapObjectID(primaryID, secondaryID)] = handler->getAiValue().value(); } else //some default handling when aiValue not found, objects that require advanced properties (unavailable from handler) get their value calculated in getObjectValue { @@ -41,7 +41,7 @@ MapObjectsEvaluator::MapObjectsEvaluator() } } -boost::optional MapObjectsEvaluator::getObjectValue(int primaryID, int secondaryID) const +std::optional MapObjectsEvaluator::getObjectValue(int primaryID, int secondaryID) const { CompoundMapObjectID internalIdentifier = CompoundMapObjectID(primaryID, secondaryID); auto object = objectDatabase.find(internalIdentifier); @@ -49,10 +49,10 @@ boost::optional MapObjectsEvaluator::getObjectValue(int primaryID, int seco return object->second; logGlobal->trace("Unknown object for AI, ID: " + std::to_string(primaryID) + ", SubID: " + std::to_string(secondaryID)); - return boost::optional(); + return std::optional(); } -boost::optional MapObjectsEvaluator::getObjectValue(const CGObjectInstance * obj) const +std::optional MapObjectsEvaluator::getObjectValue(const CGObjectInstance * obj) const { if(obj->ID == Obj::HERO) { diff --git a/AI/VCAI/MapObjectsEvaluator.h b/AI/VCAI/MapObjectsEvaluator.h index 35a76d304..d51873a02 100644 --- a/AI/VCAI/MapObjectsEvaluator.h +++ b/AI/VCAI/MapObjectsEvaluator.h @@ -18,8 +18,8 @@ private: public: MapObjectsEvaluator(); static MapObjectsEvaluator & getInstance(); - boost::optional getObjectValue(int primaryID, int secondaryID) const; - boost::optional getObjectValue(const CGObjectInstance * obj) const; + std::optional getObjectValue(int primaryID, int secondaryID) const; + std::optional getObjectValue(const CGObjectInstance * obj) const; void addObjectData(int primaryID, int secondaryID, int value); void removeObjectData(int primaryID, int secondaryID); }; diff --git a/AI/VCAI/Pathfinding/AINodeStorage.cpp b/AI/VCAI/Pathfinding/AINodeStorage.cpp index 719e93903..99ba9dfd9 100644 --- a/AI/VCAI/Pathfinding/AINodeStorage.cpp +++ b/AI/VCAI/Pathfinding/AINodeStorage.cpp @@ -83,7 +83,7 @@ bool AINodeStorage::isBattleNode(const CGPathNode * node) const return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0; } -boost::optional AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber) +std::optional AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber) { auto chains = nodes[layer][pos.z][pos.x][pos.y]; @@ -102,15 +102,13 @@ boost::optional AINodeStorage::getOrCreateNode(const int3 & pos, c } } - return boost::none; + return std::nullopt; } std::vector AINodeStorage::getInitialNodes() { auto hpos = hero->visitablePos(); - auto initialNode = - getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN) - .get(); + auto initialNode = getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN).value(); initialNode->turns = 0; initialNode->moveRemains = hero->movement; @@ -171,10 +169,10 @@ std::vector AINodeStorage::calculateNeighbours( { auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask); - if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET) + if(!nextNode || nextNode.value()->accessible == CGPathNode::NOT_SET) continue; - neighbours.push_back(nextNode.get()); + neighbours.push_back(nextNode.value()); } } @@ -207,7 +205,7 @@ std::vector AINodeStorage::calculateTeleportations( if(!node) continue; - neighbours.push_back(node.get()); + neighbours.push_back(node.value()); } } @@ -273,7 +271,7 @@ void AINodeStorage::calculateTownPortalTeleportations( logAi->trace("Adding town portal node at %s", targetTown->name); #endif - AIPathNode * node = nodeOptional.get(); + AIPathNode * node = nodeOptional.value(); node->theNodeBefore = source.node; node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown)); diff --git a/AI/VCAI/Pathfinding/AINodeStorage.h b/AI/VCAI/Pathfinding/AINodeStorage.h index b5696578d..b63ffc25e 100644 --- a/AI/VCAI/Pathfinding/AINodeStorage.h +++ b/AI/VCAI/Pathfinding/AINodeStorage.h @@ -107,7 +107,7 @@ public: bool isBattleNode(const CGPathNode * node) const; bool hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const; - boost::optional getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, int chainNumber); + std::optional getOrCreateNode(const int3 & coord, const EPathfindingLayer layer, int chainNumber); std::vector getChainInfo(const int3 & pos, bool isOnLand) const; bool isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const; diff --git a/AI/VCAI/Pathfinding/PathfindingManager.cpp b/AI/VCAI/Pathfinding/PathfindingManager.cpp index d0b19519b..615d68096 100644 --- a/AI/VCAI/Pathfinding/PathfindingManager.cpp +++ b/AI/VCAI/Pathfinding/PathfindingManager.cpp @@ -114,7 +114,7 @@ Goals::TGoalVec PathfindingManager::findPath( const std::function doVisitTile) const { Goals::TGoalVec result; - boost::optional armyValueRequired; + std::optional armyValueRequired; uint64_t danger; std::vector chainInfo = pathfinder->getPathInfo(hero, dest); @@ -165,12 +165,12 @@ Goals::TGoalVec PathfindingManager::findPath( if(!armyValueRequired || armyValueRequired > danger) { - armyValueRequired = boost::make_optional(danger); + armyValueRequired = std::make_optional(danger); } } } - danger = armyValueRequired.get_value_or(0); + danger = armyValueRequired.value_or(0); if(allowGatherArmy && danger > 0) { diff --git a/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp b/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp index fe9878a22..6689765e6 100644 --- a/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp +++ b/AI/VCAI/Pathfinding/Rules/AILayerTransitionRule.cpp @@ -120,7 +120,7 @@ namespace AIPathfinding if(boatNodeOptional) { - AIPathNode * boatNode = boatNodeOptional.get(); + AIPathNode * boatNode = boatNodeOptional.value(); if(boatNode->action == CGPathNode::UNKNOWN) { diff --git a/AI/VCAI/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp b/AI/VCAI/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp index 83e51161b..10393ec9c 100644 --- a/AI/VCAI/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp +++ b/AI/VCAI/Pathfinding/Rules/AIMovementAfterDestinationRule.cpp @@ -106,7 +106,7 @@ namespace AIPathfinding return; } - AIPathNode * battleNode = battleNodeOptional.get(); + auto * battleNode = battleNodeOptional.value(); if(battleNode->locked) { diff --git a/AI/VCAI/VCAI.cpp b/AI/VCAI/VCAI.cpp index db4bd6b65..ec14d11c6 100644 --- a/AI/VCAI/VCAI.cpp +++ b/AI/VCAI/VCAI.cpp @@ -1241,14 +1241,14 @@ void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruit } } -bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional movementCostLimit) +bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional movementCostLimit) { int3 op = obj->visitablePos(); auto paths = ah->getPathsToTile(h, op); for(const auto & path : paths) { - if(movementCostLimit && movementCostLimit.get() < path.movementCost()) + if(movementCostLimit && movementCostLimit.value() < path.movementCost()) return false; if(isGoodForVisit(obj, h, path)) @@ -1363,18 +1363,13 @@ void VCAI::wander(HeroPtr h) }); int pass = 0; - std::vector> distanceLimits = - { - 1.0, - 2.0, - boost::none - }; + std::vector> distanceLimits = {1.0, 2.0, std::nullopt}; while(!dests.size() && pass < distanceLimits.size()) { auto & distanceLimit = distanceLimits[pass]; - logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.get_value_or(-1.0)); + logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0)); vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool { diff --git a/AI/VCAI/VCAI.h b/AI/VCAI/VCAI.h index d15933383..f4c63ef93 100644 --- a/AI/VCAI/VCAI.h +++ b/AI/VCAI/VCAI.h @@ -217,7 +217,7 @@ public: void completeGoal(Goals::TSubgoal goal); //safely removes goal from reserved hero void recruitHero(const CGTownInstance * t, bool throwing = false); - bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional movementCostLimit = boost::none); + bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional movementCostLimit = std::nullopt); bool isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const; //void recruitCreatures(const CGTownInstance * t); void recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter); diff --git a/CCallback.cpp b/CCallback.cpp index e58c31480..8e50d7e99 100644 --- a/CCallback.cpp +++ b/CCallback.cpp @@ -90,7 +90,7 @@ bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, Crea void CCallback::endTurn() { - logGlobal->trace("Player %d ended his turn.", player.get().getNum()); + logGlobal->trace("Player %d ended his turn.", player->getNum()); EndTurn pack; sendRequest(&pack); } @@ -306,8 +306,8 @@ void CCallback::buildBoat( const IShipyard *obj ) sendRequest(&bb); } -CCallback::CCallback(CGameState * GS, boost::optional Player, CClient * C) - : CBattleCallback(Player, C) +CCallback::CCallback(CGameState * GS, std::optional Player, CClient * C): + CBattleCallback(Player, C) { gs = GS; @@ -380,7 +380,7 @@ scripting::Pool * CBattleCallback::getContextPool() const } #endif -CBattleCallback::CBattleCallback(boost::optional Player, CClient *C ) +CBattleCallback::CBattleCallback(std::optional Player, CClient * C) { player = Player; cl = C; @@ -395,8 +395,7 @@ bool CBattleCallback::battleMakeTacticAction( BattleAction * action ) return true; } -boost::optional CBattleCallback::makeSurrenderRetreatDecision( - const BattleStateInfoForRetreat & battleState) +std::optional CBattleCallback::makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) { - return cl->playerint[getPlayerID().get()]->makeSurrenderRetreatDecision(battleState); + return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleState); } diff --git a/CCallback.h b/CCallback.h index 815022fb0..a1793098d 100644 --- a/CCallback.h +++ b/CCallback.h @@ -54,7 +54,7 @@ public: //battle virtual int battleMakeAction(const BattleAction * action) = 0;//for casting spells by hero - DO NOT use it for moving active stack virtual bool battleMakeTacticAction(BattleAction * action) = 0; // performs tactic phase actions - virtual boost::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) = 0; + virtual std::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) = 0; }; class IGameActionCallback @@ -113,10 +113,10 @@ protected: CClient *cl; public: - CBattleCallback(boost::optional Player, CClient *C); + CBattleCallback(std::optional Player, CClient * C); int battleMakeAction(const BattleAction * action) override;//for casting spells by hero - DO NOT use it for moving active stack bool battleMakeTacticAction(BattleAction * action) override; // performs tactic phase actions - boost::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; + std::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) override; #if SCRIPTING_ENABLED scripting::Pool * getContextPool() const override; @@ -131,7 +131,7 @@ class CCallback : public CPlayerSpecificInfoCallback, public CBattleCallback { public: - CCallback(CGameState * GS, boost::optional Player, CClient *C); + CCallback(CGameState * GS, std::optional Player, CClient * C); virtual ~CCallback(); //client-specific functionalities (pathfinding) diff --git a/Global.h b/Global.h index 0a10239c4..b54ea4fac 100644 --- a/Global.h +++ b/Global.h @@ -101,6 +101,7 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size."); #define _USE_MATH_DEFINES #include +#include #include #include #include @@ -144,14 +145,13 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size."); #endif #include -#include -#include #include +#include #include #include #include -#include #include +#include #include #include #include @@ -159,14 +159,11 @@ static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size."); #include #endif #include -#include -#include +#include #include #include #include #include -#include -#include #ifndef M_PI # define M_PI 3.14159265358979323846 @@ -576,28 +573,6 @@ namespace vstd return i >= 0 && i < c.size(); } - template - boost::optional tryAt(const Container &c, Index i) - { - if(isValidIndex(c, i)) - { - auto itr = c.begin(); - std::advance(itr, i); - return *itr; - } - return boost::none; - } - - template - static boost::optional tryFindIf(const Container &r, const Pred &t) - { - auto pos = range::find_if(r, t); - if(pos == boost::end(r)) - return boost::none; - else - return *pos; - } - template typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue) { @@ -668,8 +643,8 @@ namespace vstd return false; } - template - typename M::mapped_type & getOrCompute(M & m, Key const & k, F f) + template + typename M::mapped_type & getOrCompute(M & m, const Key & k, F f) { typedef typename M::mapped_type V; diff --git a/android/vcmi-app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/vcmi-app/src/main/res/mipmap-hdpi/ic_launcher.png index 0f94c89b0..0112f0583 100644 Binary files a/android/vcmi-app/src/main/res/mipmap-hdpi/ic_launcher.png and b/android/vcmi-app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/vcmi-app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/vcmi-app/src/main/res/mipmap-mdpi/ic_launcher.png index d712a81d2..4c6c239af 100644 Binary files a/android/vcmi-app/src/main/res/mipmap-mdpi/ic_launcher.png and b/android/vcmi-app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/vcmi-app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/vcmi-app/src/main/res/mipmap-xhdpi/ic_launcher.png index 5d2c59344..308b6da28 100644 Binary files a/android/vcmi-app/src/main/res/mipmap-xhdpi/ic_launcher.png and b/android/vcmi-app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/vcmi-app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/vcmi-app/src/main/res/mipmap-xxhdpi/ic_launcher.png index ec331216a..03c68efa7 100644 Binary files a/android/vcmi-app/src/main/res/mipmap-xxhdpi/ic_launcher.png and b/android/vcmi-app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/vcmi-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/vcmi-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png index 0ac591fa8..ecbf76a7a 100644 Binary files a/android/vcmi-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and b/android/vcmi-app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 4fc7d2192..0a829ed0e 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -403,9 +403,15 @@ endif() #install icons and desktop file on Linux if(NOT WIN32 AND NOT APPLE AND NOT ANDROID) #FIXME: move to client makefile? - install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.64x64.png" DESTINATION share/icons/hicolor/64x64/apps RENAME vcmiclient.png) - install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.48x48.png" DESTINATION share/icons/hicolor/48x48/apps RENAME vcmiclient.png) - install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.32x32.png" DESTINATION share/icons/hicolor/32x32/apps RENAME vcmiclient.png) - install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.256x256.png" DESTINATION share/icons/hicolor/256x256/apps RENAME vcmiclient.png) - install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.desktop" DESTINATION share/applications) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.16x16.png" DESTINATION share/icons/hicolor/16x16/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.32x32.png" DESTINATION share/icons/hicolor/32x32/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.48x48.png" DESTINATION share/icons/hicolor/48x48/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.64x64.png" DESTINATION share/icons/hicolor/64x64/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.128x128.png" DESTINATION share/icons/hicolor/128x128/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.256x256.png" DESTINATION share/icons/hicolor/256x256/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.512x512.png" DESTINATION share/icons/hicolor/512x512/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.1024x1024.png" DESTINATION share/icons/hicolor/1024x1024/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.2048x2048.png" DESTINATION share/icons/hicolor/2048x2048/apps RENAME vcmiclient.png) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.svg" DESTINATION share/icons/hicolor/scalable/apps RENAME vcmiclient.svg) + install(FILES "${CMAKE_SOURCE_DIR}/client/icons/vcmiclient.desktop" DESTINATION share/applications) endif() diff --git a/client/CPlayerInterface.cpp b/client/CPlayerInterface.cpp index 5aa6801bf..8ab3bab52 100644 --- a/client/CPlayerInterface.cpp +++ b/client/CPlayerInterface.cpp @@ -103,7 +103,7 @@ std::shared_ptr CPlayerInterface::battleInt; enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE}; CondSh stillMoveHero(STOP_MOVE); //used during hero movement -struct HeroObjectRetriever : boost::static_visitor +struct HeroObjectRetriever { const CGHeroInstance * operator()(const ConstTransitivePtr &h) const { @@ -328,7 +328,7 @@ void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose) if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK) { if(hero->getRemovalSound() && hero->tempOwner == playerID) - CCS->soundh->playSound(hero->getRemovalSound().get()); + CCS->soundh->playSound(hero->getRemovalSound().value()); } adventureInt->minimap->updateTile(hero->convertToVisitablePos(details.start)); @@ -463,7 +463,7 @@ void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectI if(start && visitedObj) { if(visitedObj->getVisitSound()) - CCS->soundh->playSound(visitedObj->getVisitSound().get()); + CCS->soundh->playSound(visitedObj->getVisitSound().value()); } } @@ -1530,7 +1530,7 @@ void CPlayerInterface::objectRemoved(const CGObjectInstance * obj) if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound()) { waitWhileDialog(); - CCS->soundh->playSound(obj->getRemovalSound().get()); + CCS->soundh->playSound(obj->getRemovalSound().value()); } CGI->mh->waitForOngoingAnimations(); @@ -1758,7 +1758,7 @@ void CPlayerInterface::acceptTurn() if(optDaysWithoutCastle) { - auto daysWithoutCastle = optDaysWithoutCastle.get(); + auto daysWithoutCastle = optDaysWithoutCastle.value(); if (daysWithoutCastle < 6) { text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land. @@ -1915,7 +1915,7 @@ void CPlayerInterface::requestReturningToMainMenu(bool won) void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al) { - auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder); + auto hero = std::visit(HeroObjectRetriever(), al.artHolder); if(hero) { auto art = hero->getArt(al.slot); @@ -1932,14 +1932,14 @@ void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al) void CPlayerInterface::artifactPut(const ArtifactLocation &al) { EVENT_HANDLER_CALLED_BY_CLIENT; - auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder); + auto hero = std::visit(HeroObjectRetriever(), al.artHolder); updateInfo(hero); } void CPlayerInterface::artifactRemoved(const ArtifactLocation &al) { EVENT_HANDLER_CALLED_BY_CLIENT; - auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder); + auto hero = std::visit(HeroObjectRetriever(), al.artHolder); updateInfo(hero); for(auto isa : GH.listInt) { @@ -1954,7 +1954,7 @@ void CPlayerInterface::artifactRemoved(const ArtifactLocation &al) void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst) { EVENT_HANDLER_CALLED_BY_CLIENT; - auto hero = boost::apply_visitor(HeroObjectRetriever(), dst.artHolder); + auto hero = std::visit(HeroObjectRetriever(), dst.artHolder); updateInfo(hero); bool redraw = true; @@ -1983,7 +1983,7 @@ void CPlayerInterface::bulkArtMovementStart(size_t numOfArts) void CPlayerInterface::artifactAssembled(const ArtifactLocation &al) { EVENT_HANDLER_CALLED_BY_CLIENT; - auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder); + auto hero = std::visit(HeroObjectRetriever(), al.artHolder); updateInfo(hero); for(auto isa : GH.listInt) { @@ -1996,7 +1996,7 @@ void CPlayerInterface::artifactAssembled(const ArtifactLocation &al) void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al) { EVENT_HANDLER_CALLED_BY_CLIENT; - auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder); + auto hero = std::visit(HeroObjectRetriever(), al.artHolder); updateInfo(hero); for(auto isa : GH.listInt) { diff --git a/client/Client.cpp b/client/Client.cpp index a85f9ecc0..90080eed3 100644 --- a/client/Client.cpp +++ b/client/Client.cpp @@ -421,7 +421,7 @@ void CClient::initPlayerEnvironments() if(settings["session"]["spectate"].Bool()) { - playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared(PlayerColor::SPECTATOR, this, std::make_shared(gs, boost::none, this)); + playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared(PlayerColor::SPECTATOR, this, std::make_shared(gs, std::nullopt, this)); } } @@ -626,7 +626,7 @@ void CClient::commenceTacticPhaseForInt(std::shared_ptr ba battleInt->yourTacticPhase(gs->curB->tacticDistance); if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game) { - MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).get())); + MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).value())); sendRequest(&ma, battleInt->playerID); } } diff --git a/client/Client.h b/client/Client.h index 95344ba1f..adc5dfaf4 100644 --- a/client/Client.h +++ b/client/Client.h @@ -140,7 +140,7 @@ public: std::map>> additionalBattleInts; - boost::optional curbaction; + std::optional curbaction; CClient(); ~CClient(); diff --git a/client/ClientCommandManager.cpp b/client/ClientCommandManager.cpp index a5e1790da..194f8c94c 100644 --- a/client/ClientCommandManager.cpp +++ b/client/ClientCommandManager.cpp @@ -42,7 +42,34 @@ #include -void ClientCommandManager::handleGoSolo() +void ClientCommandManager::handleQuitCommand() +{ + exit(EXIT_SUCCESS); +} + +void ClientCommandManager::handleSaveCommand(std::istringstream & singleWordBuffer) +{ + if(!CSH->client) + { + printCommandMessage("Game is not in playing state"); + return; + } + + std::string saveFilename; + singleWordBuffer >> saveFilename; + CSH->client->save(saveFilename); + printCommandMessage("Game saved as: " + saveFilename); +} + +void ClientCommandManager::handleLoadCommand(std::istringstream& singleWordBuffer) +{ + // TODO: this code should end the running game and manage to call startGame instead + //std::string fname; + //singleWordBuffer >> fname; + //CSH->client->loadGame(fname); +} + +void ClientCommandManager::handleGoSoloCommand() { Settings session = settings.write["session"]; @@ -80,21 +107,33 @@ void ClientCommandManager::handleGoSolo() session["aiSolo"].Bool() = !session["aiSolo"].Bool(); } -void ClientCommandManager::handleControlAi(const std::string &colorName) +void ClientCommandManager::handleAutoskipCommand() { + Settings session = settings.write["session"]; + session["autoSkip"].Bool() = !session["autoSkip"].Bool(); +} + +void ClientCommandManager::handleControlaiCommand(std::istringstream& singleWordBuffer) +{ + std::string colorName; + singleWordBuffer >> colorName; + boost::to_lower(colorName); + boost::unique_lock un(*CPlayerInterface::pim); if(!CSH->client) { printCommandMessage("Game is not in playing state"); return; } + PlayerColor color; if(LOCPLINT) color = LOCPLINT->playerID; + for(auto & elem : CSH->client->gameState()->players) { - if(elem.second.human || (colorName.length() && - elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName))) + if(elem.second.human || + (colorName.length() && elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName))) { continue; } @@ -102,386 +141,319 @@ void ClientCommandManager::handleControlAi(const std::string &colorName) CSH->client->removeGUI(); CSH->client->installNewPlayerInterface(std::make_shared(elem.first), elem.first); } + GH.totalRedraw(); if(color != PlayerColor::NEUTRAL) giveTurn(color); } -void ClientCommandManager::processCommand(const std::string &message, bool calledFromIngameConsole) +void ClientCommandManager::handleSetBattleAICommand(std::istringstream& singleWordBuffer) { - std::istringstream singleWordBuffer; - singleWordBuffer.str(message); - std::string commandName; - singleWordBuffer >> commandName; - currentCallFromIngameConsole = calledFromIngameConsole; + std::string aiName; + singleWordBuffer >> aiName; - if(message==std::string("die, fool")) + printCommandMessage("Will try loading that AI to see if it is correct name...\n"); + try { - exit(EXIT_SUCCESS); + if(auto ai = CDynLibHandler::getNewBattleAI(aiName)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game + { + Settings neutralAI = settings.write["server"]["neutralAI"]; + neutralAI->String() = aiName; + printCommandMessage("Setting changed, from now the battle ai will be " + aiName + "!\n"); + } } - else if(commandName == "redraw") + catch(std::exception &e) { - GH.totalRedraw(); + printCommandMessage("Failed opening " + aiName + ": " + e.what(), ELogLevel::WARN); + printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN); } - else if(commandName == "screen") - { - printCommandMessage("Screenbuf points to "); +} - if(screenBuf == screen) - printCommandMessage("screen", ELogLevel::ERROR); - else if(screenBuf == screen2) - printCommandMessage("screen2", ELogLevel::ERROR); +void ClientCommandManager::handleRedrawCommand() +{ + GH.totalRedraw(); +} + +void ClientCommandManager::handleScreenCommand() +{ + printCommandMessage("Screenbuf points to "); + + if(screenBuf == screen) + printCommandMessage("screen", ELogLevel::ERROR); + else if(screenBuf == screen2) + printCommandMessage("screen2", ELogLevel::ERROR); + else + printCommandMessage("?!?", ELogLevel::ERROR); + + SDL_SaveBMP(screen, "Screen_c.bmp"); + SDL_SaveBMP(screen2, "Screen2_c.bmp"); +} + +void ClientCommandManager::handleNotDialogCommand() +{ + LOCPLINT->showingDialog->setn(false); +} + +void ClientCommandManager::handleGuiCommand() +{ + for(const auto & child : GH.listInt) + { + const auto childPtr = child.get(); + if(const CIntObject * obj = dynamic_cast(childPtr)) + printInfoAboutInterfaceObject(obj, 0); else - printCommandMessage("?!?", ELogLevel::ERROR); - - SDL_SaveBMP(screen, "Screen_c.bmp"); - SDL_SaveBMP(screen2, "Screen2_c.bmp"); + printCommandMessage(std::string(typeid(childPtr).name()) + "\n"); } - else if(commandName == "save") +} + +void ClientCommandManager::handleConvertTextCommand() +{ + logGlobal->info("Searching for available maps"); + std::unordered_set mapList = CResourceHandler::get()->getFilteredFiles([&](const ResourceID & ident) { - if(!CSH->client) - { - printCommandMessage("Game is not in playing state"); - return; - } - std::string fname; - singleWordBuffer >> fname; - CSH->client->save(fname); - } -// else if(commandName=="load") -// { -// // TODO: this code should end the running game and manage to call startGame instead -// std::string fname; -// singleWordBuffer >> fname; -// CSH->client->loadGame(fname); -// } - else if(message=="convert txt") + return ident.getType() == EResType::MAP; + }); + + std::unordered_set campaignList = CResourceHandler::get()->getFilteredFiles([&](const ResourceID & ident) { - logGlobal->info("Searching for available maps"); - std::unordered_set mapList = CResourceHandler::get()->getFilteredFiles([&](const ResourceID & ident) - { - return ident.getType() == EResType::MAP; - }); + return ident.getType() == EResType::CAMPAIGN; + }); - std::unordered_set campaignList = CResourceHandler::get()->getFilteredFiles([&](const ResourceID & ident) - { - return ident.getType() == EResType::CAMPAIGN; - }); + CMapService mapService; - CMapService mapService; - - logGlobal->info("Loading maps for export"); - for (auto const & mapName : mapList) - { - try - { - // load and drop loaded map - we only need loader to run over all maps - mapService.loadMap(mapName); - } - catch(std::exception & e) - { - logGlobal->error("Map %s is invalid. Message: %s", mapName.getName(), e.what()); - } - } - - logGlobal->info("Loading campaigns for export"); - for (auto const & campaignName : campaignList) - { - CCampaignState state(CCampaignHandler::getCampaign(campaignName.getName())); - for (auto const & part : state.camp->mapPieces) - delete state.getMap(part.first); - } - - VLC->generaltexth->dumpAllTexts(); - } - else if(message=="get config") + logGlobal->info("Loading maps for export"); + for (auto const & mapName : mapList) { - printCommandMessage("Command accepted.\t"); - - const boost::filesystem::path outPath = - VCMIDirs::get().userExtractedPath() / "configuration"; - - boost::filesystem::create_directories(outPath); - - const std::vector contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"}; - - for(auto contentName : contentNames) - { - auto & content = (*VLC->modh->content)[contentName]; - - auto contentOutPath = outPath / contentName; - boost::filesystem::create_directories(contentOutPath); - - for(auto & iter : content.modData) - { - const JsonNode & modData = iter.second.modData; - - for(auto & nameAndObject : modData.Struct()) - { - const JsonNode & object = nameAndObject.second; - - std::string name = CModHandler::makeFullIdentifier(object.meta, contentName, nameAndObject.first); - - boost::algorithm::replace_all(name,":","_"); - - const boost::filesystem::path filePath = contentOutPath / (name + ".json"); - boost::filesystem::ofstream file(filePath); - file << object.toJson(); - } - } - } - - printCommandMessage("\rExtracting done :)\n"); - printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); - } -#if SCRIPTING_ENABLED - else if(message=="get scripts") - { - printCommandMessage("Command accepted.\t"); - - const boost::filesystem::path outPath = - VCMIDirs::get().userExtractedPath() / "scripts"; - - boost::filesystem::create_directories(outPath); - - for(auto & kv : VLC->scriptHandler->objects) - { - std::string name = kv.first; - boost::algorithm::replace_all(name,":","_"); - - const scripting::ScriptImpl * script = kv.second.get(); - boost::filesystem::path filePath = outPath / (name + ".lua"); - boost::filesystem::ofstream file(filePath); - file << script->getSource(); - } - printCommandMessage("\rExtracting done :)\n"); - printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); - } -#endif - else if(message=="get txt") - { - printCommandMessage("Command accepted.\t"); - - const boost::filesystem::path outPath = - VCMIDirs::get().userExtractedPath(); - - auto list = - CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident) - { - return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/"); - }); - - for (auto & filename : list) - { - const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT"); - - boost::filesystem::create_directories(filePath.parent_path()); - - boost::filesystem::ofstream file(filePath); - auto text = CResourceHandler::get()->load(filename)->readAll(); - - file.write((char*)text.first.get(), text.second); - } - - printCommandMessage("\rExtracting done :)\n"); - printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); - } - else if(commandName == "crash") - { - int *ptr = nullptr; - *ptr = 666; - //disaster! - } - else if(commandName == "mp" && adventureInt) - { - if(const CGHeroInstance *h = adventureInt->curHero()) - printCommandMessage(std::to_string(h->movement) + "; max: " + std::to_string(h->maxMovePoints(true)) + "/" + std::to_string(h->maxMovePoints(false)) + "\n"); - } - else if(commandName == "bonuses") - { - bool jsonFormat = (message == "bonuses json"); - auto format = [jsonFormat](const BonusList & b) -> std::string - { - if(jsonFormat) - return b.toJsonNode().toJson(true); - std::ostringstream ss; - ss << b; - return ss.str(); - }; - printCommandMessage("Bonuses of " + adventureInt->curArmy()->getObjectName() + "\n"); - printCommandMessage(format(adventureInt->curArmy()->getBonusList()) + "\n"); - - printCommandMessage("\nInherited bonuses:\n"); - TCNodes parents; - adventureInt->curArmy()->getParents(parents); - for(const CBonusSystemNode *parent : parents) - { - printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n"); - } - } - else if(commandName == "not dialog") - { - LOCPLINT->showingDialog->setn(false); - } - else if(commandName == "gui") - { - for(auto & child : GH.listInt) - { - const auto childPtr = child.get(); - if(const CIntObject * obj = dynamic_cast(childPtr)) - printInfoAboutInterfaceObject(obj, 0); - else - printCommandMessage(std::string(typeid(childPtr).name()) + "\n"); - } - } - else if(commandName == "tell") - { - std::string what; - int id1, id2; - singleWordBuffer >> what >> id1 >> id2; - if(what == "hs") - { - for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo()) - if(h->type->getIndex() == id1) - if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2))) - printCommandMessage(a->nodeName()); - } - } - else if (commandName == "set") - { - std::string what, value; - singleWordBuffer >> what; - - Settings config = settings.write["session"][what]; - - singleWordBuffer >> value; - - if (value == "on") - { - config->Bool() = true; - printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO); - } - else if (value == "off") - { - config->Bool() = false; - printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO); - } - } - else if(commandName == "unlock") - { - std::string mxname; - singleWordBuffer >> mxname; - if(mxname == "pim" && LOCPLINT) - LOCPLINT->pim->unlock(); - } - else if(commandName == "def2bmp") - { - std::string URI; - singleWordBuffer >> URI; - std::unique_ptr anim = std::make_unique(URI); - anim->preload(); - anim->exportBitmaps(VCMIDirs::get().userExtractedPath()); - } - else if(commandName == "extract") - { - std::string URI; - singleWordBuffer >> URI; - - if (CResourceHandler::get()->existsResource(ResourceID(URI))) - { - const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI; - - auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll(); - - boost::filesystem::create_directories(outPath.parent_path()); - boost::filesystem::ofstream outFile(outPath, boost::filesystem::ofstream::binary); - outFile.write((char*)data.first.get(), data.second); - } - else - printCommandMessage("File not found!", ELogLevel::ERROR); - } - else if(commandName == "setBattleAI") - { - std::string fname; - singleWordBuffer >> fname; - printCommandMessage("Will try loading that AI to see if it is correct name...\n"); try { - if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game + // load and drop loaded map - we only need loader to run over all maps + mapService.loadMap(mapName); + } + catch(std::exception & e) + { + logGlobal->error("Map %s is invalid. Message: %s", mapName.getName(), e.what()); + } + } + + logGlobal->info("Loading campaigns for export"); + for (auto const & campaignName : campaignList) + { + CCampaignState state(CCampaignHandler::getCampaign(campaignName.getName())); + for (auto const & part : state.camp->mapPieces) + delete state.getMap(part.first); + } + + VLC->generaltexth->dumpAllTexts(); +} + +void ClientCommandManager::handleGetConfigCommand() +{ + printCommandMessage("Command accepted.\t"); + + const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "configuration"; + + boost::filesystem::create_directories(outPath); + + const std::vector contentNames = { "heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills" }; + + for(auto contentName : contentNames) + { + auto& content = (*VLC->modh->content)[contentName]; + + auto contentOutPath = outPath / contentName; + boost::filesystem::create_directories(contentOutPath); + + for(auto& iter : content.modData) + { + const JsonNode& modData = iter.second.modData; + + for(auto& nameAndObject : modData.Struct()) { - Settings neutralAI = settings.write["server"]["neutralAI"]; - neutralAI->String() = fname; - printCommandMessage("Setting changed, from now the battle ai will be " + fname + "!\n"); + const JsonNode& object = nameAndObject.second; + + std::string name = CModHandler::makeFullIdentifier(object.meta, contentName, nameAndObject.first); + + boost::algorithm::replace_all(name, ":", "_"); + + const boost::filesystem::path filePath = contentOutPath / (name + ".json"); + boost::filesystem::ofstream file(filePath); + file << object.toJson(); } } - catch(std::exception &e) - { - printCommandMessage("Failed opening " + fname + ": " + e.what(), ELogLevel::WARN); - printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN); - } } - else if(commandName == "autoskip") - { - Settings session = settings.write["session"]; - session["autoSkip"].Bool() = !session["autoSkip"].Bool(); - } - else if(commandName == "gosolo") - { - ClientCommandManager::handleGoSolo(); - } - else if(commandName == "controlai") - { - std::string colorName; - singleWordBuffer >> colorName; - boost::to_lower(colorName); - ClientCommandManager::handleControlAi(colorName); + printCommandMessage("\rExtracting done :)\n"); + printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); +} + +void ClientCommandManager::handleGetScriptsCommand() +{ +#if SCRIPTING_ENABLED + printCommandMessage("Command accepted.\t"); + + const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "scripts"; + + boost::filesystem::create_directories(outPath); + + for(auto & kv : VLC->scriptHandler->objects) + { + std::string name = kv.first; + boost::algorithm::replace_all(name,":","_"); + + const scripting::ScriptImpl * script = kv.second.get(); + boost::filesystem::path filePath = outPath / (name + ".lua"); + boost::filesystem::ofstream file(filePath); + file << script->getSource(); + } + printCommandMessage("\rExtracting done :)\n"); + printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); +#endif +} + +void ClientCommandManager::handleGetTextCommand() +{ + printCommandMessage("Command accepted.\t"); + + const boost::filesystem::path outPath = + VCMIDirs::get().userExtractedPath(); + + auto list = + CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident) + { + return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/"); + }); + + for (auto & filename : list) + { + const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT"); + + boost::filesystem::create_directories(filePath.parent_path()); + + boost::filesystem::ofstream file(filePath); + auto text = CResourceHandler::get()->load(filename)->readAll(); + + file.write((char*)text.first.get(), text.second); + } + + printCommandMessage("\rExtracting done :)\n"); + printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n"); +} + +void ClientCommandManager::handleDef2bmpCommand(std::istringstream& singleWordBuffer) +{ + std::string URI; + singleWordBuffer >> URI; + std::unique_ptr anim = std::make_unique(URI); + anim->preload(); + anim->exportBitmaps(VCMIDirs::get().userExtractedPath()); +} + +void ClientCommandManager::handleExtractCommand(std::istringstream& singleWordBuffer) +{ + std::string URI; + singleWordBuffer >> URI; + + if(CResourceHandler::get()->existsResource(ResourceID(URI))) + { + const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI; + + auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll(); + + boost::filesystem::create_directories(outPath.parent_path()); + boost::filesystem::ofstream outFile(outPath, boost::filesystem::ofstream::binary); + outFile.write((char*)data.first.get(), data.second); } else + printCommandMessage("File not found!", ELogLevel::ERROR); +} + +void ClientCommandManager::handleBonusesCommand(std::istringstream & singleWordBuffer) +{ + if(currentCallFromIngameConsole) { - if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise - printCommandMessage("Command not found :(", ELogLevel::ERROR); + printCommandMessage("Output for this command is too large for ingame chat! Please run it from client console.\n"); + return; + } + + std::string outputFormat; + singleWordBuffer >> outputFormat; + + auto format = [outputFormat](const BonusList & b) -> std::string + { + if(outputFormat == "json") + return b.toJsonNode().toJson(true); + + std::ostringstream ss; + ss << b; + return ss.str(); + }; + printCommandMessage("Bonuses of " + adventureInt->curArmy()->getObjectName() + "\n"); + printCommandMessage(format(adventureInt->curArmy()->getBonusList()) + "\n"); + + printCommandMessage("\nInherited bonuses:\n"); + TCNodes parents; + adventureInt->curArmy()->getParents(parents); + for(const CBonusSystemNode *parent : parents) + { + printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n"); } } -void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier) +void ClientCommandManager::handleTellCommand(std::istringstream& singleWordBuffer) { - YourTurn yt; - yt.player = colorIdentifier; - yt.daysWithoutCastle = CSH->client->getPlayerState(colorIdentifier)->daysWithoutCastle; + std::string what; + int id1, id2; + singleWordBuffer >> what >> id1 >> id2; - ApplyClientNetPackVisitor visitor(*CSH->client, *CSH->client->gameState()); - yt.visit(visitor); + if(what == "hs") + { + for(const CGHeroInstance* h : LOCPLINT->cb->getHeroesInfo()) + if(h->type->getIndex() == id1) + if(const CArtifactInstance* a = h->getArt(ArtifactPosition(id2))) + printCommandMessage(a->nodeName()); + } } -void ClientCommandManager::printInfoAboutInterfaceObject(const CIntObject *obj, int level) +void ClientCommandManager::handleMpCommand() { - std::stringstream sbuffer; - sbuffer << std::string(level, '\t'); + if(const CGHeroInstance* h = adventureInt->curHero()) + printCommandMessage(std::to_string(h->movement) + "; max: " + std::to_string(h->maxMovePoints(true)) + "/" + std::to_string(h->maxMovePoints(false)) + "\n"); +} - sbuffer << typeid(*obj).name() << " *** "; - if (obj->active) +void ClientCommandManager::handleSetCommand(std::istringstream& singleWordBuffer) +{ + std::string what, value; + singleWordBuffer >> what; + + Settings config = settings.write["session"][what]; + + singleWordBuffer >> value; + + if(value == "on") { -#define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text - PRINT(LCLICK, 'L'); - PRINT(RCLICK, 'R'); - PRINT(HOVER, 'H'); - PRINT(MOVE, 'M'); - PRINT(KEYBOARD, 'K'); - PRINT(TIME, 'T'); - PRINT(GENERAL, 'A'); - PRINT(WHEEL, 'W'); - PRINT(DOUBLECLICK, 'D'); -#undef PRINT + config->Bool() = true; + printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO); } - else - sbuffer << "inactive"; - sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y; - sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")"; - printCommandMessage(sbuffer.str(), ELogLevel::INFO); + else if(value == "off") + { + config->Bool() = false; + printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO); + } +} - for(const CIntObject *child : obj->children) - printInfoAboutInterfaceObject(child, level+1); +void ClientCommandManager::handleUnlockCommand(std::istringstream& singleWordBuffer) +{ + std::string mxname; + singleWordBuffer >> mxname; + if(mxname == "pim" && LOCPLINT) + LOCPLINT->pim->unlock(); +} + +void ClientCommandManager::handleCrashCommand() +{ + int* ptr = nullptr; + *ptr = 666; + //disaster! } void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType) @@ -520,3 +492,131 @@ void ClientCommandManager::printCommandMessage(const std::string &commandMessage } } } + +void ClientCommandManager::printInfoAboutInterfaceObject(const CIntObject *obj, int level) +{ + std::stringstream sbuffer; + sbuffer << std::string(level, '\t'); + + sbuffer << typeid(*obj).name() << " *** "; + if (obj->active) + { +#define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text + PRINT(LCLICK, 'L'); + PRINT(RCLICK, 'R'); + PRINT(HOVER, 'H'); + PRINT(MOVE, 'M'); + PRINT(KEYBOARD, 'K'); + PRINT(TIME, 'T'); + PRINT(GENERAL, 'A'); + PRINT(WHEEL, 'W'); + PRINT(DOUBLECLICK, 'D'); +#undef PRINT + } + else + sbuffer << "inactive"; + sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y; + sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")"; + printCommandMessage(sbuffer.str(), ELogLevel::INFO); + + for(const CIntObject *child : obj->children) + printInfoAboutInterfaceObject(child, level+1); +} + +void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier) +{ + YourTurn yt; + yt.player = colorIdentifier; + yt.daysWithoutCastle = CSH->client->getPlayerState(colorIdentifier)->daysWithoutCastle; + + ApplyClientNetPackVisitor visitor(*CSH->client, *CSH->client->gameState()); + yt.visit(visitor); +} + +void ClientCommandManager::processCommand(const std::string & message, bool calledFromIngameConsole) +{ + // split the message into individual words + std::istringstream singleWordBuffer; + singleWordBuffer.str(message); + + // get command name, to be used for single word commands + std::string commandName; + singleWordBuffer >> commandName; + + currentCallFromIngameConsole = calledFromIngameConsole; + + if(message == std::string("die, fool")) + handleQuitCommand(); + + else if(commandName == "save") + handleSaveCommand(singleWordBuffer); + + else if(commandName=="load") + handleLoadCommand(singleWordBuffer); // not implemented + + else if(commandName == "gosolo") + handleGoSoloCommand(); + + else if(commandName == "autoskip") + handleAutoskipCommand(); + + else if(commandName == "controlai") + handleControlaiCommand(singleWordBuffer); + + else if(commandName == "setBattleAI") + handleSetBattleAICommand(singleWordBuffer); + + else if(commandName == "redraw") + handleRedrawCommand(); + + else if(commandName == "screen") + handleScreenCommand(); + + else if(commandName == "not dialog") + handleNotDialogCommand(); + + else if(commandName == "gui") + handleGuiCommand(); + + else if(message=="convert txt") + handleConvertTextCommand(); + + else if(message=="get config") + handleGetConfigCommand(); + + else if(message=="get scripts") + handleGetScriptsCommand(); + + else if(message=="get txt") + handleGetTextCommand(); + + else if(commandName == "def2bmp") + handleDef2bmpCommand(singleWordBuffer); + + else if(commandName == "extract") + handleExtractCommand(singleWordBuffer); + + else if(commandName == "bonuses") + handleBonusesCommand(singleWordBuffer); + + else if(commandName == "tell") + handleTellCommand(singleWordBuffer); + + else if(commandName == "mp" && adventureInt) + handleMpCommand(); + + else if (commandName == "set") + handleSetCommand(singleWordBuffer); + + else if(commandName == "unlock") + handleUnlockCommand(singleWordBuffer); + + else if(commandName == "crash") + handleCrashCommand(); + + else + { + if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise + printCommandMessage("Command not found :(", ELogLevel::ERROR); + } +} diff --git a/client/ClientCommandManager.h b/client/ClientCommandManager.h index 14ce180af..ea7ca321f 100644 --- a/client/ClientCommandManager.h +++ b/client/ClientCommandManager.h @@ -17,15 +17,85 @@ class CIntObject; class ClientCommandManager //take mantis #2292 issue about account if thinking about handling cheats from command-line { - bool currentCallFromIngameConsole = false; + bool currentCallFromIngameConsole = false; // commands can come from 2 sources: ingame console (chat) and client console + + // Quits the game (die, fool command) + void handleQuitCommand(); - void giveTurn(const PlayerColor &color); - void printInfoAboutInterfaceObject(const CIntObject *obj, int level); + // Saves current game under the given filename + void handleSaveCommand(std::istringstream & singleWordBuffer); + + // Loads a game with the given filename + void handleLoadCommand(std::istringstream & singleWordBuffer); + + // AI takes over until the end of turn (unlike original H3 currently causes AI to take over until typed again) + void handleGoSoloCommand(); + + // Toggles autoskip mode on and off. In this mode, player turns are automatically skipped and only AI moves. + // However, GUI is still present and allows to observe AI moves. After this option is activated, you need to end first turn manually. + // Press [Shift] before your turn starts to not skip it. + void handleAutoskipCommand(); + + // Gives you control over specified AI player. If none is specified gives you control over all AI players + void handleControlaiCommand(std::istringstream& singleWordBuffer); + + // Change battle AI used by neutral creatures to the one specified. Persists through game quit + void handleSetBattleAICommand(std::istringstream& singleWordBuffer); + + // Redraw the current screen + void handleRedrawCommand(); + + // Prints information about current screen, and saves both screens as .bmp in root folder + void handleScreenCommand(); + + // Set the state indicating if dialog box is active to "no" + void handleNotDialogCommand(); + + // Displays tree view of currently present VCMI common GUI elements + void handleGuiCommand(); + + // Dumps all game text, maps text and campaign maps text into Client log between BEGIN TEXT EXPORT and END TEXT EXPORT + void handleConvertTextCommand(); + + // Saves current game configuration into extracted/configuration folder + void handleGetConfigCommand(); + + // Dumps all scripts in Extracted/Scripts + void handleGetScriptsCommand(); + + // Dumps all .txt files from DATA into Extracted/DATA + void handleGetTextCommand(); + + // Extract .def animation as BMP files + void handleDef2bmpCommand(std::istringstream& singleWordBuffer); + + // Export file into Extracted directory + void handleExtractCommand(std::istringstream& singleWordBuffer); + + // Print in console the current bonuses for curent army + void handleBonusesCommand(std::istringstream & singleWordBuffer); + + // Get what artifact is present on artifact slot with specified ID for hero with specified ID + void handleTellCommand(std::istringstream& singleWordBuffer); + + // Show current movement points, max movement points on land / max movement points on water. + void handleMpCommand(); + + // set - sets special temporary settings that reset on game quit. + void handleSetCommand(std::istringstream& singleWordBuffer); + + // Unlocks specific mutex known in VCMI code as "pim" + void handleUnlockCommand(std::istringstream& singleWordBuffer); + + // Crashes the game forcing an exception + void handleCrashCommand(); + + // Prints in Chat the given message void printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType = ELogLevel::NOT_SET); - void handleGoSolo(); - void handleControlAi(const std::string &colorName); + void printInfoAboutInterfaceObject(const CIntObject *obj, int level); + void giveTurn(const PlayerColor &color); public: ClientCommandManager() = default; - void processCommand(const std::string &message, bool calledFromIngameConsole); + void processCommand(const std::string & message, bool calledFromIngameConsole); }; diff --git a/client/NetPacksClient.cpp b/client/NetPacksClient.cpp index 7b39e0f1b..e2f4313ad 100644 --- a/client/NetPacksClient.cpp +++ b/client/NetPacksClient.cpp @@ -762,7 +762,7 @@ void ApplyClientNetPackVisitor::visitBattleAttack(BattleAttack & pack) void ApplyFirstClientNetPackVisitor::visitStartAction(StartAction & pack) { - cl.curbaction = boost::make_optional(pack.ba); + cl.curbaction = std::make_optional(pack.ba); callBattleInterfaceIfPresentForBothSides(cl, &IBattleEventsReceiver::actionStarted, pack.ba); } diff --git a/client/adventureMap/CAdvMapInt.cpp b/client/adventureMap/CAdvMapInt.cpp index e9f1d7b4a..6f969f0ae 100644 --- a/client/adventureMap/CAdvMapInt.cpp +++ b/client/adventureMap/CAdvMapInt.cpp @@ -853,7 +853,7 @@ void CAdvMapInt::keyPressed(const SDL_Keycode & key) } } -boost::optional CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key) +std::optional CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key) { switch (key) { case SDLK_DOWN: return Point( 0, +1); @@ -871,7 +871,7 @@ boost::optional CAdvMapInt::keyToMoveDirection(const SDL_Keycode & key) case SDLK_KP_8: return Point( 0, -1); case SDLK_KP_9: return Point(+1, -1); } - return boost::none; + return std::nullopt; } void CAdvMapInt::select(const CArmedInstance *sel, bool centerView) diff --git a/client/adventureMap/CAdvMapInt.h b/client/adventureMap/CAdvMapInt.h index 1c4de0ce4..9fd1eb856 100644 --- a/client/adventureMap/CAdvMapInt.h +++ b/client/adventureMap/CAdvMapInt.h @@ -143,7 +143,7 @@ private: const CGObjectInstance *getActiveObject(const int3 &tile); - boost::optional keyToMoveDirection(const SDL_Keycode & key); + std::optional keyToMoveDirection(const SDL_Keycode & key); public: CAdvMapInt(); diff --git a/client/adventureMap/MapAudioPlayer.cpp b/client/adventureMap/MapAudioPlayer.cpp index e289c80f8..5d99d5bd0 100644 --- a/client/adventureMap/MapAudioPlayer.cpp +++ b/client/adventureMap/MapAudioPlayer.cpp @@ -136,7 +136,7 @@ std::vector MapAudioPlayer::getAmbientSounds(const int3 & tile) logGlobal->warn("Already removed object %d found on tile! (%d %d %d)", objectID.getNum(), tile.x, tile.y, tile.z); if(object && object->getAmbientSound()) - result.push_back(object->getAmbientSound().get()); + result.push_back(object->getAmbientSound().value()); } if(CGI->mh->getMap()->isCoastalTile(tile)) diff --git a/client/battle/BattleInterface.cpp b/client/battle/BattleInterface.cpp index 5549c013a..a5c652e5c 100644 --- a/client/battle/BattleInterface.cpp +++ b/client/battle/BattleInterface.cpp @@ -252,7 +252,7 @@ void BattleInterface::giveCommand(EActionType action, BattleHex tile, si32 addit } auto ba = new BattleAction(); //is deleted in CPlayerInterface::stacksController->getActiveStack()() - ba->side = side.get(); + ba->side = side.value(); ba->actionType = action; ba->aimToHex(tile); ba->actionSubtype = additional; diff --git a/client/battle/BattleInterfaceClasses.cpp b/client/battle/BattleInterfaceClasses.cpp index 1fbd4f3ce..ebdff1507 100644 --- a/client/battle/BattleInterfaceClasses.cpp +++ b/client/battle/BattleInterfaceClasses.cpp @@ -68,7 +68,7 @@ void BattleConsole::showAll(SDL_Surface * to) std::vector BattleConsole::getVisibleText() { // high priority texts that hide battle log entries - for (auto const & text : {consoleText, hoverText} ) + for(const auto & text : {consoleText, hoverText}) { if (text.empty()) continue; @@ -94,7 +94,7 @@ std::vector BattleConsole::splitText(const std::string &text) boost::split(lines, text, boost::is_any_of("\n")); - for (auto const & line : lines) + for(const auto & line : lines) { if (graphics->fonts[FONT_SMALL]->getStringWidth(text) < pos.w) { @@ -679,7 +679,7 @@ int32_t StackQueue::getSiegeShooterIconID() return owner.siegeController->getSiegedTown()->town->faction->getIndex(); } -boost::optional StackQueue::getHoveredUnitIdIfAny() const +std::optional StackQueue::getHoveredUnitIdIfAny() const { for(const auto & stackBox : stackBoxes) { @@ -689,7 +689,7 @@ boost::optional StackQueue::getHoveredUnitIdIfAny() const } } - return boost::none; + return std::nullopt; } StackQueue::StackBox::StackBox(StackQueue * owner): @@ -758,7 +758,7 @@ void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn) } else { - boundUnitID = boost::none; + boundUnitID = std::nullopt; background->colorize(PlayerColor::NEUTRAL); icon->visible = false; icon->setFrame(0); @@ -769,7 +769,7 @@ void StackQueue::StackBox::setUnit(const battle::Unit * unit, size_t turn) } } -boost::optional StackQueue::StackBox::getBoundUnitID() const +std::optional StackQueue::StackBox::getBoundUnitID() const { return boundUnitID; } diff --git a/client/battle/BattleInterfaceClasses.h b/client/battle/BattleInterfaceClasses.h index 00799bf22..c96a3ae69 100644 --- a/client/battle/BattleInterfaceClasses.h +++ b/client/battle/BattleInterfaceClasses.h @@ -166,7 +166,7 @@ class StackQueue : public CIntObject class StackBox : public CIntObject { StackQueue * owner; - boost::optional boundUnitID; + std::optional boundUnitID; bool highlighted = false; public: @@ -178,7 +178,7 @@ class StackQueue : public CIntObject StackBox(StackQueue * owner); void setUnit(const battle::Unit * unit, size_t turn = 0); void toggleHighlight(bool value); - boost::optional getBoundUnitID() const; + std::optional getBoundUnitID() const; void show(SDL_Surface * to) override; }; @@ -197,7 +197,7 @@ public: StackQueue(bool Embedded, BattleInterface & owner); void update(); - boost::optional getHoveredUnitIdIfAny() const; + std::optional getHoveredUnitIdIfAny() const; void show(SDL_Surface * to) override; }; diff --git a/client/battle/BattleObstacleController.cpp b/client/battle/BattleObstacleController.cpp index b29741622..d0f32cdf9 100644 --- a/client/battle/BattleObstacleController.cpp +++ b/client/battle/BattleObstacleController.cpp @@ -66,7 +66,7 @@ void BattleObstacleController::loadObstacleImage(const CObstacleInstance & oi) void BattleObstacleController::obstacleRemoved(const std::vector & obstacles) { - for (auto const & oi : obstacles) + for(const auto & oi : obstacles) { auto & obstacle = oi.data["obstacle"]; @@ -97,11 +97,11 @@ void BattleObstacleController::obstacleRemoved(const std::vector> & obstacles) { - for (auto const & oi : obstacles) + for(const auto & oi : obstacles) { auto side = owner.curInt->cb->playerToSide(owner.curInt->playerID); - if(!oi->visibleForSide(side.get(),owner.curInt->cb->battleHasNativeStack(side.get()))) + if(!oi->visibleForSide(side.value(), owner.curInt->cb->battleHasNativeStack(side.value()))) continue; auto animation = std::make_shared(oi->getAppearAnimation()); diff --git a/client/battle/BattleStacksController.cpp b/client/battle/BattleStacksController.cpp index a63ed5c02..8f6b2a29a 100644 --- a/client/battle/BattleStacksController.cpp +++ b/client/battle/BattleStacksController.cpp @@ -281,7 +281,7 @@ std::shared_ptr BattleStacksController::getStackAmountBox(const CStack * int effectsPositivness = 0; - for ( auto const & spellID : activeSpells) + for(const auto & spellID : activeSpells) effectsPositivness += CGI->spellh->objects.at(spellID)->positiveness; if (effectsPositivness > 0) @@ -336,7 +336,7 @@ void BattleStacksController::showStackAmountBox(Canvas & canvas, const CStack * void BattleStacksController::showStack(Canvas & canvas, const CStack * stack) { ColorFilter fullFilter = ColorFilter::genEmptyShifter(); - for (auto const & filter : stackFilterEffects) + for(const auto & filter : stackFilterEffects) { if (filter.target == stack) fullFilter = ColorFilter::genCombined(fullFilter, filter.effect); @@ -814,7 +814,7 @@ void BattleStacksController::updateHoveredStacks() { auto newStacks = selectHoveredStacks(); - for (auto const * stack : mouseHoveredStacks) + for(const auto * stack : mouseHoveredStacks) { if (vstd::contains(newStacks, stack)) continue; @@ -825,7 +825,7 @@ void BattleStacksController::updateHoveredStacks() stackAnimation[stack->ID]->setBorderColor(AnimationControls::getNoBorder()); } - for (auto const * stack : newStacks) + for(const auto * stack : newStacks) { if (vstd::contains(mouseHoveredStacks, stack)) continue; @@ -848,7 +848,7 @@ std::vector BattleStacksController::selectHoveredStacks() return {}; auto hoveredQueueUnitId = owner.windowObject->getQueueHoveredUnitId(); - if(hoveredQueueUnitId.is_initialized()) + if(hoveredQueueUnitId.has_value()) { return { owner.curInt->cb->battleGetStackByID(hoveredQueueUnitId.value(), true) }; } @@ -889,7 +889,7 @@ std::vector BattleStacksController::selectHoveredStacks() const std::vector BattleStacksController::getHoveredStacksUnitIds() const { auto result = std::vector(); - for (auto const * stack : mouseHoveredStacks) + for(const auto * stack : mouseHoveredStacks) { result.push_back(stack->unitId()); } diff --git a/client/battle/BattleWindow.cpp b/client/battle/BattleWindow.cpp index 91b3dbb04..db15c30ba 100644 --- a/client/battle/BattleWindow.cpp +++ b/client/battle/BattleWindow.cpp @@ -590,7 +590,7 @@ void BattleWindow::blockUI(bool on) } } -boost::optional BattleWindow::getQueueHoveredUnitId() +std::optional BattleWindow::getQueueHoveredUnitId() { return queue->getHoveredUnitIdIfAny(); } diff --git a/client/battle/BattleWindow.h b/client/battle/BattleWindow.h index 3b03c78f5..1d6305a2a 100644 --- a/client/battle/BattleWindow.h +++ b/client/battle/BattleWindow.h @@ -80,7 +80,7 @@ public: void updateQueue(); /// Get mouse-hovered battle queue unit ID if any found - boost::optional getQueueHoveredUnitId(); + std::optional getQueueHoveredUnitId(); void activate() override; void deactivate() override; diff --git a/client/icons/vcmiclient.1024x1024.png b/client/icons/vcmiclient.1024x1024.png index f2c437857..3d5d93ad8 100644 Binary files a/client/icons/vcmiclient.1024x1024.png and b/client/icons/vcmiclient.1024x1024.png differ diff --git a/client/icons/vcmiclient.128x128.png b/client/icons/vcmiclient.128x128.png index 66df22cfe..5a1457b08 100644 Binary files a/client/icons/vcmiclient.128x128.png and b/client/icons/vcmiclient.128x128.png differ diff --git a/client/icons/vcmiclient.16x16.png b/client/icons/vcmiclient.16x16.png new file mode 100644 index 000000000..a4458bd8c Binary files /dev/null and b/client/icons/vcmiclient.16x16.png differ diff --git a/client/icons/vcmiclient.2048x2048.png b/client/icons/vcmiclient.2048x2048.png new file mode 100644 index 000000000..59822f2e5 Binary files /dev/null and b/client/icons/vcmiclient.2048x2048.png differ diff --git a/client/icons/vcmiclient.256x256.png b/client/icons/vcmiclient.256x256.png index 6d2c83cbe..012cd0999 100644 Binary files a/client/icons/vcmiclient.256x256.png and b/client/icons/vcmiclient.256x256.png differ diff --git a/client/icons/vcmiclient.32x32.png b/client/icons/vcmiclient.32x32.png index d50e9fec2..89819f298 100644 Binary files a/client/icons/vcmiclient.32x32.png and b/client/icons/vcmiclient.32x32.png differ diff --git a/client/icons/vcmiclient.48x48.png b/client/icons/vcmiclient.48x48.png index 7f725a2e8..4c6c239af 100644 Binary files a/client/icons/vcmiclient.48x48.png and b/client/icons/vcmiclient.48x48.png differ diff --git a/client/icons/vcmiclient.512x512.png b/client/icons/vcmiclient.512x512.png index 4f236d1ae..8c0b7e4df 100644 Binary files a/client/icons/vcmiclient.512x512.png and b/client/icons/vcmiclient.512x512.png differ diff --git a/client/icons/vcmiclient.64x64.png b/client/icons/vcmiclient.64x64.png index 8363f8ac2..89865281b 100644 Binary files a/client/icons/vcmiclient.64x64.png and b/client/icons/vcmiclient.64x64.png differ diff --git a/client/icons/vcmiclient.psd b/client/icons/vcmiclient.psd deleted file mode 100644 index 8a45174e3..000000000 Binary files a/client/icons/vcmiclient.psd and /dev/null differ diff --git a/client/icons/vcmiclient.svg b/client/icons/vcmiclient.svg new file mode 100644 index 000000000..0d1f01b5b --- /dev/null +++ b/client/icons/vcmiclient.svg @@ -0,0 +1,401 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/icons/vcmiclient.xpm b/client/icons/vcmiclient.xpm index e27e76a6c..ce82b0f95 100644 --- a/client/icons/vcmiclient.xpm +++ b/client/icons/vcmiclient.xpm @@ -1,226 +1,238 @@ /* XPM */ -static char *vcmiclient[] = { +static char *x[] = { /* columns rows colors chars-per-pixel */ -"32 32 188 2 ", -" c #010101", -". c #090909", -"X c #140600", -"o c #180700", -"O c #140A06", -"+ c #1B0901", -"@ c #1E120C", -"# c #161414", -"$ c #1C1C1B", -"% c #220B01", -"& c #2B0E00", -"* c #2E1002", -"= c #2C140A", -"- c #331507", -"; c #341609", -": c #35180B", -"> c #221612", -", c #221915", -"< c #2C1C15", -"1 c #281F1A", -"2 c #351C10", -"3 c #391E11", -"4 c #3D2214", -"5 c #3C2519", -"6 c #252424", -"7 c #2D2D2C", -"8 c #3B2B24", -"9 c #3C302B", -"0 c #343333", -"q c #3F3036", -"w c #393837", -"e c #3D3C3B", -"r c #402215", -"t c #422618", -"y c #442B1E", -"u c #482D1F", -"i c #452D21", -"p c #4A2F21", -"a c #4D3325", -"s c #4E372C", -"d c #503729", -"f c #52392C", -"g c #423433", -"h c #483C35", -"j c #443438", -"k c #443B3E", -"l c #533E32", -"z c #41403F", -"x c #4B433E", -"c c #514037", -"v c #5D4236", -"b c #53433B", -"n c #5E4438", -"m c #634F3F", -"M c #695337", -"N c #67523F", -"B c #6A543D", -"V c #6C583B", -"C c #795F36", -"Z c #725A3E", -"A c #795F3E", -"S c #413741", -"D c #473C46", -"F c #444242", -"G c #4A4845", -"H c #4C4B4B", -"J c #5A4D46", -"K c #54524F", -"L c #5B504C", -"P c #555454", -"I c #5A5956", -"U c #5B5B5B", -"Y c #645143", -"T c #6B5544", -"R c #6F5A45", -"E c #65544C", -"W c #6D564B", -"Q c #6A594F", -"! c #735D46", -"~ c #6B5655", -"^ c #6D5A53", -"/ c #655D58", -"( c #6C595B", -") c #755E56", -"_ c #735F59", -"` c #796143", -"' c #75624E", -"] c #7B624C", -"[ c #67625D", -"{ c #7B6356", -"} c #71645E", -"| c #7B665A", -" . c #7E695E", -".. c #715E60", -"X. c #656362", -"o. c #6A6762", -"O. c #6D6A66", -"+. c #6A6168", -"@. c #6D6B6B", -"#. c #726C67", -"$. c #726E6A", -"%. c #76726F", -"&. c #79726D", -"*. c #716F70", -"=. c #747473", -"-. c #7B7671", -";. c #7D7976", -":. c #7E7D7B", -">. c #80673C", -",. c #8D713F", -"<. c #9F7E37", -"1. c #816843", -"2. c #886D41", -"3. c #927745", -"4. c #826B5E", -"5. c #836E62", -"6. c #877166", -"7. c #887266", -"8. c #8B756A", -"9. c #8F796E", -"0. c #907A6F", -"q. c #857A73", -"w. c #827E79", -"e. c #927D73", -"r. c #A38234", -"t. c #A58439", -"y. c #AF8B3E", -"u. c #B08E39", -"i. c #BD9738", -"p. c #E3B101", -"a. c #CAA021", -"s. c #CEA43F", -"d. c #E4B437", -"f. c #E4B53E", -"g. c #F4C23D", -"h. c #A28343", -"j. c #A88741", -"k. c #B39040", -"l. c #BF9940", -"z. c #86837E", -"x. c #948177", -"c. c #94867E", -"v. c #99847A", -"b. c #9D897E", -"n. c #BE9C6E", -"m. c #D3AB6D", -"M. c #E3B76C", -"N. c #F0C26B", -"B. c #F0C273", -"V. c #858482", -"C. c #888682", -"Z. c #8C8985", -"A. c #8E8D8D", -"S. c #928C86", -"D. c #918F8C", -"F. c #95918D", -"G. c #959492", -"H. c #9A9792", -"J. c #9B9995", -"K. c #9E9B99", -"L. c #A18D82", -"P. c #A39086", -"I. c #A6948A", -"U. c #A9968C", -"Y. c #AB988E", -"T. c #AF9C92", -"R. c #A19E9A", -"E. c #A4A29E", -"W. c #B4A298", -"Q. c #A5A4A1", -"!. c #A9A7A3", -"~. c #ACA9A6", -"^. c #ADACAB", -"/. c #B1AEAB", -"(. c #B2B0AD", -"). c #B5B4B2", -"_. c #BAB9B7", -"`. c #BDBCBB", -"'. c #C4C3C3", -"]. c #C8C8C8", -"[. c #D1D0CE", -"{. c #D4D3D3", -"}. c #DADADA", -"|. c #E8E7E6", -" X c #EBEBEA", -".X c gray96", -"XX c #FDFDFC", -"oX c None", +"32 32 200 2 ", +" c gray11", +". c #161616", +"X c #2C0E00", +"o c #2D1003", +"O c #25140C", +"+ c #28130A", +"@ c #311305", +"# c #331609", +"$ c #34190C", +"% c #391C0D", +"& c #241610", +"* c #241A16", +"= c #251E1A", +"- c #2C1C14", +"; c #391E11", +": c #2A241D", +"> c #20201F", +", c #3D2112", +"< c #38231B", +"1 c #3C351E", +"2 c #242323", +"3 c #2C2B2B", +"4 c #282625", +"5 c #332E20", +"6 c #362D29", +"7 c #302620", +"8 c #363122", +"9 c #3C3521", +"0 c #3E352C", +"q c #36302D", +"w c #353433", +"e c #3D3B3B", +"r c #3B3431", +"t c #412516", +"y c #462A1B", +"u c #492E1E", +"i c #45271B", +"p c #443A1B", +"a c #4A3F1C", +"s c #4A2F20", +"d c #4D3323", +"f c #423B24", +"g c #48372E", +"h c #483F25", +"j c #503627", +"k c #513728", +"l c #543B2C", +"z c #593D2F", +"x c #483D37", +"c c #473C37", +"v c #573E30", +"b c #583F31", +"n c #5A4C1D", +"m c #63531C", +"M c #6F5C18", +"N c #725D13", +"B c #7D6515", +"V c #4E4426", +"C c #514623", +"Z c #44423F", +"A c #5C4234", +"S c #5A4438", +"D c #625220", +"F c #6C5A24", +"G c #6B5A29", +"H c #715E26", +"J c #674D3F", +"K c #604537", +"L c #7A6525", +"P c #746129", +"I c #444242", +"U c #494645", +"Y c #4C4B4A", +"T c #4A4845", +"R c #554A46", +"E c #5B4D45", +"W c #514742", +"Q c #555352", +"! c #595757", +"~ c #5D5B5A", +"^ c #694E40", +"/ c #6B5549", +"( c #775D4F", +") c #705648", +"_ c #6B5F58", +"` c #755E52", +"' c #62605E", +"] c #7E6557", +"[ c #7A665A", +"{ c #666564", +"} c #696766", +"| c #6D6B6A", +" . c #6A6865", +".. c #7B6B62", +"X. c #726D69", +"o. c #7A7674", +"O. c #7D7B7B", +"+. c #767471", +"@. c #95750A", +"#. c #98770A", +"$. c #846B1B", +"%. c #876D17", +"&. c #8E731E", +"*. c #93761D", +"=. c #96781C", +"-. c #9B7B10", +";. c #A07F0F", +":. c #A07D10", +">. c #836C22", +",. c #866F29", +"<. c #8C7324", +"1. c #997D22", +"2. c #967A28", +"3. c #826A5D", +"4. c #80675A", +"5. c #856D60", +"6. c #897164", +"7. c #8C7569", +"8. c #8F786C", +"9. c #927C6F", +"0. c #827D79", +"q. c #937E72", +"w. c #A7840F", +"e. c #AE8A16", +"r. c #A5831A", +"t. c #B08C1C", +"y. c #B79015", +"u. c #BD961A", +"i. c #A88825", +"p. c #B08E23", +"a. c #BB9624", +"s. c #BB9626", +"d. c #C69D1B", +"f. c #C29B22", +"g. c #C29C2A", +"h. c #CCA220", +"j. c #CDA42A", +"k. c #D9AD26", +"l. c #D2A726", +"z. c #E6B726", +"x. c #86827D", +"c. c #8A847F", +"v. c #978175", +"b. c #94867D", +"n. c #9B867A", +"m. c #9E897D", +"M. c #998377", +"N. c #848383", +"B. c #8A8680", +"V. c #8F8B86", +"C. c #9B8D85", +"Z. c #938E89", +"A. c #918984", +"S. c #96928E", +"D. c #9A9693", +"F. c #9C9996", +"G. c #9D9B99", +"H. c #939292", +"J. c #A28E82", +"K. c #A69287", +"L. c #A5948A", +"P. c #AC988D", +"I. c #A9958A", +"U. c #A69C96", +"Y. c #AD9C93", +"T. c #A29D99", +"R. c #A89F99", +"E. c #B19E93", +"W. c #A5A29F", +"Q. c #B3A196", +"!. c #B8A69C", +"~. c #B9A69C", +"^. c #A4A3A2", +"/. c #A9A6A3", +"(. c #ADABA9", +"). c #ABA8A5", +"_. c #BCABA1", +"`. c #B2AEAC", +"'. c #B5A9A3", +"]. c #B3B2AF", +"[. c #B3B2B2", +"{. c #B9B5B3", +"}. c #BAB9B9", +"|. c #BBB9B6", +" X c #C0AFA5", +".X c #C4B3AA", +"XX c #C8B8AE", +"oX c #C1BFBE", +"OX c #CDBDB4", +"+X c #CCC9C7", +"@X c #CFCCCB", +"#X c #C5C3C1", +"$X c #D3D1CF", +"%X c #D6D3D2", +"&X c #DDDBDA", +"*X c #EDECEB", +"=X c #E4E3E3", +"-X c #F3F3F3", +";X c #F9F9F9", +":X c None", /* pixels */ -"oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoX0 I 0 oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXw H oXoXoXoX", -"oXoXoXoX'.'.'.`.Q.D.:.+.P F F 6 6 w e H I @.:.Z.K.E.R.H.$.oXoXoX", -"oXoXoXoX).).`.`.`._.)./.(.(.(.(.(./.~.!.E.R.H.G.D.Z.S.C.o.oXoXoX", -"oXoXoXoXV.A.G.*.Z.K.^.).).^.~.Q.Q.E.K.K.J.F.C.-.$.$.S.S.K oXoXoX", -"oXoXoXoXX.@.P & : f E } #.&.q.&.-.&.&.&.&.q.c.I.W.S.z.G.w oXoXoX", -"oXoXoXoXH X.H = & * r n { 5.7.8.0.x.v.b.L.P.I.Y.T.q.G.H.$ oXoXoX", -"oXoXoXoX7 X.H = * & & : a W 5.6.7.9.x.x.x.L.L.I.U.q.R.F.oXoXoXoX", -"oXoXoXoXoXX.F , * & & & * 3 l { 5.6.8.0.x.x.b.L.P.-.Q.;.oXoXoXoX", -"oXoXoXoXoXI e 1 & & & & & & ; p T | .5.8.0.0.x.x.V.Q.U oXoXoXoX", -"oXoXoXoX F 0 # o & % o o o o & 3 8 g h ^ 5.J b x C.G.$ oXoXoXoX", -"oXoXoXB.4.7 6 B.{ % X N.g.g.] o % { g.B.g Q 4.g.B.U U B.4.oXoXoX", -"oXoXoXf.>.. $ d.` + M.y.A C f.) % A p.d.> 9 1.p.f.e e f.1.oXoXoX", -"oXoXoX| s._ m.h.k @ s.Z + o ) g + Z a.<.m._ s.t.s.7 6 s.] oXoXoX", -"oXoXoX i.V i.' k > l.B = % o o % B l.B i.M l.R l.6 . i.! oXoXoX", -"oXoXoXoX_ u.3.+.C.1 k.B @ O n.^ % N y.g ,.u.Q N y.$ k.! oXoXoX", -"oXoXoXoX j.Y '.}.F ^ j.j.t.2.j % Y j.o m j.X J j.. j.W oXoXoX", -"oXoXoXoXoX..S Q..XK.< ( Y Y k 5 2 j ~ o q ~ O S ( oX..D oXoXoX", -"oXoXoXoXoXoXoXK |.{.b i i y y i y 5 : * & & , 7 6 oXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoX_.[.&.a d a a a p p y 4 - - F e $ oXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoX@.(.H.c f d d a a p p u t L G.*.oXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXE.E./ f f d d a a a a c ].}.*.oXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXo.G.C.b f f f s d a s R.XX XoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXZ.Z.#.c f f f d f $.{. X=.oXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXe z.w.O.c l f l [ E.).K.oXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXP -.&.&.o.o.;.G.J.D.oXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXK $.$.%.-.z.z.w.$ oXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXoX7 I o.O.$.G oXoXoXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX# oXoXoXoXoXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX", -"oXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoXoX" +":X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X", +":X:X:XO.V.| Q :X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:XZ Q ' T :X:X", +":X:XI G.(.}.}.}.(.^.H.N.O.| } ~ ! ' { { } X.o.0.B.x.x.x.x.x.:X:X", +":X:X3 N.H.^.[.}.}.}.}.}.}.}.}.[.`.(./.^.T.T.D.S.Z.V.B.x.x.o.:X:X", +":X:X:X| O. .^ ..b.D./.[.{.}.}.}.{.[.`.(.^.F.S.D.W.'.'.c.c.' :X:X", +":X:X:X! { c % s b ^ ( 5.7.q.b.C.C.L.L.I.Y.E.~. X XXXOXZ.V.~ :X:X", +":X:X:XU ~ c X @ t j K ) [ 3.6.7.q.b.n.J.L.P.E.E.~. XXXZ.D.Y :X:X", +":X:X:Xw Q Z X X X % y v ^ ( ] 5.6.8.q.M.C.J.I.E.Q.~.~.F.F.:X:X:X", +":X:X:X4 Y U X X X X @ t d A ) ] 3.6.7.9.q.n.J.K.P.E.W.W.D.:X:X:X", +":X:X:X:XI U @ X X X X X % i z ^ ( 4.3.6.8.q.M.n.m.I.U.(.x.:X:X:X", +":X . w 3 * + X + O & & & - d K g x Z ^ 7...U E R N.N.e :X:X", +":XG j.9 2 ,.s.* + = s.j.j.j.P * i F j.j.0 [ R i.l.i.' Y g.2.:X:X", +":XH z.f 2 2.k.* * p.f.,.,.2.l.G X L z.z.8 x q p.z.s.{ Y k.i.:X:X", +":Xh i.f.>.d.L : = h.1.O X : L V X H k.p.a.4 <.f.a.p.{ e h.1.:X:X", +":X:XF d.<.d.w k = d.&.+ X X X X o F d.B d.2 <.t.<.r.{ w u.*.:X:X", +":X:XF y.$.y.I ' : e.$.- # & = * X D y.V =.e.e.D %.=.{ 2 e.$.:X:X", +":X:X9 %.w.n Q G.: -.B : : 1 w.n X n w.: M w.-.2 B %.Y > -.B :X:X", +":X:X:Xm #. -X-X6 a @.@.@.#.M 5 o n @.: 1 a a = N B w @.N :X:X", +":X:X:X8 a #X;XC.7 p p p p 8 , # 8 p * X X X + 1 p p 9 :X:X", +":X:X:X:X:X:XO.*X@Xk d h u u u y t % # o X X X < Q Y :X:X:X:X:X:X", +":X:X:X:X:X:X:X&X*X[ d j j d s u u t , % @ o X r Y 3 :X:X:X:X:X:X", +":X:X:X:X:X:X:XF.&XW.z k k j j s d u y , , # - c I :X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X$X%X/ z l k k d d d u u t , 6 w 3 :X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:XF.@XT.v l l l k d d d d u S .Y :X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:XI |.#X..A z l l k j j d v F.F.! :X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:XO.{.]./ A z l z l j z {.=X}.:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:XF.].).` A A z l S `.-X;XO.:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:Xe G.).].V.....b.$X=X*X^.:X:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:X:XT D.W.(.{.}.+X%X&X/.:X:X:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:X:X:Xe x.T./.].|.}.O.:X:X:X:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:X:X:X:X:XY | o. .:X:X:X:X:X:X:X:X:X:X:X:X:X:X", +":X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X:X" }; diff --git a/client/ios/vcmi_logo.png b/client/ios/vcmi_logo.png index 1762c14aa..73d432480 100644 Binary files a/client/ios/vcmi_logo.png and b/client/ios/vcmi_logo.png differ diff --git a/client/vcmi.ico b/client/vcmi.ico index 40818c464..2c27331dd 100644 Binary files a/client/vcmi.ico and b/client/vcmi.ico differ diff --git a/client/widgets/Buttons.cpp b/client/widgets/Buttons.cpp index bb1553fd6..10cabfd99 100644 --- a/client/widgets/Buttons.cpp +++ b/client/widgets/Buttons.cpp @@ -57,15 +57,15 @@ void CButton::update() redraw(); } -void CButton::setBorderColor(boost::optional borderColor) +void CButton::setBorderColor(std::optional borderColor) { setBorderColor(borderColor, borderColor, borderColor, borderColor); } -void CButton::setBorderColor(boost::optional normalBorderColor, - boost::optional pressedBorderColor, - boost::optional blockedBorderColor, - boost::optional highlightedBorderColor) +void CButton::setBorderColor(std::optional normalBorderColor, + std::optional pressedBorderColor, + std::optional blockedBorderColor, + std::optional highlightedBorderColor) { stateToBorderColor[NORMAL] = normalBorderColor; stateToBorderColor[PRESSED] = pressedBorderColor; @@ -591,7 +591,7 @@ void CSlider::setScrollBounds(const Rect & bounds ) void CSlider::clearScrollBounds() { - scrollBounds = boost::none; + scrollBounds = std::nullopt; } int CSlider::getAmount() const diff --git a/client/widgets/Buttons.h b/client/widgets/Buttons.h index da5677cef..67665cfbd 100644 --- a/client/widgets/Buttons.h +++ b/client/widgets/Buttons.h @@ -52,7 +52,7 @@ private: std::array stateToIndex; // mapping of button state to index of frame in animation std::array hoverTexts; //texts for statusbar, if empty - first entry will be used - std::array, 4> stateToBorderColor; // mapping of button state to border color + std::array, 4> stateToBorderColor; // mapping of button state to border color std::string helpBox; //for right-click help std::shared_ptr image; //image for this button @@ -73,13 +73,13 @@ public: // sets border color for each button state; // if it's set, the button will have 1-px border around it with this color - void setBorderColor(boost::optional normalBorderColor, - boost::optional pressedBorderColor, - boost::optional blockedBorderColor, - boost::optional highlightedBorderColor); + void setBorderColor(std::optional normalBorderColor, + std::optional pressedBorderColor, + std::optional blockedBorderColor, + std::optional highlightedBorderColor); // sets the same border color for all button states. - void setBorderColor(boost::optional borderColor); + void setBorderColor(std::optional borderColor); /// adds one more callback to on-click actions void addCallback(std::function callback); @@ -229,7 +229,7 @@ class CSlider : public CIntObject std::shared_ptr right; std::shared_ptr slider; - boost::optional scrollBounds; + std::optional scrollBounds; int capacity;//how many elements can be active at same time (e.g. hero list = 5) int positions; //number of highest position (0 if there is only one) diff --git a/client/widgets/Images.cpp b/client/widgets/Images.cpp index 232406593..77e27e651 100644 --- a/client/widgets/Images.cpp +++ b/client/widgets/Images.cpp @@ -85,7 +85,7 @@ void CPicture::show(SDL_Surface * to) void CPicture::showAll(SDL_Surface * to) { if(bg && visible) - bg->draw(to, pos.x, pos.y, srcRect.get_ptr()); + bg->draw(to, pos.x, pos.y, srcRect.has_value() ? &srcRect.value() : nullptr); } void CPicture::setAlpha(int value) diff --git a/client/widgets/Images.h b/client/widgets/Images.h index c7928fd1e..cac867b05 100644 --- a/client/widgets/Images.h +++ b/client/widgets/Images.h @@ -30,7 +30,7 @@ class CPicture : public CIntObject public: /// if set, only specified section of internal image will be rendered - boost::optional srcRect; + std::optional srcRect; /// If set to true, iamge will be redrawn on each frame bool needRefresh; diff --git a/client/windows/CCreatureWindow.cpp b/client/windows/CCreatureWindow.cpp index beda2681d..1ef1f9672 100644 --- a/client/windows/CCreatureWindow.cpp +++ b/client/windows/CCreatureWindow.cpp @@ -64,9 +64,9 @@ public: const CGHeroInstance * owner; // temporary objects which should be kept as copy if needed - boost::optional levelupInfo; - boost::optional dismissInfo; - boost::optional upgradeInfo; + std::optional levelupInfo; + std::optional dismissInfo; + std::optional upgradeInfo; // misc fields unsigned int creatureCount; @@ -246,8 +246,8 @@ CStackWindow::BonusLineSection::BonusLineSection(CStackWindow * owner, size_t li } } -CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, boost::optional preferredSize) - : CWindowSection(owner, "", yOffset) +CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, std::optional preferredSize): + CWindowSection(owner, "", yOffset) { OBJECT_CONSTRUCTION_CAPTURING(255-DISPOSE); @@ -255,7 +255,7 @@ CStackWindow::BonusesSection::BonusesSection(CStackWindow * owner, int yOffset, static const int itemHeight = 59; size_t totalSize = (owner->activeBonuses.size() + 1) / 2; - size_t visibleSize = preferredSize ? preferredSize.get() : std::min(3, totalSize); + size_t visibleSize = preferredSize.value_or(std::min(3, totalSize)); pos.w = owner->pos.w; pos.h = itemHeight * (int)visibleSize; @@ -292,7 +292,7 @@ CStackWindow::ButtonsSection::ButtonsSection(CStackWindow * owner, int yOffset) // used space overlaps with commander switch button // besides - should commander really be upgradeable? - UnitView::StackUpgradeInfo & upgradeInfo = parent->info->upgradeInfo.get(); + auto & upgradeInfo = parent->info->upgradeInfo.value(); const size_t buttonsToCreate = std::min(upgradeInfo.info.newID.size(), upgrade.size()); for(size_t buttonIndex = 0; buttonIndex < buttonsToCreate; buttonIndex++) @@ -686,8 +686,8 @@ CStackWindow::CStackWindow(const CStackInstance * stack, std::function d info->creature = stack->type; info->creatureCount = stack->count; - info->upgradeInfo = boost::make_optional(UnitView::StackUpgradeInfo()); - info->dismissInfo = boost::make_optional(UnitView::StackDismissInfo()); + info->upgradeInfo = std::make_optional(UnitView::StackUpgradeInfo()); + info->dismissInfo = std::make_optional(UnitView::StackDismissInfo()); info->upgradeInfo->info = upgradeInfo; info->upgradeInfo->callback = callback; info->dismissInfo->callback = dismiss; @@ -716,7 +716,7 @@ CStackWindow::CStackWindow(const CCommanderInstance * commander, std::vectorcreature = commander->type; info->commander = commander; info->creatureCount = 1; - info->levelupInfo = boost::make_optional(UnitView::CommanderLevelInfo()); + info->levelupInfo = std::make_optional(UnitView::CommanderLevelInfo()); info->levelupInfo->skills = skills; info->levelupInfo->callback = callback; info->owner = dynamic_cast (commander->armyObj); @@ -814,7 +814,7 @@ void CStackWindow::initSections() commanderMainSection = std::make_shared(this, 0); - auto size = boost::make_optional((info->levelupInfo) ? 4 : 3); + auto size = std::make_optional((info->levelupInfo) ? 4 : 3); commanderBonusesSection = std::make_shared(this, 0, size); deactivateObj(commanderBonusesSection); diff --git a/client/windows/CCreatureWindow.h b/client/windows/CCreatureWindow.h index ef51b57b8..adf714e8c 100644 --- a/client/windows/CCreatureWindow.h +++ b/client/windows/CCreatureWindow.h @@ -83,7 +83,7 @@ class CStackWindow : public CWindowObject { std::shared_ptr lines; public: - BonusesSection(CStackWindow * owner, int yOffset, boost::optional preferredSize = boost::optional()); + BonusesSection(CStackWindow * owner, int yOffset, std::optional preferredSize = std::optional()); }; class ButtonsSection : public CWindowSection diff --git a/lib/CArtHandler.cpp b/lib/CArtHandler.cpp index 2b6da96a7..043240a0b 100644 --- a/lib/CArtHandler.cpp +++ b/lib/CArtHandler.cpp @@ -740,15 +740,28 @@ void CArtHandler::erasePickedArt(const ArtifactID & id) { CArtifact *art = objects[id]; - if(auto artifactList = listFromClass(art->aClass)) + if(!(art->aClass & CArtifact::ART_SPECIAL)) { - if(artifactList->empty()) - fillList(*artifactList, art->aClass); - - auto itr = vstd::find(*artifactList, art); - if(itr != artifactList->end()) + auto & artifactList = treasures; + switch(art->aClass) { - artifactList->erase(itr); + case CArtifact::ART_MINOR: + artifactList = minors; + break; + case CArtifact::ART_MAJOR: + artifactList = majors; + break; + case CArtifact::ART_RELIC: + artifactList = relics; + break; + } + if(artifactList.empty()) + fillList(artifactList, art->aClass); + + auto itr = vstd::find(artifactList, art); + if(itr != artifactList.end()) + { + artifactList.erase(itr); } else logMod->warn("Problem: cannot erase artifact %s from list, it was not present", art->getNameTranslated()); @@ -758,23 +771,6 @@ void CArtHandler::erasePickedArt(const ArtifactID & id) logMod->warn("Problem: cannot find list for artifact %s, strange class. (special?)", art->getNameTranslated()); } -boost::optional&> CArtHandler::listFromClass( CArtifact::EartClass artifactClass ) -{ - switch(artifactClass) - { - case CArtifact::ART_TREASURE: - return treasures; - case CArtifact::ART_MINOR: - return minors; - case CArtifact::ART_MAJOR: - return majors; - case CArtifact::ART_RELIC: - return relics; - default: //special artifacts should not be erased - return boost::optional&>(); - } -} - void CArtHandler::fillList( std::vector &listToBeFilled, CArtifact::EartClass artifactClass ) { assert(listToBeFilled.empty()); diff --git a/lib/CArtHandler.h b/lib/CArtHandler.h index 8f669c32c..90d1a0d81 100644 --- a/lib/CArtHandler.h +++ b/lib/CArtHandler.h @@ -244,8 +244,6 @@ public: void fillList(std::vector &listToBeFilled, CArtifact::EartClass artifactClass); //fills given empty list with allowed artifacts of given class. No side effects - boost::optional&> listFromClass(CArtifact::EartClass artifactClass); - static CArtifact::EartClass stringToClass(const std::string & className); //TODO: rework EartClass to make this a constructor /// Gets a artifact ID randomly and removes the selected artifact from this handler. diff --git a/lib/CCreatureHandler.cpp b/lib/CCreatureHandler.cpp index 7a60ea483..030b979b1 100644 --- a/lib/CCreatureHandler.cpp +++ b/lib/CCreatureHandler.cpp @@ -408,7 +408,7 @@ CCreatureHandler::CCreatureHandler() const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const { - boost::optional index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier); + std::optional index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier); if(!index) throw std::runtime_error("Creature not found "+identifier); diff --git a/lib/CCreatureSet.cpp b/lib/CCreatureSet.cpp index f44478ac0..0f26f84ed 100644 --- a/lib/CCreatureSet.cpp +++ b/lib/CCreatureSet.cpp @@ -624,7 +624,7 @@ void CCreatureSet::armyChanged() } -void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const boost::optional fixedSize) +void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const std::optional fixedSize) { if(handler.saving && stacks.empty()) return; @@ -640,7 +640,7 @@ void CCreatureSet::serializeJson(JsonSerializeFormat & handler, const std::strin vstd::amax(sz, p.first.getNum()+1); if(fixedSize) - vstd::amax(sz, fixedSize.get()); + vstd::amax(sz, fixedSize.value()); a.resize(sz, JsonNode::JsonType::DATA_STRUCT); diff --git a/lib/CCreatureSet.h b/lib/CCreatureSet.h index 9fee73321..2530e8b5c 100644 --- a/lib/CCreatureSet.h +++ b/lib/CCreatureSet.h @@ -75,7 +75,7 @@ public: uint8_t upgrade; }; // helper variable used during loading map, when object (hero or town) have creatures that must have same alignment. - boost::optional randomStack; + std::optional randomStack; const CArmedInstance * const & armyObj; //stack must be part of some army, army must be part of some object TExpType experience;//commander needs same amount of exp as hero @@ -286,7 +286,7 @@ public: h & formation; } - void serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const boost::optional fixedSize = boost::none); + void serializeJson(JsonSerializeFormat & handler, const std::string & fieldName, const std::optional fixedSize = std::nullopt); operator bool() const { diff --git a/lib/CGameInfoCallback.cpp b/lib/CGameInfoCallback.cpp index 3e6e8a4ed..c5b99e81d 100644 --- a/lib/CGameInfoCallback.cpp +++ b/lib/CGameInfoCallback.cpp @@ -401,7 +401,7 @@ int CGameInfoCallback::getDate(Date::EDateType mode) const return gs->getDate(mode); } -bool CGameInfoCallback::isVisible(int3 pos, const boost::optional & Player) const +bool CGameInfoCallback::isVisible(int3 pos, const std::optional & Player) const { //boost::shared_lock lock(*gs->mx); return gs->isVisible(pos, Player); @@ -412,7 +412,7 @@ bool CGameInfoCallback::isVisible(int3 pos) const return isVisible(pos, player); } -bool CGameInfoCallback::isVisible( const CGObjectInstance *obj,const boost::optional & Player) const +bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional & Player) const { return gs->isVisible(obj, Player); } @@ -521,8 +521,8 @@ EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) cons //TODO: typedef? std::shared_ptr> CGameInfoCallback::getAllVisibleTiles() const { - assert(player.is_initialized()); - const auto * team = getPlayerTeam(player.get()); + assert(player.has_value()); + const auto * team = getPlayerTeam(player.value()); size_t width = gs->map->width; size_t height = gs->map->height; @@ -619,9 +619,9 @@ const CMapHeader * CGameInfoCallback::getMapHeader() const return gs->map; } -bool CGameInfoCallback::hasAccess(boost::optional playerId) const +bool CGameInfoCallback::hasAccess(std::optional playerId) const { - return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES; + return !player || player->isSpectator() || gs->getPlayerRelations(*playerId, *player) != PlayerRelations::ENEMIES; } EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const @@ -703,7 +703,7 @@ PlayerColor CGameInfoCallback::getCurrentPlayer() const return gs->currentPlayer; } -CGameInfoCallback::CGameInfoCallback(CGameState * GS, boost::optional Player): +CGameInfoCallback::CGameInfoCallback(CGameState * GS, std::optional Player): gs(GS) { player = std::move(Player); @@ -754,7 +754,7 @@ std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo return ret; } -boost::optional CPlayerSpecificInfoCallback::getMyColor() const +std::optional CPlayerSpecificInfoCallback::getMyColor() const { return player; } @@ -882,7 +882,7 @@ const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const if (team != gs->teams.end()) { const TeamState *ret = &team->second; - if (!player.is_initialized()) //neutral (or invalid) player + if(!player.has_value()) //neutral (or invalid) player return ret; else { diff --git a/lib/CGameInfoCallback.h b/lib/CGameInfoCallback.h index 9d23c4965..dfb586f10 100644 --- a/lib/CGameInfoCallback.h +++ b/lib/CGameInfoCallback.h @@ -133,8 +133,8 @@ protected: CGameState * gs;//todo: replace with protected const getter, only actual Server and Client objects should hold game state CGameInfoCallback() = default; - CGameInfoCallback(CGameState *GS, boost::optional Player); - bool hasAccess(boost::optional playerId) const; + CGameInfoCallback(CGameState * GS, std::optional Player); + bool hasAccess(std::optional playerId) const; bool canGetFullInfo(const CGObjectInstance *obj) const; //true we player owns obj or ally owns obj or privileged mode bool isOwnedOrVisited(const CGObjectInstance *obj) const; @@ -157,9 +157,9 @@ public: virtual const PlayerSettings * getPlayerSettings(PlayerColor color) const; //map - virtual bool isVisible(int3 pos, const boost::optional & Player) const; - virtual bool isVisible(const CGObjectInstance *obj, const boost::optional & Player) const; - virtual bool isVisible(const CGObjectInstance *obj) const; + virtual bool isVisible(int3 pos, const std::optional & Player) const; + virtual bool isVisible(const CGObjectInstance * obj, const std::optional & Player) const; + virtual bool isVisible(const CGObjectInstance * obj) const; virtual bool isVisible(int3 pos) const; @@ -234,7 +234,7 @@ public: virtual int howManyTowns() const; virtual int howManyHeroes(bool includeGarrisoned = true) const; virtual int3 getGrailPos(double *outKnownRatio); - virtual boost::optional getMyColor() const; + virtual std::optional getMyColor() const; virtual std::vector getTownsInfo(bool onlyOur = true) const; //true -> only owned; false -> all visible virtual int getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned=true) const; diff --git a/lib/CGameInterface.h b/lib/CGameInterface.h index 8f0d8ff2d..da736d90e 100644 --- a/lib/CGameInterface.h +++ b/lib/CGameInterface.h @@ -110,9 +110,9 @@ public: virtual void showWorldViewEx(const std::vector & objectPositions, bool showTerrain){}; - virtual boost::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) + virtual std::optional makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState) { - return boost::none; + return std::nullopt; } virtual void saveGame(BinarySerializer & h, const int version) = 0; diff --git a/lib/CGameState.cpp b/lib/CGameState.cpp index 4284c334f..980389161 100644 --- a/lib/CGameState.cpp +++ b/lib/CGameState.cpp @@ -925,7 +925,7 @@ void CGameState::initNewGame(const CMapService * mapService, bool allowSavingRan void CGameState::initCampaign() { - logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.get()); + logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.value()); map = scenarioOps->campState->getMap(); } @@ -1068,7 +1068,7 @@ void CGameState::placeCampaignHeroes() { // place bonus hero auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap(); - bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO; + bool campaignGiveHero = campaignBonus && campaignBonus->type == CScenarioTravel::STravelBonus::HERO; if(campaignGiveHero) { @@ -1566,7 +1566,7 @@ void CGameState::initHeroes() void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero) { - const boost::optional & curBonus = scenarioOps->campState->getBonusForCurrentMap(); + const std::optional & curBonus = scenarioOps->campState->getBonusForCurrentMap(); if(!curBonus) return; @@ -2237,7 +2237,7 @@ void CGameState::updateRumor() while(!rumor.update(rumorId, rumorExtra)); } -bool CGameState::isVisible(int3 pos, const boost::optional & player) const +bool CGameState::isVisible(int3 pos, const std::optional & player) const { if (!map->isInTheMap(pos)) return false; @@ -2251,7 +2251,7 @@ bool CGameState::isVisible(int3 pos, const boost::optional & player return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y]; } -bool CGameState::isVisible( const CGObjectInstance *obj, const boost::optional & player) const +bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional & player) const { if(!player) return true; @@ -2436,7 +2436,7 @@ bool CGameState::checkForVictory(const PlayerColor & player, const EventConditio case EventCondition::DAYS_WITHOUT_TOWN: { if (p->daysWithoutCastle) - return p->daysWithoutCastle.get() >= condition.value; + return p->daysWithoutCastle >= condition.value; else return false; } diff --git a/lib/CGameState.h b/lib/CGameState.h index 882c776be..92c7427e8 100644 --- a/lib/CGameState.h +++ b/lib/CGameState.h @@ -202,9 +202,8 @@ public: void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild std::map > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns - - bool isVisible(int3 pos, const boost::optional & player) const override; - bool isVisible(const CGObjectInstance *obj, const boost::optional & player) const override; + bool isVisible(int3 pos, const std::optional & player) const override; + bool isVisible(const CGObjectInstance * obj, const std::optional & player) const override; int getDate(Date::EDateType mode=Date::DAY) const override; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month diff --git a/lib/CModHandler.cpp b/lib/CModHandler.cpp index 17ab1c134..410e0ac47 100644 --- a/lib/CModHandler.cpp +++ b/lib/CModHandler.cpp @@ -156,7 +156,7 @@ void CIdentifierStorage::tryRequestIdentifier(const std::string & type, const Js requestIdentifier(ObjectCallback::fromNameAndType(name.meta, type, name.String(), callback, true)); } -boost::optional CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) +std::optional CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent) { auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(scope, type, name, std::function(), silent)); @@ -165,10 +165,10 @@ boost::optional CIdentifierStorage::getIdentifier(const std::string & scop if (!silent) logMod->error("Failed to resolve identifier %s of type %s from mod %s", name , type ,scope); - return boost::optional(); + return std::optional(); } -boost::optional CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) +std::optional CIdentifierStorage::getIdentifier(const std::string & type, const JsonNode & name, bool silent) { auto idList = getPossibleIdentifiers(ObjectCallback::fromNameAndType(name.meta, type, name.String(), std::function(), silent)); @@ -177,10 +177,10 @@ boost::optional CIdentifierStorage::getIdentifier(const std::string & type if (!silent) logMod->error("Failed to resolve identifier %s of type %s from mod %s", name.String(), type, name.meta); - return boost::optional(); + return std::optional(); } -boost::optional CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) +std::optional CIdentifierStorage::getIdentifier(const JsonNode & name, bool silent) { auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(name.meta, name.String(), std::function(), silent)); @@ -189,10 +189,10 @@ boost::optional CIdentifierStorage::getIdentifier(const JsonNode & name, b if (!silent) logMod->error("Failed to resolve identifier %s from mod %s", name.String(), name.meta); - return boost::optional(); + return std::optional(); } -boost::optional CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) +std::optional CIdentifierStorage::getIdentifier(const std::string & scope, const std::string & fullName, bool silent) { auto idList = getPossibleIdentifiers(ObjectCallback::fromNameWithType(scope, fullName, std::function(), silent)); @@ -201,7 +201,7 @@ boost::optional CIdentifierStorage::getIdentifier(const std::string & scop if (!silent) logMod->error("Failed to resolve identifier %s from mod %s", fullName, scope); - return boost::optional(); + return std::optional(); } void CIdentifierStorage::registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier) diff --git a/lib/CModHandler.h b/lib/CModHandler.h index 92eb9748e..e1a8bdec2 100644 --- a/lib/CModHandler.h +++ b/lib/CModHandler.h @@ -99,10 +99,10 @@ public: void tryRequestIdentifier(const std::string & type, const JsonNode & name, const std::function & callback); /// get identifier immediately. If identifier is not know and not silent call will result in error message - boost::optional getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent = false); - boost::optional getIdentifier(const std::string & type, const JsonNode & name, bool silent = false); - boost::optional getIdentifier(const JsonNode & name, bool silent = false); - boost::optional getIdentifier(const std::string & scope, const std::string & fullName, bool silent = false); + std::optional getIdentifier(const std::string & scope, const std::string & type, const std::string & name, bool silent = false); + std::optional getIdentifier(const std::string & type, const JsonNode & name, bool silent = false); + std::optional getIdentifier(const JsonNode & name, bool silent = false); + std::optional getIdentifier(const std::string & scope, const std::string & fullName, bool silent = false); /// registers new object void registerObject(const std::string & scope, const std::string & type, const std::string & name, si32 identifier); diff --git a/lib/CPathfinder.cpp b/lib/CPathfinder.cpp index 28d742002..8e66e4662 100644 --- a/lib/CPathfinder.cpp +++ b/lib/CPathfinder.cpp @@ -897,7 +897,7 @@ void CPathfinderHelper::initializePatrol() if(hero->patrol.patrolRadius) { state = PATROL_RADIUS; - gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, boost::optional(), 0, int3::DIST_MANHATTAN); + gs->getTilesInRange(patrolTiles, hero->patrol.initialPos, hero->patrol.patrolRadius, std::optional(), 0, int3::DIST_MANHATTAN); } else state = PATROL_LOCKED; @@ -1100,8 +1100,12 @@ void TurnInfo::updateHeroBonuses(Bonus::BonusType type, const CSelector& sel) co } } -CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options) - : CGameInfoCallback(gs, boost::optional()), turn(-1), hero(Hero), options(Options), owner(Hero->tempOwner) +CPathfinderHelper::CPathfinderHelper(CGameState * gs, const CGHeroInstance * Hero, const PathfinderOptions & Options): + CGameInfoCallback(gs, std::optional()), + turn(-1), + hero(Hero), + options(Options), + owner(Hero->tempOwner) { turnsInfo.reserve(16); updateTurnInfo(); diff --git a/lib/CPlayerState.h b/lib/CPlayerState.h index 70a378cae..55c080f72 100644 --- a/lib/CPlayerState.h +++ b/lib/CPlayerState.h @@ -38,7 +38,7 @@ public: bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory EPlayerStatus::EStatus status; - boost::optional daysWithoutCastle; + std::optional daysWithoutCastle; PlayerState(); PlayerState(PlayerState && other) noexcept; diff --git a/lib/CSkillHandler.cpp b/lib/CSkillHandler.cpp index e1fc93801..cd1866647 100644 --- a/lib/CSkillHandler.cpp +++ b/lib/CSkillHandler.cpp @@ -262,7 +262,7 @@ si32 CSkillHandler::decodeSkill(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "skill", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; } diff --git a/lib/CTownHandler.cpp b/lib/CTownHandler.cpp index bbc5c3979..5eccc845a 100644 --- a/lib/CTownHandler.cpp +++ b/lib/CTownHandler.cpp @@ -1151,7 +1151,7 @@ void CTownHandler::initializeRequirements() logMod->warn("Entry contains: "); logMod->warn(node.toJson()); } - return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).get()); + return BuildingID(VLC->modh->identifiers.getIdentifier(requirement.town->getBuildingScope(), node.Vector()[0]).value()); }); } requirementsToLoad.clear(); @@ -1166,7 +1166,7 @@ void CTownHandler::initializeOverridden() for(const auto & b : jsonNode.Vector()) { - auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).get()); + auto bid = BuildingID(VLC->modh->identifiers.getIdentifier(scope, b).value()); bidHelper.building->overrideBids.insert(bid); } } diff --git a/lib/GameConstants.cpp b/lib/GameConstants.cpp index 5839ebb61..5997c4574 100644 --- a/lib/GameConstants.cpp +++ b/lib/GameConstants.cpp @@ -64,7 +64,7 @@ si32 HeroTypeID::decode(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; } @@ -88,7 +88,7 @@ si32 ArtifactID::decode(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "artifact", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; } @@ -112,7 +112,7 @@ si32 CreatureID::decode(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; } @@ -141,7 +141,7 @@ si32 SpellID::decode(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "spell", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; } @@ -204,7 +204,7 @@ si32 FactionID::decode(const std::string & identifier) { auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "faction", identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return FactionID::DEFAULT; } @@ -292,7 +292,7 @@ BattleField BattleField::fromString(const std::string & identifier) auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "battlefield", identifier); if(rawId) - return BattleField(rawId.get()); + return BattleField(rawId.value()); else return BattleField::NONE; } @@ -312,7 +312,7 @@ Obstacle Obstacle::fromString(const std::string & identifier) auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "obstacle", identifier); if(rawId) - return Obstacle(rawId.get()); + return Obstacle(rawId.value()); else return Obstacle(-1); } diff --git a/lib/HeroBonus.cpp b/lib/HeroBonus.cpp index 24f9e1a97..c789d5487 100644 --- a/lib/HeroBonus.cpp +++ b/lib/HeroBonus.cpp @@ -1520,7 +1520,7 @@ int64_t CBonusSystemNode::getTreeVersion() const return treeChanged; } -std::string Bonus::Description(boost::optional customValue) const +std::string Bonus::Description(std::optional customValue) const { std::ostringstream str; diff --git a/lib/HeroBonus.h b/lib/HeroBonus.h index 213f2b86b..43ba4f4e5 100644 --- a/lib/HeroBonus.h +++ b/lib/HeroBonus.h @@ -533,7 +533,7 @@ struct DLL_LINKAGE Bonus : public std::enable_shared_from_this return sid & 0x0000FFFF; } - std::string Description(boost::optional customValue = {}) const; + std::string Description(std::optional customValue = {}) const; JsonNode toJsonNode() const; std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct diff --git a/lib/IGameCallback.cpp b/lib/IGameCallback.cpp index ddd7fc05c..557bd5a68 100644 --- a/lib/IGameCallback.cpp +++ b/lib/IGameCallback.cpp @@ -66,7 +66,7 @@ void CPrivilegedInfoCallback::getFreeTiles(std::vector & tiles) const void CPrivilegedInfoCallback::getTilesInRange(std::unordered_set & tiles, const int3 & pos, int radious, - boost::optional player, + std::optional player, int mode, int3::EDistanceFormula distanceFormula) const { @@ -100,7 +100,7 @@ void CPrivilegedInfoCallback::getTilesInRange(std::unordered_set & tiles, boost::optional Player, int level, MapTerrainFilterMode tileFilterMode) const +void CPrivilegedInfoCallback::getAllTiles(std::unordered_set & tiles, std::optional Player, int level, MapTerrainFilterMode tileFilterMode) const { if(!!Player && *Player >= PlayerColor::PLAYER_LIMIT) { diff --git a/lib/IGameCallback.h b/lib/IGameCallback.h index c22f641bf..c34c0bf80 100644 --- a/lib/IGameCallback.h +++ b/lib/IGameCallback.h @@ -62,12 +62,12 @@ public: void getTilesInRange(std::unordered_set & tiles, const int3 & pos, int radious, - boost::optional player = boost::optional(), + std::optional player = std::optional(), int mode = 0, int3::EDistanceFormula formula = int3::DIST_2D) const; //returns all tiles on given level (-1 - both levels, otherwise number of level) - void getAllTiles(std::unordered_set &tiles, boost::optional player = boost::optional(), + void getAllTiles(std::unordered_set &tiles, std::optional player = std::optional(), int level = -1, MapTerrainFilterMode tileFilterMode = MapTerrainFilterMode::NONE) const; //gives 3 treasures, 3 minors, 1 major -> used by Black Market and Artifact Merchant diff --git a/lib/LogicalExpression.h b/lib/LogicalExpression.h index 1671e3b35..a94108e3c 100644 --- a/lib/LogicalExpression.h +++ b/lib/LogicalExpression.h @@ -21,7 +21,7 @@ namespace LogicalExpressionDetail class ExpressionBase { public: - /// Possible logical operations, mostly needed to create different types for boost::variant + /// Possible logical operations, mostly needed to create different types for std::variant enum EOperations { ANY_OF, @@ -37,7 +37,7 @@ namespace LogicalExpressionDetail typedef ContainedClass Value; /// Variant that contains all possible elements from logical expression - typedef boost::variant< + typedef std::variant< OperatorAll, OperatorAny, OperatorNone, @@ -70,8 +70,8 @@ namespace LogicalExpressionDetail }; /// Visitor to test result (true/false) of the expression - template - class TestVisitor : public boost::static_visitor + template + class TestVisitor { typedef ExpressionBase Base; @@ -81,7 +81,7 @@ namespace LogicalExpressionDetail { return boost::range::count_if(element, [&](const typename Base::Variant & expr) { - return boost::apply_visitor(*this, expr); + return std::visit(*this, expr); }); } public: @@ -116,8 +116,8 @@ namespace LogicalExpressionDetail template class FalsifiabilityVisitor; - template - class PossibilityVisitor : public boost::static_visitor + template + class PossibilityVisitor { typedef ExpressionBase Base; @@ -131,7 +131,7 @@ namespace LogicalExpressionDetail { return boost::range::count_if(element, [&](const typename Base::Variant & expr) { - return boost::apply_visitor(*satisfiabilityVisitor, expr); + return std::visit(*satisfiabilityVisitor, expr); }); } @@ -139,7 +139,7 @@ namespace LogicalExpressionDetail { return boost::range::count_if(element, [&](const typename Base::Variant & expr) { - return boost::apply_visitor(*falsifiabilityVisitor, expr); + return std::visit(*falsifiabilityVisitor, expr); }); } @@ -235,8 +235,8 @@ namespace LogicalExpressionDetail /// visitor that is trying to generates candidates that must be fulfilled /// to complete this expression - template - class CandidatesVisitor : public boost::static_visitor > + template + class CandidatesVisitor { typedef ExpressionBase Base; typedef std::vector TValueList; @@ -254,7 +254,7 @@ namespace LogicalExpressionDetail if (!classTest(element)) { for (auto & elem : element.expressions) - boost::range::copy(boost::apply_visitor(*this, elem), std::back_inserter(ret)); + boost::range::copy(std::visit(*this, elem), std::back_inserter(ret)); } return ret; } @@ -265,7 +265,7 @@ namespace LogicalExpressionDetail if (!classTest(element)) { for (auto & elem : element.expressions) - boost::range::copy(boost::apply_visitor(*this, elem), std::back_inserter(ret)); + boost::range::copy(std::visit(*this, elem), std::back_inserter(ret)); } return ret; } @@ -285,8 +285,8 @@ namespace LogicalExpressionDetail }; /// Simple foreach visitor - template - class ForEachVisitor : public boost::static_visitor::Variant> + template + class ForEachVisitor { typedef ExpressionBase Base; @@ -306,14 +306,14 @@ namespace LogicalExpressionDetail typename Base::Variant operator()(Type element) const { for (auto & entry : element.expressions) - entry = boost::apply_visitor(*this, entry); + entry = std::visit(*this, entry); return element; } }; /// Minimizing visitor that removes all redundant elements from variant (e.g. AllOf inside another AllOf can be merged safely) - template - class MinimizingVisitor : public boost::static_visitor::Variant> + template + class MinimizingVisitor { typedef ExpressionBase Base; @@ -330,15 +330,15 @@ namespace LogicalExpressionDetail for (auto & entryRO : element.expressions) { - auto entry = boost::apply_visitor(*this, entryRO); + auto entry = std::visit(*this, entryRO); try { // copy entries from child of this type - auto sublist = boost::get(entry).expressions; + auto sublist = std::get(entry).expressions; std::move(sublist.begin(), sublist.end(), std::back_inserter(ret.expressions)); } - catch (boost::bad_get &) + catch (std::bad_variant_access &) { // different type (e.g. allOf vs oneOf) just copy ret.expressions.push_back(entry); @@ -397,8 +397,8 @@ namespace LogicalExpressionDetail }; /// Serializes expression in JSON format. Part of map format. - template - class Writer : public boost::static_visitor + template + class Writer { typedef ExpressionBase Base; @@ -410,7 +410,7 @@ namespace LogicalExpressionDetail ret.Vector().resize(1); ret.Vector().back().String() = name; for (auto & expr : element) - ret.Vector().push_back(boost::apply_visitor(*this, expr)); + ret.Vector().push_back(std::visit(*this, expr)); return ret; } public: @@ -442,8 +442,8 @@ namespace LogicalExpressionDetail std::string DLL_LINKAGE getTextForOperator(const std::string & operation); /// Prints expression in human-readable format - template - class Printer : public boost::static_visitor + template + class Printer { typedef ExpressionBase Base; @@ -465,7 +465,7 @@ namespace LogicalExpressionDetail std::string ret; prefix.push_back('\t'); for (auto & expr : element) - ret += prefix + boost::apply_visitor(*this, expr) + "\n"; + ret += prefix + std::visit(*this, expr) + "\n"; prefix.pop_back(); return ret; } @@ -552,14 +552,14 @@ public: Variant morph(std::function morpher) const { LogicalExpressionDetail::ForEachVisitor visitor(morpher); - return boost::apply_visitor(visitor, data); + return std::visit(visitor, data); } /// Minimizes expression, removing any redundant elements void minimize() { LogicalExpressionDetail::MinimizingVisitor visitor; - data = boost::apply_visitor(visitor, data); + data = std::visit(visitor, data); } /// calculates if expression evaluates to "true". @@ -567,7 +567,7 @@ public: bool test(std::function toBool) const { LogicalExpressionDetail::TestVisitor testVisitor(toBool); - return boost::apply_visitor(testVisitor, data); + return std::visit(testVisitor, data); } /// calculates if expression can evaluate to "true". @@ -579,7 +579,7 @@ public: satisfiabilityVisitor.setFalsifiabilityVisitor(&falsifiabilityVisitor); falsifiabilityVisitor.setSatisfiabilityVisitor(&satisfiabilityVisitor); - return boost::apply_visitor(satisfiabilityVisitor, data); + return std::visit(satisfiabilityVisitor, data); } /// calculates if expression can evaluate to "false". @@ -591,14 +591,14 @@ public: satisfiabilityVisitor.setFalsifiabilityVisitor(&falsifiabilityVisitor); falsifiabilityVisitor.setFalsifiabilityVisitor(&satisfiabilityVisitor); - return boost::apply_visitor(falsifiabilityVisitor, data); + return std::visit(falsifiabilityVisitor, data); } /// generates list of candidates that can be fulfilled by caller (like AI) std::vector getFulfillmentCandidates(std::function toBool) const { LogicalExpressionDetail::CandidatesVisitor candidateVisitor(toBool); - return boost::apply_visitor(candidateVisitor, data); + return std::visit(candidateVisitor, data); } /// Converts expression in human-readable form @@ -607,18 +607,18 @@ public: std::string toString(std::function toStr) const { LogicalExpressionDetail::Printer printVisitor(toStr); - return boost::apply_visitor(printVisitor, data); + return std::visit(printVisitor, data); } std::string toString(std::function toStr, std::function toBool) const { LogicalExpressionDetail::Printer printVisitor(toStr, toBool); - return boost::apply_visitor(printVisitor, data); + return std::visit(printVisitor, data); } JsonNode toJson(std::function toJson) const { LogicalExpressionDetail::Writer writeVisitor(toJson); - return boost::apply_visitor(writeVisitor, data); + return std::visit(writeVisitor, data); } template diff --git a/lib/NetPacks.h b/lib/NetPacks.h index 2cadc2b6e..d9c59e7da 100644 --- a/lib/NetPacks.h +++ b/lib/NetPacks.h @@ -145,7 +145,7 @@ struct DLL_LINKAGE YourTurn : public CPackForClient void applyGs(CGameState * gs) const; PlayerColor player; - boost::optional daysWithoutCastle; + std::optional daysWithoutCastle; virtual void visitTyped(ICPackVisitor & visitor) override; @@ -591,7 +591,7 @@ struct DLL_LINKAGE TryMoveHero : public CPackForClient EResult result = FAILED; //uses EResult int3 start, end; //h3m format std::unordered_set fowRevealed; //revealed tiles - boost::optional attackedFrom; // Set when stepping into endangered tile. + std::optional attackedFrom; // Set when stepping into endangered tile. virtual void visitTyped(ICPackVisitor & visitor) override; @@ -930,17 +930,17 @@ struct DLL_LINKAGE BulkSmartRebalanceStacks : CGarrisonOperationPack } }; -struct GetEngagedHeroIds : boost::static_visitor> +struct GetEngagedHeroIds { - boost::optional operator()(const ConstTransitivePtr & h) const + std::optional operator()(const ConstTransitivePtr & h) const { return h->id; } - boost::optional operator()(const ConstTransitivePtr & s) const + std::optional operator()(const ConstTransitivePtr & s) const { if(s->armyObj && s->armyObj->ID == Obj::HERO) return s->armyObj->id; - return boost::optional(); + return std::optional(); } }; diff --git a/lib/NetPacksBase.h b/lib/NetPacksBase.h index e7b3da5f1..ac4ff7c66 100644 --- a/lib/NetPacksBase.h +++ b/lib/NetPacksBase.h @@ -233,7 +233,7 @@ struct Component } }; -using TArtHolder = boost::variant, ConstTransitivePtr>; +using TArtHolder = std::variant, ConstTransitivePtr>; struct ArtifactLocation { @@ -259,9 +259,9 @@ struct ArtifactLocation template bool isHolder(const T *t) const { - if(auto ptrToT = boost::get >(&artHolder)) + if(auto ptrToT = std::get>(artHolder)) { - return ptrToT->get() == t; + return ptrToT == t; } return false; } diff --git a/lib/NetPacksLib.cpp b/lib/NetPacksLib.cpp index 260abd6d8..f51f177b7 100644 --- a/lib/NetPacksLib.cpp +++ b/lib/NetPacksLib.cpp @@ -1532,7 +1532,7 @@ const CStackInstance * StackLocation::getStack() return &army->getStack(slot); } -struct ObjectRetriever : boost::static_visitor +struct ObjectRetriever { const CArmedInstance * operator()(const ConstTransitivePtr &h) const { @@ -1543,8 +1543,8 @@ struct ObjectRetriever : boost::static_visitor return s->armyObj; } }; -template -struct GetBase : boost::static_visitor +template +struct GetBase { template T * operator()(TArg &arg) const @@ -1563,7 +1563,7 @@ void ArtifactLocation::removeArtifact() const CArmedInstance * ArtifactLocation::relatedObj() const { - return boost::apply_visitor(ObjectRetriever(), artHolder); + return std::visit(ObjectRetriever(), artHolder); } PlayerColor ArtifactLocation::owningPlayer() const @@ -1574,12 +1574,12 @@ PlayerColor ArtifactLocation::owningPlayer() const CArtifactSet *ArtifactLocation::getHolderArtSet() { - return boost::apply_visitor(GetBase(), artHolder); + return std::visit(GetBase(), artHolder); } CBonusSystemNode *ArtifactLocation::getHolderNode() { - return boost::apply_visitor(GetBase(), artHolder); + return std::visit(GetBase(), artHolder); } const CArtifactInstance *ArtifactLocation::getArt() const @@ -2050,11 +2050,11 @@ void NewTurn::applyGs(CGameState *gs) if (playerState.daysWithoutCastle) ++(*playerState.daysWithoutCastle); else - playerState.daysWithoutCastle = boost::make_optional(0); + playerState.daysWithoutCastle = std::make_optional(0); } else { - playerState.daysWithoutCastle = boost::none; + playerState.daysWithoutCastle = std::nullopt; } } } @@ -2085,7 +2085,7 @@ void SetObjectProperty::applyGs(CGameState * gs) const //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured if(p->daysWithoutCastle) - p->daysWithoutCastle = boost::none; + p->daysWithoutCastle = std::nullopt; } } @@ -2533,12 +2533,12 @@ const CArtifactInstance * ArtSlotInfo::getArt() const CArtifactSet * BulkMoveArtifacts::getSrcHolderArtSet() { - return boost::apply_visitor(GetBase(), srcArtHolder); + return std::visit(GetBase(), srcArtHolder); } CArtifactSet * BulkMoveArtifacts::getDstHolderArtSet() { - return boost::apply_visitor(GetBase(), dstArtHolder); + return std::visit(GetBase(), dstArtHolder); } VCMI_LIB_NAMESPACE_END diff --git a/lib/battle/BattleHex.h b/lib/battle/BattleHex.h index b7e26d944..060962780 100644 --- a/lib/battle/BattleHex.h +++ b/lib/battle/BattleHex.h @@ -29,7 +29,7 @@ namespace GameConstants const int BFIELD_SIZE = BFIELD_WIDTH * BFIELD_HEIGHT; } -using BattleSideOpt = boost::optional; +using BattleSideOpt = std::optional; // for battle stacks' positions struct DLL_LINKAGE BattleHex //TODO: decide if this should be changed to class for better code design diff --git a/lib/battle/CBattleInfoCallback.cpp b/lib/battle/CBattleInfoCallback.cpp index 7c54f7cd5..8b3fd21a4 100644 --- a/lib/battle/CBattleInfoCallback.cpp +++ b/lib/battle/CBattleInfoCallback.cpp @@ -106,7 +106,7 @@ ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(con const auto side = playerToSide(player); if(!side) return ESpellCastProblem::INVALID; - if(!battleDoWeKnowAbout(side.get())) + if(!battleDoWeKnowAbout(side.value())) { logGlobal->warn("You can't check if enemy can cast given spell!"); return ESpellCastProblem::INVALID; @@ -119,7 +119,7 @@ ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(con { case spells::Mode::HERO: { - if(battleCastSpells(side.get()) > 0) + if(battleCastSpells(side.value()) > 0) return ESpellCastProblem::CASTS_PER_TURN_LIMIT; const auto * hero = dynamic_cast(caster); @@ -229,7 +229,7 @@ std::vector CBattleInfoCallback::getClientActionsFor { if(stack->hasBonusOfType(Bonus::SPELLCASTER)) { - for (auto const & spellID : data.creatureSpellsToCast) + for(const auto & spellID : data.creatureSpellsToCast) { const CSpell *spell = spellID.toSpell(); PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE); @@ -767,7 +767,7 @@ DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInf //TODO: rewrite using boost::numeric::interval //TODO: rewire once more using interval-based fuzzy arithmetic - auto const & estimateRetaliation = [&]( int64_t damage) + const auto & estimateRetaliation = [&](int64_t damage) { auto retaliationAttack = bai.reverse(); auto state = retaliationAttack.attacker->acquireState(); @@ -1763,7 +1763,7 @@ int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) cons const auto sideOpt = playerToSide(Player); if(!sideOpt) return -1; - const auto side = sideOpt.get(); + const auto side = sideOpt.value(); int ret = 0; double discount = 0; @@ -1816,7 +1816,7 @@ si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const return GameConstants::SPELL_LEVELS; } -boost::optional CBattleInfoCallback::battleIsFinished() const +std::optional CBattleInfoCallback::battleIsFinished() const { auto units = battleGetUnitsIf([=](const battle::Unit * unit) { @@ -1831,7 +1831,7 @@ boost::optional CBattleInfoCallback::battleIsFinished() const hasUnit.at(unit->unitSide()) = true; if(hasUnit[0] && hasUnit[1]) - return boost::none; + return std::nullopt; } hasUnit = {false, false}; diff --git a/lib/battle/CBattleInfoCallback.h b/lib/battle/CBattleInfoCallback.h index 3551d96c4..f25afb785 100644 --- a/lib/battle/CBattleInfoCallback.h +++ b/lib/battle/CBattleInfoCallback.h @@ -58,7 +58,7 @@ public: RANDOM_GENIE, RANDOM_AIMED }; - boost::optional battleIsFinished() const override; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw + std::optional battleIsFinished() const override; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw std::vector> battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking = true) const override; std::vector> getAllAffectedObstaclesByStack(const battle::Unit * unit, const std::set & passed) const override; diff --git a/lib/battle/CBattleInfoEssentials.cpp b/lib/battle/CBattleInfoEssentials.cpp index a787badcc..912b3e6c8 100644 --- a/lib/battle/CBattleInfoEssentials.cpp +++ b/lib/battle/CBattleInfoEssentials.cpp @@ -34,7 +34,7 @@ int32_t CBattleInfoEssentials::battleGetEnchanterCounter(ui8 side) const return getBattle()->getEnchanterCounter(side); } -std::vector> CBattleInfoEssentials::battleGetAllObstacles(boost::optional perspective) const +std::vector> CBattleInfoEssentials::battleGetAllObstacles(std::optional perspective) const { std::vector > ret; RETURN_IF_NOT_BATTLE(ret); @@ -42,7 +42,7 @@ std::vector> CBattleInfoEssentials::bat if(!perspective) { //if no particular perspective request, use default one - perspective = boost::make_optional(battleGetMySide()); + perspective = std::make_optional(battleGetMySide()); } else { @@ -156,7 +156,7 @@ const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const { RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID); - if(!player || player.get().isSpectator()) + if(!player || player->isSpectator()) return BattlePerspective::ALL_KNOWING; if(*player == getBattle()->getSidePlayer(BattleSide::ATTACKER)) return BattlePerspective::LEFT_SIDE; @@ -264,7 +264,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const if(!side) return false; - const CGHeroInstance *myHero = battleGetFightingHero(side.get()); + const CGHeroInstance * myHero = battleGetFightingHero(side.value()); //current player have no hero if(!myHero) @@ -275,7 +275,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const return false; //we are besieged defender - if(side.get() == BattleSide::DEFENDER && battleGetSiegeLevel()) + if(side == BattleSide::DEFENDER && battleGetSiegeLevel()) { const auto * town = battleGetDefendedTown(); if(!town->hasBuilt(BuildingSubID::ESCAPE_TUNNEL)) @@ -287,7 +287,7 @@ bool CBattleInfoEssentials::battleCanFlee(const PlayerColor & player) const BattleSideOpt CBattleInfoEssentials::playerToSide(const PlayerColor & player) const { - RETURN_IF_NOT_BATTLE(boost::none); + RETURN_IF_NOT_BATTLE(std::nullopt); if(getBattle()->getSidePlayer(BattleSide::ATTACKER) == player) return BattleSideOpt(BattleSide::ATTACKER); @@ -297,7 +297,7 @@ BattleSideOpt CBattleInfoEssentials::playerToSide(const PlayerColor & player) co logGlobal->warn("Cannot find side for player %s", player.getStr()); - return boost::none; + return std::nullopt; } PlayerColor CBattleInfoEssentials::sideToPlayer(ui8 side) const @@ -322,7 +322,7 @@ PlayerColor CBattleInfoEssentials::otherPlayer(const PlayerColor & player) const if(!side) return PlayerColor::CANNOT_DETERMINE; - return getBattle()->getSidePlayer(otherSide(side.get())); + return getBattle()->getSidePlayer(otherSide(side.value())); } bool CBattleInfoEssentials::playerHasAccessToHeroInfo(const PlayerColor & player, const CGHeroInstance * h) const @@ -331,7 +331,7 @@ bool CBattleInfoEssentials::playerHasAccessToHeroInfo(const PlayerColor & player const auto side = playerToSide(player); if(side) { - auto opponentSide = otherSide(side.get()); + auto opponentSide = otherSide(side.value()); if(getBattle()->getSideHero(opponentSide) == h) return true; } @@ -350,9 +350,9 @@ bool CBattleInfoEssentials::battleCanSurrender(const PlayerColor & player) const const auto side = playerToSide(player); if(!side) return false; - bool iAmSiegeDefender = (side.get() == BattleSide::DEFENDER && battleGetSiegeLevel()); + bool iAmSiegeDefender = (side.value() == BattleSide::DEFENDER && battleGetSiegeLevel()); //conditions like for fleeing (except escape tunnel presence) + enemy must have a hero - return battleCanFlee(player) && !iAmSiegeDefender && battleHasHero(otherSide(side.get())); + return battleCanFlee(player) && !iAmSiegeDefender && battleHasHero(otherSide(side.value())); } bool CBattleInfoEssentials::battleHasHero(ui8 side) const @@ -409,7 +409,7 @@ const CGHeroInstance * CBattleInfoEssentials::battleGetOwnerHero(const battle::U const auto side = playerToSide(battleGetOwner(unit)); if(!side) return nullptr; - return getBattle()->getSideHero(side.get()); + return getBattle()->getSideHero(side.value()); } bool CBattleInfoEssentials::battleMatchOwner(const battle::Unit * attacker, const battle::Unit * defender, const boost::logic::tribool positivness) const diff --git a/lib/battle/CBattleInfoEssentials.h b/lib/battle/CBattleInfoEssentials.h index 62115e6ed..d5d198150 100644 --- a/lib/battle/CBattleInfoEssentials.h +++ b/lib/battle/CBattleInfoEssentials.h @@ -52,7 +52,7 @@ public: BattleField battleGetBattlefieldType() const override; int32_t battleGetEnchanterCounter(ui8 side) const; - std::vector > battleGetAllObstacles(boost::optional perspective = boost::none) const; //returns all obstacles on the battlefield + std::vector > battleGetAllObstacles(std::optional perspective = std::nullopt) const; //returns all obstacles on the battlefield std::shared_ptr battleGetObstacleByID(uint32_t ID) const; diff --git a/lib/battle/CCallbackBase.cpp b/lib/battle/CCallbackBase.cpp index 86d1b21f7..fb638793c 100644 --- a/lib/battle/CCallbackBase.cpp +++ b/lib/battle/CCallbackBase.cpp @@ -23,7 +23,7 @@ const IBattleInfo * CCallbackBase::getBattle() const return battle; } -CCallbackBase::CCallbackBase(boost::optional Player): +CCallbackBase::CCallbackBase(std::optional Player): player(std::move(Player)) { } @@ -33,7 +33,7 @@ void CCallbackBase::setBattle(const IBattleInfo * B) battle = B; } -boost::optional CCallbackBase::getPlayerID() const +std::optional CCallbackBase::getPlayerID() const { return player; } diff --git a/lib/battle/CCallbackBase.h b/lib/battle/CCallbackBase.h index 165999047..dc5ac95eb 100644 --- a/lib/battle/CCallbackBase.h +++ b/lib/battle/CCallbackBase.h @@ -26,9 +26,9 @@ class DLL_LINKAGE CCallbackBase const IBattleInfo * battle = nullptr; //battle to which the player is engaged, nullptr if none or not applicable protected: - boost::optional player; // not set gives access to all information, otherwise callback provides only information "visible" for player + std::optional player; // not set gives access to all information, otherwise callback provides only information "visible" for player - CCallbackBase(boost::optional Player); + CCallbackBase(std::optional Player); CCallbackBase() = default; const IBattleInfo * getBattle() const; @@ -36,7 +36,7 @@ protected: bool duringBattle() const; public: - boost::optional getPlayerID() const; + std::optional getPlayerID() const; friend class CBattleInfoEssentials; }; diff --git a/lib/battle/IBattleInfoCallback.h b/lib/battle/IBattleInfoCallback.h index 08112ddc8..984bf9093 100644 --- a/lib/battle/IBattleInfoCallback.h +++ b/lib/battle/IBattleInfoCallback.h @@ -58,7 +58,7 @@ public: virtual BattleField battleGetBattlefieldType() const = 0; ///return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw - virtual boost::optional battleIsFinished() const = 0; + virtual std::optional battleIsFinished() const = 0; virtual si8 battleTacticDist() const = 0; //returns tactic distance in current tactics phase; 0 if not in tactics phase virtual si8 battleGetTacticsSide() const = 0; //returns which side is in tactics phase, undefined if none (?) diff --git a/lib/filesystem/AdapterLoaders.cpp b/lib/filesystem/AdapterLoaders.cpp index a3fd4699f..fddd889fb 100644 --- a/lib/filesystem/AdapterLoaders.cpp +++ b/lib/filesystem/AdapterLoaders.cpp @@ -39,7 +39,7 @@ std::string CMappedFileLoader::getMountPoint() const return ""; // does not have any meaning with this type of data source } -boost::optional CMappedFileLoader::getResourceName(const ResourceID & resourceName) const +std::optional CMappedFileLoader::getResourceName(const ResourceID & resourceName) const { return CResourceHandler::get()->getResourceName(fileList.at(resourceName)); } @@ -90,11 +90,11 @@ std::string CFilesystemList::getMountPoint() const return ""; } -boost::optional CFilesystemList::getResourceName(const ResourceID & resourceName) const +std::optional CFilesystemList::getResourceName(const ResourceID & resourceName) const { if (existsResource(resourceName)) return getResourcesWithName(resourceName).back()->getResourceName(resourceName); - return boost::optional(); + return std::optional(); } std::set CFilesystemList::getResourceNames(const ResourceID & resourceName) const diff --git a/lib/filesystem/AdapterLoaders.h b/lib/filesystem/AdapterLoaders.h index 7f5620c88..3e0386ed5 100644 --- a/lib/filesystem/AdapterLoaders.h +++ b/lib/filesystem/AdapterLoaders.h @@ -41,7 +41,7 @@ public: std::unique_ptr load(const ResourceID & resourceName) const override; bool existsResource(const ResourceID & resourceName) const override; std::string getMountPoint() const override; - boost::optional getResourceName(const ResourceID & resourceName) const override; + std::optional getResourceName(const ResourceID & resourceName) const override; void updateFilteredFiles(std::function filter) const override {} std::unordered_set getFilteredFiles(std::function filter) const override; @@ -71,7 +71,7 @@ public: std::unique_ptr load(const ResourceID & resourceName) const override; bool existsResource(const ResourceID & resourceName) const override; std::string getMountPoint() const override; - boost::optional getResourceName(const ResourceID & resourceName) const override; + std::optional getResourceName(const ResourceID & resourceName) const override; std::set getResourceNames(const ResourceID & resourceName) const override; void updateFilteredFiles(std::function filter) const override; std::unordered_set getFilteredFiles(std::function filter) const override; diff --git a/lib/filesystem/CFilesystemLoader.cpp b/lib/filesystem/CFilesystemLoader.cpp index 2d37e3e35..1290406a6 100644 --- a/lib/filesystem/CFilesystemLoader.cpp +++ b/lib/filesystem/CFilesystemLoader.cpp @@ -44,7 +44,7 @@ std::string CFilesystemLoader::getMountPoint() const return mountPoint; } -boost::optional CFilesystemLoader::getResourceName(const ResourceID & resourceName) const +std::optional CFilesystemLoader::getResourceName(const ResourceID & resourceName) const { assert(existsResource(resourceName)); diff --git a/lib/filesystem/CFilesystemLoader.h b/lib/filesystem/CFilesystemLoader.h index 847aaa42c..8aeb23581 100644 --- a/lib/filesystem/CFilesystemLoader.h +++ b/lib/filesystem/CFilesystemLoader.h @@ -38,7 +38,7 @@ public: bool existsResource(const ResourceID & resourceName) const override; std::string getMountPoint() const override; bool createResource(std::string filename, bool update = false) override; - boost::optional getResourceName(const ResourceID & resourceName) const override; + std::optional getResourceName(const ResourceID & resourceName) const override; void updateFilteredFiles(std::function filter) const override; std::unordered_set getFilteredFiles(std::function filter) const override; diff --git a/lib/filesystem/ISimpleResourceLoader.h b/lib/filesystem/ISimpleResourceLoader.h index 833000df1..88c6a9fad 100644 --- a/lib/filesystem/ISimpleResourceLoader.h +++ b/lib/filesystem/ISimpleResourceLoader.h @@ -49,9 +49,9 @@ public: * * @return path or empty optional if file can't be accessed independently (e.g. file in archive) */ - virtual boost::optional getResourceName(const ResourceID & resourceName) const + virtual std::optional getResourceName(const ResourceID & resourceName) const { - return boost::optional(); + return std::optional(); } /** diff --git a/lib/mapObjects/CArmedInstance.cpp b/lib/mapObjects/CArmedInstance.cpp index b0ebc8080..c05415e97 100644 --- a/lib/mapObjects/CArmedInstance.cpp +++ b/lib/mapObjects/CArmedInstance.cpp @@ -29,7 +29,7 @@ void CArmedInstance::randomizeArmy(int type) int upgrade = elem.second->randomStack->upgrade; elem.second->setType((*VLC->townh)[type]->town->creatures[level][upgrade]); - elem.second->randomStack = boost::none; + elem.second->randomStack = std::nullopt; } assert(elem.second->valid(false)); assert(elem.second->armyObj == this); diff --git a/lib/mapObjects/CGHeroInstance.cpp b/lib/mapObjects/CGHeroInstance.cpp index 5826f19b2..949023718 100644 --- a/lib/mapObjects/CGHeroInstance.cpp +++ b/lib/mapObjects/CGHeroInstance.cpp @@ -1280,11 +1280,11 @@ PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & r return static_cast(primarySkill); } -boost::optional CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const +std::optional CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const { assert(gainsLevel()); - boost::optional chosenSecondarySkill; + std::optional chosenSecondarySkill; const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills(); if(!proposedSecondarySkills.empty()) { @@ -1300,12 +1300,12 @@ boost::optional CGHeroInstance::nextSecondarySkill(CRandomGenera if(learnedSecondarySkills.empty()) { // there are only new skills to learn, so choose anyone of them - chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand)); + chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand)); } else { // preferably upgrade a already learned secondary skill - chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand)); + chosenSecondarySkill = std::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand)); } } return chosenSecondarySkill; @@ -1441,7 +1441,7 @@ void CGHeroInstance::setHeroTypeName(const std::string & identifier) auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), "hero", identifier); if(rawId) - subID = rawId.get(); + subID = rawId.value(); else { throw std::runtime_error("Couldn't resolve hero identifier " + identifier); diff --git a/lib/mapObjects/CGHeroInstance.h b/lib/mapObjects/CGHeroInstance.h index 28b2dae4b..ea525b177 100644 --- a/lib/mapObjects/CGHeroInstance.h +++ b/lib/mapObjects/CGHeroInstance.h @@ -182,7 +182,7 @@ public: PrimarySkill::PrimarySkill nextPrimarySkill(CRandomGenerator & rand) const; /// Returns the next secondary skill randomly on level up. Can only be called if hero can gain a level up. - boost::optional nextSecondarySkill(CRandomGenerator & rand) const; + std::optional nextSecondarySkill(CRandomGenerator & rand) const; /// Gets 0, 1 or 2 secondary skills which are proposed on hero level up. std::vector getLevelUpProposedSecondarySkills() const; diff --git a/lib/mapObjects/CGTownInstance.cpp b/lib/mapObjects/CGTownInstance.cpp index 10f2fbb2b..93cf4f092 100644 --- a/lib/mapObjects/CGTownInstance.cpp +++ b/lib/mapObjects/CGTownInstance.cpp @@ -1507,7 +1507,7 @@ void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler) auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier); if(rawId) - return rawId.get(); + return rawId.value(); else return -1; }; diff --git a/lib/mapObjects/CObjectClassesHandler.cpp b/lib/mapObjects/CObjectClassesHandler.cpp index 3b142bb75..6cd42ac6d 100644 --- a/lib/mapObjects/CObjectClassesHandler.cpp +++ b/lib/mapObjects/CObjectClassesHandler.cpp @@ -165,7 +165,7 @@ void CObjectClassesHandler::loadSubObject(const std::string & scope, const std:: obj->objects.push_back(object); registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype); - for (auto const & compatID : entry["compatibilityIdentifiers"].Vector()) + for(const auto & compatID : entry["compatibilityIdentifiers"].Vector()) registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype); } @@ -178,7 +178,7 @@ void CObjectClassesHandler::loadSubObject(const std::string & scope, const std:: obj->objects[index] = object; registerObject(scope, obj->getJsonKey(), object->getSubTypeName(), object->subtype); - for (auto const & compatID : entry["compatibilityIdentifiers"].Vector()) + for(const auto & compatID : entry["compatibilityIdentifiers"].Vector()) registerObject(scope, obj->getJsonKey(), compatID.String(), object->subtype); } @@ -313,14 +313,14 @@ TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) TObjectTypeHandler CObjectClassesHandler::getHandlerFor(const std::string & scope, const std::string & type, const std::string & subtype) const { - boost::optional id = VLC->modh->identifiers.getIdentifier(scope, "object", type); + std::optional id = VLC->modh->identifiers.getIdentifier(scope, "object", type); if(id) { - auto * object = objects[id.get()]; - boost::optional subID = VLC->modh->identifiers.getIdentifier(scope, object->getJsonKey(), subtype); + auto * object = objects[id.value()]; + std::optional subID = VLC->modh->identifiers.getIdentifier(scope, object->getJsonKey(), subtype); if (subID) - return object->objects[subID.get()]; + return object->objects[subID.value()]; } std::string errorString = "Failed to find object of type " + type + "::" + subtype; @@ -515,7 +515,7 @@ void AObjectTypeHandler::init(const JsonNode & input) const JsonNode & mapLimit = input["rmg"]["mapLimit"]; if (!mapLimit.isNull()) - rmgInfo.mapLimit.reset(static_cast(mapLimit.Float())); + rmgInfo.mapLimit = static_cast(mapLimit.Float()); rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]); rmgInfo.rarity = static_cast(input["rmg"]["rarity"].Float()); @@ -551,14 +551,14 @@ void AObjectTypeHandler::init(const JsonNode & input) sounds.removal.push_back(node.String()); if(input["aiValue"].isNull()) - aiValue = boost::none; + aiValue = std::nullopt; else - aiValue = static_cast>(input["aiValue"].Integer()); + aiValue = static_cast>(input["aiValue"].Integer()); if(input["battleground"].getType() == JsonNode::JsonType::DATA_STRING) battlefield = input["battleground"].String(); else - battlefield = boost::none; + battlefield = std::nullopt; initTypeData(input); } @@ -625,7 +625,7 @@ std::vector> AObjectTypeHandler::getTempla BattleField AObjectTypeHandler::getBattlefield() const { - return battlefield ? BattleField::fromString(battlefield.get()) : BattleField::NONE; + return battlefield ? BattleField::fromString(battlefield.value()) : BattleField::NONE; } std::vector>AObjectTypeHandler::getTemplates(TerrainId terrainType) const @@ -661,7 +661,7 @@ const RandomMapInfo & AObjectTypeHandler::getRMGInfo() return rmgInfo; } -boost::optional AObjectTypeHandler::getAiValue() const +std::optional AObjectTypeHandler::getAiValue() const { return aiValue; } diff --git a/lib/mapObjects/CObjectClassesHandler.h b/lib/mapObjects/CObjectClassesHandler.h index 8fcb20678..910ee3f16 100644 --- a/lib/mapObjects/CObjectClassesHandler.h +++ b/lib/mapObjects/CObjectClassesHandler.h @@ -43,7 +43,7 @@ struct DLL_LINKAGE RandomMapInfo ui32 value; /// How many of such objects can be placed on map, 0 = object can not be placed by RMG - boost::optional mapLimit; + std::optional mapLimit; /// How many of such objects can be placed in one zone, 0 = unplaceable ui32 zoneLimit; @@ -57,7 +57,7 @@ struct DLL_LINKAGE RandomMapInfo rarity(0) {} - void setMapLimit(ui32 val) { mapLimit.reset(val); } + void setMapLimit(ui32 val) { mapLimit = val; } template void serialize(Handler &h, const int version) { @@ -150,8 +150,8 @@ class DLL_LINKAGE AObjectTypeHandler : public boost::noncopyable SObjectSounds sounds; - boost::optional aiValue; - boost::optional battlefield; + std::optional aiValue; + std::optional battlefield; std::string modScope; std::string typeName; @@ -200,7 +200,7 @@ public: const RandomMapInfo & getRMGInfo(); - boost::optional getAiValue() const; + std::optional getAiValue() const; /// returns true if this class provides custom text ID's instead of generic per-object name virtual bool hasNameTextID() const; diff --git a/lib/mapObjects/CObjectHandler.cpp b/lib/mapObjects/CObjectHandler.cpp index 17e94634c..43799ff64 100644 --- a/lib/mapObjects/CObjectHandler.cpp +++ b/lib/mapObjects/CObjectHandler.cpp @@ -288,31 +288,31 @@ std::string CGObjectInstance::getObjectName() const return VLC->objtypeh->getObjectName(ID, subID); } -boost::optional CGObjectInstance::getAmbientSound() const +std::optional CGObjectInstance::getAmbientSound() const { const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).ambient; if(!sounds.empty()) return sounds.front(); // TODO: Support randomization of ambient sounds - return boost::none; + return std::nullopt; } -boost::optional CGObjectInstance::getVisitSound() const +std::optional CGObjectInstance::getVisitSound() const { const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).visit; if(!sounds.empty()) return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault()); - return boost::none; + return std::nullopt; } -boost::optional CGObjectInstance::getRemovalSound() const +std::optional CGObjectInstance::getRemovalSound() const { const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).removal; if(!sounds.empty()) return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault()); - return boost::none; + return std::nullopt; } std::string CGObjectInstance::getHoverText(PlayerColor player) const @@ -384,7 +384,7 @@ void CGObjectInstance::serializeJson(JsonSerializeFormat & handler) handler.serializeInt("l", pos.z); JsonNode app; appearance->writeJson(app, false); - handler.serializeRaw("template",app, boost::none); + handler.serializeRaw("template", app, std::nullopt); } { diff --git a/lib/mapObjects/CObjectHandler.h b/lib/mapObjects/CObjectHandler.h index 983050a9e..4b2c4415e 100644 --- a/lib/mapObjects/CObjectHandler.h +++ b/lib/mapObjects/CObjectHandler.h @@ -171,10 +171,9 @@ public: virtual bool isTile2Terrain() const { return false; } - boost::optional getAmbientSound() const; - boost::optional getVisitSound() const; - boost::optional getRemovalSound() const; - + std::optional getAmbientSound() const; + std::optional getVisitSound() const; + std::optional getRemovalSound() const; /** VIRTUAL METHODS **/ diff --git a/lib/mapObjects/CQuest.cpp b/lib/mapObjects/CQuest.cpp index 086517b92..bd9163a24 100644 --- a/lib/mapObjects/CQuest.cpp +++ b/lib/mapObjects/CQuest.cpp @@ -1067,7 +1067,7 @@ void CGSeerHut::serializeJsonOptions(JsonSerializeFormat & handler) if(rawId) { - rID = rawId.get(); + rID = rawId.value(); } else { diff --git a/lib/mapObjects/CRewardableConstructor.cpp b/lib/mapObjects/CRewardableConstructor.cpp index 1a9d1e0f6..219d1f7ea 100644 --- a/lib/mapObjects/CRewardableConstructor.cpp +++ b/lib/mapObjects/CRewardableConstructor.cpp @@ -140,8 +140,8 @@ void CRandomRewardObjectInfo::configureReward(CRewardableObject * object, CRando for ( auto node : source["changeCreatures"].Struct() ) { - CreatureID from (VLC->modh->identifiers.getIdentifier (node.second.meta, "creature", node.first) .get()); - CreatureID dest (VLC->modh->identifiers.getIdentifier (node.second.meta, "creature", node.second.String()).get()); + CreatureID from(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.first).value()); + CreatureID dest(VLC->modh->identifiers.getIdentifier(node.second.meta, "creature", node.second.String()).value()); reward.extraComponents.emplace_back(Component::EComponentType::CREATURE, dest.getNum(), 0, 0); diff --git a/lib/mapObjects/CommonConstructors.cpp b/lib/mapObjects/CommonConstructors.cpp index e1512c78a..52fbabbfb 100644 --- a/lib/mapObjects/CommonConstructors.cpp +++ b/lib/mapObjects/CommonConstructors.cpp @@ -50,7 +50,7 @@ void CTownInstanceConstructor::afterLoadFinalization() { filters[entry.first] = LogicalExpression(entry.second, [this](const JsonNode & node) { - return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->getJsonKey(), node.Vector()[0]).get()); + return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->getJsonKey(), node.Vector()[0]).value()); }); } } @@ -98,7 +98,7 @@ void CHeroInstanceConstructor::afterLoadFinalization() { filters[entry.first] = LogicalExpression(entry.second, [](const JsonNode & node) { - return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).get()); + return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).value()); }); } } diff --git a/lib/mapObjects/JsonRandom.cpp b/lib/mapObjects/JsonRandom.cpp index b0533d332..01f9d866f 100644 --- a/lib/mapObjects/JsonRandom.cpp +++ b/lib/mapObjects/JsonRandom.cpp @@ -99,7 +99,7 @@ namespace JsonRandom std::string resourceName = loadKey(value, rng, defaultResources); si32 resourceAmount = loadValue(value, rng, 0); - si32 resourceID(VLC->modh->identifiers.getIdentifier(value.meta, "resource", resourceName).get()); + si32 resourceID(VLC->modh->identifiers.getIdentifier(value.meta, "resource", resourceName).value()); TResources ret; ret[resourceID] = resourceAmount; @@ -138,7 +138,7 @@ namespace JsonRandom { for(const auto & pair : value.Struct()) { - SecondarySkill id(VLC->modh->identifiers.getIdentifier(pair.second.meta, "skill", pair.first).get()); + SecondarySkill id(VLC->modh->identifiers.getIdentifier(pair.second.meta, "skill", pair.first).value()); ret[id] = loadValue(pair.second, rng); } } @@ -153,7 +153,7 @@ namespace JsonRandom for(const auto & element : value.Vector()) { - SecondarySkill id(VLC->modh->identifiers.getIdentifier(element.meta, "skill", loadKey(element, rng, defaultSkills)).get()); + SecondarySkill id(VLC->modh->identifiers.getIdentifier(element.meta, "skill", loadKey(element, rng, defaultSkills)).value()); ret[id] = loadValue(element, rng); } } @@ -163,7 +163,7 @@ namespace JsonRandom ArtifactID loadArtifact(const JsonNode & value, CRandomGenerator & rng) { if (value.getType() == JsonNode::JsonType::DATA_STRING) - return ArtifactID(VLC->modh->identifiers.getIdentifier("artifact", value).get()); + return ArtifactID(VLC->modh->identifiers.getIdentifier("artifact", value).value()); std::set allowedClasses; std::set allowedPositions; @@ -224,7 +224,7 @@ namespace JsonRandom SpellID loadSpell(const JsonNode & value, CRandomGenerator & rng, std::vector spells) { if (value.getType() == JsonNode::JsonType::DATA_STRING) - return SpellID(VLC->modh->identifiers.getIdentifier("spell", value).get()); + return SpellID(VLC->modh->identifiers.getIdentifier("spell", value).value()); vstd::erase_if(spells, [=](const SpellID & spell) { @@ -252,7 +252,7 @@ namespace JsonRandom CStackBasicDescriptor loadCreature(const JsonNode & value, CRandomGenerator & rng) { CStackBasicDescriptor stack; - stack.type = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", value["type"]).get()]; + stack.type = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", value["type"]).value()]; stack.count = loadValue(value, rng); if (!value["upgradeChance"].isNull() && !stack.type->upgrades.empty()) { @@ -288,7 +288,7 @@ namespace JsonRandom info.minAmount = static_cast(node["min"].Float()); info.maxAmount = static_cast(node["max"].Float()); } - const CCreature * crea = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", node["type"]).get()]; + const CCreature * crea = VLC->creh->objects[VLC->modh->identifiers.getIdentifier("creature", node["type"]).value()]; info.allowedCreatures.push_back(crea); if (node["upgradeChance"].Float() > 0) { diff --git a/lib/mapObjects/MiscObjects.cpp b/lib/mapObjects/MiscObjects.cpp index cfacc80f1..04503e56d 100644 --- a/lib/mapObjects/MiscObjects.cpp +++ b/lib/mapObjects/MiscObjects.cpp @@ -762,7 +762,7 @@ void CGMine::serializeJsonOptions(JsonSerializeFormat & handler) one.String() = GameConstants::RESOURCE_NAMES[resID]; node.Vector().push_back(one); } - handler.serializeRaw("possibleResources", node, boost::none); + handler.serializeRaw("possibleResources", node, std::nullopt); } else { @@ -1737,7 +1737,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler) if(raw) { bonusType = PRIM_SKILL; - bonusID = raw.get(); + bonusID = raw.value(); } } else if(!json["rewardSkill"].String().empty()) @@ -1746,7 +1746,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler) if(raw) { bonusType = SECONDARY_SKILL; - bonusID = raw.get(); + bonusID = raw.value(); } } else if(!json["rewardSpell"].String().empty()) @@ -1755,7 +1755,7 @@ void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler) if(raw) { bonusType = SPELL; - bonusID = raw.get(); + bonusID = raw.value(); } } } diff --git a/lib/mapping/CCampaignHandler.cpp b/lib/mapping/CCampaignHandler.cpp index a91712494..8cfec9eed 100644 --- a/lib/mapping/CCampaignHandler.cpp +++ b/lib/mapping/CCampaignHandler.cpp @@ -778,13 +778,13 @@ void CCampaignState::setCurrentMapAsConquered(const std::vectorscenarios[*currentMap].conquered = true; } -boost::optional CCampaignState::getBonusForCurrentMap() const +std::optional CCampaignState::getBonusForCurrentMap() const { auto bonuses = getCurrentScenario().travelOptions.bonusesToChoose; assert(chosenCampaignBonuses.count(*currentMap) || bonuses.size() == 0); if(bonuses.empty()) - return boost::optional(); + return std::optional(); else return bonuses[currentBonusID()]; } @@ -817,7 +817,7 @@ CMap * CCampaignState::getMap(int scenarioId) const { // FIXME: there is certainly better way to handle maps inside campaigns if(scenarioId == -1) - scenarioId = currentMap.get(); + scenarioId = currentMap.value(); CMapService mapService; if(camp->header.version == CampaignVersion::Version::VCMI) @@ -834,7 +834,7 @@ CMap * CCampaignState::getMap(int scenarioId) const std::unique_ptr CCampaignState::getHeader(int scenarioId) const { if(scenarioId == -1) - scenarioId = currentMap.get(); + scenarioId = currentMap.value(); CMapService mapService; if(camp->header.version == CampaignVersion::Version::VCMI) @@ -851,7 +851,7 @@ std::unique_ptr CCampaignState::getHeader(int scenarioId) const std::shared_ptr CCampaignState::getMapInfo(int scenarioId) const { if(scenarioId == -1) - scenarioId = currentMap.get(); + scenarioId = currentMap.value(); auto mapInfo = std::make_shared(); mapInfo->fileURI = camp->header.filename; diff --git a/lib/mapping/CCampaignHandler.h b/lib/mapping/CCampaignHandler.h index 9dde5cae1..7b9c1631e 100644 --- a/lib/mapping/CCampaignHandler.h +++ b/lib/mapping/CCampaignHandler.h @@ -245,12 +245,12 @@ public: std::unique_ptr camp; std::string fileEncoding; std::vector mapsConquered, mapsRemaining; - boost::optional currentMap; + std::optional currentMap; std::map chosenCampaignBonuses; void setCurrentMapAsConquered(const std::vector & heroes); - boost::optional getBonusForCurrentMap() const; + std::optional getBonusForCurrentMap() const; const CCampaignScenario & getCurrentScenario() const; CCampaignScenario & getCurrentScenario(); ui8 currentBonusID() const; diff --git a/lib/mapping/CMapOperation.cpp b/lib/mapping/CMapOperation.cpp index 157cee2f5..1865523ba 100644 --- a/lib/mapping/CMapOperation.cpp +++ b/lib/mapping/CMapOperation.cpp @@ -396,10 +396,10 @@ CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainVi { if(terType->getId() == centerTerType->getId()) { - const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType->getId(), rule.name); + const auto patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType->getId(), rule.name); if(auto p = patternForRule) { - auto rslt = validateTerrainView(currentPos, &(*p), 1); + auto rslt = validateTerrainView(currentPos, &(p->get()), 1); if(rslt.result) topPoints = std::max(topPoints, rule.points); } } diff --git a/lib/mapping/MapEditUtils.cpp b/lib/mapping/MapEditUtils.cpp index fcb6c7479..e6ff84f86 100644 --- a/lib/mapping/MapEditUtils.cpp +++ b/lib/mapping/MapEditUtils.cpp @@ -276,35 +276,35 @@ const std::vector & CTerrainViewPatternCon return iter->second; } -boost::optional CTerrainViewPatternConfig::getTerrainViewPatternById(const std::string & patternId, const std::string & id) const +std::optional> CTerrainViewPatternConfig::getTerrainViewPatternById(const std::string & patternId, const std::string & id) const { auto iter = terrainViewPatterns.find(patternId); - const std::vector & groupPatterns = (iter == terrainViewPatterns.end()) ? terrainViewPatterns.at("normal") : iter->second; + const auto & groupPatterns = (iter == terrainViewPatterns.end()) ? terrainViewPatterns.at("normal") : iter->second; - for (const TVPVector & patternFlips : groupPatterns) + for(const auto & patternFlips : groupPatterns) { - const TerrainViewPattern & pattern = patternFlips.front(); + const auto & pattern = patternFlips.front(); if (id == pattern.id) { - return boost::optional(pattern); + return {std::ref(pattern)}; } } - return boost::optional(); + return {}; } -boost::optional CTerrainViewPatternConfig::getTerrainViewPatternsById(TerrainId terrain, const std::string & id) const +std::optional> CTerrainViewPatternConfig::getTerrainViewPatternsById(TerrainId terrain, const std::string & id) const { - const std::vector & groupPatterns = getTerrainViewPatterns(terrain); - for (const TVPVector & patternFlips : groupPatterns) + const auto & groupPatterns = getTerrainViewPatterns(terrain); + for(const auto & patternFlips : groupPatterns) { - const TerrainViewPattern & pattern = patternFlips.front(); + const auto & pattern = patternFlips.front(); if (id == pattern.id) { - return boost::optional(patternFlips); + return {std::ref(patternFlips)}; } } - return boost::optional(); + return {}; } diff --git a/lib/mapping/MapEditUtils.h b/lib/mapping/MapEditUtils.h index b68e94529..dd45b95e7 100644 --- a/lib/mapping/MapEditUtils.h +++ b/lib/mapping/MapEditUtils.h @@ -217,8 +217,8 @@ public: CTerrainViewPatternConfig(); const std::vector & getTerrainViewPatterns(TerrainId terrain) const; - boost::optional getTerrainViewPatternById(const std::string & patternId, const std::string & id) const; - boost::optional getTerrainViewPatternsById(TerrainId terrain, const std::string & id) const; + std::optional> getTerrainViewPatternById(const std::string & patternId, const std::string & id) const; + std::optional> getTerrainViewPatternsById(TerrainId terrain, const std::string & id) const; const TVPVector * getTerrainTypePatternById(const std::string & id) const; void flipPattern(TerrainViewPattern & pattern, int flip) const; diff --git a/lib/mapping/MapFormatJson.cpp b/lib/mapping/MapFormatJson.cpp index e668380dd..8ddfbb75c 100644 --- a/lib/mapping/MapFormatJson.cpp +++ b/lib/mapping/MapFormatJson.cpp @@ -224,7 +224,7 @@ namespace TriggeredEventsDetail auto type = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), fullIdentifier, false); if(type) - event.objectType = type.get(); + event.objectType = type.value(); event.objectInstanceName = data["object"].String(); if(data["value"].isNumber()) event.value = static_cast(data["value"].Integer()); @@ -242,7 +242,7 @@ namespace TriggeredEventsDetail { auto identifier = VLC->modh->identifiers.getIdentifier(data["type"]); if(identifier) - event.objectType = identifier.get(); + event.objectType = identifier.value(); else throw std::runtime_error("Identifier resolution failed in event condition"); } @@ -658,7 +658,7 @@ void CMapFormatJson::writeTeams(JsonSerializer & handler) } dest.Vector().push_back(std::move(team)); } - handler.serializeRaw("teams", dest, boost::none); + handler.serializeRaw("teams", dest, std::nullopt); } } @@ -695,7 +695,7 @@ void CMapFormatJson::writeTriggeredEvents(JsonSerializer & handler) for(const auto & event : mapHeader->triggeredEvents) writeTriggeredEvent(event, triggeredEvents[event.identifier]); - handler.serializeRaw("triggeredEvents", triggeredEvents, boost::none); + handler.serializeRaw("triggeredEvents", triggeredEvents, std::nullopt); } void CMapFormatJson::writeTriggeredEvent(const TriggeredEvent & event, JsonNode & dest) const @@ -774,7 +774,7 @@ void CMapFormatJson::writeDisposedHeroes(JsonSerializeFormat & handler) players.Vector().push_back(player); } } - definition->serializeRaw("availableFor", players, boost::none); + definition->serializeRaw("availableFor", players, std::nullopt); } } @@ -1193,7 +1193,7 @@ void CMapLoaderJson::MapObjectLoader::configure() auto spellIdentifier = configuration["options"]["spell"].String(); auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "spell", spellIdentifier); if(rawId) - spellID = rawId.get(); + spellID = rawId.value(); else spellID = 0; artID = ArtifactID::SPELL_SCROLL; diff --git a/lib/rmg/CRmgTemplate.cpp b/lib/rmg/CRmgTemplate.cpp index 17c56852b..385211759 100644 --- a/lib/rmg/CRmgTemplate.cpp +++ b/lib/rmg/CRmgTemplate.cpp @@ -137,7 +137,7 @@ ZoneOptions::ZoneOptions(): type(ETemplateZoneType::PLAYER_START), size(1), maxTreasureValue(0), - owner(boost::none), + owner(std::nullopt), matchTerrainToTown(true), townsAreSameType(false), zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL), @@ -182,7 +182,7 @@ void ZoneOptions::setSize(int value) size = value; } -boost::optional ZoneOptions::getOwner() const +std::optional ZoneOptions::getOwner() const { return owner; } @@ -355,7 +355,7 @@ void ZoneOptions::serializeJson(JsonSerializeFormat & handler) node.Vector().push_back(n); } } - handler.serializeRaw("terrainTypes", node, boost::none); + handler.serializeRaw("terrainTypes", node, std::nullopt); if(!handler.saving) { if(!node.Vector().empty()) @@ -657,7 +657,7 @@ void CRmgTemplate::serializeJson(JsonSerializeFormat & handler) node.Vector().push_back(n); } } - handler.serializeRaw("allowedWaterContent", node, boost::none); + handler.serializeRaw("allowedWaterContent", node, std::nullopt); if(!handler.saving) { for(auto wc : node.Vector()) diff --git a/lib/rmg/CRmgTemplate.h b/lib/rmg/CRmgTemplate.h index fc2479346..186880b2f 100644 --- a/lib/rmg/CRmgTemplate.h +++ b/lib/rmg/CRmgTemplate.h @@ -124,7 +124,7 @@ public: int getSize() const; void setSize(int value); - boost::optional getOwner() const; + std::optional getOwner() const; const std::set & getTerrainTypes() const; void setTerrainTypes(const std::set & value); @@ -166,7 +166,7 @@ protected: ETemplateZoneType::ETemplateZoneType type; int size; ui32 maxTreasureValue; - boost::optional owner; + std::optional owner; CTownInfo playerTowns; CTownInfo neutralTowns; bool matchTerrainToTown; diff --git a/lib/rmg/CZonePlacer.cpp b/lib/rmg/CZonePlacer.cpp index 716d8da4b..4551c6262 100644 --- a/lib/rmg/CZonePlacer.cpp +++ b/lib/rmg/CZonePlacer.cpp @@ -175,7 +175,7 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const zonesToPlace.push_back(zone); else //place players depending on their factions { - if (boost::optional owner = zone.second->getOwner()) + if(std::optional owner = zone.second->getOwner()) { auto player = PlayerColor(*owner - 1); auto playerSettings = map.getMapGenOptions().getPlayersSettings(); diff --git a/lib/rmg/ObjectDistributor.cpp b/lib/rmg/ObjectDistributor.cpp index c8ce97cad..d9b338ef2 100644 --- a/lib/rmg/ObjectDistributor.cpp +++ b/lib/rmg/ObjectDistributor.cpp @@ -98,7 +98,7 @@ void ObjectDistributor::distributeLimitedObjects() oi.templ = temp; //Rounding up will make sure all possible objects are exhausted - uint32_t mapLimit = rmgInfo.mapLimit.get(); + uint32_t mapLimit = rmgInfo.mapLimit.value(); uint32_t maxPerZone = std::ceil(float(mapLimit) / numZones); //But not more than zone limit diff --git a/lib/serializer/BinaryDeserializer.h b/lib/serializer/BinaryDeserializer.h index 20d47d8a2..c8a2588f8 100644 --- a/lib/serializer/BinaryDeserializer.h +++ b/lib/serializer/BinaryDeserializer.h @@ -9,6 +9,7 @@ */ #pragma once +#include #include #include "CTypeList.h" @@ -43,10 +44,21 @@ class DLL_LINKAGE BinaryDeserializer : public CLoaderBase Source & source; std::vector> funcs; + template + struct mpl_types_impl; + + template + struct mpl_types_impl> { + using type = boost::mpl::vector; + }; + + template + using mpl_types = typename mpl_types_impl::type; + VariantLoaderHelper(Source & source): source(source) { - boost::mpl::for_each(std::ref(*this)); + boost::mpl::for_each>(std::ref(*this)); } template @@ -170,7 +182,7 @@ public: std::map loadedPointers; std::map loadedPointersTypes; - std::map loadedSharedPointers; + std::map loadedSharedPointers; bool smartPointerSerialization; bool saving; @@ -365,13 +377,13 @@ public: if(*actualType == *typeWeNeedToReturn) { // No casting needed, just unpack already stored shared_ptr and return it - data = boost::any_cast>(itr->second); + data = std::any_cast>(itr->second); } else { // We need to perform series of casts auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn); - data = boost::any_cast>(ret); + data = std::any_cast>(ret); } } catch(std::exception &e) @@ -494,10 +506,10 @@ public: this->read((void*)data.c_str(),length); } - template - void load(boost::variant &data) + template + void load(std::variant & data) { - typedef boost::variant TVariant; + using TVariant = std::variant; VariantLoaderHelper loader(*this); @@ -507,8 +519,8 @@ public: data = loader.funcs.at(which)(); } - template - void load(boost::optional & data) + template + void load(std::optional & data) { ui8 present; load( present ); @@ -517,11 +529,11 @@ public: //TODO: replace with emplace once we start request Boost 1.56+, see PR360 T t; load(t); - data = boost::make_optional(std::move(t)); + data = std::make_optional(std::move(t)); } else { - data = boost::optional(); + data = std::optional(); } } diff --git a/lib/serializer/BinarySerializer.h b/lib/serializer/BinarySerializer.h index 8a622dc9f..df0da5ed5 100644 --- a/lib/serializer/BinarySerializer.h +++ b/lib/serializer/BinarySerializer.h @@ -36,8 +36,8 @@ public: /// VCMI Classes: recursively serialize them via ClassName::serialize( BinarySerializer &, int version) call class DLL_LINKAGE BinarySerializer : public CSaverBase { - template - struct VariantVisitorSaver : boost::static_visitor<> + template + struct VariantVisitorSaver { Handler &h; VariantVisitorSaver(Handler &H):h(H) @@ -330,17 +330,17 @@ public: save(i->second); } } - template - void save(const boost::variant &data) + template + void save(const std::variant & data) { - si32 which = data.which(); + si32 which = data.index(); save(which); VariantVisitorSaver visitor(*this); - boost::apply_visitor(visitor, data); + std::visit(visitor, data); } - template - void save(const boost::optional &data) + template + void save(const std::optional & data) { if(data) { diff --git a/lib/serializer/CSerializer.h b/lib/serializer/CSerializer.h index e5b5acb4c..407c5bcc3 100644 --- a/lib/serializer/CSerializer.h +++ b/lib/serializer/CSerializer.h @@ -76,7 +76,7 @@ class DLL_LINKAGE CSerializer vectors[&typeid(T)] = VectorizedObjectInfo(Vector, idRetriever); } - typedef std::map TTypeVecMap; + typedef std::map TTypeVecMap; TTypeVecMap vectors; //entry must be a pointer to vector containing pointers to the objects of key type public: @@ -103,7 +103,7 @@ public: #ifndef __APPLE__ assert(i->second.type() == typeid(VectorizedObjectInfo)); #endif - VectorizedObjectInfo *ret = &(boost::any_cast&>(i->second)); + auto *ret = std::any_cast>(&i->second); return ret; } } diff --git a/lib/serializer/CTypeList.h b/lib/serializer/CTypeList.h index 46a08695e..a4a9f8a6b 100644 --- a/lib/serializer/CTypeList.h +++ b/lib/serializer/CTypeList.h @@ -15,30 +15,30 @@ VCMI_LIB_NAMESPACE_BEGIN struct IPointerCaster { - virtual boost::any castRawPtr(const boost::any &ptr) const = 0; // takes From*, returns To* - virtual boost::any castSharedPtr(const boost::any &ptr) const = 0; // takes std::shared_ptr, performs dynamic cast, returns std::shared_ptr - virtual boost::any castWeakPtr(const boost::any &ptr) const = 0; // takes std::weak_ptr, performs dynamic cast, returns std::weak_ptr. The object under poitner must live. - //virtual boost::any castUniquePtr(const boost::any &ptr) const = 0; // takes std::unique_ptr, performs dynamic cast, returns std::unique_ptr + virtual std::any castRawPtr(const std::any &ptr) const = 0; // takes From*, returns To* + virtual std::any castSharedPtr(const std::any &ptr) const = 0; // takes std::shared_ptr, performs dynamic cast, returns std::shared_ptr + virtual std::any castWeakPtr(const std::any &ptr) const = 0; // takes std::weak_ptr, performs dynamic cast, returns std::weak_ptr. The object under poitner must live. + //virtual std::any castUniquePtr(const std::any &ptr) const = 0; // takes std::unique_ptr, performs dynamic cast, returns std::unique_ptr virtual ~IPointerCaster() = default; }; template struct PointerCaster : IPointerCaster { - virtual boost::any castRawPtr(const boost::any &ptr) const override // takes void* pointing to From object, performs dynamic cast, returns void* pointing to To object + virtual std::any castRawPtr(const std::any &ptr) const override // takes void* pointing to From object, performs dynamic cast, returns void* pointing to To object { - From * from = (From*)boost::any_cast(ptr); + From * from = (From*)std::any_cast(ptr); To * ret = static_cast(from); return (void*)ret; } // Helper function performing casts between smart pointers template - boost::any castSmartPtr(const boost::any &ptr) const + std::any castSmartPtr(const std::any &ptr) const { try { - auto from = boost::any_cast(ptr); + auto from = std::any_cast(ptr); auto ret = std::static_pointer_cast(from); return ret; } @@ -48,13 +48,13 @@ struct PointerCaster : IPointerCaster } } - virtual boost::any castSharedPtr(const boost::any &ptr) const override + virtual std::any castSharedPtr(const std::any &ptr) const override { return castSmartPtr>(ptr); } - virtual boost::any castWeakPtr(const boost::any &ptr) const override + virtual std::any castWeakPtr(const std::any &ptr) const override { - auto from = boost::any_cast>(ptr); + auto from = std::any_cast>(ptr); return castSmartPtr>(from.lock()); } }; @@ -88,13 +88,13 @@ private: 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 + template + std::any castHelper(std::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; + std::any ptr = inputPtr; for(int i = 0; i < static_cast(typesSequence.size()) - 1; i++) { auto &from = typesSequence[i]; @@ -158,13 +158,13 @@ public: return const_cast(reinterpret_cast(inputPtr)); } - return boost::any_cast(castHelper<&IPointerCaster::castRawPtr>( + return std::any_cast(castHelper<&IPointerCaster::castRawPtr>( const_cast(reinterpret_cast(inputPtr)), &baseType, derivedType)); } template - boost::any castSharedToMostDerived(const std::shared_ptr inputPtr) const + std::any castSharedToMostDerived(const std::shared_ptr inputPtr) const { auto &baseType = typeid(typename std::remove_cv::type); auto derivedType = getTypeInfo(inputPtr.get()); @@ -177,9 +177,9 @@ public: 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)); + return std::any_cast(castHelper<&IPointerCaster::castRawPtr>(inputPtr, from, to)); } - boost::any castShared(boost::any inputPtr, const std::type_info *from, const std::type_info *to) const + std::any castShared(std::any inputPtr, const std::type_info *from, const std::type_info *to) const { return castHelper<&IPointerCaster::castSharedPtr>(inputPtr, from, to); } diff --git a/lib/serializer/JsonDeserializer.cpp b/lib/serializer/JsonDeserializer.cpp index 0c34d064a..5cb7c1398 100644 --- a/lib/serializer/JsonDeserializer.cpp +++ b/lib/serializer/JsonDeserializer.cpp @@ -31,12 +31,12 @@ void JsonDeserializer::serializeInternal(const std::string & fieldName, boost::l value = data.Bool(); } -void JsonDeserializer::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) +void JsonDeserializer::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) { std::string identifier; serializeString(fieldName, identifier); - value = defaultValue ? defaultValue.get() : 0; + value = defaultValue.value_or(0); if(!identifier.empty()) { @@ -74,31 +74,31 @@ void JsonDeserializer::serializeInternal(const std::string & fieldName, std::vec } } -void JsonDeserializer::serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) +void JsonDeserializer::serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) { const JsonNode & data = currentObject->operator[](fieldName); if(!data.isNumber()) - value = defaultValue ? defaultValue.get() : 0;//todo: report error on not null? + value = defaultValue.value_or(0);//todo: report error on not null? else value = data.Float(); } -void JsonDeserializer::serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) +void JsonDeserializer::serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) { const JsonNode & data = currentObject->operator[](fieldName); if(!data.isNumber()) - value = defaultValue ? defaultValue.get() : 0;//todo: report error on not null? + value = defaultValue.value_or(0);//todo: report error on not null? else value = data.Integer(); } -void JsonDeserializer::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) +void JsonDeserializer::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) { const std::string & valueName = currentObject->operator[](fieldName).String(); - const si32 actualOptional = defaultValue ? defaultValue.get() : 0; + const si32 actualOptional = defaultValue.value_or(0); si32 rawValue = vstd::find_pos(enumMap, valueName); if(rawValue < 0) @@ -238,13 +238,13 @@ void JsonDeserializer::serializeString(const std::string & fieldName, std::strin value = currentObject->operator[](fieldName).String(); } -void JsonDeserializer::serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) +void JsonDeserializer::serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) { const JsonNode & data = currentObject->operator[](fieldName); if(data.getType() == JsonNode::JsonType::DATA_NULL) { if(defaultValue) - value = defaultValue.get(); + value = defaultValue.value(); else value.clear(); } diff --git a/lib/serializer/JsonDeserializer.h b/lib/serializer/JsonDeserializer.h index c56443dea..e11892b27 100644 --- a/lib/serializer/JsonDeserializer.h +++ b/lib/serializer/JsonDeserializer.h @@ -24,15 +24,15 @@ public: void serializeLIC(const std::string & fieldName, LICSet & value) override; void serializeString(const std::string & fieldName, std::string & value) override; - void serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) override; + void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) override; protected: void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; void serializeInternal(const std::string & fieldName, std::vector & value, const TDecoder & decoder, const TEncoder & encoder) override; - void serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) override; + void serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) override; void serializeInternal(std::string & value) override; void serializeInternal(int64_t & value) override; diff --git a/lib/serializer/JsonSerializeFormat.h b/lib/serializer/JsonSerializeFormat.h index 696a3710e..f001f6c43 100644 --- a/lib/serializer/JsonSerializeFormat.h +++ b/lib/serializer/JsonSerializeFormat.h @@ -200,7 +200,7 @@ public: template void serializeEnum(const std::string & fieldName, T & value, const std::vector & enumMap) { - doSerializeInternal(fieldName, value, boost::none, enumMap); + doSerializeInternal(fieldName, value, std::nullopt, enumMap); }; ///si32-convertible enum <-> Json string enum @@ -224,7 +224,7 @@ public: template void serializeFloat(const std::string & fieldName, T & value) { - doSerializeInternal(fieldName, value, boost::none); + doSerializeInternal(fieldName, value, std::nullopt); }; ///Anything double-convertible <-> Json double @@ -239,7 +239,7 @@ public: template void serializeInt(const std::string & fieldName, T & value) { - doSerializeInternal(fieldName, value, boost::none); + doSerializeInternal(fieldName, value, std::nullopt); }; ///Anything int64-convertible <-> Json integer @@ -251,9 +251,9 @@ public: }; ///Anything int64-convertible <-> Json integer - ///default value is boost::none - template - void serializeInt(const std::string & fieldName, boost::optional & value) + ///default value is std::nullopt + template + void serializeInt(const std::string & fieldName, std::optional & value) { dispatchOptional(fieldName, value); }; @@ -420,7 +420,7 @@ public: value.serializeJson(*this); } - virtual void serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) = 0; + virtual void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) = 0; protected: JsonSerializeFormat(const IInstanceResolver * instanceResolver_, const bool saving_, const bool updating_); @@ -429,19 +429,19 @@ protected: virtual void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) = 0; ///Numeric Id <-> String Id - virtual void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) = 0; + virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) = 0; ///Numeric Id vector <-> String Id vector virtual void serializeInternal(const std::string & fieldName, std::vector & value, const TDecoder & decoder, const TEncoder & encoder) = 0; ///Numeric <-> Json double - virtual void serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) = 0; + virtual void serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) = 0; ///Numeric <-> Json integer - virtual void serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) = 0; + virtual void serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) = 0; ///Enum/Numeric <-> Json string enum - virtual void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) = 0; + virtual void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) = 0; virtual void pop() = 0; virtual void pushStruct(const std::string & fieldName) = 0; @@ -457,10 +457,10 @@ protected: private: const IInstanceResolver * instanceResolver; - template - void doSerializeInternal(const std::string & fieldName, VType & value, const boost::optional & defaultValue, Args ... args) + template + void doSerializeInternal(const std::string & fieldName, VType & value, const std::optional & defaultValue, Args... args) { - const boost::optional tempDefault = defaultValue ? boost::optional(static_cast(defaultValue.get())) : boost::none; + const std::optional tempDefault = defaultValue ? std::optional(static_cast(defaultValue.value())) : std::nullopt; IType temp = static_cast(value); serializeInternal(fieldName, temp, tempDefault, args...); @@ -469,14 +469,14 @@ private: value = static_cast(temp); } - template - void dispatchOptional(const std::string & fieldName, boost::optional & value, Args ... args) + template + void dispatchOptional(const std::string & fieldName, std::optional & value, Args... args) { if(saving) { if(value) { - IType temp = static_cast(value.get()); + IType temp = static_cast(value.value()); pushField(fieldName); serializeInternal(temp, args...); pop(); @@ -488,13 +488,13 @@ private: if(getCurrent().getType() == JsonNode::JsonType::DATA_NULL) { - value = boost::none; + value = std::nullopt; } else { IType temp = IType(); serializeInternal(temp, args...); - value = boost::make_optional(temp); + value = std::make_optional(temp); } pop(); diff --git a/lib/serializer/JsonSerializer.cpp b/lib/serializer/JsonSerializer.cpp index 69253b986..4db9b5817 100644 --- a/lib/serializer/JsonSerializer.cpp +++ b/lib/serializer/JsonSerializer.cpp @@ -26,30 +26,30 @@ void JsonSerializer::serializeInternal(const std::string & fieldName, boost::log currentObject->operator[](fieldName).Bool() = (bool)value; } -void JsonSerializer::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) +void JsonSerializer::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) { - if(!defaultValue || defaultValue.get() != value) + if(!defaultValue || defaultValue.value() != value) { std::string identifier = encoder(value); serializeString(fieldName, identifier); } } -void JsonSerializer::serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) +void JsonSerializer::serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) { - if(!defaultValue || defaultValue.get() != value) + if(!defaultValue || defaultValue.value() != value) currentObject->operator[](fieldName).Float() = value; } -void JsonSerializer::serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) +void JsonSerializer::serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) { - if(!defaultValue || defaultValue.get() != value) + if(!defaultValue || defaultValue.value() != value) currentObject->operator[](fieldName).Integer() = value; } -void JsonSerializer::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) +void JsonSerializer::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) { - if(!defaultValue || defaultValue.get() != value) + if(!defaultValue || defaultValue.value() != value) currentObject->operator[](fieldName).String() = enumMap.at(value); } @@ -112,9 +112,9 @@ void JsonSerializer::serializeString(const std::string & fieldName, std::string currentObject->operator[](fieldName).String() = value; } -void JsonSerializer::serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) +void JsonSerializer::serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) { - if(!defaultValue || value != defaultValue.get()) + if(!defaultValue || value != defaultValue.value()) currentObject->operator[](fieldName) = value; } diff --git a/lib/serializer/JsonSerializer.h b/lib/serializer/JsonSerializer.h index c75bf1ac6..18afa0909 100644 --- a/lib/serializer/JsonSerializer.h +++ b/lib/serializer/JsonSerializer.h @@ -23,15 +23,15 @@ public: void serializeLIC(const std::string & fieldName, LICSet & value) override; void serializeString(const std::string & fieldName, std::string & value) override; - void serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) override; + void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) override; protected: void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; void serializeInternal(const std::string & fieldName, std::vector & value, const TDecoder & decoder, const TEncoder & encoder) override; - void serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) override; + void serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) override; void serializeInternal(std::string & value) override; void serializeInternal(int64_t & value) override; diff --git a/lib/serializer/JsonUpdater.cpp b/lib/serializer/JsonUpdater.cpp index 2712c1c26..a2538b1b8 100644 --- a/lib/serializer/JsonUpdater.cpp +++ b/lib/serializer/JsonUpdater.cpp @@ -28,12 +28,12 @@ void JsonUpdater::serializeInternal(const std::string & fieldName, boost::logic: value = data.Bool(); } -void JsonUpdater::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) +void JsonUpdater::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) { // std::string identifier; // serializeString(fieldName, identifier); // -// value = defaultValue ? defaultValue.get() : 0; +// value = defaultValue.value_or(0); // // if(identifier != "") // { @@ -59,7 +59,7 @@ void JsonUpdater::serializeInternal(const std::string & fieldName, std::vector & defaultValue) +void JsonUpdater::serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) { const JsonNode & data = currentObject->operator[](fieldName); @@ -67,7 +67,7 @@ void JsonUpdater::serializeInternal(const std::string & fieldName, double & valu value = data.Float(); } -void JsonUpdater::serializeInternal(const std::string & fieldName, si64 & value, const boost::optional &) +void JsonUpdater::serializeInternal(const std::string & fieldName, si64 & value, const std::optional &) { const JsonNode & data = currentObject->operator[](fieldName); @@ -75,11 +75,11 @@ void JsonUpdater::serializeInternal(const std::string & fieldName, si64 & value, value = data.Integer(); } -void JsonUpdater::serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) +void JsonUpdater::serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) { // const std::string & valueName = currentObject->operator[](fieldName).String(); // -// const si32 actualOptional = defaultValue ? defaultValue.get() : 0; +// const si32 actualOptional = defaultValue.value_or(0); // // si32 rawValue = vstd::find_pos(enumMap, valueName); // if(rawValue < 0) @@ -230,7 +230,7 @@ void JsonUpdater::serializeString(const std::string & fieldName, std::string & v value = data.String(); } -void JsonUpdater::serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) +void JsonUpdater::serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) { const JsonNode & data = currentObject->operator[](fieldName); if(data.getType() != JsonNode::JsonType::DATA_NULL) diff --git a/lib/serializer/JsonUpdater.h b/lib/serializer/JsonUpdater.h index b549dbad2..47e55ea74 100644 --- a/lib/serializer/JsonUpdater.h +++ b/lib/serializer/JsonUpdater.h @@ -26,17 +26,17 @@ public: void serializeLIC(const std::string & fieldName, LICSet & value) override; void serializeString(const std::string & fieldName, std::string & value) override; - void serializeRaw(const std::string & fieldName, JsonNode & value, const boost::optional defaultValue) override; + void serializeRaw(const std::string & fieldName, JsonNode & value, const std::optional> defaultValue) override; void serializeBonuses(const std::string & fieldName, CBonusSystemNode * value); protected: void serializeInternal(const std::string & fieldName, boost::logic::tribool & value) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const TDecoder & decoder, const TEncoder & encoder) override; void serializeInternal(const std::string & fieldName, std::vector & value, const TDecoder & decoder, const TEncoder & encoder) override; - void serializeInternal(const std::string & fieldName, double & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si64 & value, const boost::optional & defaultValue) override; - void serializeInternal(const std::string & fieldName, si32 & value, const boost::optional & defaultValue, const std::vector & enumMap) override; + void serializeInternal(const std::string & fieldName, double & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si64 & value, const std::optional & defaultValue) override; + void serializeInternal(const std::string & fieldName, si32 & value, const std::optional & defaultValue, const std::vector & enumMap) override; void serializeInternal(std::string & value) override; void serializeInternal(int64_t & value) override; diff --git a/lib/spells/BattleSpellMechanics.cpp b/lib/spells/BattleSpellMechanics.cpp index 81a8709bc..b243c6b3c 100644 --- a/lib/spells/BattleSpellMechanics.cpp +++ b/lib/spells/BattleSpellMechanics.cpp @@ -200,7 +200,7 @@ bool BattleSpellMechanics::canBeCast(Problem & problem) const //TODO: check creature abilities to block //TODO: check any possible caster - if(battle()->battleMaxSpellLevel(side.get()) < getSpellLevel() || battle()->battleMinSpellLevel(side.get()) > getSpellLevel()) + if(battle()->battleMaxSpellLevel(side.value()) < getSpellLevel() || battle()->battleMinSpellLevel(side.value()) > getSpellLevel()) return adaptProblem(ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED, problem); return effects->applicable(problem, this); diff --git a/lib/spells/CSpellHandler.cpp b/lib/spells/CSpellHandler.cpp index 31e2204d7..b213f9575 100644 --- a/lib/spells/CSpellHandler.cpp +++ b/lib/spells/CSpellHandler.cpp @@ -349,7 +349,7 @@ si32 CSpell::getProbability(const FactionID & factionId) const return probabilities.at(factionId); } -void CSpell::getEffects(std::vector & lst, const int level, const bool cumulative, const si32 duration, boost::optional maxDuration) const +void CSpell::getEffects(std::vector & lst, const int level, const bool cumulative, const si32 duration, std::optional maxDuration) const { if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS) { @@ -377,7 +377,7 @@ void CSpell::getEffects(std::vector & lst, const int level, const bool cu if(nb.turnsRemain == 0) nb.turnsRemain = duration; if(maxDuration) - vstd::amax(*(maxDuration.get()), nb.turnsRemain); + vstd::amax(*(maxDuration.value()), nb.turnsRemain); lst.push_back(nb); } diff --git a/lib/spells/CSpellHandler.h b/lib/spells/CSpellHandler.h index 607f6077f..60b3386a9 100644 --- a/lib/spells/CSpellHandler.h +++ b/lib/spells/CSpellHandler.h @@ -217,7 +217,7 @@ public: spells::AimType getTargetType() const; bool hasEffects() const; - void getEffects(std::vector & lst, const int level, const bool cumulative, const si32 duration, boost::optional maxDuration = boost::none) const; + void getEffects(std::vector & lst, const int level, const bool cumulative, const si32 duration, std::optional maxDuration = std::nullopt) const; bool hasBattleEffects() const; diff --git a/lib/spells/ISpellMechanics.cpp b/lib/spells/ISpellMechanics.cpp index fc7a27d9f..6da400c26 100644 --- a/lib/spells/ISpellMechanics.cpp +++ b/lib/spells/ISpellMechanics.cpp @@ -222,22 +222,22 @@ boost::logic::tribool BattleCast::isMassive() const void BattleCast::setSpellLevel(BattleCast::Value value) { - magicSkillLevel = boost::make_optional(value); + magicSkillLevel = std::make_optional(value); } void BattleCast::setEffectPower(BattleCast::Value value) { - effectPower = boost::make_optional(value); + effectPower = std::make_optional(value); } void BattleCast::setEffectDuration(BattleCast::Value value) { - effectDuration = boost::make_optional(value); + effectDuration = std::make_optional(value); } void BattleCast::setEffectValue(BattleCast::Value64 value) { - effectValue = boost::make_optional(value); + effectValue = std::make_optional(value); } void BattleCast::applyEffects(ServerCallback * server, const Target & target, bool indirect, bool ignoreImmunity) const @@ -424,54 +424,32 @@ BaseMechanics::BaseMechanics(const IBattleCast * event): caster = event->getCaster(); //FIXME: do not crash on invalid side - casterSide = cb->playerToSide(caster->getCasterOwner()).get(); + casterSide = cb->playerToSide(caster->getCasterOwner()).value(); { auto value = event->getSpellLevel(); - if(value) - rangeLevel = value.get(); - else - rangeLevel = caster->getSpellSchoolLevel(owner); + rangeLevel = value.value_or(caster->getSpellSchoolLevel(owner)); vstd::abetween(rangeLevel, 0, 3); } { auto value = event->getSpellLevel(); - if(value) - effectLevel = value.get(); - else - effectLevel = caster->getEffectLevel(owner); + effectLevel = value.value_or(caster->getEffectLevel(owner)); vstd::abetween(effectLevel, 0, 3); } { auto value = event->getEffectPower(); - if(value) - effectPower = value.get(); - else - effectPower = caster->getEffectPower(owner); + effectPower = value.value_or(caster->getEffectPower(owner)); vstd::amax(effectPower, 0); } { auto value = event->getEffectDuration(); - if(value) - effectDuration = value.get(); - else - effectDuration = caster->getEnchantPower(owner); + effectDuration = value.value_or(caster->getEnchantPower(owner)); vstd::amax(effectDuration, 0); //??? } { auto value = event->getEffectValue(); - if(value) - { - effectValue = value.get(); - } - else - { - auto casterValue = caster->getEffectValue(owner); - if(casterValue == 0) - effectValue = owner->calculateRawEffectValue(effectLevel, effectPower, 1); - else - effectValue = casterValue; - } + auto casterValue = caster->getEffectValue(owner) ? caster->getEffectValue(owner) : owner->calculateRawEffectValue(effectLevel, effectPower, 1); + effectValue = value.value_or(casterValue); vstd::amax(effectValue, 0); } } diff --git a/lib/spells/ISpellMechanics.h b/lib/spells/ISpellMechanics.h index 4d6f828e6..b9be708a7 100644 --- a/lib/spells/ISpellMechanics.h +++ b/lib/spells/ISpellMechanics.h @@ -68,8 +68,8 @@ public: using Value = int32_t; using Value64 = int64_t; - using OptionalValue = boost::optional; - using OptionalValue64 = boost::optional; + using OptionalValue = std::optional; + using OptionalValue64 = std::optional; virtual const CSpell * getSpell() const = 0; virtual Mode getMode() const = 0; diff --git a/lib/spells/TargetCondition.cpp b/lib/spells/TargetCondition.cpp index 3f2d638e4..14e42ac41 100644 --- a/lib/spells/TargetCondition.cpp +++ b/lib/spells/TargetCondition.cpp @@ -350,7 +350,7 @@ public: auto rawId = VLC->modh->identifiers.getIdentifier(scope, type, identifier, true); if(rawId) - return std::make_shared(CreatureID(rawId.get())); + return std::make_shared(CreatureID(rawId.value())); else logMod->error("Invalid creature %s type in spell target condition.", identifier); } @@ -359,7 +359,7 @@ public: auto rawId = VLC->modh->identifiers.getIdentifier(scope, type, identifier, true); if(rawId) - return std::make_shared(SpellID(rawId.get())); + return std::make_shared(SpellID(rawId.value())); else logMod->error("Invalid spell %s in spell target condition.", identifier); } diff --git a/osx/vcmi.icns b/osx/vcmi.icns index 4fdfe983d..6b11520ec 100644 Binary files a/osx/vcmi.icns and b/osx/vcmi.icns differ diff --git a/scripting/erm/ERMInterpreter.cpp b/scripting/erm/ERMInterpreter.cpp index a29ee54f4..663cb3572 100644 --- a/scripting/erm/ERMInterpreter.cpp +++ b/scripting/erm/ERMInterpreter.cpp @@ -156,13 +156,13 @@ namespace ERMConverter } }; - struct LVL2IexpToVar : boost::static_visitor + struct LVL2IexpToVar { LVL2IexpToVar() = default; Variable operator()(const TVarExpNotMacro & val) const { - if(val.val.is_initialized()) + if(val.val.has_value()) return Variable(val.varsym, val.val.get()); else return Variable(val.varsym, 0); @@ -174,30 +174,27 @@ namespace ERMConverter } }; - struct LVL1IexpToVar : boost::static_visitor + struct LVL1IexpToVar { LVL1IexpToVar() = default; - Variable operator()(int const & constant) const + Variable operator()(const int & constant) const { return Variable("", constant); } Variable operator()(const TVarExp & var) const { - return boost::apply_visitor(LVL2IexpToVar(), var); + return std::visit(LVL2IexpToVar(), var); } }; - struct Condition : public boost::static_visitor + struct Condition { - Condition() - {} - std::string operator()(const TComparison & cmp) const { - Variable lhs = boost::apply_visitor(LVL1IexpToVar(), cmp.lhs); - Variable rhs = boost::apply_visitor(LVL1IexpToVar(), cmp.rhs); + Variable lhs = std::visit(LVL1IexpToVar(), cmp.lhs); + Variable rhs = std::visit(LVL1IexpToVar(), cmp.rhs); auto sign = CMP_OPERATION.find(cmp.compSign); if(sign == std::end(CMP_OPERATION)) @@ -207,7 +204,7 @@ namespace ERMConverter fmt % lhs.str() % sign->second % rhs.str(); return fmt.str(); } - std::string operator()(int const & flag) const + std::string operator()(const int & flag) const { return boost::to_string(boost::format("F['%d']") % flag); } @@ -222,7 +219,7 @@ namespace ERMConverter std::string semiCmpSign = ""; }; - struct Converter : public boost::static_visitor<> + struct Converter { mutable std::ostream * out; Converter(std::ostream * out_) @@ -246,11 +243,8 @@ namespace ERMConverter } }; - struct GetBodyOption : public boost::static_visitor + struct GetBodyOption { - GetBodyOption() - {} - virtual std::string operator()(const TVarConcatString & cmp) const { throw EScriptExecError("String concatenation not allowed in this receiver"); @@ -285,7 +279,7 @@ namespace ERMConverter } }; - struct BodyOption : public boost::static_visitor + struct BodyOption { ParamIO operator()(const TVarConcatString & cmp) const { @@ -314,7 +308,7 @@ namespace ERMConverter ret.isInput = false; ret.semi = true; ret.semiCmpSign = cmp.compSign; - ret.name = (boost::apply_visitor(LVL1IexpToVar(), cmp.rhs)).str(); + ret.name = (std::visit(LVL1IexpToVar(), cmp.rhs)).str(); return ret; } @@ -327,7 +321,7 @@ namespace ERMConverter { ParamIO ret; ret.isInput = true; - ret.name = (boost::apply_visitor(LVL1IexpToVar(), cmp)).str();; + ret.name = (std::visit(LVL1IexpToVar(), cmp)).str();; return ret; } @@ -336,7 +330,7 @@ namespace ERMConverter ParamIO ret; ret.isInput = false; - ret.name = (boost::apply_visitor(LVL2IexpToVar(), cmp.var)).str(); + ret.name = (std::visit(LVL2IexpToVar(), cmp.var)).str(); return ret; } @@ -396,10 +390,10 @@ namespace ERMConverter std::vector optionParams; - if(trig.params.is_initialized()) + if(trig.params.has_value()) { for(auto & p : trig.params.get()) - optionParams.push_back(boost::apply_visitor(BodyOption(), p)); + optionParams.push_back(std::visit(BodyOption(), p)); } int idx = 1; @@ -511,7 +505,7 @@ namespace ERMConverter FU(std::ostream * out_, const ERM::TIexp & tid) : Receiver(out_), - v(boost::apply_visitor(LVL1IexpToVar(), tid)) + v(std::visit(LVL1IexpToVar(), tid)) { } @@ -558,7 +552,7 @@ namespace ERMConverter MC(std::ostream * out_, const ERM::TIexp & tid) : Receiver(out_), - v(boost::apply_visitor(LVL1IexpToVar(), tid)) + v(std::visit(LVL1IexpToVar(), tid)) { } @@ -576,11 +570,11 @@ namespace ERMConverter { case 'S': { - if(option.params.is_initialized()) + if(option.params.has_value()) { for(auto & p : option.params.get()) { - std::string macroName = boost::apply_visitor(MC_S(), p); + std::string macroName = std::visit(MC_S(), p); boost::format callFormat; @@ -616,7 +610,7 @@ namespace ERMConverter std::string operator()(const TIexp & cmp) const override { - auto v = boost::apply_visitor(LVL1IexpToVar(), cmp); + auto v = std::visit(LVL1IexpToVar(), cmp); return v.str(); } std::string operator()(const TStringConstant & cmp) const override @@ -636,7 +630,7 @@ namespace ERMConverter std::string operator()(const TIexp & cmp) const override { - Variable p = boost::apply_visitor(LVL1IexpToVar(), cmp); + Variable p = std::visit(LVL1IexpToVar(), cmp); if(p.index <= 0) throw EScriptExecError("VR:H requires flag index"); @@ -661,7 +655,7 @@ namespace ERMConverter std::string operator()(const TIexp & cmp) const override { - Variable p = boost::apply_visitor(LVL1IexpToVar(), cmp); + Variable p = std::visit(LVL1IexpToVar(), cmp); return p.str(); } @@ -673,7 +667,7 @@ namespace ERMConverter VR(std::ostream * out_, const ERM::TIexp & tid) : Receiver(out_), - v(boost::apply_visitor(LVL1IexpToVar(), tid)) + v(std::visit(LVL1IexpToVar(), tid)) { } @@ -681,7 +675,7 @@ namespace ERMConverter void operator()(const TVRLogic & trig) const override { - Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.var); + Variable rhs = std::visit(LVL1IexpToVar(), trig.var); std::string opcode; @@ -705,7 +699,7 @@ namespace ERMConverter void operator()(const TVRArithmetic & trig) const override { - Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.rhs); + Variable rhs = std::visit(LVL1IexpToVar(), trig.rhs); std::string opcode; @@ -743,10 +737,10 @@ namespace ERMConverter std::vector optionParams; - if(trig.params.is_initialized()) + if(trig.params.has_value()) { for(auto & p : trig.params.get()) - optionParams.push_back(boost::apply_visitor(BodyOption(), p)); + optionParams.push_back(std::visit(BodyOption(), p)); } auto index = v.index; @@ -765,10 +759,10 @@ namespace ERMConverter break; case 'H': //checking if string is empty { - if(!trig.params.is_initialized() || trig.params.get().size() != 1) + if(!trig.params.has_value() || trig.params.get().size() != 1) throw EScriptExecError("VR:H option takes exactly 1 parameter!"); - std::string opt = boost::apply_visitor(VR_H(), trig.params.get()[0]); + std::string opt = std::visit(VR_H(), trig.params.get()[0]); boost::format fmt("ERM.VR(%s):H(%s)"); fmt % v.str() % opt; putLine(fmt.str()); @@ -776,10 +770,10 @@ namespace ERMConverter break; case 'U': { - if(!trig.params.is_initialized() || trig.params.get().size() != 1) + if(!trig.params.has_value() || trig.params.get().size() != 1) throw EScriptExecError("VR:H/U need 1 parameter!"); - std::string opt = boost::apply_visitor(VR_S(), trig.params.get()[0]); + std::string opt = std::visit(VR_S(), trig.params.get()[0]); boost::format fmt("ERM.VR(%s):%c(%s)"); fmt % v.str() % (trig.optionCode) % opt; putLine(fmt.str()); @@ -787,10 +781,10 @@ namespace ERMConverter break; case 'M': //string operations { - if(!trig.params.is_initialized() || trig.params.get().size() < 2) + if(!trig.params.has_value() || trig.params.get().size() < 2) throw EScriptExecError("VR:M needs at least 2 parameters!"); - std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]); + std::string opt = std::visit(VR_X(), trig.params.get()[0]); int paramIndex = 1; if(opt == "3") @@ -801,7 +795,7 @@ namespace ERMConverter } else { - auto target = boost::apply_visitor(VR_X(), trig.params.get()[paramIndex++]); + auto target = std::visit(VR_X(), trig.params.get()[paramIndex++]); boost::format fmt("%s = ERM.VR(%s):M%s("); fmt % target % v.str() % opt; @@ -810,7 +804,7 @@ namespace ERMConverter for(int i = paramIndex; i < trig.params.get().size(); i++) { - opt = boost::apply_visitor(VR_X(), trig.params.get()[i]); + opt = std::visit(VR_X(), trig.params.get()[i]); if(i > paramIndex) put(","); put(opt); } @@ -820,10 +814,10 @@ namespace ERMConverter break; case 'X': //bit xor { - if(!trig.params.is_initialized() || trig.params.get().size() != 1) + if(!trig.params.has_value() || trig.params.get().size() != 1) throw EScriptExecError("VR:X option takes exactly 1 parameter!"); - std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]); + std::string opt = std::visit(VR_X(), trig.params.get()[0]); boost::format fmt("%s = bit.bxor(%s, %s)"); fmt % v.str() % v.str() % opt;putLine(fmt.str()); @@ -837,10 +831,10 @@ namespace ERMConverter break; case 'S': //setting variable { - if(!trig.params.is_initialized() || trig.params.get().size() != 1) + if(!trig.params.has_value() || trig.params.get().size() != 1) throw EScriptExecError("VR:S option takes exactly 1 parameter!"); - std::string opt = boost::apply_visitor(VR_S(), trig.params.get()[0]); + std::string opt = std::visit(VR_S(), trig.params.get()[0]); put(v.str()); put(" = "); put(opt); @@ -855,10 +849,10 @@ namespace ERMConverter break; case 'V': //convert string to value { - if(!trig.params.is_initialized() || trig.params.get().size() != 1) + if(!trig.params.has_value() || trig.params.get().size() != 1) throw EScriptExecError("VR:V option takes exactly 1 parameter!"); - std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]); + std::string opt = std::visit(VR_X(), trig.params.get()[0]); boost::format fmt("%s = tostring(%s)"); fmt % v.str() % opt; putLine(fmt.str()); @@ -879,26 +873,26 @@ namespace ERMConverter {} template - void performBody(const boost::optional & body, const Visitor & visitor) const + void performBody(const std::optional & body, const Visitor & visitor) const { - if(body.is_initialized()) + if(body.has_value()) { const ERM::Tbody & bo = body.get(); for(int g=0; g & identifier, const boost::optional & body) const + void convert(const std::string & name, const std::optional & identifier, const std::optional & body) const { if(name == "VR") { - if(!identifier.is_initialized()) + if(!identifier.has_value()) throw EScriptExecError("VR receiver requires arguments"); - ERM::Tidentifier tid = identifier.get(); + ERM::Tidentifier tid = identifier.value(); if(tid.size() != 1) throw EScriptExecError("VR receiver takes exactly 1 argument"); @@ -906,20 +900,20 @@ namespace ERMConverter } else if(name == "re") { - if(!identifier.is_initialized()) + if(!identifier.has_value()) throw EScriptExecError("re receiver requires arguments"); - ERM::Tidentifier tid = identifier.get(); + ERM::Tidentifier tid = identifier.value(); auto argc = tid.size(); if(argc > 0) { - std::string loopCounter = (boost::apply_visitor(LVL1IexpToVar(), tid.at(0))).str(); + std::string loopCounter = (std::visit(LVL1IexpToVar(), tid.at(0))).str(); - std::string startVal = argc > 1 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(1))).str() : loopCounter; - std::string stopVal = argc > 2 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(2))).str() : loopCounter; - std::string increment = argc > 3 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(3))).str() : "1"; + std::string startVal = argc > 1 ? (std::visit(LVL1IexpToVar(), tid.at(1))).str() : loopCounter; + std::string stopVal = argc > 2 ? (std::visit(LVL1IexpToVar(), tid.at(2))).str() : loopCounter; + std::string increment = argc > 3 ? (std::visit(LVL1IexpToVar(), tid.at(3))).str() : "1"; boost::format fmt("for __iter = %s, %s, %s do"); @@ -935,15 +929,15 @@ namespace ERMConverter throw EScriptExecError("re receiver requires arguments"); } } - else if(name == "FU" && !identifier.is_initialized()) + else if(name == "FU" && !identifier.has_value()) { performBody(body, FU(out)); //assume FU:E } else if(name == "MC") { - if(identifier.is_initialized()) + if(identifier.has_value()) { - ERM::Tidentifier tid = identifier.get(); + ERM::Tidentifier tid = identifier.value(); if(tid.size() != 1) throw EScriptExecError("MC receiver takes no more than 1 argument"); @@ -958,11 +952,11 @@ namespace ERMConverter { std::vector identifiers; - if(identifier.is_initialized()) + if(identifier.has_value()) { - for(const auto & id : identifier.get()) + for(const auto & id : identifier.value()) { - Variable v = boost::apply_visitor(LVL1IexpToVar(), id); + Variable v = std::visit(LVL1IexpToVar(), id); if(v.isSpecial()) throw ELineProblem("Special variable syntax ('d') is not allowed in receiver identifier"); @@ -979,7 +973,7 @@ namespace ERMConverter params += *iter; } - if(body.is_initialized()) + if(body.has_value()) { const ERM::Tbody & bo = body.get(); if(bo.size() == 1) @@ -1018,7 +1012,7 @@ namespace ERMConverter void convertConditionInner(const Tcondition & cond, char op) const { - std::string lhs = boost::apply_visitor(Condition(), cond.cond); + std::string lhs = std::visit(Condition(), cond.cond); if(cond.ctype != '/') op = cond.ctype; @@ -1038,7 +1032,7 @@ namespace ERMConverter put(lhs); - if(cond.rhs.is_initialized()) + if(cond.rhs.has_value()) { switch (op) { @@ -1057,11 +1051,11 @@ namespace ERMConverter void convertCondition(const Tcondition & cond) const { //&c1/c2/c3|c4/c5/c6 -> (c1 & c2 & c3) | c4 | c5 | c6 - std::string lhs = boost::apply_visitor(Condition(), cond.cond); + std::string lhs = std::visit(Condition(), cond.cond); put("if "); put(lhs); - if(cond.rhs.is_initialized()) + if(cond.rhs.has_value()) { switch (cond.ctype) { @@ -1079,14 +1073,14 @@ namespace ERMConverter putLine(" then "); } - void convertReceiverOrInstruction(const boost::optional & condition, + void convertReceiverOrInstruction(const std::optional & condition, const std::string & name, - const boost::optional & identifier, - const boost::optional & body) const + const std::optional & identifier, + const std::optional & body) const { if(name=="if") { - if(condition.is_initialized()) + if(condition.has_value()) convertCondition(condition.get()); else putLine("if true then"); @@ -1101,7 +1095,7 @@ namespace ERMConverter } else { - if(condition.is_initialized()) + if(condition.has_value()) { convertCondition(condition.get()); convert(name, identifier, body); @@ -1126,7 +1120,7 @@ namespace ERMConverter void operator()(const Tinstruction & trig) const { - convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, boost::make_optional(trig.body)); + convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, std::make_optional(trig.body)); } void operator()(const Treceiver & trig) const @@ -1143,7 +1137,7 @@ namespace ERMConverter void operator()(const Tcommand & cmd) const { - boost::apply_visitor(ERMExp(out), cmd.cmd); + std::visit(ERMExp(out), cmd.cmd); } void operator()(const std::string & comment) const { @@ -1151,23 +1145,23 @@ namespace ERMConverter endLine(); } - void operator()(spirit::unused_type const &) const + void operator()(const spirit::unused_type &) const { } }; - struct TLiteralEval : public boost::static_visitor + struct TLiteralEval { - std::string operator()(char const & val) + std::string operator()(const char & val) { return "{\"'\",'"+ std::to_string(val) +"'}"; } - std::string operator()(double const & val) + std::string operator()(const double & val) { return std::to_string(val); } - std::string operator()(int const & val) + std::string operator()(const int & val) { return std::to_string(val); } @@ -1187,28 +1181,28 @@ namespace ERMConverter { (*out) << "{}"; } - void operator()(VNode const & opt) const; + void operator()(const VNode & opt) const; - void operator()(VSymbol const & opt) const + void operator()(const VSymbol & opt) const { (*out) << "\"" << opt.text << "\""; } - void operator()(TLiteral const & opt) const + void operator()(const TLiteral & opt) const { TLiteralEval tmp; - (*out) << boost::apply_visitor(tmp, opt); + (*out) << std::visit(tmp, opt); } - void operator()(ERM::Tcommand const & opt) const + void operator()(ERM const ::Tcommand & opt) const { //this is how FP works, evaluation == producing side effects //TODO: can we evaluate to smth more useful? //??? throw EVermScriptExecError("Using ERM options in VERM expression is not (yet) allowed"); -// boost::apply_visitor(ERMExp(out), opt.cmd); +// std::visit(ERMExp(out), opt.cmd); } }; - void VOptionEval::operator()(VNode const& opt) const + void VOptionEval::operator()(const VNode & opt) const { VNode tmpn(opt); @@ -1216,7 +1210,7 @@ namespace ERMConverter for(VOption & op : tmpn.children) { - boost::apply_visitor(VOptionEval(out), op); + std::visit(VOptionEval(out), op); (*out) << ","; } (*out) << "}"; @@ -1228,7 +1222,7 @@ namespace ERMConverter : Converter(out_) {} - void operator()(TVExp const & cmd) const + void operator()(const TVExp & cmd) const { put("VERM:E"); @@ -1240,9 +1234,9 @@ namespace ERMConverter endLine(); } - void operator()(TERMline const & cmd) const + void operator()(const TERMline & cmd) const { - boost::apply_visitor(Command(out), cmd); + std::visit(Command(out), cmd); } }; @@ -1257,7 +1251,7 @@ namespace ERMConverter { ERM::TLine & line = owner->retrieveLine(lp); - boost::apply_visitor(lineConverter, line); + std::visit(lineConverter, line); } out << "end" << std::endl; @@ -1277,15 +1271,15 @@ namespace ERMConverter out << "ERM:addTrigger({" << std::endl; - if(!trig.identifier.is_initialized()) + if(!trig.identifier.has_value()) throw EInterpreterError("Function must have identifier"); - ERM::Tidentifier tid = trig.identifier.get(); + ERM::Tidentifier tid = trig.identifier.value(); if(tid.empty()) throw EInterpreterError("Function must have identifier"); - Variable v = boost::apply_visitor(LVL1IexpToVar(), tid[0]); + Variable v = std::visit(LVL1IexpToVar(), tid[0]); if(v.isSpecial()) throw ELineProblem("Special variable syntax ('d') is not allowed in function definition"); @@ -1304,7 +1298,7 @@ namespace ERMConverter if(owner->isATrigger(curLine)) break; - boost::apply_visitor(lineConverter, curLine); + std::visit(lineConverter, curLine); } out << "end," << std::endl; @@ -1328,11 +1322,11 @@ namespace ERMConverter std::vector identifiers; - if(trig.identifier.is_initialized()) + if(trig.identifier.has_value()) { - for(const auto & id : trig.identifier.get()) + for(const auto & id : trig.identifier.value()) { - Variable v = boost::apply_visitor(LVL1IexpToVar(), id); + Variable v = std::visit(LVL1IexpToVar(), id); if(v.isSpecial()) throw ELineProblem("Special variable syntax ('d') is not allowed in trigger definition"); @@ -1358,7 +1352,7 @@ namespace ERMConverter if(owner->isATrigger(curLine)) break; - boost::apply_visitor(lineConverter, curLine); + std::visit(lineConverter, curLine); } out << "end," << std::endl; @@ -1367,7 +1361,7 @@ namespace ERMConverter } } -struct ScriptScanner : boost::static_visitor<> +struct ScriptScanner { ERMInterpreter * interpreter; LinePointer lp; @@ -1375,22 +1369,22 @@ struct ScriptScanner : boost::static_visitor<> ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp) {} - void operator()(TVExp const& cmd) const + void operator()(const TVExp & cmd) const { // } - void operator()(TERMline const& cmd) const + void operator()(const TERMline & cmd) const { if(cmd.which() == 0) //TCommand { - Tcommand tcmd = boost::get(cmd); + Tcommand tcmd = std::get(cmd); switch (tcmd.cmd.which()) { case 0: //trigger { Trigger trig; trig.line = lp; - interpreter->triggers[ TriggerType(boost::get(tcmd.cmd).name) ].push_back(trig); + interpreter->triggers[ TriggerType(std::get(tcmd.cmd).name) ].push_back(trig); } break; case 1: //instruction @@ -1402,7 +1396,7 @@ struct ScriptScanner : boost::static_visitor<> { Trigger trig; trig.line = lp; - interpreter->postTriggers[ TriggerType(boost::get(tcmd.cmd).name) ].push_back(trig); + interpreter->postTriggers[ TriggerType(std::get(tcmd.cmd).name) ].push_back(trig); } break; default: @@ -1431,7 +1425,7 @@ bool ERMInterpreter::isATrigger( const ERM::TLine & line ) { case 0: //v-exp { - TVExp vexp = boost::get(line); + TVExp vexp = std::get(line); if(vexp.children.empty()) return false; @@ -1441,7 +1435,7 @@ bool ERMInterpreter::isATrigger( const ERM::TLine & line ) return false; break; case TCMD: - return isCMDATrigger( boost::get(vexp.children[0]) ); + return isCMDATrigger( std::get(vexp.children[0]) ); break; default: return false; @@ -1451,11 +1445,11 @@ bool ERMInterpreter::isATrigger( const ERM::TLine & line ) break; case 1: //erm { - TERMline ermline = boost::get(line); + TERMline ermline = std::get(line); switch(ermline.which()) { case 0: //tcmd - return isCMDATrigger( boost::get(ermline) ); + return isCMDATrigger( std::get(ermline) ); break; default: return false; @@ -1500,17 +1494,17 @@ ERM::TTriggerBase & ERMInterpreter::retrieveTrigger(ERM::TLine & line) { if(line.which() == 1) { - ERM::TERMline &tl = boost::get(line); + ERM::TERMline &tl = std::get(line); if(tl.which() == 0) { - ERM::Tcommand &tcm = boost::get(tl); + ERM::Tcommand &tcm = std::get(tl); if(tcm.cmd.which() == 0) { - return boost::get(tcm.cmd); + return std::get(tcm.cmd); } else if(tcm.cmd.which() == 3) { - return boost::get(tcm.cmd); + return std::get(tcm.cmd); } throw ELineProblem("Given line is not a trigger!"); } @@ -1533,7 +1527,7 @@ std::string ERMInterpreter::loadScript(const std::string & name, const std::stri scripts[LinePointer(static_cast(buf.size()), g, buf[g].realLineNum)] = buf[g].tl; for(auto p : scripts) - boost::apply_visitor(ScriptScanner(this, p.first), p.second); + std::visit(ScriptScanner(this, p.first), p.second); std::stringstream out; @@ -1575,7 +1569,7 @@ namespace VERMInterpreter { VOption convertToVOption(const ERM::TVOption & tvo) { - return boost::apply_visitor(OptionConverterVisitor(), tvo); + return std::visit(OptionConverterVisitor(), tvo); } VNode::VNode( const ERM::TVExp & exp ) @@ -1712,34 +1706,34 @@ namespace VERMInterpreter return ret; } - VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const + VOption OptionConverterVisitor::operator()(ERM const ::TVExp & cmd) const { return VNode(cmd); } - VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const + VOption OptionConverterVisitor::operator()(ERM const ::TSymbol & cmd) const { if(cmd.symModifier.empty()) return VSymbol(cmd.sym); else return VNode(cmd); } - VOption OptionConverterVisitor::operator()( char const& cmd ) const + VOption OptionConverterVisitor::operator()(const char & cmd) const { return TLiteral(cmd); } - VOption OptionConverterVisitor::operator()( double const& cmd ) const + VOption OptionConverterVisitor::operator()(const double & cmd) const { return TLiteral(cmd); } - VOption OptionConverterVisitor::operator()(int const& cmd) const + VOption OptionConverterVisitor::operator()(const int & cmd) const { return TLiteral(cmd); } - VOption OptionConverterVisitor::operator()(ERM::Tcommand const& cmd) const + VOption OptionConverterVisitor::operator()(ERM const ::Tcommand & cmd) const { return cmd; } - VOption OptionConverterVisitor::operator()( ERM::TStringConstant const& cmd ) const + VOption OptionConverterVisitor::operator()(ERM const ::TStringConstant & cmd) const { return TLiteral(cmd.str); } diff --git a/scripting/erm/ERMInterpreter.h b/scripting/erm/ERMInterpreter.h index eda381c13..baf3d317e 100644 --- a/scripting/erm/ERMInterpreter.h +++ b/scripting/erm/ERMInterpreter.h @@ -213,15 +213,15 @@ namespace VERMInterpreter {}; - typedef boost::variant TLiteral; + typedef std::variant TLiteral; - typedef boost::variant, VSymbol, TLiteral, ERM::Tcommand> VOption; //options in v-expression, VNIl should be the default + typedef std::variant, VSymbol, TLiteral, ERM::Tcommand> VOption; //options in v-expression, VNIl should be the default template T& getAs(SecType & opt) { if(opt.type() == typeid(T)) - return boost::get(opt); + return std::get(opt); else throw EVermScriptExecError("Wrong type!"); } @@ -278,15 +278,15 @@ namespace VERMInterpreter VermTreeIterator cdr(); }; - struct OptionConverterVisitor : boost::static_visitor + struct OptionConverterVisitor { - VOption operator()(ERM::TVExp const& cmd) const; - VOption operator()(ERM::TSymbol const& cmd) const; - VOption operator()(char const& cmd) const; - VOption operator()(double const& cmd) const; - VOption operator()(int const& cmd) const; - VOption operator()(ERM::Tcommand const& cmd) const; - VOption operator()(ERM::TStringConstant const& cmd) const; + VOption operator()(ERM const ::TVExp & cmd) const; + VOption operator()(ERM const ::TSymbol & cmd) const; + VOption operator()(const char & cmd) const; + VOption operator()(const double & cmd) const; + VOption operator()(const int & cmd) const; + VOption operator()(ERM const ::Tcommand & cmd) const; + VOption operator()(ERM const ::TStringConstant & cmd) const; }; struct VNode diff --git a/scripting/erm/ERMParser.cpp b/scripting/erm/ERMParser.cpp index 9e19aafd1..e13d0a9a5 100644 --- a/scripting/erm/ERMParser.cpp +++ b/scripting/erm/ERMParser.cpp @@ -28,7 +28,7 @@ namespace phoenix = boost::phoenix; //Greenspun's Tenth Rule of Programming: //Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, //bug-ridden, slow implementation of half of Common Lisp. -//actually these macros help in dealing with boost::variant +//actually these macros help in dealing with std::variant CERMPreprocessor::CERMPreprocessor(const std::string & source) @@ -216,7 +216,7 @@ BOOST_FUSION_ADAPT_STRUCT( BOOST_FUSION_ADAPT_STRUCT( ERM::TVarExpNotMacro, - (boost::optional, questionMark) + (std::optional, questionMark) (std::string, varsym) (ERM::TVarExpNotMacro::Tval, val) ) @@ -248,14 +248,14 @@ BOOST_FUSION_ADAPT_STRUCT( BOOST_FUSION_ADAPT_STRUCT( ERM::TNormalBodyOption, (char, optionCode) - (boost::optional, params) + (std::optional, params) ) BOOST_FUSION_ADAPT_STRUCT( ERM::Ttrigger, (ERM::TCmdName, name) - (boost::optional, identifier) - (boost::optional, condition) + (std::optional, identifier) + (std::optional, condition) ) BOOST_FUSION_ADAPT_STRUCT( @@ -293,24 +293,24 @@ BOOST_FUSION_ADAPT_STRUCT( BOOST_FUSION_ADAPT_STRUCT( ERM::Tinstruction, (ERM::TCmdName, name) - (boost::optional, identifier) - (boost::optional, condition) + (std::optional, identifier) + (std::optional, condition) (ERM::Tbody, body) ) BOOST_FUSION_ADAPT_STRUCT( ERM::Treceiver, (ERM::TCmdName, name) - (boost::optional, identifier) - (boost::optional, condition) - (boost::optional, body) + (std::optional, identifier) + (std::optional, condition) + (std::optional, body) ) BOOST_FUSION_ADAPT_STRUCT( ERM::TPostTrigger, (ERM::TCmdName, name) - (boost::optional, identifier) - (boost::optional, condition) + (std::optional, identifier) + (std::optional, condition) ) //BOOST_FUSION_ADAPT_STRUCT( diff --git a/scripting/erm/ERMParser.h b/scripting/erm/ERMParser.h index 4c9ad9be0..29d92e61b 100644 --- a/scripting/erm/ERMParser.h +++ b/scripting/erm/ERMParser.h @@ -74,13 +74,13 @@ namespace ERM struct TVarExpNotMacro { - typedef boost::optional Tval; - boost::optional questionMark; + typedef std::optional Tval; + std::optional questionMark; std::string varsym; Tval val; }; - typedef boost::variant TVarExp; + typedef std::variant TVarExp; //write-only variable expression struct TVarpExp @@ -89,7 +89,7 @@ namespace ERM }; //i-expression (identifier expression) - an integral constant, variable symbol or array symbol - typedef boost::variant TIexp; + typedef std::variant TIexp; struct TArithmeticOp { @@ -127,18 +127,18 @@ namespace ERM TStringConstant string; }; - typedef boost::variant TBodyOptionItem; + typedef std::variant TBodyOptionItem; typedef std::vector TNormalBodyOptionList; struct TNormalBodyOption { char optionCode; - boost::optional params; + std::optional params; }; - typedef boost::variant TBodyOption; + typedef std::variant TBodyOption; -// typedef boost::variant TIdentifierInternal; +// typedef std::variant TIdentifierInternal; typedef std::vector< TIexp > Tidentifier; struct TComparison @@ -148,16 +148,11 @@ namespace ERM }; struct Tcondition; - typedef - boost::optional< - boost::recursive_wrapper - > - TconditionNode; - + typedef std::optional> TconditionNode; struct Tcondition { - typedef boost::variant< + typedef std::variant< TComparison, int> Tcond; //comparison or condition flag @@ -170,8 +165,8 @@ namespace ERM { bool pre; //if false it's !$ post-trigger, elsewise it's !# (pre)trigger TCmdName name; - boost::optional identifier; - boost::optional condition; + std::optional identifier; + std::optional condition; }; struct Ttrigger : TTriggerBase @@ -196,28 +191,28 @@ namespace ERM //moreover, I encountered a quite serious bug in boost: http://boost.2283326.n4.nabble.com/container-hpp-111-error-C2039-value-type-is-not-a-member-of-td3352328.html //not sure how serious it is... - //typedef boost::variant bodyItem; + //typedef std::variant bodyItem; typedef std::vector Tbody; struct Tinstruction { TCmdName name; - boost::optional identifier; - boost::optional condition; + std::optional identifier; + std::optional condition; Tbody body; }; struct Treceiver { TCmdName name; - boost::optional identifier; - boost::optional condition; - boost::optional body; + std::optional identifier; + std::optional condition; + std::optional body; }; struct Tcommand { - typedef boost::variant< + typedef std::variant< Ttrigger, Tinstruction, Treceiver, @@ -231,7 +226,7 @@ namespace ERM //vector expression - typedef boost::variant TERMline; + typedef std::variant TERMline; typedef std::string TVModifier; //'`', ',', ',@', '#'' @@ -245,7 +240,7 @@ namespace ERM enum EVOtions{VEXP, SYMBOL, CHAR, DOUBLE, INT, TCMD, STRINGC}; struct TVExp; - typedef boost::variant, TSymbol, char, double, int, Tcommand, TStringConstant > TVOption; //options in v-expression + typedef std::variant, TSymbol, char, double, int, Tcommand, TStringConstant > TVOption; //options in v-expression //v-expression struct TVExp { @@ -254,7 +249,7 @@ namespace ERM }; //script line - typedef boost::variant TLine; + typedef std::variant TLine; template struct ERM_grammar; } diff --git a/scripting/lua/LuaStack.h b/scripting/lua/LuaStack.h index 5564dd0eb..dd5ce9497 100644 --- a/scripting/lua/LuaStack.h +++ b/scripting/lua/LuaStack.h @@ -53,10 +53,10 @@ public: void push(const JsonNode & value); template - void push(const boost::optional & value) + void push(const std::optional & value) { - if(value.is_initialized()) - push(value.get()); + if(value.has_value()) + push(value.value()); else pushNil(); } diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp index 3f3856e6f..4ffd70ade 100644 --- a/server/CGameHandler.cpp +++ b/server/CGameHandler.cpp @@ -593,7 +593,7 @@ void CGameHandler::endBattle(int3 tile, const CGHeroInstance * heroAttacker, con return; } - battleQuery->result = boost::make_optional(*battleResult.data); + battleQuery->result = std::make_optional(*battleResult.data); //Check how many battle queries were created (number of players blocked by battle) const int queriedPlayers = battleQuery ? (int)boost::count(queries.allQueries(), battleQuery) : 0; @@ -662,7 +662,7 @@ void CGameHandler::endBattleConfirm(const BattleInfo * battleInfo) if (finishingBattle->loserHero) { - //TODO: wrap it into a function, somehow (boost::variant -_-) + //TODO: wrap it into a function, somehow (std::variant -_-) auto artifactsWorn = finishingBattle->loserHero->artifactsWorn; for (auto artSlot : artifactsWorn) { @@ -2330,7 +2330,7 @@ bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, boo leaveTile(); if (isInTheMap(guardPos)) - tmh.attackedFrom = boost::make_optional(guardPos); + tmh.attackedFrom = std::make_optional(guardPos); tmh.result = result; sendAndApply(&tmh); @@ -2651,7 +2651,7 @@ void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedI } battleQuery->bi = gs->curB; - battleQuery->result = boost::none; + battleQuery->result = std::nullopt; battleQuery->belligerents[0] = gs->curB->sides[0].armyObject; battleQuery->belligerents[1] = gs->curB->sides[1].armyObject; } @@ -3930,11 +3930,11 @@ bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocat try { - auto hero = boost::get>(dst.artHolder); + auto hero = std::get>(dst.artHolder); if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot)) giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK); } - catch(const boost::bad_get &) + catch(const std::bad_variant_access &) { // object other than hero received an art - ignore } @@ -6901,7 +6901,7 @@ void CGameHandler::handleCheatCode(std::string & cheat, PlayerColor player, cons creatures.insert(std::make_pair("vcmiazure", std::make_pair("azureDragon", 5000))); //5000 azure dragons creatures.insert(std::make_pair("vcmifaerie", std::make_pair("fairieDragon", 5000))); //5000 faerie dragons - const int32_t creatureIdentifier = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatures[cheat].first, false).get(); + const int32_t creatureIdentifier = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatures[cheat].first, false).value(); const CCreature * creature = VLC->creh->objects.at(creatureIdentifier); for (int i = 0; i < GameConstants::ARMY_SIZE; i++) if (!hero->hasStackAtSlot(SlotID(i))) @@ -6920,11 +6920,11 @@ void CGameHandler::handleCheatCode(std::string & cheat, PlayerColor player, cons std::string creatureIdentifier = words[1]; - boost::optional creatureId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatureIdentifier, false); + std::optional creatureId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatureIdentifier, false); - if(creatureId.is_initialized()) + if(creatureId.has_value()) { - const CCreature * creature = VLC->creh->objects.at(creatureId.get()); + const auto * creature = CreatureID(creatureId.value()).toCreature(); for (int i = 0; i < GameConstants::ARMY_SIZE; i++) if (!hero->hasStackAtSlot(SlotID(i))) diff --git a/server/CQuery.cpp b/server/CQuery.cpp index 50b7d5b95..4456fa961 100644 --- a/server/CQuery.cpp +++ b/server/CQuery.cpp @@ -360,11 +360,11 @@ bool CGarrisonDialogQuery::blocksPack(const CPack * pack) const if(auto arts = dynamic_ptr_cast(pack)) { - if(auto id1 = boost::apply_visitor(GetEngagedHeroIds(), arts->src.artHolder)) + if(auto id1 = std::visit(GetEngagedHeroIds(), arts->src.artHolder)) if(!vstd::contains(ourIds, *id1)) return true; - if(auto id2 = boost::apply_visitor(GetEngagedHeroIds(), arts->dst.artHolder)) + if(auto id2 = std::visit(GetEngagedHeroIds(), arts->dst.artHolder)) if(!vstd::contains(ourIds, *id2)) return true; return false; @@ -377,7 +377,7 @@ bool CGarrisonDialogQuery::blocksPack(const CPack * pack) const if(auto art = dynamic_ptr_cast(pack)) { - if (auto id = boost::apply_visitor(GetEngagedHeroIds(), art->al.artHolder)) + if (auto id = std::visit(GetEngagedHeroIds(), art->al.artHolder)) return !vstd::contains(ourIds, *id); } @@ -455,7 +455,7 @@ CHeroLevelUpDialogQuery::CHeroLevelUpDialogQuery(CGameHandler * owner, const Her void CHeroLevelUpDialogQuery::onRemoval(PlayerColor color) { assert(answer); - logGlobal->trace("Completing hero level-up query. %s gains skill %d", hero->getObjectName(), answer.get()); + logGlobal->trace("Completing hero level-up query. %s gains skill %d", hero->getObjectName(), answer.value()); gh->levelUpHero(hero, hlu.skills[*answer]); } @@ -474,7 +474,7 @@ CCommanderLevelUpDialogQuery::CCommanderLevelUpDialogQuery(CGameHandler * owner, void CCommanderLevelUpDialogQuery::onRemoval(PlayerColor color) { assert(answer); - logGlobal->trace("Completing commander level-up query. Commander of hero %s gains skill %s", hero->getObjectName(), answer.get()); + logGlobal->trace("Completing commander level-up query. Commander of hero %s gains skill %s", hero->getObjectName(), answer.value()); gh->levelUpCommander(hero->commander, clu.skills[*answer]); } diff --git a/server/CQuery.h b/server/CQuery.h index fae8c8d9a..9c7c92ddd 100644 --- a/server/CQuery.h +++ b/server/CQuery.h @@ -100,7 +100,7 @@ public: std::array initialHeroMana; const BattleInfo *bi; - boost::optional result; + std::optional result; CBattleQuery(CGameHandler * owner); CBattleQuery(CGameHandler * owner, const BattleInfo * Bi); //TODO @@ -133,7 +133,7 @@ public: virtual bool blocksPack(const CPack *pack) const override; void setReply(const JsonNode & reply) override; protected: - boost::optional answer; + std::optional answer; }; class CGarrisonDialogQuery : public CDialogQuery //used also for hero exchange dialogs diff --git a/server/CVCMIServer.cpp b/server/CVCMIServer.cpp index 2f0058b2d..b166167a5 100644 --- a/server/CVCMIServer.cpp +++ b/server/CVCMIServer.cpp @@ -296,7 +296,7 @@ bool CVCMIServer::prepareToStartGame() { case StartInfo::CAMPAIGN: logNetwork->info("Preparing to start new campaign"); - si->campState->currentMap = boost::make_optional(campaignMap); + si->campState->currentMap = std::make_optional(campaignMap); si->campState->chosenCampaignBonuses[campaignMap] = campaignBonus; gh->init(si.get()); break; @@ -665,7 +665,7 @@ void CVCMIServer::updateStartInfoOnMapChange(std::shared_ptr mapInfo, si = CMemorySerializer::deepCopy(*mi->scenarioOptionsOfSave); si->mode = StartInfo::LOAD_GAME; if(si->campState) - campaignMap = si->campState->currentMap.get(); + campaignMap = si->campState->currentMap.value(); for(auto & ps : si->playerInfos) { diff --git a/test/erm/ERM_BU.cpp b/test/erm/ERM_BU.cpp index 18aa18e3e..2fd105690 100644 --- a/test/erm/ERM_BU.cpp +++ b/test/erm/ERM_BU.cpp @@ -32,7 +32,7 @@ protected: class ERM_BU_C : public ERM_BU { protected: - void doTest(boost::optional input, double output) + void doTest(std::optional input, double output) { EXPECT_CALL(binfoMock, battleIsFinished()).WillOnce(Return(input)); @@ -51,12 +51,12 @@ protected: TEST_F(ERM_BU_C, Finished) { - doTest(boost::make_optional(1), 1); + doTest(std::make_optional(1), 1); } TEST_F(ERM_BU_C, NotFinished) { - doTest(boost::none, 0); + doTest(std::nullopt, 0); } class ERM_BU_D : public ERM_BU diff --git a/test/googletest b/test/googletest index 4bab34d20..b796f7d44 160000 --- a/test/googletest +++ b/test/googletest @@ -1 +1 @@ -Subproject commit 4bab34d2084259cba67f3bfb51217c10d606e175 +Subproject commit b796f7d44681514f58a683a3a71ff17c94edb0c1 diff --git a/test/mock/mock_IBattleInfoCallback.h b/test/mock/mock_IBattleInfoCallback.h index b051f4355..ba03a75ae 100644 --- a/test/mock/mock_IBattleInfoCallback.h +++ b/test/mock/mock_IBattleInfoCallback.h @@ -20,7 +20,7 @@ public: MOCK_CONST_METHOD0(battleTerrainType, TerrainId()); MOCK_CONST_METHOD0(battleGetBattlefieldType, BattleField()); - MOCK_CONST_METHOD0(battleIsFinished, boost::optional()); + MOCK_CONST_METHOD0(battleIsFinished, std::optional()); MOCK_CONST_METHOD0(battleTacticDist, si8()); MOCK_CONST_METHOD0(battleGetTacticsSide, si8()); diff --git a/test/serializer/JsonUpdaterTest.cpp b/test/serializer/JsonUpdaterTest.cpp index d54111f5c..e40bf4fae 100644 --- a/test/serializer/JsonUpdaterTest.cpp +++ b/test/serializer/JsonUpdaterTest.cpp @@ -72,8 +72,8 @@ public: handler.serializeString("s1", s1); handler.serializeString("s2", s2); - handler.serializeRaw("j1", j1, boost::none); - handler.serializeRaw("j2", j2, boost::none); + handler.serializeRaw("j1", j1, std::nullopt); + handler.serializeRaw("j2", j2, std::nullopt); handler.serializeStruct("inner1", inner1); handler.serializeStruct("inner2", inner2);