File: selection.cpp

package info (click to toggle)
boswars 2.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 96,652 kB
  • sloc: cpp: 57,250; python: 1,715; sh: 25; makefile: 17
file content (1184 lines) | stat: -rw-r--r-- 29,499 bytes parent folder | download | duplicates (5)
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//     ____                _       __               
//    / __ )____  _____   | |     / /___ ___________
//   / __  / __ \/ ___/   | | /| / / __ `/ ___/ ___/
//  / /_/ / /_/ (__  )    | |/ |/ / /_/ / /  (__  ) 
// /_____/\____/____/     |__/|__/\__,_/_/  /____/  
//                                              
//       A futuristic real-time strategy game.
//          This file is part of Bos Wars.
//
/**@name selection.cpp - The units' selection. */
//
//      (c) Copyright 1999-2008 by Patrice Fortier, Lutz Sammer, and
//                                 Jimmy Salmon
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; only version 2 of the License.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//      02111-1307, USA.
//

//@{

/*----------------------------------------------------------------------------
--  Includes
----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "stratagus.h"
#include "unittype.h"
#include "player.h"
#include "unit.h"
#include "unit_manager.h"
#include "unit_cache.h"
#include "interface.h"
#include "map.h"
#include "ui.h"
#include "commands.h"
#include "network.h"
#include "iolib.h"

#include "script.h"

/*----------------------------------------------------------------------------
--  Variables
----------------------------------------------------------------------------*/

int NumSelected;                 /// Number of selected units
int TeamNumSelected[PlayerMax];  /// How many units selected
int MaxSelectable;               /// Maximum number of selected units
CUnit **Selected;                 /// All selected units
CUnit **TeamSelected[PlayerMax];  /// teams currently selected units

static int _NumSelected;                 /// save of NumSelected
static int _TeamNumSelected[PlayerMax];  /// save of TeamNumSelected
static CUnit **_Selected;                 /// save of Selected
static CUnit **_TeamSelected[PlayerMax];  /// save of TeamSelected

static unsigned GroupId;         /// Unique group # for automatic groups

/*----------------------------------------------------------------------------
--  Functions
----------------------------------------------------------------------------*/

/**
**  Save selection to restore after.
*/
void SaveSelection(void)
{
	int i;
	int j;

	for (i = 0; i < PlayerMax; ++i) {
		_TeamNumSelected[i] = TeamNumSelected[i];
		for (j = 0; j < TeamNumSelected[i]; ++j) {
			_TeamSelected[i][j] = TeamSelected[i][j];
		}
	}
	_NumSelected = NumSelected;
	for (j = 0; j < NumSelected; ++j) {
		_Selected[j] = Selected[j];
	}
}

/**
**  Restore selection.
*/
void RestoreSelection(void)
{
	int i;
	int j;

	UnSelectAll();
	for (i = 0; i < PlayerMax; ++i) {
		TeamNumSelected[i] = _TeamNumSelected[i];
		for (j = 0; j < _TeamNumSelected[i]; ++j) {
			TeamSelected[i][j] = _TeamSelected[i][j];
			TeamSelected[i][j]->TeamSelected |= (1 << i);
		}
	}
	NumSelected = _NumSelected;
	for (j = 0; j < _NumSelected; ++j) {
		Selected[j] = _Selected[j];
		Selected[j]->Selected = 1;
	}
}

/**
**  Unselect all the units in the current selection
*/
void UnSelectAll(void)
{
	CUnit *unit;

	while (!++GroupId) { // Advance group id, but keep non zero
	}

	while (NumSelected) {
		unit = Selected[--NumSelected];
		Selected[NumSelected] = NoUnitP; // FIXME: only needed for old code
		unit->Selected = 0;
	}

}

