1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-01-28 03:57:02 +02:00

Merge remote-tracking branch 'upstream/develop' into develop

This commit is contained in:
Xilmi 2024-09-06 17:04:34 +02:00
commit d4ee899565
63 changed files with 592 additions and 456 deletions

View File

@ -217,12 +217,12 @@ bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
return true;
}
bool CCallback::triggerTownSpecialBuildingAction(const CGTownInstance *town, BuildingSubID::EBuildingSubID subBuildingID)
bool CCallback::visitTownBuilding(const CGTownInstance *town, BuildingID buildingID)
{
if(town->tempOwner!=player)
return false;
TriggerTownSpecialBuildingAction pack(town->id, subBuildingID);
VisitTownBuilding pack(town->id, buildingID);
sendRequest(&pack);
return true;
}

View File

@ -75,7 +75,7 @@ public:
//town
virtual void recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero=HeroTypeID::NONE)=0;
virtual bool buildBuilding(const CGTownInstance *town, BuildingID buildingID)=0;
virtual bool triggerTownSpecialBuildingAction(const CGTownInstance *town, BuildingSubID::EBuildingSubID subBuildingID)=0;
virtual bool visitTownBuilding(const CGTownInstance *town, BuildingID buildingID)=0;
virtual void recruitCreatures(const CGDwelling *obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level=-1)=0;
virtual bool upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID=CreatureID::NONE)=0; //if newID==-1 then best possible upgrade will be made
virtual void swapGarrisonHero(const CGTownInstance *town)=0;
@ -182,7 +182,7 @@ public:
void manageHeroCostume(ObjectInstanceID hero, size_t costumeIdx, bool saveCostume) override;
void eraseArtifactByClient(const ArtifactLocation & al) override;
bool buildBuilding(const CGTownInstance *town, BuildingID buildingID) override;
bool triggerTownSpecialBuildingAction(const CGTownInstance *town, BuildingSubID::EBuildingSubID subBuildingID) override;
bool visitTownBuilding(const CGTownInstance *town, BuildingID buildingID) override;
void recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level=-1) override;
bool dismissCreature(const CArmedInstance *obj, SlotID stackPos) override;
bool upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID=CreatureID::NONE) override;

View File

@ -162,6 +162,38 @@
"vcmi.systemOptions.otherGroup" : "Outras Configurações", // não utilizado no momento
"vcmi.systemOptions.townsGroup" : "Tela da Cidade",
"vcmi.statisticWindow.statistics" : "Estatísticas",
"vcmi.statisticWindow.tsvCopy" : "Copiar dados",
"vcmi.statisticWindow.selectView" : "Selecionar visualização",
"vcmi.statisticWindow.value" : "Valor",
"vcmi.statisticWindow.title.overview" : "Visão geral",
"vcmi.statisticWindow.title.resources" : "Recursos",
"vcmi.statisticWindow.title.income" : "Renda",
"vcmi.statisticWindow.title.numberOfHeroes" : "Nº de heróis",
"vcmi.statisticWindow.title.numberOfTowns" : "Nº de cidades",
"vcmi.statisticWindow.title.numberOfArtifacts" : "Nº de artefatos",
"vcmi.statisticWindow.title.numberOfDwellings" : "Nº de moradias",
"vcmi.statisticWindow.title.numberOfMines" : "Nº de minas",
"vcmi.statisticWindow.title.armyStrength" : "Força do exército",
"vcmi.statisticWindow.title.experience" : "Experiência",
"vcmi.statisticWindow.title.resourcesSpentArmy" : "Custo do exército",
"vcmi.statisticWindow.title.resourcesSpentBuildings" : "Custo de construção",
"vcmi.statisticWindow.title.mapExplored" : "Exploração do mapa",
"vcmi.statisticWindow.param.playerName" : "Nome do jogador",
"vcmi.statisticWindow.param.daysSurvived" : "Dias sobrevividos",
"vcmi.statisticWindow.param.maxHeroLevel" : "Nível máximo do herói",
"vcmi.statisticWindow.param.battleWinRatioHero" : "Taxa de vitória (vs. herói)",
"vcmi.statisticWindow.param.battleWinRatioNeutral" : "Taxa de vitória (vs. neutro)",
"vcmi.statisticWindow.param.battlesHero" : "Batalhas (vs. herói)",
"vcmi.statisticWindow.param.battlesNeutral" : "Batalhas (vs. neutro)",
"vcmi.statisticWindow.param.maxArmyStrength" : "Força máxima do exército",
"vcmi.statisticWindow.param.tradeVolume" : "Volume de comércio",
"vcmi.statisticWindow.param.obeliskVisited" : "Obelisco visitado",
"vcmi.statisticWindow.icon.townCaptured" : "Cidade capturada",
"vcmi.statisticWindow.icon.strongestHeroDefeated" : "Herói mais forte do oponente derrotado",
"vcmi.statisticWindow.icon.grailFound" : "Graal encontrado",
"vcmi.statisticWindow.icon.defeated" : "Derrotado",
"vcmi.systemOptions.fullscreenBorderless.hover" : "Tela Cheia (sem bordas)",
"vcmi.systemOptions.fullscreenBorderless.help" : "{Tela Cheia sem Bordas}\n\nSe selecionado, o VCMI será executado em modo de tela cheia sem bordas. Neste modo, o jogo sempre usará a mesma resolução que a área de trabalho, ignorando a resolução selecionada.",
"vcmi.systemOptions.fullscreenExclusive.hover" : "Tela Cheia (exclusiva)",
@ -293,6 +325,8 @@
"vcmi.townHall.missingBase" : "A construção base %s deve ser construída primeiro",
"vcmi.townHall.noCreaturesToRecruit" : "Não há criaturas para recrutar!",
"vcmi.townStructure.bank.borrow" : "Você entra no banco. Um banqueiro o vê e diz: \"Temos uma oferta especial para você. Você pode tomar um empréstimo de 2500 de ouro por 5 dias. Você terá que pagar 500 de ouro todos os dias.\"",
"vcmi.townStructure.bank.payBack" : "Você entra no banco. Um banqueiro o vê e diz: \"Você já pegou um empréstimo. Pague-o antes de tomar um novo.\"",
"vcmi.logicalExpressions.anyOf" : "Qualquer um dos seguintes:",
"vcmi.logicalExpressions.allOf" : "Todos os seguintes:",

View File

@ -51,7 +51,6 @@
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include "../lib/serializer/Cast.h"
#include "LobbyClientNetPackVisitors.h"
#include <vcmi/events/EventBus.h>

View File

@ -164,7 +164,7 @@ public:
void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs = false) override {};
void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs = false) override {};
void showBlockingDialog(BlockingDialog * iw) override {};
void showBlockingDialog(const IObjectInterface * caller, BlockingDialog * iw) override {};
void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {};
void showTeleportDialog(TeleportDialog * iw) override {};
void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override {};
@ -184,7 +184,8 @@ public:
void removeAfterVisit(const CGObjectInstance * object) override {};
bool swapGarrisonOnSiege(ObjectInstanceID tid) override {return false;};
bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos) override {return false;}
bool giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos) override {return false;};
bool giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos) override {return false;};
bool putArtifact(const ArtifactLocation & al, const CArtifactInstance * art, std::optional<bool> askAssemble) override {return false;};
void removeArtifact(const ArtifactLocation & al) override {};
bool moveArtifact(const PlayerColor & player, const ArtifactLocation & al1, const ArtifactLocation & al2) override {return false;};

View File

@ -743,6 +743,12 @@ bool CCastleBuildings::buildingTryActivateCustomUI(BuildingID buildingToTest, Bu
}
}
if (town->rewardableBuildings.count(buildingToTest) && town->town->buildings.at(buildingToTest)->manualHeroVisit)
{
enterRewardable(buildingToTest);
return true;
}
if (buildingToTest >= BuildingID::DWELL_FIRST)
{
enterDwelling((BuildingID::getLevelFromDwelling(buildingToTest)));
@ -820,7 +826,7 @@ bool CCastleBuildings::buildingTryActivateCustomUI(BuildingID buildingToTest, Bu
return true;
case BuildingSubID::BANK:
enterBank();
enterBank(buildingTarget);
return true;
}
}
@ -837,6 +843,11 @@ bool CCastleBuildings::buildingTryActivateCustomUI(BuildingID buildingToTest, Bu
return false;
}
void CCastleBuildings::enterRewardable(BuildingID building)
{
LOCPLINT->cb->visitTownBuilding(town, building);
}
void CCastleBuildings::enterBlacksmith(BuildingID building, ArtifactID artifactID)
{
const CGHeroInstance *hero = town->visitingHero;
@ -1053,7 +1064,7 @@ void CCastleBuildings::enterAnyThievesGuild()
LOCPLINT->showInfoDialog(CGI->generaltexth->translate("vcmi.adventureMap.noTownWithTavern"));
}
void CCastleBuildings::enterBank()
void CCastleBuildings::enterBank(BuildingID building)
{
std::vector<std::shared_ptr<CComponent>> components;
if(town->bonusValue.second > 0)
@ -1064,7 +1075,7 @@ void CCastleBuildings::enterBank()
else{
components.push_back(std::make_shared<CComponent>(ComponentType::RESOURCE, GameResID(GameResID::GOLD), 2500));
LOCPLINT->showYesNoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.borrow"), [this](){ LOCPLINT->cb->triggerTownSpecialBuildingAction(town, BuildingSubID::BANK); }, nullptr, components);
LOCPLINT->showYesNoDialog(CGI->generaltexth->translate("vcmi.townStructure.bank.borrow"), [this, building](){ LOCPLINT->cb->visitTownBuilding(town, building); }, nullptr, components);
}
}

View File

@ -167,10 +167,11 @@ public:
void enterDwelling(int level);
void enterTownHall();
void enterRewardable(BuildingID building);
void enterMagesGuild();
void enterAnyMarket();
void enterAnyThievesGuild();
void enterBank();
void enterBank(BuildingID building);
void enterToTheQuickRecruitmentWindow();
bool buildingTryActivateCustomUI(BuildingID buildingToTest, BuildingID buildingTarget);

View File

