File: AAirMoveType.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 (417 lines) | stat: -rw-r--r-- 11,805 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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "AAirMoveType.h"
#include "MoveMath/MoveMath.h"

#include "Map/Ground.h"
#include "Map/MapInfo.h"
#include "Sim/Misc/GlobalSynced.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Units/Unit.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/Scripts/UnitScript.h"

CR_BIND_DERIVED_INTERFACE(AAirMoveType, AMoveType)

CR_REG_METADATA(AAirMoveType, (
	CR_ENUM_MEMBER(aircraftState),
	CR_ENUM_MEMBER(padStatus),

	CR_MEMBER(oldGoalPos),
	CR_MEMBER(reservedLandingPos),

	CR_MEMBER(wantedHeight),
	CR_MEMBER(orgWantedHeight),

	CR_MEMBER(accRate),
	CR_MEMBER(decRate),
	CR_MEMBER(altitudeRate),

	CR_MEMBER(collide),
	CR_MEMBER(useSmoothMesh),
	CR_MEMBER(autoLand),

	CR_MEMBER(lastColWarning),
	CR_MEMBER(reservedPad),

	CR_MEMBER(lastColWarningType),
	CR_MEMBER(lastFuelUpdateFrame)
))

AAirMoveType::AAirMoveType(CUnit* unit):
	AMoveType(unit),
	aircraftState(AIRCRAFT_LANDED),
	padStatus(PAD_STATUS_FLYING),

	oldGoalPos((unit != NULL)? unit->pos : ZeroVector),
	reservedLandingPos(-1.0f, -1.0f, -1.0f),

	wantedHeight(80.0f),
	orgWantedHeight(0.0f),

	accRate(1.0f),
	decRate(1.0f),
	altitudeRate(3.0f),

	collide(true),
	useSmoothMesh(false),
	autoLand(true),

	lastColWarning(NULL),
	reservedPad(NULL),

	lastColWarningType(0),
	lastFuelUpdateFrame(gs->frameNum)
{
	// same as {Ground, HoverAir}MoveType::accRate
	accRate = std::max(0.01f, unit->unitDef->maxAcc);
	decRate = std::max(0.01f, unit->unitDef->maxDec);
	altitudeRate = std::max(0.01f, unit->unitDef->verticalSpeed);

	useHeading = false;
}

AAirMoveType::~AAirMoveType()
{
	// NOTE:
	//   this calls Takeoff and (indirectly) SetState,
	//   so neither of these must be pure virtuals (!)
	UnreservePad(reservedPad);
}

bool AAirMoveType::UseSmoothMesh() const {
	if (!useSmoothMesh)
		return false;

	const bool onTransportMission =
		!owner->commandAI->commandQue.empty() &&
		((owner->commandAI->commandQue.front().GetID() == CMD_LOAD_UNITS) || (owner->commandAI->commandQue.front().GetID() == CMD_UNLOAD_UNIT));
	const bool repairing = reservedPad ? padStatus >= PAD_STATUS_LANDING : false;
	const bool forceDisableSmooth = repairing || onTransportMission || (aircraftState != AIRCRAFT_FLYING);
	return !forceDisableSmooth;
}


void AAirMoveType::ReservePad(CAirBaseHandler::LandingPad* lp) {
	oldGoalPos = goalPos;
	orgWantedHeight = wantedHeight;

	assert(reservedPad == NULL);

	AddDeathDependence(lp, DEPENDENCE_LANDINGPAD);
	SetGoal(lp->GetUnit()->pos);

	reservedPad = lp;
	padStatus = PAD_STATUS_FLYING;

	Takeoff();
}

void AAirMoveType::UnreservePad(CAirBaseHandler::LandingPad* lp)
{
	if (lp == NULL)
		return;

	assert(reservedPad == lp);

	DeleteDeathDependence(reservedPad, DEPENDENCE_LANDINGPAD);
	airBaseHandler->LeaveLandingPad(reservedPad);

	reservedPad = NULL;
	padStatus = PAD_STATUS_FLYING;

	goalPos = oldGoalPos;
	wantedHeight = orgWantedHeight;
	SetState(AIRCRAFT_TAKEOFF);
}

void AAirMoveType::DependentDied(CObject* o) {
	if (o == lastColWarning) {
		lastColWarning = NULL;
		lastColWarningType = 0;
	}

	if (o == reservedPad) {
		if (aircraftState != AIRCRAFT_CRASHING) {
			// change state only if not crashing
			SetState(AIRCRAFT_TAKEOFF);

			goalPos = oldGoalPos;
			wantedHeight = orgWantedHeight;
			padStatus = PAD_STATUS_FLYING;
		}
		reservedPad = NULL;
	}
}

