]> git.localhorst.tv Git - blobs.git/blob - src/creature/creature.cpp
74d5751bce5f9f413a9f111cbdd17e8a42862807
[blobs.git] / src / creature / creature.cpp
1 #include "Creature.hpp"
2 #include "Genome.hpp"
3 #include "Memory.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
7
8 #include "BlobBackgroundTask.hpp"
9 #include "Goal.hpp"
10 #include "IdleGoal.hpp"
11 #include "InhaleNeed.hpp"
12 #include "IngestNeed.hpp"
13 #include "Need.hpp"
14 #include "../app/Assets.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 Creature::Creature(world::Simulation &sim)
33 : sim(sim)
34 , name()
35 , genome()
36 , properties()
37 , cur_prop(0)
38 , base_color(1.0)
39 , highlight_color(0.0)
40 , mass(1.0)
41 , density(1.0)
42 , size(1.0)
43 , birth(sim.Time())
44 , health(1.0)
45 , on_death()
46 , removable(false)
47 , memory(*this)
48 , bg_task()
49 , needs()
50 , goals()
51 , situation()
52 , steering(*this)
53 , vao() {
54         // all creatures avoid each other for now
55         steering.Separate(0.1, 1.5);
56 }
57
58 Creature::~Creature() {
59 }
60
61 glm::dvec4 Creature::HighlightColor() const noexcept {
62         return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
63 }
64
65 void Creature::Ingest(int res, double amount) noexcept {
66         const Genome::Composition *cmp = nullptr;
67         for (const auto &c : genome.composition) {
68                 if (c.resource == res) {
69                         cmp = &c;
70                         break;
71                 }
72         }
73         if (cmp) {
74                 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
75                 Mass(std::min(max_mass, mass + amount));
76         } else {
77                 // foreign material. poisonous?
78         }
79 }
80
81 void Creature::Hurt(double dt) noexcept {
82         health = std::max(0.0, health - dt);
83         if (health == 0.0) {
84                 std::cout << "[" << int(sim.Time()) << "s] "
85                         << name << " died" << std::endl;
86                 Die();
87         }
88 }
89
90 void Creature::Die() noexcept {
91         needs.clear();
92         goals.clear();
93         steering.Halt();
94         if (on_death) {
95                 on_death(*this);
96         }
97         Remove();
98 }
99
100 double Creature::Size() const noexcept {
101         return size;
102 }
103
104 double Creature::Age() const noexcept {
105         return sim.Time() - birth;
106 }
107
108 std::string Creature::AgeName() const {
109         switch (cur_prop) {
110                 case 0:
111                         return "Newborn";
112                 case 1:
113                         return "Child";
114                 case 2:
115                         return "Youth";
116                 case 3:
117                         return "Adult";
118                 case 4:
119                         return "Elder";
120                 case 5:
121                         return "Dead";
122                 default:
123                         return "Unknown";
124         }
125 }
126
127 double Creature::AgeLerp(double from, double to) const noexcept {
128         return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
129 }
130
131 double Creature::Fertility() const noexcept {
132         return AgeLerp(CurProps().fertility, NextProps().fertility) * (1.0 / 3600.0);
133 }
134
135 double Creature::Mutability() const noexcept {
136         return GetProperties().mutability * (1.0 / 3600.0);
137 }
138
139 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
140         g->Enable();
141         goals.emplace_back(std::move(g));
142 }
143
144 namespace {
145
146 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
147         return b->Urgency() < a->Urgency();
148 }
149
150 }
151
152 void Creature::Tick(double dt) {
153         if (cur_prop < 5 && Age() > NextProps().age) {
154                 ++cur_prop;
155                 if (cur_prop == 5) {
156                         std::cout << "[" << int(sim.Time()) << "s] "
157                                 << name << " died of old age" << std::endl;
158                         Die();
159                 } else {
160                         std::cout << "[" << int(sim.Time()) << "s] "
161                                 << name << " grew up to " << AgeName() << std::endl;
162                 }
163         }
164
165         {
166                 Situation::State state(situation.GetState());
167                 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
168                 Situation::Derivative b(Step(a, dt * 0.5));
169                 Situation::Derivative c(Step(b, dt * 0.5));
170                 Situation::Derivative d(Step(c, dt));
171                 Situation::Derivative f(
172                         (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
173                         (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc),
174                         (1.0 / 6.0) * (a.turn + 2.0 * (b.turn + c.turn) + d.turn)
175                 );
176                 state.pos += f.vel * dt;
177                 state.vel += f.acc * dt;
178                 constexpr double turn_speed = 10.0;
179                 // TODO: this is crap
180                 state.dir = glm::normalize(state.dir + f.turn * turn_speed * dt);
181                 situation.SetState(state);
182         }
183
184         bg_task->Tick(dt);
185         bg_task->Action();
186         memory.Tick(dt);
187         for (auto &need : needs) {
188                 need->Tick(dt);
189         }
190         for (auto &goal : goals) {
191                 goal->Tick(dt);
192         }
193         // do background stuff
194         for (auto &need : needs) {
195                 need->ApplyEffect(*this, dt);
196         }
197         if (goals.empty()) {
198                 return;
199         }
200         // if active goal can be interrupted, check priorities
201         if (goals.size() > 1 && goals[0]->Interruptible()) {
202                 std::sort(goals.begin(), goals.end(), GoalCompare);
203         }
204         goals[0]->Action();
205         for (auto goal = goals.begin(); goal != goals.end();) {
206                 if ((*goal)->Complete()) {
207                         goals.erase(goal);
208                 } else {
209                         ++goal;
210                 }
211         }
212 }
213
214 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
215         Situation::State s = situation.GetState();
216         s.pos += ds.vel * dt;
217         s.vel += ds.acc * dt;
218         s.dir = normalize(s.dir + ds.turn * dt);
219         return {
220                 s.vel,
221                 steering.Acceleration(s),
222                 allzero(s.vel) ? glm::dvec3(0.0) : normalize(s.vel) - s.dir
223         };
224 }
225
226 glm::dmat4 Creature::LocalTransform() noexcept {
227         // TODO: surface transform
228         const double half_size = size * 0.5;
229         const glm::dvec3 &pos = situation.Position();
230         return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
231                 * glm::dmat4(world::Planet::SurfaceOrientation(situation.Surface()))
232                 * glm::rotate(glm::orientedAngle(glm::dvec3(0.0, 0.0, -1.0), situation.Heading(), glm::dvec3(0.0, 1.0, 0.0)), glm::dvec3(0.0, 1.0, 0.0))
233                 * glm::scale(glm::dvec3(half_size, half_size, half_size));
234 }
235
236 void Creature::BuildVAO() {
237         vao.Bind();
238         vao.BindAttributes();
239         vao.EnableAttribute(0);
240         vao.EnableAttribute(1);
241         vao.EnableAttribute(2);
242         vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
243         vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
244         vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
245         vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
246         {
247                 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
248                 const float offset = 1.0f;
249                 for (int surface = 0; surface < 6; ++surface) {
250                         const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
251                         const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
252
253                         attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
254                         attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
255                         attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
256                         attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
257                         attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
258                         attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
259                         attrib[4 * surface + 0].texture.x = tex_u_begin;
260                         attrib[4 * surface + 0].texture.y = 1.0f;
261                         attrib[4 * surface + 0].texture.z = surface;
262
263                         attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
264                         attrib[4 * surface + 1].position[(surface + 1) % 3] =  offset;
265                         attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
266                         attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
267                         attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
268                         attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
269                         attrib[4 * surface + 1].texture.x = tex_u_end;
270                         attrib[4 * surface + 1].texture.y = 1.0f;
271                         attrib[4 * surface + 1].texture.z = surface;
272
273                         attrib[4 * surface + 2].position[(surface + 0) % 3] =  offset;
274                         attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
275                         attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
276                         attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
277                         attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
278                         attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
279                         attrib[4 * surface + 2].texture.x = tex_u_begin;
280                         attrib[4 * surface + 2].texture.y = 0.0f;
281                         attrib[4 * surface + 2].texture.z = surface;
282
283                         attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
284                         attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
285                         attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
286                         attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
287                         attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
288                         attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
289                         attrib[4 * surface + 3].texture.x = tex_u_end;
290                         attrib[4 * surface + 3].texture.y = 0.0f;
291                         attrib[4 * surface + 3].texture.z = surface;
292                 }
293         }
294         vao.BindElements();
295         vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
296         {
297                 auto element = vao.MapElements(GL_WRITE_ONLY);
298                 for (int surface = 0; surface < 3; ++surface) {
299                         element[6 * surface + 0] = 4 * surface + 0;
300                         element[6 * surface + 1] = 4 * surface + 2;
301                         element[6 * surface + 2] = 4 * surface + 1;
302                         element[6 * surface + 3] = 4 * surface + 1;
303                         element[6 * surface + 4] = 4 * surface + 2;
304                         element[6 * surface + 5] = 4 * surface + 3;
305                 }
306                 for (int surface = 3; surface < 6; ++surface) {
307                         element[6 * surface + 0] = 4 * surface + 0;
308                         element[6 * surface + 1] = 4 * surface + 1;
309                         element[6 * surface + 2] = 4 * surface + 2;
310                         element[6 * surface + 3] = 4 * surface + 2;
311                         element[6 * surface + 4] = 4 * surface + 1;
312                         element[6 * surface + 5] = 4 * surface + 3;
313                 }
314         }
315         vao.Unbind();
316 }
317
318 void Creature::Draw(graphics::Viewport &viewport) {
319         vao.Bind();
320         vao.DrawTriangles(6 * 6);
321 }
322
323
324 void Spawn(Creature &c, world::Planet &p) {
325         p.AddCreature(&c);
326         c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
327
328         // probe surrounding area for common resources
329         int start = p.SideLength() / 2 - 2;
330         int end = start + 5;
331         std::map<int, double> yields;
332         for (int y = start; y < end; ++y) {
333                 for (int x = start; x < end; ++x) {
334                         const world::TileType &t = p.TypeAt(0, x, y);
335                         for (auto yield : t.resources) {
336                                 yields[yield.resource] += yield.ubiquity;
337                         }
338                 }
339         }
340         int liquid = -1;
341         int solid = -1;
342         for (auto e : yields) {
343                 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
344                         if (liquid < 0 || e.second > yields[liquid]) {
345                                 liquid = e.first;
346                         }
347                 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
348                         if (solid < 0 || e.second > yields[solid]) {
349                                 solid = e.first;
350                         }
351                 }
352         }
353
354         Genome genome;
355
356         genome.properties.Birth().age = { 0.0, 0.0 };
357         genome.properties.Birth().mass = { 0.5, 0.05 };
358         genome.properties.Birth().fertility = { 0.0, 0.0 };
359         genome.properties.Birth().highlight = { 0.0, 0.0 };
360
361         genome.properties.Child().age = { 30.0, 1.0 };
362         genome.properties.Child().mass = { 0.7, 0.05 };
363         genome.properties.Child().fertility = { 0.0, 0.0 };
364         genome.properties.Child().highlight = { 0.2, 0.05 };
365
366         genome.properties.Youth().age = { 60.0, 5.0 };
367         genome.properties.Youth().mass = { 0.9, 0.1 };
368         genome.properties.Youth().fertility = { 0.5, 0.03 };
369         genome.properties.Youth().highlight = { 0.9, 0.1 };
370
371         genome.properties.Adult().age = { 120.0, 10.0 };
372         genome.properties.Adult().mass = { 1.3, 0.1 };
373         genome.properties.Adult().fertility = { 0.4, 0.01 };
374         genome.properties.Adult().highlight = { 0.7, 0.1 };
375
376         genome.properties.Elder().age = { 360.0, 30.0 };
377         genome.properties.Elder().mass = { 1.0, 0.05 };
378         genome.properties.Elder().fertility = { 0.1, 0.01 };
379         genome.properties.Elder().highlight = { 0.6, 0.1 };
380
381         genome.properties.Death().age = { 480.0, 60.0 };
382         genome.properties.Death().mass = { 0.9, 0.05 };
383         genome.properties.Death().fertility = { 0.0, 0.0 };
384         genome.properties.Death().highlight = { 0.5, 0.1 };
385
386         genome.properties.strength = { 1.0, 0.1 };
387         genome.properties.stamina = { 1.0, 0.1 };
388         genome.properties.dexerty = { 1.0, 0.1 };
389         genome.properties.intelligence = { 1.0, 0.1 };
390         genome.properties.mutability = { 1.0, 0.1 };
391
392         glm::dvec3 color_avg(0.0);
393         double color_divisor = 0.0;
394
395         if (p.HasAtmosphere()) {
396                 genome.composition.push_back({
397                         p.Atmosphere(),    // resource
398                         { 0.01, 0.00001 }, // mass
399                         { 0.5,  0.001 },   // intake
400                         { 0.1,  0.0005 },  // penalty
401                         { 0.0,  0.0 },     // growth
402                 });
403                 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
404                 color_divisor += 0.1;
405         }
406         if (liquid > -1) {
407                 genome.composition.push_back({
408                         liquid,          // resource
409                         { 0.6,  0.01 },  // mass
410                         { 0.2,  0.001 }, // intake
411                         { 0.01, 0.002 }, // penalty
412                         { 0.1, 0.0 },   // growth
413                 });
414                 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
415                 color_divisor += 0.5;
416         }
417         if (solid > -1) {
418                 genome.composition.push_back({
419                         solid,             // resource
420                         { 0.4,   0.01 },   // mass
421                         { 0.4,   0.001 },  // intake
422                         { 0.001, 0.0001 }, // penalty
423                         { 10.0,  0.002 },   // growth
424                 });
425                 color_avg += c.GetSimulation().Resources()[solid].base_color;
426                 color_divisor += 1.0;
427         }
428
429         if (color_divisor > 0.001) {
430                 color_avg /= color_divisor;
431         }
432         glm::dvec3 hsl = rgb2hsl(color_avg);
433         genome.base_hue = { hsl.x, 0.01 };
434         genome.base_saturation = { hsl.y, 0.01 };
435         genome.base_lightness = { hsl.z, 0.01 };
436
437         genome.Configure(c);
438 }
439
440 void Genome::Configure(Creature &c) const {
441         c.GetGenome() = *this;
442
443         math::GaloisLFSR &random = c.GetSimulation().Assets().random;
444
445         c.GetProperties() = Instantiate(properties, random);
446
447         double mass = 0.0;
448         double volume = 0.0;
449         for (const auto &comp : composition) {
450                 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
451                 double comp_mass = comp.mass.FakeNormal(random.SNorm());
452                 double intake = comp.intake.FakeNormal(random.SNorm());
453                 double penalty = comp.penalty.FakeNormal(random.SNorm());
454
455                 mass += comp_mass;
456                 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
457
458                 std::unique_ptr<Need> need;
459                 if (resource.state == world::Resource::SOLID) {
460                         intake *= std::atan(c.GetProperties().strength);
461                         need.reset(new IngestNeed(comp.resource, intake, penalty));
462                         need->gain = intake * 0.05;
463                 } else if (resource.state == world::Resource::LIQUID) {
464                         intake *= std::atan(c.GetProperties().stamina);
465                         need.reset(new IngestNeed(comp.resource, intake, penalty));
466                         need->gain = intake * 0.1;
467                 } else {
468                         need.reset(new InhaleNeed(comp.resource, intake, penalty));
469                         need->gain = intake * 0.5;
470                 }
471                 need->name = c.GetSimulation().Resources()[comp.resource].label;
472                 need->growth = comp.growth.FakeNormal(random.SNorm());
473                 need->value = 0.4;
474                 need->inconvenient = 0.5;
475                 need->critical = 0.95;
476                 c.AddNeed(std::move(need));
477         }
478
479         glm::dvec3 base_color(
480                 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
481                 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
482                 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
483         );
484         glm::dvec3 highlight_color(
485                 std::fmod(base_color.x + 0.5, 1.0),
486                 1.0 - base_color.y,
487                 1.0 - base_color.z
488         );
489         c.BaseColor(hsl2rgb(base_color));
490         c.HighlightColor(hsl2rgb(highlight_color));
491
492         c.Mass(c.GetProperties().props[0].mass);
493         c.Density(mass / volume);
494         c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
495         c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
496         c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
497         c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
498 }
499
500
501 void Split(Creature &c) {
502         Creature *a = new Creature(c.GetSimulation());
503         const Situation &s = c.GetSituation();
504         a->Name(c.GetSimulation().Assets().name.Sequential());
505         // TODO: mutate
506         c.GetGenome().Configure(*a);
507         s.GetPlanet().AddCreature(a);
508         // TODO: duplicate situation somehow
509         a->GetSituation().SetPlanetSurface(
510                 s.GetPlanet(), s.Surface(),
511                 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
512         a->BuildVAO();
513         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
514                 << a->Name() << " was born" << std::endl;
515
516         Creature *b = new Creature(c.GetSimulation());
517         b->Name(c.GetSimulation().Assets().name.Sequential());
518         c.GetGenome().Configure(*b);
519         s.GetPlanet().AddCreature(b);
520         b->GetSituation().SetPlanetSurface(
521                 s.GetPlanet(), s.Surface(),
522                 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
523         b->BuildVAO();
524         std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
525                 << b->Name() << " was born" << std::endl;
526
527         c.Die();
528 }
529
530
531 Memory::Memory(Creature &c)
532 : c(c) {
533 }
534
535 Memory::~Memory() {
536 }
537
538 void Memory::Tick(double dt) {
539         Situation &s = c.GetSituation();
540         if (s.OnSurface()) {
541                 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
542         }
543 }
544
545 void Memory::TrackStay(const Location &l, double t) {
546         const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
547         auto entry = known_types.find(type.id);
548         if (entry != known_types.end()) {
549                 entry->second.last_been = c.GetSimulation().Time();
550                 entry->second.last_loc = l;
551                 entry->second.time_spent += t;
552         } else {
553                 known_types.emplace(type.id, Stay{
554                         c.GetSimulation().Time(),
555                         l,
556                         c.GetSimulation().Time(),
557                         l,
558                         t
559                 });
560         }
561 }
562
563
564 NameGenerator::NameGenerator()
565 : counter(0) {
566 }
567
568 NameGenerator::~NameGenerator() {
569 }
570
571 std::string NameGenerator::Sequential() {
572         std::stringstream ss;
573         ss << "Blob " << ++counter;
574         return ss.str();
575 }
576
577
578 Situation::Situation()
579 : planet(nullptr)
580 , state(glm::dvec3(0.0), glm::dvec3(0.0))
581 , surface(0)
582 , type(LOST) {
583 }
584
585 Situation::~Situation() {
586 }
587
588 bool Situation::OnPlanet() const noexcept {
589         return type == PLANET_SURFACE;
590 }
591
592 bool Situation::OnSurface() const noexcept {
593         return type == PLANET_SURFACE;
594 }
595
596 bool Situation::OnTile() const noexcept {
597         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
598         return type == PLANET_SURFACE
599                 && t.x >= 0 && t.x < planet->SideLength()
600                 && t.y >= 0 && t.y < planet->SideLength();
601 }
602
603 glm::ivec2 Situation::SurfacePosition() const noexcept {
604         return planet->SurfacePosition(surface, state.pos);
605 }
606
607 world::Tile &Situation::GetTile() const noexcept {
608         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
609         return planet->TileAt(surface, t.x, t.y);
610 }
611
612 const world::TileType &Situation::GetTileType() const noexcept {
613         glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
614         return planet->TypeAt(surface, t.x, t.y);
615 }
616
617 void Situation::Move(const glm::dvec3 &dp) noexcept {
618         state.pos += dp;
619         if (OnSurface()) {
620                 // enforce ground constraint
621                 if (Surface() < 3) {
622                         state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
623                 } else {
624                         state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
625                 }
626         }
627 }
628
629 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
630         type = PLANET_SURFACE;
631         planet = &p;
632         surface = srf;
633         state.pos = pos;
634 }
635
636
637 Steering::Steering(const Creature &c)
638 : c(c)
639 , target(0.0)
640 , haste(0.0)
641 , max_accel(1.0)
642 , max_speed(1.0)
643 , min_dist(0.0)
644 , max_look(0.0)
645 , separating(false)
646 , halting(true)
647 , seeking(false)
648 , arriving(false) {
649 }
650
651 Steering::~Steering() {
652 }
653
654 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
655         separating = true;
656         min_dist = min_distance;
657         max_look = max_lookaround;
658 }
659
660 void Steering::DontSeparate() noexcept {
661         separating = false;
662 }
663
664 void Steering::Halt() noexcept {
665         halting = true;
666         seeking = false;
667         arriving = false;
668 }
669
670 void Steering::Pass(const glm::dvec3 &t) noexcept {
671         target = t;
672         halting = false;
673         seeking = true;
674         arriving = false;
675 }
676
677 void Steering::GoTo(const glm::dvec3 &t) noexcept {
678         target = t;
679         halting = false;
680         seeking = false;
681         arriving = true;
682 }
683
684 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
685         double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
686         double accel = max_speed * glm::clamp(max_accel * haste * haste, 0.5, 1.0);
687         glm::dvec3 result(0.0);
688         if (separating) {
689                 // TODO: off surface situation
690                 glm::dvec3 repulse(0.0);
691                 const Situation &s = c.GetSituation();
692                 for (auto &other : s.GetPlanet().Creatures()) {
693                         if (&*other == &c) continue;
694                         glm::dvec3 diff = s.Position() - other->GetSituation().Position();
695                         if (length2(diff) > max_look * max_look) continue;
696                         double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
697                         if (sep < min_dist) {
698                                 repulse += normalize(diff) * (1.0 - sep / min_dist);
699                         }
700                 }
701                 SumForce(result, repulse, accel);
702         }
703         if (halting) {
704                 SumForce(result, s.vel * -accel, accel);
705         }
706         if (seeking) {
707                 glm::dvec3 diff = target - s.pos;
708                 if (!allzero(diff)) {
709                         SumForce(result, TargetVelocity(s, (normalize(diff) * speed), accel), accel);
710                 }
711         }
712         if (arriving) {
713                 glm::dvec3 diff = target - s.pos;
714                 double dist = length(diff);
715                 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
716                         SumForce(result, TargetVelocity(s, diff * std::min(dist * accel, speed) / dist, accel), accel);
717                 }
718         }
719         return result;
720 }
721
722 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
723         if (allzero(in) || anynan(in)) {
724                 return false;
725         }
726         double cur = allzero(out) ? 0.0 : length(out);
727         double rem = max - cur;
728         if (rem < 0.0) {
729                 return true;
730         }
731         double add = length(in);
732         if (add > rem) {
733                 // this method is off if in and out are in different
734                 // directions, but gives okayish results
735                 out += in * (1.0 / add);
736                 return true;
737         } else {
738                 out += in;
739                 return false;
740         }
741 }
742
743 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
744         return (vel - s.vel) * acc;
745 }
746
747 }
748 }