@ -179,7 +179,7 @@
"period" : 7,
"visitors" : true
},
"visitMode" : "hero", // Should be 'once' to match (somewhat buggy) H3 logic
"visitMode" : "once",
"rewards" : [
{
"limiter" : {

View File

@ -61,11 +61,15 @@
"description" : "If set to true, this building will replace all bonuses from base building, leaving only bonuses defined by this building",
"type" : "boolean"
},
"manualHeroVisit" : {
"description" : "If set to true, this building will not automatically activate on new day or on entering town and needs to be activated manually on click",
"type" : "boolean"
},
"configuration" : {
"description" : "Optional, configuration of building that can be activated by visiting hero",
"$ref" : "rewardable.json"
},
"firtufications" : {
"fortifications" : {
"type" : "object",
"additionalProperties" : false,
"description" : "Fortifications provided by this buildings, if any",

View File

@ -16,18 +16,18 @@ These are just a couple of examples of what can be done in VCMI. See vcmi config
##### Order of Fire from Inferno:
```jsonc
"special4": {
"requires" : [ "mageGuild1" ],
"requires" : [ "mageGuild1" ],
"name" : "Order of Fire",
"description" : "Increases spellpower of visiting hero",
"cost" : {
"mercury" : 5,
"mercury" : 5,
"gold" : 1000
},
"configuration" : {
"visitMode" : "hero",
"visitMode" : "hero",
"rewards" : [
{
// NOTE: this forces vcmi to load string from H3 text file. In order to define own string simply write your own message without '@' symbol
{
// NOTE: this forces vcmi to load string from H3 text file. In order to define own string simply write your own message without '@' symbol
"message" : "@core.genrltxt.582",
"primary" : { "spellpower" : 1 }
}
@ -39,22 +39,22 @@ These are just a couple of examples of what can be done in VCMI. See vcmi config
##### Mana Vortex from Dungeon
```jsonc
"special2": {
"requires" : [ "mageGuild1" ],
"requires" : [ "mageGuild1" ],
"name" : "Mana Vortex",
"description" : "Doubles mana points of the first visiting hero each week",
"cost" : {
"gold" : 5000
"gold" : 5000
},
"configuration" : {
"resetParameters" : {
"period" : 7,
"resetParameters" : {
"period" : 7,
"visitors" : true
},
"visitMode" : "once",
"rewards" : [
{
"limiter" : {
"noneOf" : [ { "manaPercentage" : 200 } ]
{
"limiter" : {
"noneOf" : [ { "manaPercentage" : 200 } ]
},
"message" : "As you near the mana vortex your body is filled with new energy. You have doubled your normal spell points.",
"manaPercentage" : 200
@ -67,14 +67,14 @@ These are just a couple of examples of what can be done in VCMI. See vcmi config
#### Resource Silo with custom production
```jsonc
"resourceSilo": {
"name" : "Wood Resource Silo",
"name" : "Wood Resource Silo",
"description" : "Produces 2 wood every day",
"cost" : {
"wood" : 10,
"wood" : 10,
"gold" : 5000
},
"produce" : {
"wood": 2
"wood": 2
}
},
```
@ -193,11 +193,15 @@ These are just a couple of examples of what can be done in VCMI. See vcmi config
// Buildings which bonuses should be overridden with bonuses of the current building
"overrides" : [ "anotherBuilding ]
// Bonuses provided by this special building if this building or any of its upgrades are constructed in town
// Bonuses provided by this special building if this building or any of its upgrades are constructed in town
"bonuses" : [ BONUS_FORMAT ]
// If set to true, this building will not automatically activate on new day or on entering town and needs to be activated manually on click
"manualHeroVisit" : false,
// Bonuses provided by this special building if this building or any of its upgrades are constructed in town
"bonuses" : [ BONUS_FORMAT ]
// If set to true, this building will replace all bonuses from base building, leaving only bonuses defined by this building"
"upgradeReplacesBonuses" : false,
// If the building is a market, it requires market mode.
"marketModes" : [ "resource-resource", "resource-player" ],
@ -209,18 +213,18 @@ Building requirements can be described using logical expressions:
```jsonc
"requires" :
[
"allOf", // Normal H3 "build all" mode
[ "mageGuild1" ],
[
"noneOf", // available only when none of these building are built
[ "dwelling5A" ],
[ "dwelling5AUpgrade" ]
],
[
"anyOf", // any non-zero number of these buildings must be built
[ "tavern" ],
[ "blacksmith" ]
]
"allOf", // Normal H3 "build all" mode
[ "mageGuild1" ],
[
"noneOf", // available only when none of these building are built
[ "dwelling5A" ],
[ "dwelling5AUpgrade" ]
],
[
"anyOf", // any non-zero number of these buildings must be built
[ "tavern" ],
[ "blacksmith" ]
]
]
```
### List of unique town buildings

View File

@ -11,7 +11,7 @@
<message>
<location filename="../aboutProject/aboutproject_moc.ui" line="29"/>
<source>Have a question? Found a bug? Want to help? Join us!</source>
<translation>Têm uma pergunta? Encontrou algum erro? Quer ajudar? Junte-se a nós</translation>
<translation>Tem uma pergunta? Encontrou algum erro? Quer ajudar? Junte-se a nós</translation>
</message>
<message>
<location filename="../aboutProject/aboutproject_moc.ui" line="36"/>
@ -341,7 +341,7 @@
<location filename="../modManager/cmodlistview_moc.cpp" line="311"/>
<location filename="../modManager/cmodlistview_moc.cpp" line="319"/>
<source>Required VCMI version</source>
<translation>Versão do VCMI requerida</translation>
<translation>Versão do VCMI necessária</translation>
</message>
<message>
<location filename="../modManager/cmodlistview_moc.cpp" line="317"/>
@ -884,7 +884,7 @@ Instalar o download realizado com sucesso?</translation>
<translation>Ativado</translation>
</message>
<message>
<location filename="../settingsView/csettingsview_moc.ui" line="389"/>
<location filename="../settingsView/csettingsview_moc.ui" line="391"/>
<source>Select display mode for game
Windowed - game will run inside a window that covers part of your screen
@ -1173,7 +1173,7 @@ O instalador offline consiste em duas partes, .exe e .bin. Certifique-se de baix
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.ui" line="441"/>
<source>Heroes III data files</source>
<source>Heroes III data files</source>
<translation>Arquivos de dados do Heroes III</translation>
</message>
<message>
@ -1259,6 +1259,28 @@ O instalador offline consiste em duas partes, .exe e .bin. Certifique-se de baix
<source>GOG data</source>
<translation>Dados do GOG</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="387"/>
<source>You&apos;ve provided GOG Galaxy installer! This file doesn&apos;t contain the game. Please download the offline backup game installer!</source>
<translation>Você forneceu o instalador do GOG Galaxy! Este arquivo não contém o jogo. Por favor, faça o download do instalador offline de backup do jogo!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="412"/>
<source>Stream error while extracting files!
error reason: </source>
<translation>Erro de fluxo ao extrair arquivos!
Motivo do erro: </translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="425"/>
<source>Not a supported Inno Setup installer!</source>
<translation>Instalador Inno Setup não suportado!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="436"/>
<source>Extracting error!</source>
<translation>Erro ao extrair!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="438"/>
<source>No Heroes III data!</source>
@ -1284,28 +1306,6 @@ Please select directory with installed Heroes III data.</source>
<translation>Falha ao detectar dados válidos do Heroes III no diretório escolhido.
Por favor, selecione o diretório com os dados do Heroes III instalados.</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="387"/>
<source>You&apos;ve provided GOG Galaxy installer! This file doesn&apos;t contain the game. Please download the offline backup game installer!</source>
<translation>Você forneceu o instalador do GOG Galaxy! Este arquivo não contém o jogo. Por favor, faça o download do instalador offline de backup do jogo!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="412"/>
<source>Stream error while extracting files!
error reason: </source>
<translation>Erro de fluxo ao extrair arquivos!
Motivo do erro: </translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="425"/>
<source>Not a supported Inno Setup installer!</source>
<translation>Instalador do Inno Setup não suportado!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="436"/>
<source>Extracting error!</source>
<translation>Erro ao extrair!</translation>
</message>
<message>
<location filename="../firstLaunch/firstlaunch_moc.cpp" line="506"/>
<source>Heroes III: HD Edition files are not supported by VCMI.
@ -1488,7 +1488,7 @@ Motivo: %2</translation>
<message>
<location filename="../updatedialog_moc.ui" line="71"/>
<source>You have the latest version</source>
<translation> possui a versão mais recente</translation>
<translation> tem a versão mais recente</translation>
</message>
<message>
<location filename="../updatedialog_moc.ui" line="94"/>

View File

@ -14,7 +14,6 @@
#include "GameSettings.h"
#include "spells/CSpellHandler.h"
#include "mapping/CMap.h"
#include "mapObjects/CGHeroInstance.h"
VCMI_LIB_NAMESPACE_BEGIN
@ -222,67 +221,47 @@ DLL_LINKAGE std::vector<const CArtifact*> ArtifactUtils::assemblyPossibilities(
return arts;
}
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createScroll(const SpellID & sid)
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createScroll(const SpellID & spellId)
{
auto ret = new CArtifactInstance(ArtifactID(ArtifactID::SPELL_SCROLL).toArtifact());
auto bonus = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::SPELL,
BonusSource::ARTIFACT_INSTANCE, -1, BonusSourceID(ArtifactID(ArtifactID::SPELL_SCROLL)), BonusSubtypeID(sid));
ret->addNewBonus(bonus);
return ret;
return ArtifactUtils::createArtifact(ArtifactID::SPELL_SCROLL, spellId);
}
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createNewArtifactInstance(const CArtifact * art)
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createArtifact(const ArtifactID & artId, const SpellID & spellId)
{
assert(art);
auto * artInst = new CArtifactInstance(art);
if(art->isCombined())
const std::function<CArtifactInstance*(const CArtifact*)> createArtInst =
[&createArtInst, &spellId](const CArtifact * art) -> CArtifactInstance*
{
for(const auto & part : art->getConstituents())
artInst->addPart(ArtifactUtils::createNewArtifactInstance(part), ArtifactPosition::PRE_FIRST);
}
if(art->isGrowing())
{
auto bonus = std::make_shared<Bonus>();
bonus->type = BonusType::LEVEL_COUNTER;
bonus->val = 0;
artInst->addNewBonus(bonus);
}
return artInst;
}
assert(art);
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createNewArtifactInstance(const ArtifactID & aid)
{
return ArtifactUtils::createNewArtifactInstance(aid.toArtifact());
}
DLL_LINKAGE CArtifactInstance * ArtifactUtils::createArtifact(CMap * map, const ArtifactID & aid, SpellID spellID)
{
CArtifactInstance * art = nullptr;
if(aid.getNum() >= 0)
{
if(spellID == SpellID::NONE)
auto * artInst = new CArtifactInstance(art);
if(art->isCombined())
{
art = ArtifactUtils::createNewArtifactInstance(aid);
for(const auto & part : art->getConstituents())
artInst->addPart(createArtInst(part), ArtifactPosition::PRE_FIRST);
}
else
if(art->isGrowing())
{
art = ArtifactUtils::createScroll(spellID);
auto bonus = std::make_shared<Bonus>();
bonus->type = BonusType::LEVEL_COUNTER;
bonus->val = 0;
artInst->addNewBonus(bonus);
}
if(art->isScroll())
{
artInst->addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::SPELL,
BonusSource::ARTIFACT_INSTANCE, -1, BonusSourceID(ArtifactID(ArtifactID::SPELL_SCROLL)), BonusSubtypeID(spellId)));
}
return artInst;
};
if(artId.getNum() >= 0)
{
return createArtInst(artId.toArtifact());
}
else
{
art = new CArtifactInstance(); // random, empty
return new CArtifactInstance(); // random, empty
}
map->addNewArtifactInstance(art);
if(art->artType && art->isCombined())
{
for(auto & part : art->getPartsInfo())
{
map->addNewArtifactInstance(part.art);
}
}
return art;
}
DLL_LINKAGE void ArtifactUtils::insertScrrollSpellName(std::string & description, const SpellID & sid)

View File

@ -21,7 +21,6 @@ class CGHeroInstance;
class CArtifactSet;
class CArtifactInstance;
struct ArtSlotInfo;
class CMap;
namespace ArtifactUtils
{
@ -40,10 +39,8 @@ namespace ArtifactUtils
DLL_LINKAGE bool isSlotEquipment(const ArtifactPosition & slot);
DLL_LINKAGE bool isBackpackFreeSlots(const CArtifactSet * target, const size_t reqSlots = 1);
DLL_LINKAGE std::vector<const CArtifact*> assemblyPossibilities(const CArtifactSet * artSet, const ArtifactID & aid, const bool onlyEquiped = false);
DLL_LINKAGE CArtifactInstance * createScroll(const SpellID & sid);
DLL_LINKAGE CArtifactInstance * createNewArtifactInstance(const CArtifact * art);
DLL_LINKAGE CArtifactInstance * createNewArtifactInstance(const ArtifactID & aid);
DLL_LINKAGE CArtifactInstance * createArtifact(CMap * map, const ArtifactID & aid, SpellID spellID = SpellID::NONE);
DLL_LINKAGE CArtifactInstance * createScroll(const SpellID & spellId);
DLL_LINKAGE CArtifactInstance * createArtifact(const ArtifactID & artId, const SpellID & spellId = SpellID::NONE);
DLL_LINKAGE void insertScrrollSpellName(std::string & description, const SpellID & sid);
}

View File

@ -964,7 +964,7 @@ void CArtifactSet::artDeserializationFix(CBonusSystemNode *node)
node->attachTo(*elem.second.artifact);
}
void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map)
void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName)
{
//todo: creature and commander artifacts
if(handler.saving && artifactsInBackpack.empty() && artifactsWorn.empty())
@ -972,7 +972,6 @@ void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const s
if(!handler.saving)
{
assert(map);
artifactsInBackpack.clear();
artifactsWorn.clear();
}
@ -982,13 +981,13 @@ void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const s
switch(bearerType())
{
case ArtBearer::HERO:
serializeJsonHero(handler, map);
serializeJsonHero(handler);
break;
case ArtBearer::CREATURE:
serializeJsonCreature(handler, map);
serializeJsonCreature(handler);
break;
case ArtBearer::COMMANDER:
serializeJsonCommander(handler, map);
serializeJsonCommander(handler);
break;
default:
assert(false);
@ -996,11 +995,11 @@ void CArtifactSet::serializeJsonArtifacts(JsonSerializeFormat & handler, const s
}
}
void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler)
{
for(const auto & slot : ArtifactUtils::allWornSlots())
{
serializeJsonSlot(handler, slot, map);
serializeJsonSlot(handler, slot);
}
std::vector<ArtifactID> backpackTemp;
@ -1016,7 +1015,7 @@ void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
{
for(const ArtifactID & artifactID : backpackTemp)
{
auto * artifact = ArtifactUtils::createArtifact(map, artifactID);
auto * artifact = ArtifactUtils::createArtifact(artifactID);
auto slot = ArtifactPosition::BACKPACK_START + artifactsInBackpack.size();
if(artifact->artType->canBePutAt(this, slot))
{
@ -1027,17 +1026,17 @@ void CArtifactSet::serializeJsonHero(JsonSerializeFormat & handler, CMap * map)
}
}
void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler, CMap * map)
void CArtifactSet::serializeJsonCreature(JsonSerializeFormat & handler)
{
logGlobal->error("CArtifactSet::serializeJsonCreature not implemented");
}
void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler, CMap * map)
void CArtifactSet::serializeJsonCommander(JsonSerializeFormat & handler)
{
logGlobal->error("CArtifactSet::serializeJsonCommander not implemented");
}
void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map)
void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot)
{
ArtifactID artifactID;
@ -1057,7 +1056,7 @@ void CArtifactSet::serializeJsonSlot(JsonSerializeFormat & handler, const Artifa
if(artifactID != ArtifactID::NONE)
{
auto * artifact = ArtifactUtils::createArtifact(map, artifactID.toEnum());
auto * artifact = ArtifactUtils::createArtifact(artifactID.toEnum());
if(artifact->artType->canBePutAt(this, slot))
{

View File

@ -25,7 +25,6 @@ class CArtHandler;
class CGHeroInstance;
class CArtifactSet;
class CArtifactInstance;
class CMap;
class JsonSerializeFormat;
#define ART_BEARER_LIST \
@ -233,16 +232,16 @@ public:
void artDeserializationFix(CBonusSystemNode *node);
void serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName, CMap * map);
void serializeJsonArtifacts(JsonSerializeFormat & handler, const std::string & fieldName);
protected:
std::pair<const CArtifactInstance *, const CArtifactInstance *> searchForConstituent(const ArtifactID & aid) const;
private:
void serializeJsonHero(JsonSerializeFormat & handler, CMap * map);
void serializeJsonCreature(JsonSerializeFormat & handler, CMap * map);
void serializeJsonCommander(JsonSerializeFormat & handler, CMap * map);
void serializeJsonHero(JsonSerializeFormat & handler);
void serializeJsonCreature(JsonSerializeFormat & handler);
void serializeJsonCommander(JsonSerializeFormat & handler);
void serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot, CMap * map);//normal slots
void serializeJsonSlot(JsonSerializeFormat & handler, const ArtifactPosition & slot);//normal slots
};
// Used to try on artifacts before the claimed changes have been applied

View File

@ -620,7 +620,6 @@ set(lib_MAIN_HEADERS
serializer/JsonSerializeFormat.h
serializer/JsonSerializer.h
serializer/JsonUpdater.h
serializer/Cast.h
serializer/ESerializationVersion.h
serializer/RegisterTypes.h
serializer/Serializeable.h

View File

@ -33,6 +33,7 @@ class CStackBasicDescriptor;
class CGCreature;
class CSaveFile;
class CLoadFile;
class IObjectInterface;
enum class EOpenWindowMode : uint8_t;
namespace spells
@ -98,7 +99,7 @@ public:
virtual void giveExperience(const CGHeroInstance * hero, TExpType val) =0;
virtual void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs=false)=0;
virtual void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false)=0;
virtual void showBlockingDialog(BlockingDialog *iw) =0;
virtual void showBlockingDialog(const IObjectInterface * caller, BlockingDialog *iw) =0;
virtual void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) =0; //cb will be called when player closes garrison window
virtual void showTeleportDialog(TeleportDialog *iw) =0;
virtual void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) = 0;
@ -118,7 +119,8 @@ public:
virtual void removeAfterVisit(const CGObjectInstance *object) = 0; //object will be destroyed when interaction is over. Do not call when interaction is not ongoing!
virtual bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos) = 0;
virtual bool giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos) = 0;
virtual bool giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos) = 0;
virtual bool putArtifact(const ArtifactLocation & al, const CArtifactInstance * art, std::optional<bool> askAssemble = std::nullopt) = 0;
virtual void removeArtifact(const ArtifactLocation& al) = 0;
virtual bool moveArtifact(const PlayerColor & player, const ArtifactLocation & al1, const ArtifactLocation & al2) = 0;

