]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
fb6e9f6540b2872152bc390d07623cf779cfe26b
[blobs.git] / src / creature / creature.cpp
1 #include "Composition.hpp"
2 #include "Creature.hpp"
3 #include "Genome.hpp"
4 #include "Memory.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
8
9 #include "BlobBackgroundTask.hpp"
10 #include "Goal.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
19
20 #include <algorithm>
21 #include <sstream>
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
24
25 #include <iostream>
26 #include <glm/gtx/io.hpp>
27
28
29 namespace blobs {
30 namespace creature {
31
32 Composition::Composition()
33 : components()
34 , total_mass(0.0) {
35 }
36
37 Composition::~Composition() {
38 }
39
40 namespace {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42         return b.value < a.value;
43 }
44 }
45
46 void Composition::Add(int res, double amount) {
47         bool found = false;
48         for (auto &c : components) {
49                 if (c.resource == res) {
50                         c.value += amount;
51                         found = true;
52                         break;
53                 }
54         }
55         if (!found) {
56                 components.emplace_back(res, amount);
57         }
58         std::sort(components.begin(), components.end(), CompositionCompare);
59         total_mass += amount;
60 }
61
62 bool Composition::Has(int res) const noexcept {
63         for (auto &c : components) {
64                 if (c.resource == res) {
65                         return true;
66                 }
67         }
68         return false;
69 }
70
71 double Composition::Get(int res) const noexcept {
72         for (auto &c : components) {
73                 if (c.resource == res) {
74                         return c.value;
75                 }
76         }
77         return 0.0;
78 }
79
80
81 Creature::Creature(world::Simulation &sim)
82 : sim(sim)
83 , name()
84 , genome()
85 , properties()
86 , composition()
87 , base_color(1.0)
88 , highlight_color(0.0, 0.0, 0.0, 1.0)
89 , mass(1.0)
90 , size(1.0)
91 , birth(sim.Time())
92 , death(0.0)
93 , on_death()
94 , removable(false)
95 , parents()
96 , stats()
97 , memory(*this)
98 , bg_task()
99 , goals()
100 , situation()
101 , steering(*this)
102 , vao() {
103         sim.SetAlive(this);
104         // all creatures avoid each other for now
105         steering.Separate(0.1, 1.5);
106 }
107
108 Creature::~Creature() {
109 }
110
111 void Creature::AddMass(int res, double amount) {
112         composition.Add(res, amount);
113         double nonsolid = 0.0;
114         double volume = 0.0;
115         for (const auto &c : composition) {
116                 volume += c.value / sim.Assets().data.resources[c.resource].density;
117                 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
118                         nonsolid += c.value;
119                 }
120         }
121         Mass(composition.TotalMass());
122         Size(std::cbrt(volume));
123         highlight_color.a = nonsolid / composition.TotalMass();
124 }
125
126 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
127         highlight_color = glm::dvec4(c, highlight_color.a);
128 }
129
130 void Creature::Ingest(int res, double amount) noexcept {
131         // TODO: check foreign materials
132         if (sim.Resources()[res].state == world::Resource::SOLID) {
133                 // 15% of solids stays in body
134                 AddMass(res, amount * 0.15);
135         } else {
136                 // 10% of fluids stays in body
137                 AddMass(res, amount * 0.05);
138         }
139 }
140
141 void Creature::Hurt(double amount) noexcept {
142         stats.Damage().Add(amount);
143         if (stats.Damage().Full()) {
144                 std::cout << "[" << ui::TimeString(sim.Time()) << "] " << name << " ";
145                 if (stats.Exhaustion().Full()) {
146                         std::cout << "died of exhaustion";
147                 } else if (stats.Breath().Full()) {
148                         std::cout << "suffocated";
149                 } else if (stats.Thirst().Full()) {
150                         std::cout << "died of thirst";
151                 } else if (stats.Hunger().Full()) {
152                         std::cout << "starved to death";
153                 } else {
154                         std::cout << "succumed to wounds";
155                 }
156                 std::cout << " at an age of " << ui::TimeString(Age())
157                         << " (" << ui::PercentageString(Age() / properties.Lifetime())
158                         << "% of life expectancy of " << ui::TimeString(properties.Lifetime())
159                         << ")" << std::endl;
160                 Die();
161         }
162 }
163
164 void Creature::Die() noexcept {
165         sim.SetDead(this);
166         death = sim.Time();
167         steering.Halt();
168         if (on_death) {
169                 on_death(*this);
170         }
171         Remove();
172 }
173
174 void Creature::Remove() noexcept {
175         removable = true;
176 }
177
178 void Creature::Removed() noexcept {
179         bg_task.reset();
180         goals.clear();
181         memory.Erase();
182         KillVAO();
183 }
184
185 void Creature::AddParent(Creature &p) {
186         parents.push_back(&p);
187 }
188
189 double Creature::Age() const noexcept {
190         return sim.Time() - birth;
191 }
192
193 double Creature::AgeFactor(double peak) const noexcept {
194         // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
195         // goes negative below -0.5 and starts to rise again above 1.0
196         double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
197         return 1.0 - (3.0 * t * t) + (2.0 * t * t * t);
198 }
199
200 double Creature::ExhaustionFactor() const noexcept {
201         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
202 }
203
204 double Creature::FatigueFactor() const noexcept {
205         return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
206 }
207
208 double Creature::Strength() const noexcept {
209         // TODO: replace all age factors with actual growth and decay
210         return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
211 }
212
213 double Creature::Stamina() const noexcept {
214         return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
215 }
216
217 double Creature::Dexerty() const noexcept {
218         return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
219 }
220
221 double Creature::Intelligence() const noexcept {
222         return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
223 }
224
225 double Creature::Lifetime() const noexcept {
226         return properties.Lifetime();
227 }
228
229 double Creature::Fertility() const noexcept {
230         return properties.Fertility() * AgeFactor(0.25);
231 }
232
233 double Creature::Mutability() const noexcept {
234         return properties.Mutability();
235 }
236
237 double Creature::OffspringMass() const noexcept {
238         return properties.OffspringMass();
239 }
240
241 double Creature::OffspringChance() const noexcept {
242         return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
243 }
244
245 double Creature::MutateChance() const noexcept {
246         return GetProperties().Mutability() * (1.0 / 3600.0);
247 }
248
249 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
250         g->Enable();
251         goals.emplace_back(std::move(g));
252 }
253
254 namespace {
255
256 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
257         return b->Urgency() < a->Urgency();
258 }
259
260 }
261
262 void Creature::Tick(double dt) {
263         TickState(dt);
264         TickStats(dt);
265         TickBrain(dt);
266 }
267
268 void Creature::TickState(double dt) {
269         steering.MaxSpeed(Dexerty());
270         steering.MaxForce(Strength());
271         Situation::State state(situation.GetState());
272         Situation::Derivative a(Step(Situation::Derivative(), 0.0));
273         Situation::Derivative b(Step(a, dt * 0.5));
274         Situation::Derivative c(Step(b, dt * 0.5));
275         Situation::Derivative d(Step(c, dt));
276         Situation::Derivative f(
277                 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
278                 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
279         );
280         state.pos += f.vel * dt;
281         state.vel += f.acc * dt;
282         situation.EnforceConstraints(state);
283         if (length2(state.vel) > 0.000001) {
284                 glm::dvec3 nvel(normalize(state.vel));
285                 double ang = angle(nvel, state.dir);
286                 double turn_rate = PI * 0.75 * dt;
287                 if (ang < turn_rate) {
288                         state.dir = normalize(state.vel);
289                 } else if (std::abs(ang - PI) < 0.001) {
290                         state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
291                 } else {
292                         state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
293                 }
294         }
295         situation.SetState(state);
296         stats.Exhaustion().Add(length(f.acc) * Mass() / Stamina() * 0.5 * dt);
297 }
298
299 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
300         Situation::State s = situation.GetState();
301         s.pos += ds.vel * dt;
302         s.vel += ds.acc * dt;
303         glm::dvec3 force(steering.Force(s));
304         // gravity = antinormal * mass * Gm / r²
305         double elevation = s.pos[(situation.Surface() + 2) % 3];
306         glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
307         force += glm::dvec3(
308                 -normal
309                 * Mass() * situation.GetPlanet().GravitationalParameter()
310                 / (elevation * elevation));
311         // if net force is applied and in contact with surface
312         if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
313                 // apply friction = -|normal force| * tangential force * coefficient
314                 glm::dvec3 fn(normal * dot(force, normal));
315                 glm::dvec3 ft(force - fn);
316                 double u = 0.4;
317                 glm::dvec3 friction(-length(fn) * ft * u);
318                 force += friction;
319         }
320         return {
321                 s.vel,
322                 force / Mass()
323         };
324 }
325
326 void Creature::TickStats(double dt) {
327         for (auto &s : stats.stat) {
328                 s.Add(s.gain * dt);
329         }
330         stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
331         // TODO: damage values depending on properties
332         if (stats.Breath().Full()) {
333                 constexpr double dps = 1.0 / 4.0;
334                 Hurt(dps * dt);
335         }
336         if (stats.Thirst().Full()) {
337                 constexpr double dps = 1.0 / 32.0;
338                 Hurt(dps * dt);
339         }
340         if (stats.Hunger().Full()) {
341                 constexpr double dps = 1.0 / 128.0;
342                 Hurt(dps * dt);
343         }
344         if (!situation.Moving()) {
345                 // double exhaustion recovery when standing still
346                 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
347         }
348 }
349
350 void Creature::TickBrain(double dt) {
351         bg_task->Tick(dt);
352         bg_task->Action();
353         memory.Tick(dt);
354         // do background stuff
355         if (goals.empty()) {
356                 return;
357         }
358         for (auto &goal : goals) {
359                 goal->Tick(dt);
360         }
361         // if active goal can be interrupted, check priorities
362         if (goals.size() > 1 && goals[0]->Interruptible()) {
363                 std::sort(goals.begin(), goals.end(), GoalCompare);
364         }
365         goals[0]->Action();
366         for (auto goal = goals.begin(); goal != goals.end();) {
367                 if ((*goal)->Complete()) {
368                         goals.erase(goal);
369                 } else {
370                         ++goal;
371                 }
372         }
373 }
374
375 math::AABB Creature::CollisionBox() const noexcept {
376         return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
377 }
378
379 glm::dmat4 Creature::CollisionTransform() const noexcept {
380         const double half_size = size * 0.5;
381         const glm::dvec3 &pos = situation.Position();
382         const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
383         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
384                 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
385                 * glm::dmat4(srf);
386 }
387
388 glm::dmat4 Creature::LocalTransform() noexcept {
389         const double half_size = size * 0.5;
390         return CollisionTransform()
391                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
392 }
393
394 void Creature::BuildVAO() {
395         vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
396         vao->Bind();
397         vao->BindAttributes();
398         vao->EnableAttribute(0);
399         vao->EnableAttribute(1);
400         vao->EnableAttribute(2);
401         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
402         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
403         vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
404         vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
405         {
406                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
407                 const float offset = 1.0f;
408                 for (int surface = 0; surface < 6; ++surface) {
409                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
410                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
411
412                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
413                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
414                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
415                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
416                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
417                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
418                         attrib[4 * surface + 0].texture.x = tex_u_begin;
419                         attrib[4 * surface + 0].texture.y = 1.0f;
420                         attrib[4 * surface + 0].texture.z = surface;
421
422                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
423                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
424                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
425                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
426                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
427                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
428                         attrib[4 * surface + 1].texture.x = tex_u_end;
429                         attrib[4 * surface + 1].texture.y = 1.0f;
430                         attrib[4 * surface + 1].texture.z = surface;
431
432                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
433                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
434                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
435                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
436                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
437                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
438                         attrib[4 * surface + 2].texture.x = tex_u_begin;
439                         attrib[4 * surface + 2].texture.y = 0.0f;
440                         attrib[4 * surface + 2].texture.z = surface;
441
442                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
443                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
444                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
445                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
446                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
447                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
448                         attrib[4 * surface + 3].texture.x = tex_u_end;
449                         attrib[4 * surface + 3].texture.y = 0.0f;
450                         attrib[4 * surface + 3].texture.z = surface;
451                 }
452         }
453         vao->BindElements();
454         vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
455         {
456                 auto element = vao->MapElements(GL_WRITE_ONLY);
457                 for (int surface = 0; surface < 3; ++surface) {
458                         element[6 * surface + 0] = 4 * surface + 0;
459                         element[6 * surface + 1] = 4 * surface + 2;
460                         element[6 * surface + 2] = 4 * surface + 1;
461                         element[6 * surface + 3] = 4 * surface + 1;
462                         element[6 * surface + 4] = 4 * surface + 2;
463                         element[6 * surface + 5] = 4 * surface + 3;
464                 }
465                 for (int surface = 3; surface < 6; ++surface) {
466                         element[6 * surface + 0] = 4 * surface + 0;
467                         element[6 * surface + 1] = 4 * surface + 1;
468                         element[6 * surface + 2] = 4 * surface + 2;
469                         element[6 * surface + 3] = 4 * surface + 2;
470                         element[6 * surface + 4] = 4 * surface + 1;
471                         element[6 * surface + 5] = 4 * surface + 3;
472                 }
473         }
474         vao->Unbind();
475 }
476
477 void Creature::KillVAO() {
478         vao.reset();
479 }
480
481 void Creature::Draw(graphics::Viewport &viewport) {
482         if (!vao) return;
483         vao->Bind();
484         vao->DrawTriangles(6 * 6);
485 }
486
487
488 void Spawn(Creature &c, world::Planet &p) {
489         p.AddCreature(&c);
490         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
491         c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
492
493         // probe surrounding area for common resources
494         int start = p.SideLength() / 2 - 2;
495         int end = start + 5;
496         std::map<int, double> yields;
497         for (int y = start; y < end; ++y) {
498                 for (int x = start; x < end; ++x) {
499                         const world::TileType &t = p.TypeAt(0, x, y);
500                         for (auto yield : t.resources) {
501                                 yields[yield.resource] += yield.ubiquity;
502                         }
503                 }
504         }
505         int liquid = -1;
506         int solid = -1;
507         for (auto e : yields) {
508                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
509                         if (liquid < 0 || e.second > yields[liquid]) {
510                                 liquid = e.first;
511                         }
512                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
513                         if (solid < 0 || e.second > yields[solid]) {
514                                 solid = e.first;
515                         }
516                 }
517         }
518
519         Genome genome;
520         genome.properties.Strength() = { 2.0, 0.1 };
521         genome.properties.Stamina() = { 2.0, 0.1 };
522         genome.properties.Dexerty() = { 2.0, 0.1 };
523         genome.properties.Intelligence() = { 1.0, 0.1 };
524         genome.properties.Lifetime() = { 480.0, 60.0 };
525         genome.properties.Fertility() = { 0.5, 0.03 };
526         genome.properties.Mutability() = { 1.0, 0.1 };
527         genome.properties.OffspringMass() = { 0.3, 0.02 };
528
529         glm::dvec3 color_avg(0.0);
530         double color_divisor = 0.0;
531
532         if (p.HasAtmosphere()) {
533                 c.AddMass(p.Atmosphere(), 0.01);
534                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
535                 color_divisor += 0.1;
536         }
537         if (liquid > -1) {
538                 c.AddMass(liquid, 0.3);
539                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
540                 color_divisor += 0.5;
541         }
542         if (solid > -1) {
543                 c.AddMass(solid, 0.1);
544                 color_avg += c.GetSimulation().Resources()[solid].base_color;
545                 color_divisor += 1.0;
546         }
547
548         if (color_divisor > 0.001) {
549                 color_avg /= color_divisor;
550         }
551         glm::dvec3 hsl = rgb2hsl(color_avg);
552         genome.base_hue = { hsl.x, 0.01 };
553         genome.base_saturation = { hsl.y, 0.01 };
554         genome.base_lightness = { hsl.z, 0.01 };
555
556         genome.Configure(c);
557 }
558
559 void Genome::Configure(Creature &c) const {
560         c.GetGenome() = *this;
561
562         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
563
564         c.GetProperties() = Instantiate(properties, random);
565
566         // TODO: derive stats from properties
567         c.GetStats().Damage().gain = (-1.0 / 100.0);
568         c.GetStats().Breath().gain = (1.0 / 5.0);
569         c.GetStats().Thirst().gain = (1.0 / 60.0);
570         c.GetStats().Hunger().gain = (1.0 / 200.0);
571         c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
572         c.GetStats().Fatigue().gain = (-1.0 / 100.0);
573         c.GetStats().Boredom().gain = (1.0 / 300.0);
574
575         glm::dvec3 base_color(
576                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
577                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
578                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
579         );
580         glm::dvec3 highlight_color(
581                 std::fmod(base_color.x + 0.5, 1.0),
582                 1.0 - base_color.y,
583                 1.0 - base_color.z
584         );
585         c.BaseColor(hsl2rgb(base_color));
586         c.HighlightColor(hsl2rgb(highlight_color));
587         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
588         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
589 }
590
591
592 void Split(Creature &c) {
593         Creature *a = new Creature(c.GetSimulation());
594         const Situation &s = c.GetSituation();
595         a->AddParent(c);
596         a->Name(c.GetSimulation().Assets().name.Sequential());
597         c.GetGenome().Configure(*a);
598         for (const auto &cmp : c.GetComposition()) {
599                 a->AddMass(cmp.resource, cmp.value * 0.5);
600         }
601         s.GetPlanet().AddCreature(a);
602         // TODO: duplicate situation somehow
603         a->GetSituation().SetPlanetSurface(
604                 s.GetPlanet(), s.Surface(),
605                 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
606         a->BuildVAO();
607         std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
608                 << a->Name() << " was born" << std::endl;
609
610         Creature *b = new Creature(c.GetSimulation());
611         b->AddParent(c);
612         b->Name(c.GetSimulation().Assets().name.Sequential());
613         c.GetGenome().Configure(*b);
614         for (const auto &cmp : c.GetComposition()) {
615                 b->AddMass(cmp.resource, cmp.value * 0.5);
616         }
617         s.GetPlanet().AddCreature(b);
618         b->GetSituation().SetPlanetSurface(
619                 s.GetPlanet(), s.Surface(),
620                 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
621         b->BuildVAO();
622         std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
623                 << b->Name() << " was born" << std::endl;
624
625         c.Die();
626 }
627
628
629 Memory::Memory(Creature &c)
630 : c(c) {
631 }
632
633 Memory::~Memory() {
634 }
635
636 void Memory::Erase() {
637         known_types.clear();
638 }
639
640 void Memory::Tick(double dt) {
641         Situation &s = c.GetSituation();
642         if (s.OnTile()) {
643                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
644         }
645 }
646
647 void Memory::TrackStay(const Location &l, double t) {
648         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
649         auto entry = known_types.find(type.id);
650         if (entry != known_types.end()) {
651                 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
652                         // "it's been ages"
653                         if (entry->second.time_spent > c.Age() * 0.25) {
654                                 // the place is very familiar
655                                 c.GetStats().Boredom().Add(-0.2);
656                         } else {
657                                 // infrequent stays
658                                 c.GetStats().Boredom().Add(-0.1);
659                         }
660                 }
661                 entry->second.last_been = c.GetSimulation().Time();
662                 entry->second.last_loc = l;
663                 entry->second.time_spent += t;
664         } else {
665                 known_types.emplace(type.id, Stay{
666                         c.GetSimulation().Time(),
667                         l,
668                         c.GetSimulation().Time(),
669                         l,
670                         t
671                 });
672                 // completely new place, interesting
673                 // TODO: scale by personality trait
674                 c.GetStats().Boredom().Add(-0.25);
675         }
676 }
677
678
679 NameGenerator::NameGenerator()
680 : counter(0) {
681 }
682
683 NameGenerator::~NameGenerator() {
684 }
685
686 std::string NameGenerator::Sequential() {
687         std::stringstream ss;
688         ss << "Blob " << ++counter;
689         return ss.str();
690 }
691
692
693 Situation::Situation()
694 : planet(nullptr)
695 , state(glm::dvec3(0.0), glm::dvec3(0.0))
696 , surface(0)
697 , type(LOST) {
698 }
699
700 Situation::~Situation() {
701 }
702
703 bool Situation::OnPlanet() const noexcept {
704         return type == PLANET_SURFACE;
705 }
706
707 bool Situation::OnSurface() const noexcept {
708         return type == PLANET_SURFACE;
709 }
710
711 bool Situation::OnTile() const noexcept {
712         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
713         return type == PLANET_SURFACE
714                 && t.x >= 0 && t.x < planet->SideLength()
715                 && t.y >= 0 && t.y < planet->SideLength();
716 }
717
718 glm::ivec2 Situation::SurfacePosition() const noexcept {
719         return planet->SurfacePosition(surface, state.pos);
720 }
721
722 world::Tile &Situation::GetTile() const noexcept {
723         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
724         return planet->TileAt(surface, t.x, t.y);
725 }
726
727 const world::TileType &Situation::GetTileType() const noexcept {
728         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
729         return planet->TypeAt(surface, t.x, t.y);
730 }
731
732 void Situation::Move(const glm::dvec3 &dp) noexcept {
733         state.pos += dp;
734         EnforceConstraints(state);
735 }
736
737 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
738         state.vel += dv;
739         EnforceConstraints(state);
740 }
741
742 void Situation::EnforceConstraints(State &s) noexcept {
743         if (OnSurface()) {
744                 if (Surface() < 3) {
745                         if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
746                                 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
747                                 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
748                         }
749                 } else {
750                         if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
751                                 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
752                                 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
753                         }
754                 }
755         }
756 }
757
758 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
759         type = PLANET_SURFACE;
760         planet = &p;
761         surface = srf;
762         state.pos = pos;
763         EnforceConstraints(state);
764 }
765
766
767 Steering::Steering(const Creature &c)
768 : c(c)
769 , target(0.0)
770 , haste(0.0)
771 , max_force(1.0)
772 , max_speed(1.0)
773 , min_dist(0.0)
774 , max_look(0.0)
775 , separating(false)
776 , halting(true)
777 , seeking(false)
778 , arriving(false) {
779 }
780
781 Steering::~Steering() {
782 }
783
784 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
785         separating = true;
786         min_dist = min_distance;
787         max_look = max_lookaround;
788 }
789
790 void Steering::DontSeparate() noexcept {
791         separating = false;
792 }
793
794 void Steering::ResumeSeparate() noexcept {
795         separating = true;
796 }
797
798 void Steering::Halt() noexcept {
799         halting = true;
800         seeking = false;
801         arriving = false;
802 }
803
804 void Steering::Pass(const glm::dvec3 &t) noexcept {
805         target = t;
806         halting = false;
807         seeking = true;
808         arriving = false;
809 }
810
811 void Steering::GoTo(const glm::dvec3 &t) noexcept {
812         target = t;
813         halting = false;
814         seeking = false;
815         arriving = true;
816 }
817
818 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
819         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
820         double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
821         glm::dvec3 result(0.0);
822         if (separating) {
823                 // TODO: off surface situation
824                 glm::dvec3 repulse(0.0);
825                 const Situation &s = c.GetSituation();
826                 for (auto &other : s.GetPlanet().Creatures()) {
827                         if (&*other == &c) continue;
828                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
829                         if (length2(diff) > max_look * max_look) continue;
830                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
831                         if (sep < min_dist) {
832                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
833                         }
834                 }
835                 SumForce(result, repulse, force);
836         }
837         if (halting) {
838                 SumForce(result, s.vel * -force, force);
839         }
840         if (seeking) {
841                 glm::dvec3 diff = target - s.pos;
842                 if (!allzero(diff)) {
843                         SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
844                 }
845         }
846         if (arriving) {
847                 glm::dvec3 diff = target - s.pos;
848                 double dist = length(diff);
849                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
850                         SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
851                 }
852         }
853         return result;
854 }
855
856 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
857         if (allzero(in) || anynan(in)) {
858                 return false;
859         }
860         double cur = allzero(out) ? 0.0 : length(out);
861         double rem = max - cur;
862         if (rem < 0.0) {
863                 return true;
864         }
865         double add = length(in);
866         if (add > rem) {
867                 // this method is off if in and out are in different
868                 // directions, but gives okayish results
869                 out += in * (1.0 / add);
870                 return true;
871         } else {
872                 out += in;
873                 return false;
874         }
875 }
876
877 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
878         return (vel - s.vel) * acc;
879 }
880
881 }
882 }