bool AAirMoveType::Update() {
	// NOTE: useHeading is never true by default for aircraft (AAirMoveType
	// forces it to false, TransportUnit::{Attach,Detach}Unit manipulate it
	// specifically for HoverAirMoveType's)
	if (useHeading) {
		SetState(AIRCRAFT_TAKEOFF);
	}

	if (owner->beingBuilt) {
		// while being built, MoveType::SlowUpdate is not
		// called so UpdateFuel will not be either --> do
		// it here to prevent a drop in fuel level as soon
		// as unit finishes construction
		UpdateFuel(false);
	}

	// this return value is never used
	return (useHeading = false);
}

void AAirMoveType::UpdateLanded()
{
	// while an aircraft is being built we do not adjust its
	// position, because the builder might be a tall platform
	// we also do nothing if the aircraft is preparing to land
	// or has already landed on a repair-pad
	if (owner->beingBuilt)
		return;
	if (padStatus != PAD_STATUS_FLYING)
		return;

	// when an aircraft transitions to the landed state it
	// is on the ground, but the terrain can be raised (or
	// lowered) later and we do not want to end up hovering
	// in mid-air or sink below it
	// let gravity do the job instead of teleporting
	const float minHeight = owner->unitDef->canSubmerge?
		CGround::GetHeightReal(owner->pos.x, owner->pos.z):
		CGround::GetHeightAboveWater(owner->pos.x, owner->pos.z);
	const float curHeight = owner->pos.y;

	if (curHeight > minHeight) {
		if (curHeight > 0.0f) {
			owner->speed.y += mapInfo->map.gravity;
		} else {
			owner->speed.y = mapInfo->map.gravity;
		}
	} else {
		owner->speed.y = 0.0f;
	}

	owner->SetVelocityAndSpeed(owner->speed + owner->GetDragAccelerationVec(float4(0.0f, 0.0f, 0.0f, 0.1f)));
	owner->Move(UpVector * (std::max(curHeight, minHeight) - owner->pos.y), true);
	owner->Move(owner->speed, true);
	// match the terrain normal
	owner->UpdateDirVectors(owner->IsOnGround());
	owner->UpdateMidAndAimPos();
}

void AAirMoveType::UpdateFuel(bool slowUpdate) {
	if (owner->unitDef->maxFuel <= 0.0f)
		return;

	// lastFuelUpdateFrame must be updated even when early-outing
	// otherwise fuel level will jump after a period of not using
	// any (eg. when on a pad or after being built)
	if (!slowUpdate) {
		lastFuelUpdateFrame = gs->frameNum;
		return;
	}
	if (aircraftState == AIRCRAFT_LANDED) {
		lastFuelUpdateFrame = gs->frameNum;
		return;
	}
	if (padStatus == PAD_STATUS_ARRIVED) {
		lastFuelUpdateFrame = gs->frameNum;
		return;
	}

	owner->currentFuel = std::max(0.0f, owner->currentFuel - (float(gs->frameNum - lastFuelUpdateFrame) / GAME_SPEED));
	lastFuelUpdateFrame = gs->frameNum;
}



void AAirMoveType::CheckForCollision()
{
	if (!collide)
		return;

	const SyncedFloat3& pos = owner->midPos;
	const SyncedFloat3& forward = owner->frontdir;

	const float3 midTestPos = pos + forward * 121.0f;
	const std::vector<CUnit*>& others = quadField->GetUnitsExact(midTestPos, 115.0f);

	float dist = 200.0f;

	if (lastColWarning) {
		DeleteDeathDependence(lastColWarning, DEPENDENCE_LASTCOLWARN);
		lastColWarning = NULL;
		lastColWarningType = 0;
	}

	for (std::vector<CUnit*>::const_iterator ui = others.begin(); ui != others.end(); ++ui) {
		const CUnit* unit = *ui;

		if (unit == owner || !unit->unitDef->canfly) {
			continue;
		}

		const SyncedFloat3& op = unit->midPos;
		const float3 dif = op - pos;
		const float3 forwardDif = forward * (forward.dot(dif));

		if (forwardDif.SqLength() >= (dist * dist)) {
			continue;
		}

		const float3 ortoDif = dif - forwardDif;
		const float frontLength = forwardDif.Length();
		// note: radii are multiplied by two
		const float minOrtoDif = (unit->radius + owner->radius) * 2.0f + frontLength * 0.1f + 10;

		if (ortoDif.SqLength() < (minOrtoDif * minOrtoDif)) {
			dist = frontLength;
			lastColWarning = const_cast<CUnit*>(unit);
		}
	}

	if (lastColWarning != NULL) {
		lastColWarningType = 2;
		AddDeathDependence(lastColWarning, DEPENDENCE_LASTCOLWARN);
		return;
	}

	for (std::vector<CUnit*>::const_iterator ui = others.begin(); ui != others.end(); ++ui) {
		if (*ui == owner)
			continue;
		if (((*ui)->midPos - pos).SqLength() < (dist * dist)) {
			lastColWarning = *ui;
		}
	}

	if (lastColWarning != NULL) {
		lastColWarningType = 1;
		AddDeathDependence(lastColWarning, DEPENDENCE_LASTCOLWARN);
	}
}


