]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
use RK4 to integrate creature state
[blobs.git] / src / creature / creature.cpp
1 #include "Creature.hpp"
2 #include "Genome.hpp"
3 #include "Memory.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
7
8 #include "Goal.hpp"
9 #include "IdleGoal.hpp"
10 #include "InhaleNeed.hpp"
11 #include "IngestNeed.hpp"
12 #include "Need.hpp"
13 #include "../app/Assets.hpp"
14 #include "../world/Body.hpp"
15 #include "../world/Planet.hpp"
16 #include "../world/Simulation.hpp"
17 #include "../world/TileType.hpp"
18
19 #include <algorithm>
20 #include <sstream>
21 #include <glm/gtx/transform.hpp>
22
23 #include <iostream>
24 #include <glm/gtx/io.hpp>
25
26
27 namespace blobs {
28 namespace creature {
29
30 Creature::Creature(world::Simulation &sim)
31 : sim(sim)
32 , name()
33 , genome()
34 , mass(1.0)
35 , density(1.0)
36 , size(1.0)
37 , birth(sim.Time())
38 , health(1.0)
39 , on_death()
40 , removable(false)
41 , memory(*this)
42 , needs()
43 , goals()
44 , situation()
45 , steering()
46 , vao() {
47 }
48
49 Creature::~Creature() {
50 }
51
52 void Creature::Grow(double amount) noexcept {
53         Mass(std::min(properties.max_mass, mass + amount));
54 }
55
56 void Creature::Hurt(double dt) noexcept {
57         health = std::max(0.0, health - dt);
58         if (health == 0.0) {
59                 std::cout << "[" << int(sim.Time()) << "s] "
60                 << name << " died" << std::endl;
61                 Die();
62         }
63 }
64
65 void Creature::Die() noexcept {
66         needs.clear();
67         goals.clear();
68         steering.Halt();
69         if (on_death) {
70                 on_death(*this);
71         }
72         Remove();
73 }
74
75 double Creature::Size() const noexcept {
76         return size;
77 }
78
79 double Creature::Age() const noexcept {
80         return sim.Time() - birth;
81 }
82
83 double Creature::Fertility() const noexcept {
84         double age = Age();
85         if (mass < properties.fertile_mass
86                 || age < properties.fertile_age
87                 || age > properties.infertile_age) {
88                 return 0.0;
89         }
90         return properties.fertility / 3600.0;
91 }
92
93 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
94         std::cout << "[" << int(sim.Time()) << "s] " << name << " new goal: " << g->Describe() << std::endl;
95         g->Enable();
96         goals.emplace_back(std::move(g));
97 }
98
99 namespace {
100
101 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
102         return b->Urgency() < a->Urgency();
103 }
104
105 }
106
107 void Creature::Tick(double dt) {
108         {
109                 Situation::State state(situation.GetState());
110                 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
111                 Situation::Derivative b(Step(a, dt * 0.5));
112                 Situation::Derivative c(Step(b, dt * 0.5));
113                 Situation::Derivative d(Step(c, dt));
114                 Situation::Derivative f(
115                         (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
116                         (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
117                 );
118                 state.pos += f.vel * dt;
119                 state.vel += f.acc * dt;
120                 situation.SetState(state);
121         }
122
123         if (Age() > properties.death_age) {
124                 std::cout << "[" << int(sim.Time()) << "s] "
125                 << name << " died of old age" << std::endl;
126         }
127
128         memory.Tick(dt);
129         for (auto &need : needs) {
130                 need->Tick(dt);
131         }
132         for (auto &goal : goals) {
133                 goal->Tick(dt);
134         }
135         // do background stuff
136         for (auto &need : needs) {
137                 need->ApplyEffect(*this, dt);
138         }
139         if (goals.empty()) {
140                 return;
141         }
142         // if active goal can be interrupted, check priorities
143         if (goals.size() > 1 && goals[0]->Interruptible()) {
144                 Goal *old_top = &*goals[0];
145                 std::sort(goals.begin(), goals.end(), GoalCompare);
146                 Goal *new_top = &*goals[0];
147                 if (new_top != old_top) {
148                         std::cout << "[" << int(sim.Time()) << "s] " << name
149                                 << " changing goal from " << old_top->Describe()
150                                 << " to " << new_top->Describe() << std::endl;
151                 }
152         }
153         goals[0]->Action();
154         for (auto goal = goals.begin(); goal != goals.end();) {
155                 if ((*goal)->Complete()) {
156                         std::cout << "[" << int(sim.Time()) << "s] " << name
157                                 << " complete goal: " << (*goal)->Describe() << std::endl;
158                         goals.erase(goal);
159                 } else {
160                         ++goal;
161                 }
162         }
163 }
164
165 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
166         Situation::State s = situation.GetState();
167         s.pos += ds.vel * dt;
168         s.vel += ds.acc * dt;
169         return { s.vel, steering.Acceleration(s) };
170 }
171
172 glm::dmat4 Creature::LocalTransform() noexcept {
173         // TODO: surface transform
174         const double half_size = size * 0.5;
175         const glm::dvec3 &pos = situation.Position();
176         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
177                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
178 }
179
180 void Creature::BuildVAO() {
181         vao.Bind();
182         vao.BindAttributes();
183         vao.EnableAttribute(0);
184         vao.EnableAttribute(1);
185         vao.EnableAttribute(2);
186         vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
187         vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
188         vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
189         vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
190         {
191                 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
192                 const float offset = 1.0f;
193                 for (int surface = 0; surface < 6; ++surface) {
194                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
195                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
196
197                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
198                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
199                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
200                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
201                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
202                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
203                         attrib[4 * surface + 0].texture.x = tex_u_begin;
204                         attrib[4 * surface + 0].texture.y = 1.0f;
205                         attrib[4 * surface + 0].texture.z = surface;
206
207                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
208                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
209                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
210                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
211                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
212                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
213                         attrib[4 * surface + 1].texture.x = tex_u_end;
214                         attrib[4 * surface + 1].texture.y = 1.0f;
215                         attrib[4 * surface + 1].texture.z = surface;
216
217                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
218                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
219                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
220                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
221                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
222                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
223                         attrib[4 * surface + 2].texture.x = tex_u_begin;
224                         attrib[4 * surface + 2].texture.y = 0.0f;
225                         attrib[4 * surface + 2].texture.z = surface;
226
227                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
228                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
229                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
230                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
231                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
232                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
233                         attrib[4 * surface + 3].texture.x = tex_u_end;
234                         attrib[4 * surface + 3].texture.y = 0.0f;
235                         attrib[4 * surface + 3].texture.z = surface;
236                 }
237         }
238         vao.BindElements();
239         vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
240         {
241                 auto element = vao.MapElements(GL_WRITE_ONLY);
242                 for (int surface = 0; surface < 3; ++surface) {
243                         element[6 * surface + 0] = 4 * surface + 0;
244                         element[6 * surface + 1] = 4 * surface + 2;
245                         element[6 * surface + 2] = 4 * surface + 1;
246                         element[6 * surface + 3] = 4 * surface + 1;
247                         element[6 * surface + 4] = 4 * surface + 2;
248                         element[6 * surface + 5] = 4 * surface + 3;
249                 }
250                 for (int surface = 3; surface < 6; ++surface) {
251                         element[6 * surface + 0] = 4 * surface + 0;
252                         element[6 * surface + 1] = 4 * surface + 1;
253                         element[6 * surface + 2] = 4 * surface + 2;
254                         element[6 * surface + 3] = 4 * surface + 2;
255                         element[6 * surface + 4] = 4 * surface + 1;
256                         element[6 * surface + 5] = 4 * surface + 3;
257                 }
258         }
259         vao.Unbind();
260 }
261
262 void Creature::Draw(graphics::Viewport &viewport) {
263         vao.Bind();
264         vao.DrawTriangles(6 * 6);
265 }
266
267
268 void Spawn(Creature &c, world::Planet &p) {
269         p.AddCreature(&c);
270         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
271
272         // probe surrounding area for common resources
273         int start = p.SideLength() / 2 - 2;
274         int end = start + 5;
275         std::map<int, double> yields;
276         for (int y = start; y < end; ++y) {
277                 for (int x = start; x < end; ++x) {
278                         const world::TileType &t = p.TypeAt(0, x, y);
279                         for (auto yield : t.resources) {
280                                 yields[yield.resource] += yield.ubiquity;
281                         }
282                 }
283         }
284         int liquid = -1;
285         int solid = -1;
286         for (auto e : yields) {
287                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
288                         if (liquid < 0 || e.second > yields[liquid]) {
289                                 liquid = e.first;
290                         }
291                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
292                         if (solid < 0 || e.second > yields[solid]) {
293                                 solid = e.first;
294                         }
295                 }
296         }
297
298         Genome genome;
299         genome.properties.birth_mass = { 0.5, 0.1 };
300         genome.properties.fertile_mass = { 1.0, 0.1 };
301         genome.properties.max_mass = { 1.2, 0.1 };
302         genome.properties.fertile_age = { 60.0, 5.0 };
303         genome.properties.infertile_age = { 700.0, 30.0 };
304         genome.properties.death_age = { 900.0, 90.0 };
305         genome.properties.fertility = { 0.5, 0.01 };
306
307         if (p.HasAtmosphere()) {
308                 genome.composition.push_back({
309                         p.Atmosphere(),    // resource
310                         { 0.01, 0.00001 }, // mass
311                         { 0.5,  0.001 },   // intake
312                         { 0.1,  0.0005 },  // penalty
313                         { 0.0,  0.0 },     // growth
314                 });
315         }
316         if (liquid > -1) {
317                 genome.composition.push_back({
318                         liquid,          // resource
319                         { 0.6,  0.01 },  // mass
320                         { 0.2,  0.001 }, // intake
321                         { 0.01, 0.002 }, // penalty
322                         { 0.1, 0.0 },   // growth
323                 });
324         }
325         if (solid > -1) {
326                 genome.composition.push_back({
327                         solid,             // resource
328                         { 0.4,   0.01 },   // mass
329                         //{ 0.1,   0.001 },  // intake
330                         { 0.4,   0.001 },  // intake
331                         { 0.001, 0.0001 }, // penalty
332                         { 10.0,  0.002 },   // growth
333                 });
334         }
335
336         genome.Configure(c);
337 }
338
339 void Genome::Configure(Creature &c) const {
340         c.GetGenome() = *this;
341
342         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
343
344         c.GetProperties().birth_mass = properties.birth_mass.FakeNormal(random.SNorm());
345         c.GetProperties().fertile_mass = properties.fertile_mass.FakeNormal(random.SNorm());
346         c.GetProperties().max_mass = properties.max_mass.FakeNormal(random.SNorm());
347         c.GetProperties().fertile_age = properties.fertile_age.FakeNormal(random.SNorm());
348         c.GetProperties().infertile_age = properties.infertile_age.FakeNormal(random.SNorm());
349         c.GetProperties().death_age = properties.death_age.FakeNormal(random.SNorm());
350         c.GetProperties().fertility = properties.fertility.FakeNormal(random.SNorm());
351
352         double mass = 0.0;
353         double volume = 0.0;
354         for (const auto &comp : composition) {
355                 double comp_mass = comp.mass.FakeNormal(random.SNorm());
356                 double intake = comp.intake.FakeNormal(random.SNorm());
357                 double penalty = comp.penalty.FakeNormal(random.SNorm());
358
359                 mass += comp_mass;
360                 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
361
362                 std::unique_ptr<Need> need;
363                 if (c.GetSimulation().Resources()[comp.resource].state == world::Resource::SOLID) {
364                         need.reset(new IngestNeed(comp.resource, intake, penalty));
365                         need->gain = intake * 0.05;
366                 } else if (c.GetSimulation().Resources()[comp.resource].state == world::Resource::LIQUID) {
367                         need.reset(new IngestNeed(comp.resource, intake, penalty));
368                         need->gain = intake * 0.1;
369                 } else {
370                         need.reset(new InhaleNeed(comp.resource, intake, penalty));
371                         need->gain = intake * 0.5;
372                 }
373                 need->name = c.GetSimulation().Resources()[comp.resource].label;
374                 need->growth = comp.growth.FakeNormal(random.SNorm());
375                 need->inconvenient = 0.5;
376                 need->critical = 0.95;
377                 c.AddNeed(std::move(need));
378         }
379
380         c.Mass(c.GetProperties().birth_mass);
381         c.Density(mass / volume);
382         c.GetSteering().MaxAcceleration(1.4);
383         c.GetSteering().MaxSpeed(4.4);
384         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
385 }
386
387
388 void Split(Creature &c) {
389         Creature *a = new Creature(c.GetSimulation());
390         const Situation &s = c.GetSituation();
391         // TODO: generate names
392         a->Name(c.GetSimulation().Assets().name.Sequential());
393         // TODO: mutate
394         c.GetGenome().Configure(*a);
395         s.GetPlanet().AddCreature(a);
396         // TODO: duplicate situation somehow
397         a->GetSituation().SetPlanetSurface(
398                 s.GetPlanet(), s.Surface(),
399                 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
400         a->BuildVAO();
401
402         Creature *b = new Creature(c.GetSimulation());
403         b->Name(c.GetSimulation().Assets().name.Sequential());
404         c.GetGenome().Configure(*b);
405         s.GetPlanet().AddCreature(b);
406         b->GetSituation().SetPlanetSurface(
407                 s.GetPlanet(), s.Surface(),
408                 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
409         b->BuildVAO();
410
411         c.Die();
412 }
413
414
415 Memory::Memory(Creature &c)
416 : c(c) {
417 }
418
419 Memory::~Memory() {
420 }
421
422 void Memory::Tick(double dt) {
423         Situation &s = c.GetSituation();
424         if (s.OnSurface()) {
425                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
426         }
427 }
428
429 void Memory::TrackStay(const Location &l, double t) {
430         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
431         auto entry = known_types.find(type.id);
432         if (entry != known_types.end()) {
433                 entry->second.last_been = c.GetSimulation().Time();
434                 entry->second.last_loc = l;
435                 entry->second.time_spent += t;
436         } else {
437                 known_types.emplace(type.id, Stay{
438                         c.GetSimulation().Time(),
439                         l,
440                         c.GetSimulation().Time(),
441                         l,
442                         t
443                 });
444         }
445 }
446
447
448 NameGenerator::NameGenerator()
449 : counter(0) {
450 }
451
452 NameGenerator::~NameGenerator() {
453 }
454
455 std::string NameGenerator::Sequential() {
456         std::stringstream ss;
457         ss << "Blob " << ++counter;
458         return ss.str();
459 }
460
461
462 Situation::Situation()
463 : planet(nullptr)
464 , state(glm::dvec3(0.0), glm::dvec3(0.0))
465 , surface(0)
466 , type(LOST) {
467 }
468
469 Situation::~Situation() {
470 }
471
472 bool Situation::OnPlanet() const noexcept {
473         return type == PLANET_SURFACE;
474 }
475
476 bool Situation::OnSurface() const noexcept {
477         return type == PLANET_SURFACE;
478 }
479
480 bool Situation::OnTile() const noexcept {
481         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
482         return type == PLANET_SURFACE
483                 && t.x >= 0 && t.x < planet->SideLength()
484                 && t.y >= 0 && t.y < planet->SideLength();
485 }
486
487 glm::ivec2 Situation::SurfacePosition() const noexcept {
488         return planet->SurfacePosition(surface, state.pos);
489 }
490
491 world::Tile &Situation::GetTile() const noexcept {
492         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
493         return planet->TileAt(surface, t.x, t.y);
494 }
495
496 const world::TileType &Situation::GetTileType() const noexcept {
497         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
498         return planet->TypeAt(surface, t.x, t.y);
499 }
500
501 void Situation::Move(const glm::dvec3 &dp) noexcept {
502         state.pos += dp;
503         if (OnSurface()) {
504                 // enforce ground constraint
505                 if (Surface() < 3) {
506                         state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
507                 } else {
508                         state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
509                 }
510         }
511 }
512
513 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
514         type = PLANET_SURFACE;
515         planet = &p;
516         surface = srf;
517         state.pos = pos;
518 }
519
520
521 Steering::Steering()
522 : seek_target(0.0)
523 , max_accel(1.0)
524 , max_speed(1.0)
525 , halting(false)
526 , seeking(false) {
527 }
528
529 Steering::~Steering() {
530 }
531
532 void Steering::Halt() noexcept {
533         halting = true;
534         seeking = false;
535 }
536
537 void Steering::GoTo(const glm::dvec3 &t) noexcept {
538         seek_target = t;
539         halting = false;
540         seeking = true;
541 }
542
543 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
544         glm::dvec3 acc(0.0);
545         if (halting) {
546                 SumForce(acc, s.vel * -max_accel);
547         }
548         if (seeking) {
549                 glm::dvec3 diff = seek_target - s.pos;
550                 if (!allzero(diff)) {
551                         SumForce(acc, ((normalize(diff) * max_speed) - s.vel) * max_accel);
552                 }
553         }
554         return acc;
555 }
556
557 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
558         if (allzero(in) || anynan(in)) {
559                 return false;
560         }
561         double cur = allzero(out) ? 0.0 : length(out);
562         double rem = max_accel - cur;
563         if (rem < 0.0) {
564                 return true;
565         }
566         double add = length(in);
567         if (add > rem) {
568                 // this method is off if in and out are in different
569                 // directions, but gives okayish results
570                 out += in * (1.0 / add);
571                 return true;
572         } else {
573                 out += in;
574                 return false;
575         }
576 }
577
578 }
579 }