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