1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "BlobBackgroundTask.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"
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
26 #include <glm/gtx/io.hpp>
32 Composition::Composition()
37 Composition::~Composition() {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42 return b.value < a.value;
46 void Composition::Add(int res, double amount) {
48 for (auto &c : components) {
49 if (c.resource == res) {
56 components.emplace_back(res, amount);
58 std::sort(components.begin(), components.end(), CompositionCompare);
62 bool Composition::Has(int res) const noexcept {
63 for (auto &c : components) {
64 if (c.resource == res) {
71 double Composition::Get(int res) const noexcept {
72 for (auto &c : components) {
73 if (c.resource == res) {
81 Creature::Creature(world::Simulation &sim)
88 , highlight_color(0.0, 0.0, 0.0, 1.0)
104 // all creatures avoid each other for now
105 steering.Separate(0.1, 1.5);
108 Creature::~Creature() {
111 void Creature::AddMass(int res, double amount) {
112 composition.Add(res, amount);
113 double nonsolid = 0.0;
115 for (const auto &c : composition) {
116 volume += c.value / sim.Assets().data.resources[c.resource].density;
117 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
121 Mass(composition.TotalMass());
122 Size(std::cbrt(volume));
123 highlight_color.a = nonsolid / composition.TotalMass();
126 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
127 highlight_color = glm::dvec4(c, highlight_color.a);
130 void Creature::Ingest(int res, double amount) noexcept {
131 // TODO: check foreign materials
132 if (sim.Resources()[res].state == world::Resource::SOLID) {
133 // 15% of solids stays in body
134 AddMass(res, amount * 0.15);
136 // 10% of fluids stays in body
137 AddMass(res, amount * 0.05);
141 void Creature::Hurt(double amount) noexcept {
142 stats.Damage().Add(amount);
143 if (stats.Damage().Full()) {
144 std::cout << "[" << ui::TimeString(sim.Time()) << "] " << name << " ";
145 if (stats.Exhaustion().Full()) {
146 std::cout << "died of exhaustion";
147 } else if (stats.Breath().Full()) {
148 std::cout << "suffocated";
149 } else if (stats.Thirst().Full()) {
150 std::cout << "died of thirst";
151 } else if (stats.Hunger().Full()) {
152 std::cout << "starved to death";
154 std::cout << "succumed to wounds";
156 std::cout << " at an age of " << ui::TimeString(Age())
157 << " (" << ui::PercentageString(Age() / properties.Lifetime())
158 << "% of life expectancy of " << ui::TimeString(properties.Lifetime())
164 void Creature::Die() noexcept {
174 void Creature::Remove() noexcept {
178 void Creature::Removed() noexcept {
185 void Creature::AddParent(Creature &p) {
186 parents.push_back(&p);
189 double Creature::Age() const noexcept {
190 return sim.Time() - birth;
193 double Creature::AgeFactor(double peak) const noexcept {
194 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
195 // goes negative below -0.5 and starts to rise again above 1.0
196 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
197 return 1.0 - (3.0 * t * t) + (2.0 * t * t * t);
200 double Creature::ExhaustionFactor() const noexcept {
201 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
204 double Creature::FatigueFactor() const noexcept {
205 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
208 double Creature::Strength() const noexcept {
209 // TODO: replace all age factors with actual growth and decay
210 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
213 double Creature::Stamina() const noexcept {
214 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
217 double Creature::Dexerty() const noexcept {
218 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
221 double Creature::Intelligence() const noexcept {
222 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
225 double Creature::Lifetime() const noexcept {
226 return properties.Lifetime();
229 double Creature::Fertility() const noexcept {
230 return properties.Fertility() * AgeFactor(0.25);
233 double Creature::Mutability() const noexcept {
234 return properties.Mutability();
237 double Creature::OffspringMass() const noexcept {
238 return properties.OffspringMass();
241 double Creature::OffspringChance() const noexcept {
242 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
245 double Creature::MutateChance() const noexcept {
246 return GetProperties().Mutability() * (1.0 / 3600.0);
249 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
251 goals.emplace_back(std::move(g));
256 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
257 return b->Urgency() < a->Urgency();
262 void Creature::Tick(double dt) {
268 void Creature::TickState(double dt) {
269 steering.MaxSpeed(Dexerty());
270 steering.MaxForce(Strength());
271 Situation::State state(situation.GetState());
272 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
273 Situation::Derivative b(Step(a, dt * 0.5));
274 Situation::Derivative c(Step(b, dt * 0.5));
275 Situation::Derivative d(Step(c, dt));
276 Situation::Derivative f(
277 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
278 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
280 state.pos += f.vel * dt;
281 state.vel += f.acc * dt;
282 situation.EnforceConstraints(state);
283 if (length2(state.vel) > 0.000001) {
284 glm::dvec3 nvel(normalize(state.vel));
285 double ang = angle(nvel, state.dir);
286 double turn_rate = PI * 0.75 * dt;
287 if (ang < turn_rate) {
288 state.dir = normalize(state.vel);
289 } else if (std::abs(ang - PI) < 0.001) {
290 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
292 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
295 situation.SetState(state);
296 stats.Exhaustion().Add(length(f.acc) * Mass() / Stamina() * 0.5 * dt);
299 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
300 Situation::State s = situation.GetState();
301 s.pos += ds.vel * dt;
302 s.vel += ds.acc * dt;
303 glm::dvec3 force(steering.Force(s));
304 // gravity = antinormal * mass * Gm / r²
305 double elevation = s.pos[(situation.Surface() + 2) % 3];
306 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
309 * Mass() * situation.GetPlanet().GravitationalParameter()
310 / (elevation * elevation));
311 // if net force is applied and in contact with surface
312 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
313 // apply friction = -|normal force| * tangential force * coefficient
314 glm::dvec3 fn(normal * dot(force, normal));
315 glm::dvec3 ft(force - fn);
317 glm::dvec3 friction(-length(fn) * ft * u);
326 void Creature::TickStats(double dt) {
327 for (auto &s : stats.stat) {
330 stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
331 // TODO: damage values depending on properties
332 if (stats.Breath().Full()) {
333 constexpr double dps = 1.0 / 4.0;
336 if (stats.Thirst().Full()) {
337 constexpr double dps = 1.0 / 32.0;
340 if (stats.Hunger().Full()) {
341 constexpr double dps = 1.0 / 128.0;
344 if (!situation.Moving()) {
345 // double exhaustion recovery when standing still
346 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
350 void Creature::TickBrain(double dt) {
354 // do background stuff
358 for (auto &goal : goals) {
361 // if active goal can be interrupted, check priorities
362 if (goals.size() > 1 && goals[0]->Interruptible()) {
363 std::sort(goals.begin(), goals.end(), GoalCompare);
366 for (auto goal = goals.begin(); goal != goals.end();) {
367 if ((*goal)->Complete()) {
375 math::AABB Creature::CollisionBox() const noexcept {
376 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
379 glm::dmat4 Creature::CollisionTransform() const noexcept {
380 const double half_size = size * 0.5;
381 const glm::dvec3 &pos = situation.Position();
382 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
383 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
384 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
388 glm::dmat4 Creature::LocalTransform() noexcept {
389 const double half_size = size * 0.5;
390 return CollisionTransform()
391 * glm::scale(glm::dvec3(half_size, half_size, half_size));
394 void Creature::BuildVAO() {
395 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
397 vao->BindAttributes();
398 vao->EnableAttribute(0);
399 vao->EnableAttribute(1);
400 vao->EnableAttribute(2);
401 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
402 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
403 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
404 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
406 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
407 const float offset = 1.0f;
408 for (int surface = 0; surface < 6; ++surface) {
409 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
410 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
412 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
413 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
414 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
415 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
416 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
417 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
418 attrib[4 * surface + 0].texture.x = tex_u_begin;
419 attrib[4 * surface + 0].texture.y = 1.0f;
420 attrib[4 * surface + 0].texture.z = surface;
422 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
423 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
424 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
425 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
426 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
427 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
428 attrib[4 * surface + 1].texture.x = tex_u_end;
429 attrib[4 * surface + 1].texture.y = 1.0f;
430 attrib[4 * surface + 1].texture.z = surface;
432 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
433 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
434 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
435 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
436 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
437 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
438 attrib[4 * surface + 2].texture.x = tex_u_begin;
439 attrib[4 * surface + 2].texture.y = 0.0f;
440 attrib[4 * surface + 2].texture.z = surface;
442 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
443 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
444 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
445 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
446 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
447 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
448 attrib[4 * surface + 3].texture.x = tex_u_end;
449 attrib[4 * surface + 3].texture.y = 0.0f;
450 attrib[4 * surface + 3].texture.z = surface;
454 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
456 auto element = vao->MapElements(GL_WRITE_ONLY);
457 for (int surface = 0; surface < 3; ++surface) {
458 element[6 * surface + 0] = 4 * surface + 0;
459 element[6 * surface + 1] = 4 * surface + 2;
460 element[6 * surface + 2] = 4 * surface + 1;
461 element[6 * surface + 3] = 4 * surface + 1;
462 element[6 * surface + 4] = 4 * surface + 2;
463 element[6 * surface + 5] = 4 * surface + 3;
465 for (int surface = 3; surface < 6; ++surface) {
466 element[6 * surface + 0] = 4 * surface + 0;
467 element[6 * surface + 1] = 4 * surface + 1;
468 element[6 * surface + 2] = 4 * surface + 2;
469 element[6 * surface + 3] = 4 * surface + 2;
470 element[6 * surface + 4] = 4 * surface + 1;
471 element[6 * surface + 5] = 4 * surface + 3;
477 void Creature::KillVAO() {
481 void Creature::Draw(graphics::Viewport &viewport) {
484 vao->DrawTriangles(6 * 6);
488 void Spawn(Creature &c, world::Planet &p) {
490 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
491 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
493 // probe surrounding area for common resources
494 int start = p.SideLength() / 2 - 2;
496 std::map<int, double> yields;
497 for (int y = start; y < end; ++y) {
498 for (int x = start; x < end; ++x) {
499 const world::TileType &t = p.TypeAt(0, x, y);
500 for (auto yield : t.resources) {
501 yields[yield.resource] += yield.ubiquity;
507 for (auto e : yields) {
508 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
509 if (liquid < 0 || e.second > yields[liquid]) {
512 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
513 if (solid < 0 || e.second > yields[solid]) {
520 genome.properties.Strength() = { 2.0, 0.1 };
521 genome.properties.Stamina() = { 2.0, 0.1 };
522 genome.properties.Dexerty() = { 2.0, 0.1 };
523 genome.properties.Intelligence() = { 1.0, 0.1 };
524 genome.properties.Lifetime() = { 480.0, 60.0 };
525 genome.properties.Fertility() = { 0.5, 0.03 };
526 genome.properties.Mutability() = { 1.0, 0.1 };
527 genome.properties.OffspringMass() = { 0.3, 0.02 };
529 glm::dvec3 color_avg(0.0);
530 double color_divisor = 0.0;
532 if (p.HasAtmosphere()) {
533 c.AddMass(p.Atmosphere(), 0.01);
534 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
535 color_divisor += 0.1;
538 c.AddMass(liquid, 0.3);
539 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
540 color_divisor += 0.5;
543 c.AddMass(solid, 0.1);
544 color_avg += c.GetSimulation().Resources()[solid].base_color;
545 color_divisor += 1.0;
548 if (color_divisor > 0.001) {
549 color_avg /= color_divisor;
551 glm::dvec3 hsl = rgb2hsl(color_avg);
552 genome.base_hue = { hsl.x, 0.01 };
553 genome.base_saturation = { hsl.y, 0.01 };
554 genome.base_lightness = { hsl.z, 0.01 };
559 void Genome::Configure(Creature &c) const {
560 c.GetGenome() = *this;
562 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
564 c.GetProperties() = Instantiate(properties, random);
566 // TODO: derive stats from properties
567 c.GetStats().Damage().gain = (-1.0 / 100.0);
568 c.GetStats().Breath().gain = (1.0 / 5.0);
569 c.GetStats().Thirst().gain = (1.0 / 60.0);
570 c.GetStats().Hunger().gain = (1.0 / 200.0);
571 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
572 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
573 c.GetStats().Boredom().gain = (1.0 / 300.0);
575 glm::dvec3 base_color(
576 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
577 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
578 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
580 glm::dvec3 highlight_color(
581 std::fmod(base_color.x + 0.5, 1.0),
585 c.BaseColor(hsl2rgb(base_color));
586 c.HighlightColor(hsl2rgb(highlight_color));
587 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
588 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
592 void Split(Creature &c) {
593 Creature *a = new Creature(c.GetSimulation());
594 const Situation &s = c.GetSituation();
596 a->Name(c.GetSimulation().Assets().name.Sequential());
597 c.GetGenome().Configure(*a);
598 for (const auto &cmp : c.GetComposition()) {
599 a->AddMass(cmp.resource, cmp.value * 0.5);
601 s.GetPlanet().AddCreature(a);
602 // TODO: duplicate situation somehow
603 a->GetSituation().SetPlanetSurface(
604 s.GetPlanet(), s.Surface(),
605 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
607 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
608 << a->Name() << " was born" << std::endl;
610 Creature *b = new Creature(c.GetSimulation());
612 b->Name(c.GetSimulation().Assets().name.Sequential());
613 c.GetGenome().Configure(*b);
614 for (const auto &cmp : c.GetComposition()) {
615 b->AddMass(cmp.resource, cmp.value * 0.5);
617 s.GetPlanet().AddCreature(b);
618 b->GetSituation().SetPlanetSurface(
619 s.GetPlanet(), s.Surface(),
620 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
622 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
623 << b->Name() << " was born" << std::endl;
629 Memory::Memory(Creature &c)
636 void Memory::Erase() {
640 void Memory::Tick(double dt) {
641 Situation &s = c.GetSituation();
643 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
647 void Memory::TrackStay(const Location &l, double t) {
648 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
649 auto entry = known_types.find(type.id);
650 if (entry != known_types.end()) {
651 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
653 if (entry->second.time_spent > c.Age() * 0.25) {
654 // the place is very familiar
655 c.GetStats().Boredom().Add(-0.2);
658 c.GetStats().Boredom().Add(-0.1);
661 entry->second.last_been = c.GetSimulation().Time();
662 entry->second.last_loc = l;
663 entry->second.time_spent += t;
665 known_types.emplace(type.id, Stay{
666 c.GetSimulation().Time(),
668 c.GetSimulation().Time(),
672 // completely new place, interesting
673 // TODO: scale by personality trait
674 c.GetStats().Boredom().Add(-0.25);
679 NameGenerator::NameGenerator()
683 NameGenerator::~NameGenerator() {
686 std::string NameGenerator::Sequential() {
687 std::stringstream ss;
688 ss << "Blob " << ++counter;
693 Situation::Situation()
695 , state(glm::dvec3(0.0), glm::dvec3(0.0))
700 Situation::~Situation() {
703 bool Situation::OnPlanet() const noexcept {
704 return type == PLANET_SURFACE;
707 bool Situation::OnSurface() const noexcept {
708 return type == PLANET_SURFACE;
711 bool Situation::OnTile() const noexcept {
712 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
713 return type == PLANET_SURFACE
714 && t.x >= 0 && t.x < planet->SideLength()
715 && t.y >= 0 && t.y < planet->SideLength();
718 glm::ivec2 Situation::SurfacePosition() const noexcept {
719 return planet->SurfacePosition(surface, state.pos);
722 world::Tile &Situation::GetTile() const noexcept {
723 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
724 return planet->TileAt(surface, t.x, t.y);
727 const world::TileType &Situation::GetTileType() const noexcept {
728 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
729 return planet->TypeAt(surface, t.x, t.y);
732 void Situation::Move(const glm::dvec3 &dp) noexcept {
734 EnforceConstraints(state);
737 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
739 EnforceConstraints(state);
742 void Situation::EnforceConstraints(State &s) noexcept {
745 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
746 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
747 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
750 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
751 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
752 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
758 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
759 type = PLANET_SURFACE;
763 EnforceConstraints(state);
767 Steering::Steering(const Creature &c)
781 Steering::~Steering() {
784 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
786 min_dist = min_distance;
787 max_look = max_lookaround;
790 void Steering::DontSeparate() noexcept {
794 void Steering::ResumeSeparate() noexcept {
798 void Steering::Halt() noexcept {
804 void Steering::Pass(const glm::dvec3 &t) noexcept {
811 void Steering::GoTo(const glm::dvec3 &t) noexcept {
818 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
819 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
820 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
821 glm::dvec3 result(0.0);
823 // TODO: off surface situation
824 glm::dvec3 repulse(0.0);
825 const Situation &s = c.GetSituation();
826 for (auto &other : s.GetPlanet().Creatures()) {
827 if (&*other == &c) continue;
828 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
829 if (length2(diff) > max_look * max_look) continue;
830 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
831 if (sep < min_dist) {
832 repulse += normalize(diff) * (1.0 - sep / min_dist);
835 SumForce(result, repulse, force);
838 SumForce(result, s.vel * -force, force);
841 glm::dvec3 diff = target - s.pos;
842 if (!allzero(diff)) {
843 SumForce(result, TargetVelocity(s, (normalize(diff) * speed), force), force);
847 glm::dvec3 diff = target - s.pos;
848 double dist = length(diff);
849 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
850 SumForce(result, TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force), force);
856 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
857 if (allzero(in) || anynan(in)) {
860 double cur = allzero(out) ? 0.0 : length(out);
861 double rem = max - cur;
865 double add = length(in);
867 // this method is off if in and out are in different
868 // directions, but gives okayish results
869 out += in * (1.0 / add);
877 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
878 return (vel - s.vel) * acc;