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