summaryrefslogtreecommitdiff
path: root/sim/src/TurretControl.cpp
blob: 51f2a4611800c827492bc5fd1433f1a654f4ef75 (plain)
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
#include <kurator/sim/TurretControl.h>

#include <kurator/sim/components.h>
#include <kurator/sim/FloatingMovement.h>
#include <kurator/sim/HitPoints.h>
#include <kurator/sim/events.h>
#include <kurator/sim/State.h>
#include <kurator/universe/TurretType.h>


namespace kurator
{
namespace sim
{


bool consume(float& dt, double& target);


void
TurretControl::update(State& ctx)
{
	auto view = ctx.registry.view<TurretControl, universe::TurretType>();
	for (auto&& [entity, control, def] : view.each()) {
		if (!ctx.registry.valid(control.owner)) {
			ctx.registry.destroy(entity);
			continue;
		}
		if (!ctx.registry.all_of<AIState, Transform>(control.owner))
			continue;
		const auto& [state, transform] = ctx.registry.get<AIState, Transform>(control.owner);
		if (!ctx.registry.valid(state.target))
			continue;
		const auto& target = ctx.registry.get<Transform>(state.target);
		const auto distance = transform.position.distance(target.position);
		if (distance > def.effective_range())
			continue;
		auto remaining_dt = ctx.clock.dt;
		while (remaining_dt > 0.0) {
			if (control.rounds < 1 && consume(remaining_dt, control.reload))
				control.rounds = def.rounds;
			if (control.rounds > 0 && consume(remaining_dt, control.delay)) {
				auto& target_points = ctx.registry.get<HitPoints>(state.target);
				const auto& movement = ctx.registry.get<FloatingMovement>(state.target);
				auto damage = def.effective_damage(distance, movement.speed.magnitude());
				if (damage > 0.0) {
					damage = target_points.deal(damage);
					ctx.dispatcher.trigger(Hit{damage, control.owner, state.target});
				}
				control.delay = def.rate_of_fire;
				if (--control.rounds < 1)
					control.reload = def.reload;
			}
		}
	}
}


bool
consume(float& dt, double& target)
{
	if (target <= 0.0)
		return true;
	const auto _dt = dt;
	dt -= target;
	target -= _dt;
	return target <= 0.0;
}


}  // namespace sim
}  // namespace kurator