/**
**  Replace a group of selected units by an other group of units.
**
**  @param units  Array of units to be selected.
**  @param count  Number of units in array to be selected.
*/
void ChangeSelectedUnits(CUnit **units,int count)
{
	CUnit *unit;
	int i;
	int n;

	Assert(count <= MaxSelectable);

	UnSelectAll();
	NetworkSendSelection(units, count);
	for (n = i = 0; i < count; ++i) {
		if (!units[i]->Removed && !units[i]->TeamSelected && !units[i]->Type->IsNotSelectable) {
			Selected[n++] = unit = units[i];
			unit->Selected = 1;
			if (count > 1) {
				unit->LastGroup = GroupId;
			}
		}
	}
	NumSelected = n;
}

/**
**  Change A Unit Selection from my Team
**
**  @param player  The Player who is selecting the units
**  @param units   The Units to add/remove
**  @param adjust  0 = reset, 1 = remove units, 2 = add units
**  @param count   the number of units to be adjusted
*/
void ChangeTeamSelectedUnits(CPlayer *player, CUnit **units, int adjust, int count)
{
	int i;
	int n;
	CUnit *unit;

	switch (adjust) {
		case 0:
			// UnSelectAllTeam(player);
			while (TeamNumSelected[player->Index]) {
				unit = TeamSelected[player->Index][--TeamNumSelected[player->Index]];
				unit->TeamSelected &= ~(1 << player->Index);
				TeamSelected[player->Index][TeamNumSelected[player->Index]] = NoUnitP; // FIXME: only needed for old code
			}
			// FALL THROUGH
		case 2:
			for (i = 0; i < count; ++i) {
				Assert(!units[i]->Removed);
				if (!units[i]->Type->IsNotSelectable) {
					TeamSelected[player->Index][TeamNumSelected[player->Index]++] = units[i];
					units[i]->TeamSelected |= 1 << player->Index;
				}
			}
			Assert(TeamNumSelected[player->Index] <= MaxSelectable);
			break;
		case 1:
			for (n = 0; n < TeamNumSelected[player->Index]; ++n) {
				for (i = 0; i < count; ++i) {
					if (units[i] == TeamSelected[player->Index][n]) {
						TeamSelected[player->Index][n] =
							TeamSelected[player->Index][TeamNumSelected[player->Index]--];
					}
				}
			}
			Assert(TeamNumSelected[player->Index] >= 0);
			break;
		default:
			Assert(0);
	}
}

/**
**  Add a unit to the other selected units.
**
**  @param unit  Pointer to unit to add.
**
**  @return      true if added to selection, false otherwise
**               (if NumSelected == MaxSelectable or
**                unit is already selected or unselectable)
*/
int SelectUnit(CUnit *unit)
{
	if (unit->Type->Revealer) { // Revealers cannot be selected
		DebugPrint("Selecting revealer?\n");
		return 0;
	}

	if (unit->Removed) { // Removed cannot be selected
		DebugPrint("Selecting removed?\n");
		return 0;
	}

	if (NumSelected == MaxSelectable) {
		return 0;
	}

	if (unit->Selected) {
		return 0;
	}

	if (unit->Type->IsNotSelectable && GameRunning) {
		return 0;
	}

	Selected[NumSelected++] = unit;
	unit->Selected = 1;
	if (NumSelected > 1) {
		Selected[0]->LastGroup = unit->LastGroup = GroupId;
	}
	return 1;
}

/**
**  Select a single unit, unselecting the previous ones
**
**  @param unit  Pointer to unit to be selected.
*/
void SelectSingleUnit(CUnit *unit)
{
	ChangeSelectedUnits(&unit, 1);
}

/**
**  Unselect unit
**
**  @param unit  Pointer to unit to be unselected.
*/
void UnSelectUnit(CUnit *unit)
{
	int i;
	int j;

	if (unit->TeamSelected) {
		for (i = 0; i < PlayerMax; ++i) {
			if (unit->TeamSelected & (1 << i)) {
				for (j = 0; TeamSelected[i][j] != unit; ++j) {
					;
				}
				Assert(j < TeamNumSelected[i]);

				if (j < --TeamNumSelected[i]) {

					TeamSelected[i][j] = TeamSelected[i][TeamNumSelected[i]];
				}
				unit->TeamSelected &= ~(1 << i);
			}
		}
	}
	if (!unit->Selected) {
		return;
	}

	for (i = 0; Selected[i] != unit; ++i) {
		;
	}
	Assert(i < NumSelected);

	if (i < --NumSelected) {
		Selected[i] = Selected[NumSelected];
	}

	if (NumSelected > 1) { // Assign new group to remaining units
		while (!++GroupId) { // Advance group id, but keep non zero
		}
		for (i = 0; i < NumSelected; ++i) {
			Selected[i]->LastGroup = GroupId;
		}
	}

	Selected[NumSelected] = NoUnitP; // FIXME: only needed for old code
	unit->Selected = 0;
}

