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