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