1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-04 09:42:40 +02:00
vcmi/lib/mapping/CMapOperation.cpp

686 lines
17 KiB
C++
Raw Normal View History

2022-09-17 13:04:01 +02:00
/*
* CMapOperation.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 "CMapOperation.h"
#include "../VCMI_Lib.h"
#include "../TerrainHandler.h"
2022-09-17 13:04:01 +02:00
#include "CMap.h"
#include "MapEditUtils.h"
VCMI_LIB_NAMESPACE_BEGIN
2022-09-17 13:04:01 +02:00
CMapOperation::CMapOperation(CMap* map) : map(map)
{
}
std::string CMapOperation::getLabel() const
{
return "";
}
2023-02-11 18:30:06 +02:00
MapRect CMapOperation::extendTileAround(const int3 & centerPos) const
2022-09-17 13:04:01 +02:00
{
return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
}
MapRect CMapOperation::extendTileAroundSafely(const int3& centerPos) const
{
return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
}
CComposedOperation::CComposedOperation(CMap* map) : CMapOperation(map)
{
}
void CComposedOperation::execute()
{
for(auto & operation : operations)
{
operation->execute();
}
}
void CComposedOperation::undo()
{
//reverse order
for(auto operation = operations.rbegin(); operation != operations.rend(); operation++)
{
operation->get()->undo();
}
}
void CComposedOperation::redo()
{
for(auto & operation : operations)
{
operation->redo();
}
}
std::string CComposedOperation::getLabel() const
{
std::string ret = "Composed operation: ";
2023-02-11 18:30:06 +02:00
for(const auto & operation : operations)
2022-09-17 13:04:01 +02:00
{
ret.append(operation->getLabel() + ";");
}
return ret;
}
void CComposedOperation::addOperation(std::unique_ptr<CMapOperation>&& operation)
{
operations.push_back(std::move(operation));
}
2023-02-11 18:30:06 +02:00
CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, CTerrainSelection terrainSel, TerrainId terType, CRandomGenerator * gen):
2022-09-21 11:34:23 +02:00
CMapOperation(map),
2023-02-11 18:30:06 +02:00
terrainSel(std::move(terrainSel)),
2022-09-21 11:34:23 +02:00
terType(terType),
gen(gen)
2022-09-17 13:04:01 +02:00
{
}
void CDrawTerrainOperation::execute()
{
for(const auto & pos : terrainSel.getSelectedItems())
{
auto & tile = map->getTile(pos);
tile.terType = const_cast<TerrainType*>(VLC->terrainTypeHandler->getById(terType));
2022-09-17 13:04:01 +02:00
invalidateTerrainViews(pos);
}
updateTerrainTypes();
updateTerrainViews();
}
void CDrawTerrainOperation::undo()
{
//TODO
}
void CDrawTerrainOperation::redo()
{
//TODO
}
std::string CDrawTerrainOperation::getLabel() const
{
return "Draw Terrain";
}
void CDrawTerrainOperation::updateTerrainTypes()
{
auto positions = terrainSel.getSelectedItems();
while(!positions.empty())
{
const auto & centerPos = *(positions.begin());
auto centerTile = map->getTile(centerPos);
//logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
auto tiles = getInvalidTiles(centerPos);
auto updateTerrainType = [&](const int3& pos)
{
map->getTile(pos).terType = centerTile.terType;
positions.insert(pos);
invalidateTerrainViews(pos);
//logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
};
// Fill foreign invalid tiles
for(const auto & tile : tiles.foreignTiles)
{
updateTerrainType(tile);
}
tiles = getInvalidTiles(centerPos);
if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
{
// Blow up
auto rect = extendTileAroundSafely(centerPos);
std::set<int3> suitableTiles;
2023-02-11 18:30:06 +02:00
int invalidForeignTilesCnt = std::numeric_limits<int>::max();
int invalidNativeTilesCnt = 0;
2022-09-17 13:04:01 +02:00
bool centerPosValid = false;
rect.forEach([&](const int3& posToTest)
{
auto & terrainTile = map->getTile(posToTest);
if(centerTile.terType->getId() != terrainTile.terType->getId())
2022-09-17 13:04:01 +02:00
{
2023-02-11 18:30:06 +02:00
const auto * formerTerType = terrainTile.terType;
2022-09-17 13:04:01 +02:00
terrainTile.terType = centerTile.terType;
auto testTile = getInvalidTiles(posToTest);
2023-02-11 18:30:06 +02:00
int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : static_cast<int>(testTile.nativeTiles.size());
2022-09-17 13:04:01 +02:00
bool putSuitableTile = false;
bool addToSuitableTiles = false;
if(testTile.centerPosValid)
{
if(!centerPosValid)
{
centerPosValid = true;
putSuitableTile = true;
}
else
{
if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
{
putSuitableTile = true;
}
else
{
addToSuitableTiles = true;
}
}
}
else if(!centerPosValid)
{
if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
{
putSuitableTile = true;
}
else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
{
addToSuitableTiles = true;
}
}
if(putSuitableTile)
{
//if(!suitableTiles.empty())
//{
// logGlobal->debug("Clear suitables tiles.");
//}
invalidNativeTilesCnt = nativeTilesCntNorm;
invalidForeignTilesCnt = static_cast<int>(testTile.foreignTiles.size());
suitableTiles.clear();
addToSuitableTiles = true;
}
if(addToSuitableTiles)
{
suitableTiles.insert(posToTest);
}
terrainTile.terType = formerTerType;
}
});
if(suitableTiles.size() == 1)
{
updateTerrainType(*suitableTiles.begin());
}
else
{
static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0) };
2023-02-11 18:30:06 +02:00
for(const auto & direction : directions)
2022-09-17 13:04:01 +02:00
{
auto it = suitableTiles.find(centerPos + direction);
if (it != suitableTiles.end())
{
updateTerrainType(*it);
break;
}
}
}
}
else
{
// add invalid native tiles which are not in the positions list
for(const auto & nativeTile : tiles.nativeTiles)
{
if (positions.find(nativeTile) == positions.end())
{
positions.insert(nativeTile);
}
}
positions.erase(centerPos);
}
}
}
void CDrawTerrainOperation::updateTerrainViews()
{
for(const auto & pos : invalidatedTerViews)
{
const auto & patterns = VLC->terviewh->getTerrainViewPatterns(map->getTile(pos).terType->getId());
2022-09-17 13:04:01 +02:00
// Detect a pattern which fits best
int bestPattern = -1;
ValidationResult valRslt(false);
for(int k = 0; k < patterns.size(); ++k)
{
const auto & pattern = patterns[k];
//(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
valRslt = validateTerrainView(pos, &pattern);
if (valRslt.result)
{
bestPattern = k;
break;
}
}
//assert(bestPattern != -1);
if(bestPattern == -1)
{
// This shouldn't be the case
logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
continue;
}
// Get mapping
const TerrainViewPattern& pattern = patterns[bestPattern][valRslt.flip];
std::pair<int, int> mapping;
if(valRslt.transitionReplacement.empty())
{
mapping = pattern.mapping[0];
}
else
{
mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
}
// Set terrain view
auto & tile = map->getTile(pos);
if(!pattern.diffImages)
{
tile.terView = gen->nextInt(mapping.first, mapping.second);
tile.extTileFlags = valRslt.flip;
}
else
{
const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
int firstFrame = mapping.first + flip * framesPerRot;
tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
tile.extTileFlags = 0;
}
}
}
CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3& pos, const std::vector<TerrainViewPattern>* pattern, int recDepth) const
{
for(int flip = 0; flip < 4; ++flip)
{
auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
if(valRslt.result)
{
valRslt.flip = flip;
return valRslt;
}
}
return ValidationResult(false);
}
CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3& pos, const TerrainViewPattern& pattern, int recDepth) const
{
2023-02-11 18:30:06 +02:00
const auto * centerTerType = map->getTile(pos).terType;
2022-09-17 13:04:01 +02:00
int totalPoints = 0;
std::string transitionReplacement;
for(int i = 0; i < 9; ++i)
{
// The center, middle cell can be skipped
if(i == 4)
{
continue;
}
// Get terrain group of the current cell
int cx = pos.x + (i % 3) - 1;
int cy = pos.y + (i / 3) - 1;
int3 currentPos(cx, cy, pos.z);
bool isAlien = false;
2023-01-10 01:05:28 +02:00
const TerrainType * terType = nullptr;
2022-09-17 13:04:01 +02:00
if(!map->isInTheMap(currentPos))
{
// position is not in the map, so take the ter type from the neighbor tile
bool widthTooHigh = currentPos.x >= map->width;
bool widthTooLess = currentPos.x < 0;
bool heightTooHigh = currentPos.y >= map->height;
bool heightTooLess = currentPos.y < 0;
if((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
{
terType = centerTerType;
}
else if(widthTooHigh)
{
terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
}
else if(heightTooHigh)
{
terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
}
else if(widthTooLess)
{
terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
}
else if(heightTooLess)
{
terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
}
}
else
{
terType = map->getTile(currentPos).terType;
2022-09-21 11:34:23 +02:00
if(terType != centerTerType && (terType->isPassable() || centerTerType->isPassable()))
2022-09-17 13:04:01 +02:00
{
isAlien = true;
}
}
// Validate all rules per cell
int topPoints = -1;
2023-02-11 18:30:06 +02:00
for(const auto & elem : pattern.data[i])
2022-09-17 13:04:01 +02:00
{
TerrainViewPattern::WeightedRule rule = elem;
if(!rule.isStandardRule())
{
if(recDepth == 0 && map->isInTheMap(currentPos))
{
if(terType->getId() == centerTerType->getId())
2022-09-17 13:04:01 +02:00
{
2023-04-16 19:42:56 +02:00
const auto patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType->getId(), rule.name);
2022-09-17 13:04:01 +02:00
if(auto p = patternForRule)
{
2023-04-16 19:42:56 +02:00
auto rslt = validateTerrainView(currentPos, &(p->get()), 1);
2022-09-17 13:04:01 +02:00
if(rslt.result) topPoints = std::max(topPoints, rule.points);
}
}
continue;
}
else
{
rule.setNative();
}
}
auto applyValidationRslt = [&](bool rslt)
{
if(rslt)
{
topPoints = std::max(topPoints, rule.points);
}
};
// Validate cell with the ruleset of the pattern
2023-02-11 18:30:06 +02:00
bool nativeTestOk = false;
bool nativeTestStrongOk = false;
2022-09-17 13:04:01 +02:00
nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
if(centerTerType->getId() == ETerrainId::DIRT)
2022-09-17 13:04:01 +02:00
{
2022-09-21 11:34:23 +02:00
nativeTestOk = rule.isNativeRule() && !terType->isTransitionRequired();
2022-09-17 13:04:01 +02:00
bool sandTestOk = (rule.isSandRule() || rule.isTransition())
2022-09-21 11:34:23 +02:00
&& terType->isTransitionRequired();
2022-09-17 13:04:01 +02:00
applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
}
else if(centerTerType->getId() == ETerrainId::SAND)
2022-09-17 13:04:01 +02:00
{
applyValidationRslt(true);
}
2022-09-21 11:34:23 +02:00
else if(centerTerType->isTransitionRequired()) //water, rock and some special terrains require sand transition
2022-09-17 13:04:01 +02:00
{
bool sandTestOk = (rule.isSandRule() || rule.isTransition())
&& isAlien;
applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
}
else
{
bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
2022-09-21 11:34:23 +02:00
&& isAlien && !terType->isTransitionRequired();
2022-09-17 13:04:01 +02:00
bool sandTestOk = (rule.isSandRule() || rule.isTransition())
2022-09-21 11:34:23 +02:00
&& terType->isTransitionRequired();
2022-09-17 13:04:01 +02:00
if(transitionReplacement.empty() && rule.isTransition()
&& (dirtTestOk || sandTestOk))
{
transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
}
if(rule.isTransition())
{
applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
(sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
}
else
{
applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
}
}
}
if(topPoints == -1)
{
return ValidationResult(false);
}
else
{
totalPoints += topPoints;
}
}
if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
{
return ValidationResult(true, transitionReplacement);
}
else
{
return ValidationResult(false);
}
}
void CDrawTerrainOperation::invalidateTerrainViews(const int3& centerPos)
{
auto rect = extendTileAroundSafely(centerPos);
rect.forEach([&](const int3& pos)
{
invalidatedTerViews.insert(pos);
});
}
CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3& centerPos) const
{
//TODO: this is very expensive function for RMG, needs optimization
InvalidTiles tiles;
2023-02-11 18:30:06 +02:00
const auto * centerTerType = map->getTile(centerPos).terType;
2022-09-17 13:04:01 +02:00
auto rect = extendTileAround(centerPos);
rect.forEach([&](const int3& pos)
{
if(map->isInTheMap(pos))
{
2023-02-11 18:30:06 +02:00
auto * ptrConfig = VLC->terviewh;
const auto * terType = map->getTile(pos).terType;
2022-09-17 13:04:01 +02:00
auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
// Special validity check for rock & water
2022-09-21 11:34:23 +02:00
if(valid && (terType->isWater() || !terType->isPassable()))
2022-09-17 13:04:01 +02:00
{
static const std::string patternIds[] = { "s1", "s2" };
2023-02-11 18:30:06 +02:00
for(const auto & patternId : patternIds)
2022-09-17 13:04:01 +02:00
{
valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
if(!valid) break;
}
}
// Additional validity check for non rock OR water
2022-09-21 11:34:23 +02:00
else if(!valid && (terType->isLand() && terType->isPassable()))
2022-09-17 13:04:01 +02:00
{
static const std::string patternIds[] = { "n2", "n3" };
2023-02-11 18:30:06 +02:00
for(const auto & patternId : patternIds)
2022-09-17 13:04:01 +02:00
{
valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
if(valid) break;
}
}
if(!valid)
{
if(terType == centerTerType) tiles.nativeTiles.insert(pos);
else tiles.foreignTiles.insert(pos);
}
else if(centerPos == pos)
{
tiles.centerPosValid = true;
}
}
});
return tiles;
}
2023-02-11 18:30:06 +02:00
CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, std::string transitionReplacement)
: result(result)
, transitionReplacement(std::move(transitionReplacement))
, flip(0)
2022-09-17 13:04:01 +02:00
{
}
CClearTerrainOperation::CClearTerrainOperation(CMap* map, CRandomGenerator* gen) : CComposedOperation(map)
{
CTerrainSelection terrainSel(map);
terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
addOperation(std::make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainId::WATER, gen));
2022-09-17 13:04:01 +02:00
if(map->twoLevel)
{
terrainSel.clearSelection();
terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
addOperation(std::make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainId::ROCK, gen));
2022-09-17 13:04:01 +02:00
}
}
std::string CClearTerrainOperation::getLabel() const
{
return "Clear Terrain";
}
CInsertObjectOperation::CInsertObjectOperation(CMap* map, CGObjectInstance* obj)
: CMapOperation(map), obj(obj)
{
}
void CInsertObjectOperation::execute()
{
obj->id = ObjectInstanceID(map->objects.size());
do
{
map->setUniqueInstanceName(obj);
} while(vstd::contains(map->instanceNames, obj->instanceName));
map->addNewObject(obj);
}
void CInsertObjectOperation::undo()
{
map->removeObject(obj);
}
void CInsertObjectOperation::redo()
{
execute();
}
std::string CInsertObjectOperation::getLabel() const
{
return "Insert Object";
}
CMoveObjectOperation::CMoveObjectOperation(CMap* map, CGObjectInstance* obj, const int3& targetPosition)
: CMapOperation(map),
obj(obj),
initialPos(obj->pos),
targetPos(targetPosition)
{
}
void CMoveObjectOperation::execute()
{
map->moveObject(obj, targetPos);
}
void CMoveObjectOperation::undo()
{
map->moveObject(obj, initialPos);
}
void CMoveObjectOperation::redo()
{
execute();
}
std::string CMoveObjectOperation::getLabel() const
{
return "Move Object";
}
CRemoveObjectOperation::CRemoveObjectOperation(CMap* map, CGObjectInstance* obj)
: CMapOperation(map), obj(obj)
{
}
CRemoveObjectOperation::~CRemoveObjectOperation()
{
//when operation is destroyed and wasn't undone, the object is lost forever
if(!obj)
{
return;
}
//do not destroy an object that belongs to map
if(!vstd::contains(map->instanceNames, obj->instanceName))
{
delete obj;
obj = nullptr;
}
}
void CRemoveObjectOperation::execute()
{
map->removeObject(obj);
}
void CRemoveObjectOperation::undo()
{
try
{
//set new id, but do not rename object
2023-02-11 18:30:06 +02:00
obj->id = ObjectInstanceID(static_cast<si32>(map->objects.size()));
2022-09-17 13:04:01 +02:00
map->addNewObject(obj);
}
catch(const std::exception& e)
{
logGlobal->error(e.what());
}
}
void CRemoveObjectOperation::redo()
{
execute();
}
std::string CRemoveObjectOperation::getLabel() const
{
return "Remove Object";
}
VCMI_LIB_NAMESPACE_END