/**
**  Toggle the selection of a unit in a group of selected units
**
**  @param unit  Pointer to unit to be toggled.
**  @return      0 if unselected, 1 otherwise
*/
int ToggleSelectUnit(CUnit *unit)
{
	if (unit->Selected) {
		UnSelectUnit(unit);
		return 0;
	}
	SelectUnit(unit);
	return 1;
}

/**
**  Select units from a particular type and belonging to the local player.
**
**  The base is included in the selection and defines
**  the type of the other units to be selected.
**
**  @param base  Select all units of same type.
**
**  @return      Number of units found, 0 means selection unchanged
**
**  FIXME: 0 can't happen. Maybe when scripting will use it?
**
**  FIXME: should always select the nearest 9 units to the base!
*/
int SelectUnitsByType(CUnit *base)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	const CUnitType *type;
	int r;
	int i;
	const CViewport *vp;

	Assert(UI.MouseViewport);

	type = base->Type;

	// select all visible units.
	// StephanR: should be (MapX,MapY,MapX+MapWidth-1,MapY+MapHeight-1) ???
	/* FIXME: this should probably be cleaner implemented if SelectUnitsByType()
	 * took parameters of the selection rectangle as arguments */
	vp = UI.MouseViewport;
	r = UnitCache.Select(vp->MapX - 1, vp->MapY - 1, vp->MapX + vp->MapWidth + 1,
		vp->MapY + vp->MapHeight + 1, table, UnitMax);

	// if unit is a cadaver or hidden (not on map)
	// no unit can be selected.
	if (base->Removed || base->Orders[0]->Action == UnitActionDie) {
		return 0;
	}

	if (base->Type->IsNotSelectable && GameRunning) {
		return 0;
	}
	if (base->TeamSelected) { // Somebody else onteam has this unit
		return 0;
	}

	UnSelectAll();
	Selected[0] = base;
	base->Selected = 1;
	NumSelected = 1;

	// if unit isn't belonging to the player or allied player, or is a static unit
	// (like a building), only 1 unit can be selected at the same time.
	if (!CanSelectMultipleUnits(base->Player) || !type->SelectableByRectangle) {
		return NumSelected;
	}

	//
	// Search for other visible units of the same type
	//
	// FIXME: peon/peasant with gold/wood & co are considered from
	//   different type... idem for tankers
	for (i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) || unit->Type != type) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit == base) {  // no need to have the same unit twice :)
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		Selected[NumSelected++] = unit;
		unit->Selected = 1;
		if (NumSelected == MaxSelectable) {
			break;
		}
	}

	if (NumSelected > 1) {
		for (i = 0; i < NumSelected; ++i) {
			Selected[i]->LastGroup = GroupId;
		}
	}

	NetworkSendSelection(Selected, NumSelected);
	return NumSelected;
}