View File

@ -429,7 +429,10 @@ CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap
hero->ID = Obj::HERO;
hero->serializeJsonOptions(handler);
if (map)
hero->serializeJsonArtifacts(handler, "artifacts", map);
{
hero->serializeJsonArtifacts(handler, "artifacts");
map->addNewArtifactInstance(*hero);
}
return hero;
}

View File

@ -44,6 +44,7 @@ public:
BuildingID upgrade; /// indicates that building "upgrade" can be improved by this, -1 = empty
BuildingSubID::EBuildingSubID subId; /// subtype for special buildings, -1 = the building is not special
bool upgradeReplacesBonuses = false;
bool manualHeroVisit = false;
BonusList buildingBonuses;
Rewardable::Info rewardableObjectInfo; ///configurable rewards for special buildings

View File

@ -299,6 +299,9 @@ void CTownHandler::loadBuilding(CTown * town, const std::string & stringID, cons
ret->resources = TResources(source["cost"]);
ret->produce = TResources(source["produce"]);
ret->manualHeroVisit = source["manualHeroVisit"].Bool();
ret->upgradeReplacesBonuses = source["upgradeReplacesBonuses"].Bool();
const JsonNode & fortifications = source["fortifications"];
if (!fortifications.isNull())
{

View File

@ -1628,7 +1628,7 @@ void CGameState::attachArmedObjects()
bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
{
CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(aid);
CArtifactInstance * ai = ArtifactUtils::createArtifact(aid);
map->addNewArtifactInstance(ai);
auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))

View File

@ -178,7 +178,7 @@ void CBank::onHeroVisit(const CGHeroInstance * h) const
if (banktext == 32)
bd.text.replaceRawString(getObjectName());
cb->showBlockingDialog(&bd);
cb->showBlockingDialog(this, &bd);
}
void CBank::doVisit(const CGHeroInstance * hero) const
@ -292,7 +292,7 @@ void CBank::doVisit(const CGHeroInstance * hero) const
iw.components.emplace_back(ComponentType::ARTIFACT, elem);
loot.appendRawString("%s");
loot.replaceName(elem);
cb->giveHeroNewArtifact(hero, elem.toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
cb->giveHeroNewArtifact(hero, elem, ArtifactPosition::FIRST_AVAILABLE);
}
//display loot
if (!iw.components.empty())

View File

@ -164,7 +164,7 @@ void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
ynd.player = h->tempOwner;
ynd.text.appendLocalString(EMetaText::ADVOB_TXT, 86);
ynd.text.replaceName(getCreature(), getStackCount(SlotID(0)));
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
break;
}
default: //join for gold
@ -180,7 +180,7 @@ void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
boost::algorithm::replace_first(tmp,"%s",VLC->creatures()->getById(getCreature())->getNamePluralTranslated());
ynd.text.appendRawString(tmp);
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
break;
}
}
@ -475,7 +475,7 @@ void CGCreature::flee( const CGHeroInstance * h ) const
ynd.player = h->tempOwner;
ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
ynd.text.replaceName(getCreature(), getStackCount(SlotID(0)));
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
}
void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
@ -605,7 +605,7 @@ void CGCreature::giveReward(const CGHeroInstance * h) const
if(gainedArtifact != ArtifactID::NONE)
{
cb->giveHeroNewArtifact(h, gainedArtifact.toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
cb->giveHeroNewArtifact(h, gainedArtifact, ArtifactPosition::FIRST_AVAILABLE);
iw.components.emplace_back(ComponentType::ARTIFACT, gainedArtifact);
}

View File

@ -244,7 +244,7 @@ void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
else
bd.text.replaceLocalString(EMetaText::ARRAY_TXT, 173 + (int)Slots().begin()->second->getQuantityID()*3);
bd.text.replaceName(*Slots().begin()->second);
cb->showBlockingDialog(&bd);
cb->showBlockingDialog(this, &bd);
return;
}
@ -280,7 +280,7 @@ void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
bd.flags |= BlockingDialog::SAFE_TO_AUTOACCEPT;
}
cb->showBlockingDialog(&bd);
cb->showBlockingDialog(this, &bd);
}
void CGDwelling::newTurn(vstd::RNG & rand) const

View File

@ -343,7 +343,7 @@ void CGHeroInstance::initHero(vstd::RNG & rand)
// hero starts with default spellbook presence status
if(!getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook)
{
auto artifact = ArtifactUtils::createNewArtifactInstance(ArtifactID::SPELLBOOK);
auto artifact = ArtifactUtils::createArtifact(ArtifactID::SPELLBOOK);
putArtifact(ArtifactPosition::SPELLBOOK, artifact);
}
}
@ -352,7 +352,7 @@ void CGHeroInstance::initHero(vstd::RNG & rand)
if(!getArt(ArtifactPosition::MACH4))
{
auto artifact = ArtifactUtils::createNewArtifactInstance(ArtifactID::CATAPULT);
auto artifact = ArtifactUtils::createArtifact(ArtifactID::CATAPULT);
putArtifact(ArtifactPosition::MACH4, artifact); //everyone has a catapult
}
@ -468,7 +468,7 @@ void CGHeroInstance::initArmy(vstd::RNG & rand, IArmyDescriptor * dst)
if(!getArt(slot))
{
auto artifact = ArtifactUtils::createNewArtifactInstance(aid);
auto artifact = ArtifactUtils::createArtifact(aid);
putArtifact(slot, artifact);
}
else
@ -1709,7 +1709,7 @@ void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
handler.serializeIdArray("spellBook", spells);
if(handler.saving)
CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
CArtifactSet::serializeJsonArtifacts(handler, "artifacts");
}
void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)

View File

@ -175,7 +175,7 @@ void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
BlockingDialog bd (true, false);
bd.player = h->getOwner();
bd.text.appendLocalString(EMetaText::ADVOB_TXT, 14);
cb->showBlockingDialog(&bd);
cb->showBlockingDialog(this, &bd);
}
void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const

View File

