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