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)
142 , perception_range(1.0)
143 , perception_range_squared(1.0)
144 , perception_omni_range(1.0)
145 , perception_omni_range_squared(1.0)
146 , perception_field(1.0)
149 // all creatures avoid each other for now
150 steering.Separate(0.1, 1.5);
153 Creature::~Creature() {
156 void Creature::AddMass(int res, double amount) {
157 composition.Add(res, amount);
158 double nonsolid = 0.0;
160 for (const auto &c : composition) {
161 volume += c.value / sim.Resources()[c.resource].density;
162 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
166 Mass(composition.TotalMass());
167 Size(std::cbrt(volume));
168 highlight_color.a = nonsolid / composition.TotalMass();
171 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
172 highlight_color = glm::dvec4(c, highlight_color.a);
175 void Creature::Ingest(int res, double amount) noexcept {
176 if (sim.Resources()[res].state == world::Resource::SOLID) {
177 // 30% of solids stays in body
178 AddMass(res, amount * 0.3 * composition.Compatibility(res));
180 // 5% of fluids stays in body
181 AddMass(res, amount * 0.05 * composition.Compatibility(res));
183 math::GaloisLFSR &random = sim.Assets().random;
184 if (random.UNorm() < AdaptChance()) {
185 // change color to be slightly more like resource
186 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
187 // solids affect base color, others highlight
188 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
189 double q = random.UInt(3); // hue, sat, or val
190 double r = random.UInt(2); // mean or deviation
191 math::Distribution *d = nullptr;
195 d = &genome.base_hue;
198 d = &genome.base_saturation;
201 d = &genome.base_lightness;
206 d = &genome.highlight_hue;
209 d = &genome.highlight_saturation;
212 d = &genome.highlight_lightness;
217 double diff = ref - d->Mean();
221 } else if (diff > 0.5) {
224 // move ±15% of distance
225 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
227 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
230 // scale by ±15%, enforce bounds
231 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
236 void Creature::DoWork(double amount) noexcept {
237 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
238 // burn resources proportional to composition
239 // factor = 1/total * 1/efficiency * amount * -1
240 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
241 // make a copy to total remains constant and
242 // no entries disappear during iteration
243 Composition comp(composition);
244 for (auto &cmp : comp) {
245 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
246 AddMass(cmp.resource, value);
248 // doing work improves strength a little
249 properties.Strength() += amount * 0.0001;
252 void Creature::Hurt(double amount) noexcept {
253 stats.Damage().Add(amount);
254 if (stats.Damage().Full()) {
259 void Creature::Die() noexcept {
262 if (stats.Damage().Full()) {
263 std::ostream &log = sim.Log() << name << " ";
264 if (stats.Exhaustion().Full()) {
265 log << "died of exhaustion";
266 } else if (stats.Breath().Full()) {
268 } else if (stats.Thirst().Full()) {
269 log << "died of thirst";
270 } else if (stats.Hunger().Full()) {
271 log << "starved to death";
273 log << "succumed to wounds";
275 log << " at an age of " << ui::TimeString(Age())
276 << " (" << ui::PercentageString(Age() / properties.Lifetime())
277 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
290 bool Creature::Dead() const noexcept {
291 return death > birth;
294 void Creature::Remove() noexcept {
298 void Creature::Removed() noexcept {
305 void Creature::AddParent(Creature &p) {
306 parents.push_back(&p);
309 double Creature::Age() const noexcept {
310 return Dead() ? death - birth : sim.Time() - birth;
313 double Creature::AgeFactor(double peak) const noexcept {
314 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
315 // goes negative below -0.5 and starts to rise again above 1.0
316 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
317 // guarantee at least 1%
318 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
321 double Creature::EnergyEfficiency() const noexcept {
322 return 0.25 * AgeFactor(0.05);
325 double Creature::ExhaustionFactor() const noexcept {
326 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
329 double Creature::FatigueFactor() const noexcept {
330 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
333 double Creature::Strength() const noexcept {
334 // TODO: replace all age factors with actual growth and decay
335 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
338 double Creature::StrengthFactor() const noexcept {
339 double str = Strength();
340 return str / (str + 1.0);
343 double Creature::Stamina() const noexcept {
344 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
347 double Creature::StaminaFactor() const noexcept {
348 double stm = Stamina();
349 return stm / (stm + 1.0);
352 double Creature::Dexerty() const noexcept {
353 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
356 double Creature::DexertyFactor() const noexcept {
357 double dex = Dexerty();
358 return dex / (dex + 1.0);
361 double Creature::Intelligence() const noexcept {
362 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
365 double Creature::IntelligenceFactor() const noexcept {
366 double intl = Intelligence();
367 return intl / (intl + 1.0);
370 double Creature::Lifetime() const noexcept {
371 return properties.Lifetime();
374 double Creature::Fertility() const noexcept {
375 return properties.Fertility() * AgeFactor(0.25);
378 double Creature::Mutability() const noexcept {
379 return properties.Mutability();
382 double Creature::Adaptability() const noexcept {
383 return properties.Adaptability();
386 double Creature::OffspringMass() const noexcept {
387 return properties.OffspringMass();
390 double Creature::PerceptionRange() const noexcept {
391 return perception_range;
394 double Creature::PerceptionOmniRange() const noexcept {
395 return perception_omni_range;
398 double Creature::PerceptionField() const noexcept {
399 return perception_field;
402 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
403 const glm::dvec3 diff(p - situation.Position());
404 double ldiff = glm::length2(diff);
405 if (ldiff < perception_omni_range_squared) return true;
406 if (ldiff > perception_range_squared) return false;
407 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
410 double Creature::OffspringChance() const noexcept {
411 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
414 double Creature::MutateChance() const noexcept {
415 return GetProperties().Mutability() * (1.0 / 3600.0);
418 double Creature::AdaptChance() const noexcept {
419 return GetProperties().Adaptability() * (1.0 / 120.0);
422 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
427 goals.emplace_back(std::move(g));
432 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
433 return b->Urgency() < a->Urgency();
438 void Creature::Tick(double dt) {
445 void Creature::Cache() noexcept {
446 double dex_fact = DexertyFactor();
447 perception_range = 3.0 * dex_fact + size;
448 perception_range_squared = perception_range * perception_range;
449 perception_omni_range = 0.5 * dex_fact + size;
450 perception_omni_range_squared = perception_omni_range * perception_omni_range;
451 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
452 perception_field = 0.8 - dex_fact;
455 void Creature::TickState(double dt) {
456 steering.MaxSpeed(Dexerty());
457 steering.MaxForce(Strength());
458 Situation::State state(situation.GetState());
459 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
460 Situation::Derivative b(Step(a, dt * 0.5));
461 Situation::Derivative c(Step(b, dt * 0.5));
462 Situation::Derivative d(Step(c, dt));
463 Situation::Derivative f(
464 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
465 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
467 state.pos += f.vel * dt;
468 state.vel += f.acc * dt;
469 situation.EnforceConstraints(state);
470 if (glm::length2(state.vel) > 0.000001) {
471 glm::dvec3 nvel(glm::normalize(state.vel));
472 double ang = glm::angle(nvel, state.dir);
473 double turn_rate = PI * 0.75 * dt;
474 if (ang < turn_rate) {
475 state.dir = glm::normalize(state.vel);
476 } else if (std::abs(ang - PI) < 0.001) {
477 state.dir = glm::rotate(state.dir, turn_rate, situation.GetPlanet().NormalAt(state.pos));
479 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, nvel)));
482 situation.SetState(state);
483 // work is force times distance
484 // exclude gravity for no apparent reason
485 // actually, this should solely be based on steering force
486 DoWork(glm::length(f.acc - situation.GetPlanet().GravityAt(state.pos)) * Mass() * glm::length(f.vel) * dt);
489 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
490 Situation::State s = situation.GetState();
491 s.pos += ds.vel * dt;
492 s.vel += ds.acc * dt;
493 situation.EnforceConstraints(s);
494 glm::dvec3 force(steering.Force(s));
495 // gravity = antinormal * mass * Gm / r²
496 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
499 * (Mass() * situation.GetPlanet().GravitationalParameter()
500 / glm::length2(s.pos)));
501 // if net force is applied and in contact with surface
502 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
504 glm::dvec3 fn(normal * glm::dot(force, normal));
505 // TODO: friction somehow bigger than force?
506 glm::dvec3 ft(force - fn);
508 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
517 void Creature::TickStats(double dt) {
518 for (auto &s : stats.stat) {
521 // TODO: damage values depending on properties
522 if (stats.Breath().Full()) {
523 constexpr double dps = 1.0 / 4.0;
526 if (stats.Thirst().Full()) {
527 constexpr double dps = 1.0 / 32.0;
530 if (stats.Hunger().Full()) {
531 constexpr double dps = 1.0 / 128.0;
534 if (!situation.Moving()) {
535 // double exhaustion recovery when standing still
536 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
540 void Creature::TickBrain(double dt) {
544 // do background stuff
548 for (auto &goal : goals) {
551 Goal *top = &*goals.front();
552 // if active goal can be interrupted, check priorities
553 if (goals.size() > 1 && goals[0]->Interruptible()) {
554 std::sort(goals.begin(), goals.end(), GoalCompare);
556 if (&*goals.front() != top) {
557 top->SetBackground();
558 goals.front()->SetForeground();
559 top = &*goals.front();
562 for (auto goal = goals.begin(); goal != goals.end();) {
563 if ((*goal)->Complete()) {
569 if (&*goals.front() != top) {
570 goals.front()->SetForeground();
574 math::AABB Creature::CollisionBounds() const noexcept {
575 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
578 glm::dmat4 Creature::CollisionTransform() const noexcept {
579 const double half_size = size * 0.5;
580 const glm::dvec3 &pos = situation.Position();
582 orient[1] = situation.GetPlanet().NormalAt(pos);
583 orient[2] = situation.Heading();
584 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
585 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
587 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
588 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
589 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
591 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
594 glm::dmat4 Creature::LocalTransform() noexcept {
595 const double half_size = size * 0.5;
596 return CollisionTransform()
597 * glm::scale(glm::dvec3(half_size, half_size, half_size));
600 void Creature::BuildVAO() {
601 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
603 vao->BindAttributes();
604 vao->EnableAttribute(0);
605 vao->EnableAttribute(1);
606 vao->EnableAttribute(2);
607 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
608 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
609 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
610 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
612 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
613 const float offset = 1.0f;
614 for (int surface = 0; surface < 6; ++surface) {
615 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
616 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
618 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
619 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
620 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
621 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
622 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
623 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
624 attrib[4 * surface + 0].texture.x = tex_u_begin;
625 attrib[4 * surface + 0].texture.y = 1.0f;
626 attrib[4 * surface + 0].texture.z = surface;
628 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
629 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
630 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
631 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
632 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
633 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
634 attrib[4 * surface + 1].texture.x = tex_u_end;
635 attrib[4 * surface + 1].texture.y = 1.0f;
636 attrib[4 * surface + 1].texture.z = surface;
638 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
639 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
640 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
641 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
642 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
643 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
644 attrib[4 * surface + 2].texture.x = tex_u_begin;
645 attrib[4 * surface + 2].texture.y = 0.0f;
646 attrib[4 * surface + 2].texture.z = surface;
648 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
649 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
650 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
651 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
652 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
653 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
654 attrib[4 * surface + 3].texture.x = tex_u_end;
655 attrib[4 * surface + 3].texture.y = 0.0f;
656 attrib[4 * surface + 3].texture.z = surface;
660 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
662 auto element = vao->MapElements(GL_WRITE_ONLY);
663 for (int surface = 0; surface < 3; ++surface) {
664 element[6 * surface + 0] = 4 * surface + 0;
665 element[6 * surface + 1] = 4 * surface + 2;
666 element[6 * surface + 2] = 4 * surface + 1;
667 element[6 * surface + 3] = 4 * surface + 1;
668 element[6 * surface + 4] = 4 * surface + 2;
669 element[6 * surface + 5] = 4 * surface + 3;
671 for (int surface = 3; surface < 6; ++surface) {
672 element[6 * surface + 0] = 4 * surface + 0;
673 element[6 * surface + 1] = 4 * surface + 1;
674 element[6 * surface + 2] = 4 * surface + 2;
675 element[6 * surface + 3] = 4 * surface + 2;
676 element[6 * surface + 4] = 4 * surface + 1;
677 element[6 * surface + 5] = 4 * surface + 3;
683 void Creature::KillVAO() {
687 void Creature::Draw(graphics::Viewport &viewport) {
690 vao->DrawTriangles(6 * 6);
694 void Spawn(Creature &c, world::Planet &p) {
696 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
697 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
699 // probe surrounding area for common resources
700 int start = p.SideLength() / 2 - 2;
702 std::map<int, double> yields;
703 for (int y = start; y < end; ++y) {
704 for (int x = start; x < end; ++x) {
705 const world::TileType &t = p.TypeAt(0, x, y);
706 for (auto yield : t.resources) {
707 yields[yield.resource] += yield.ubiquity;
713 for (auto e : yields) {
714 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
715 if (liquid < 0 || e.second > yields[liquid]) {
718 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
719 if (solid < 0 || e.second > yields[solid]) {
726 genome.properties.Strength() = { 2.0, 0.1 };
727 genome.properties.Stamina() = { 2.0, 0.1 };
728 genome.properties.Dexerty() = { 2.0, 0.1 };
729 genome.properties.Intelligence() = { 1.0, 0.1 };
730 genome.properties.Lifetime() = { 480.0, 60.0 };
731 genome.properties.Fertility() = { 0.5, 0.03 };
732 genome.properties.Mutability() = { 0.9, 0.1 };
733 genome.properties.Adaptability() = { 0.9, 0.1 };
734 genome.properties.OffspringMass() = { 0.3, 0.02 };
736 glm::dvec3 color_avg(0.0);
737 double color_divisor = 0.0;
739 if (p.HasAtmosphere()) {
740 c.AddMass(p.Atmosphere(), 0.01);
741 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
742 color_divisor += 0.1;
745 c.AddMass(liquid, 0.3);
746 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
747 color_divisor += 0.5;
750 c.AddMass(solid, 0.1);
751 color_avg += c.GetSimulation().Resources()[solid].base_color;
752 color_divisor += 1.0;
755 if (color_divisor > 0.001) {
756 color_avg /= color_divisor;
758 glm::dvec3 hsl = rgb2hsl(color_avg);
759 genome.base_hue = { hsl.x, 0.01 };
760 genome.base_saturation = { hsl.y, 0.01 };
761 genome.base_lightness = { hsl.z, 0.01 };
762 // use opposite color as start highlight
763 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
764 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
765 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
770 void Genome::Configure(Creature &c) const {
771 c.GetGenome() = *this;
773 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
775 c.GetProperties() = Instantiate(properties, random);
777 // TODO: derive stats from properties
778 c.GetStats().Damage().gain = (-1.0 / 100.0);
779 c.GetStats().Breath().gain = (1.0 / 5.0);
780 c.GetStats().Thirst().gain = (1.0 / 60.0);
781 c.GetStats().Hunger().gain = (1.0 / 200.0);
782 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
783 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
784 c.GetStats().Boredom().gain = (1.0 / 300.0);
786 glm::dvec3 base_color(
787 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
788 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
789 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
791 glm::dvec3 highlight_color(
792 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
793 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
794 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
796 c.BaseColor(hsl2rgb(base_color));
797 c.HighlightColor(hsl2rgb(highlight_color));
798 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
799 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
803 void Split(Creature &c) {
804 Creature *a = new Creature(c.GetSimulation());
805 const Situation &s = c.GetSituation();
807 a->Name(c.GetSimulation().Assets().name.Sequential());
808 c.GetGenome().Configure(*a);
809 for (const auto &cmp : c.GetComposition()) {
810 a->AddMass(cmp.resource, cmp.value * 0.5);
812 s.GetPlanet().AddCreature(a);
813 // TODO: duplicate situation somehow
814 a->GetSituation().SetPlanetSurface(
816 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.6, PI * 0.5, s.SurfaceNormal()));
818 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
820 Creature *b = new Creature(c.GetSimulation());
822 b->Name(c.GetSimulation().Assets().name.Sequential());
823 c.GetGenome().Configure(*b);
824 for (const auto &cmp : c.GetComposition()) {
825 b->AddMass(cmp.resource, cmp.value * 0.5);
827 s.GetPlanet().AddCreature(b);
828 b->GetSituation().SetPlanetSurface(
830 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.6, PI * -0.5, s.SurfaceNormal()));
832 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
838 Memory::Memory(Creature &c)
845 void Memory::Erase() {
849 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
850 double best_rating = -1.0;
851 for (const auto &k : known_types) {
852 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
853 auto entry = t.FindBestResource(accept);
854 if (entry != t.resources.end()) {
855 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
856 if (rating > best_rating) {
857 best_rating = rating;
858 pos = k.second.first_loc.position;
860 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
861 if (rating > best_rating) {
862 best_rating = rating;
863 pos = k.second.last_loc.position;
867 if (best_rating > 0.0) {
869 c.GetSimulation().Assets().random.SNorm(),
870 c.GetSimulation().Assets().random.SNorm(),
871 c.GetSimulation().Assets().random.SNorm());
872 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
873 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
880 void Memory::Tick(double dt) {
881 Situation &s = c.GetSituation();
883 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
888 void Memory::TrackStay(const Location &l, double t) {
889 const world::TileType &type = l.planet->TileTypeAt(l.position);
890 auto entry = known_types.find(type.id);
891 if (entry != known_types.end()) {
892 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
894 if (entry->second.time_spent > c.Age() * 0.25) {
895 // the place is very familiar
896 c.GetStats().Boredom().Add(-0.2);
899 c.GetStats().Boredom().Add(-0.1);
902 entry->second.last_been = c.GetSimulation().Time();
903 entry->second.last_loc = l;
904 entry->second.time_spent += t;
906 known_types.emplace(type.id, Stay{
907 c.GetSimulation().Time(),
909 c.GetSimulation().Time(),
913 // completely new place, interesting
914 // TODO: scale by personality trait
915 c.GetStats().Boredom().Add(-0.25);
920 NameGenerator::NameGenerator()
924 NameGenerator::~NameGenerator() {
927 std::string NameGenerator::Sequential() {
928 std::stringstream ss;
929 ss << "Blob " << ++counter;
934 Situation::Situation()
936 , state(glm::dvec3(0.0), glm::dvec3(0.0))
940 Situation::~Situation() {
943 bool Situation::OnPlanet() const noexcept {
944 return type == PLANET_SURFACE;
947 bool Situation::OnSurface() const noexcept {
948 return type == PLANET_SURFACE;
951 bool Situation::OnGround() const noexcept {
952 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
955 glm::dvec3 Situation::SurfaceNormal() const noexcept {
956 return planet->NormalAt(state.pos);
959 world::Tile &Situation::GetTile() const noexcept {
960 return planet->TileAt(state.pos);
963 const world::TileType &Situation::GetTileType() const noexcept {
964 return planet->TileTypeAt(state.pos);
967 void Situation::Move(const glm::dvec3 &dp) noexcept {
969 EnforceConstraints(state);
972 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
974 EnforceConstraints(state);
977 void Situation::EnforceConstraints(State &s) const noexcept {
979 double r = GetPlanet().Radius();
980 if (glm::length2(s.pos) < r * r) {
981 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
983 s.vel -= normal * glm::dot(normal, s.vel);
988 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
989 type = PLANET_SURFACE;
992 EnforceConstraints(state);
996 Steering::Steering(const Creature &c)
1010 Steering::~Steering() {
1013 void Steering::Off() noexcept {
1020 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1022 min_dist = min_distance;
1023 max_look = max_lookaround;
1026 void Steering::DontSeparate() noexcept {
1030 void Steering::ResumeSeparate() noexcept {
1034 void Steering::Halt() noexcept {
1040 void Steering::Pass(const glm::dvec3 &t) noexcept {
1047 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1054 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1055 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1056 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1057 glm::dvec3 result(0.0);
1059 // TODO: off surface situation
1060 glm::dvec3 repulse(0.0);
1061 const Situation &s = c.GetSituation();
1062 for (auto &other : s.GetPlanet().Creatures()) {
1063 if (&*other == &c) continue;
1064 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1065 if (glm::length2(diff) > max_look * max_look) continue;
1066 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1067 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1068 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1074 result += -5.0 * s.vel * force;
1077 glm::dvec3 diff = target - s.pos;
1078 if (!allzero(diff)) {
1079 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1083 glm::dvec3 diff = target - s.pos;
1084 double dist = glm::length(diff);
1085 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1086 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1089 // remove vertical component, if any
1090 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1091 result -= normal * glm::dot(normal, result);
1093 if (glm::length2(result) > max_force * max_force) {
1094 result = glm::normalize(result) * max_force;
1099 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1100 return (vel - s.vel) * acc;