1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "AttackGoal.hpp"
10 #include "BlobBackgroundTask.hpp"
12 #include "IdleGoal.hpp"
13 #include "../app/Assets.hpp"
14 #include "../graphics/color.hpp"
15 #include "../math/const.hpp"
16 #include "../ui/string.hpp"
17 #include "../world/Body.hpp"
18 #include "../world/Planet.hpp"
19 #include "../world/Simulation.hpp"
20 #include "../world/TileType.hpp"
24 #include <glm/gtx/transform.hpp>
25 #include <glm/gtx/vector_angle.hpp>
28 #include <glm/gtx/io.hpp>
30 using blobs::graphics::hsl2rgb;
31 using blobs::graphics::rgb2hsl;
37 Composition::Composition(const world::Set<world::Resource> &resources)
38 : resources(resources)
45 Composition::~Composition() {
49 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
50 return b.value < a.value;
54 void Composition::Add(int res, double amount) {
56 for (auto c = components.begin(); c != components.end(); ++c) {
57 if (c->resource == res) {
59 if (c->value <= 0.0) {
67 if (!found && amount > 0.0) {
68 components.emplace_back(res, amount);
70 std::sort(components.begin(), components.end(), CompositionCompare);
71 state_mass[resources[res].state] += amount;
73 total_volume += amount / resources[res].density;
76 bool Composition::Has(int res) const noexcept {
77 for (auto &c : components) {
78 if (c.resource == res) {
85 double Composition::Get(int res) const noexcept {
86 for (auto &c : components) {
87 if (c.resource == res) {
94 double Composition::Proportion(int res) const noexcept {
95 return Get(res) / TotalMass();
98 double Composition::StateProportion(int res) const noexcept {
99 return Get(res) / StateMass(resources[res].state);
102 double Composition::Compatibility(int res) const noexcept {
104 return StateProportion(res);
106 double max_compat = -1.0;
107 double min_compat = 1.0;
108 for (const auto &c : components) {
109 double prop = c.value / StateMass(resources[res].state);
110 for (const auto &compat : resources[c.resource].compatibility) {
111 double value = compat.second * prop;
112 if (value > max_compat) {
115 if (value < min_compat) {
120 if (min_compat < 0.0) {
128 Creature::Creature(world::Simulation &sim)
133 , composition(sim.Resources())
135 , highlight_color(0.0, 0.0, 0.0, 1.0)
149 , heading_target(0.0, 0.0, -1.0)
150 , heading_manual(false)
151 , perception_range(1.0)
152 , perception_range_squared(1.0)
153 , perception_omni_range(1.0)
154 , perception_omni_range_squared(1.0)
155 , perception_field(1.0)
158 // all creatures avoid each other for now
159 steering.Separate(0.1, 1.5);
162 Creature::~Creature() {
165 void Creature::AddMass(int res, double amount) {
166 composition.Add(res, amount);
167 double nonsolid = 0.0;
169 for (const auto &c : composition) {
170 volume += c.value / sim.Resources()[c.resource].density;
171 if (sim.Resources()[c.resource].state != world::Resource::SOLID) {
175 Mass(composition.TotalMass());
176 Size(std::cbrt(volume));
177 highlight_color.a = nonsolid / composition.TotalMass();
180 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
181 highlight_color = glm::dvec4(c, highlight_color.a);
184 void Creature::Ingest(int res, double amount) noexcept {
185 if (sim.Resources()[res].state == world::Resource::SOLID) {
186 // 30% of solids stays in body
187 AddMass(res, amount * 0.3 * composition.Compatibility(res));
189 // 10% of fluids stays in body
190 AddMass(res, amount * 0.1 * composition.Compatibility(res));
192 math::GaloisLFSR &random = sim.Assets().random;
193 if (random.UNorm() < AdaptChance()) {
194 // change color to be slightly more like resource
195 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
196 // solids affect base color, others highlight
197 int p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
198 int q = random.UInt(3); // hue, sat, or val
199 int r = random.UInt(2); // mean or deviation
200 math::Distribution *d = nullptr;
204 d = &genome.base_hue;
207 d = &genome.base_saturation;
210 d = &genome.base_lightness;
215 d = &genome.highlight_hue;
218 d = &genome.highlight_saturation;
221 d = &genome.highlight_lightness;
226 double diff = ref - d->Mean();
230 } else if (diff > 0.5) {
233 // move 0-15% of distance
234 d->Mean(std::fmod(d->Mean() + diff * random.UNorm() * 0.15, 1.0));
236 d->Mean(glm::clamp(d->Mean() + diff * random.UNorm() * 0.15, 0.0, 1.0));
239 // scale by ±15%, enforce bounds
240 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
243 if (sim.Resources()[res].state == world::Resource::LIQUID && random.UNorm() < AdaptChance()) {
244 // change texture randomly
245 // TODO: make change depending on surroundings and/or resource
246 int p = random.UInt(2); // back or side
247 int q = random.UInt(2); // mean or deviation
248 math::Distribution &d = p ? genome.skin_side : genome.skin_back;
250 // move ± one standard deviation
251 d.Mean(d.Mean() + (random.SNorm() * d.StandardDeviation()));
253 // scale by ±10%, enforce bounds
254 d.StandardDeviation(glm::clamp(d.StandardDeviation() * (1.0 + random.SNorm() * 0.1), 0.0001, 0.5));
259 void Creature::DoWork(double amount) noexcept {
260 stats.Exhaustion().Add(amount / (Stamina() + 1.0));
261 // burn resources proportional to composition
262 // factor = 1/total * 1/efficiency * amount * -1
263 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
264 // make a copy to total remains constant and
265 // no entries disappear during iteration
266 Composition comp(composition);
267 for (auto &cmp : comp) {
268 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
269 AddMass(cmp.resource, value);
271 // doing work improves strength a little
272 properties.Strength() += amount * 0.0001;
275 void Creature::Hurt(double amount) noexcept {
276 stats.Damage().Add(amount);
277 if (stats.Damage().Full()) {
282 void Creature::Die() noexcept {
285 if (stats.Damage().Full()) {
286 std::ostream &log = sim.Log() << name << " ";
287 if (stats.Exhaustion().Full()) {
288 log << "died of exhaustion";
289 } else if (stats.Breath().Full()) {
291 } else if (stats.Thirst().Full()) {
292 log << "died of thirst";
293 } else if (stats.Hunger().Full()) {
294 log << "starved to death";
296 log << "succumed to wounds";
298 log << " at an age of " << ui::TimeString(Age())
299 << " (" << ui::PercentageString(Age() / properties.Lifetime())
300 << " of life expectancy of " << ui::TimeString(properties.Lifetime())
313 bool Creature::Dead() const noexcept {
314 return death > birth;
317 void Creature::Remove() noexcept {
321 void Creature::Removed() noexcept {
328 void Creature::AddParent(Creature &p) {
329 parents.push_back(&p);
332 double Creature::Age() const noexcept {
333 return Dead() ? death - birth : sim.Time() - birth;
336 double Creature::AgeFactor(double peak) const noexcept {
337 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
338 // goes negative below -0.5 and starts to rise again above 1.0
339 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
340 // guarantee at least 1%
341 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
344 double Creature::EnergyEfficiency() const noexcept {
345 return 0.25 * AgeFactor(0.05);
348 double Creature::ExhaustionFactor() const noexcept {
349 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
352 double Creature::FatigueFactor() const noexcept {
353 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
356 double Creature::Strength() const noexcept {
357 // TODO: replace all age factors with actual growth and decay
358 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
361 double Creature::StrengthFactor() const noexcept {
362 double str = Strength();
363 return str / (str + 1.0);
366 double Creature::Stamina() const noexcept {
367 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
370 double Creature::StaminaFactor() const noexcept {
371 double stm = Stamina();
372 return stm / (stm + 1.0);
375 double Creature::Dexerty() const noexcept {
376 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
379 double Creature::DexertyFactor() const noexcept {
380 double dex = Dexerty();
381 return dex / (dex + 1.0);
384 double Creature::Intelligence() const noexcept {
385 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
388 double Creature::IntelligenceFactor() const noexcept {
389 double intl = Intelligence();
390 return intl / (intl + 1.0);
393 double Creature::Lifetime() const noexcept {
394 return properties.Lifetime();
397 double Creature::Fertility() const noexcept {
398 return properties.Fertility() * AgeFactor(0.25);
401 double Creature::Mutability() const noexcept {
402 return properties.Mutability();
405 double Creature::Adaptability() const noexcept {
406 return properties.Adaptability();
409 double Creature::OffspringMass() const noexcept {
410 return properties.OffspringMass();
413 double Creature::PerceptionRange() const noexcept {
414 return perception_range;
417 double Creature::PerceptionOmniRange() const noexcept {
418 return perception_omni_range;
421 double Creature::PerceptionField() const noexcept {
422 return perception_field;
425 bool Creature::PerceptionTest(const glm::dvec3 &p) const noexcept {
426 const glm::dvec3 diff(p - situation.Position());
427 double ldiff = glm::length2(diff);
428 if (ldiff < perception_omni_range_squared) return true;
429 if (ldiff > perception_range_squared) return false;
430 return glm::dot(diff / std::sqrt(ldiff), situation.Heading()) > perception_field;
433 double Creature::OffspringChance() const noexcept {
434 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
437 double Creature::MutateChance() const noexcept {
438 return GetProperties().Mutability() * (1.0 / 3600.0);
441 double Creature::AdaptChance() const noexcept {
442 return GetProperties().Adaptability() * (1.0 / 120.0);
445 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
450 goals.emplace_back(std::move(g));
453 void Creature::SetBackgroundTask(std::unique_ptr<Goal> &&g) {
454 bg_task = std::move(g);
457 Goal &Creature::BackgroundTask() {
463 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
464 return b->Urgency() < a->Urgency();
469 void Creature::Tick(double dt) {
476 void Creature::Cache() noexcept {
477 double dex_fact = DexertyFactor();
478 perception_range = 3.0 * dex_fact + size;
479 perception_range_squared = perception_range * perception_range;
480 perception_omni_range = 0.5 * dex_fact + size;
481 perception_omni_range_squared = perception_omni_range * perception_omni_range;
482 // this is the cosine of half the angle, so 1.0 is none, -1.0 is perfect
483 perception_field = 0.8 - dex_fact;
486 void Creature::TickState(double dt) {
487 steering.MaxSpeed(Dexerty());
488 steering.MaxForce(Strength());
489 Situation::State state(situation.GetState());
490 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
491 Situation::Derivative b(Step(a, dt * 0.5));
492 Situation::Derivative c(Step(b, dt * 0.5));
493 Situation::Derivative d(Step(c, dt));
494 Situation::Derivative f(
495 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
496 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
498 state.pos += f.vel * dt;
499 state.vel += f.acc * dt;
500 situation.EnforceConstraints(state);
502 if (!heading_manual && glm::length2(state.vel) > 0.000001) {
503 const glm::dvec3 normal(situation.GetPlanet().NormalAt(state.pos));
504 const glm::dvec3 tangent(state.vel - (normal * glm::dot(state.vel, normal)));
505 if (glm::length2(tangent) > 0.000001) {
506 heading_target = glm::normalize(tangent);
509 double ang = glm::angle(heading_target, state.dir);
510 double turn_rate = PI * 0.75 * dt;
511 if (ang < turn_rate) {
512 state.dir = heading_target;
513 heading_manual = false;
515 state.dir = glm::rotate(state.dir, turn_rate, glm::normalize(glm::cross(state.dir, heading_target)));
518 situation.SetState(state);
519 // work is force times distance
520 // keep 10% of gravity as a kind of background burn
521 DoWork(glm::length(f.acc - (0.9 * situation.GetPlanet().GravityAt(state.pos))) * Mass() * glm::length(f.vel) * dt);
524 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
525 Situation::State s = situation.GetState();
526 s.pos += ds.vel * dt;
527 s.vel += ds.acc * dt;
528 situation.EnforceConstraints(s);
529 glm::dvec3 force(steering.Force(s));
530 // gravity = antinormal * mass * Gm / r²
531 glm::dvec3 normal(situation.GetPlanet().NormalAt(s.pos));
534 * (Mass() * situation.GetPlanet().GravitationalParameter()
535 / glm::length2(s.pos)));
536 // if net force is applied and in contact with surface
537 if (!allzero(force) && !allzero(s.vel) && glm::length2(s.pos) < (situation.GetPlanet().Radius() + 0.01) * (situation.GetPlanet().Radius() + 0.01)) {
539 glm::dvec3 fn(normal * glm::dot(force, normal));
540 // TODO: friction somehow bigger than force?
541 glm::dvec3 ft(force - fn);
543 glm::dvec3 friction(-glm::clamp(glm::length(ft), 0.0, glm::length(fn) * u) * glm::normalize(s.vel));
552 void Creature::TickStats(double dt) {
553 for (auto &s : stats.stat) {
556 // TODO: damage values depending on properties
557 if (stats.Breath().Full()) {
558 constexpr double dps = 1.0 / 4.0;
561 if (stats.Thirst().Full()) {
562 constexpr double dps = 1.0 / 32.0;
565 if (stats.Hunger().Full()) {
566 constexpr double dps = 1.0 / 128.0;
569 if (!situation.Moving()) {
570 // double exhaustion recovery when standing still
571 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
575 void Creature::TickBrain(double dt) {
579 // do background stuff
583 for (auto &goal : goals) {
586 Goal *top = &*goals.front();
587 // if active goal can be interrupted, check priorities
588 if (goals.size() > 1 && goals[0]->Interruptible()) {
589 std::sort(goals.begin(), goals.end(), GoalCompare);
591 if (&*goals.front() != top) {
592 top->SetBackground();
593 goals.front()->SetForeground();
594 top = &*goals.front();
597 for (auto goal = goals.begin(); goal != goals.end();) {
598 if ((*goal)->Complete()) {
604 if (&*goals.front() != top) {
605 goals.front()->SetForeground();
609 math::AABB Creature::CollisionBounds() const noexcept {
610 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
613 glm::dmat4 Creature::CollisionTransform() const noexcept {
614 const double half_size = size * 0.5;
615 const glm::dvec3 &pos = situation.Position();
617 orient[1] = situation.GetPlanet().NormalAt(pos);
618 orient[2] = situation.Heading();
619 if (std::abs(glm::dot(orient[1], orient[2])) > 0.999) {
620 orient[2] = glm::dvec3(orient[1].z, orient[1].x, orient[1].y);
622 orient[0] = glm::normalize(glm::cross(orient[1], orient[2]));
623 orient[2] = glm::normalize(glm::cross(orient[0], orient[1]));
624 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z))
626 * glm::translate(glm::dvec3(0.0, half_size, 0.0));
629 void Creature::OnCollide(Creature &other) {
630 memory.TrackCollision(other);
633 glm::dmat4 Creature::LocalTransform() noexcept {
634 const double half_size = size * 0.5;
635 return CollisionTransform()
636 * glm::scale(glm::dvec3(half_size, half_size, half_size));
639 void Creature::BuildVAO() {
640 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
642 vao->BindAttributes();
643 vao->EnableAttribute(0);
644 vao->EnableAttribute(1);
645 vao->EnableAttribute(2);
646 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
647 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
648 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
649 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
651 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
652 constexpr float offset = 1.0f;
653 constexpr float max_tex = 5.999f;
654 const float tex[6] = {
656 float(std::floor(skin_side * max_tex)), // left
657 float(std::floor(skin_back * max_tex)), // top
658 float(std::floor(skin_back * max_tex)), // back
659 float(std::floor(skin_side * max_tex)), // right
662 for (int surface = 0; surface < 6; ++surface) {
663 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
664 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
666 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
667 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
668 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
669 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
670 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
671 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
672 attrib[4 * surface + 0].texture.x = tex_u_begin;
673 attrib[4 * surface + 0].texture.y = 1.0f;
674 attrib[4 * surface + 0].texture.z = tex[surface];
676 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
677 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
678 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
679 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
680 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
681 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
682 attrib[4 * surface + 1].texture.x = tex_u_end;
683 attrib[4 * surface + 1].texture.y = 1.0f;
684 attrib[4 * surface + 1].texture.z = tex[surface];
686 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
687 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
688 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
689 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
690 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
691 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
692 attrib[4 * surface + 2].texture.x = tex_u_begin;
693 attrib[4 * surface + 2].texture.y = 0.0f;
694 attrib[4 * surface + 2].texture.z = tex[surface];
696 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
697 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
698 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
699 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
700 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
701 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
702 attrib[4 * surface + 3].texture.x = tex_u_end;
703 attrib[4 * surface + 3].texture.y = 0.0f;
704 attrib[4 * surface + 3].texture.z = tex[surface];
708 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
710 auto element = vao->MapElements(GL_WRITE_ONLY);
711 for (int surface = 0; surface < 3; ++surface) {
712 element[6 * surface + 0] = 4 * surface + 0;
713 element[6 * surface + 1] = 4 * surface + 2;
714 element[6 * surface + 2] = 4 * surface + 1;
715 element[6 * surface + 3] = 4 * surface + 1;
716 element[6 * surface + 4] = 4 * surface + 2;
717 element[6 * surface + 5] = 4 * surface + 3;
719 for (int surface = 3; surface < 6; ++surface) {
720 element[6 * surface + 0] = 4 * surface + 0;
721 element[6 * surface + 1] = 4 * surface + 1;
722 element[6 * surface + 2] = 4 * surface + 2;
723 element[6 * surface + 3] = 4 * surface + 2;
724 element[6 * surface + 4] = 4 * surface + 1;
725 element[6 * surface + 5] = 4 * surface + 3;
731 void Creature::KillVAO() {
735 void Creature::Draw(graphics::Viewport &viewport) {
738 vao->DrawTriangles(6 * 6);
742 void Spawn(Creature &c, world::Planet &p) {
744 c.GetSituation().SetPlanetSurface(p, glm::dvec3(0.0, 0.0, p.Radius()));
745 c.GetSituation().Heading(glm::dvec3(1.0, 0.0, 0.0));
746 c.HeadingTarget(glm::dvec3(1.0, 0.0, 0.0));
748 // probe surrounding area for common resources
749 int start = p.SideLength() / 2 - 2;
751 std::map<int, double> yields;
752 for (int y = start; y < end; ++y) {
753 for (int x = start; x < end; ++x) {
754 const world::TileType &t = p.TypeAt(0, x, y);
755 for (auto yield : t.resources) {
756 yields[yield.resource] += yield.ubiquity;
762 for (auto e : yields) {
763 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
764 if (liquid < 0 || e.second > yields[liquid]) {
767 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
768 if (solid < 0 || e.second > yields[solid]) {
775 genome.properties.Strength() = { 2.0, 0.1 };
776 genome.properties.Stamina() = { 2.0, 0.1 };
777 genome.properties.Dexerty() = { 2.0, 0.1 };
778 genome.properties.Intelligence() = { 1.0, 0.1 };
779 genome.properties.Lifetime() = { 480.0, 60.0 };
780 genome.properties.Fertility() = { 0.5, 0.03 };
781 genome.properties.Mutability() = { 0.9, 0.1 };
782 genome.properties.Adaptability() = { 0.9, 0.1 };
783 genome.properties.OffspringMass() = { 0.3, 0.02 };
785 glm::dvec3 color_avg(0.0);
786 double color_divisor = 0.0;
788 if (p.HasAtmosphere()) {
789 c.AddMass(p.Atmosphere(), 0.005);
790 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
791 color_divisor += 0.1;
794 c.AddMass(liquid, 0.3);
795 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
796 color_divisor += 0.5;
799 c.AddMass(solid, 0.1);
800 color_avg += c.GetSimulation().Resources()[solid].base_color;
801 color_divisor += 1.0;
804 if (color_divisor > 0.001) {
805 color_avg /= color_divisor;
807 glm::dvec3 hsl = rgb2hsl(color_avg);
808 genome.base_hue = { hsl.x, 0.01 };
809 genome.base_saturation = { hsl.y, 0.01 };
810 genome.base_lightness = { hsl.z, 0.01 };
811 // use opposite color as start highlight
812 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
813 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
814 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
816 genome.skin_side = { 0.5, 0.01 };
817 genome.skin_back = { 0.5, 0.01 };
822 void Genome::Configure(Creature &c) const {
823 c.GetGenome() = *this;
825 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
827 c.GetProperties() = Instantiate(properties, random);
829 // TODO: derive stats from properties
830 c.GetStats().Damage().gain = (-1.0 / 100.0);
831 c.GetStats().Breath().gain = (1.0 / 5.0);
832 c.GetStats().Thirst().gain = (1.0 / 60.0);
833 c.GetStats().Hunger().gain = (1.0 / 200.0);
834 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
835 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
836 c.GetStats().Boredom().gain = (1.0 / 300.0);
838 glm::dvec3 base_color(
839 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
840 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
841 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
843 glm::dvec3 highlight_color(
844 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
845 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
846 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
848 c.BaseColor(hsl2rgb(base_color));
849 c.HighlightColor(hsl2rgb(highlight_color));
850 c.BackSkin(glm::clamp(skin_back.FakeNormal(random.SNorm()), 0.0, 1.0));
851 c.SideSkin(glm::clamp(skin_side.FakeNormal(random.SNorm()), 0.0, 1.0));
852 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
853 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
857 void Split(Creature &c) {
858 Creature *a = new Creature(c.GetSimulation());
859 const Situation &s = c.GetSituation();
861 a->Name(c.GetSimulation().Assets().name.Sequential());
862 c.GetGenome().Configure(*a);
863 for (const auto &cmp : c.GetComposition()) {
864 // require at least 0.1%
865 if (cmp.value > 0.002) {
866 a->AddMass(cmp.resource, cmp.value * 0.5);
869 s.GetPlanet().AddCreature(a);
870 // TODO: duplicate situation somehow
871 a->GetSituation().SetPlanetSurface(
873 s.Position() + glm::rotate(s.Heading() * a->Size() * 0.86, PI * 0.5, s.SurfaceNormal()));
875 c.GetSimulation().Log() << a->Name() << " was born" << std::endl;
877 Creature *b = new Creature(c.GetSimulation());
879 b->Name(c.GetSimulation().Assets().name.Sequential());
880 c.GetGenome().Configure(*b);
881 for (const auto &cmp : c.GetComposition()) {
882 // require at least 0.1%
883 if (cmp.value > 0.002) {
884 b->AddMass(cmp.resource, cmp.value * 0.5);
887 s.GetPlanet().AddCreature(b);
888 b->GetSituation().SetPlanetSurface(
890 s.Position() + glm::rotate(s.Heading() * b->Size() * 0.86, PI * -0.5, s.SurfaceNormal()));
892 c.GetSimulation().Log() << b->Name() << " was born" << std::endl;
898 Memory::Memory(Creature &c)
905 void Memory::Erase() {
907 known_creatures.clear();
910 bool Memory::RememberLocation(const Composition &accept, glm::dvec3 &pos) const noexcept {
911 double best_rating = -1.0;
912 for (const auto &k : known_types) {
913 const world::TileType &t = c.GetSimulation().TileTypes()[k.first];
914 auto entry = t.FindBestResource(accept);
915 if (entry != t.resources.end()) {
916 double rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.first_loc.position));
917 if (rating > best_rating) {
918 best_rating = rating;
919 pos = k.second.first_loc.position;
921 rating = entry->ubiquity / std::max(0.125, 0.25 * glm::length2(c.GetSituation().Position() - k.second.last_loc.position));
922 if (rating > best_rating) {
923 best_rating = rating;
924 pos = k.second.last_loc.position;
928 if (best_rating > 0.0) {
930 c.GetSimulation().Assets().random.SNorm(),
931 c.GetSimulation().Assets().random.SNorm(),
932 c.GetSimulation().Assets().random.SNorm());
933 pos += error * (4.0 * (1.0 - c.IntelligenceFactor()));
934 pos = glm::normalize(pos) * c.GetSituation().GetPlanet().Radius();
941 void Memory::TrackCollision(Creature &other) {
942 // TODO: find out whose fault it was
943 // TODO: source values from personality
944 Profile &p = known_creatures[&other];
946 const double annoy_fact = p.annoyance / (p.annoyance + 1.0);
947 if (c.GetSimulation().Assets().random.UNorm() > annoy_fact * 0.1 * (1.0 - c.GetStats().Damage().value)) {
948 AttackGoal *g = new AttackGoal(c, other);
949 g->SetDamageTarget(annoy_fact);
950 g->Urgency(annoy_fact);
951 c.AddGoal(std::unique_ptr<Goal>(g));
956 void Memory::Tick(double dt) {
957 Situation &s = c.GetSituation();
959 TrackStay({ &s.GetPlanet(), s.Position() }, dt);
964 void Memory::TrackStay(const Location &l, double t) {
965 const world::TileType &type = l.planet->TileTypeAt(l.position);
966 auto entry = known_types.find(type.id);
967 if (entry != known_types.end()) {
968 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
970 if (entry->second.time_spent > c.Age() * 0.25) {
971 // the place is very familiar
972 c.GetStats().Boredom().Add(-0.2);
975 c.GetStats().Boredom().Add(-0.1);
978 entry->second.last_been = c.GetSimulation().Time();
979 entry->second.last_loc = l;
980 entry->second.time_spent += t;
982 known_types.emplace(type.id, Stay{
983 c.GetSimulation().Time(),
985 c.GetSimulation().Time(),
989 // completely new place, interesting
990 // TODO: scale by personality trait
991 c.GetStats().Boredom().Add(-0.25);
996 NameGenerator::NameGenerator()
1000 NameGenerator::~NameGenerator() {
1003 std::string NameGenerator::Sequential() {
1004 std::stringstream ss;
1005 ss << "Blob " << ++counter;
1010 Situation::Situation()
1012 , state(glm::dvec3(0.0), glm::dvec3(0.0))
1016 Situation::~Situation() {
1019 bool Situation::OnPlanet() const noexcept {
1020 return type == PLANET_SURFACE;
1023 bool Situation::OnSurface() const noexcept {
1024 return type == PLANET_SURFACE;
1027 bool Situation::OnGround() const noexcept {
1028 return OnSurface() && glm::length2(state.pos) < (planet->Radius() + 0.05) * (planet->Radius() + 0.05);
1031 glm::dvec3 Situation::SurfaceNormal() const noexcept {
1032 return planet->NormalAt(state.pos);
1035 world::Tile &Situation::GetTile() const noexcept {
1036 return planet->TileAt(state.pos);
1039 const world::TileType &Situation::GetTileType() const noexcept {
1040 return planet->TileTypeAt(state.pos);
1043 void Situation::Move(const glm::dvec3 &dp) noexcept {
1045 EnforceConstraints(state);
1048 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
1050 EnforceConstraints(state);
1053 void Situation::EnforceConstraints(State &s) const noexcept {
1055 double r = GetPlanet().Radius();
1056 if (glm::length2(s.pos) < r * r) {
1057 const glm::dvec3 normal(GetPlanet().NormalAt(s.pos));
1059 s.vel -= normal * glm::dot(normal, s.vel);
1064 void Situation::SetPlanetSurface(world::Planet &p, const glm::dvec3 &pos) noexcept {
1065 type = PLANET_SURFACE;
1068 EnforceConstraints(state);
1072 Steering::Steering(const Creature &c)
1086 Steering::~Steering() {
1089 void Steering::Off() noexcept {
1096 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
1098 min_dist = min_distance;
1099 max_look = max_lookaround;
1102 void Steering::DontSeparate() noexcept {
1106 void Steering::ResumeSeparate() noexcept {
1110 void Steering::Halt() noexcept {
1116 void Steering::Pass(const glm::dvec3 &t) noexcept {
1123 void Steering::GoTo(const glm::dvec3 &t) noexcept {
1130 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
1131 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
1132 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
1133 glm::dvec3 result(0.0);
1135 // TODO: off surface situation
1136 glm::dvec3 repulse(0.0);
1137 const Situation &s = c.GetSituation();
1138 for (auto &other : s.GetPlanet().Creatures()) {
1139 if (&*other == &c) continue;
1140 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
1141 if (glm::length2(diff) > max_look * max_look) continue;
1142 if (!c.PerceptionTest(other->GetSituation().Position())) continue;
1143 double sep = glm::clamp(glm::length(diff) - other->Size() * 0.707 - c.Size() * 0.707, 0.0, min_dist);
1144 repulse += glm::normalize(diff) * (1.0 - sep / min_dist) * force;
1150 result += -5.0 * s.vel * force;
1153 glm::dvec3 diff = target - s.pos;
1154 if (!allzero(diff)) {
1155 result += TargetVelocity(s, (glm::normalize(diff) * speed), force);
1159 glm::dvec3 diff = target - s.pos;
1160 double dist = glm::length(diff);
1161 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
1162 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
1165 // remove vertical component, if any
1166 const glm::dvec3 normal(c.GetSituation().GetPlanet().NormalAt(s.pos));
1167 result -= normal * glm::dot(normal, result);
1169 if (glm::length2(result) > max_force * max_force) {
1170 result = glm::normalize(result) * max_force;
1175 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
1176 return (vel - s.vel) * acc;