/**
**  Toggle units from a particular type and belonging to the local player.
**
**  The base is included in the selection and defines
**  the type of the other units to be selected.
**
**  @param base  Toggle all units of same type.
**
**  @return      Number of units found, 0 means selection unchanged
**
**  FIXME: toggle not written
**  FIXME: should always select the nearest 9 units to the base!
*/
int ToggleUnitsByType(CUnit *base)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	const CUnitType *type;
	int r;
	int i;

	type = base->Type;

	// select all visible units.
	// StephanR: should be (MapX,MapY,MapX+MapWidth-1,MapY+MapHeight-1) ???
	// FIXME: this should probably be cleaner implemented if SelectUnitsByType()
	// took parameters of the selection rectangle as arguments */
	r = UnitCache.Select(UI.MouseViewport->MapX - 1,
		UI.MouseViewport->MapY - 1,
		UI.MouseViewport->MapX + UI.MouseViewport->MapWidth + 1,
		UI.MouseViewport->MapY + UI.MouseViewport->MapHeight + 1, table, UnitMax);

	// if unit is a cadaver or hidden (not on map)
	// no unit can be selected.
	if (base->Removed || base->Orders[0]->Action == UnitActionDie) {
		return 0;
	}
	// if unit isn't belonging to the player, or is a static unit
	// (like a building), only 1 unit can be selected at the same time.
	if (!CanSelectMultipleUnits(base->Player) || !type->SelectableByRectangle) {
		return 0;
	}

	if (!SelectUnit(base)) { // Add base to selection
		return 0;
	}
	//
	//  Search for other visible units of the same type
	//
	// FIXME: peon/peasant with gold/wood & co are considered from
	// different type... idem for tankers
	for (i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) || unit->Type != type) {
			continue;
		}
		if (unit->IsUnusable()) { // guess SelectUnits doesn't check this
			continue;
		}
		if (unit == base) { // no need to have the same unit twice
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		if (!SelectUnit(unit)) { // add unit to selection
			return NumSelected;
		}
	}

	NetworkSendSelection(Selected, NumSelected);
	return NumSelected;
}

/**
**  Change selected units to units from group group_number
**  Doesn't change the selection if the group has no unit.
**
**  @param group_number  number of the group to be selected.
**
**  @return              number of units in the group.
*/
int SelectGroup(int group_number)
{
	int nunits;

	Assert(group_number <= NUM_GROUPS);

	if (!(nunits = GetNumberUnitsOfGroup(group_number))) {
		return 0;
	}

	ChangeSelectedUnits(GetUnitsOfGroup(group_number), nunits);
	return NumSelected;
}

/**
**  Add units from group of a particular unit to selection.
**
**  @param unit  unit belonging to the group to be selected.
**
**  @return      0 if the unit doesn't belong to a group,
**               or the number of units in the group.
*/
int AddGroupFromUnitToSelection(CUnit *unit)
{
	int i;
	int group;

	if (!(group = unit->LastGroup)) { // belongs to no group
		return 0;
	}

	for (i = 0; i < NumUnits; ++i) {
		if (Units[i]->LastGroup == group && !Units[i]->Removed) {
			SelectUnit(Units[i]);
			if (NumSelected == MaxSelectable) {
				return NumSelected;
			}
		}
	}
	return NumSelected;
}

/**
**  Select units from group of a particular unit.
**  Doesn't change the selection if the group has no unit,
**  or the unit doesn't belong to any group.
**
**  @param unit  unit belonging to the group to be selected.
**
**  @return      0 if the unit doesn't belong to a group,
**               or the number of units in the group.
*/
int SelectGroupFromUnit(CUnit *unit)
{
	if (!unit->LastGroup) { // belongs to no group
		return 0;
	}

	UnSelectAll();
	return AddGroupFromUnitToSelection(unit);
}

/**
**  Select the units selecteable by rectangle in a local table.
**  Act like a filter: The source table is modified.
**  Return the original table if no unit is found.
**
**  @param table      Input/Output table of units.
**  @param num_units  Number of units in input table.
**
**  @return           the number of units found.
*/
static int SelectOrganicUnitsInTable(CUnit **table, int num_units)
{
	CUnit *unit;
	int n;
	int i;

	for (n = i = 0; i < num_units; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) || !unit->Type->SelectableByRectangle) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		table[n++] = unit;
		if (n == MaxSelectable) {
			break;
		}
	}
	return n;
}