@ -301,12 +301,6 @@ void CGTownInstance::setOwner(const PlayerColor & player) const
cb->setOwner(this, player);
}
void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
{
for (auto building : rewardableBuildings)
building.second->blockingDialogAnswered(hero, answer); // FIXME: why call for every building?
}
void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
{
if(cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)

View File

@ -239,7 +239,6 @@ public:
protected:
void setPropertyDer(ObjProperty what, ObjPropertyID identifier) override;
void serializeJsonOptions(JsonSerializeFormat & handler) override;
void blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const override;
private:
FactionID randomizeFaction(vstd::RNG & rand);

View File

@ -163,7 +163,7 @@ void CQuest::completeQuest(IGameCallback * cb, const CGHeroInstance *h) const
for(const auto & ci : parts)
{
if(ci.art->getTypeId() != elem)
cb->giveHeroNewArtifact(h, ci.art->artType, ArtifactPosition::BACKPACK_START);
cb->giveHeroNewArtifact(h, ci.art->getTypeId(), ArtifactPosition::BACKPACK_START);
}
}
}
@ -851,7 +851,7 @@ void CGBorderGuard::onHeroVisit(const CGHeroInstance * h) const
BlockingDialog bd (true, false);
bd.player = h->getOwner();
bd.text.appendLocalString (EMetaText::ADVOB_TXT, 17);
cb->showBlockingDialog (&bd);
cb->showBlockingDialog (this, &bd);
}
else
{

View File

@ -52,7 +52,7 @@ void CRewardableObject::selectRewardWithMessage(const CGHeroInstance * contextHe
sd.player = contextHero->tempOwner;
sd.text = dialog;
sd.components = loadComponents(contextHero, rewardIndices);
cb->showBlockingDialog(&sd);
cb->showBlockingDialog(this, &sd);
}

View File

@ -88,7 +88,7 @@ void CGMine::onHeroVisit( const CGHeroInstance * h ) const
BlockingDialog ynd(true,false);
ynd.player = h->tempOwner;
ynd.text.appendLocalString(EMetaText::ADVOB_TXT, isAbandoned() ? 84 : 187);
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
return;
}
@ -310,7 +310,7 @@ void CGResource::onHeroVisit( const CGHeroInstance * h ) const
BlockingDialog ynd(true,false);
ynd.player = h->getOwner();
ynd.text = message;
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
}
else
{
@ -879,7 +879,7 @@ void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
ynd.text.replaceRawString(getArmyDescription());
ynd.text.replaceLocalString(EMetaText::GENERAL_TXT, 43); // creatures
}
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
}
break;
case Obj::SPELL_SCROLL:
@ -889,7 +889,7 @@ void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
BlockingDialog ynd(true,false);
ynd.player = h->getOwner();
ynd.text = message;
cb->showBlockingDialog(&ynd);
cb->showBlockingDialog(this, &ynd);
}
else
blockingDialogAnswered(h, true);

View File

@ -221,7 +221,7 @@ void TownRewardableBuildingInstance::onHeroVisit(const CGHeroInstance *h) const
if (rewards.size() == 1)
configuration.info.at(rewards.front()).reward.loadComponents(sd.components, h);
cb->showBlockingDialog(&sd);
cb->showBlockingDialog(this, &sd);
};
if(!town->hasBuilt(getBuildingType()))

View File

@ -519,10 +519,26 @@ void CMap::checkForObjectives()
}
}
void CMap::addNewArtifactInstance(CArtifactSet & artSet)
{
for(const auto & [slot, slotInfo] : artSet.artifactsWorn)
{
if(!slotInfo.locked && slotInfo.getArt())
addNewArtifactInstance(slotInfo.artifact);
}
for(const auto & slotInfo : artSet.artifactsInBackpack)
addNewArtifactInstance(slotInfo.artifact);
}
void CMap::addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art)
{
assert(art);
assert(art->getId() == -1);
art->setId(static_cast<ArtifactInstanceID>(artInstances.size()));
artInstances.emplace_back(art);
for(const auto & partInfo : art->getPartsInfo())
addNewArtifactInstance(partInfo.art);
}
void CMap::eraseArtifactInstance(CArtifactInstance * art)

View File

@ -20,6 +20,7 @@
VCMI_LIB_NAMESPACE_BEGIN
class CArtifactInstance;
class CArtifactSet;
class CGObjectInstance;
class CGHeroInstance;
class CCommanderInstance;
@ -102,6 +103,7 @@ public:
void removeBlockVisTiles(CGObjectInstance * obj, bool total = false);
void calculateGuardingGreaturePositions();
void addNewArtifactInstance(CArtifactSet & artSet);
void addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art);
void eraseArtifactInstance(CArtifactInstance * art);

View File

@ -957,14 +957,15 @@ bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
// H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
// He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
// Artifact seems to be missing in game, so skip artifacts that don't fit target slot
auto * artifact = ArtifactUtils::createArtifact(map, artifactID);
if(artifact->canBePutAt(hero, ArtifactPosition(slot)))
if(ArtifactID(artifactID).toArtifact()->canBePutAt(hero, ArtifactPosition(slot)))
{
auto * artifact = ArtifactUtils::createArtifact(artifactID);
artifact->putAt(*hero, ArtifactPosition(slot));
map->addNewArtifactInstance(artifact);
}
else
{
logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, artifact->artType->getNameTranslated(), slot);
logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, ArtifactID(artifactID).toArtifact()->getNameTranslated(), slot);
return false;
}
@ -1308,7 +1309,8 @@ CGObjectInstance * CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::sh
artID = ArtifactID(objectTemplate->subid);
}
object->storedArtifact = ArtifactUtils::createArtifact(map, artID, spellID.getNum());
object->storedArtifact = ArtifactUtils::createArtifact(artID, spellID.getNum());
map->addNewArtifactInstance(object->storedArtifact);
return object;
}

View File

@ -1107,13 +1107,15 @@ void CMapLoaderJson::MapObjectLoader::configure()
artID = art->getArtifact();
}
art->storedArtifact = ArtifactUtils::createArtifact(owner->map, artID, spellID.getNum());
art->storedArtifact = ArtifactUtils::createArtifact(artID, spellID.getNum());
owner->map->addNewArtifactInstance(art->storedArtifact);
}
if(auto * hero = dynamic_cast<CGHeroInstance *>(instance))
{
auto o = handler.enterStruct("options");
hero->serializeJsonArtifacts(handler, "artifacts", owner->map);
hero->serializeJsonArtifacts(handler, "artifacts");
owner->map->addNewArtifactInstance(*hero);
}
}

View File

@ -126,7 +126,7 @@ public:
virtual void visitBulkSmartSplitStack(BulkSmartSplitStack & pack) {}
virtual void visitDisbandCreature(DisbandCreature & pack) {}
virtual void visitBuildStructure(BuildStructure & pack) {}
virtual void visitTriggerTownSpecialBuildingAction(TriggerTownSpecialBuildingAction & pack) {}
virtual void visitVisitTownBuilding(VisitTownBuilding & pack) {}
virtual void visitRazeStructure(RazeStructure & pack) {}
virtual void visitRecruitCreatures(RecruitCreatures & pack) {}
virtual void visitUpgradeCreature(UpgradeCreature & pack) {}

View File

@ -582,9 +582,9 @@ void BuildStructure::visitTyped(ICPackVisitor & visitor)
visitor.visitBuildStructure(*this);
}
void TriggerTownSpecialBuildingAction::visitTyped(ICPackVisitor & visitor)
void VisitTownBuilding::visitTyped(ICPackVisitor & visitor)
{
visitor.visitTriggerTownSpecialBuildingAction(*this);
visitor.visitVisitTownBuilding(*this);
}
void RazeStructure::visitTyped(ICPackVisitor & visitor)
@ -1472,17 +1472,11 @@ void NewObject::applyGs(CGameState *gs)
void NewArtifact::applyGs(CGameState *gs)
{
assert(!vstd::contains(gs->map->artInstances, art));
assert(!art->getParentNodes().size());
assert(art->artType);
art->setType(art->artType);
if(art->isCombined())
{
for(const auto & part : art->artType->getConstituents())
art->addPart(ArtifactUtils::createNewArtifactInstance(part), ArtifactPosition::PRE_FIRST);
}
auto art = ArtifactUtils::createArtifact(artId, spellId);
gs->map->addNewArtifactInstance(art);
PutArtifact pa(ArtifactLocation(artHolder, pos), false);
pa.art = art;
pa.applyGs(gs);
}
const CStackInstance * StackLocation::getStack()
@ -1700,6 +1694,7 @@ void PutArtifact::applyGs(CGameState *gs)
auto hero = gs->getHero(al.artHolder);
assert(hero);
assert(art && art->canBePutAt(hero, al.slot));
assert(ArtifactUtils::checkIfSlotValid(*hero, al.slot));
art->putAt(*hero, al.slot);
}

View File

@ -965,7 +965,7 @@ struct DLL_LINKAGE CArtifactOperationPack : CPackForClient
struct DLL_LINKAGE PutArtifact : CArtifactOperationPack
{
PutArtifact() = default;
explicit PutArtifact(ArtifactLocation & dst, bool askAssemble = true)
explicit PutArtifact(const ArtifactLocation & dst, bool askAssemble = true)
: al(dst), askAssemble(askAssemble)
{
}
@ -987,14 +987,20 @@ struct DLL_LINKAGE PutArtifact : CArtifactOperationPack
struct DLL_LINKAGE NewArtifact : public CArtifactOperationPack
{
ConstTransitivePtr<CArtifactInstance> art;
ObjectInstanceID artHolder;
ArtifactID artId;
SpellID spellId;
ArtifactPosition pos;
void applyGs(CGameState * gs) override;
void visitTyped(ICPackVisitor & visitor) override;
template <typename Handler> void serialize(Handler & h)
{
h & art;
h & artHolder;
h & artId;
h & spellId;
h & pos;
}
};

View File

@ -280,16 +280,16 @@ struct DLL_LINKAGE BuildStructure : public CPackForServer
}
};
struct DLL_LINKAGE TriggerTownSpecialBuildingAction : public CPackForServer
struct DLL_LINKAGE VisitTownBuilding : public CPackForServer
{
TriggerTownSpecialBuildingAction() = default;
TriggerTownSpecialBuildingAction(const ObjectInstanceID & TID, const BuildingSubID::EBuildingSubID SID)
VisitTownBuilding() = default;
VisitTownBuilding(const ObjectInstanceID & TID, const BuildingID BID)
: tid(TID)
, sid(SID)
, bid(BID)
{
}
ObjectInstanceID tid;
BuildingSubID::EBuildingSubID sid;
BuildingID bid;
void visitTyped(ICPackVisitor & visitor) override;
@ -297,7 +297,7 @@ struct DLL_LINKAGE TriggerTownSpecialBuildingAction : public CPackForServer
{
h & static_cast<CPackForServer &>(*this);
h & tid;
h & sid;
h & bid;
}
};

View File

