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(const world::Set<world::Resource> &resources)
33 : resources(resources)
39 Composition::~Composition() {
43 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
44 return b.value < a.value;
48 void Composition::Add(int res, double amount) {
50 for (auto c = components.begin(); c != components.end(); ++c) {
51 if (c->resource == res) {
53 if (c->value <= 0.0) {
61 if (!found && amount > 0.0) {
62 components.emplace_back(res, amount);
64 std::sort(components.begin(), components.end(), CompositionCompare);
65 state_mass[resources[res].state] += amount;
69 bool Composition::Has(int res) const noexcept {
70 for (auto &c : components) {
71 if (c.resource == res) {
78 double Composition::Get(int res) const noexcept {
79 for (auto &c : components) {
80 if (c.resource == res) {
87 double Composition::Proportion(int res) const noexcept {
88 return Get(res) / TotalMass();
91 double Composition::StateProportion(int res) const noexcept {
92 return Get(res) / StateMass(resources[res].state);
95 double Composition::Compatibility(int res) const noexcept {
97 return StateProportion(res);
99 double max_compat = -1.0;
100 double min_compat = 1.0;
101 for (const auto &c : components) {
102 double prop = c.value / StateMass(resources[res].state);
103 for (const auto &compat : resources[c.resource].compatibility) {
104 double value = compat.second * prop;
105 if (value > max_compat) {
108 if (value < min_compat) {
113 if (min_compat < 0.0) {
121 Creature::Creature(world::Simulation &sim)
126 , composition(sim.Resources())
128 , highlight_color(0.0, 0.0, 0.0, 1.0)
144 // all creatures avoid each other for now
145 steering.Separate(0.1, 1.5);
148 Creature::~Creature() {
151 void Creature::AddMass(int res, double amount) {
152 composition.Add(res, amount);
153 double nonsolid = 0.0;
155 for (const auto &c : composition) {
156 volume += c.value / sim.Resources()[c.resource].density;
157 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
161 Mass(composition.TotalMass());
162 Size(std::cbrt(volume));
163 highlight_color.a = nonsolid / composition.TotalMass();
166 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
167 highlight_color = glm::dvec4(c, highlight_color.a);
170 void Creature::Ingest(int res, double amount) noexcept {
171 if (sim.Resources()[res].state == world::Resource::SOLID) {
172 // 30% of solids stays in body
173 AddMass(res, amount * 0.3 * composition.Compatibility(res));
175 // 5% of fluids stays in body
176 AddMass(res, amount * 0.05 * composition.Compatibility(res));
178 math::GaloisLFSR &random = sim.Assets().random;
179 if (random.UNorm() < AdaptChance()) {
180 // change color to be slightly more like resource
181 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
182 // solids affect base color, others highlight
183 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
184 double q = random.UInt(3); // hue, sat, or val
185 double r = random.UInt(2); // mean or deviation
186 math::Distribution *d = nullptr;
190 d = &genome.base_hue;
193 d = &genome.base_saturation;
196 d = &genome.base_lightness;
201 d = &genome.highlight_hue;
204 d = &genome.highlight_saturation;
207 d = &genome.highlight_lightness;
212 double diff = ref - d->Mean();
216 } else if (diff > 0.5) {
219 // move ±15% of distance
220 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
222 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
225 // scale by ±15%, enforce bounds
226 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
231 void Creature::DoWork(double amount) noexcept {
232 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
233 // burn resources proportional to composition
234 // factor = 1/total * 1/efficiency * amount * -1
235 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
236 // make a copy to total remains constant and
237 // no entries disappear during iteration
238 Composition comp(composition);
239 for (auto &cmp : comp) {
240 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
241 AddMass(cmp.resource, value);
243 // doing work improves strength a little
244 properties.Strength() += amount * 0.0001;
247 void Creature::Hurt(double amount) noexcept {
248 stats.Damage().Add(amount);
249 if (stats.Damage().Full()) {
254 void Creature::Die() noexcept {
257 if (stats.Damage().Full()) {
258 std::ostream &log = sim.Log() << name << " ";
259 if (stats.Exhaustion().Full()) {
260 log << "died of exhaustion";
261 } else if (stats.Breath().Full()) {
263 } else if (stats.Thirst().Full()) {
264 log << "died of thirst";
265 } else if (stats.Hunger().Full()) {
266 log << "starved to death";
268 log << "succumed to wounds";
270 log << " at an age of " << ui::TimeString(Age())
271 << " (" << ui::PercentageString(Age() / properties.Lifetime())
272 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
285 bool Creature::Dead() const noexcept {
286 return death > birth;
289 void Creature::Remove() noexcept {
293 void Creature::Removed() noexcept {
300 void Creature::AddParent(Creature &p) {
301 parents.push_back(&p);
304 double Creature::Age() const noexcept {
305 return Dead() ? death - birth : sim.Time() - birth;
308 double Creature::AgeFactor(double peak) const noexcept {
309 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
310 // goes negative below -0.5 and starts to rise again above 1.0
311 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
312 // guarantee at least 1%
313 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
316 double Creature::EnergyEfficiency() const noexcept {
317 return 0.25 * AgeFactor(0.05);
320 double Creature::ExhaustionFactor() const noexcept {
321 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
324 double Creature::FatigueFactor() const noexcept {
325 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
328 double Creature::Strength() const noexcept {
329 // TODO: replace all age factors with actual growth and decay
330 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
333 double Creature::StrengthFactor() const noexcept {
334 return Strength() / (Strength() + 1.0);
337 double Creature::Stamina() const noexcept {
338 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
341 double Creature::StaminaFactor() const noexcept {
342 return Stamina() / (Stamina() + 1.0);
345 double Creature::Dexerty() const noexcept {
346 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
349 double Creature::DexertyFactor() const noexcept {
350 return Dexerty() / (Dexerty() + 1.0);
353 double Creature::Intelligence() const noexcept {
354 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
357 double Creature::IntelligenceFactor() const noexcept {
358 return Intelligence() / (Intelligence() + 1.0);
361 double Creature::Lifetime() const noexcept {
362 return properties.Lifetime();
365 double Creature::Fertility() const noexcept {
366 return properties.Fertility() * AgeFactor(0.25);
369 double Creature::Mutability() const noexcept {
370 return properties.Mutability();
373 double Creature::Adaptability() const noexcept {
374 return properties.Adaptability();
377 double Creature::OffspringMass() const noexcept {
378 return properties.OffspringMass();
381 double Creature::PerceptionRange() const noexcept {
382 return 3.0 * DexertyFactor() + Size();
385 double Creature::PerceptionOmniRange() const noexcept {
386 return 0.5 * DexertyFactor() + Size();
389 double Creature::PerceptionField() const noexcept {
390 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
391 return 0.8 - DexertyFactor();
394 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
395 const glm::dvec3 diff(p - situation.Position());
396 double omni_range = PerceptionOmniRange();
397 if (glm::length2(diff) < omni_range * omni_range) return true;
398 double range = PerceptionRange();
399 if (glm::length2(diff) > range * range) return false;
400 return glm::dot(glm::normalize(diff), situation.Heading()) > PerceptionField();
403 double Creature::OffspringChance() const noexcept {
404 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
407 double Creature::MutateChance() const noexcept {
408 return GetProperties().Mutability() * (1.0 / 3600.0);
411 double Creature::AdaptChance() const noexcept {
412 return GetProperties().Adaptability() * (1.0 / 120.0);
415 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
420 goals.emplace_back(std::move(g));
425 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
426 return b->Urgency() < a->Urgency();
431 void Creature::Tick(double dt) {
437 void Creature::TickState(double dt) {
438 steering.MaxSpeed(Dexerty());
439 steering.MaxForce(Strength());
440 Situation::State state(situation.GetState());
441 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
442 Situation::Derivative b(Step(a, dt * 0.5));
443 Situation::Derivative c(Step(b, dt * 0.5));
444 Situation::Derivative d(Step(c, dt));
445 Situation::Derivative f(
446 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
447 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
449 state.pos += f.vel * dt;
450 state.vel += f.acc * dt;
451 situation.EnforceConstraints(state);
452 if (glm::length2(state.vel) > 0.000001) {
453 glm::dvec3 nvel(glm::normalize(state.vel));
454 double ang = glm::angle(nvel, state.dir);
455 double turn_rate = PI * 0.75 * dt;
456 if (ang < turn_rate) {
457 state.dir = glm::normalize(state.vel);
458 } else if (std::abs(ang - PI) < 0.001) {
459 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
461 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
464 situation.SetState(state);
465 // work is force times distance
466 DoWork(glm::length(f.acc) * Mass() * glm::length(f.vel) * dt);
469 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
470 Situation::State s = situation.GetState();
471 s.pos += ds.vel * dt;
472 s.vel += ds.acc * dt;
473 glm::dvec3 force(steering.Force(s));
474 // gravity = antinormal * mass * Gm / r²
475 double elevation = situation.GetPlanet().DistanceAt(s.pos);
476 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
479 * Mass() * situation.GetPlanet().GravitationalParameter()
480 / (elevation * elevation));
481 // if net force is applied and in contact with surface
482 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
483 // apply friction = -|normal force| * tangential force * coefficient
484 glm::dvec3 fn(normal * glm::dot(force, normal));
485 glm::dvec3 ft(force - fn);
487 glm::dvec3 friction(-glm::length(fn) * ft * u);
496 void Creature::TickStats(double dt) {
497 for (auto &s : stats.stat) {
500 // TODO: damage values depending on properties
501 if (stats.Breath().Full()) {
502 constexpr double dps = 1.0 / 4.0;
505 if (stats.Thirst().Full()) {
506 constexpr double dps = 1.0 / 32.0;
509 if (stats.Hunger().Full()) {
510 constexpr double dps = 1.0 / 128.0;
513 if (!situation.Moving()) {
514 // double exhaustion recovery when standing still
515 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
519 void Creature::TickBrain(double dt) {
523 // do background stuff
527 for (auto &goal : goals) {
530 Goal *top = &*goals.front();
531 // if active goal can be interrupted, check priorities
532 if (goals.size() > 1 && goals[0]->Interruptible()) {
533 std::sort(goals.begin(), goals.end(), GoalCompare);
535 if (&*goals.front() != top) {
536 top->SetBackground();
537 goals.front()->SetForeground();
538 top = &*goals.front();
541 for (auto goal = goals.begin(); goal != goals.end();) {
542 if ((*goal)->Complete()) {
548 if (&*goals.front() != top) {
549 goals.front()->SetForeground();
553 math::AABB Creature::CollisionBox() const noexcept {
554 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
557 glm::dmat4 Creature::CollisionTransform() const noexcept {
558 const double half_size = size * 0.5;
559 const glm::dvec3 &pos = situation.Position();
561 orient[1] = situation.GetPlanet().NormalAt(pos);
562 orient[2] = situation.Heading();
563 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
564 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
566 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
567 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
568 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
570 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
573 glm::dmat4 Creature::LocalTransform() noexcept {
574 const double half_size = size * 0.5;
575 return CollisionTransform()
576 * glm::scale(glm::dvec3(half_size, half_size, half_size));
579 void Creature::BuildVAO() {
580 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
582 vao->BindAttributes();
583 vao->EnableAttribute(0);
584 vao->EnableAttribute(1);
585 vao->EnableAttribute(2);
586 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
587 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
588 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
589 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
591 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
592 const float offset = 1.0f;
593 for (int surface = 0; surface < 6; ++surface) {
594 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
595 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
597 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
598 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
599 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
600 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
601 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
602 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
603 attrib[4 * surface + 0].texture.x = tex_u_begin;
604 attrib[4 * surface + 0].texture.y = 1.0f;
605 attrib[4 * surface + 0].texture.z = surface;
607 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
608 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
609 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
610 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
611 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
612 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
613 attrib[4 * surface + 1].texture.x = tex_u_end;
614 attrib[4 * surface + 1].texture.y = 1.0f;
615 attrib[4 * surface + 1].texture.z = surface;
617 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
618 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
619 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
620 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
621 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
622 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
623 attrib[4 * surface + 2].texture.x = tex_u_begin;
624 attrib[4 * surface + 2].texture.y = 0.0f;
625 attrib[4 * surface + 2].texture.z = surface;
627 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
628 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
629 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
630 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
631 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
632 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
633 attrib[4 * surface + 3].texture.x = tex_u_end;
634 attrib[4 * surface + 3].texture.y = 0.0f;
635 attrib[4 * surface + 3].texture.z = surface;
639 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
641 auto element = vao->MapElements(GL_WRITE_ONLY);
642 for (int surface = 0; surface < 3; ++surface) {
643 element[6 * surface + 0] = 4 * surface + 0;
644 element[6 * surface + 1] = 4 * surface + 2;
645 element[6 * surface + 2] = 4 * surface + 1;
646 element[6 * surface + 3] = 4 * surface + 1;
647 element[6 * surface + 4] = 4 * surface + 2;
648 element[6 * surface + 5] = 4 * surface + 3;
650 for (int surface = 3; surface < 6; ++surface) {
651 element[6 * surface + 0] = 4 * surface + 0;
652 element[6 * surface + 1] = 4 * surface + 1;
653 element[6 * surface + 2] = 4 * surface + 2;
654 element[6 * surface + 3] = 4 * surface + 2;
655 element[6 * surface + 4] = 4 * surface + 1;
656 element[6 * surface + 5] = 4 * surface + 3;
662 void Creature::KillVAO() {
666 void Creature::Draw(graphics::Viewport &viewport) {
669 vao->DrawTriangles(6 * 6);
673 void Spawn(Creature &c, world::Planet &p) {
675 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
676 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
678 // probe surrounding area for common resources
679 int start = p.SideLength() / 2 - 2;
681 std::map<int, double> yields;
682 for (int y = start; y < end; ++y) {
683 for (int x = start; x < end; ++x) {
684 const world::TileType &t = p.TypeAt(0, x, y);
685 for (auto yield : t.resources) {
686 yields[yield.resource] += yield.ubiquity;
692 for (auto e : yields) {
693 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
694 if (liquid < 0 || e.second > yields[liquid]) {
697 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
698 if (solid < 0 || e.second > yields[solid]) {
705 genome.properties.Strength() = { 2.0, 0.1 };
706 genome.properties.Stamina() = { 2.0, 0.1 };
707 genome.properties.Dexerty() = { 2.0, 0.1 };
708 genome.properties.Intelligence() = { 1.0, 0.1 };
709 genome.properties.Lifetime() = { 480.0, 60.0 };
710 genome.properties.Fertility() = { 0.5, 0.03 };
711 genome.properties.Mutability() = { 0.9, 0.1 };
712 genome.properties.Adaptability() = { 0.9, 0.1 };
713 genome.properties.OffspringMass() = { 0.3, 0.02 };
715 glm::dvec3 color_avg(0.0);
716 double color_divisor = 0.0;
718 if (p.HasAtmosphere()) {
719 c.AddMass(p.Atmosphere(), 0.01);
720 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
721 color_divisor += 0.1;
724 c.AddMass(liquid, 0.3);
725 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
726 color_divisor += 0.5;
729 c.AddMass(solid, 0.1);
730 color_avg += c.GetSimulation().Resources()[solid].base_color;
731 color_divisor += 1.0;
734 if (color_divisor > 0.001) {
735 color_avg /= color_divisor;
737 glm::dvec3 hsl = rgb2hsl(color_avg);
738 genome.base_hue = { hsl.x, 0.01 };
739 genome.base_saturation = { hsl.y, 0.01 };
740 genome.base_lightness = { hsl.z, 0.01 };
741 // use opposite color as start highlight
742 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
743 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
744 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
749 void Genome::Configure(Creature &c) const {
750 c.GetGenome() = *this;
752 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
754 c.GetProperties() = Instantiate(properties, random);
756 // TODO: derive stats from properties
757 c.GetStats().Damage().gain = (-1.0 / 100.0);
758 c.GetStats().Breath().gain = (1.0 / 5.0);
759 c.GetStats().Thirst().gain = (1.0 / 60.0);
760 c.GetStats().Hunger().gain = (1.0 / 200.0);
761 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
762 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
763 c.GetStats().Boredom().gain = (1.0 / 300.0);
765 glm::dvec3 base_color(
766 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
767 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
768 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
770 glm::dvec3 highlight_color(
771 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
772 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
773 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
775 c.BaseColor(hsl2rgb(base_color));
776 c.HighlightColor(hsl2rgb(highlight_color));
777 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
778 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
782 void Split(Creature &c) {
783 Creature *a = new Creature(c.GetSimulation());
784 const Situation &s = c.GetSituation();
786 a->Name(c.GetSimulation().Assets().name.Sequential());
787 c.GetGenome().Configure(*a);
788 for (const auto &cmp : c.GetComposition()) {
789 a->AddMass(cmp.resource, cmp.value * 0.5);
791 s.GetPlanet().AddCreature(a);
792 // TODO: duplicate situation somehow
793 a->GetSituation().SetPlanetSurface(
795 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
797 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
799 Creature *b = new Creature(c.GetSimulation());
801 b->Name(c.GetSimulation().Assets().name.Sequential());
802 c.GetGenome().Configure(*b);
803 for (const auto &cmp : c.GetComposition()) {
804 b->AddMass(cmp.resource, cmp.value * 0.5);
806 s.GetPlanet().AddCreature(b);
807 b->GetSituation().SetPlanetSurface(
809 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
811 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
817 Memory::Memory(Creature &c)
824 void Memory::Erase() {
828 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
829 double best_rating = -1.0;
830 for (const auto &k : known_types) {
831 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
832 auto entry = t.FindBestResource(accept);
833 if (entry != t.resources.end()) {
834 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
835 if (rating > best_rating) {
836 best_rating = rating;
837 pos = k.second.first_loc.position;
839 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
840 if (rating > best_rating) {
841 best_rating = rating;
842 pos = k.second.last_loc.position;
846 if (best_rating > 0.0) {
848 c.GetSimulation().Assets().random.SNorm(),
849 c.GetSimulation().Assets().random.SNorm(),
850 c.GetSimulation().Assets().random.SNorm());
851 pos += error * (2.0 * (1.0 - c.IntelligenceFactor()));
852 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
859 void Memory::Tick(double dt) {
860 Situation &s = c.GetSituation();
862 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
867 void Memory::TrackStay(const Location &l, double t) {
868 const world::TileType &type = l.planet->TileTypeAt(l.position);
869 auto entry = known_types.find(type.id);
870 if (entry != known_types.end()) {
871 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
873 if (entry->second.time_spent > c.Age() * 0.25) {
874 // the place is very familiar
875 c.GetStats().Boredom().Add(-0.2);
878 c.GetStats().Boredom().Add(-0.1);
881 entry->second.last_been = c.GetSimulation().Time();
882 entry->second.last_loc = l;
883 entry->second.time_spent += t;
885 known_types.emplace(type.id, Stay{
886 c.GetSimulation().Time(),
888 c.GetSimulation().Time(),
892 // completely new place, interesting
893 // TODO: scale by personality trait
894 c.GetStats().Boredom().Add(-0.25);
899 NameGenerator::NameGenerator()
903 NameGenerator::~NameGenerator() {
906 std::string NameGenerator::Sequential() {
907 std::stringstream ss;
908 ss << "Blob " << ++counter;
913 Situation::Situation()
915 , state(glm::dvec3(0.0), glm::dvec3(0.0))
919 Situation::~Situation() {
922 bool Situation::OnPlanet() const noexcept {
923 return type == PLANET_SURFACE;
926 bool Situation::OnSurface() const noexcept {
927 return type == PLANET_SURFACE;
930 glm::dvec3 Situation::SurfaceNormal() const noexcept {
931 return planet->NormalAt(state.pos);
934 world::Tile &Situation::GetTile() const noexcept {
935 return planet->TileAt(state.pos);
938 const world::TileType &Situation::GetTileType() const noexcept {
939 return planet->TileTypeAt(state.pos);
942 void Situation::Move(const glm::dvec3 &dp) noexcept {
944 EnforceConstraints(state);
947 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
949 EnforceConstraints(state);
952 void Situation::EnforceConstraints(State &s) noexcept {
954 double r = GetPlanet().Radius();
955 if (glm::length2(s.pos) < r * r) {
956 s.pos = glm::normalize(s.pos) * r;
961 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
962 type = PLANET_SURFACE;
965 EnforceConstraints(state);
969 Steering::Steering(const Creature &c)
983 Steering::~Steering() {
986 void Steering::Off() noexcept {
993 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
995 min_dist = min_distance;
996 max_look = max_lookaround;
999 void Steering::DontSeparate() noexcept {
1003 void Steering::ResumeSeparate() noexcept {
1007 void Steering::Halt() noexcept {
1013 void Steering::Pass(const glm::dvec3 &t) noexcept {
1020 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1027 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1028 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1029 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1030 glm::dvec3 result(0.0);
1032 // TODO: off surface situation
1033 glm::dvec3 repulse(0.0);
1034 const Situation &s = c.GetSituation();
1035 for (auto &other : s.GetPlanet().Creatures()) {
1036 if (&*other == &c) continue;
1037 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1038 if (glm::length2(diff) > max_look * max_look) continue;
1039 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1040 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1041 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1047 result += -5.0 * s.vel * force;
1050 glm::dvec3 diff = target - s.pos;
1051 if (!allzero(diff)) {
1052 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1056 glm::dvec3 diff = target - s.pos;
1057 double dist = glm::length(diff);
1058 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1059 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1062 if (glm::length2(result) > max_force * max_force) {
1063 result = glm::normalize(result) * max_force;
1068 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1069 return (vel - s.vel) * acc;