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