@ -157,7 +157,7 @@ void Rewardable::Interface::grantRewardAfterLevelup(IGameCallback * cb, const Re
}
for(const ArtifactID & art : info.reward.artifacts)
cb->giveHeroNewArtifact(hero, art.toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
cb->giveHeroNewArtifact(hero, art, ArtifactPosition::FIRST_AVAILABLE);
if(!info.reward.spells.empty())
{

View File

@ -1,26 +0,0 @@
/*
* Cast.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
VCMI_LIB_NAMESPACE_BEGIN
template<class T, class F>
inline const T * dynamic_ptr_cast(const F * ptr)
{
return dynamic_cast<const T *>(ptr);
}
template<class T, class F>
inline T * dynamic_ptr_cast(F * ptr)
{
return dynamic_cast<T *>(ptr);
}
VCMI_LIB_NAMESPACE_END

View File

@ -239,7 +239,7 @@ void registerTypes(Serializer &s)
s.template registerType<ArrangeStacks>(183);
s.template registerType<DisbandCreature>(184);
s.template registerType<BuildStructure>(185);
s.template registerType<TriggerTownSpecialBuildingAction>(186);
s.template registerType<VisitTownBuilding>(186);
s.template registerType<RecruitCreatures>(187);
s.template registerType<UpgradeCreature>(188);
s.template registerType<GarrisonHeroSwap>(189);

View File

@ -165,7 +165,7 @@ void MapController::repairMap(CMap * map) const
{
nih->removeSpellFromSpellbook(SpellID::SPELLBOOK_PRESET);
if(!nih->getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook)
nih->putArtifact(ArtifactPosition::SPELLBOOK, ArtifactUtils::createNewArtifactInstance(ArtifactID::SPELLBOOK));
nih->putArtifact(ArtifactPosition::SPELLBOOK, ArtifactUtils::createArtifact(ArtifactID::SPELLBOOK));
}
}

View File

@ -1473,37 +1473,37 @@
<message>
<location filename="../inspector/townbuildingswidget.ui" line="53"/>
<source>Build all</source>
<translation type="unfinished"></translation>
<translation>Construir tudo</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.ui" line="60"/>
<source>Demolish all</source>
<translation type="unfinished"></translation>
<translation>Demolir tudo</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.ui" line="67"/>
<source>Enable all</source>
<translation type="unfinished"></translation>
<translation>Ativar tudo</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.ui" line="74"/>
<source>Disable all</source>
<translation type="unfinished"></translation>
<translation>Desativar tudo</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.cpp" line="132"/>
<source>Type</source>
<translation type="unfinished">Tipo</translation>
<translation>Tipo</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.cpp" line="132"/>
<source>Enabled</source>
<translation type="unfinished"></translation>
<translation>Ativado</translation>
</message>
<message>
<location filename="../inspector/townbuildingswidget.cpp" line="132"/>
<source>Built</source>
<translation type="unfinished"></translation>
<translation>Construído</translation>
</message>
</context>
<context>
@ -1511,77 +1511,77 @@
<message>
<location filename="../inspector/towneventdialog.ui" line="23"/>
<source>Town event</source>
<translation type="unfinished"></translation>
<translation>Evento da cidade</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="42"/>
<source>General</source>
<translation type="unfinished">Geral</translation>
<translation>Geral</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="57"/>
<source>Event name</source>
<translation type="unfinished">Nome do evento</translation>
<translation>Nome do evento</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="64"/>
<source>Type event message text</source>
<translation type="unfinished">Introduza o texto da mensagem do evento</translation>
<translation>Introduza o texto da mensagem do evento</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="85"/>
<source>Day of first occurrence</source>
<translation type="unfinished">Dia da primeira ocorrência</translation>
<translation>Dia da primeira ocorrência</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="99"/>
<source>Repeat after (0 = no repeat)</source>
<translation type="unfinished">Repetir após (0 = não repetir)</translation>
<translation>Repetir após (0 = não repetir)</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="123"/>
<source>Affected players</source>
<translation type="unfinished">Jogadores afetados</translation>
<translation>Jogadores afetados</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="146"/>
<source>affects human</source>
<translation type="unfinished">afeta humano</translation>
<translation>afeta humano</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="155"/>
<source>affects AI</source>
<translation type="unfinished">afeta IA</translation>
<translation>afeta IA</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="166"/>
<source>Resources</source>
<translation type="unfinished">Recursos</translation>
<translation>Recursos</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="198"/>
<source>Buildings</source>
<translation type="unfinished">Estruturas</translation>
<translation>Estruturas</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="219"/>
<source>Creatures</source>
<translation type="unfinished">Criaturas</translation>
<translation>Criaturas</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.ui" line="258"/>
<source>OK</source>
<translation type="unfinished"></translation>
<translation>OK</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.cpp" line="163"/>
<source>Creature level %1 / Creature level %1 Upgrade</source>
<translation type="unfinished"></translation>
<translation>Nível da criatura %1 / Nível da criatura %1 - Atualização</translation>
</message>
<message>
<location filename="../inspector/towneventdialog.cpp" line="205"/>
<source>Day %1 - %2</source>
<translation type="unfinished"></translation>
<translation>Dia %1 - %2</translation>
</message>
</context>
<context>
@ -1589,32 +1589,32 @@
<message>
<location filename="../inspector/towneventswidget.ui" line="29"/>
<source>Town events</source>
<translation type="unfinished"></translation>
<translation>Eventos da cidade</translation>
</message>
<message>
<location filename="../inspector/towneventswidget.ui" line="37"/>
<source>Timed events</source>
<translation type="unfinished">Eventos Temporizados</translation>
<translation>Eventos Temporizados</translation>
</message>
<message>
<location filename="../inspector/towneventswidget.ui" line="63"/>
<source>Add</source>
<translation type="unfinished">Adicionar</translation>
<translation>Adicionar</translation>
</message>
<message>
<location filename="../inspector/towneventswidget.ui" line="76"/>
<source>Remove</source>
<translation type="unfinished">Remover</translation>
<translation>Remover</translation>
</message>
<message>
<location filename="../inspector/towneventswidget.cpp" line="106"/>
<source>Day %1 - %2</source>
<translation type="unfinished"></translation>
<translation>Dia %1 - %2</translation>
</message>
<message>
<location filename="../inspector/towneventswidget.cpp" line="127"/>
<source>New event</source>
<translation type="unfinished">Novo Evento</translation>
<translation>Novo Evento</translation>
</message>
</context>
<context>
@ -1622,17 +1622,17 @@
<message>
<location filename="../inspector/townspellswidget.ui" line="29"/>
<source>Spells</source>
<translation type="unfinished">Feitiços</translation>
<translation>Feitiços</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="47"/>
<source>Customize spells</source>
<translation type="unfinished">Personalizar feitiços</translation>
<translation>Personalizar feitiços</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="76"/>
<source>Level 1</source>
<translation type="unfinished">Nível 1</translation>
<translation>Nível 1</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="93"/>
@ -1641,7 +1641,7 @@
<location filename="../inspector/townspellswidget.ui" line="231"/>
<location filename="../inspector/townspellswidget.ui" line="277"/>
<source>Spell that may appear in mage guild</source>
<translation type="unfinished"></translation>
<translation>Feitiço que pode aparecer na guilda dos magos</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="100"/>
@ -1650,27 +1650,27 @@
<location filename="../inspector/townspellswidget.ui" line="238"/>
<location filename="../inspector/townspellswidget.ui" line="284"/>
<source>Spell that must appear in mage guild</source>
<translation type="unfinished"></translation>
<translation>Feitiço que deve aparecer na guilda dos magos</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="122"/>
<source>Level 2</source>
<translation type="unfinished">Nível 2</translation>
<translation>Nível 2</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="168"/>
<source>Level 3</source>
<translation type="unfinished">Nível 3</translation>
<translation>Nível 3</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="214"/>
<source>Level 4</source>
<translation type="unfinished">Nível 4</translation>
<translation>Nível 4</translation>
</message>
<message>
<location filename="../inspector/townspellswidget.ui" line="260"/>
<source>Level 5</source>
<translation type="unfinished">Nível 5</translation>
<translation>Nível 5</translation>
</message>
</context>
<context>

View File

@ -21,6 +21,7 @@
#include "processors/TurnOrderProcessor.h"
#include "queries/QueriesProcessor.h"
#include "queries/MapQueries.h"
#include "queries/VisitQueries.h"
#include "../lib/ArtifactUtils.h"
#include "../lib/CArtHandler.h"
@ -1077,9 +1078,9 @@ void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owne
}
}
void CGameHandler::showBlockingDialog(BlockingDialog *iw)
void CGameHandler::showBlockingDialog(const IObjectInterface * caller, BlockingDialog *iw)
{
auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, caller, *iw);
queries->addQuery(dialogQuery);
iw->queryID = dialogQuery->queryID;
sendToAllClients(iw);
@ -1181,7 +1182,10 @@ void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInsta
void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
{
for (auto & building : t->rewardableBuildings)
building.second->onHeroVisit(h);
{
if (!t->town->buildings.at(building.first)->manualHeroVisit)
building.second->onHeroVisit(h);
}
}
void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
@ -2148,20 +2152,38 @@ bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID,
return true;
}
bool CGameHandler::triggerTownSpecialBuildingAction(ObjectInstanceID tid, BuildingSubID::EBuildingSubID sid)
bool CGameHandler::visitTownBuilding(ObjectInstanceID tid, BuildingID bid)
{
const CGTownInstance * t = getTown(tid);
if(t->town->getBuildingType(sid) == BuildingID::NONE)
if(!t->hasBuilt(bid))
return false;
if(sid == BuildingSubID::EBuildingSubID::BANK)
auto subID = t->town->buildings.at(bid)->subId;
if(subID == BuildingSubID::EBuildingSubID::BANK)
{
TResources res;
res[EGameResID::GOLD] = 2500;
giveResources(t->getOwner(), res);
setObjPropertyValue(t->id, ObjProperty::BONUS_VALUE_SECOND, 2500);
return true;
}
if (t->rewardableBuildings.count(bid))
{
auto & hero = t->garrisonHero ? t->garrisonHero : t->visitingHero;
auto * building = t->rewardableBuildings.at(bid);
if (hero && t->town->buildings.at(bid)->manualHeroVisit)
{
auto visitQuery = std::make_shared<TownBuildingVisitQuery>(this, t, hero, bid);
queries->addQuery(visitQuery);
building->onHeroVisit(hero);
queries->popIfTop(visitQuery);
return true;
}
}
return true;
@ -2267,7 +2289,7 @@ bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst
COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
return giveHeroNewArtifact(hero, art);
return giveHeroNewArtifact(hero, artId, ArtifactPosition::FIRST_AVAILABLE);
}
else
{
@ -2502,7 +2524,7 @@ bool CGameHandler::moveArtifact(const PlayerColor & player, const ArtifactLocati
auto hero = getHero(dst.artHolder);
if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dstSlot))
giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
ma.artsPack0.push_back(BulkMoveArtifacts::LinkedSlots(src.slot, dstSlot));
if(src.artHolder != dst.artHolder)
@ -2543,7 +2565,7 @@ bool CGameHandler::bulkMoveArtifacts(const PlayerColor & player, ObjectInstanceI
if(auto dstHero = getHero(dstId))
{
if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
giveHeroNewArtifact(dstHero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
giveHeroNewArtifact(dstHero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
}
}
};
@ -2736,7 +2758,7 @@ bool CGameHandler::assembleArtifacts(ObjectInstanceID heroID, ArtifactPosition a
}
if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
AssembledArtifact aa;
aa.al = dstLoc;
@ -2793,7 +2815,7 @@ bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
return false;
giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
assert(hero->getArt(ArtifactPosition::SPELLBOOK));
giveSpells(town,hero);
return true;
@ -2821,7 +2843,7 @@ bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
}
giveResource(hero->getOwner(),EGameResID::GOLD,-price);
return giveHeroNewArtifact(hero, art);
return giveHeroNewArtifact(hero, aid, ArtifactPosition::FIRST_AVAILABLE);
}
else
COMPLAIN_RET("This machine is unavailable here!");
@ -2874,7 +2896,7 @@ bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameRe
COMPLAIN_RET("Cannot find selected artifact on the list");
sendAndApply(&saa);
giveHeroNewArtifact(h, aid.toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
giveHeroNewArtifact(h, aid, ArtifactPosition::FIRST_AVAILABLE);
return true;
}
@ -3185,7 +3207,7 @@ void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInsta
throw std::runtime_error("Can not visit object that is being visited");
}
std::shared_ptr<CObjectVisitQuery> visitQuery;
std::shared_ptr<MapObjectVisitQuery> visitQuery;
auto startVisit = [&](ObjectVisitStarted & event)
{
@ -3204,7 +3226,7 @@ void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInsta
visitedObject = visitedTown;
}
}
visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
visitQuery = std::make_shared<MapObjectVisitQuery>(this, visitedObject, h);
queries->addQuery(visitQuery); //TODO real visit pos
HeroVisit hv;
@ -3223,11 +3245,11 @@ void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInsta
queries->popIfTop(visitQuery); //visit ends here if no queries were created
}
void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
void CGameHandler::objectVisitEnded(const CGHeroInstance *h, PlayerColor player)
{
using events::ObjectVisitEnded;
logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
logGlobal->debug("%s visit ends.\n", h->nodeName());
auto endVisit = [&](ObjectVisitEnded & event)
{
@ -3240,7 +3262,7 @@ void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
//TODO: ObjectVisitEnded should also have id of visited object,
//but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, player, h->id);
}
bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
@ -3416,7 +3438,7 @@ bool CGameHandler::dig(const CGHeroInstance *h)
iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the " ...
iw.text.appendName(grail); // ... " The Grail"
iw.soundID = soundBase::ULTIMATEARTIFACT;
giveHeroNewArtifact(h, grail.toArtifact(), ArtifactPosition::FIRST_AVAILABLE); //give grail
giveHeroNewArtifact(h, grail, ArtifactPosition::FIRST_AVAILABLE); //give grail
sendAndApply(&iw);
iw.soundID = soundBase::invalid;
@ -3756,13 +3778,21 @@ bool CGameHandler::putArtifact(const ArtifactLocation & al, const CArtifactInsta
}
}
bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
bool CGameHandler::giveHeroNewArtifact(
const CGHeroInstance * h, const CArtifact * artType, const SpellID & spellId, const ArtifactPosition & pos)
{
assert(artType);
NewArtifact na;
na.artHolder = h->id;
na.artId = artType->getId();
na.spellId = spellId;
na.pos = pos;
if(pos == ArtifactPosition::FIRST_AVAILABLE)
{
if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
na.pos = ArtifactUtils::getArtAnyPosition(h, artType->getId());
if(!artType->canBePutAt(h, na.pos))
COMPLAIN_RET("Cannot put artifact in that slot!");
}
else if(ArtifactUtils::isSlotBackpack(pos))
@ -3774,18 +3804,18 @@ bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact
{
COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
}
sendAndApply(&na);
return true;
}
auto * newArtInst = new CArtifactInstance();
newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos)
{
return giveHeroNewArtifact(h, artId.toArtifact(), SpellID::NONE, pos);
}
NewArtifact na;
na.art = newArtInst;
sendAndApply(&na); // -> updates newArtInst!!!
if(putArtifact(ArtifactLocation(h->id, pos), newArtInst, false))
return true;
else
return false;
bool CGameHandler::giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos)
{
return giveHeroNewArtifact(h, ArtifactID(ArtifactID::SPELL_SCROLL).toArtifact(), spellId, pos);
}
void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
@ -3829,7 +3859,7 @@ bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
{
if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
if (dynamic_cast<const PlayerMessage *>(pack) != nullptr)
return false;
auto query = queries->topQuery(player);
@ -3851,7 +3881,7 @@ void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
//If the object is being visited, there must be a matching query
for (const auto &query : queries->allQueries())
{
if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
if (auto someVistQuery = std::dynamic_pointer_cast<MapObjectVisitQuery>(query))
{
if (someVistQuery->visitedObject == object)
{
@ -3915,7 +3945,7 @@ const CGHeroInstance * CGameHandler::getVisitingHero(const CGObjectInstance *obj
for(const auto & query : queries->allQueries())
{
auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(query);
auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
if (visit && visit->visitedObject == obj)
return visit->visitingHero;
}
@ -3928,7 +3958,7 @@ const CGObjectInstance * CGameHandler::getVisitingObject(const CGHeroInstance *h
for(const auto & query : queries->allQueries())
{
auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(query);
auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
if (visit && visit->visitingHero == hero)
return visit->visitedObject;
}
@ -3945,7 +3975,7 @@ bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, con
// visitation query is covered by other query that must be answered first
if (auto topQuery = queries->topQuery(hero->getOwner()))
if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
if (auto visit = std::dynamic_pointer_cast<const VisitQuery>(topQuery))
return !(visit->visitedObject == obj && visit->visitingHero == hero);
return true;

View File

@ -113,7 +113,7 @@ public:
void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs=false) override;
void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
void showBlockingDialog(BlockingDialog *iw) override;
void showBlockingDialog(const IObjectInterface * caller, BlockingDialog *iw) override;
void showTeleportDialog(TeleportDialog *iw) override;
void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override;
@ -133,7 +133,9 @@ public:
void removeAfterVisit(const CGObjectInstance *object) override;
bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos = ArtifactPosition::FIRST_AVAILABLE) override;
bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, const SpellID & spellId, const ArtifactPosition & pos);
bool giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos) override;
bool giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos) override;
bool putArtifact(const ArtifactLocation & al, const CArtifactInstance * art, std::optional<bool> askAssemble) override;
void removeArtifact(const ArtifactLocation &al) override;
void removeArtifact(const ObjectInstanceID & srcId, const std::vector<ArtifactPosition> & slotsPack);
@ -214,7 +216,7 @@ public:
bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level, PlayerColor player);
bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
bool triggerTownSpecialBuildingAction(ObjectInstanceID tid, BuildingSubID::EBuildingSubID sid);
bool visitTownBuilding(ObjectInstanceID tid, BuildingID bid);
bool razeStructure(ObjectInstanceID tid, BuildingID bid);
bool disbandCreature( ObjectInstanceID id, SlotID pos );
bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
@ -232,7 +234,7 @@ public:
bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
void objectVisitEnded(const CObjectVisitQuery &query);
void objectVisitEnded(const CGHeroInstance *h, PlayerColor player);
bool dig(const CGHeroInstance *h);
void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);

View File

@ -9,6 +9,7 @@ set(vcmiservercommon_SRCS
queries/BattleQueries.cpp
queries/CQuery.cpp
queries/MapQueries.cpp
queries/VisitQueries.cpp
queries/QueriesProcessor.cpp
processors/HeroPoolProcessor.cpp
@ -36,6 +37,7 @@ set(vcmiservercommon_HEADERS
queries/BattleQueries.h
queries/CQuery.h
queries/MapQueries.h
queries/VisitQueries.h
queries/QueriesProcessor.h
processors/HeroPoolProcessor.h

View File

@ -27,7 +27,6 @@
#include "../lib/battle/Unit.h"
#include "../lib/spells/CSpellHandler.h"
#include "../lib/spells/ISpellMechanics.h"
#include "../lib/serializer/Cast.h"
void ApplyGhNetPackVisitor::visitSaveGame(SaveGame & pack)
{
@ -139,12 +138,12 @@ void ApplyGhNetPackVisitor::visitBuildStructure(BuildStructure & pack)
result = gh.buildStructure(pack.tid, pack.bid);
}
void ApplyGhNetPackVisitor::visitTriggerTownSpecialBuildingAction(TriggerTownSpecialBuildingAction & pack)
void ApplyGhNetPackVisitor::visitVisitTownBuilding(VisitTownBuilding & pack)
{
gh.throwIfWrongOwner(&pack, pack.tid);
gh.throwIfPlayerNotActive(&pack);
result = gh.triggerTownSpecialBuildingAction(pack.tid, pack.sid);
result = gh.visitTownBuilding(pack.tid, pack.bid);
}
void ApplyGhNetPackVisitor::visitRecruitCreatures(RecruitCreatures & pack)

View File

@ -41,7 +41,7 @@ public:
void visitBulkSmartSplitStack(BulkSmartSplitStack & pack) override;
void visitDisbandCreature(DisbandCreature & pack) override;
void visitBuildStructure(BuildStructure & pack) override;
void visitTriggerTownSpecialBuildingAction(TriggerTownSpecialBuildingAction & pack) override;
void visitVisitTownBuilding(VisitTownBuilding & pack) override;
void visitRecruitCreatures(RecruitCreatures & pack) override;
void visitUpgradeCreature(UpgradeCreature & pack) override;
void visitGarrisonHeroSwap(GarrisonHeroSwap & pack) override;

View File

@ -27,7 +27,6 @@
#include "../../lib/mapObjects/CGTownInstance.h"
#include "../../lib/networkPacks/PacksForClientBattle.h"
#include "../../lib/networkPacks/PacksForClient.h"
#include "../../lib/serializer/Cast.h"
#include "../../lib/spells/CSpellHandler.h"
#include <vstd/RNG.h>
@ -81,7 +80,7 @@ CasualtiesAfterBattle::CasualtiesAfterBattle(const CBattleInfoCallback & battle,
else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
{
logGlobal->debug("War machine has been destroyed");
auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
auto hero = dynamic_cast<const CGHeroInstance*> (army);
if (hero)
removedWarMachines.push_back (ArtifactLocation(hero->id, hero->getArtPos(warMachine, true)));
else

View File

@ -29,6 +29,7 @@
#include "../../lib/networkPacks/PacksForClient.h"
#include "../../lib/networkPacks/StackLocation.h"
#include "../../lib/serializer/Connection.h"
#include "../../lib/spells/CSpellHandler.h"
#include "../lib/VCMIDirs.h"
PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
@ -343,7 +344,7 @@ void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroIns
///Give hero spellbook
if (!hero->hasSpellbook())
gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
gameHandler->giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
///Give all spells with bonus (to allow banned spells)
GiveBonus giveBonus(GiveBonus::ETarget::OBJECT);
@ -421,11 +422,11 @@ void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroI
return;
if (!hero->getArt(ArtifactPosition::MACH1))
gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::BALLISTA).toArtifact(), ArtifactPosition::MACH1);
gameHandler->giveHeroNewArtifact(hero, ArtifactID::BALLISTA, ArtifactPosition::MACH1);
if (!hero->getArt(ArtifactPosition::MACH2))
gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::AMMO_CART).toArtifact(), ArtifactPosition::MACH2);
gameHandler->giveHeroNewArtifact(hero, ArtifactID::AMMO_CART, ArtifactPosition::MACH2);
if (!hero->getArt(ArtifactPosition::MACH3))
gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::FIRST_AID_TENT).toArtifact(), ArtifactPosition::MACH3);
gameHandler->giveHeroNewArtifact(hero, ArtifactID::FIRST_AID_TENT, ArtifactPosition::MACH3);
}
void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
@ -439,7 +440,7 @@ void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHero
{
auto artID = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "artifact", word, false);
if(artID && VLC->arth->objects[*artID])
gameHandler->giveHeroNewArtifact(hero, ArtifactID(*artID).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
gameHandler->giveHeroNewArtifact(hero, ArtifactID(*artID), ArtifactPosition::FIRST_AVAILABLE);
}
}
else
@ -447,11 +448,23 @@ void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHero
for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
{
if(VLC->arth->objects[g]->canBePutAt(hero))
gameHandler->giveHeroNewArtifact(hero, ArtifactID(g).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
gameHandler->giveHeroNewArtifact(hero, ArtifactID(g), ArtifactPosition::FIRST_AVAILABLE);
}
}
}
void PlayerMessageProcessor::cheatGiveScrolls(PlayerColor player, const CGHeroInstance * hero)
{
if(!hero)
return;
for(const auto & spell : VLC->spellh->objects)
if(gameHandler->gameState()->isAllowed(spell->getId()) && !spell->isSpecial())
{
gameHandler->giveHeroNewScroll(hero, spell->getId(), ArtifactPosition::FIRST_AVAILABLE);
}
}
void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
{
if (!hero)
@ -675,7 +688,8 @@ bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerCo
"vcmiolorin", "vcmiexp",
"vcmiluck", "nwcfollowthewhiterabbit",
"vcmimorale", "nwcmorpheus",
"vcmigod", "nwctheone"
"vcmigod", "nwctheone",
"vcmiscrolls"
};
if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
@ -752,6 +766,7 @@ void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, Pla
const auto & doCheatRevealPuzzle = [&]() { cheatPuzzleReveal(player); };
const auto & doCheatMaxLuck = [&]() { cheatMaxLuck(player, hero); };
const auto & doCheatMaxMorale = [&]() { cheatMaxMorale(player, hero); };
const auto & doCheatGiveScrolls = [&]() { cheatGiveScrolls(player, hero); };
const auto & doCheatTheOne = [&]()
{
if(!hero)
@ -820,6 +835,7 @@ void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, Pla
{"nwcmorpheus", doCheatMaxMorale },
{"vcmigod", doCheatTheOne },
{"nwctheone", doCheatTheOne },
{"vcmiscrolls", doCheatGiveScrolls },
};
assert(callbacks.count(cheatName));

View File

@ -46,6 +46,7 @@ class PlayerMessageProcessor
void cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words);
void cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero);
void cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words);
void cheatGiveScrolls(PlayerColor player, const CGHeroInstance * hero);
void cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words);
void cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words);
void cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words);

View File

@ -21,14 +21,13 @@
#include "../../lib/mapObjects/CGObjectInstance.h"
#include "../../lib/mapObjects/CGTownInstance.h"
#include "../../lib/networkPacks/PacksForServer.h"
#include "../../lib/serializer/Cast.h"
void CBattleQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CBattleQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
assert(result);
if(result)
objectVisit.visitedObject->battleFinished(objectVisit.visitingHero, *result);
visitedObject->battleFinished(visitingHero, *result);
}
CBattleQuery::CBattleQuery(CGameHandler * owner, const IBattleInfo * bi):
@ -51,10 +50,10 @@ CBattleQuery::CBattleQuery(CGameHandler * owner):
bool CBattleQuery::blocksPack(const CPack * pack) const
{
if(dynamic_ptr_cast<MakeAction>(pack) != nullptr)
if(dynamic_cast<const MakeAction*>(pack) != nullptr)
return false;
if(dynamic_ptr_cast<GamePause>(pack) != nullptr)
if(dynamic_cast<const GamePause*>(pack) != nullptr)
return false;
return true;

View File

@ -29,7 +29,7 @@ public:
CBattleQuery(CGameHandler * owner);
CBattleQuery(CGameHandler * owner, const IBattleInfo * Bi); //TODO
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
bool blocksPack(const CPack *pack) const override;
void onRemoval(PlayerColor color) override;
void onExposure(QueryPtr topQuery) override;

View File

@ -14,7 +14,6 @@
#include "../CGameHandler.h"
#include "../../lib/serializer/Cast.h"
#include "../../lib/networkPacks/PacksForServer.h"
std::ostream & operator<<(std::ostream & out, const CQuery & query)
@ -87,7 +86,7 @@ bool CQuery::blocksPack(const CPack * pack) const
return false;
}
void CQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
}
@ -116,7 +115,7 @@ void CQuery::setReply(std::optional<int32_t> reply)
bool CQuery::blockAllButReply(const CPack * pack) const
{
//We accept only query replies from correct player
if(auto reply = dynamic_ptr_cast<QueryReply>(pack))
if(auto reply = dynamic_cast<const QueryReply*>(pack))
return !vstd::contains(players, reply->player);
return true;

View File

@ -14,6 +14,8 @@
VCMI_LIB_NAMESPACE_BEGIN
struct CPack;
class CGObjectInstance;
class CGHeroInstance;
VCMI_LIB_NAMESPACE_END
@ -40,18 +42,29 @@ public:
CQuery(CGameHandler * gh);
virtual bool blocksPack(const CPack *pack) const; //query can block attempting actions by player. Eg. he can't move hero during the battle.
/// query can block attempting actions by player. Eg. he can't move hero during the battle.
virtual bool blocksPack(const CPack *pack) const;
virtual bool endsByPlayerAnswer() const; //query is removed after player gives answer (like dialogs)
virtual void onAdding(PlayerColor color); //called just before query is pushed on stack
virtual void onAdded(PlayerColor color); //called right after query is pushed on stack
virtual void onRemoval(PlayerColor color); //called after query is removed from stack
virtual void onExposure(QueryPtr topQuery);//called when query immediately above is removed and this is exposed (becomes top)
virtual std::string toString() const;
/// query is removed after player gives answer (like dialogs)
virtual bool endsByPlayerAnswer() const;
virtual void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const;
/// called just before query is pushed on stack
virtual void onAdding(PlayerColor color);
/// called right after query is pushed on stack
virtual void onAdded(PlayerColor color);
/// called after query is removed from stack
virtual void onRemoval(PlayerColor color);
/// called when query immediately above is removed and this is exposed (becomes top)
virtual void onExposure(QueryPtr topQuery);
/// called when this query is being removed and must report its result to currently visited object
virtual void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const;
virtual void setReply(std::optional<int32_t> reply);
virtual std::string toString() const;
virtual ~CQuery();
protected:

View File

@ -13,10 +13,9 @@
#include "QueriesProcessor.h"
#include "../CGameHandler.h"
#include "../TurnTimerHandler.h"
#include "../../lib/mapObjects/MiscObjects.h"
#include "../../lib/mapObjects/CGHeroInstance.h"
#include "../../lib/mapObjects/MiscObjects.h"
#include "../../lib/networkPacks/PacksForServer.h"
#include "../../lib/serializer/Cast.h"
TimerPauseQuery::TimerPauseQuery(CGameHandler * owner, PlayerColor player):
CQuery(owner)
@ -44,41 +43,9 @@ bool TimerPauseQuery::endsByPlayerAnswer() const
return true;
}
CObjectVisitQuery::CObjectVisitQuery(CGameHandler * owner, const CGObjectInstance * Obj, const CGHeroInstance * Hero, int3 Tile):
CQuery(owner), visitedObject(Obj), visitingHero(Hero), tile(Tile), removeObjectAfterVisit(false)
void CGarrisonDialogQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
addPlayer(Hero->tempOwner);
}
bool CObjectVisitQuery::blocksPack(const CPack *pack) const
{
//During the visit itself ALL actions are blocked.
//(However, the visit may trigger a query above that'll pass some.)
return true;
}
void CObjectVisitQuery::onRemoval(PlayerColor color)
{
gh->objectVisitEnded(*this);
//TODO or should it be destructor?
//Can object visit affect 2 players and what would be desired behavior?
if(removeObjectAfterVisit)
gh->removeObject(visitedObject, color);
}
void CObjectVisitQuery::onExposure(QueryPtr topQuery)
{
//Object may have been removed and deleted.
if(gh->isValidObject(visitedObject))
topQuery->notifyObjectAboutRemoval(*this);
owner->popIfTop(*this);
}
void CGarrisonDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
{
objectVisit.visitedObject->garrisonDialogClosed(objectVisit.visitingHero);
visitedObject->garrisonDialogClosed(visitingHero);
}
CGarrisonDialogQuery::CGarrisonDialogQuery(CGameHandler * owner, const CArmedInstance * up, const CArmedInstance * down):
@ -97,22 +64,22 @@ bool CGarrisonDialogQuery::blocksPack(const CPack * pack) const
ourIds.insert(this->exchangingArmies[0]->id);
ourIds.insert(this->exchangingArmies[1]->id);
if(auto stacks = dynamic_ptr_cast<ArrangeStacks>(pack))
if(auto stacks = dynamic_cast<const ArrangeStacks*>(pack))
return !vstd::contains(ourIds, stacks->id1) || !vstd::contains(ourIds, stacks->id2);
if(auto stacks = dynamic_ptr_cast<BulkSplitStack>(pack))
if(auto stacks = dynamic_cast<const BulkSplitStack*>(pack))
return !vstd::contains(ourIds, stacks->srcOwner);
if(auto stacks = dynamic_ptr_cast<BulkMergeStacks>(pack))
if(auto stacks = dynamic_cast<const BulkMergeStacks*>(pack))
return !vstd::contains(ourIds, stacks->srcOwner);
if(auto stacks = dynamic_ptr_cast<BulkSmartSplitStack>(pack))
if(auto stacks = dynamic_cast<const BulkSmartSplitStack*>(pack))
return !vstd::contains(ourIds, stacks->srcOwner);
if(auto stacks = dynamic_ptr_cast<BulkMoveArmy>(pack))
if(auto stacks = dynamic_cast<const BulkMoveArmy*>(pack))
return !vstd::contains(ourIds, stacks->srcArmy) || !vstd::contains(ourIds, stacks->destArmy);
if(auto arts = dynamic_ptr_cast<ExchangeArtifacts>(pack))
if(auto arts = dynamic_cast<const ExchangeArtifacts*>(pack))
{
if(auto id1 = arts->src.artHolder)
if(!vstd::contains(ourIds, id1))
@ -123,41 +90,42 @@ bool CGarrisonDialogQuery::blocksPack(const CPack * pack) const
return true;
return false;
}
if(auto dismiss = dynamic_ptr_cast<DisbandCreature>(pack))
if(auto dismiss = dynamic_cast<const DisbandCreature*>(pack))
return !vstd::contains(ourIds, dismiss->id);
if(auto arts = dynamic_ptr_cast<BulkExchangeArtifacts>(pack))
if(auto arts = dynamic_cast<const BulkExchangeArtifacts*>(pack))
return !vstd::contains(ourIds, arts->srcHero) || !vstd::contains(ourIds, arts->dstHero);
if(auto arts = dynamic_ptr_cast<ManageBackpackArtifacts>(pack))
if(auto arts = dynamic_cast<const ManageBackpackArtifacts*>(pack))
return !vstd::contains(ourIds, arts->artHolder);
if(auto art = dynamic_ptr_cast<EraseArtifactByClient>(pack))
if(auto art = dynamic_cast<const EraseArtifactByClient*>(pack))
{
if(auto id = art->al.artHolder)
return !vstd::contains(ourIds, id);
}
if(auto dismiss = dynamic_ptr_cast<AssembleArtifacts>(pack))
if(auto dismiss = dynamic_cast<const AssembleArtifacts*>(pack))
return !vstd::contains(ourIds, dismiss->heroID);
if(auto upgrade = dynamic_ptr_cast<UpgradeCreature>(pack))
if(auto upgrade = dynamic_cast<const UpgradeCreature*>(pack))
return !vstd::contains(ourIds, upgrade->id);
if(auto formation = dynamic_ptr_cast<SetFormation>(pack))
if(auto formation = dynamic_cast<const SetFormation*>(pack))
return !vstd::contains(ourIds, formation->hid);
return CDialogQuery::blocksPack(pack);
}
void CBlockingDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CBlockingDialogQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
assert(answer);
objectVisit.visitedObject->blockingDialogAnswered(objectVisit.visitingHero, *answer);
caller->blockingDialogAnswered(visitingHero, *answer);
}
CBlockingDialogQuery::CBlockingDialogQuery(CGameHandler * owner, const BlockingDialog & bd):
CDialogQuery(owner)
CBlockingDialogQuery::CBlockingDialogQuery(CGameHandler * owner, const IObjectInterface * caller, const BlockingDialog & bd):
CDialogQuery(owner),
caller(caller)
{
this->bd = bd;
addPlayer(bd.player);
@ -179,56 +147,55 @@ bool OpenWindowQuery::blocksPack(const CPack *pack) const
{
if (mode == EOpenWindowMode::RECRUITMENT_FIRST || mode == EOpenWindowMode::RECRUITMENT_ALL)
{
if(dynamic_ptr_cast<RecruitCreatures>(pack) != nullptr)
if(dynamic_cast<const RecruitCreatures*>(pack) != nullptr)
return false;
// If hero has no free slots, he might get some stacks merged automatically
if(dynamic_ptr_cast<ArrangeStacks>(pack) != nullptr)
if(dynamic_cast<const ArrangeStacks*>(pack) != nullptr)
return false;
}
if (mode == EOpenWindowMode::TAVERN_WINDOW)
{
if(dynamic_ptr_cast<HireHero>(pack) != nullptr)
if(dynamic_cast<const HireHero*>(pack) != nullptr)
return false;
}
if (mode == EOpenWindowMode::UNIVERSITY_WINDOW)
{
if(dynamic_ptr_cast<TradeOnMarketplace>(pack) != nullptr)
if(dynamic_cast<const TradeOnMarketplace*>(pack) != nullptr)
return false;
}
if (mode == EOpenWindowMode::MARKET_WINDOW)
{
if(dynamic_ptr_cast<ExchangeArtifacts>(pack) != nullptr)
if(dynamic_cast<const ExchangeArtifacts*>(pack) != nullptr)
return false;
if(dynamic_ptr_cast<BulkExchangeArtifacts>(pack) != nullptr)
if(dynamic_cast<const BulkExchangeArtifacts*>(pack) != nullptr)
return false;
if(dynamic_ptr_cast<ManageBackpackArtifacts>(pack) != nullptr)
if(dynamic_cast<const ManageBackpackArtifacts*>(pack) != nullptr)
return false;
if(dynamic_ptr_cast<AssembleArtifacts>(pack))
if(dynamic_cast<const AssembleArtifacts*>(pack))
return false;
if(dynamic_ptr_cast<EraseArtifactByClient>(pack))
if(dynamic_cast<const EraseArtifactByClient*>(pack))
return false;
if(dynamic_ptr_cast<TradeOnMarketplace>(pack) != nullptr)
if(dynamic_cast<const TradeOnMarketplace*>(pack) != nullptr)
return false;
}
return CDialogQuery::blocksPack(pack);
}
void CTeleportDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CTeleportDialogQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
// do not change to dynamic_ptr_cast - SIGSEGV!
auto obj = dynamic_cast<const CGTeleport*>(objectVisit.visitedObject);
auto obj = dynamic_cast<const CGTeleport*>(visitedObject);
if(obj)
obj->teleportDialogAnswered(objectVisit.visitingHero, *answer, td.exits);
obj->teleportDialogAnswered(visitingHero, *answer, td.exits);
else
logGlobal->error("Invalid instance in teleport query");
}
@ -254,9 +221,9 @@ void CHeroLevelUpDialogQuery::onRemoval(PlayerColor color)
gh->levelUpHero(hero, hlu.skills[*answer]);
}
void CHeroLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CHeroLevelUpDialogQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
objectVisit.visitedObject->heroLevelUpDone(objectVisit.visitingHero);
visitedObject->heroLevelUpDone(visitingHero);
}
CCommanderLevelUpDialogQuery::CCommanderLevelUpDialogQuery(CGameHandler * owner, const CommanderLevelUp & Clu, const CGHeroInstance * Hero):
@ -273,9 +240,9 @@ void CCommanderLevelUpDialogQuery::onRemoval(PlayerColor color)
gh->levelUpCommander(hero->commander, clu.skills[*answer]);
}
void CCommanderLevelUpDialogQuery::notifyObjectAboutRemoval(const CObjectVisitQuery & objectVisit) const
void CCommanderLevelUpDialogQuery::notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const
{
objectVisit.visitedObject->heroLevelUpDone(objectVisit.visitingHero);
visitedObject->heroLevelUpDone(visitingHero);
}
CHeroMovementQuery::CHeroMovementQuery(CGameHandler * owner, const TryMoveHero & Tmh, const CGHeroInstance * Hero, bool VisitDestAfterVictory):

View File

@ -15,12 +15,9 @@
VCMI_LIB_NAMESPACE_BEGIN
class CGHeroInstance;
class CGObjectInstance;
class int3;
class IObjectInterface;
VCMI_LIB_NAMESPACE_END
class TurnTimerHandler;
//Created when player starts turn or when player puts game on [ause
//Removed when player accepts a turn or continur play
class TimerPauseQuery : public CQuery
@ -34,23 +31,6 @@ public:
bool endsByPlayerAnswer() const override;
};
//Created when hero visits object.
//Removed when query above is resolved (or immediately after visit if no queries were created)
class CObjectVisitQuery : public CQuery
{
public:
const CGObjectInstance *visitedObject;
const CGHeroInstance *visitingHero;
int3 tile; //may be different than hero pos -> eg. visit via teleport
bool removeObjectAfterVisit;
CObjectVisitQuery(CGameHandler * owner, const CGObjectInstance *Obj, const CGHeroInstance *Hero, int3 Tile);
bool blocksPack(const CPack *pack) const override;
void onRemoval(PlayerColor color) override;
void onExposure(QueryPtr topQuery) override;
};
//Created when hero attempts move and something happens
//(not necessarily position change, could be just an object interaction).
class CHeroMovementQuery : public CQuery
@ -73,7 +53,7 @@ public:
std::array<const CArmedInstance *,2> exchangingArmies;
CGarrisonDialogQuery(CGameHandler * owner, const CArmedInstance *up, const CArmedInstance *down);
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
bool blocksPack(const CPack *pack) const override;
};
@ -81,11 +61,12 @@ public:
class CBlockingDialogQuery : public CDialogQuery
{
public:
const IObjectInterface * caller;
BlockingDialog bd; //copy of pack... debug purposes
CBlockingDialogQuery(CGameHandler * owner, const BlockingDialog &bd);
CBlockingDialogQuery(CGameHandler * owner, const IObjectInterface * caller, const BlockingDialog &bd);
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
};
class OpenWindowQuery : public CDialogQuery
@ -105,7 +86,7 @@ public:
CTeleportDialogQuery(CGameHandler * owner, const TeleportDialog &td);
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
};
class CHeroLevelUpDialogQuery : public CDialogQuery
@ -114,7 +95,7 @@ public:
CHeroLevelUpDialogQuery(CGameHandler * owner, const HeroLevelUp &Hlu, const CGHeroInstance * Hero);
void onRemoval(PlayerColor color) override;
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
HeroLevelUp hlu;
const CGHeroInstance * hero;
@ -126,7 +107,7 @@ public:
CCommanderLevelUpDialogQuery(CGameHandler * owner, const CommanderLevelUp &Clu, const CGHeroInstance * Hero);
void onRemoval(PlayerColor color) override;
void notifyObjectAboutRemoval(const CObjectVisitQuery &objectVisit) const override;
void notifyObjectAboutRemoval(const CGObjectInstance * visitedObject, const CGHeroInstance * visitingHero) const override;
CommanderLevelUp clu;
const CGHeroInstance * hero;

View File

@ -0,0 +1,66 @@
/*
* VisitQueries.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "VisitQueries.h"
#include "../../lib/mapObjects/CGHeroInstance.h"
#include "../CGameHandler.h"
#include "QueriesProcessor.h"
VisitQuery::VisitQuery(CGameHandler * owner, const CGObjectInstance * Obj, const CGHeroInstance * Hero)
: CQuery(owner)
, visitedObject(Obj)
, visitingHero(Hero)
{
addPlayer(Hero->tempOwner);
}
bool VisitQuery::blocksPack(const CPack * pack) const
{
//During the visit itself ALL actions are blocked.
//(However, the visit may trigger a query above that'll pass some.)
return true;
}
void VisitQuery::onExposure(QueryPtr topQuery)
{
//Object may have been removed and deleted.
if(gh->isValidObject(visitedObject))
topQuery->notifyObjectAboutRemoval(visitedObject, visitingHero);
owner->popIfTop(*this);
}
MapObjectVisitQuery::MapObjectVisitQuery(CGameHandler * owner, const CGObjectInstance * Obj, const CGHeroInstance * Hero)
: VisitQuery(owner, Obj, Hero)
, removeObjectAfterVisit(false)
{
}
void MapObjectVisitQuery::onRemoval(PlayerColor color)
{
gh->objectVisitEnded(visitingHero, players.front());
//TODO or should it be destructor?
//Can object visit affect 2 players and what would be desired behavior?
if(removeObjectAfterVisit)
gh->removeObject(visitedObject, color);
}
TownBuildingVisitQuery::TownBuildingVisitQuery(CGameHandler * owner, const CGObjectInstance * Obj, const CGHeroInstance * Hero, BuildingID buildingToVisit)
: VisitQuery(owner, Obj, Hero)
, visitedBuilding(buildingToVisit)
{
}
void TownBuildingVisitQuery::onRemoval(PlayerColor color)
{
}

View File

@ -0,0 +1,47 @@
/*
* VisitQueries.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include "CQuery.h"
//Created when hero visits object.
//Removed when query above is resolved (or immediately after visit if no queries were created)
class VisitQuery : public CQuery
{
protected:
VisitQuery(CGameHandler * owner, const CGObjectInstance *Obj, const CGHeroInstance *Hero);
public:
const CGObjectInstance *visitedObject;
const CGHeroInstance *visitingHero;
bool blocksPack(const CPack *pack) const final;
void onExposure(QueryPtr topQuery) final;
};
class MapObjectVisitQuery final : public VisitQuery
{
public:
bool removeObjectAfterVisit;
MapObjectVisitQuery(CGameHandler * owner, const CGObjectInstance *Obj, const CGHeroInstance *Hero);
void onRemoval(PlayerColor color) final;
};
class TownBuildingVisitQuery final : public VisitQuery
{
public:
BuildingID visitedBuilding;
TownBuildingVisitQuery(CGameHandler * owner, const CGObjectInstance *Obj, const CGHeroInstance *Hero, BuildingID buildingToVisit);
void onRemoval(PlayerColor color) final;
};

View File

@ -230,17 +230,11 @@ TEST_F(CGameStateTest, DISABLED_issue2765)
ASSERT_NE(attacker->tempOwner, defender->tempOwner);
{
CArtifactInstance * a = new CArtifactInstance();
a->artType = const_cast<CArtifact *>(ArtifactID(ArtifactID::BALLISTA).toArtifact());
NewArtifact na;
na.art = a;
na.artHolder = defender->id;
na.artId = ArtifactID::BALLISTA;
na.pos = ArtifactPosition::MACH1;
gameCallback->sendAndApply(&na);
PutArtifact pack;
pack.al = ArtifactLocation(defender->id, ArtifactPosition::MACH1);
pack.art = a;
gameCallback->sendAndApply(&pack);
}
startTestBattle(attacker, defender);
@ -324,17 +318,11 @@ TEST_F(CGameStateTest, DISABLED_battleResurrection)
attacker->mana = attacker->manaLimit();
{
CArtifactInstance * a = new CArtifactInstance();
a->artType = const_cast<CArtifact *>(ArtifactID(ArtifactID::SPELLBOOK).toArtifact());
NewArtifact na;
na.art = a;
na.artHolder = attacker->id;
na.artId = ArtifactID::SPELLBOOK;
na.pos = ArtifactPosition::SPELLBOOK;
gameCallback->sendAndApply(&na);
PutArtifact pack;
pack.al = ArtifactLocation(attacker->id, ArtifactPosition::SPELLBOOK);
pack.art = a;
gameCallback->sendAndApply(&pack);
}
startTestBattle(attacker, defender);

View File

@ -50,7 +50,7 @@ public:
void giveExperience(const CGHeroInstance * hero, TExpType val) override {}
void changePrimSkill(const CGHeroInstance * hero, PrimarySkill which, si64 val, bool abs=false) override {}
void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override {}
void showBlockingDialog(BlockingDialog *iw) override {}
void showBlockingDialog(const IObjectInterface * caller, BlockingDialog *iw) override {}
void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override {} //cb will be called when player closes garrison window
void showTeleportDialog(TeleportDialog *iw) override {}
void showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery) override {};
@ -70,7 +70,8 @@ public:
void removeAfterVisit(const CGObjectInstance *object) override {} //object will be destroyed when interaction is over. Do not call when interaction is not ongoing!
bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos) override {return false;}
bool giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos) override {return false;}
bool giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos) override {return false;}
bool putArtifact(const ArtifactLocation & al, const CArtifactInstance * art, std::optional<bool> askAssemble) override {return false;}
void removeArtifact(const ArtifactLocation &al) override {}
bool moveArtifact(const PlayerColor & player, const ArtifactLocation & al1, const ArtifactLocation & al2) override {return false;}