File: CameraHandler.cpp

package info (click to toggle)
spring 103.0%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,720 kB
  • ctags: 63,685
  • sloc: cpp: 368,283; ansic: 33,988; python: 12,417; java: 12,203; awk: 5,879; sh: 1,846; xml: 655; perl: 405; php: 211; objc: 194; makefile: 77; sed: 2
file content (485 lines) | stat: -rw-r--r-- 12,329 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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include <cstdlib>
#include <stdarg.h>

#include "CameraHandler.h"

#include "Action.h"
#include "Camera.h"
#include "Camera/CameraController.h"
#include "Camera/FPSController.h"
#include "Camera/OverheadController.h"
#include "Camera/RotOverheadController.h"
#include "Camera/FreeController.h"
#include "Camera/OverviewController.h"
#include "Camera/SpringController.h"
#include "Players/Player.h"
#include "UI/UnitTracker.h"
#include "Rendering/GlobalRendering.h"
#include "System/myMath.h"
#include "System/Config/ConfigHandler.h"
#include "System/Log/ILog.h"


static std::string strformat(const char* fmt, ...)
{
	char buf[256];
	va_list args;
	va_start(args,fmt);
	VSNPRINTF(buf, sizeof(buf), fmt, args);
	va_end(args);
	return std::string(buf);
}

CONFIG(std::string, CamModeName).defaultValue("");

CONFIG(int, CamMode)
	.defaultValue(CCameraHandler::CAMERA_MODE_SPRING)
	.description(strformat("Defines the used camera. Options are:\n%i = FPS\n%i = Overhead\n%i = Spring\n%i = RotOverhead\n%i = Free\n%i = Overview",
		(int)CCameraHandler::CAMERA_MODE_FIRSTPERSON,
		(int)CCameraHandler::CAMERA_MODE_OVERHEAD,
		(int)CCameraHandler::CAMERA_MODE_SPRING,
		(int)CCameraHandler::CAMERA_MODE_ROTOVERHEAD,
		(int)CCameraHandler::CAMERA_MODE_FREE,
		(int)CCameraHandler::CAMERA_MODE_OVERVIEW
	))
	.minimumValue(0)
	.maximumValue(CCameraHandler::CAMERA_MODE_LAST - 1);

CONFIG(float, CamTimeFactor)
	.defaultValue(1.0f)
	.minimumValue(0.0f)
	.description("Scales the speed of camera transitions, e.g. zooming or position change.");

CONFIG(float, CamTimeExponent)
	.defaultValue(4.0f)
	.minimumValue(0.0f)
	.description("Camera transitions happen at lerp(old, new, timeNorm ^ CamTimeExponent).");


CCameraHandler* camHandler = nullptr;


static void CreateGlobalCams() {
	// create all global cameras
	for (unsigned int i = CCamera::CAMTYPE_PLAYER; i < CCamera::CAMTYPE_ACTIVE; i++) {
		CCamera::SetCamera(i, new CCamera(i));
	}

	CCamera::SetCamera(CCamera::CAMTYPE_ACTIVE, CCamera::GetCamera(CCamera::CAMTYPE_PLAYER));
}

static void RemoveGlobalCams() {
	// remove all global cameras
	for (unsigned int i = CCamera::CAMTYPE_PLAYER; i < CCamera::CAMTYPE_ACTIVE; i++) {
		delete CCamera::GetCamera(i); CCamera::SetCamera(i, nullptr);
	}

	CCamera::SetCamera(CCamera::CAMTYPE_ACTIVE, nullptr);
}


