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.begin(); c != components.end(); ++c) {
49 if (c->resource == res) {
51 if (c->value <= 0.0) {
58 if (!found && amount > 0.0) {
59 components.emplace_back(res, amount);
61 std::sort(components.begin(), components.end(), CompositionCompare);
65 bool Composition::Has(int res) const noexcept {
66 for (auto &c : components) {
67 if (c.resource == res) {
74 double Composition::Get(int res) const noexcept {
75 for (auto &c : components) {
76 if (c.resource == res) {
84 Creature::Creature(world::Simulation &sim)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
107 // all creatures avoid each other for now
108 steering.Separate(0.1, 1.5);
111 Creature::~Creature() {
114 void Creature::AddMass(int res, double amount) {
115 composition.Add(res, amount);
116 double nonsolid = 0.0;
118 for (const auto &c : composition) {
119 volume += c.value / sim.Assets().data.resources[c.resource].density;
120 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
124 Mass(composition.TotalMass());
125 Size(std::cbrt(volume));
126 highlight_color.a = nonsolid / composition.TotalMass();
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130 highlight_color = glm::dvec4(c, highlight_color.a);
133 void Creature::Ingest(int res, double amount) noexcept {
134 // TODO: check foreign materials
135 if (sim.Resources()[res].state == world::Resource::SOLID) {
136 // 15% of solids stays in body
137 AddMass(res, amount * 0.15);
139 // 10% of fluids stays in body
140 AddMass(res, amount * 0.05);
142 math::GaloisLFSR &random = sim.Assets().random;
143 if (random.UNorm() < AdaptChance()) {
144 // change color to be slightly more like resource
145 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
146 // solids affect base color, others highlight
147 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
148 double q = random.UInt(3); // hue, sat, or val
149 double r = random.UInt(2); // mean or deviation
150 math::Distribution *d = nullptr;
154 d = &genome.base_hue;
157 d = &genome.base_saturation;
160 d = &genome.base_lightness;
165 d = &genome.highlight_hue;
168 d = &genome.highlight_saturation;
171 d = &genome.highlight_lightness;
176 double diff = ref - d->Mean();
180 } else if (diff > 0.5) {
183 // move ±15% of distance
184 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
186 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
189 // scale by ±15%, enforce bounds
190 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
195 void Creature::DoWork(double amount) noexcept {
196 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
197 // burn resources proportional to composition
198 // factor = 1/total * 1/efficiency * amount * -1
199 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
200 // make a copy to total remains constant and
201 // no entries disappear during iteration
202 Composition comp(composition);
203 for (auto &cmp : comp) {
204 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
205 AddMass(cmp.resource, value);
207 // doing work improves strength a little
208 properties.Strength() += amount * 0.0001;
211 void Creature::Hurt(double amount) noexcept {
212 stats.Damage().Add(amount);
213 if (stats.Damage().Full()) {
218 void Creature::Die() noexcept {
221 if (stats.Damage().Full()) {
222 std::ostream &log = sim.Log() << name << " ";
223 if (stats.Exhaustion().Full()) {
224 log << "died of exhaustion";
225 } else if (stats.Breath().Full()) {
227 } else if (stats.Thirst().Full()) {
228 log << "died of thirst";
229 } else if (stats.Hunger().Full()) {
230 log << "starved to death";
232 log << "succumed to wounds";
234 log << " at an age of " << ui::TimeString(Age())
235 << " (" << ui::PercentageString(Age() / properties.Lifetime())
236 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
249 bool Creature::Dead() const noexcept {
250 return death > birth;
253 void Creature::Remove() noexcept {
257 void Creature::Removed() noexcept {
264 void Creature::AddParent(Creature &p) {
265 parents.push_back(&p);
268 double Creature::Age() const noexcept {
269 return sim.Time() - birth;
272 double Creature::AgeFactor(double peak) const noexcept {
273 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
274 // goes negative below -0.5 and starts to rise again above 1.0
275 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
276 // guarantee at least 1%
277 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
280 double Creature::EnergyEfficiency() const noexcept {
281 return 0.25 * AgeFactor(0.05);
284 double Creature::ExhaustionFactor() const noexcept {
285 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
288 double Creature::FatigueFactor() const noexcept {
289 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
292 double Creature::Strength() const noexcept {
293 // TODO: replace all age factors with actual growth and decay
294 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
297 double Creature::Stamina() const noexcept {
298 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
301 double Creature::Dexerty() const noexcept {
302 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
305 double Creature::Intelligence() const noexcept {
306 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
309 double Creature::Lifetime() const noexcept {
310 return properties.Lifetime();
313 double Creature::Fertility() const noexcept {
314 return properties.Fertility() * AgeFactor(0.25);
317 double Creature::Mutability() const noexcept {
318 return properties.Mutability();
321 double Creature::Adaptability() const noexcept {
322 return properties.Adaptability();
325 double Creature::OffspringMass() const noexcept {
326 return properties.OffspringMass();
329 double Creature::PerceptionRange() const noexcept {
330 return 3.0 * (Dexerty() / (Dexerty() + 1)) + Size();
333 double Creature::PerceptionOmniRange() const noexcept {
334 return 0.5 * (Dexerty() / (Dexerty() + 1)) + Size();
337 double Creature::PerceptionField() const noexcept {
338 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
339 return 0.8 - (Dexerty() / (Dexerty() + 1));
342 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
343 const glm::dvec3 diff(p - situation.Position());
344 double omni_range = PerceptionOmniRange();
345 if (length2(diff) < omni_range * omni_range) return true;
346 double range = PerceptionRange();
347 if (length2(diff) > range * range) return false;
348 return dot(normalize(diff), situation.Heading()) > PerceptionField();
351 double Creature::OffspringChance() const noexcept {
352 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
355 double Creature::MutateChance() const noexcept {
356 return GetProperties().Mutability() * (1.0 / 3600.0);
359 double Creature::AdaptChance() const noexcept {
360 return GetProperties().Adaptability() * (1.0 / 120.0);
363 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
368 goals.emplace_back(std::move(g));
373 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
374 return b->Urgency() < a->Urgency();
379 void Creature::Tick(double dt) {
385 void Creature::TickState(double dt) {
386 steering.MaxSpeed(Dexerty());
387 steering.MaxForce(Strength());
388 Situation::State state(situation.GetState());
389 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
390 Situation::Derivative b(Step(a, dt * 0.5));
391 Situation::Derivative c(Step(b, dt * 0.5));
392 Situation::Derivative d(Step(c, dt));
393 Situation::Derivative f(
394 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
395 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
397 state.pos += f.vel * dt;
398 state.vel += f.acc * dt;
399 situation.EnforceConstraints(state);
400 if (length2(state.vel) > 0.000001) {
401 glm::dvec3 nvel(normalize(state.vel));
402 double ang = angle(nvel, state.dir);
403 double turn_rate = PI * 0.75 * dt;
404 if (ang < turn_rate) {
405 state.dir = normalize(state.vel);
406 } else if (std::abs(ang - PI) < 0.001) {
407 state.dir = rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
409 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
412 situation.SetState(state);
413 // work is force times distance
414 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
417 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
418 Situation::State s = situation.GetState();
419 s.pos += ds.vel * dt;
420 s.vel += ds.acc * dt;
421 glm::dvec3 force(steering.Force(s));
422 // gravity = antinormal * mass * Gm / r²
423 double elevation = situation.GetPlanet().DistanceAt(s.pos);
424 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
427 * Mass() * situation.GetPlanet().GravitationalParameter()
428 / (elevation * elevation));
429 // if net force is applied and in contact with surface
430 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
431 // apply friction = -|normal force| * tangential force * coefficient
432 glm::dvec3 fn(normal * dot(force, normal));
433 glm::dvec3 ft(force - fn);
435 glm::dvec3 friction(-length(fn) * ft * u);
444 void Creature::TickStats(double dt) {
445 for (auto &s : stats.stat) {
448 // TODO: damage values depending on properties
449 if (stats.Breath().Full()) {
450 constexpr double dps = 1.0 / 4.0;
453 if (stats.Thirst().Full()) {
454 constexpr double dps = 1.0 / 32.0;
457 if (stats.Hunger().Full()) {
458 constexpr double dps = 1.0 / 128.0;
461 if (!situation.Moving()) {
462 // double exhaustion recovery when standing still
463 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
467 void Creature::TickBrain(double dt) {
471 // do background stuff
475 for (auto &goal : goals) {
478 Goal *top = &*goals.front();
479 // if active goal can be interrupted, check priorities
480 if (goals.size() > 1 && goals[0]->Interruptible()) {
481 std::sort(goals.begin(), goals.end(), GoalCompare);
483 if (&*goals.front() != top) {
484 top->SetBackground();
485 goals.front()->SetForeground();
486 top = &*goals.front();
489 for (auto goal = goals.begin(); goal != goals.end();) {
490 if ((*goal)->Complete()) {
496 if (&*goals.front() != top) {
497 goals.front()->SetForeground();
501 math::AABB Creature::CollisionBox() const noexcept {
502 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
505 glm::dmat4 Creature::CollisionTransform() const noexcept {
506 const double half_size = size * 0.5;
507 const glm::dvec3 &pos = situation.Position();
509 orient[1] = situation.GetPlanet().NormalAt(pos);
510 orient[2] = situation.Heading();
511 if (std::abs(dot(orient[1], orient[2])) > 0.999) {
512 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
514 orient[0] = normalize(cross(orient[1], orient[2]));
515 orient[2] = normalize(cross(orient[0], orient[1]));
516 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
518 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
521 glm::dmat4 Creature::LocalTransform() noexcept {
522 const double half_size = size * 0.5;
523 return CollisionTransform()
524 * glm::scale(glm::dvec3(half_size, half_size, half_size));
527 void Creature::BuildVAO() {
528 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
530 vao->BindAttributes();
531 vao->EnableAttribute(0);
532 vao->EnableAttribute(1);
533 vao->EnableAttribute(2);
534 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
535 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
536 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
537 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
539 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
540 const float offset = 1.0f;
541 for (int surface = 0; surface < 6; ++surface) {
542 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
543 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
545 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
546 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
547 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
548 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
549 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
550 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
551 attrib[4 * surface + 0].texture.x = tex_u_begin;
552 attrib[4 * surface + 0].texture.y = 1.0f;
553 attrib[4 * surface + 0].texture.z = surface;
555 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
556 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
557 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
558 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
559 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
560 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
561 attrib[4 * surface + 1].texture.x = tex_u_end;
562 attrib[4 * surface + 1].texture.y = 1.0f;
563 attrib[4 * surface + 1].texture.z = surface;
565 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
566 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
567 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
568 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
569 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
570 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
571 attrib[4 * surface + 2].texture.x = tex_u_begin;
572 attrib[4 * surface + 2].texture.y = 0.0f;
573 attrib[4 * surface + 2].texture.z = surface;
575 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
576 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
577 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
578 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
579 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
580 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
581 attrib[4 * surface + 3].texture.x = tex_u_end;
582 attrib[4 * surface + 3].texture.y = 0.0f;
583 attrib[4 * surface + 3].texture.z = surface;
587 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
589 auto element = vao->MapElements(GL_WRITE_ONLY);
590 for (int surface = 0; surface < 3; ++surface) {
591 element[6 * surface + 0] = 4 * surface + 0;
592 element[6 * surface + 1] = 4 * surface + 2;
593 element[6 * surface + 2] = 4 * surface + 1;
594 element[6 * surface + 3] = 4 * surface + 1;
595 element[6 * surface + 4] = 4 * surface + 2;
596 element[6 * surface + 5] = 4 * surface + 3;
598 for (int surface = 3; surface < 6; ++surface) {
599 element[6 * surface + 0] = 4 * surface + 0;
600 element[6 * surface + 1] = 4 * surface + 1;
601 element[6 * surface + 2] = 4 * surface + 2;
602 element[6 * surface + 3] = 4 * surface + 2;
603 element[6 * surface + 4] = 4 * surface + 1;
604 element[6 * surface + 5] = 4 * surface + 3;
610 void Creature::KillVAO() {
614 void Creature::Draw(graphics::Viewport &viewport) {
617 vao->DrawTriangles(6 * 6);
621 void Spawn(Creature &c, world::Planet &p) {
623 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
624 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
626 // probe surrounding area for common resources
627 int start = p.SideLength() / 2 - 2;
629 std::map<int, double> yields;
630 for (int y = start; y < end; ++y) {
631 for (int x = start; x < end; ++x) {
632 const world::TileType &t = p.TypeAt(0, x, y);
633 for (auto yield : t.resources) {
634 yields[yield.resource] += yield.ubiquity;
640 for (auto e : yields) {
641 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
642 if (liquid < 0 || e.second > yields[liquid]) {
645 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
646 if (solid < 0 || e.second > yields[solid]) {
653 genome.properties.Strength() = { 2.0, 0.1 };
654 genome.properties.Stamina() = { 2.0, 0.1 };
655 genome.properties.Dexerty() = { 2.0, 0.1 };
656 genome.properties.Intelligence() = { 1.0, 0.1 };
657 genome.properties.Lifetime() = { 480.0, 60.0 };
658 genome.properties.Fertility() = { 0.5, 0.03 };
659 genome.properties.Mutability() = { 0.9, 0.1 };
660 genome.properties.Adaptability() = { 0.9, 0.1 };
661 genome.properties.OffspringMass() = { 0.3, 0.02 };
663 glm::dvec3 color_avg(0.0);
664 double color_divisor = 0.0;
666 if (p.HasAtmosphere()) {
667 c.AddMass(p.Atmosphere(), 0.01);
668 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
669 color_divisor += 0.1;
672 c.AddMass(liquid, 0.3);
673 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
674 color_divisor += 0.5;
677 c.AddMass(solid, 0.1);
678 color_avg += c.GetSimulation().Resources()[solid].base_color;
679 color_divisor += 1.0;
682 if (color_divisor > 0.001) {
683 color_avg /= color_divisor;
685 glm::dvec3 hsl = rgb2hsl(color_avg);
686 genome.base_hue = { hsl.x, 0.01 };
687 genome.base_saturation = { hsl.y, 0.01 };
688 genome.base_lightness = { hsl.z, 0.01 };
689 // use opposite color as start highlight
690 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
691 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
692 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
697 void Genome::Configure(Creature &c) const {
698 c.GetGenome() = *this;
700 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
702 c.GetProperties() = Instantiate(properties, random);
704 // TODO: derive stats from properties
705 c.GetStats().Damage().gain = (-1.0 / 100.0);
706 c.GetStats().Breath().gain = (1.0 / 5.0);
707 c.GetStats().Thirst().gain = (1.0 / 60.0);
708 c.GetStats().Hunger().gain = (1.0 / 200.0);
709 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
710 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
711 c.GetStats().Boredom().gain = (1.0 / 300.0);
713 glm::dvec3 base_color(
714 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
715 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
716 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
718 glm::dvec3 highlight_color(
719 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
720 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
721 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
723 c.BaseColor(hsl2rgb(base_color));
724 c.HighlightColor(hsl2rgb(highlight_color));
725 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
726 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
730 void Split(Creature &c) {
731 Creature *a = new Creature(c.GetSimulation());
732 const Situation &s = c.GetSituation();
734 a->Name(c.GetSimulation().Assets().name.Sequential());
735 c.GetGenome().Configure(*a);
736 for (const auto &cmp : c.GetComposition()) {
737 a->AddMass(cmp.resource, cmp.value * 0.5);
739 s.GetPlanet().AddCreature(a);
740 // TODO: duplicate situation somehow
741 a->GetSituation().SetPlanetSurface(
743 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
745 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
747 Creature *b = new Creature(c.GetSimulation());
749 b->Name(c.GetSimulation().Assets().name.Sequential());
750 c.GetGenome().Configure(*b);
751 for (const auto &cmp : c.GetComposition()) {
752 b->AddMass(cmp.resource, cmp.value * 0.5);
754 s.GetPlanet().AddCreature(b);
755 b->GetSituation().SetPlanetSurface(
757 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
759 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
765 Memory::Memory(Creature &c)
772 void Memory::Erase() {
776 void Memory::Tick(double dt) {
777 Situation &s = c.GetSituation();
779 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
783 void Memory::TrackStay(const Location &l, double t) {
784 const world::TileType &type = l.planet->TileTypeAt(l.position);
785 auto entry = known_types.find(type.id);
786 if (entry != known_types.end()) {
787 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
789 if (entry->second.time_spent > c.Age() * 0.25) {
790 // the place is very familiar
791 c.GetStats().Boredom().Add(-0.2);
794 c.GetStats().Boredom().Add(-0.1);
797 entry->second.last_been = c.GetSimulation().Time();
798 entry->second.last_loc = l;
799 entry->second.time_spent += t;
801 known_types.emplace(type.id, Stay{
802 c.GetSimulation().Time(),
804 c.GetSimulation().Time(),
808 // completely new place, interesting
809 // TODO: scale by personality trait
810 c.GetStats().Boredom().Add(-0.25);
815 NameGenerator::NameGenerator()
819 NameGenerator::~NameGenerator() {
822 std::string NameGenerator::Sequential() {
823 std::stringstream ss;
824 ss << "Blob " << ++counter;
829 Situation::Situation()
831 , state(glm::dvec3(0.0), glm::dvec3(0.0))
835 Situation::~Situation() {
838 bool Situation::OnPlanet() const noexcept {
839 return type == PLANET_SURFACE;
842 bool Situation::OnSurface() const noexcept {
843 return type == PLANET_SURFACE;
846 world::Tile &Situation::GetTile() const noexcept {
847 return planet->TileAt(state.pos);
850 const world::TileType &Situation::GetTileType() const noexcept {
851 return planet->TileTypeAt(state.pos);
854 void Situation::Move(const glm::dvec3 &dp) noexcept {
856 EnforceConstraints(state);
859 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
861 EnforceConstraints(state);
864 void Situation::EnforceConstraints(State &s) noexcept {
866 double r = GetPlanet().Radius();
867 if (length2(s.pos) < r * r) {
868 s.pos = normalize(s.pos) * r;
873 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
874 type = PLANET_SURFACE;
877 EnforceConstraints(state);
881 Steering::Steering(const Creature &c)
895 Steering::~Steering() {
898 void Steering::Off() noexcept {
905 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
907 min_dist = min_distance;
908 max_look = max_lookaround;
911 void Steering::DontSeparate() noexcept {
915 void Steering::ResumeSeparate() noexcept {
919 void Steering::Halt() noexcept {
925 void Steering::Pass(const glm::dvec3 &t) noexcept {
932 void Steering::GoTo(const glm::dvec3 &t) noexcept {
939 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
940 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
941 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
942 glm::dvec3 result(0.0);
944 // TODO: off surface situation
945 glm::dvec3 repulse(0.0);
946 const Situation &s = c.GetSituation();
947 for (auto &other : s.GetPlanet().Creatures()) {
948 if (&*other == &c) continue;
949 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
950 if (length2(diff) > max_look * max_look) continue;
951 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
952 double sep = glm::clamp(length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
953 repulse += normalize(diff) * (1.0 - sep / min_dist) * force;
958 // break twice as hard
959 result += -2.0 * s.vel * force;
962 glm::dvec3 diff = target - s.pos;
963 if (!allzero(diff)) {
964 result += TargetVelocity(s, (normalize(diff) * speed), force);
968 glm::dvec3 diff = target - s.pos;
969 double dist = length(diff);
970 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
971 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
974 if (length2(result) > max_force * max_force) {
975 result = normalize(result) * max_force;
980 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
981 return (vel - s.vel) * acc;