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) {
83 double Composition::Proportion(int res) const noexcept {
84 return Get(res) / TotalMass();
87 double Composition::Compatibility(const world::Set<world::Resource> &resources, int res) const noexcept {
89 return Proportion(res);
91 double max_compat = -1.0;
92 double min_compat = 1.0;
93 for (const auto &c : components) {
94 double prop = c.value / TotalMass();
95 for (const auto &compat : resources[c.resource].compatibility) {
96 double value = compat.second * prop;
97 if (value > max_compat) {
100 if (value < min_compat) {
105 if (min_compat < 0.0) {
113 Creature::Creature(world::Simulation &sim)
120 , highlight_color(0.0, 0.0, 0.0, 1.0)
136 // all creatures avoid each other for now
137 steering.Separate(0.1, 1.5);
140 Creature::~Creature() {
143 void Creature::AddMass(int res, double amount) {
144 composition.Add(res, amount);
145 double nonsolid = 0.0;
147 for (const auto &c : composition) {
148 volume += c.value / sim.Assets().data.resources[c.resource].density;
149 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
153 Mass(composition.TotalMass());
154 Size(std::cbrt(volume));
155 highlight_color.a = nonsolid / composition.TotalMass();
158 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
159 highlight_color = glm::dvec4(c, highlight_color.a);
162 void Creature::Ingest(int res, double amount) noexcept {
163 if (sim.Resources()[res].state == world::Resource::SOLID) {
164 // 30% of solids stays in body
165 AddMass(res, amount * 0.3 * composition.Compatibility(sim.Resources(), res));
167 // 10% of fluids stays in body
168 AddMass(res, amount * 0.1 * composition.Compatibility(sim.Resources(), res));
170 math::GaloisLFSR &random = sim.Assets().random;
171 if (random.UNorm() < AdaptChance()) {
172 // change color to be slightly more like resource
173 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
174 // solids affect base color, others highlight
175 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
176 double q = random.UInt(3); // hue, sat, or val
177 double r = random.UInt(2); // mean or deviation
178 math::Distribution *d = nullptr;
182 d = &genome.base_hue;
185 d = &genome.base_saturation;
188 d = &genome.base_lightness;
193 d = &genome.highlight_hue;
196 d = &genome.highlight_saturation;
199 d = &genome.highlight_lightness;
204 double diff = ref - d->Mean();
208 } else if (diff > 0.5) {
211 // move ±15% of distance
212 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
214 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
217 // scale by ±15%, enforce bounds
218 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
223 void Creature::DoWork(double amount) noexcept {
224 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
225 // burn resources proportional to composition
226 // factor = 1/total * 1/efficiency * amount * -1
227 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
228 // make a copy to total remains constant and
229 // no entries disappear during iteration
230 Composition comp(composition);
231 for (auto &cmp : comp) {
232 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
233 AddMass(cmp.resource, value);
235 // doing work improves strength a little
236 properties.Strength() += amount * 0.0001;
239 void Creature::Hurt(double amount) noexcept {
240 stats.Damage().Add(amount);
241 if (stats.Damage().Full()) {
246 void Creature::Die() noexcept {
249 if (stats.Damage().Full()) {
250 std::ostream &log = sim.Log() << name << " ";
251 if (stats.Exhaustion().Full()) {
252 log << "died of exhaustion";
253 } else if (stats.Breath().Full()) {
255 } else if (stats.Thirst().Full()) {
256 log << "died of thirst";
257 } else if (stats.Hunger().Full()) {
258 log << "starved to death";
260 log << "succumed to wounds";
262 log << " at an age of " << ui::TimeString(Age())
263 << " (" << ui::PercentageString(Age() / properties.Lifetime())
264 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
277 bool Creature::Dead() const noexcept {
278 return death > birth;
281 void Creature::Remove() noexcept {
285 void Creature::Removed() noexcept {
292 void Creature::AddParent(Creature &p) {
293 parents.push_back(&p);
296 double Creature::Age() const noexcept {
297 return Dead() ? death - birth : sim.Time() - birth;
300 double Creature::AgeFactor(double peak) const noexcept {
301 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
302 // goes negative below -0.5 and starts to rise again above 1.0
303 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
304 // guarantee at least 1%
305 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
308 double Creature::EnergyEfficiency() const noexcept {
309 return 0.25 * AgeFactor(0.05);
312 double Creature::ExhaustionFactor() const noexcept {
313 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
316 double Creature::FatigueFactor() const noexcept {
317 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
320 double Creature::Strength() const noexcept {
321 // TODO: replace all age factors with actual growth and decay
322 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
325 double Creature::StrengthFactor() const noexcept {
326 return Strength() / (Strength() + 1.0);
329 double Creature::Stamina() const noexcept {
330 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
333 double Creature::StaminaFactor() const noexcept {
334 return Stamina() / (Stamina() + 1.0);
337 double Creature::Dexerty() const noexcept {
338 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
341 double Creature::DexertyFactor() const noexcept {
342 return Dexerty() / (Dexerty() + 1.0);
345 double Creature::Intelligence() const noexcept {
346 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
349 double Creature::IntelligenceFactor() const noexcept {
350 return Intelligence() / (Intelligence() + 1.0);
353 double Creature::Lifetime() const noexcept {
354 return properties.Lifetime();
357 double Creature::Fertility() const noexcept {
358 return properties.Fertility() * AgeFactor(0.25);
361 double Creature::Mutability() const noexcept {
362 return properties.Mutability();
365 double Creature::Adaptability() const noexcept {
366 return properties.Adaptability();
369 double Creature::OffspringMass() const noexcept {
370 return properties.OffspringMass();
373 double Creature::PerceptionRange() const noexcept {
374 return 3.0 * DexertyFactor() + Size();
377 double Creature::PerceptionOmniRange() const noexcept {
378 return 0.5 * DexertyFactor() + Size();
381 double Creature::PerceptionField() const noexcept {
382 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
383 return 0.8 - DexertyFactor();
386 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
387 const glm::dvec3 diff(p - situation.Position());
388 double omni_range = PerceptionOmniRange();
389 if (glm::length2(diff) < omni_range * omni_range) return true;
390 double range = PerceptionRange();
391 if (glm::length2(diff) > range * range) return false;
392 return glm::dot(glm::normalize(diff), situation.Heading()) > PerceptionField();
395 double Creature::OffspringChance() const noexcept {
396 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
399 double Creature::MutateChance() const noexcept {
400 return GetProperties().Mutability() * (1.0 / 3600.0);
403 double Creature::AdaptChance() const noexcept {
404 return GetProperties().Adaptability() * (1.0 / 120.0);
407 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
412 goals.emplace_back(std::move(g));
417 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
418 return b->Urgency() < a->Urgency();
423 void Creature::Tick(double dt) {
429 void Creature::TickState(double dt) {
430 steering.MaxSpeed(Dexerty());
431 steering.MaxForce(Strength());
432 Situation::State state(situation.GetState());
433 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
434 Situation::Derivative b(Step(a, dt * 0.5));
435 Situation::Derivative c(Step(b, dt * 0.5));
436 Situation::Derivative d(Step(c, dt));
437 Situation::Derivative f(
438 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
439 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
441 state.pos += f.vel * dt;
442 state.vel += f.acc * dt;
443 situation.EnforceConstraints(state);
444 if (glm::length2(state.vel) > 0.000001) {
445 glm::dvec3 nvel(glm::normalize(state.vel));
446 double ang = glm::angle(nvel, state.dir);
447 double turn_rate = PI * 0.75 * dt;
448 if (ang < turn_rate) {
449 state.dir = glm::normalize(state.vel);
450 } else if (std::abs(ang - PI) < 0.001) {
451 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
453 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
456 situation.SetState(state);
457 // work is force times distance
458 DoWork(glm::length(f.acc) * Mass() * glm::length(f.vel) * dt);
461 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
462 Situation::State s = situation.GetState();
463 s.pos += ds.vel * dt;
464 s.vel += ds.acc * dt;
465 glm::dvec3 force(steering.Force(s));
466 // gravity = antinormal * mass * Gm / r²
467 double elevation = situation.GetPlanet().DistanceAt(s.pos);
468 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
471 * Mass() * situation.GetPlanet().GravitationalParameter()
472 / (elevation * elevation));
473 // if net force is applied and in contact with surface
474 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
475 // apply friction = -|normal force| * tangential force * coefficient
476 glm::dvec3 fn(normal * glm::dot(force, normal));
477 glm::dvec3 ft(force - fn);
479 glm::dvec3 friction(-glm::length(fn) * ft * u);
488 void Creature::TickStats(double dt) {
489 for (auto &s : stats.stat) {
492 // TODO: damage values depending on properties
493 if (stats.Breath().Full()) {
494 constexpr double dps = 1.0 / 4.0;
497 if (stats.Thirst().Full()) {
498 constexpr double dps = 1.0 / 32.0;
501 if (stats.Hunger().Full()) {
502 constexpr double dps = 1.0 / 128.0;
505 if (!situation.Moving()) {
506 // double exhaustion recovery when standing still
507 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
511 void Creature::TickBrain(double dt) {
515 // do background stuff
519 for (auto &goal : goals) {
522 Goal *top = &*goals.front();
523 // if active goal can be interrupted, check priorities
524 if (goals.size() > 1 && goals[0]->Interruptible()) {
525 std::sort(goals.begin(), goals.end(), GoalCompare);
527 if (&*goals.front() != top) {
528 top->SetBackground();
529 goals.front()->SetForeground();
530 top = &*goals.front();
533 for (auto goal = goals.begin(); goal != goals.end();) {
534 if ((*goal)->Complete()) {
540 if (&*goals.front() != top) {
541 goals.front()->SetForeground();
545 math::AABB Creature::CollisionBox() const noexcept {
546 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
549 glm::dmat4 Creature::CollisionTransform() const noexcept {
550 const double half_size = size * 0.5;
551 const glm::dvec3 &pos = situation.Position();
553 orient[1] = situation.GetPlanet().NormalAt(pos);
554 orient[2] = situation.Heading();
555 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
556 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
558 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
559 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
560 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
562 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
565 glm::dmat4 Creature::LocalTransform() noexcept {
566 const double half_size = size * 0.5;
567 return CollisionTransform()
568 * glm::scale(glm::dvec3(half_size, half_size, half_size));
571 void Creature::BuildVAO() {
572 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
574 vao->BindAttributes();
575 vao->EnableAttribute(0);
576 vao->EnableAttribute(1);
577 vao->EnableAttribute(2);
578 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
579 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
580 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
581 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
583 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
584 const float offset = 1.0f;
585 for (int surface = 0; surface < 6; ++surface) {
586 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
587 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
589 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
590 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
591 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
592 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
593 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
594 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
595 attrib[4 * surface + 0].texture.x = tex_u_begin;
596 attrib[4 * surface + 0].texture.y = 1.0f;
597 attrib[4 * surface + 0].texture.z = surface;
599 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
600 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
601 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
602 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
603 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
604 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
605 attrib[4 * surface + 1].texture.x = tex_u_end;
606 attrib[4 * surface + 1].texture.y = 1.0f;
607 attrib[4 * surface + 1].texture.z = surface;
609 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
610 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
611 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
612 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
613 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
614 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
615 attrib[4 * surface + 2].texture.x = tex_u_begin;
616 attrib[4 * surface + 2].texture.y = 0.0f;
617 attrib[4 * surface + 2].texture.z = surface;
619 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
620 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
621 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
622 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
623 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
624 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
625 attrib[4 * surface + 3].texture.x = tex_u_end;
626 attrib[4 * surface + 3].texture.y = 0.0f;
627 attrib[4 * surface + 3].texture.z = surface;
631 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
633 auto element = vao->MapElements(GL_WRITE_ONLY);
634 for (int surface = 0; surface < 3; ++surface) {
635 element[6 * surface + 0] = 4 * surface + 0;
636 element[6 * surface + 1] = 4 * surface + 2;
637 element[6 * surface + 2] = 4 * surface + 1;
638 element[6 * surface + 3] = 4 * surface + 1;
639 element[6 * surface + 4] = 4 * surface + 2;
640 element[6 * surface + 5] = 4 * surface + 3;
642 for (int surface = 3; surface < 6; ++surface) {
643 element[6 * surface + 0] = 4 * surface + 0;
644 element[6 * surface + 1] = 4 * surface + 1;
645 element[6 * surface + 2] = 4 * surface + 2;
646 element[6 * surface + 3] = 4 * surface + 2;
647 element[6 * surface + 4] = 4 * surface + 1;
648 element[6 * surface + 5] = 4 * surface + 3;
654 void Creature::KillVAO() {
658 void Creature::Draw(graphics::Viewport &viewport) {
661 vao->DrawTriangles(6 * 6);
665 void Spawn(Creature &c, world::Planet &p) {
667 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
668 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
670 // probe surrounding area for common resources
671 int start = p.SideLength() / 2 - 2;
673 std::map<int, double> yields;
674 for (int y = start; y < end; ++y) {
675 for (int x = start; x < end; ++x) {
676 const world::TileType &t = p.TypeAt(0, x, y);
677 for (auto yield : t.resources) {
678 yields[yield.resource] += yield.ubiquity;
684 for (auto e : yields) {
685 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
686 if (liquid < 0 || e.second > yields[liquid]) {
689 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
690 if (solid < 0 || e.second > yields[solid]) {
697 genome.properties.Strength() = { 2.0, 0.1 };
698 genome.properties.Stamina() = { 2.0, 0.1 };
699 genome.properties.Dexerty() = { 2.0, 0.1 };
700 genome.properties.Intelligence() = { 1.0, 0.1 };
701 genome.properties.Lifetime() = { 480.0, 60.0 };
702 genome.properties.Fertility() = { 0.5, 0.03 };
703 genome.properties.Mutability() = { 0.9, 0.1 };
704 genome.properties.Adaptability() = { 0.9, 0.1 };
705 genome.properties.OffspringMass() = { 0.3, 0.02 };
707 glm::dvec3 color_avg(0.0);
708 double color_divisor = 0.0;
710 if (p.HasAtmosphere()) {
711 c.AddMass(p.Atmosphere(), 0.01);
712 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
713 color_divisor += 0.1;
716 c.AddMass(liquid, 0.3);
717 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
718 color_divisor += 0.5;
721 c.AddMass(solid, 0.1);
722 color_avg += c.GetSimulation().Resources()[solid].base_color;
723 color_divisor += 1.0;
726 if (color_divisor > 0.001) {
727 color_avg /= color_divisor;
729 glm::dvec3 hsl = rgb2hsl(color_avg);
730 genome.base_hue = { hsl.x, 0.01 };
731 genome.base_saturation = { hsl.y, 0.01 };
732 genome.base_lightness = { hsl.z, 0.01 };
733 // use opposite color as start highlight
734 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
735 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
736 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
741 void Genome::Configure(Creature &c) const {
742 c.GetGenome() = *this;
744 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
746 c.GetProperties() = Instantiate(properties, random);
748 // TODO: derive stats from properties
749 c.GetStats().Damage().gain = (-1.0 / 100.0);
750 c.GetStats().Breath().gain = (1.0 / 5.0);
751 c.GetStats().Thirst().gain = (1.0 / 60.0);
752 c.GetStats().Hunger().gain = (1.0 / 200.0);
753 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
754 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
755 c.GetStats().Boredom().gain = (1.0 / 300.0);
757 glm::dvec3 base_color(
758 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
759 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
760 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
762 glm::dvec3 highlight_color(
763 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
764 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
765 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
767 c.BaseColor(hsl2rgb(base_color));
768 c.HighlightColor(hsl2rgb(highlight_color));
769 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
770 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
774 void Split(Creature &c) {
775 Creature *a = new Creature(c.GetSimulation());
776 const Situation &s = c.GetSituation();
778 a->Name(c.GetSimulation().Assets().name.Sequential());
779 c.GetGenome().Configure(*a);
780 for (const auto &cmp : c.GetComposition()) {
781 a->AddMass(cmp.resource, cmp.value * 0.5);
783 s.GetPlanet().AddCreature(a);
784 // TODO: duplicate situation somehow
785 a->GetSituation().SetPlanetSurface(
787 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
789 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
791 Creature *b = new Creature(c.GetSimulation());
793 b->Name(c.GetSimulation().Assets().name.Sequential());
794 c.GetGenome().Configure(*b);
795 for (const auto &cmp : c.GetComposition()) {
796 b->AddMass(cmp.resource, cmp.value * 0.5);
798 s.GetPlanet().AddCreature(b);
799 b->GetSituation().SetPlanetSurface(
801 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
803 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
809 Memory::Memory(Creature &c)
816 void Memory::Erase() {
820 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
821 double best_rating = -1.0;
822 for (const auto &k : known_types) {
823 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
824 auto entry = t.FindBestResource(accept);
825 if (entry != t.resources.end()) {
826 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
827 if (rating > best_rating) {
828 best_rating = rating;
829 pos = k.second.first_loc.position;
831 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
832 if (rating > best_rating) {
833 best_rating = rating;
834 pos = k.second.last_loc.position;
838 if (best_rating > 0.0) {
840 c.GetSimulation().Assets().random.SNorm(),
841 c.GetSimulation().Assets().random.SNorm(),
842 c.GetSimulation().Assets().random.SNorm());
843 pos += error * (2.0 * (1.0 - c.IntelligenceFactor()));
844 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
851 void Memory::Tick(double dt) {
852 Situation &s = c.GetSituation();
854 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
859 void Memory::TrackStay(const Location &l, double t) {
860 const world::TileType &type = l.planet->TileTypeAt(l.position);
861 auto entry = known_types.find(type.id);
862 if (entry != known_types.end()) {
863 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
865 if (entry->second.time_spent > c.Age() * 0.25) {
866 // the place is very familiar
867 c.GetStats().Boredom().Add(-0.2);
870 c.GetStats().Boredom().Add(-0.1);
873 entry->second.last_been = c.GetSimulation().Time();
874 entry->second.last_loc = l;
875 entry->second.time_spent += t;
877 known_types.emplace(type.id, Stay{
878 c.GetSimulation().Time(),
880 c.GetSimulation().Time(),
884 // completely new place, interesting
885 // TODO: scale by personality trait
886 c.GetStats().Boredom().Add(-0.25);
891 NameGenerator::NameGenerator()
895 NameGenerator::~NameGenerator() {
898 std::string NameGenerator::Sequential() {
899 std::stringstream ss;
900 ss << "Blob " << ++counter;
905 Situation::Situation()
907 , state(glm::dvec3(0.0), glm::dvec3(0.0))
911 Situation::~Situation() {
914 bool Situation::OnPlanet() const noexcept {
915 return type == PLANET_SURFACE;
918 bool Situation::OnSurface() const noexcept {
919 return type == PLANET_SURFACE;
922 glm::dvec3 Situation::SurfaceNormal() const noexcept {
923 return planet->NormalAt(state.pos);
926 world::Tile &Situation::GetTile() const noexcept {
927 return planet->TileAt(state.pos);
930 const world::TileType &Situation::GetTileType() const noexcept {
931 return planet->TileTypeAt(state.pos);
934 void Situation::Move(const glm::dvec3 &dp) noexcept {
936 EnforceConstraints(state);
939 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
941 EnforceConstraints(state);
944 void Situation::EnforceConstraints(State &s) noexcept {
946 double r = GetPlanet().Radius();
947 if (glm::length2(s.pos) < r * r) {
948 s.pos = glm::normalize(s.pos) * r;
953 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
954 type = PLANET_SURFACE;
957 EnforceConstraints(state);
961 Steering::Steering(const Creature &c)
975 Steering::~Steering() {
978 void Steering::Off() noexcept {
985 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
987 min_dist = min_distance;
988 max_look = max_lookaround;
991 void Steering::DontSeparate() noexcept {
995 void Steering::ResumeSeparate() noexcept {
999 void Steering::Halt() noexcept {
1005 void Steering::Pass(const glm::dvec3 &t) noexcept {
1012 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1019 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1020 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1021 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1022 glm::dvec3 result(0.0);
1024 // TODO: off surface situation
1025 glm::dvec3 repulse(0.0);
1026 const Situation &s = c.GetSituation();
1027 for (auto &other : s.GetPlanet().Creatures()) {
1028 if (&*other == &c) continue;
1029 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1030 if (glm::length2(diff) > max_look * max_look) continue;
1031 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1032 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1033 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1039 result += -5.0 * s.vel * force;
1042 glm::dvec3 diff = target - s.pos;
1043 if (!allzero(diff)) {
1044 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1048 glm::dvec3 diff = target - s.pos;
1049 double dist = glm::length(diff);
1050 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1051 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1054 if (glm::length2(result) > max_force * max_force) {
1055 result = glm::normalize(result) * max_force;
1060 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1061 return (vel - s.vel) * acc;