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