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