CCameraHandler::CCameraHandler()
{
	CreateGlobalCams();

	camTransState.startFOV  = 90.0f;
	camTransState.timeStart =  0.0f;
	camTransState.timeEnd   =  0.0f;

	// FPS camera must always be the first one in the list
	camControllers.resize(CAMERA_MODE_LAST, nullptr);
	camControllers[CAMERA_MODE_FIRSTPERSON] = new CFPSController();
	camControllers[CAMERA_MODE_OVERHEAD   ] = new COverheadController();
	camControllers[CAMERA_MODE_SPRING     ] = new CSpringController();
	camControllers[CAMERA_MODE_ROTOVERHEAD] = new CRotOverheadController();
	camControllers[CAMERA_MODE_FREE       ] = new CFreeController();
	camControllers[CAMERA_MODE_OVERVIEW   ] = new COverviewController();

	for (unsigned int i = 0; i < camControllers.size(); i++) {
		nameModeMap[camControllers[i]->GetName()] = i;
	}

	const std::string& modeName = configHandler->GetString("CamModeName");

	if (!modeName.empty()) {
		currCamCtrlNum = GetModeIndex(modeName);
	} else {
		currCamCtrlNum = configHandler->GetInt("CamMode");
	}

	camTransState.timeFactor   = configHandler->GetFloat("CamTimeFactor");
	camTransState.timeExponent = configHandler->GetFloat("CamTimeExponent");

	RegisterAction("viewfps");
	RegisterAction("viewta");
	RegisterAction("viewspring");
	RegisterAction("viewrot");
	RegisterAction("viewfree");
	RegisterAction("viewov");
	RegisterAction("viewtaflip");

	RegisterAction("toggleoverview");
	RegisterAction("togglecammode");

	RegisterAction("viewsave");
	RegisterAction("viewload");

	SetCameraMode(currCamCtrlNum);
}


CCameraHandler::~CCameraHandler()
{
	while (!camControllers.empty()) {
		delete camControllers.back();
		camControllers.pop_back();
	}

	RemoveGlobalCams();
}


void CCameraHandler::UpdateController(CPlayer* player, bool fpsMode, bool fsEdgeMove, bool wnEdgeMove)
{
	CCameraController& camCon = GetCurrentController();
	FPSUnitController& fpsCon = player->fpsController;

	const bool fusEdgeMove = ( globalRendering->fullScreen && fsEdgeMove);
	const bool winEdgeMove = (!globalRendering->fullScreen && wnEdgeMove);

	// We have to update transition both before and after updating the controller:
	// before: if the controller makes a new begincam, it needs to take into account previous transitions
	// after: apply changes made by the controller with 0 time transition.
	UpdateTransition();

	if (fpsCon.oldDCpos != ZeroVector) {
		camCon.SetPos(fpsCon.oldDCpos);
		fpsCon.oldDCpos = ZeroVector;
	}

	if (!fpsMode)
		UpdateController(camCon, true, true, fusEdgeMove || winEdgeMove);

	camCon.Update();

	UpdateTransition();
}

void CCameraHandler::UpdateController(CCameraController& camCon, bool keyMove, bool wheelMove, bool edgeMove)
{
	if (keyMove) {
		// NOTE: z-component contains speed scaling factor, xy is movement
		const float3 camMoveVector = camera->GetMoveVectorFromState(true);

		// key scrolling
		if ((camMoveVector * XYVector).SqLength() > 0.0f) {
			if (camCon.DisableTrackingByKey())
				unitTracker.Disable();

			camCon.KeyMove(camMoveVector);
		}
	}

	if (edgeMove) {
		const float3 camMoveVector = camera->GetMoveVectorFromState(false);

		// screen edge scrolling
		if ((camMoveVector * XYVector).SqLength() > 0.0f) {
			unitTracker.Disable();
			camCon.ScreenEdgeMove(camMoveVector);
		}
	}

	if (wheelMove) {
		// mouse wheel zoom
		float mouseWheelDist = 0.0f;
		mouseWheelDist +=  float(camera->GetMovState()[CCamera::MOVE_STATE_UP]);
		mouseWheelDist += -float(camera->GetMovState()[CCamera::MOVE_STATE_DWN]);
		mouseWheelDist *= 0.2f * globalRendering->lastFrameTime;

		if (mouseWheelDist == 0.0f)
			return;

		camCon.MouseWheelMove(mouseWheelDist);
	}
}


