]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
a9c4dc73c613312e18da52b3a2ead77ddc827643
[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         if (stats.Damage().Full()) {
220                 std::ostream &log = sim.Log() << name << " ";
221                 if (stats.Exhaustion().Full()) {
222                         log << "died of exhaustion";
223                 } else if (stats.Breath().Full()) {
224                         log << "suffocated";
225                 } else if (stats.Thirst().Full()) {
226                         log << "died of thirst";
227                 } else if (stats.Hunger().Full()) {
228                         log << "starved to death";
229                 } else {
230                         log << "succumed to wounds";
231                 }
232                 log << " at an age of " << ui::TimeString(Age())
233                         << " (" << ui::PercentageString(Age() / properties.Lifetime())
234                         << " of life expectancy of " << ui::TimeString(properties.Lifetime())
235                         << ")" << std::endl;
236         }
237
238         sim.SetDead(this);
239         death = sim.Time();
240         steering.Off();
241         if (on_death) {
242                 on_death(*this);
243         }
244         Remove();
245 }
246
247 bool Creature::Dead() const noexcept {
248         return death > birth;
249 }
250
251 void Creature::Remove() noexcept {
252         removable = true;
253 }
254
255 void Creature::Removed() noexcept {
256         bg_task.reset();
257         goals.clear();
258         memory.Erase();
259         KillVAO();
260 }
261
262 void Creature::AddParent(Creature &p) {
263         parents.push_back(&p);
264 }
265
266 double Creature::Age() const noexcept {
267         return sim.Time() - birth;
268 }
269
270 double Creature::AgeFactor(double peak) const noexcept {
271         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
272         // goes negative below -0.5 and starts to rise again above 1.0
273         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
274         // guarantee at least 1%
275         return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
276 }
277
278 double Creature::EnergyEfficiency() const noexcept {
279         return 0.25 * AgeFactor(0.05);
280 }
281
282 double Creature::ExhaustionFactor() const noexcept {
283         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
284 }
285
286 double Creature::FatigueFactor() const noexcept {
287         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
288 }
289
290 double Creature::Strength() const noexcept {
291         // TODO: replace all age factors with actual growth and decay
292         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
293 }
294
295 double Creature::Stamina() const noexcept {
296         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
297 }
298
299 double Creature::Dexerty() const noexcept {
300         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
301 }
302
303 double Creature::Intelligence() const noexcept {
304         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
305 }
306
307 double Creature::Lifetime() const noexcept {
308         return properties.Lifetime();
309 }
310
311 double Creature::Fertility() const noexcept {
312         return properties.Fertility() * AgeFactor(0.25);
313 }
314
315 double Creature::Mutability() const noexcept {
316         return properties.Mutability();
317 }
318
319 double Creature::Adaptability() const noexcept {
320         return properties.Adaptability();
321 }
322
323 double Creature::OffspringMass() const noexcept {
324         return properties.OffspringMass();
325 }
326
327 double Creature::PerceptionRange() const noexcept {
328         return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
329 }
330
331 double Creature::PerceptionOmniRange() const noexcept {
332         return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
333 }
334
335 double Creature::PerceptionField() const noexcept {
336         // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
337         return 0.8 - (Dexerty() / (Dexerty() + 1));
338 }
339
340 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
341         const glm::dvec3 diff(p - situation.Position());
342         double omni_range = PerceptionOmniRange();
343         if (length2(diff) < omni_range * omni_range) return true;
344         double range = PerceptionRange();
345         if (length2(diff) > range * range) return false;
346         return dot(normalize(diff), situation.Heading()) > PerceptionField();
347 }
348
349 double Creature::OffspringChance() const noexcept {
350         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
351 }
352
353 double Creature::MutateChance() const noexcept {
354         return GetProperties().Mutability() * (1.0 / 3600.0);
355 }
356
357 double Creature::AdaptChance() const noexcept {
358         return GetProperties().Adaptability() * (1.0 / 120.0);
359 }
360
361 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
362         g->Enable();
363         goals.emplace_back(std::move(g));
364 }
365
366 namespace {
367
368 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
369         return b->Urgency() < a->Urgency();
370 }
371
372 }
373
374 void Creature::Tick(double dt) {
375         TickState(dt);
376         TickStats(dt);
377         TickBrain(dt);
378 }
379
380 void Creature::TickState(double dt) {
381         steering.MaxSpeed(Dexerty());
382         steering.MaxForce(Strength());
383         Situation::State state(situation.GetState());
384         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
385         Situation::Derivative b(Step(a, dt * 0.5));
386         Situation::Derivative c(Step(b, dt * 0.5));
387         Situation::Derivative d(Step(c, dt));
388         Situation::Derivative f(
389                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
390                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
391         );
392         state.pos += f.vel * dt;
393         state.vel += f.acc * dt;
394         situation.EnforceConstraints(state);
395         if (length2(state.vel) > 0.000001) {
396                 glm::dvec3 nvel(normalize(state.vel));
397                 double ang = angle(nvel, state.dir);
398                 double turn_rate = PI * 0.75 * dt;
399                 if (ang < turn_rate) {
400                         state.dir = normalize(state.vel);
401                 } else if (std::abs(ang - PI) < 0.001) {
402                         state.dir = rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
403                 } else {
404                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
405                 }
406         }
407         situation.SetState(state);
408         // work is force times distance
409         DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
410 }
411
412 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
413         Situation::State s = situation.GetState();
414         s.pos += ds.vel * dt;
415         s.vel += ds.acc * dt;
416         glm::dvec3 force(steering.Force(s));
417         // gravity = antinormal * mass * Gm / r²
418         double elevation = situation.GetPlanet().DistanceAt(s.pos);
419         glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
420         force += glm::dvec3(
421                 -normal
422                 * Mass() * situation.GetPlanet().GravitationalParameter()
423                 / (elevation * elevation));
424         // if net force is applied and in contact with surface
425         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
426                 // apply friction = -|normal force| * tangential force * coefficient
427                 glm::dvec3 fn(normal * dot(force, normal));
428                 glm::dvec3 ft(force - fn);
429                 double u = 0.4;
430                 glm::dvec3 friction(-length(fn) * ft * u);
431                 force += friction;
432         }
433         return {
434                 s.vel,
435                 force / Mass()
436         };
437 }
438
439 void Creature::TickStats(double dt) {
440         for (auto &s : stats.stat) {
441                 s.Add(s.gain * dt);
442         }
443         // TODO: damage values depending on properties
444         if (stats.Breath().Full()) {
445                 constexpr double dps = 1.0 / 4.0;
446                 Hurt(dps * dt);
447         }
448         if (stats.Thirst().Full()) {
449                 constexpr double dps = 1.0 / 32.0;
450                 Hurt(dps * dt);
451         }
452         if (stats.Hunger().Full()) {
453                 constexpr double dps = 1.0 / 128.0;
454                 Hurt(dps * dt);
455         }
456         if (!situation.Moving()) {
457                 // double exhaustion recovery when standing still
458                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
459         }
460 }
461
462 void Creature::TickBrain(double dt) {
463         bg_task->Tick(dt);
464         bg_task->Action();
465         memory.Tick(dt);
466         // do background stuff
467         if (goals.empty()) {
468                 return;
469         }
470         for (auto &goal : goals) {
471                 goal->Tick(dt);
472         }
473         // if active goal can be interrupted, check priorities
474         if (goals.size() > 1 && goals[0]->Interruptible()) {
475                 std::sort(goals.begin(), goals.end(), GoalCompare);
476         }
477         goals[0]->Action();
478         for (auto goal = goals.begin(); goal != goals.end();) {
479                 if ((*goal)->Complete()) {
480                         goals.erase(goal);
481                 } else {
482                         ++goal;
483                 }
484         }
485 }
486
487 math::AABB Creature::CollisionBox() const noexcept {
488         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
489 }
490
491 glm::dmat4 Creature::CollisionTransform() const noexcept {
492         const double half_size = size * 0.5;
493         const glm::dvec3 &pos = situation.Position();
494         glm::dmat3 orient;
495         orient[1] = situation.GetPlanet().NormalAt(pos);
496         orient[2] = situation.Heading();
497         if (std::abs(dot(orient[1], orient[2])) > 0.999) {
498                 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
499         }
500         orient[0] = normalize(cross(orient[1], orient[2]));
501         orient[2] = normalize(cross(orient[0], orient[1]));
502         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
503                 * glm::dmat4(orient);
504 }
505
506 glm::dmat4 Creature::LocalTransform() noexcept {
507         const double half_size = size * 0.5;
508         return CollisionTransform()
509                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
510 }
511
512 void Creature::BuildVAO() {
513         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
514         vao->Bind();
515         vao->BindAttributes();
516         vao->EnableAttribute(0);
517         vao->EnableAttribute(1);
518         vao->EnableAttribute(2);
519         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
520         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
521         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
522         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
523         {
524                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
525                 const float offset = 1.0f;
526                 for (int surface = 0; surface < 6; ++surface) {
527                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
528                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
529
530                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
531                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
532                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
533                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
534                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
535                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
536                         attrib[4 * surface + 0].texture.x = tex_u_begin;
537                         attrib[4 * surface + 0].texture.y = 1.0f;
538                         attrib[4 * surface + 0].texture.z = surface;
539
540                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
541                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
542                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
543                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
544                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
545                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
546                         attrib[4 * surface + 1].texture.x = tex_u_end;
547                         attrib[4 * surface + 1].texture.y = 1.0f;
548                         attrib[4 * surface + 1].texture.z = surface;
549
550                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
551                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
552                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
553                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
554                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
555                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
556                         attrib[4 * surface + 2].texture.x = tex_u_begin;
557                         attrib[4 * surface + 2].texture.y = 0.0f;
558                         attrib[4 * surface + 2].texture.z = surface;
559
560                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
561                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
562                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
563                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
564                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
565                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
566                         attrib[4 * surface + 3].texture.x = tex_u_end;
567                         attrib[4 * surface + 3].texture.y = 0.0f;
568                         attrib[4 * surface + 3].texture.z = surface;
569                 }
570         }
571         vao->BindElements();
572         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
573         {
574                 auto element = vao->MapElements(GL_WRITE_ONLY);
575                 for (int surface = 0; surface < 3; ++surface) {
576                         element[6 * surface + 0] = 4 * surface + 0;
577                         element[6 * surface + 1] = 4 * surface + 2;
578                         element[6 * surface + 2] = 4 * surface + 1;
579                         element[6 * surface + 3] = 4 * surface + 1;
580                         element[6 * surface + 4] = 4 * surface + 2;
581                         element[6 * surface + 5] = 4 * surface + 3;
582                 }
583                 for (int surface = 3; surface < 6; ++surface) {
584                         element[6 * surface + 0] = 4 * surface + 0;
585                         element[6 * surface + 1] = 4 * surface + 1;
586                         element[6 * surface + 2] = 4 * surface + 2;
587                         element[6 * surface + 3] = 4 * surface + 2;
588                         element[6 * surface + 4] = 4 * surface + 1;
589                         element[6 * surface + 5] = 4 * surface + 3;
590                 }
591         }
592         vao->Unbind();
593 }
594
595 void Creature::KillVAO() {
596         vao.reset();
597 }
598
599 void Creature::Draw(graphics::Viewport &viewport) {
600         if (!vao) return;
601         vao->Bind();
602         vao->DrawTriangles(6 * 6);
603 }
604
605
606 void Spawn(Creature &c, world::Planet &p) {
607         p.AddCreature(&c);
608         c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
609         c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
610
611         // probe surrounding area for common resources
612         int start = p.SideLength() / 2 - 2;
613         int end = start + 5;
614         std::map<int, double> yields;
615         for (int y = start; y < end; ++y) {
616                 for (int x = start; x < end; ++x) {
617                         const world::TileType &t = p.TypeAt(0, x, y);
618                         for (auto yield : t.resources) {
619                                 yields[yield.resource] += yield.ubiquity;
620                         }
621                 }
622         }
623         int liquid = -1;
624         int solid = -1;
625         for (auto e : yields) {
626                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
627                         if (liquid < 0 || e.second > yields[liquid]) {
628                                 liquid = e.first;
629                         }
630                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
631                         if (solid < 0 || e.second > yields[solid]) {
632                                 solid = e.first;
633                         }
634                 }
635         }
636
637         Genome genome;
638         genome.properties.Strength() = { 2.0, 0.1 };
639         genome.properties.Stamina() = { 2.0, 0.1 };
640         genome.properties.Dexerty() = { 2.0, 0.1 };
641         genome.properties.Intelligence() = { 1.0, 0.1 };
642         genome.properties.Lifetime() = { 480.0, 60.0 };
643         genome.properties.Fertility() = { 0.5, 0.03 };
644         genome.properties.Mutability() = { 0.9, 0.1 };
645         genome.properties.Adaptability() = { 0.9, 0.1 };
646         genome.properties.OffspringMass() = { 0.3, 0.02 };
647
648         glm::dvec3 color_avg(0.0);
649         double color_divisor = 0.0;
650
651         if (p.HasAtmosphere()) {
652                 c.AddMass(p.Atmosphere(), 0.01);
653                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
654                 color_divisor += 0.1;
655         }
656         if (liquid > -1) {
657                 c.AddMass(liquid, 0.3);
658                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
659                 color_divisor += 0.5;
660         }
661         if (solid > -1) {
662                 c.AddMass(solid, 0.1);
663                 color_avg += c.GetSimulation().Resources()[solid].base_color;
664                 color_divisor += 1.0;
665         }
666
667         if (color_divisor > 0.001) {
668                 color_avg /= color_divisor;
669         }
670         glm::dvec3 hsl = rgb2hsl(color_avg);
671         genome.base_hue = { hsl.x, 0.01 };
672         genome.base_saturation = { hsl.y, 0.01 };
673         genome.base_lightness = { hsl.z, 0.01 };
674         // use opposite color as start highlight
675         genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
676         genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
677         genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
678
679         genome.Configure(c);
680 }
681
682 void Genome::Configure(Creature &c) const {
683         c.GetGenome() = *this;
684
685         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
686
687         c.GetProperties() = Instantiate(properties, random);
688
689         // TODO: derive stats from properties
690         c.GetStats().Damage().gain = (-1.0 / 100.0);
691         c.GetStats().Breath().gain = (1.0 / 5.0);
692         c.GetStats().Thirst().gain = (1.0 / 60.0);
693         c.GetStats().Hunger().gain = (1.0 / 200.0);
694         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
695         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
696         c.GetStats().Boredom().gain = (1.0 / 300.0);
697
698         glm::dvec3 base_color(
699                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
700                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
701                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
702         );
703         glm::dvec3 highlight_color(
704                 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
705                 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
706                 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
707         );
708         c.BaseColor(hsl2rgb(base_color));
709         c.HighlightColor(hsl2rgb(highlight_color));
710         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
711         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
712 }
713
714
715 void Split(Creature &c) {
716         Creature *a = new Creature(c.GetSimulation());
717         const Situation &s = c.GetSituation();
718         a->AddParent(c);
719         a->Name(c.GetSimulation().Assets().name.Sequential());
720         c.GetGenome().Configure(*a);
721         for (const auto &cmp : c.GetComposition()) {
722                 a->AddMass(cmp.resource, cmp.value * 0.5);
723         }
724         s.GetPlanet().AddCreature(a);
725         // TODO: duplicate situation somehow
726         a->GetSituation().SetPlanetSurface(
727                 s.GetPlanet(),
728                 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
729         a->BuildVAO();
730         c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
731
732         Creature *b = new Creature(c.GetSimulation());
733         b->AddParent(c);
734         b->Name(c.GetSimulation().Assets().name.Sequential());
735         c.GetGenome().Configure(*b);
736         for (const auto &cmp : c.GetComposition()) {
737                 b->AddMass(cmp.resource, cmp.value * 0.5);
738         }
739         s.GetPlanet().AddCreature(b);
740         b->GetSituation().SetPlanetSurface(
741                 s.GetPlanet(),
742                 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
743         b->BuildVAO();
744         c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
745
746         c.Die();
747 }
748
749
750 Memory::Memory(Creature &c)
751 : c(c) {
752 }
753
754 Memory::~Memory() {
755 }
756
757 void Memory::Erase() {
758         known_types.clear();
759 }
760
761 void Memory::Tick(double dt) {
762         Situation &s = c.GetSituation();
763         if (s.OnSurface()) {
764                 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
765         }
766 }
767
768 void Memory::TrackStay(const Location &l, double t) {
769         const world::TileType &type = l.planet->TileTypeAt(l.position);
770         auto entry = known_types.find(type.id);
771         if (entry != known_types.end()) {
772                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
773                         // "it's been ages"
774                         if (entry->second.time_spent > c.Age() * 0.25) {
775                                 // the place is very familiar
776                                 c.GetStats().Boredom().Add(-0.2);
777                         } else {
778                                 // infrequent stays
779                                 c.GetStats().Boredom().Add(-0.1);
780                         }
781                 }
782                 entry->second.last_been = c.GetSimulation().Time();
783                 entry->second.last_loc = l;
784                 entry->second.time_spent += t;
785         } else {
786                 known_types.emplace(type.id, Stay{
787                         c.GetSimulation().Time(),
788                         l,
789                         c.GetSimulation().Time(),
790                         l,
791                         t
792                 });
793                 // completely new place, interesting
794                 // TODO: scale by personality trait
795                 c.GetStats().Boredom().Add(-0.25);
796         }
797 }
798
799
800 NameGenerator::NameGenerator()
801 : counter(0) {
802 }
803
804 NameGenerator::~NameGenerator() {
805 }
806
807 std::string NameGenerator::Sequential() {
808         std::stringstream ss;
809         ss << "Blob " << ++counter;
810         return ss.str();
811 }
812
813
814 Situation::Situation()
815 : planet(nullptr)
816 , state(glm::dvec3(0.0), glm::dvec3(0.0))
817 , type(LOST) {
818 }
819
820 Situation::~Situation() {
821 }
822
823 bool Situation::OnPlanet() const noexcept {
824         return type == PLANET_SURFACE;
825 }
826
827 bool Situation::OnSurface() const noexcept {
828         return type == PLANET_SURFACE;
829 }
830
831 world::Tile &Situation::GetTile() const noexcept {
832         return planet->TileAt(state.pos);
833 }
834
835 const world::TileType &Situation::GetTileType() const noexcept {
836         return planet->TileTypeAt(state.pos);
837 }
838
839 void Situation::Move(const glm::dvec3 &dp) noexcept {
840         state.pos += dp;
841         EnforceConstraints(state);
842 }
843
844 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
845         state.vel += dv;
846         EnforceConstraints(state);
847 }
848
849 void Situation::EnforceConstraints(State &s) noexcept {
850         if (OnSurface()) {
851                 double r = GetPlanet().Radius();
852                 if (length2(s.pos) < r * r) {
853                         s.pos = normalize(s.pos) * r;
854                 }
855         }
856 }
857
858 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
859         type = PLANET_SURFACE;
860         planet = &p;
861         state.pos = pos;
862         EnforceConstraints(state);
863 }
864
865
866 Steering::Steering(const Creature &c)
867 : c(c)
868 , target(0.0)
869 , haste(0.0)
870 , max_force(1.0)
871 , max_speed(1.0)
872 , min_dist(0.0)
873 , max_look(0.0)
874 , separating(false)
875 , halting(true)
876 , seeking(false)
877 , arriving(false) {
878 }
879
880 Steering::~Steering() {
881 }
882
883 void Steering::Off() noexcept {
884         separating = false;
885         halting = false;
886         seeking = false;
887         arriving = false;
888 }
889
890 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
891         separating = true;
892         min_dist = min_distance;
893         max_look = max_lookaround;
894 }
895
896 void Steering::DontSeparate() noexcept {
897         separating = false;
898 }
899
900 void Steering::ResumeSeparate() noexcept {
901         separating = true;
902 }
903
904 void Steering::Halt() noexcept {
905         halting = true;
906         seeking = false;
907         arriving = false;
908 }
909
910 void Steering::Pass(const glm::dvec3 &t) noexcept {
911         target = t;
912         halting = false;
913         seeking = true;
914         arriving = false;
915 }
916
917 void Steering::GoTo(const glm::dvec3 &t) noexcept {
918         target = t;
919         halting = false;
920         seeking = false;
921         arriving = true;
922 }
923
924 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
925         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
926         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
927         glm::dvec3 result(0.0);
928         if (separating) {
929                 // TODO: off surface situation
930                 glm::dvec3 repulse(0.0);
931                 const Situation &s = c.GetSituation();
932                 for (auto &other : s.GetPlanet().Creatures()) {
933                         if (&*other == &c) continue;
934                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
935                         if (length2(diff) > max_look * max_look) continue;
936                         if (!c.PerceptionTest(other->GetSituation().Position())) continue;
937                         double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
938                         repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
939                 }
940                 result += repulse;
941         }
942         if (halting) {
943                 // break twice as hard
944                 result += -2.0 * s.vel * force;
945         }
946         if (seeking) {
947                 glm::dvec3 diff = target - s.pos;
948                 if (!allzero(diff)) {
949                         result += TargetVelocity(s, (normalize(diff) * speed), force);
950                 }
951         }
952         if (arriving) {
953                 glm::dvec3 diff = target - s.pos;
954                 double dist = length(diff);
955                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
956                         result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
957                 }
958         }
959         if (length2(result) > max_force * max_force) {
960                 result = normalize(result) * max_force;
961         }
962         return result;
963 }
964
965 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
966         return (vel - s.vel) * acc;
967 }
968
969 }
970 }