bool AAirMoveType::CanLandOnPad(const float3& padPos) const {
	// once distance to pad becomes smaller than current braking distance, switch states
	// (but do not allow state-switch until the aircraft is heading ~directly toward pad)
	// braking distance is 0.5*a*t*t where t is v/a --> 0.5*a*((v*v)/(a*a)) --> 0.5*v*v*(1/a)
	// FIXME:
	//   apply N-frame lookahead when deciding to switch state for strafing aircraft
	//   (see comments in StrafeAirMoveType::UpdateLanding, overshooting prevention)
	//   the lookahead is roughly based on the time to descend to pad-target altitude
	const float3 flatFrontDir = (float3(owner->frontdir)).Normalize2D();

	const float brakingDistSq = Square(0.5f * owner->speed.SqLength2D() / decRate);
	const float descendDistSq = Square(maxSpeed * ((owner->pos.y - padPos.y) / altitudeRate)) * owner->unitDef->IsStrafingAirUnit();

	if (padPos.SqDistance2D(owner->pos) > std::max(brakingDistSq, descendDistSq))
		return false;

	if (owner->unitDef->IsStrafingAirUnit()) {
		// horizontal guide
		if (flatFrontDir.dot((padPos - owner->pos).SafeNormalize2D()) < 0.985f)
			return false;
		// vertical guide
		if (flatFrontDir.dot((padPos - owner->pos).SafeNormalize()) < 0.707f)
			return false;
	}

	return true;
}

bool AAirMoveType::HaveLandedOnPad(const float3& padPos) {
	const AircraftState landingState = GetLandingState();
	const float landingPadHeight = CGround::GetHeightAboveWater(padPos.x, padPos.z);

	reservedLandingPos = padPos;
	wantedHeight = padPos.y - landingPadHeight;

	const float3 padVector = (padPos - owner->pos).SafeNormalize2D();
	const float curOwnerAltitude = (owner->pos.y - landingPadHeight);
	const float minOwnerAltitude = (wantedHeight + 1.0f);

	if (aircraftState != landingState)
		SetState(landingState);
	if (aircraftState == AIRCRAFT_LANDED)
		return true;

	if (curOwnerAltitude <= minOwnerAltitude) {
		// deal with overshooting aircraft: "tractor" them in
		// once they descend down to the landing pad altitude
		// this is a no-op for HAMT planes which do not apply
		// speed updates at this point
		owner->SetVelocityAndSpeed((owner->speed + (padVector * accRate)) * XZVector);
	}

	if (Square(owner->rightdir.y) < 0.01f && owner->frontdir.dot(padVector) > 0.01f) {
		owner->frontdir = padVector;
		owner->rightdir = owner->frontdir.cross(UpVector);
		owner->updir    = owner->rightdir.cross(owner->frontdir);

		owner->SetHeadingFromDirection();
	}

	if (curOwnerAltitude > minOwnerAltitude)
		return false;

	return ((owner->pos.SqDistance2D(padPos) <= 1.0f || owner->unitDef->IsHoveringAirUnit()));
}

bool AAirMoveType::MoveToRepairPad() {
	CUnit* airBase = reservedPad->GetUnit();

	if (airBase->beingBuilt || airBase->IsStunned()) {
		// pad became inoperable after being reserved
		DependentDied(airBase);
		return false;
	} else {
		const float3& relPadPos = airBase->script->GetPiecePos(reservedPad->GetPiece());
		const float3 absPadPos = airBase->GetObjectSpacePos(relPadPos);

		switch (padStatus) {
			case PAD_STATUS_FLYING: {
				// flying toward pad
				if (aircraftState != AIRCRAFT_FLYING && aircraftState != AIRCRAFT_TAKEOFF) {
					SetState(AIRCRAFT_FLYING);
				}

				if (CanLandOnPad(goalPos = absPadPos)) {
					padStatus = PAD_STATUS_LANDING;
				}
			} break;

			case PAD_STATUS_LANDING: {
				// landing on pad
				if (HaveLandedOnPad(goalPos = absPadPos)) {
					padStatus = PAD_STATUS_ARRIVED;
				}
			} break;

			case PAD_STATUS_ARRIVED: {
				if (aircraftState != AIRCRAFT_LANDED) {
					SetState(AIRCRAFT_LANDED);
				}

				owner->SetVelocityAndSpeed(ZeroVector);
				owner->Move(absPadPos, false);
				owner->UpdateMidAndAimPos(); // needed here?
				owner->AddBuildPower(airBase, airBase->unitDef->buildSpeed / GAME_SPEED);

				owner->currentFuel += (owner->unitDef->maxFuel / (GAME_SPEED * owner->unitDef->refuelTime));
				owner->currentFuel = std::min(owner->unitDef->maxFuel, owner->currentFuel);

				if (owner->health >= owner->maxHealth - 1.0f && owner->currentFuel >= owner->unitDef->maxFuel) {
					// repaired and filled up, leave the pad
					UnreservePad(reservedPad);
				}
			} break;
		}
	}

	return true;
}