/**
**  Selects units from the table whose sprite is at least partially
**  covered by the rectangle. The rectangle is determined by coordinates
**  of its upper left and lower right corner expressed in screen map
**  coordinate system.
**
**  @param sx0        x-coord of upper left corner of the rectangle
**  @param sy0        y-coord of upper left corner of the rectangle
**  @param sx1        x-coord of lower right corner of the rectangle
**  @param sy1        y-coord of lower right corner of the rectangle
**  @param table      table of units
**  @param num_units  number of units in table
**
**  @return           number of units found
*/
static int SelectSpritesInsideRectangle (int sx0, int sy0, int sx1, int sy1,
	CUnit **table, int num_units)
{
	int n;
	int i;

	for (i = n = 0; i < num_units; ++i) {
		int sprite_x;
		int sprite_y;
		CUnit *unit;
		const CUnitType *type;

		unit = table[i];
		type = unit->Type;
		sprite_x = unit->X * TileSizeX + unit->IX;
		sprite_x -= (type->BoxWidth - TileSizeX * type->TileWidth) / 2;
		sprite_x += type->OffsetX;
		sprite_y = unit->Y * TileSizeY + unit->IY;
		sprite_y -= (type->BoxHeight - TileSizeY * type->TileHeight) / 2;
		sprite_y += type->OffsetY;
		if (sprite_x + type->BoxWidth < sx0) {
			continue;
		}
		if (sprite_x > sx1) {
			continue;
		}
		if (sprite_y + type->BoxHeight < sy0) {
			continue;
		}
		if (sprite_y > sy1) {
			continue;
		}
		table[n++] = unit;
	}
	return n;
}

/**
**  Add the units in the rectangle to the current selection
**
**  @param x0  X start of selection rectangle in tile coordinates
**  @param y0  Y start of selection rectangle in tile coordinates
**  @param x1  X start of selection rectangle in tile coordinates
**  @param y1  Y start of selection rectangle in tile coordinates
**
**  @return    the _total_ number of units selected.
*/
int AddSelectedUnitsInRectangle(int x0, int y0, int x1, int y1)
{
	CUnit *table[UnitMax];
	int toggle_num;
	int n;
	int i;

	// If there is no selected unit yet, do a simple selection.
	if (!NumSelected) {
		return SelectUnitsInRectangle(x0, y0, x1, y1);
	}

	// Check if the original selected unit (if it's alone) is ours,
	// and can be selectable by rectangle.
	// In this case, do nothing.
	if (NumSelected == 1 &&
			(!CanSelectMultipleUnits(Selected[0]->Player) ||
				!Selected[0]->Type->SelectableByRectangle)) {
		return NumSelected;
	}

	// If no unit in rectangle area... do nothing
	toggle_num = UnitCache.Select((x0 / TileSizeX) - 2, (y0 / TileSizeY) - 2,
		(x1 / TileSizeX) + 2 + 1, (y1 / TileSizeX) + 2 + 1, table, UnitMax);
	if (!toggle_num) {
		return NumSelected;
	}
	toggle_num = SelectSpritesInsideRectangle(x0, y0, x1, y1, table, toggle_num);
	if (!toggle_num) {
		return NumSelected;
	}

	// Now we should only have mobile (organic) units belonging to us,
	// so if there's no such units in the rectangle, do nothing.
	if (!(n = SelectOrganicUnitsInTable(table, toggle_num))) {
		return NumSelected;
	}

	for (i = 0; i < n && NumSelected < MaxSelectable; ++i) {
		SelectUnit(table[i]);
	}
	return NumSelected;
}