void CCameraHandler::CameraTransition(float nsecs)
{
	nsecs = std::max(nsecs, 0.0f) * camTransState.timeFactor;

	// calculate when transition should end based on duration in seconds
	camTransState.timeStart = globalRendering->lastFrameStart.toMilliSecsf();
	camTransState.timeEnd   = camTransState.timeStart + nsecs * 1000.0f;

	camTransState.startPos = camera->GetPos();
	camTransState.startRot = camera->GetRot();
	camTransState.startFOV = camera->GetVFOV();
}

void CCameraHandler::UpdateTransition()
{
	camTransState.tweenPos = camControllers[currCamCtrlNum]->GetPos();
	camTransState.tweenRot = camControllers[currCamCtrlNum]->GetRot();
	camTransState.tweenFOV = camControllers[currCamCtrlNum]->GetFOV();

	const float transTime = globalRendering->lastFrameStart.toMilliSecsf();

	if (transTime >= camTransState.timeEnd) {
		camera->SetPos(camTransState.tweenPos);
		camera->SetRot(camTransState.tweenRot);
		camera->SetVFOV(camTransState.tweenFOV);
		camera->Update();
		return;
	}

	if (camTransState.timeEnd <= camTransState.timeStart)
		return;

	const float timeRatio = (camTransState.timeEnd - transTime) / (camTransState.timeEnd - camTransState.timeStart);
	const float tweenFact = 1.0f - math::pow(timeRatio, camTransState.timeExponent);

	camera->SetPos(mix(camTransState.startPos, camTransState.tweenPos, tweenFact));
	camera->SetRot(mix(camTransState.startRot, camTransState.tweenRot, tweenFact));
	camera->SetVFOV(mix(camTransState.startFOV, camTransState.tweenFOV, tweenFact));
	camera->Update();
}


void CCameraHandler::SetCameraMode(unsigned int newMode)
{
	if ((newMode >= camControllers.size()) || (newMode == currCamCtrlNum))
		return;

	CameraTransition(1.0f);

	const unsigned int oldMode = currCamCtrlNum;

	CCameraController* oldCamCtrl = camControllers[currCamCtrlNum          ];
	CCameraController* newCamCtrl = camControllers[currCamCtrlNum = newMode];

	newCamCtrl->SetPos(oldCamCtrl->SwitchFrom());
	newCamCtrl->SwitchTo(oldMode);
	newCamCtrl->Update();
}

void CCameraHandler::SetCameraMode(const std::string& modeName)
{
	const int modeNum = GetModeIndex(modeName);

	// do nothing if the name is not matched
	if (modeNum >= 0) {
		SetCameraMode(modeNum);
	}
}


int CCameraHandler::GetModeIndex(const std::string& name) const
{
	const auto it = nameModeMap.find(name);

	if (it != nameModeMap.end())
		return it->second;

	return -1;
}


void CCameraHandler::PushMode()
{
	controllerStack.push_back(GetCurrentControllerNum());
}

void CCameraHandler::PopMode()
{
	if (controllerStack.empty())
		return;

	SetCameraMode(controllerStack.back());
	controllerStack.pop_back();
}


void CCameraHandler::ToggleState()
{
	unsigned int newMode = (currCamCtrlNum + 1) % camControllers.size();
	unsigned int numTries = 0;

	const unsigned int maxTries = camControllers.size() - 1;

	while ((numTries++ < maxTries) && !camControllers[newMode]->enabled) {
		newMode = (newMode + 1) % camControllers.size();
	}

	SetCameraMode(newMode);
}


void CCameraHandler::ToggleOverviewCamera()
{
	CameraTransition(1.0f);

	if (controllerStack.empty()) {
		PushMode();
		SetCameraMode(CAMERA_MODE_OVERVIEW);
	} else {
		PopMode();
	}
}


