File: SelectionKeyHandler.cpp

package info (click to toggle)
spring 98.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 41,928 kB
  • ctags: 60,665
  • sloc: cpp: 356,167; ansic: 39,434; python: 12,228; java: 12,203; awk: 5,856; sh: 1,719; xml: 997; perl: 405; php: 253; objc: 194; makefile: 72; sed: 2
file content (432 lines) | stat: -rw-r--r-- 11,609 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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include <fstream>

#include "Game/Camera/CameraController.h"
#include "Game/Camera.h"
#include "Game/CameraHandler.h"
#include "Game/GlobalUnsynced.h"
#include "Game/SelectedUnitsHandler.h"
#include "MouseHandler.h"
#include "SelectionKeyHandler.h"
#include "Map/Ground.h"
#include "Sim/Misc/CategoryHandler.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Units/UnitTypes/Building.h"
#include "System/Log/ILog.h"
#include "System/myMath.h"
#include "System/FileSystem/DataDirsAccess.h"
#include <boost/cstdint.hpp>

CSelectionKeyHandler* selectionKeys;

CSelectionKeyHandler::CSelectionKeyHandler()
	: selectNumber(0)
{
}

CSelectionKeyHandler::~CSelectionKeyHandler()
{
}

std::string CSelectionKeyHandler::ReadToken(std::string& str)
{
	std::string ret;

	size_t index = 0;
	while ((index < str.length()) && (str[index] != '_') && (str[index] != '+')) {
		index++;
	}

	ret = str.substr(0, index);
	str = str.substr(index, std::string::npos);

	return ret;
}


std::string CSelectionKeyHandler::ReadDelimiter(std::string& str)
{
	std::string ret = str.substr(0, 1);
	if (str.size() >= 1) {
		str = str.substr(1, std::string::npos);
	} else {
		str = "";
	}
	return ret;
}


namespace
{
	struct Filter
	{
	public:
		typedef std::map<std::string, Filter*> Map;

		/// Contains all existing filter singletons.
		static Map& all() {
			static Map instance;
			return instance;
		}

		virtual ~Filter() {}

		/// Called immediately before the filter is used.
		virtual void Prepare() {}

		/// Called immediately before the filter is used for every parameter.
		virtual void SetParam(int index, const std::string& value) {
			assert(false);
		}

		/**
		 * Actual filtering, should return false if unit should be removed
		 * from proposed selection.
		 */
		virtual bool ShouldIncludeUnit(const CUnit* unit) const = 0;

		/// Number of arguments this filter has.
		const int numArgs;

	protected:
		Filter(const std::string& name, int args) : numArgs(args) {
			all().insert(Map::value_type(name, this));
		}
	};

	// prototype / factory based approach might be better at some point?
	// for now these singleton filters seem ok. (they are not reentrant tho!)

#define DECLARE_FILTER_EX(name, args, condition, extra, init) \
	struct name ## _Filter : public Filter { \
		name ## _Filter() : Filter(#name, args) { init; } \
		bool ShouldIncludeUnit(const CUnit* unit) const { return condition; } \
		extra \
	} name ## _filter_instance; \

#define DECLARE_FILTER(name, condition) \
	DECLARE_FILTER_EX(name, 0, condition, ,)

	DECLARE_FILTER(Builder, unit->unitDef->buildSpeed > 0)
	DECLARE_FILTER(Building, dynamic_cast<const CBuilding*>(unit) != NULL)
	DECLARE_FILTER(Transport, unit->unitDef->transportCapacity > 0)
	DECLARE_FILTER(Aircraft, unit->unitDef->canfly)
	DECLARE_FILTER(Weapons, !unit->weapons.empty())
	DECLARE_FILTER(Idle, unit->commandAI->commandQue.empty())
	DECLARE_FILTER(Waiting, !unit->commandAI->commandQue.empty() &&
	               (unit->commandAI->commandQue.front().GetID() == CMD_WAIT))
	DECLARE_FILTER(InHotkeyGroup, unit->group != NULL)
	DECLARE_FILTER(Radar, unit->radarRadius || unit->sonarRadius || unit->jammerRadius)
	DECLARE_FILTER(ManualFireUnit, unit->unitDef->canManualFire)

	DECLARE_FILTER_EX(WeaponRange, 1, unit->maxRange > minRange,
		float minRange;
		void SetParam(int index, const std::string& value) {
			minRange = atof(value.c_str());
		},
		minRange=0.0f;
	)

	DECLARE_FILTER_EX(AbsoluteHealth, 1, unit->health > minHealth,
		float minHealth;
		void SetParam(int index, const std::string& value) {
			minHealth = atof(value.c_str());
		},
		minHealth=0.0f;
	)

	DECLARE_FILTER_EX(RelativeHealth, 1, unit->health / unit->maxHealth > minHealth,
		float minHealth;
		void SetParam(int index, const std::string& value) {
			minHealth = atof(value.c_str()) * 0.01f; // convert from percent
		},
		minHealth=0.0f;
	)

	DECLARE_FILTER_EX(InPrevSel, 0, prevTypes.find(unit->unitDef->id) != prevTypes.end(),
		std::set<int> prevTypes;
		void Prepare() {
			prevTypes.clear();
			const CUnitSet& tu = selectedUnitsHandler.selectedUnits;
			for (CUnitSet::const_iterator si = tu.begin(); si != tu.end(); ++si) {
				prevTypes.insert((*si)->unitDef->id);
			}
		},
	)

	DECLARE_FILTER_EX(NameContain, 1, unit->unitDef->humanName.find(name) != std::string::npos,
		std::string name;
		void SetParam(int index, const std::string& value) {
			name = value;
		},
	)

	DECLARE_FILTER_EX(Category, 1, unit->category == cat,
		unsigned int cat;
		void SetParam(int index, const std::string& value) {
			cat = CCategoryHandler::Instance()->GetCategory(value);
		},
		cat=0;
	)