/**
**  Select units in a rectangle.
**  Proceed in order in none found:
**    @li select local player mobile units
**    @li select one local player static unit (random)
**    @li select one neutral unit (critter, mine...)
**    @li select one enemy unit (random)
**
**  @param sx0  X start of selection rectangle in tile coordinates
**  @param sy0  Y start of selection rectangle in tile coordinates
**  @param sx1  X start of selection rectangle in tile coordinates
**  @param sy1  Y start of selection rectangle in tile coordinates
**
**  @return     the number of units found.
*/
int SelectUnitsInRectangle (int sx0, int sy0, int sx1, int sy1)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	CUnitType *type;
	int r;
	int n;
	int i;
	int tx0;
	int ty0;
	int tx1;
	int ty1;

	tx0 = sx0 / TileSizeX;
	ty0 = sy0 / TileSizeY;
	tx1 = sx1 / TileSizeX;
	ty1 = sy1 / TileSizeY;

	r = UnitCache.Select(tx0 - 2, ty0 - 2, tx1 + 2 + 1, ty1 + 2 + 1, table, UnitMax);
	r = SelectSpritesInsideRectangle(sx0, sy0, sx1, sy1, table, r);

	//
	// 1) search for the player units selectable with rectangle
	//
	if ((n = SelectOrganicUnitsInTable(table, r))) {
		ChangeSelectedUnits(table, n);
		return n;
	}

	//
	// 2) If no unit found, try a player's unit not selectable by rectangle
	//
	for (i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player)) {
			continue;
		}
		// FIXME: Can we get this?
		if (!unit->Removed && unit->Orders[0]->Action != UnitActionDie) {
			SelectSingleUnit(unit);
			return 1;
		}
	}

	//
	// 3) If no unit found, try a resource or a neutral critter
	//
	for (i = 0; i < r; ++i) {
		unit = table[i];
		// Unit visible FIXME: write function UnitSelectable
		if (!unit->IsVisibleInViewport(UI.SelectedViewport)) {
			continue;
		}
		type = unit->Type;
		// Buildings are visible but not selectable
		if (type->Building && !unit->IsVisibleOnMap(ThisPlayer)) {
			continue;
		}
		if ((type->CanHarvestFrom && !unit->Removed)) { // no built resources.
			SelectSingleUnit(unit);
			return 1;
		}
	}

	//
	// 4) If no unit found, select an enemy unit (first found)
	//
	for (i = 0; i < r; ++i) {
		unit = table[i];
		// Unit visible FIXME: write function UnitSelectable
		if (!unit->IsVisibleInViewport(UI.SelectedViewport)) {
			continue;
		}
		// Buildings are visible but not selectable
		if (unit->Type->Building && !unit->IsVisibleOnMap(ThisPlayer)) {
			continue;
		}
		if (!unit->Removed && unit->Orders[0]->Action != UnitActionDie) {
			SelectSingleUnit(unit);
			return 1;
		}
	}

	return 0;
}

/**
**  Select own ground units in a rectangle.
**
**  @param sx0  X start of selection rectangle in tile coordinates
**  @param sy0  Y start of selection rectangle in tile coordinates
**  @param sx1  X start of selection rectangle in tile coordinates
**  @param sy1  Y start of selection rectangle in tile coordinates
**
**  @return     the number of units found.
*/
int SelectGroundUnitsInRectangle(int sx0, int sy0, int sx1, int sy1)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	int r;
	int n;
	int i;
	int tx0;
	int ty0;
	int tx1;
	int ty1;

	tx0 = sx0 / TileSizeX;
	ty0 = sy0 / TileSizeY;
	tx1 = sx1 / TileSizeX;
	ty1 = sy1 / TileSizeY;

	r = UnitCache.Select(tx0 - 2, ty0 - 2, tx1 + 2 + 1, ty1 + 2 + 1, table, UnitMax);
	r = SelectSpritesInsideRectangle(sx0, sy0, sx1, sy1, table, r);

	for (n = i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) || !unit->Type->SelectableByRectangle) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit->Type->UnitType == UnitTypeFly) {
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		table[n++] = unit;
		if (n == MaxSelectable) {
			break;
		}
	}
	if (n) {
		ChangeSelectedUnits(table, n);
	}
	return n;
}

