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