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