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