]> git.localhorst.tv Git - blobs.git/blob - src/creature/goal.cpp
"look around" activity
[blobs.git] / src / creature / goal.cpp
1 #include "AttackGoal.hpp"
2 #include "BlobBackgroundTask.hpp"
3 #include "Goal.hpp"
4 #include "IdleGoal.hpp"
5 #include "IngestGoal.hpp"
6 #include "LocateResourceGoal.hpp"
7 #include "LookAroundGoal.hpp"
8 #include "StrollGoal.hpp"
9
10 #include "Creature.hpp"
11 #include "../app/Assets.hpp"
12 #include "../math/const.hpp"
13 #include "../ui/string.hpp"
14 #include "../world/Planet.hpp"
15 #include "../world/Resource.hpp"
16 #include "../world/Simulation.hpp"
17 #include "../world/TileType.hpp"
18
19 #include <cstring>
20 #include <iostream>
21 #include <sstream>
22 #include <glm/gtx/io.hpp>
23 #include <glm/gtx/rotate_vector.hpp>
24
25
26 namespace blobs {
27 namespace creature {
28
29 AttackGoal::AttackGoal(Creature &self, Creature &target)
30 : Goal(self)
31 , target(target)
32 , damage_target(0.25)
33 , damage_dealt(0.0)
34 , cooldown(0.0) {
35 }
36
37 AttackGoal::~AttackGoal() {
38 }
39
40 std::string AttackGoal::Describe() const {
41         return "attack " + target.Name();
42 }
43
44 void AttackGoal::Tick(double dt) {
45         cooldown -= dt;
46 }
47
48 void AttackGoal::Action() {
49         if (target.Dead() || !GetCreature().PerceptionTest(target.GetSituation().Position())) {
50                 SetComplete();
51                 return;
52         }
53         const glm::dvec3 diff(GetSituation().Position() - target.GetSituation().Position());
54         const double hit_range = GetCreature().Size() * 0.5 * GetCreature().DexertyFactor();
55         const double hit_dist = hit_range + (0.5 * GetCreature().Size()) + 0.5 * (target.Size());
56         if (GetStats().Damage().Critical()) {
57                 // flee
58                 GetSteering().Pass(diff * 5.0);
59                 GetSteering().DontSeparate();
60                 GetSteering().Haste(1.0);
61         } else if (glm::length2(diff) > hit_dist * hit_dist) {
62                 // full throttle chase
63                 GetSteering().Pass(target.GetSituation().Position());
64                 GetSteering().DontSeparate();
65                 GetSteering().Haste(1.0);
66         } else {
67                 // attack
68                 GetSteering().Halt();
69                 GetSteering().DontSeparate();
70                 GetSteering().Haste(1.0);
71                 if (cooldown <= 0.0) {
72                         constexpr double impulse = 0.05;
73                         const double force = GetCreature().Strength();
74                         const double damage =
75                                 force * impulse
76                                 * (GetCreature().GetComposition().TotalDensity() / target.GetComposition().TotalDensity())
77                                 * (GetCreature().Mass() / target.Mass())
78                                 / target.Mass();
79                         GetCreature().DoWork(force * impulse * glm::length(diff));
80                         target.Hurt(damage);
81                         target.GetSituation().Accelerate(glm::normalize(diff) * force * -impulse);
82                         damage_dealt += damage;
83                         if (damage_dealt >= damage_target || target.Dead()) {
84                                 SetComplete();
85                                 if (target.Dead()) {
86                                         GetCreature().GetSimulation().Log() << GetCreature().Name()
87                                                 << " killed " << target.Name() << std::endl;
88                                 }
89                         }
90                         cooldown = 1.0 + (4.0 * (1.0 - GetCreature().DexertyFactor()));
91                 }
92         }
93 }
94
95 void AttackGoal::OnBackground() {
96         // abort if something more important comes up
97         SetComplete();
98 }
99
100
101 BlobBackgroundTask::BlobBackgroundTask(Creature &c)
102 : Goal(c)
103 , breathing(false)
104 , drink_subtask(nullptr)
105 , eat_subtask(nullptr) {
106 }
107
108 BlobBackgroundTask::~BlobBackgroundTask() {
109 }
110
111 std::string BlobBackgroundTask::Describe() const {
112         return "being a blob";
113 }
114
115 void BlobBackgroundTask::Tick(double dt) {
116         if (breathing) {
117                 // TODO: derive breathing ability
118                 int gas = Assets().data.resources["air"].id;
119                 // TODO: check if in compatible atmosphere
120                 double amount = GetStats().Breath().gain * -(1.0 + GetCreature().ExhaustionFactor());
121                 GetStats().Breath().Add(amount * dt);
122                 // maintain ~1% gas composition
123                 double gas_amount = GetCreature().GetComposition().Get(gas);
124                 if (gas_amount < GetCreature().GetComposition().TotalMass() * 0.01) {
125                         double add = std::min(GetCreature().GetComposition().TotalMass() * 0.025 - gas_amount, -amount * dt);
126                         GetCreature().Ingest(gas, add);
127                 }
128                 if (GetStats().Breath().Empty()) {
129                         breathing = false;
130                 }
131         }
132 }
133
134 void BlobBackgroundTask::Action() {
135         CheckStats();
136         CheckSplit();
137         CheckMutate();
138 }
139
140 void BlobBackgroundTask::CheckStats() {
141         Creature::Stats &stats = GetStats();
142
143         if (!breathing && stats.Breath().Bad()) {
144                 breathing = true;
145         }
146
147         if (!drink_subtask && stats.Thirst().Bad()) {
148                 drink_subtask = new IngestGoal(GetCreature(), stats.Thirst());
149                 for (const auto &cmp : GetCreature().GetComposition()) {
150                         if (Assets().data.resources[cmp.resource].state == world::Resource::LIQUID) {
151                                 double value = cmp.value / GetCreature().GetComposition().TotalMass();
152                                 drink_subtask->Accept(cmp.resource, value);
153                                 for (const auto &compat : Assets().data.resources[cmp.resource].compatibility) {
154                                         if (Assets().data.resources[compat.first].state == world::Resource::LIQUID) {
155                                                 drink_subtask->Accept(compat.first, value * compat.second);
156                                         }
157                                 }
158                         }
159                 }
160                 drink_subtask->WhenComplete([&](Goal &) { drink_subtask = nullptr; });
161                 GetCreature().AddGoal(std::unique_ptr<Goal>(drink_subtask));
162         }
163
164         if (!eat_subtask && stats.Hunger().Bad()) {
165                 eat_subtask = new IngestGoal(GetCreature(), stats.Hunger());
166                 for (const auto &cmp : GetCreature().GetComposition()) {
167                         if (Assets().data.resources[cmp.resource].state == world::Resource::SOLID) {
168                                 double value = cmp.value / GetCreature().GetComposition().TotalMass();
169                                 eat_subtask->Accept(cmp.resource, value);
170                                 for (const auto &compat : Assets().data.resources[cmp.resource].compatibility) {
171                                         if (Assets().data.resources[compat.first].state == world::Resource::SOLID) {
172                                                 eat_subtask->Accept(compat.first, value * compat.second);
173                                         }
174                                 }
175                         }
176                 }
177                 eat_subtask->WhenComplete([&](Goal &) { eat_subtask = nullptr; });
178                 GetCreature().AddGoal(std::unique_ptr<Goal>(eat_subtask));
179         }
180 }
181
182 void BlobBackgroundTask::CheckSplit() {
183         if (GetCreature().Mass() > GetCreature().OffspringMass() * 2.0
184                 && GetCreature().OffspringChance() > Random().UNorm()) {
185                 GetCreature().GetSimulation().Log() << GetCreature().Name() << " split" << std::endl;
186                 Split(GetCreature());
187                 return;
188         }
189 }
190
191 void BlobBackgroundTask::CheckMutate() {
192         // check for random property mutation
193         if (GetCreature().MutateChance() > Random().UNorm()) {
194                 double amount = 1.0 + (Random().SNorm() * 0.05);
195                 math::Distribution &d = GetCreature().GetGenome().properties.props[Random().UInt(9)];
196                 if (Random().UNorm() < 0.5) {
197                         d.Mean(d.Mean() * amount);
198                 } else {
199                         d.StandardDeviation(d.StandardDeviation() * amount);
200                 }
201         }
202 }
203
204
205 Goal::Goal(Creature &c)
206 : c(c)
207 , on_complete()
208 , on_foreground()
209 , on_background()
210 , urgency(0.0)
211 , interruptible(true)
212 , complete(false) {
213 }
214
215 Goal::~Goal() noexcept {
216 }
217
218 app::Assets &Goal::Assets() noexcept {
219         return c.GetSimulation().Assets();
220 }
221
222 const app::Assets &Goal::Assets() const noexcept {
223         return c.GetSimulation().Assets();
224 }
225
226 math::GaloisLFSR &Goal::Random() noexcept {
227         return Assets().random;
228 }
229
230 void Goal::SetComplete() {
231         if (!complete) {
232                 complete = true;
233                 OnComplete();
234                 if (on_complete) {
235                         on_complete(*this);
236                 }
237         }
238 }
239
240 void Goal::SetForeground() {
241         OnForeground();
242         if (on_foreground) {
243                 on_foreground(*this);
244         }
245 }
246
247 void Goal::SetBackground() {
248         OnBackground();
249         if (on_background) {
250                 on_background(*this);
251         }
252 }
253
254 void Goal::WhenComplete(std::function<void(Goal &)> cb) noexcept {
255         on_complete = cb;
256         if (complete) {
257                 on_complete(*this);
258         }
259 }
260
261 void Goal::WhenForeground(std::function<void(Goal &)> cb) noexcept {
262         on_foreground = cb;
263 }
264
265 void Goal::WhenBackground(std::function<void(Goal &)> cb) noexcept {
266         on_background = cb;
267 }
268
269
270 IdleGoal::IdleGoal(Creature &c)
271 : Goal(c) {
272         Urgency(-1.0);
273         Interruptible(true);
274 }
275
276 IdleGoal::~IdleGoal() {
277 }
278
279 std::string IdleGoal::Describe() const {
280         return "idle";
281 }
282
283 void IdleGoal::Action() {
284         // when in bad shape, don't make much effort
285         if (GetStats().Damage().Bad() || GetStats().Exhaustion().Bad() || GetStats().Fatigue().Critical()) {
286                 GetSteering().DontSeparate();
287         } else {
288                 GetSteering().ResumeSeparate();
289         }
290
291         // use boredom as chance per 15s
292         if (Random().UNorm() < GetStats().Boredom().value * (1.0 / 900.0)) {
293                 PickActivity();
294         }
295 }
296
297 void IdleGoal::PickActivity() {
298         int n = Random().UInt(2);
299         if (n == 0) {
300                 GetCreature().AddGoal(std::unique_ptr<Goal>(new StrollGoal(GetCreature())));
301         } else {
302                 GetCreature().AddGoal(std::unique_ptr<Goal>(new LookAroundGoal(GetCreature())));
303         }
304 }
305
306
307 namespace {
308
309 std::string summarize(const Composition &comp, const app::Assets &assets) {
310         std::stringstream s;
311         bool first = true;
312         for (const auto &c : comp) {
313                 if (first) {
314                         first = false;
315                 } else {
316                         s << " or ";
317                 }
318                 s << assets.data.resources[c.resource].label;
319         }
320         return s.str();
321 }
322
323 }
324
325 IngestGoal::IngestGoal(Creature &c, Creature::Stat &stat)
326 : Goal(c)
327 , stat(stat)
328 , accept(Assets().data.resources)
329 , locate_subtask(nullptr)
330 , ingesting(false)
331 , resource(-1)
332 , yield(0.0) {
333         Urgency(stat.value);
334 }
335
336 IngestGoal::~IngestGoal() {
337 }
338
339 void IngestGoal::Accept(int resource, double value) {
340         accept.Add(resource, value);
341 }
342
343 std::string IngestGoal::Describe() const {
344         if (resource == -1) {
345                 return "ingest " + summarize(accept, Assets());
346         } else {
347                 const world::Resource &r = Assets().data.resources[resource];
348                 if (r.state == world::Resource::SOLID) {
349                         return "eat " + r.label;
350                 } else {
351                         return "drink " + r.label;
352                 }
353         }
354 }
355
356 void IngestGoal::Enable() {
357 }
358
359 void IngestGoal::Tick(double dt) {
360         Urgency(stat.value);
361         if (locate_subtask) {
362                 locate_subtask->Urgency(Urgency() + 0.1);
363         }
364         if (ingesting) {
365                 if (OnSuitableTile() && !GetSituation().Moving()) {
366                         GetCreature().Ingest(resource, yield * dt);
367                         stat.Add(-1.0 * yield * GetCreature().GetComposition().Compatibility(resource) * dt);
368                         if (stat.Empty()) {
369                                 SetComplete();
370                         }
371                 } else {
372                         // left tile somehow, some idiot probably pushed us off
373                         ingesting = false;
374                         Interruptible(true);
375                 }
376         }
377 }
378
379 void IngestGoal::Action() {
380         if (ingesting) {
381                 // all good
382                 return;
383         }
384         if (OnSuitableTile()) {
385                 if (GetSituation().Moving()) {
386                         // break with maximum force
387                         GetSteering().Haste(1.0);
388                         GetSteering().Halt();
389                 } else {
390                         // finally
391                         // TODO: somehow this still gets interrupted
392                         Interruptible(false);
393                         ingesting = true;
394                 }
395         } else {
396                 locate_subtask = new LocateResourceGoal(GetCreature());
397                 for (const auto &c : accept) {
398                         locate_subtask->Accept(c.resource, c.value);
399                 }
400                 locate_subtask->SetMinimum(stat.gain * -1.1);
401                 locate_subtask->Urgency(Urgency() + 0.1);
402                 locate_subtask->WhenComplete([&](Goal &){ locate_subtask = nullptr; });
403                 GetCreature().AddGoal(std::unique_ptr<Goal>(locate_subtask));
404         }
405 }
406
407 bool IngestGoal::OnSuitableTile() {
408         if (!GetSituation().OnGround()) {
409                 return false;
410         }
411         const world::TileType &t = GetSituation().GetTileType();
412         auto found = t.FindBestResource(accept);
413         if (found != t.resources.end()) {
414                 resource = found->resource;
415                 yield = found->ubiquity;
416                 return true;
417         } else {
418                 resource = -1;
419                 return false;
420         }
421 }
422
423
424 LocateResourceGoal::LocateResourceGoal(Creature &c)
425 : Goal(c)
426 , accept(Assets().data.resources)
427 , found(false)
428 , target_pos(0.0)
429 , searching(false)
430 , reevaluate(0.0)
431 , minimum(0.0) {
432 }
433
434 LocateResourceGoal::~LocateResourceGoal() noexcept {
435 }
436
437 void LocateResourceGoal::Accept(int resource, double value) {
438         accept.Add(resource, value);
439 }
440
441 std::string LocateResourceGoal::Describe() const {
442         return "locate " + summarize(accept, Assets());
443 }
444
445 void LocateResourceGoal::Enable() {
446
447 }
448
449 void LocateResourceGoal::Tick(double dt) {
450         reevaluate -= dt;
451 }
452
453 void LocateResourceGoal::Action() {
454         if (reevaluate < 0.0) {
455                 LocateResource();
456                 reevaluate = 3.0;
457         } else if (!found) {
458                 if (!searching) {
459                         LocateResource();
460                 } else {
461                         if (OnTarget()) {
462                                 searching = false;
463                                 LocateResource();
464                         } else {
465                                 GetSteering().GoTo(target_pos);
466                         }
467                 }
468         } else if (OnTarget()) {
469                 GetSteering().Halt();
470                 if (!GetSituation().Moving()) {
471                         SetComplete();
472                 }
473         } else {
474                 GetSteering().GoTo(target_pos);
475         }
476         GetSteering().Haste(Urgency());
477 }
478
479 void LocateResourceGoal::LocateResource() {
480         if (GetSituation().OnSurface()) {
481                 const world::TileType &t = GetSituation().GetTileType();
482                 auto yield = t.FindBestResource(accept);
483                 if (yield != t.resources.cend()) {
484                         // hoooray
485                         GetSteering().Halt();
486                         found = true;
487                         searching = false;
488                         target_pos = GetSituation().Position();
489                 } else {
490                         // go find somewhere else
491                         SearchVicinity();
492                         if (!found) {
493                                 Remember();
494                                 if (!found) {
495                                         RandomWalk();
496                                 }
497                         }
498                 }
499         } else {
500                 // well, what now?
501                 found = false;
502                 searching = false;
503         }
504 }
505
506 void LocateResourceGoal::SearchVicinity() {
507         const world::Planet &planet = GetSituation().GetPlanet();
508         const glm::dvec3 &pos = GetSituation().Position();
509         const glm::dvec3 normal(planet.NormalAt(pos));
510         const glm::dvec3 step_x(glm::normalize(glm::cross(normal, glm::dvec3(normal.z, normal.x, normal.y))) * (GetCreature().PerceptionOmniRange() * 0.7));
511         const glm::dvec3 step_y(glm::normalize(glm::cross(step_x, normal)) * (GetCreature().PerceptionOmniRange() * 0.7));
512
513         const int search_radius = int(GetCreature().PerceptionRange() / (GetCreature().PerceptionOmniRange() * 0.7));
514         double rating[2 * search_radius + 1][2 * search_radius + 1];
515         std::memset(rating, '\0', (2 * search_radius + 1) * (2 * search_radius + 1) * sizeof(double));
516
517         // find close and rich field
518         for (int y = -search_radius; y < search_radius + 1; ++y) {
519                 for (int x = -search_radius; x < search_radius + 1; ++x) {
520                         const glm::dvec3 tpos(pos + (double(x) * step_x) + (double(y) * step_y));
521                         if (!GetCreature().PerceptionTest(tpos)) continue;
522                         const world::TileType &type = planet.TileTypeAt(tpos);
523                         auto yield = type.FindBestResource(accept);
524                         if (yield != type.resources.cend()) {
525                                 rating[y + search_radius][x + search_radius] = yield->ubiquity * accept.Get(yield->resource);
526                                 // penalize distance
527                                 double dist = std::max(0.125, 0.25 * glm::length2(tpos - pos));
528                                 rating[y + search_radius][x + search_radius] /= dist;
529                         }
530                 }
531         }
532
533         // penalize crowding
534         for (auto &c : planet.Creatures()) {
535                 if (&*c == &GetCreature()) continue;
536                 for (int y = -search_radius; y < search_radius + 1; ++y) {
537                         for (int x = -search_radius; x < search_radius + 1; ++x) {
538                                 const glm::dvec3 tpos(pos + (double(x) * step_x) + (double(y) * step_y));
539                                 if (glm::length2(tpos - c->GetSituation().Position()) < 1.0) {
540                                         rating[y + search_radius][x + search_radius] *= 0.8;
541                                 }
542                         }
543                 }
544         }
545
546         glm::ivec2 best_pos(0);
547         double best_rating = -1.0;
548
549         for (int y = -search_radius; y < search_radius + 1; ++y) {
550                 for (int x = -search_radius; x < search_radius + 1; ++x) {
551                         if (rating[y + search_radius][x + search_radius] > best_rating) {
552                                 best_pos = glm::ivec2(x, y);
553                                 best_rating = rating[y + search_radius][x + search_radius];
554                         }
555                 }
556         }
557
558         if (best_rating > minimum) {
559                 found = true;
560                 searching = false;
561                 target_pos = glm::normalize(pos + (double(best_pos.x) * step_x) + (double(best_pos.y) * step_y)) * planet.Radius();
562                 GetSteering().GoTo(target_pos);
563         }
564 }
565
566 void LocateResourceGoal::Remember() {
567         glm::dvec3 pos(0.0);
568         if (GetCreature().GetMemory().RememberLocation(accept, pos)) {
569                 found = true;
570                 searching = false;
571                 target_pos = pos;
572                 GetSteering().GoTo(target_pos);
573         }
574 }
575
576 void LocateResourceGoal::RandomWalk() {
577         if (searching) {
578                 return;
579         }
580
581         const world::Planet &planet = GetSituation().GetPlanet();
582         const glm::dvec3 &pos = GetSituation().Position();
583         const glm::dvec3 normal(planet.NormalAt(pos));
584         const glm::dvec3 step_x(glm::normalize(glm::cross(normal, glm::dvec3(normal.z, normal.x, normal.y))));
585         const glm::dvec3 step_y(glm::normalize(glm::cross(step_x, normal)));
586
587         found = false;
588         searching = true;
589         target_pos = GetSituation().Position();
590         target_pos += Random().SNorm() * 3.0 * step_x;
591         target_pos += Random().SNorm() * 3.0 * step_y;
592         // bias towards current heading
593         target_pos += GetSituation().Heading() * 1.5;
594         target_pos = glm::normalize(target_pos) * planet.Radius();
595         GetSteering().GoTo(target_pos);
596 }
597
598 bool LocateResourceGoal::OnTarget() const noexcept {
599         const Situation &s = GetSituation();
600         return s.OnGround() && glm::length2(s.Position() - target_pos) < 0.0001;
601 }
602
603
604 LookAroundGoal::LookAroundGoal(Creature &c)
605 : Goal(c)
606 , timer(0.0) {
607 }
608
609 LookAroundGoal::~LookAroundGoal() {
610 }
611
612 std::string LookAroundGoal::Describe() const {
613         return "look around";
614 }
615
616 void LookAroundGoal::Enable() {
617         GetSteering().Halt();
618 }
619
620 void LookAroundGoal::Tick(double dt) {
621         timer -= dt;
622 }
623
624 void LookAroundGoal::Action() {
625         if (timer < 0.0) {
626                 PickDirection();
627                 timer = 1.0 + (Random().UNorm() * 4.0);
628         }
629 }
630
631 void LookAroundGoal::OnBackground() {
632         SetComplete();
633 }
634
635 void LookAroundGoal::PickDirection() noexcept {
636         double r = Random().SNorm();
637         r *= std::abs(r) * 0.5 * PI;
638         GetCreature().HeadingTarget(glm::rotate(GetSituation().Heading(), r, GetSituation().SurfaceNormal()));
639 }
640
641
642 StrollGoal::StrollGoal(Creature &c)
643 : Goal(c)
644 , last(GetSituation().Position())
645 , next(last) {
646 }
647
648 StrollGoal::~StrollGoal() {
649 }
650
651 std::string StrollGoal::Describe() const {
652         return "take a walk";
653 }
654
655 void StrollGoal::Enable() {
656         last = GetSituation().Position();
657         GetSteering().Haste(0.0);
658         PickTarget();
659 }
660
661 void StrollGoal::Action() {
662         if (glm::length2(next - GetSituation().Position()) < 0.0001) {
663                 PickTarget();
664         }
665 }
666
667 void StrollGoal::OnBackground() {
668         SetComplete();
669 }
670
671 void StrollGoal::PickTarget() noexcept {
672         last = next;
673         next += GetSituation().Heading() * 1.5;
674         const glm::dvec3 normal(GetSituation().GetPlanet().NormalAt(GetSituation().Position()));
675         glm::dvec3 rand_x(GetSituation().Heading());
676         if (std::abs(glm::dot(normal, rand_x)) > 0.999) {
677                 rand_x = glm::dvec3(normal.z, normal.x, normal.y);
678         }
679         glm::dvec3 rand_y = glm::cross(normal, rand_x);
680         next += ((rand_x * Random().SNorm()) + (rand_y * Random().SNorm())) * 1.5;
681         next = glm::normalize(next) * GetSituation().GetPlanet().Radius();
682         GetSteering().GoTo(next);
683 }
684
685 }
686 }