File: CGarrisonInt.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 (817 lines) | stat: -rw-r--r-- 21,913 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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
/*
 * CGarrisonInt.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 "CGarrisonInt.h"

#include "Buttons.h"
#include "TextControls.h"
#include "RadialMenu.h"

#include "../gui/CGuiHandler.h"
#include "../gui/WindowHandler.h"
#include "../render/IImage.h"
#include "../windows/CCreatureWindow.h"
#include "../windows/CWindowWithArtifacts.h"
#include "../windows/GUIClasses.h"
#include "../CGameInfo.h"
#include "../CPlayerInterface.h"

#include "../../CCallback.h"

#include "../../lib/ArtifactUtils.h"
#include "../../lib/texts/CGeneralTextHandler.h"
#include "../../lib/texts/TextOperations.h"
#include "../../lib/CCreatureHandler.h"
#include "../../lib/CConfigHandler.h"
#include "../../lib/mapObjects/CGHeroInstance.h"
#include "../../lib/networkPacks/ArtifactLocation.h"
#include "../../lib/gameState/CGameState.h"
#include "../../lib/gameState/UpgradeInfo.h"

void CGarrisonSlot::setHighlight(bool on)
{
	if (on)
		selectionImage->enable(); //show
	else
		selectionImage->disable(); //hide
}

void CGarrisonSlot::hover (bool on)
{
	////Hoverable::hover(on);
	if(on)
	{
		std::string temp;
		if(creature)
		{
			if(owner->getSelection())
			{
				if(owner->getSelection() == this)
				{
					temp = CGI->generaltexth->tcommands[4]; //View %s
					boost::algorithm::replace_first(temp,"%s",creature->getNameSingularTranslated());
				}
				else if (owner->getSelection()->creature == creature)
				{
					temp = CGI->generaltexth->tcommands[2]; //Combine %s armies
					boost::algorithm::replace_first(temp,"%s",creature->getNameSingularTranslated());
				}
				else if (owner->getSelection()->creature)
				{
					temp = CGI->generaltexth->tcommands[7]; //Exchange %s with %s
					boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->getNameSingularTranslated());
					boost::algorithm::replace_first(temp,"%s",creature->getNameSingularTranslated());
				}
				else
				{
					logGlobal->warn("Warning - shouldn't be - highlighted void slot %d", owner->getSelection()->ID.getNum());
					logGlobal->warn("Highlighted set to nullptr");
					owner->selectSlot(nullptr);
				}
			}
			else
			{
				const bool isHeroOnMap = owner->upperArmy() // Hero is not a visitor and not a garrison defender
					&& owner->upperArmy()->ID == Obj::HERO
					&& (!owner->lowerArmy() || owner->lowerArmy()->ID == Obj::HERO) // one hero or we are in the Heroes exchange window
					&& !(static_cast<const CGHeroInstance*>(owner->upperArmy()))->inTownGarrison;

				if(isHeroOnMap)
				{
					temp = CGI->generaltexth->allTexts[481]; //Select %s
				}
				else if(upg == EGarrisonType::UPPER)
				{
					temp = CGI->generaltexth->tcommands[12]; //Select %s (in garrison)
				}
				else // Hero is visiting some object (town, mine, etc)
				{
					temp = CGI->generaltexth->tcommands[32]; //Select %s (visiting)
				}
				boost::algorithm::replace_first(temp,"%s",creature->getNameSingularTranslated());
			}
		}
		else
		{
			if(owner->getSelection())
			{
				const CArmedInstance *highl = owner->getSelection()->getObj();
				if(  highl->needsLastStack()		//we are moving stack from hero's
				  && highl->stacksCount() == 1	//it's only stack
				  && owner->getSelection()->upg != upg	//we're moving it to the other garrison
				  )
				{
					temp = CGI->generaltexth->tcommands[5]; //Cannot move last army to garrison
				}
				else
				{
					temp = CGI->generaltexth->tcommands[6]; //Move %s
					boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->getNameSingularTranslated());
				}
			}
			else
			{
				temp = CGI->generaltexth->tcommands[11]; //Empty
			}
		}
		GH.statusbar()->write(temp);
	}
	else
	{
		GH.statusbar()->clear();
	}
}

const CArmedInstance * CGarrisonSlot::getObj() const
{
	return owner->army(upg);
}

bool CGarrisonSlot::our() const
{
	return owner->isArmyOwned(upg);
}

bool CGarrisonSlot::ally() const
{
	if(!getObj())
		return false;

	return PlayerRelations::ALLIES == LOCPLINT->cb->getPlayerRelations(LOCPLINT->playerID, getObj()->tempOwner);
}

std::function<void()> CGarrisonSlot::getDismiss() const
{
	const bool canDismiss = getObj()->tempOwner == LOCPLINT->playerID
		&& (getObj()->stacksCount() > 1 ||
			!getObj()->needsLastStack());

	return canDismiss ? [=]()
	{
		LOCPLINT->cb->dismissCreature(getObj(), ID);
	} : (std::function<void()>)nullptr;
}

/// The creature slot has been clicked twice, therefore the creature info should be shown
/// @return Whether the view should be refreshed
bool CGarrisonSlot::viewInfo()
{
	UpgradeInfo pom(ID.getNum());
	LOCPLINT->cb->fillUpgradeInfo(getObj(), ID, pom);

	bool canUpgrade = getObj()->tempOwner == LOCPLINT->playerID && pom.canUpgrade(); //upgrade is possible
	std::function<void(CreatureID)> upgr = nullptr;
	auto dism = getDismiss();
	if(canUpgrade) upgr = [=] (CreatureID newID) { LOCPLINT->cb->upgradeCreature(getObj(), ID, newID); };

	owner->selectSlot(nullptr);
	owner->setSplittingMode(false);

	for(auto & elem : owner->splitButtons)
		elem->block(true);

	redraw();
	GH.windows().createAndPushWindow<CStackWindow>(myStack, dism, pom, upgr);
	return true;
}

/// The selection is empty, therefore the creature should be moved
/// @return Whether the view should be refreshed
bool CGarrisonSlot::highlightOrDropArtifact()
{
	bool artSelected = false;
	if (auto chw = GH.windows().topWindow<CWindowWithArtifacts>()) //dirty solution
	{
		const auto pickedArtInst = chw->getPickedArtifact();

		if(pickedArtInst)
		{
			const auto * srcHero = chw->getHeroPickedArtifact();
			artSelected = true;
			if (myStack) // try dropping the artifact only if the slot isn't empty
			{
				ArtifactLocation src(srcHero->id, ArtifactPosition::TRANSITION_POS);
				ArtifactLocation dst(getObj()->id, ArtifactPosition::CREATURE_SLOT);
				dst.creature = getSlot();

				if(pickedArtInst->canBePutAt(myStack, ArtifactPosition::CREATURE_SLOT, true))
				{	//equip clicked stack
					if(auto dstArt = myStack->getArt(ArtifactPosition::CREATURE_SLOT))
					{
						//creature can wear only one active artifact
						//if we are placing a new one, the old one will be returned to the hero's backpack
						LOCPLINT->cb->swapArtifacts(dst, ArtifactLocation(srcHero->id,
							ArtifactUtils::getArtBackpackPosition(srcHero, dstArt->getTypeId())));
					}
					LOCPLINT->cb->swapArtifacts(src, dst);
				}
			}
		}
	}
	if (!artSelected && creature)
	{
		owner->selectSlot(this);
		if(creature)
		{
			for(auto & elem : owner->splitButtons)
				elem->block(!our());
		}
	}
	redraw();
	return true;
}

/// The creature is only being partially moved
/// @return Whether the view should be refreshed
bool CGarrisonSlot::split()
{
	const CGarrisonSlot * selection = owner->getSelection();
	owner->setSplittingMode(false);

	int minLeft=0;
	int minRight=0;

	if(upg != selection->upg) // not splitting within same army
	{
		if(selection->getObj()->stacksCount() == 1 // we're splitting away the last stack
			&& selection->getObj()->needsLastStack() )
		{
			minLeft = 1;
		}
		// destination army can't be emptied, unless we're rebalancing two stacks of same creature
		if(getObj()->stacksCount() == 1
			&& selection->creature == creature
			&& getObj()->needsLastStack() )
		{
			minRight = 1;
		}
	}

	int countLeft = selection->myStack ? selection->myStack->count : 0;
	int countRight = myStack ? myStack->count : 0;

	auto splitFunctor = [this, selection](int amountLeft, int amountRight)
	{
		owner->splitStacks(selection, owner->army(upg), ID, amountRight);
	};

	GH.windows().createAndPushWindow<CSplitWindow>(selection->creature,  splitFunctor, minLeft, minRight, countLeft, countRight);
	return true;
}

bool CGarrisonSlot::mustForceReselection() const
{
	const CGarrisonSlot * selection = owner->getSelection();
	bool withAlly = selection->our() ^ our();

	// not our turn - actions are blocked
	if (!LOCPLINT->makingTurn)
		return true;

	// Attempt to take creatures from ally (select theirs first)
	if (!selection->our())
		return true;
	
	if (!creature || !selection->creature)
		return false;

	// Attempt to swap creatures with ally (select ours first)
	if (selection->creature != creature && withAlly)
		return true;

	if (!owner->removableUnits)
	{
		if (selection->upg == EGarrisonType::UPPER)
			return true;
		else
			return creature || upg == EGarrisonType::UPPER;
	}
	return false;
}

void CGarrisonSlot::showPopupWindow(const Point & cursorPosition)
{
	if(creature)
	{
		GH.windows().createAndPushWindow<CStackWindow>(myStack, true);
	}
}

void CGarrisonSlot::clickPressed(const Point & cursorPosition)
{
		bool refr = false;
		const CGarrisonSlot * selection = owner->getSelection();

		if(!selection)
		{
			refr = highlightOrDropArtifact(); // Affects selection
			handleSplittingShortcuts();
		}
		else if(selection == this)
		{
			if(!handleSplittingShortcuts())
				refr = viewInfo(); // Affects selection
		}
		// Re-highlight if troops aren't removable or not ours.
		else if (mustForceReselection())
		{
			if(creature)
				owner->selectSlot(this);
			owner->redraw();
			refr = true;
		}
		else
		{
			const CArmedInstance * selectedObj = owner->army(selection->upg);
			bool lastHeroStackSelected = false;
			if(selectedObj->stacksCount() == 1
				&& owner->getSelection()->upg != upg
				&& selectedObj->needsLastStack())
			{
				lastHeroStackSelected = true;
			}

			if((owner->getSplittingMode() || GH.isKeyboardShiftDown()) // split window
				&& (!creature || creature == selection->creature))
			{
				refr = split();
			}
			else if(!creature && lastHeroStackSelected) // split all except last creature
				LOCPLINT->cb->splitStack(selectedObj, owner->army(upg), selection->ID, ID, selection->myStack->count - 1);
			else if(creature != selection->creature) // swap
				LOCPLINT->cb->swapCreatures(owner->army(upg), selectedObj, ID, selection->ID);
			else if(lastHeroStackSelected) // merge last stack to other hero stack
				refr = split();
			else // merge
				LOCPLINT->cb->mergeStacks(selectedObj, owner->army(upg), selection->ID, ID);
		}
		if(refr)
		{
			// Refresh Statusbar
			hover(false);
			hover(true);
		}
}

void CGarrisonSlot::gesture(bool on, const Point & initialPosition, const Point & finalPosition)
{
	if(!on)
		return;

	if(!myStack)
		return;

	if (!settings["input"]["radialWheelGarrisonSwipe"].Bool())
		return;

	if(GH.windows().topWindow<CIntObject>()->isPopupWindow())
		return;

	const auto * otherArmy = upg == EGarrisonType::UPPER ? owner->lowerArmy() : owner->upperArmy();

	bool stackExists = myStack != nullptr;
	bool hasSameUnit = stackExists && !owner->army(upg)->getCreatureSlots(myStack->getCreature(), ID).empty();
	bool hasOwnEmptySlots = stackExists && owner->army(upg)->getFreeSlot() != SlotID();
	bool exchangeMode = stackExists && owner->upperArmy() && owner->lowerArmy();
	bool hasOtherEmptySlots = exchangeMode && otherArmy->getFreeSlot() != SlotID();
	bool hasAnyEmptySlots = hasOtherEmptySlots || hasOwnEmptySlots;

	std::vector<RadialMenuConfig> menuElements = {
		{ RadialMenuConfig::ITEM_NW, hasSameUnit, "stackMerge", "vcmi.radialWheel.mergeSameUnit", [this](){owner->bulkMergeStacks(this);} },
		{ RadialMenuConfig::ITEM_NE, hasOwnEmptySlots, "stackFillOne", "vcmi.radialWheel.fillSingleUnit", [this](){owner->bulkSplitStack(this);} },
		{ RadialMenuConfig::ITEM_WW, hasOwnEmptySlots, "stackSplitOne", "vcmi.radialWheel.splitSingleUnit", [this](){splitIntoParts(this->getGarrison(), 1); } },
		{ RadialMenuConfig::ITEM_EE, hasOwnEmptySlots, "stackSplitEqual", "vcmi.radialWheel.splitUnitEqually", [this](){owner->bulkSmartSplitStack(this);} },
		{ RadialMenuConfig::ITEM_SW, hasOtherEmptySlots, "heroMove", "vcmi.radialWheel.moveUnit", [this](){owner->moveStackToAnotherArmy(this);} },
		{ RadialMenuConfig::ITEM_SE, hasAnyEmptySlots, "heroSwap", "vcmi.radialWheel.splitUnit", [this](){ owner->selectSlot(this); owner->splitClick();} },
	};

	if (hasAnyEmptySlots || hasSameUnit)
		GH.windows().createAndPushWindow<RadialMenu>(pos.center(), menuElements);
}

void CGarrisonSlot::update()
{
	if(getObj() != nullptr)
	{
		addUsedEvents(LCLICK | SHOW_POPUP | GESTURE | HOVER);
		myStack = getObj()->getStackPtr(ID);
		creature = myStack ? myStack->getCreature() : nullptr;
	}
	else
	{
		removeUsedEvents(LCLICK | SHOW_POPUP | GESTURE | HOVER);
		myStack = nullptr;
		creature = nullptr;
	}

	if(creature)
	{
		creatureImage->enable();
		creatureImage->setFrame(creature->getIconIndex());

		stackCount->enable();
		stackCount->setText(TextOperations::formatMetric(myStack->count, 4));
	}
	else
	{
		creatureImage->disable();
		stackCount->disable();
	}
}

CGarrisonSlot::CGarrisonSlot(CGarrisonInt * Owner, int x, int y, SlotID IID, EGarrisonType Upg, const CStackInstance * creature_)
	: ID(IID),
	owner(Owner),
	myStack(creature_),
	creature(creature_ ? creature_->getCreature() : nullptr),
	upg(Upg)
{
	OBJECT_CONSTRUCTION;

	pos.x += x;
	pos.y += y;

	AnimationPath imgName = AnimationPath::builtin(owner->smallIcons ? "cprsmall" : "TWCRPORT");

	creatureImage = std::make_shared<CAnimImage>(imgName, 0);
	creatureImage->disable();

	selectionImage = std::make_shared<CAnimImage>(imgName, 1);
	selectionImage->disable();
	selectionImage->center(creatureImage->pos.center());

	if(Owner->smallIcons)
	{
		pos.w = 32;
		pos.h = 32;
	}
	else
	{
		pos.w = 58;
		pos.h = 64;
	}

	int labelPosW = pos.w;
	int labelPosH = pos.h;

	if(Owner->layout == CGarrisonInt::ESlotsLayout::REVERSED_TWO_ROWS) //labels under icon
	{
		labelPosW = pos.w / 2 + 1;
		labelPosH += 7;
	}
	ETextAlignment labelAlignment = Owner->layout == CGarrisonInt::ESlotsLayout::REVERSED_TWO_ROWS
			? ETextAlignment::CENTER
			: ETextAlignment::BOTTOMRIGHT;

	stackCount = std::make_shared<CLabel>(labelPosW, labelPosH, owner->smallIcons ? FONT_TINY : FONT_MEDIUM, labelAlignment, Colors::WHITE);

	update();
}

void CGarrisonSlot::splitIntoParts(EGarrisonType type, int amount)
{
	auto empty = owner->getEmptySlot(type);

	if(empty == SlotID())
		return;

	owner->splitStacks(this, owner->army(type), empty, amount);
}

bool CGarrisonSlot::handleSplittingShortcuts()
{
	const bool isAlt = GH.isKeyboardAltDown();
	const bool isLShift = GH.isKeyboardShiftDown();
	const bool isLCtrl = GH.isKeyboardCmdDown();

	if(!isAlt && !isLShift && !isLCtrl)
		return false; // This is only case when return false

	auto selected = owner->getSelection();
	if(!selected)
		return true; // Some Shortcusts are pressed but there are no appropriate actions

	auto units = selected->myStack->count;
	if(units < 1)
		return true;

	if (isLShift && isLCtrl && isAlt)
	{
		owner->bulkMoveArmy(selected);
	}
	else if(isLCtrl && isAlt)
	{
		owner->moveStackToAnotherArmy(selected);
	}
	else if(isLShift && isAlt)
	{
		auto dismiss = getDismiss();
		if(dismiss)
			LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[12], dismiss, nullptr);
	}
	else if(isAlt)
	{
		owner->bulkMergeStacks(selected);
	}
	else
	{
		if(units <= 1)
			return true;

		if(isLCtrl && isLShift)
			owner->bulkSplitStack(selected);
		else if(isLShift)
			owner->bulkSmartSplitStack(selected);
		else
			splitIntoParts(selected->upg, 1); // LCtrl
	}
	return true;
}

void CGarrisonInt::addSplitBtn(std::shared_ptr<CButton> button)
{
	addChild(button.get());
	splitButtons.push_back(button);
	button->block(getSelection() == nullptr);
}

void CGarrisonInt::createSlots()
{
	availableSlots.clear();

	int distance = interx + (smallIcons ? 32 : 58);
	for(auto i : { EGarrisonType::UPPER, EGarrisonType::LOWER })
	{
		Point offset = garOffset * static_cast<int>(i);
		for(int j = 0; j < 7; j++)
		{
			Point position(offset.x + (j*distance), offset.y);

			if(layout == ESlotsLayout::TWO_ROWS && j >= 4)
			{
				position += Point(-126, 37);
			}
			else if(layout == ESlotsLayout::REVERSED_TWO_ROWS)
			{
				if(j >= 3)
				{
					position += Point(-90, 49);
				}
				else
				{
					position += Point(36, 0);
				}
			}
			SlotID slot(j);
			availableSlots.push_back(std::make_shared<CGarrisonSlot>(this, position.x, position.y, slot, i, army(i) ? army(i)->getStackPtr(slot) : nullptr));
		}
	}
}

void CGarrisonInt::recreateSlots()
{
	selectSlot(nullptr);
	setSplittingMode(false);

	for(auto & elem : splitButtons)
		elem->block(true);

	for(auto slot : availableSlots)
		slot->update();
}

void CGarrisonInt::splitClick()
{
	if(!getSelection())
		return;
	setSplittingMode(!getSplittingMode());
	redraw();
}

void CGarrisonInt::splitStacks(const CGarrisonSlot * from, const CArmedInstance * armyDest, SlotID slotDest, int amount )
{
	LOCPLINT->cb->splitStack(armedObjs[from->upg], armyDest, from->ID, slotDest, amount);
}

bool CGarrisonInt::checkSelected(const CGarrisonSlot * selected, TQuantity min) const
{
	return selected && selected->myStack && selected->myStack->count > min && selected->creature;
}

void CGarrisonInt::moveStackToAnotherArmy(const CGarrisonSlot * selected)
{
	if(!checkSelected(selected))
		return;

	const auto srcArmyType = selected->upg;
	const auto destArmyType = srcArmyType == EGarrisonType::UPPER
		? EGarrisonType::LOWER
		: EGarrisonType::UPPER;

	auto srcArmy = armedObjs[srcArmyType];
	auto destArmy = armedObjs[destArmyType];

	if(!destArmy)
		return;

	auto destSlot = destArmy->getSlotFor(selected->creature);

	if(destSlot == SlotID())
		return;

	const auto srcSlot = selected->ID;
	const bool isDestSlotEmpty = !destArmy->getStackCount(destSlot);

	if(isDestSlotEmpty && !destArmy->getStackCount(srcSlot))
		destSlot = srcSlot; // Same place is more preferable

	const bool isLastStack = srcArmy->stacksCount() == 1 && srcArmy->needsLastStack();
	auto srcAmount = selected->myStack->count - (isLastStack ? 1 : 0);

	if(!srcAmount)
		return;

	if(!isDestSlotEmpty || isLastStack)
	{
		srcAmount += destArmy->getStackCount(destSlot); // Due to 'split' implementation in the 'CGameHandler::arrangeStacks'
		LOCPLINT->cb->splitStack(srcArmy, destArmy, srcSlot, destSlot, srcAmount);
	}
	else
	{
		LOCPLINT->cb->swapCreatures(srcArmy, destArmy, srcSlot, destSlot);
	}
}

void CGarrisonInt::bulkMoveArmy(const CGarrisonSlot * selected)
{
	if(!checkSelected(selected))
		return;

	const auto srcArmyType = selected->upg;
	const auto destArmyType = (srcArmyType == EGarrisonType::UPPER)
		? EGarrisonType::LOWER
		: EGarrisonType::UPPER;

	auto srcArmy = armedObjs[srcArmyType];
	auto destArmy = armedObjs[destArmyType];

	if(!destArmy)
		return;

	const auto srcSlot = selected->ID;
	LOCPLINT->cb->bulkMoveArmy(srcArmy->id, destArmy->id, srcSlot);
}

void CGarrisonInt::bulkMergeStacks(const CGarrisonSlot * selected)
{
	if(!checkSelected(selected))
		return;

	const auto type = selected->upg;

	if(!armedObjs[type]->hasCreatureSlots(selected->creature, selected->ID))
		return;

	LOCPLINT->cb->bulkMergeStacks(armedObjs[type]->id, selected->ID);
}

void CGarrisonInt::bulkSplitStack(const CGarrisonSlot * selected)
{
	if(!checkSelected(selected, 1)) // check if > 1
		return;

	const auto type = selected->upg;

	if(!hasEmptySlot(type))
		return;

	LOCPLINT->cb->bulkSplitStack(armedObjs[type]->id, selected->ID);
}

void CGarrisonInt::bulkSmartSplitStack(const CGarrisonSlot * selected)
{
	if(!checkSelected(selected, 1))
		return;

	const auto type = selected->upg;

	// Do not disturb the server if the creature is already balanced
	if(!hasEmptySlot(type) && armedObjs[type]->isCreatureBalanced(selected->creature))
		return;

	LOCPLINT->cb->bulkSmartSplitStack(armedObjs[type]->id, selected->ID);
}

CGarrisonInt::CGarrisonInt(const Point & position, int inx, const Point & garsOffset, const CArmedInstance * s1, const CArmedInstance * s2, bool _removableUnits, bool smallImgs, ESlotsLayout _layout)
	: highlighted(nullptr)
	, inSplittingMode(false)
	, interx(inx)
	, garOffset(garsOffset)
	, smallIcons(smallImgs)
	, removableUnits(_removableUnits)
	, layout(_layout)
{
	OBJECT_CONSTRUCTION;

	setArmy(s1, EGarrisonType::UPPER);
	setArmy(s2, EGarrisonType::LOWER);
	pos += position;
	createSlots();
}

const CGarrisonSlot * CGarrisonInt::getSelection() const
{
	return highlighted;
}

void CGarrisonInt::selectSlot(CGarrisonSlot *slot)
{
	if(slot != highlighted)
	{
		if(highlighted)
			highlighted->setHighlight(false);

		highlighted = slot;
		for(auto button : splitButtons)
			button->block(highlighted == nullptr || !slot->our());

		if(highlighted)
			highlighted->setHighlight(true);
	}
}

void CGarrisonInt::setSplittingMode(bool on)
{
	assert(on == false || highlighted != nullptr); //can't be in splitting mode without selection

	if(inSplittingMode || on)
	{
		for(auto slot : availableSlots)
		{
			if(slot.get() != getSelection())
				slot->setHighlight( ( on && (slot->our() || slot->ally()) && (slot->creature == nullptr || slot->creature == getSelection()->creature)));
		}
		inSplittingMode = on;
	}
}

bool CGarrisonInt::getSplittingMode()
{
	return inSplittingMode;
}

SlotID CGarrisonInt::getEmptySlot(EGarrisonType type) const
{
	assert(army(type));
	return army(type) ? army(type)->getFreeSlot() : SlotID();
}

bool CGarrisonInt::hasEmptySlot(EGarrisonType type) const
{
	return getEmptySlot(type) != SlotID();
}

const CArmedInstance * CGarrisonInt::upperArmy() const
{
	return army(EGarrisonType::UPPER);
}

const CArmedInstance * CGarrisonInt::lowerArmy() const
{
	return army(EGarrisonType::LOWER);
}

const CArmedInstance * CGarrisonInt::army(EGarrisonType which) const
{
	if(armedObjs.count(which))
		return armedObjs.at(which);
	return nullptr;
}

bool CGarrisonInt::isArmyOwned(EGarrisonType which) const
{
	const auto * object = army(which);

	if (!object)
		return false;

	if (object->tempOwner == LOCPLINT->playerID)
		return true;

	if (object->tempOwner == PlayerColor::UNFLAGGABLE)
		return true;

	return false;
}

void CGarrisonInt::setArmy(const CArmedInstance * army, EGarrisonType type)
{
	armedObjs[type] = army;
}