]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
log death just once
[blobs.git] / src / creature / creature.cpp
1 #include "Composition.hpp"
2 #include "Creature.hpp"
3 #include "Genome.hpp"
4 #include "Memory.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
8
9 #include "BlobBackgroundTask.hpp"
10 #include "Goal.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
19
20 #include <algorithm>
21 #include <sstream>
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
24
25 #include <iostream>
26 #include <glm/gtx/io.hpp>
27
28
29 namespace blobs {
30 namespace creature {
31
32 Composition::Composition()
33 : components()
34 , total_mass(0.0) {
35 }
36
37 Composition::~Composition() {
38 }
39
40 namespace {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42         return b.value < a.value;
43 }
44 }
45
46 void Composition::Add(int res, double amount) {
47         bool found = false;
48         for (auto c = components.begin(); c != components.end(); ++c) {
49                 if (c->resource == res) {
50                         c->value += amount;
51                         if (c->value <= 0.0) {
52                                 components.erase(c);
53                         }
54                         found = true;
55                         break;
56                 }
57         }
58         if (!found && amount > 0.0) {
59                 components.emplace_back(res, amount);
60         }
61         std::sort(components.begin(), components.end(), CompositionCompare);
62         total_mass += amount;
63 }
64
65 bool Composition::Has(int res) const noexcept {
66         for (auto &c : components) {
67                 if (c.resource == res) {
68                         return true;
69                 }
70         }
71         return false;
72 }
73
74 double Composition::Get(int res) const noexcept {
75         for (auto &c : components) {
76                 if (c.resource == res) {
77                         return c.value;
78                 }
79         }
80         return 0.0;
81 }
82
83
84 Creature::Creature(world::Simulation &sim)
85 : sim(sim)
86 , name()
87 , genome()
88 , properties()
89 , composition()
90 , base_color(1.0)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
92 , mass(1.0)
93 , size(1.0)
94 , birth(sim.Time())
95 , death(-1.0)
96 , on_death()
97 , removable(false)
98 , parents()
99 , stats()
100 , memory(*this)
101 , bg_task()
102 , goals()
103 , situation()
104 , steering(*this)
105 , vao() {
106         sim.SetAlive(this);
107         // all creatures avoid each other for now
108         steering.Separate(0.1, 1.5);
109 }
110
111 Creature::~Creature() {
112 }
113
114 void Creature::AddMass(int res, double amount) {
115         composition.Add(res, amount);
116         double nonsolid = 0.0;
117         double volume = 0.0;
118         for (const auto &c : composition) {
119                 volume += c.value / sim.Assets().data.resources[c.resource].density;
120                 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
121                         nonsolid += c.value;
122                 }
123         }
124         Mass(composition.TotalMass());
125         Size(std::cbrt(volume));
126         highlight_color.a = nonsolid / composition.TotalMass();
127 }
128
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130         highlight_color = glm::dvec4(c, highlight_color.a);
131 }
132
133 void Creature::Ingest(int res, double amount) noexcept {
134         // TODO: check foreign materials
135         if (sim.Resources()[res].state == world::Resource::SOLID) {
136                 // 15% of solids stays in body
137                 AddMass(res, amount * 0.15);
138         } else {
139                 // 10% of fluids stays in body
140                 AddMass(res, amount * 0.05);
141         }
142         math::GaloisLFSR &random = sim.Assets().random;
143         if (random.UNorm() < AdaptChance()) {
144                 // change color to be slightly more like resource
145                 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
146                 // solids affect base color, others highlight
147                 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
148                 double q = random.UInt(3); // hue, sat, or val
149                 double r = random.UInt(2); // mean or deviation
150                 math::Distribution *d = nullptr;
151                 double ref = 0.0;
152                 if (p == 0) {
153                         if (q == 0) {
154                                 d = &genome.base_hue;
155                                 ref = color.x;
156                         } else if (q == 1) {
157                                 d = &genome.base_saturation;
158                                 ref = color.y;
159                         } else {
160                                 d = &genome.base_lightness;
161                                 ref = color.z;
162                         }
163                 } else {
164                         if (q == 0) {
165                                 d = &genome.highlight_hue;
166                                 ref = color.x;
167                         } else if (q == 1) {
168                                 d = &genome.highlight_saturation;
169                                 ref = color.y;
170                         } else {
171                                 d = &genome.highlight_lightness;
172                                 ref = color.z;
173                         }
174                 }
175                 if (r == 0) {
176                         double diff = ref - d->Mean();
177                         if (q == 0) {
178                                 if (diff < -0.5) {
179                                         diff += 1.0;
180                                 } else if (diff > 0.5) {
181                                         diff -= 1.0;
182                                 }
183                                 // move ±15% of distance
184                                 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
185                         } else {
186                                 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
187                         }
188                 } else {
189                         // scale by ±15%, enforce bounds
190                         d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
191                 }
192         }
193 }
194
195 void Creature::DoWork(double amount) noexcept {
196         stats.Exhaustion().Add(amount / Stamina());
197         // burn resources proportional to composition
198         // factor = 1/total * 1/efficiency * amount * -1
199         double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
200         // make a copy to total remains constant and
201         // no entries disappear during iteration
202         Composition comp(composition);
203         for (auto &cmp : comp) {
204                 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
205                 AddMass(cmp.resource, value);
206         }
207 }
208
209 void Creature::Hurt(double amount) noexcept {
210         stats.Damage().Add(amount);
211         if (stats.Damage().Full()) {
212                 Die();
213         }
214 }
215
216 void Creature::Die() noexcept {
217         if (Dead()) return;
218
219         std::ostream &log = sim.Log() << name << " ";
220         if (stats.Exhaustion().Full()) {
221                 log << "died of exhaustion";
222         } else if (stats.Breath().Full()) {
223                 log << "suffocated";
224         } else if (stats.Thirst().Full()) {
225                 log << "died of thirst";
226         } else if (stats.Hunger().Full()) {
227                 log << "starved to death";
228         } else {
229                 log << "succumed to wounds";
230         }
231         log << " at an age of " << ui::TimeString(Age())
232                 << " (" << ui::PercentageString(Age() / properties.Lifetime())
233                 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
234                 << ")" << std::endl;
235
236         sim.SetDead(this);
237         death = sim.Time();
238         steering.Off();
239         if (on_death) {
240                 on_death(*this);
241         }
242         Remove();
243 }
244
245 bool Creature::Dead() const noexcept {
246         return death > birth;
247 }
248
249 void Creature::Remove() noexcept {
250         removable = true;
251 }
252
253 void Creature::Removed() noexcept {
254         bg_task.reset();
255         goals.clear();
256         memory.Erase();
257         KillVAO();
258 }
259
260 void Creature::AddParent(Creature &p) {
261         parents.push_back(&p);
262 }
263
264 double Creature::Age() const noexcept {
265         return sim.Time() - birth;
266 }
267
268 double Creature::AgeFactor(double peak) const noexcept {
269         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
270         // goes negative below -0.5 and starts to rise again above 1.0
271         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
272         // guarantee at least 1%
273         return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
274 }
275
276 double Creature::EnergyEfficiency() const noexcept {
277         return 0.25 * AgeFactor(0.05);
278 }
279
280 double Creature::ExhaustionFactor() const noexcept {
281         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
282 }
283
284 double Creature::FatigueFactor() const noexcept {
285         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
286 }
287
288 double Creature::Strength() const noexcept {
289         // TODO: replace all age factors with actual growth and decay
290         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
291 }
292
293 double Creature::Stamina() const noexcept {
294         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
295 }
296
297 double Creature::Dexerty() const noexcept {
298         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
299 }
300
301 double Creature::Intelligence() const noexcept {
302         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
303 }
304
305 double Creature::Lifetime() const noexcept {
306         return properties.Lifetime();
307 }
308
309 double Creature::Fertility() const noexcept {
310         return properties.Fertility() * AgeFactor(0.25);
311 }
312
313 double Creature::Mutability() const noexcept {
314         return properties.Mutability();
315 }
316
317 double Creature::Adaptability() const noexcept {
318         return properties.Adaptability();
319 }
320
321 double Creature::OffspringMass() const noexcept {
322         return properties.OffspringMass();
323 }
324
325 double Creature::PerceptionRange() const noexcept {
326         return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
327 }
328
329 double Creature::PerceptionOmniRange() const noexcept {
330         return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
331 }
332
333 double Creature::PerceptionField() const noexcept {
334         // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
335         return 0.8 - (Dexerty() / (Dexerty() + 1));
336 }
337
338 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
339         const glm::dvec3 diff(p - situation.Position());
340         double omni_range = PerceptionOmniRange();
341         if (length2(diff) < omni_range * omni_range) return true;
342         double range = PerceptionRange();
343         if (length2(diff) > range * range) return false;
344         return dot(normalize(diff), situation.Heading()) > PerceptionField();
345 }
346
347 double Creature::OffspringChance() const noexcept {
348         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
349 }
350
351 double Creature::MutateChance() const noexcept {
352         return GetProperties().Mutability() * (1.0 / 3600.0);
353 }
354
355 double Creature::AdaptChance() const noexcept {
356         return GetProperties().Adaptability() * (1.0 / 120.0);
357 }
358
359 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
360         g->Enable();
361         goals.emplace_back(std::move(g));
362 }
363
364 namespace {
365
366 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
367         return b->Urgency() < a->Urgency();
368 }
369
370 }
371
372 void Creature::Tick(double dt) {
373         TickState(dt);
374         TickStats(dt);
375         TickBrain(dt);
376 }
377
378 void Creature::TickState(double dt) {
379         steering.MaxSpeed(Dexerty());
380         steering.MaxForce(Strength());
381         Situation::State state(situation.GetState());
382         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
383         Situation::Derivative b(Step(a, dt * 0.5));
384         Situation::Derivative c(Step(b, dt * 0.5));
385         Situation::Derivative d(Step(c, dt));
386         Situation::Derivative f(
387                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
388                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
389         );
390         state.pos += f.vel * dt;
391         state.vel += f.acc * dt;
392         situation.EnforceConstraints(state);
393         if (length2(state.vel) > 0.000001) {
394                 glm::dvec3 nvel(normalize(state.vel));
395                 double ang = angle(nvel, state.dir);
396                 double turn_rate = PI * 0.75 * dt;
397                 if (ang < turn_rate) {
398                         state.dir = normalize(state.vel);
399                 } else if (std::abs(ang - PI) < 0.001) {
400                         state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
401                 } else {
402                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
403                 }
404         }
405         situation.SetState(state);
406         // work is force times distance
407         DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
408 }
409
410 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
411         Situation::State s = situation.GetState();
412         s.pos += ds.vel * dt;
413         s.vel += ds.acc * dt;
414         glm::dvec3 force(steering.Force(s));
415         // gravity = antinormal * mass * Gm / r²
416         double elevation = s.pos[(situation.Surface() + 2) % 3];
417         glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
418         force += glm::dvec3(
419                 -normal
420                 * Mass() * situation.GetPlanet().GravitationalParameter()
421                 / (elevation * elevation));
422         // if net force is applied and in contact with surface
423         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
424                 // apply friction = -|normal force| * tangential force * coefficient
425                 glm::dvec3 fn(normal * dot(force, normal));
426                 glm::dvec3 ft(force - fn);
427                 double u = 0.4;
428                 glm::dvec3 friction(-length(fn) * ft * u);
429                 force += friction;
430         }
431         return {
432                 s.vel,
433                 force / Mass()
434         };
435 }
436
437 void Creature::TickStats(double dt) {
438         for (auto &s : stats.stat) {
439                 s.Add(s.gain * dt);
440         }
441         // TODO: damage values depending on properties
442         if (stats.Breath().Full()) {
443                 constexpr double dps = 1.0 / 4.0;
444                 Hurt(dps * dt);
445         }
446         if (stats.Thirst().Full()) {
447                 constexpr double dps = 1.0 / 32.0;
448                 Hurt(dps * dt);
449         }
450         if (stats.Hunger().Full()) {
451                 constexpr double dps = 1.0 / 128.0;
452                 Hurt(dps * dt);
453         }
454         if (!situation.Moving()) {
455                 // double exhaustion recovery when standing still
456                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
457         }
458 }
459
460 void Creature::TickBrain(double dt) {
461         bg_task->Tick(dt);
462         bg_task->Action();
463         memory.Tick(dt);
464         // do background stuff
465         if (goals.empty()) {
466                 return;
467         }
468         for (auto &goal : goals) {
469                 goal->Tick(dt);
470         }
471         // if active goal can be interrupted, check priorities
472         if (goals.size() > 1 && goals[0]->Interruptible()) {
473                 std::sort(goals.begin(), goals.end(), GoalCompare);
474         }
475         goals[0]->Action();
476         for (auto goal = goals.begin(); goal != goals.end();) {
477                 if ((*goal)->Complete()) {
478                         goals.erase(goal);
479                 } else {
480                         ++goal;
481                 }
482         }
483 }
484
485 math::AABB Creature::CollisionBox() const noexcept {
486         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
487 }
488
489 glm::dmat4 Creature::CollisionTransform() const noexcept {
490         const double half_size = size * 0.5;
491         const glm::dvec3 &pos = situation.Position();
492         const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
493         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
494                 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
495                 * glm::dmat4(srf);
496 }
497
498 glm::dmat4 Creature::LocalTransform() noexcept {
499         const double half_size = size * 0.5;
500         return CollisionTransform()
501                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
502 }
503
504 void Creature::BuildVAO() {
505         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
506         vao->Bind();
507         vao->BindAttributes();
508         vao->EnableAttribute(0);
509         vao->EnableAttribute(1);
510         vao->EnableAttribute(2);
511         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
512         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
513         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
514         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
515         {
516                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
517                 const float offset = 1.0f;
518                 for (int surface = 0; surface < 6; ++surface) {
519                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
520                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
521
522                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
523                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
524                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
525                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
526                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
527                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
528                         attrib[4 * surface + 0].texture.x = tex_u_begin;
529                         attrib[4 * surface + 0].texture.y = 1.0f;
530                         attrib[4 * surface + 0].texture.z = surface;
531
532                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
533                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
534                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
535                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
536                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
537                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
538                         attrib[4 * surface + 1].texture.x = tex_u_end;
539                         attrib[4 * surface + 1].texture.y = 1.0f;
540                         attrib[4 * surface + 1].texture.z = surface;
541
542                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
543                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
544                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
545                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
546                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
547                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
548                         attrib[4 * surface + 2].texture.x = tex_u_begin;
549                         attrib[4 * surface + 2].texture.y = 0.0f;
550                         attrib[4 * surface + 2].texture.z = surface;
551
552                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
553                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
554                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
555                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
556                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
557                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
558                         attrib[4 * surface + 3].texture.x = tex_u_end;
559                         attrib[4 * surface + 3].texture.y = 0.0f;
560                         attrib[4 * surface + 3].texture.z = surface;
561                 }
562         }
563         vao->BindElements();
564         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
565         {
566                 auto element = vao->MapElements(GL_WRITE_ONLY);
567                 for (int surface = 0; surface < 3; ++surface) {
568                         element[6 * surface + 0] = 4 * surface + 0;
569                         element[6 * surface + 1] = 4 * surface + 2;
570                         element[6 * surface + 2] = 4 * surface + 1;
571                         element[6 * surface + 3] = 4 * surface + 1;
572                         element[6 * surface + 4] = 4 * surface + 2;
573                         element[6 * surface + 5] = 4 * surface + 3;
574                 }
575                 for (int surface = 3; surface < 6; ++surface) {
576                         element[6 * surface + 0] = 4 * surface + 0;
577                         element[6 * surface + 1] = 4 * surface + 1;
578                         element[6 * surface + 2] = 4 * surface + 2;
579                         element[6 * surface + 3] = 4 * surface + 2;
580                         element[6 * surface + 4] = 4 * surface + 1;
581                         element[6 * surface + 5] = 4 * surface + 3;
582                 }
583         }
584         vao->Unbind();
585 }
586
587 void Creature::KillVAO() {
588         vao.reset();
589 }
590
591 void Creature::Draw(graphics::Viewport &viewport) {
592         if (!vao) return;
593         vao->Bind();
594         vao->DrawTriangles(6 * 6);
595 }
596
597
598 void Spawn(Creature &c, world::Planet &p) {
599         p.AddCreature(&c);
600         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
601         c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
602
603         // probe surrounding area for common resources
604         int start = p.SideLength() / 2 - 2;
605         int end = start + 5;
606         std::map<int, double> yields;
607         for (int y = start; y < end; ++y) {
608                 for (int x = start; x < end; ++x) {
609                         const world::TileType &t = p.TypeAt(0, x, y);
610                         for (auto yield : t.resources) {
611                                 yields[yield.resource] += yield.ubiquity;
612                         }
613                 }
614         }
615         int liquid = -1;
616         int solid = -1;
617         for (auto e : yields) {
618                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
619                         if (liquid < 0 || e.second > yields[liquid]) {
620                                 liquid = e.first;
621                         }
622                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
623                         if (solid < 0 || e.second > yields[solid]) {
624                                 solid = e.first;
625                         }
626                 }
627         }
628
629         Genome genome;
630         genome.properties.Strength() = { 2.0, 0.1 };
631         genome.properties.Stamina() = { 2.0, 0.1 };
632         genome.properties.Dexerty() = { 2.0, 0.1 };
633         genome.properties.Intelligence() = { 1.0, 0.1 };
634         genome.properties.Lifetime() = { 480.0, 60.0 };
635         genome.properties.Fertility() = { 0.5, 0.03 };
636         genome.properties.Mutability() = { 0.9, 0.1 };
637         genome.properties.Adaptability() = { 0.9, 0.1 };
638         genome.properties.OffspringMass() = { 0.3, 0.02 };
639
640         glm::dvec3 color_avg(0.0);
641         double color_divisor = 0.0;
642
643         if (p.HasAtmosphere()) {
644                 c.AddMass(p.Atmosphere(), 0.01);
645                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
646                 color_divisor += 0.1;
647         }
648         if (liquid > -1) {
649                 c.AddMass(liquid, 0.3);
650                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
651                 color_divisor += 0.5;
652         }
653         if (solid > -1) {
654                 c.AddMass(solid, 0.1);
655                 color_avg += c.GetSimulation().Resources()[solid].base_color;
656                 color_divisor += 1.0;
657         }
658
659         if (color_divisor > 0.001) {
660                 color_avg /= color_divisor;
661         }
662         glm::dvec3 hsl = rgb2hsl(color_avg);
663         genome.base_hue = { hsl.x, 0.01 };
664         genome.base_saturation = { hsl.y, 0.01 };
665         genome.base_lightness = { hsl.z, 0.01 };
666         // use opposite color as start highlight
667         genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
668         genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
669         genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
670
671         genome.Configure(c);
672 }
673
674 void Genome::Configure(Creature &c) const {
675         c.GetGenome() = *this;
676
677         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
678
679         c.GetProperties() = Instantiate(properties, random);
680
681         // TODO: derive stats from properties
682         c.GetStats().Damage().gain = (-1.0 / 100.0);
683         c.GetStats().Breath().gain = (1.0 / 5.0);
684         c.GetStats().Thirst().gain = (1.0 / 60.0);
685         c.GetStats().Hunger().gain = (1.0 / 200.0);
686         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
687         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
688         c.GetStats().Boredom().gain = (1.0 / 300.0);
689
690         glm::dvec3 base_color(
691                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
692                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
693                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
694         );
695         glm::dvec3 highlight_color(
696                 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
697                 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
698                 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
699         );
700         c.BaseColor(hsl2rgb(base_color));
701         c.HighlightColor(hsl2rgb(highlight_color));
702         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
703         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
704 }
705
706
707 void Split(Creature &c) {
708         Creature *a = new Creature(c.GetSimulation());
709         const Situation &s = c.GetSituation();
710         a->AddParent(c);
711         a->Name(c.GetSimulation().Assets().name.Sequential());
712         c.GetGenome().Configure(*a);
713         for (const auto &cmp : c.GetComposition()) {
714                 a->AddMass(cmp.resource, cmp.value * 0.5);
715         }
716         s.GetPlanet().AddCreature(a);
717         // TODO: duplicate situation somehow
718         a->GetSituation().SetPlanetSurface(
719                 s.GetPlanet(), s.Surface(),
720                 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
721         a->BuildVAO();
722         c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
723
724         Creature *b = new Creature(c.GetSimulation());
725         b->AddParent(c);
726         b->Name(c.GetSimulation().Assets().name.Sequential());
727         c.GetGenome().Configure(*b);
728         for (const auto &cmp : c.GetComposition()) {
729                 b->AddMass(cmp.resource, cmp.value * 0.5);
730         }
731         s.GetPlanet().AddCreature(b);
732         b->GetSituation().SetPlanetSurface(
733                 s.GetPlanet(), s.Surface(),
734                 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
735         b->BuildVAO();
736         c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
737
738         c.Die();
739 }
740
741
742 Memory::Memory(Creature &c)
743 : c(c) {
744 }
745
746 Memory::~Memory() {
747 }
748
749 void Memory::Erase() {
750         known_types.clear();
751 }
752
753 void Memory::Tick(double dt) {
754         Situation &s = c.GetSituation();
755         if (s.OnTile()) {
756                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
757         }
758 }
759
760 void Memory::TrackStay(const Location &l, double t) {
761         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
762         auto entry = known_types.find(type.id);
763         if (entry != known_types.end()) {
764                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
765                         // "it's been ages"
766                         if (entry->second.time_spent > c.Age() * 0.25) {
767                                 // the place is very familiar
768                                 c.GetStats().Boredom().Add(-0.2);
769                         } else {
770                                 // infrequent stays
771                                 c.GetStats().Boredom().Add(-0.1);
772                         }
773                 }
774                 entry->second.last_been = c.GetSimulation().Time();
775                 entry->second.last_loc = l;
776                 entry->second.time_spent += t;
777         } else {
778                 known_types.emplace(type.id, Stay{
779                         c.GetSimulation().Time(),
780                         l,
781                         c.GetSimulation().Time(),
782                         l,
783                         t
784                 });
785                 // completely new place, interesting
786                 // TODO: scale by personality trait
787                 c.GetStats().Boredom().Add(-0.25);
788         }
789 }
790
791
792 NameGenerator::NameGenerator()
793 : counter(0) {
794 }
795
796 NameGenerator::~NameGenerator() {
797 }
798
799 std::string NameGenerator::Sequential() {
800         std::stringstream ss;
801         ss << "Blob " << ++counter;
802         return ss.str();
803 }
804
805
806 Situation::Situation()
807 : planet(nullptr)
808 , state(glm::dvec3(0.0), glm::dvec3(0.0))
809 , surface(0)
810 , type(LOST) {
811 }
812
813 Situation::~Situation() {
814 }
815
816 bool Situation::OnPlanet() const noexcept {
817         return type == PLANET_SURFACE;
818 }
819
820 bool Situation::OnSurface() const noexcept {
821         return type == PLANET_SURFACE;
822 }
823
824 bool Situation::OnTile() const noexcept {
825         if (type != PLANET_SURFACE) return false;
826         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
827         return t.x >= 0 && t.x < planet->SideLength()
828                 && t.y >= 0 && t.y < planet->SideLength();
829 }
830
831 glm::ivec2 Situation::SurfacePosition() const noexcept {
832         return planet->SurfacePosition(surface, state.pos);
833 }
834
835 world::Tile &Situation::GetTile() const noexcept {
836         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
837         return planet->TileAt(surface, t.x, t.y);
838 }
839
840 const world::TileType &Situation::GetTileType() const noexcept {
841         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
842         return planet->TypeAt(surface, t.x, t.y);
843 }
844
845 void Situation::Move(const glm::dvec3 &dp) noexcept {
846         state.pos += dp;
847         EnforceConstraints(state);
848 }
849
850 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
851         state.vel += dv;
852         EnforceConstraints(state);
853 }
854
855 void Situation::EnforceConstraints(State &s) noexcept {
856         if (OnSurface()) {
857                 if (Surface() < 3) {
858                         if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
859                                 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
860                                 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
861                         }
862                 } else {
863                         if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
864                                 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
865                                 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
866                         }
867                 }
868         }
869 }
870
871 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
872         type = PLANET_SURFACE;
873         planet = &p;
874         surface = srf;
875         state.pos = pos;
876         EnforceConstraints(state);
877 }
878
879
880 Steering::Steering(const Creature &c)
881 : c(c)
882 , target(0.0)
883 , haste(0.0)
884 , max_force(1.0)
885 , max_speed(1.0)
886 , min_dist(0.0)
887 , max_look(0.0)
888 , separating(false)
889 , halting(true)
890 , seeking(false)
891 , arriving(false) {
892 }
893
894 Steering::~Steering() {
895 }
896
897 void Steering::Off() noexcept {
898         separating = false;
899         halting = false;
900         seeking = false;
901         arriving = false;
902 }
903
904 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
905         separating = true;
906         min_dist = min_distance;
907         max_look = max_lookaround;
908 }
909
910 void Steering::DontSeparate() noexcept {
911         separating = false;
912 }
913
914 void Steering::ResumeSeparate() noexcept {
915         separating = true;
916 }
917
918 void Steering::Halt() noexcept {
919         halting = true;
920         seeking = false;
921         arriving = false;
922 }
923
924 void Steering::Pass(const glm::dvec3 &t) noexcept {
925         target = t;
926         halting = false;
927         seeking = true;
928         arriving = false;
929 }
930
931 void Steering::GoTo(const glm::dvec3 &t) noexcept {
932         target = t;
933         halting = false;
934         seeking = false;
935         arriving = true;
936 }
937
938 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
939         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
940         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
941         glm::dvec3 result(0.0);
942         if (separating) {
943                 // TODO: off surface situation
944                 glm::dvec3 repulse(0.0);
945                 const Situation &s = c.GetSituation();
946                 for (auto &other : s.GetPlanet().Creatures()) {
947                         if (&*other == &c) continue;
948                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
949                         if (length2(diff) > max_look * max_look) continue;
950                         if (!c.PerceptionTest(other->GetSituation().Position())) continue;
951                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
952                         if (sep < min_dist) {
953                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
954                         }
955                 }
956                 result += repulse;
957         }
958         if (halting) {
959                 // break twice as hard
960                 result += -2.0 * s.vel * force;
961         }
962         if (seeking) {
963                 glm::dvec3 diff = target - s.pos;
964                 if (!allzero(diff)) {
965                         result += TargetVelocity(s, (normalize(diff) * speed), force);
966                 }
967         }
968         if (arriving) {
969                 glm::dvec3 diff = target - s.pos;
970                 double dist = length(diff);
971                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
972                         result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
973                 }
974         }
975         if (length2(result) > max_force * max_force) {
976                 result = normalize(result) * max_force;
977         }
978         return result;
979 }
980
981 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
982         return (vel - s.vel) * acc;
983 }
984
985 }
986 }