/**
**  Select own air units in a rectangle.
**
**  @param sx0  X start of selection rectangle in tile coordinates
**  @param sy0  Y start of selection rectangle in tile coordinates
**  @param sx1  X start of selection rectangle in tile coordinates
**  @param sy1  Y start of selection rectangle in tile coordinates
**
**  @return     the number of units found.
*/
int SelectAirUnitsInRectangle(int sx0, int sy0, int sx1, int sy1)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	int r;
	int n;
	int i;
	int tx0;
	int ty0;
	int tx1;
	int ty1;

	tx0 = sx0 / TileSizeX;
	ty0 = sy0 / TileSizeY;
	tx1 = sx1 / TileSizeX;
	ty1 = sy1 / TileSizeY;

	r = UnitCache.Select(tx0 - 2, ty0 - 2, tx1 + 2 + 1, ty1 + 2 + 1, table, UnitMax);
	r = SelectSpritesInsideRectangle(sx0, sy0, sx1, sy1, table, r);

	for (n = i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) || !unit->Type->SelectableByRectangle) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit->Type->UnitType != UnitTypeFly) {
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		table[n++] = unit;
		if (n == MaxSelectable) {
			break;
		}
	}
	if (n) {
		ChangeSelectedUnits(table, n);
	}
	return n;
}

/**
**  Add the ground units in the rectangle to the current selection
**
**  @param sx0  X start of selection rectangle in tile coordinates
**  @param sy0  Y start of selection rectangle in tile coordinates
**  @param sx1  X start of selection rectangle in tile coordinates
**  @param sy1  Y start of selection rectangle in tile coordinates
**
**  @return     the number of units found.
*/
int AddSelectedGroundUnitsInRectangle(int sx0, int sy0, int sx1, int sy1)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	int r;
	int n;
	int i;
	int tx0;
	int ty0;
	int tx1;
	int ty1;

	// If there is no selected unit yet, do a simple selection.
	if (!NumSelected) {
		return SelectGroundUnitsInRectangle(sx0, sy0, sx1, sy1);
	}

	// Check if the original selected unit (if it's alone) is ours,
	// and can be selectable by rectangle.
	// In this case, do nothing.
	if (NumSelected == 1 &&
			(!CanSelectMultipleUnits(Selected[0]->Player) ||
				!Selected[0]->Type->SelectableByRectangle)) {
		return NumSelected;
	}

	tx0 = sx0 / TileSizeX;
	ty0 = sy0 / TileSizeY;
	tx1 = sx1 / TileSizeX;
	ty1 = sy1 / TileSizeY;

	r = UnitCache.Select(tx0 - 2, ty0 - 2, tx1 + 2 + 1, ty1 + 2 + 1, table, UnitMax);
	r = SelectSpritesInsideRectangle(sx0, sy0, sx1, sy1, table, r);

	for (n = i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) ||
			!unit->Type->SelectableByRectangle) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit->Type->UnitType == UnitTypeFly) {
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		table[n++] = unit;
		if (n == MaxSelectable) {
			break;
		}
	}

	//
	// Add the units to selected.
	//
	for (i = 0; i < n && NumSelected < MaxSelectable; ++i) {
		SelectUnit(table[i]);
	}
	return NumSelected;
}

