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