File: CMapOperation.cpp

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (695 lines) | stat: -rw-r--r-- 17,646 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/*
 * 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"
#include "../mapObjects/CGObjectInstance.h"
#include "CMap.h"
#include "MapEditUtils.h"

#include <vstd/RNG.h>

VCMI_LIB_NAMESPACE_BEGIN

CMapOperation::CMapOperation(CMap* map) : map(map)
{

}

std::string CMapOperation::getLabel() const
{
	return "";
}

MapRect CMapOperation::extendTileAround(const int3 & centerPos) const
{
	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()
{
	// FIXME: Only reindex objects at the end of composite operation

	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: ";
	for(const auto & operation : operations)
	{
		ret.append(operation->getLabel() + ";");
	}
	return ret;
}

void CComposedOperation::addOperation(std::unique_ptr<CMapOperation>&& operation)
{
	operations.push_back(std::move(operation));
}

CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, CTerrainSelection terrainSel, TerrainId terType, int decorationsPercentage, vstd::RNG * gen):
	CMapOperation(map),
	terrainSel(std::move(terrainSel)),
	terType(terType),
	decorationsPercentage(decorationsPercentage),
	gen(gen)
{

}

void CDrawTerrainOperation::execute()
{
	for(const auto & pos : terrainSel.getSelectedItems())
	{
		auto & tile = map->getTile(pos);
		tile.terrainType = terType;
		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).terrainType = centerTile.terrainType;
			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;
			int invalidForeignTilesCnt = std::numeric_limits<int>::max();
			int invalidNativeTilesCnt = 0;
			bool centerPosValid = false;
			rect.forEach([&](const int3& posToTest)
				{
					auto & terrainTile = map->getTile(posToTest);
					if(centerTile.getTerrain() != terrainTile.getTerrain())
					{
						const auto formerTerType = terrainTile.terrainType;
						terrainTile.terrainType = centerTile.terrainType;
						auto testTile = getInvalidTiles(posToTest);

						int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : static_cast<int>(testTile.nativeTiles.size());

						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.terrainType = 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) };
				for(const auto & direction : directions)
				{
					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).getTerrainID());

		// 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;

		mapping = pattern.mapping[0];

		if(pattern.decoration)
		{
			if (pattern.mapping.size() < 2 || gen->nextInt(100) > decorationsPercentage)
				mapping = pattern.mapping[0];
			else
				mapping = pattern.mapping[1];
		}

		if (!valRslt.transitionReplacement.empty())
			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
{
	const auto * centerTerType = map->getTile(pos).getTerrain();
	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;
		const TerrainType * terType = nullptr;
		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)).getTerrain();
			}
			else if(heightTooHigh)
			{
				terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).getTerrain();
			}
			else if(widthTooLess)
			{
				terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).getTerrain();
			}
			else if(heightTooLess)
			{
				terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).getTerrain();
			}
		}
		else
		{
			terType = map->getTile(currentPos).getTerrain();
			if(terType != centerTerType && (terType->isPassable() || centerTerType->isPassable()))
			{
				isAlien = true;
			}
		}

		// Validate all rules per cell
		int topPoints = -1;
		for(const auto & elem : pattern.data[i])
		{
			TerrainViewPattern::WeightedRule rule = elem;
			if(!rule.isStandardRule())
			{
				if(recDepth == 0 && map->isInTheMap(currentPos))
				{
					if(terType->getId() == centerTerType->getId())
					{
						const auto patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType->getId(), rule.name);
						if(auto p = patternForRule)
						{
							auto rslt = validateTerrainView(currentPos, &(p->get()), 1);
							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
			bool nativeTestOk = false;
			bool nativeTestStrongOk = false;
			nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;

			if(centerTerType->getId() == ETerrainId::DIRT)
			{
				nativeTestOk = rule.isNativeRule() && !terType->isTransitionRequired();
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
					&& terType->isTransitionRequired();
				applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
			}
			else if(centerTerType->getId() == ETerrainId::SAND)
			{
				applyValidationRslt(true);
			}
			else if(centerTerType->isTransitionRequired()) //water, rock and some special terrains require sand transition
			{
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
					&& isAlien;
				applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
			}
			else
			{
				bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
					&& isAlien && !terType->isTransitionRequired();
				bool sandTestOk = (rule.isSandRule() || rule.isTransition())
					&& terType->isTransitionRequired();

				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;
	const auto * centerTerType = map->getTile(centerPos).getTerrain();
	auto rect = extendTileAround(centerPos);
	rect.forEach([&](const int3& pos)
		{
			if(map->isInTheMap(pos))
			{
				const auto * terType = map->getTile(pos).getTerrain();
				auto valid = validateTerrainView(pos, VLC->terviewh->getTerrainTypePatternById("n1")).result;

				// Special validity check for rock & water
				if(valid && (terType->isWater() || !terType->isPassable()))
				{
					static const std::string patternIds[] = { "s1", "s2" };
					for(const auto & patternId : patternIds)
					{
						valid = !validateTerrainView(pos, VLC->terviewh->getTerrainTypePatternById(patternId)).result;
						if(!valid) break;
					}
				}
				// Additional validity check for non rock OR water
				else if(!valid && (terType->isLand() && terType->isPassable()))
				{
					static const std::string patternIds[] = { "n2", "n3" };
					for(const auto & patternId : patternIds)
					{
						valid = validateTerrainView(pos, VLC->terviewh->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;
}

CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, std::string transitionReplacement)
	: result(result)
	, transitionReplacement(std::move(transitionReplacement))
	, flip(0)
{

}

CClearTerrainOperation::CClearTerrainOperation(CMap* map, vstd::RNG* 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, 0, gen));
	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, 0, gen));
	}
}

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->anchorPos()),
	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
		obj->id = ObjectInstanceID(static_cast<si32>(map->objects.size()));
		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