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