//FIXME: std::strtof is in C99 which M$ doesn't bother to support.
#ifdef _MSC_VER
	#define STRTOF strtod
#else
	#define STRTOF strtof
#endif

	DECLARE_FILTER_EX(RulesParamEquals, 2, unit->modParamsMap.find(param) != unit->modParamsMap.end() &&
			((wantedValueStr.empty()) ? unit->modParams[unit->modParamsMap.find(param)->second].valueInt == wantedValue
			: unit->modParams[unit->modParamsMap.find(param)->second].valueString == wantedValueStr),
		std::string param;
		float wantedValue;
		std::string wantedValueStr;
		void SetParam(int index, const std::string& value) {
			switch (index) {
				case 0: {
					param = value;
				} break;
				case 1: {
					const char* cstr = value.c_str();
					char* endNumPos = NULL;
					wantedValue = STRTOF(cstr, &endNumPos);
					if (endNumPos == cstr) wantedValueStr = value;
				} break;
			}
		},
		wantedValue=0.0f;
	)

#undef DECLARE_FILTER_EX
#undef DECLARE_FILTER
#undef STRTOF
}



void CSelectionKeyHandler::DoSelection(std::string selectString)
{
	std::list<CUnit*> selection;

//	guicontroller->AddText(selectString.c_str());
	std::string s=ReadToken(selectString);

	if(s=="AllMap"){
		if (!gu->spectatingFullSelect) {
			// team units
			CUnitSet* tu=&teamHandler->Team(gu->myTeam)->units;
			for(CUnitSet::iterator ui=tu->begin();ui!=tu->end();++ui){
				selection.push_back(*ui);
			}
		} else {
			// all units
			std::list<CUnit*>* au=&unitHandler->activeUnits;
			for (std::list<CUnit*>::iterator ui=au->begin();ui!=au->end();++ui){
				selection.push_back(*ui);
			}
		}
	} else if(s=="Visible"){
		if (!gu->spectatingFullSelect) {
			// team units in viewport
			CUnitSet* tu=&teamHandler->Team(gu->myTeam)->units;
			for (CUnitSet::iterator ui=tu->begin();ui!=tu->end();++ui){
				if (camera->InView((*ui)->midPos,(*ui)->radius)){
					selection.push_back(*ui);
				}
			}
		} else {
		  // all units in viewport
			std::list<CUnit*>* au=&unitHandler->activeUnits;
			for (std::list<CUnit*>::iterator ui=au->begin();ui!=au->end();++ui){
				if (camera->InView((*ui)->midPos,(*ui)->radius)){
					selection.push_back(*ui);
				}
			}
		}
	} else if(s=="FromMouse" || s=="FromMouseC"){
		// FromMouse uses distance from a point on the ground,
		// so essentially a selection sphere.
		// FromMouseC uses a cylinder shaped volume for selection,
		// so the heights of the units do not matter.
		const bool cylindrical = (s == "FromMouseC");
		ReadDelimiter(selectString);
		float maxDist=atof(ReadToken(selectString).c_str());

		float dist = CGround::LineGroundCol(camera->GetPos(), camera->GetPos() + mouse->dir * 8000, false);
		float3 mp=camera->GetPos()+mouse->dir*dist;
		if (cylindrical) {
			mp.y = 0;
		}

		if (!gu->spectatingFullSelect) {
		  // team units in mouse range
			CUnitSet* tu=&teamHandler->Team(gu->myTeam)->units;
			for(CUnitSet::iterator ui=tu->begin();ui!=tu->end();++ui){
				float3 up = (*ui)->pos;
				if (cylindrical) {
					up.y = 0;
				}
				if(mp.SqDistance(up) < Square(maxDist)){
					selection.push_back(*ui);
				}
			}
		} else {
		  // all units in mouse range
			std::list<CUnit*>* au=&unitHandler->activeUnits;
			for(std::list<CUnit*>::iterator ui=au->begin();ui!=au->end();++ui){
				float3 up = (*ui)->pos;
				if (cylindrical) {
					up.y = 0;
				}
				if(mp.SqDistance(up)<Square(maxDist)){
					selection.push_back(*ui);
				}
			}
		}
	} else if(s=="PrevSelection"){
		CUnitSet* su=&selectedUnitsHandler.selectedUnits;
		for(CUnitSet::iterator ui=su->begin();ui!=su->end();++ui){
			selection.push_back(*ui);
		}
	} else {
		LOG_L(L_WARNING, "Unknown source token %s", s.c_str());
		return;
	}

	ReadDelimiter(selectString);

	while(true){
		std::string s=ReadDelimiter(selectString);
		if(s=="+")
			break;

		s=ReadToken(selectString);

		bool _not=false;

		if(s=="Not"){
			_not=true;
			ReadDelimiter(selectString);
			s=ReadToken(selectString);
		}

		Filter::Map& filters = Filter::all();
		Filter::Map::iterator f = filters.find(s);

		if (f != filters.end()) {
			f->second->Prepare();
			for (int i = 0; i < f->second->numArgs; ++i) {
				ReadDelimiter(selectString);
				f->second->SetParam(i, ReadToken(selectString));
			}
			std::list<CUnit*>::iterator ui = selection.begin();
			while (ui != selection.end()) {
				if (f->second->ShouldIncludeUnit(*ui) ^ _not) {
					++ui;
				}
				else {
					std::list<CUnit*>::iterator prev = ui++;
					selection.erase(prev);
				}
			}
		}
		else {
			LOG_L(L_WARNING, "Unknown token in filter %s", s.c_str());
			return;
		}
	}

	ReadDelimiter(selectString);
	s=ReadToken(selectString);

	if(s=="ClearSelection"){
		selectedUnitsHandler.ClearSelected();

		ReadDelimiter(selectString);
		s=ReadToken(selectString);
	}

	if(s=="SelectAll"){
		for (std::list<CUnit*>::iterator ui=selection.begin();ui!=selection.end();++ui)
			selectedUnitsHandler.AddUnit(*ui);
	} else if(s=="SelectOne"){
		if(selection.empty())
			return;
		if(++selectNumber>=selection.size())
			selectNumber=0;

		CUnit* sel = NULL;
		int a=0;
		for (std::list<CUnit*>::iterator ui=selection.begin();ui!=selection.end() && a<=selectNumber;++ui,++a)
			sel=*ui;

		if (sel == NULL)
			return;

		selectedUnitsHandler.AddUnit(sel);
		camHandler->CameraTransition(0.8f);
		if(camHandler->GetCurrentControllerNum() != 0){
			camHandler->GetCurrentController().SetPos(sel->pos);
		} else {	//fps camera

			if(camera->rot.x>-1)
				camera->rot.x=-1;

			float3 wantedCamDir;
			wantedCamDir.x=(float)(math::sin(camera->rot.y)*math::cos(camera->rot.x));
			wantedCamDir.y=(float)(math::sin(camera->rot.x));
			wantedCamDir.z=(float)(math::cos(camera->rot.y)*math::cos(camera->rot.x));
			wantedCamDir.ANormalize();

			camHandler->GetCurrentController().SetPos(sel->pos - wantedCamDir*800);
		}
	} else if(s=="SelectNum"){
		ReadDelimiter(selectString);
		int num=atoi(ReadToken(selectString).c_str());

		if(selection.empty())
			return;

		if(selectNumber>=selection.size())
			selectNumber=0;

		std::list<CUnit*>::iterator ui=selection.begin();
		for (int a=0;a<selectNumber;++a)
			++ui;
		for (int a=0;a<num;++ui,++a){
			if(ui==selection.end())
				ui=selection.begin();
			selectedUnitsHandler.AddUnit(*ui);
		}

		selectNumber+=num;
	} else if(s=="SelectPart"){
		ReadDelimiter(selectString);
		float part=atof(ReadToken(selectString).c_str())*0.01f;//convert from percent
		int num=(int)(selection.size()*part);

		if(selection.empty())
			return;

		if(selectNumber>=selection.size())
			selectNumber=0;

		std::list<CUnit*>::iterator ui = selection.begin();
		for (int a = 0; a < selectNumber; ++a)
			++ui;
		for(int a=0;a<num;++ui,++a){
			if(ui==selection.end())
				ui=selection.begin();
			selectedUnitsHandler.AddUnit(*ui);
		}

		selectNumber+=num;
	} else {
		LOG_L(L_WARNING, "Unknown token in conclusion %s", s.c_str());
	}
}