/**
**  Add the air units in the rectangle to the current selection
**
**  @param sx0  X start of selection rectangle in tile coordinates
**  @param sy0  Y start of selection rectangle in tile coordinates
**  @param sx1  X start of selection rectangle in tile coordinates
**  @param sy1  Y start of selection rectangle in tile coordinates
**
**  @return     the number of units found.
*/
int AddSelectedAirUnitsInRectangle(int sx0, int sy0, int sx1, int sy1)
{
	CUnit *unit;
	CUnit *table[UnitMax];
	int r;
	int n;
	int i;
	int tx0;
	int ty0;
	int tx1;
	int ty1;

	// If there is no selected unit yet, do a simple selection.
	if (!NumSelected) {
		return SelectAirUnitsInRectangle(sx0, sy0, sx1, sy1);
	}

	// Check if the original selected unit (if it's alone) is ours,
	// and can be selectable by rectangle.
	// In this case, do nothing.
	if (NumSelected == 1 &&
			(!CanSelectMultipleUnits(Selected[0]->Player) ||
				!Selected[0]->Type->SelectableByRectangle)) {
		return NumSelected;
	}

	tx0 = sx0 / TileSizeX;
	ty0 = sy0 / TileSizeY;
	tx1 = sx1 / TileSizeX;
	ty1 = sy1 / TileSizeY;

	r = UnitCache.Select(tx0 - 2, ty0 - 2, tx1 + 2 + 1, ty1 + 2 + 1, table, UnitMax);
	r = SelectSpritesInsideRectangle(sx0, sy0, sx1, sy1, table, r);

	for (n = i = 0; i < r; ++i) {
		unit = table[i];
		if (!CanSelectMultipleUnits(unit->Player) ||
			!unit->Type->SelectableByRectangle) {
			continue;
		}
		if (unit->IsUnusable()) {  // guess SelectUnits doesn't check this
			continue;
		}
		if (unit->Type->UnitType != UnitTypeFly) {
			continue;
		}
		if (unit->TeamSelected) { // Somebody else onteam has this unit
			continue;
		}
		table[n++] = unit;
		if (n == MaxSelectable) {
			break;
		}
	}

	//
	// Add the units to selected.
	//
	for (i = 0; i < n && NumSelected < MaxSelectable; ++i) {
		SelectUnit(table[i]);
	}
	return NumSelected;
}

/**
**  Initialize the selection module.
*/
void InitSelections(void)
{
	// This could have been initialized already when loading a game
	if (!Selected) {
		Selected = new CUnit *[MaxSelectable];
		_Selected = new CUnit *[MaxSelectable];
	}
	for (int i = 0; i < PlayerMax; ++i) {
		if (!TeamSelected[i]) {
			TeamSelected[i] = new CUnit *[MaxSelectable];
			_TeamSelected[i] = new CUnit *[MaxSelectable];
		}
	}
}

/**
**  Save current selection state.
**
**  @param file  Output file.
*/
void SaveSelections(CFile *file)
{
	file->printf("\n--- -----------------------------------------\n");
	file->printf("--- MODULE: selection\n\n");

	file->printf("SetGroupId(%d)\n", GroupId);
	file->printf("Selection(%d, {", NumSelected);
	for (int i = 0; i < NumSelected; ++i) {
		file->printf("\"%s\", ", UnitReference(Selected[i]).c_str());
	}
	file->printf("})\n");
}

/**
**  Clean up the selection module.
*/
void CleanSelections(void)
{
	GroupId = 0;
	NumSelected = 0;
	delete[] Selected;
	Selected = NULL;
	delete[] _Selected;
	_Selected = NULL;

	for (int i = 0; i < PlayerMax; ++i) {
		delete[] TeamSelected[i];
		TeamSelected[i] = NULL;
		delete[] _TeamSelected[i];
		_TeamSelected[i] = NULL;
		TeamNumSelected[i] = 0;
		_TeamNumSelected[i] = 0;
	}
}

// ----------------------------------------------------------------------------

/**
**  Set the current group id. (Needed for load/save)
**
**  @param l  Lua state.
*/
static int CclSetGroupId(lua_State *l)
{
	int old;

	LuaCheckArgs(l, 1);
	old = GroupId;
	GroupId = LuaToNumber(l, 1);

	lua_pushnumber(l, old);
	return 1;
}

/**
**  Define the current selection.
**
**  @param l  Lua state.
*/
static int CclSelection(lua_State *l)
{
	int i;
	int args;
	int j;

	LuaCheckArgs(l, 2);
	LuaCheckTable(l, 2);
	InitSelections();
	NumSelected = LuaToNumber(l, 1);
	i = 0;
	args = lua_objlen(l, 2);
	for (j = 0; j < args; ++j) {
		const char *str;

		str = LuaToString(l, 2, j + 1);
		Selected[i++] = UnitSlots[strtol(str + 1, NULL, 16)];
	}

	return 0;
}

/**
**  Register CCL features for selections.
*/
void SelectionCclRegister(void)
{
	lua_register(Lua, "SetGroupId", CclSetGroupId);
	lua_register(Lua, "Selection", CclSelection);
}

//@}