void CCameraHandler::SaveView(const std::string& name)
{
	if (name.empty())
		return;

	ViewData& vd = viewDataMap[name];
	vd["mode"] = currCamCtrlNum;

	camControllers[currCamCtrlNum]->GetState(vd);
	return;
}

bool CCameraHandler::LoadView(const std::string& name)
{
	if (name.empty())
		return false;

	const auto it = viewDataMap.find(name);

	if (it == viewDataMap.end())
		return false;

	const ViewData& saved = it->second;

	ViewData current;
	GetState(current);

	if (saved == current) {
		// load a view twice to return to old settings
		// safety: should not happen, but who knows?
		if (name != "__old_view")
			return LoadView("__old_view");

		return false;
	}

	if (name != "__old_view")
		SaveView("__old_view");

	return LoadViewData(saved);
}


void CCameraHandler::GetState(CCameraController::StateMap& sm) const
{
	sm.clear();
	sm["mode"] = currCamCtrlNum;

	camControllers[currCamCtrlNum]->GetState(sm);
}


bool CCameraHandler::SetState(const CCameraController::StateMap& sm)
{
	const auto it = sm.find("mode");

	if (it != sm.end()) {
		const unsigned int camMode = it->second;
		const unsigned int oldMode = currCamCtrlNum;

		if (camMode >= camControllers.size())
			return false;

		if (camMode != currCamCtrlNum) {
			camControllers[currCamCtrlNum = camMode]->SwitchTo(oldMode);
		}
	}

	const bool result = camControllers[currCamCtrlNum]->SetState(sm);
	camControllers[currCamCtrlNum]->Update();
	return result;
}


void CCameraHandler::PushAction(const Action& action)
{
	const std::string cmd = action.command;

	if (cmd == "viewfps") {
		SetCameraMode(CAMERA_MODE_FIRSTPERSON);
	}
	else if (cmd == "viewta") {
		SetCameraMode(CAMERA_MODE_OVERHEAD);
	}
	else if (cmd == "viewspring") {
		SetCameraMode(CAMERA_MODE_SPRING);
	}
	else if (cmd == "viewrot") {
		SetCameraMode(CAMERA_MODE_ROTOVERHEAD);
	}
	else if (cmd == "viewfree") {
		SetCameraMode(CAMERA_MODE_FREE);
	}
	else if (cmd == "viewov") {
		SetCameraMode(CAMERA_MODE_OVERVIEW);
	}

	else if (cmd == "viewtaflip") {
		COverheadController* taCam = dynamic_cast<COverheadController*>(camControllers[CAMERA_MODE_OVERHEAD]);

		if (taCam) {
			if (!action.extra.empty()) {
				taCam->flipped = !!atoi(action.extra.c_str());
			} else {
				taCam->flipped = !taCam->flipped;
			}
			taCam->Update();
		}
	}
	else if (cmd == "viewsave") {
		if (!action.extra.empty()) {
			SaveView(action.extra);
			LOG("Saved view: %s", action.extra.c_str());
		}
	}
	else if (cmd == "viewload") {
		if (!LoadView(action.extra)) {
			LOG_L(L_WARNING, "Loading view failed!");
		}
	}
	else if (cmd == "toggleoverview") {
		ToggleOverviewCamera();
	}
	else if (cmd == "togglecammode") {
		ToggleState();
	}
}


bool CCameraHandler::LoadViewData(const ViewData& vd)
{
	if (vd.empty())
		return false;

	const auto it = vd.find("mode");

	if (it != vd.end()) {
		const unsigned int camMode = it->second;
		const unsigned int curMode = currCamCtrlNum;

		if (camMode >= camControllers.size())
			return false;

		if (camMode != currCamCtrlNum) {
			CameraTransition(1.0f);
			camControllers[currCamCtrlNum = camMode]->SwitchTo(curMode, camMode != curMode);
		}
	}

	return camControllers[currCamCtrlNum]->SetState(vd);
}