1 #include "Composition.hpp"
2 #include "Creature.hpp"
5 #include "NameGenerator.hpp"
6 #include "Situation.hpp"
7 #include "Steering.hpp"
9 #include "BlobBackgroundTask.hpp"
11 #include "IdleGoal.hpp"
12 #include "../app/Assets.hpp"
13 #include "../math/const.hpp"
14 #include "../ui/string.hpp"
15 #include "../world/Body.hpp"
16 #include "../world/Planet.hpp"
17 #include "../world/Simulation.hpp"
18 #include "../world/TileType.hpp"
22 #include <glm/gtx/transform.hpp>
23 #include <glm/gtx/vector_angle.hpp>
26 #include <glm/gtx/io.hpp>
32 Composition::Composition()
37 Composition::~Composition() {
41 bool CompositionCompare(const Composition::Component &a, const Composition::Component &b) {
42 return b.value < a.value;
46 void Composition::Add(int res, double amount) {
48 for (auto c = components.begin(); c != components.end(); ++c) {
49 if (c->resource == res) {
51 if (c->value <= 0.0) {
58 if (!found && amount > 0.0) {
59 components.emplace_back(res, amount);
61 std::sort(components.begin(), components.end(), CompositionCompare);
65 bool Composition::Has(int res) const noexcept {
66 for (auto &c : components) {
67 if (c.resource == res) {
74 double Composition::Get(int res) const noexcept {
75 for (auto &c : components) {
76 if (c.resource == res) {
84 Creature::Creature(world::Simulation &sim)
91 , highlight_color(0.0, 0.0, 0.0, 1.0)
107 // all creatures avoid each other for now
108 steering.Separate(0.1, 1.5);
111 Creature::~Creature() {
114 void Creature::AddMass(int res, double amount) {
115 composition.Add(res, amount);
116 double nonsolid = 0.0;
118 for (const auto &c : composition) {
119 volume += c.value / sim.Assets().data.resources[c.resource].density;
120 if (sim.Assets().data.resources[c.resource].state != world::Resource::SOLID) {
124 Mass(composition.TotalMass());
125 Size(std::cbrt(volume));
126 highlight_color.a = nonsolid / composition.TotalMass();
129 void Creature::HighlightColor(const glm::dvec3 &c) noexcept {
130 highlight_color = glm::dvec4(c, highlight_color.a);
133 void Creature::Ingest(int res, double amount) noexcept {
134 // TODO: check foreign materials
135 if (sim.Resources()[res].state == world::Resource::SOLID) {
136 // 15% of solids stays in body
137 AddMass(res, amount * 0.15);
139 // 10% of fluids stays in body
140 AddMass(res, amount * 0.05);
142 math::GaloisLFSR &random = sim.Assets().random;
143 if (random.UNorm() < AdaptChance()) {
144 // change color to be slightly more like resource
145 glm::dvec3 color(rgb2hsl(sim.Resources()[res].base_color));
146 // solids affect base color, others highlight
147 double p = sim.Resources()[res].state == world::Resource::SOLID ? 0 : 1;
148 double q = random.UInt(3); // hue, sat, or val
149 double r = random.UInt(2); // mean or deviation
150 math::Distribution *d = nullptr;
154 d = &genome.base_hue;
157 d = &genome.base_saturation;
160 d = &genome.base_lightness;
165 d = &genome.highlight_hue;
168 d = &genome.highlight_saturation;
171 d = &genome.highlight_lightness;
176 double diff = ref - d->Mean();
180 } else if (diff > 0.5) {
183 // move ±15% of distance
184 d->Mean(std::fmod(d->Mean() + diff * random.SNorm() * 0.15, 1.0));
186 d->Mean(glm::clamp(d->Mean() + diff * random.SNorm() * 0.15, 0.0, 1.0));
189 // scale by ±15%, enforce bounds
190 d->StandardDeviation(glm::clamp(d->StandardDeviation() * (1.0 + random.SNorm() * 0.15), 0.0001, 0.5));
195 void Creature::DoWork(double amount) noexcept {
196 stats.Exhaustion().Add(amount / Stamina());
197 // burn resources proportional to composition
198 // factor = 1/total * 1/efficiency * amount * -1
199 double factor = -amount / (composition.TotalMass() * EnergyEfficiency());
200 // make a copy to total remains constant and
201 // no entries disappear during iteration
202 Composition comp(composition);
203 for (auto &cmp : comp) {
204 double value = cmp.value * factor * sim.Resources()[cmp.resource].inverse_energy;
205 AddMass(cmp.resource, value);
209 void Creature::Hurt(double amount) noexcept {
210 stats.Damage().Add(amount);
211 if (stats.Damage().Full()) {
212 std::cout << "[" << ui::TimeString(sim.Time()) << "] " << name << " ";
213 if (stats.Exhaustion().Full()) {
214 std::cout << "died of exhaustion";
215 } else if (stats.Breath().Full()) {
216 std::cout << "suffocated";
217 } else if (stats.Thirst().Full()) {
218 std::cout << "died of thirst";
219 } else if (stats.Hunger().Full()) {
220 std::cout << "starved to death";
222 std::cout << "succumed to wounds";
224 std::cout << " at an age of " << ui::TimeString(Age())
225 << " (" << ui::PercentageString(Age() / properties.Lifetime())
226 << "% of life expectancy of " << ui::TimeString(properties.Lifetime())
232 void Creature::Die() noexcept {
244 bool Creature::Dead() const noexcept {
245 return death > birth;
248 void Creature::Remove() noexcept {
252 void Creature::Removed() noexcept {
259 void Creature::AddParent(Creature &p) {
260 parents.push_back(&p);
263 double Creature::Age() const noexcept {
264 return sim.Time() - birth;
267 double Creature::AgeFactor(double peak) const noexcept {
268 // shifted inverse hermite, y = 1 - (3t² - 2t³) with t = normalized age - peak
269 // goes negative below -0.5 and starts to rise again above 1.0
270 double t = glm::clamp((Age() / properties.Lifetime()) - peak, -0.5, 1.0);
271 // guarantee at least 1%
272 return std::max(0.01, 1.0 - (3.0 * t * t) + (2.0 * t * t * t));
275 double Creature::EnergyEfficiency() const noexcept {
276 return 0.25 * AgeFactor(0.05);
279 double Creature::ExhaustionFactor() const noexcept {
280 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Exhaustion().value) * 0.5);
283 double Creature::FatigueFactor() const noexcept {
284 return 1.0 - (glm::smoothstep(0.5, 1.0, stats.Fatigue().value) * 0.5);
287 double Creature::Strength() const noexcept {
288 // TODO: replace all age factors with actual growth and decay
289 return properties.Strength() * ExhaustionFactor() * AgeFactor(0.25);
292 double Creature::Stamina() const noexcept {
293 return properties.Stamina() * ExhaustionFactor() * AgeFactor(0.25);
296 double Creature::Dexerty() const noexcept {
297 return properties.Dexerty() * ExhaustionFactor() * AgeFactor(0.25);
300 double Creature::Intelligence() const noexcept {
301 return properties.Intelligence() * FatigueFactor() * AgeFactor(0.25);
304 double Creature::Lifetime() const noexcept {
305 return properties.Lifetime();
308 double Creature::Fertility() const noexcept {
309 return properties.Fertility() * AgeFactor(0.25);
312 double Creature::Mutability() const noexcept {
313 return properties.Mutability();
316 double Creature::Adaptability() const noexcept {
317 return properties.Adaptability();
320 double Creature::OffspringMass() const noexcept {
321 return properties.OffspringMass();
324 double Creature::OffspringChance() const noexcept {
325 return AgeFactor(0.25) * properties.Fertility() * (1.0 / 3600.0);
328 double Creature::MutateChance() const noexcept {
329 return GetProperties().Mutability() * (1.0 / 3600.0);
332 double Creature::AdaptChance() const noexcept {
333 return GetProperties().Adaptability() * (1.0 / 120.0);
336 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
338 goals.emplace_back(std::move(g));
343 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
344 return b->Urgency() < a->Urgency();
349 void Creature::Tick(double dt) {
355 void Creature::TickState(double dt) {
356 steering.MaxSpeed(Dexerty());
357 steering.MaxForce(Strength());
358 Situation::State state(situation.GetState());
359 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
360 Situation::Derivative b(Step(a, dt * 0.5));
361 Situation::Derivative c(Step(b, dt * 0.5));
362 Situation::Derivative d(Step(c, dt));
363 Situation::Derivative f(
364 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
365 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
367 state.pos += f.vel * dt;
368 state.vel += f.acc * dt;
369 situation.EnforceConstraints(state);
370 if (length2(state.vel) > 0.000001) {
371 glm::dvec3 nvel(normalize(state.vel));
372 double ang = angle(nvel, state.dir);
373 double turn_rate = PI * 0.75 * dt;
374 if (ang < turn_rate) {
375 state.dir = normalize(state.vel);
376 } else if (std::abs(ang - PI) < 0.001) {
377 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
379 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
382 situation.SetState(state);
383 // work is force times distance
384 DoWork(length(f.acc) * Mass() * length(f.vel) * dt);
387 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
388 Situation::State s = situation.GetState();
389 s.pos += ds.vel * dt;
390 s.vel += ds.acc * dt;
391 glm::dvec3 force(steering.Force(s));
392 // gravity = antinormal * mass * Gm / r²
393 double elevation = s.pos[(situation.Surface() + 2) % 3];
394 glm::dvec3 normal(world::Planet::SurfaceNormal(situation.Surface()));
397 * Mass() * situation.GetPlanet().GravitationalParameter()
398 / (elevation * elevation));
399 // if net force is applied and in contact with surface
400 if (!allzero(force) && std::abs(std::abs(elevation) - situation.GetPlanet().Radius()) < 0.001) {
401 // apply friction = -|normal force| * tangential force * coefficient
402 glm::dvec3 fn(normal * dot(force, normal));
403 glm::dvec3 ft(force - fn);
405 glm::dvec3 friction(-length(fn) * ft * u);
414 void Creature::TickStats(double dt) {
415 for (auto &s : stats.stat) {
418 stats.Breath().Add(stats.Breath().gain * stats.Exhaustion().value * dt);
419 // TODO: damage values depending on properties
420 if (stats.Breath().Full()) {
421 constexpr double dps = 1.0 / 4.0;
424 if (stats.Thirst().Full()) {
425 constexpr double dps = 1.0 / 32.0;
428 if (stats.Hunger().Full()) {
429 constexpr double dps = 1.0 / 128.0;
432 if (!situation.Moving()) {
433 // double exhaustion recovery when standing still
434 stats.Exhaustion().Add(stats.Exhaustion().gain * dt);
438 void Creature::TickBrain(double dt) {
442 // do background stuff
446 for (auto &goal : goals) {
449 // if active goal can be interrupted, check priorities
450 if (goals.size() > 1 && goals[0]->Interruptible()) {
451 std::sort(goals.begin(), goals.end(), GoalCompare);
454 for (auto goal = goals.begin(); goal != goals.end();) {
455 if ((*goal)->Complete()) {
463 math::AABB Creature::CollisionBox() const noexcept {
464 return { glm::dvec3(size * -0.5), glm::dvec3(size * 0.5) };
467 glm::dmat4 Creature::CollisionTransform() const noexcept {
468 const double half_size = size * 0.5;
469 const glm::dvec3 &pos = situation.Position();
470 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
471 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
472 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
476 glm::dmat4 Creature::LocalTransform() noexcept {
477 const double half_size = size * 0.5;
478 return CollisionTransform()
479 * glm::scale(glm::dvec3(half_size, half_size, half_size));
482 void Creature::BuildVAO() {
483 vao.reset(new graphics::SimpleVAO<Attributes, unsigned short>);
485 vao->BindAttributes();
486 vao->EnableAttribute(0);
487 vao->EnableAttribute(1);
488 vao->EnableAttribute(2);
489 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
490 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
491 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
492 vao->ReserveAttributes(6 * 4, GL_STATIC_DRAW);
494 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
495 const float offset = 1.0f;
496 for (int surface = 0; surface < 6; ++surface) {
497 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
498 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
500 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
501 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
502 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
503 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
504 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
505 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
506 attrib[4 * surface + 0].texture.x = tex_u_begin;
507 attrib[4 * surface + 0].texture.y = 1.0f;
508 attrib[4 * surface + 0].texture.z = surface;
510 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
511 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
512 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
513 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
514 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
515 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
516 attrib[4 * surface + 1].texture.x = tex_u_end;
517 attrib[4 * surface + 1].texture.y = 1.0f;
518 attrib[4 * surface + 1].texture.z = surface;
520 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
521 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
522 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
523 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
524 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
525 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
526 attrib[4 * surface + 2].texture.x = tex_u_begin;
527 attrib[4 * surface + 2].texture.y = 0.0f;
528 attrib[4 * surface + 2].texture.z = surface;
530 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
531 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
532 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
533 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
534 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
535 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
536 attrib[4 * surface + 3].texture.x = tex_u_end;
537 attrib[4 * surface + 3].texture.y = 0.0f;
538 attrib[4 * surface + 3].texture.z = surface;
542 vao->ReserveElements(6 * 6, GL_STATIC_DRAW);
544 auto element = vao->MapElements(GL_WRITE_ONLY);
545 for (int surface = 0; surface < 3; ++surface) {
546 element[6 * surface + 0] = 4 * surface + 0;
547 element[6 * surface + 1] = 4 * surface + 2;
548 element[6 * surface + 2] = 4 * surface + 1;
549 element[6 * surface + 3] = 4 * surface + 1;
550 element[6 * surface + 4] = 4 * surface + 2;
551 element[6 * surface + 5] = 4 * surface + 3;
553 for (int surface = 3; surface < 6; ++surface) {
554 element[6 * surface + 0] = 4 * surface + 0;
555 element[6 * surface + 1] = 4 * surface + 1;
556 element[6 * surface + 2] = 4 * surface + 2;
557 element[6 * surface + 3] = 4 * surface + 2;
558 element[6 * surface + 4] = 4 * surface + 1;
559 element[6 * surface + 5] = 4 * surface + 3;
565 void Creature::KillVAO() {
569 void Creature::Draw(graphics::Viewport &viewport) {
572 vao->DrawTriangles(6 * 6);
576 void Spawn(Creature &c, world::Planet &p) {
578 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
579 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
581 // probe surrounding area for common resources
582 int start = p.SideLength() / 2 - 2;
584 std::map<int, double> yields;
585 for (int y = start; y < end; ++y) {
586 for (int x = start; x < end; ++x) {
587 const world::TileType &t = p.TypeAt(0, x, y);
588 for (auto yield : t.resources) {
589 yields[yield.resource] += yield.ubiquity;
595 for (auto e : yields) {
596 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
597 if (liquid < 0 || e.second > yields[liquid]) {
600 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
601 if (solid < 0 || e.second > yields[solid]) {
608 genome.properties.Strength() = { 2.0, 0.1 };
609 genome.properties.Stamina() = { 2.0, 0.1 };
610 genome.properties.Dexerty() = { 2.0, 0.1 };
611 genome.properties.Intelligence() = { 1.0, 0.1 };
612 genome.properties.Lifetime() = { 480.0, 60.0 };
613 genome.properties.Fertility() = { 0.5, 0.03 };
614 genome.properties.Mutability() = { 0.9, 0.1 };
615 genome.properties.Adaptability() = { 0.9, 0.1 };
616 genome.properties.OffspringMass() = { 0.3, 0.02 };
618 glm::dvec3 color_avg(0.0);
619 double color_divisor = 0.0;
621 if (p.HasAtmosphere()) {
622 c.AddMass(p.Atmosphere(), 0.01);
623 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
624 color_divisor += 0.1;
627 c.AddMass(liquid, 0.3);
628 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
629 color_divisor += 0.5;
632 c.AddMass(solid, 0.1);
633 color_avg += c.GetSimulation().Resources()[solid].base_color;
634 color_divisor += 1.0;
637 if (color_divisor > 0.001) {
638 color_avg /= color_divisor;
640 glm::dvec3 hsl = rgb2hsl(color_avg);
641 genome.base_hue = { hsl.x, 0.01 };
642 genome.base_saturation = { hsl.y, 0.01 };
643 genome.base_lightness = { hsl.z, 0.01 };
644 // use opposite color as start highlight
645 genome.highlight_hue = { std::fmod(hsl.x + 0.5, 1.0), 0.01 };
646 genome.highlight_saturation = { 1.0 - hsl.y, 0.01 };
647 genome.highlight_lightness = { 1.0 - hsl.z, 0.01 };
652 void Genome::Configure(Creature &c) const {
653 c.GetGenome() = *this;
655 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
657 c.GetProperties() = Instantiate(properties, random);
659 // TODO: derive stats from properties
660 c.GetStats().Damage().gain = (-1.0 / 100.0);
661 c.GetStats().Breath().gain = (1.0 / 5.0);
662 c.GetStats().Thirst().gain = (1.0 / 60.0);
663 c.GetStats().Hunger().gain = (1.0 / 200.0);
664 c.GetStats().Exhaustion().gain = (-1.0 / 100.0);
665 c.GetStats().Fatigue().gain = (-1.0 / 100.0);
666 c.GetStats().Boredom().gain = (1.0 / 300.0);
668 glm::dvec3 base_color(
669 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
670 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
671 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
673 glm::dvec3 highlight_color(
674 std::fmod(highlight_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
675 glm::clamp(highlight_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
676 glm::clamp(highlight_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
678 c.BaseColor(hsl2rgb(base_color));
679 c.HighlightColor(hsl2rgb(highlight_color));
680 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
681 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
685 void Split(Creature &c) {
686 Creature *a = new Creature(c.GetSimulation());
687 const Situation &s = c.GetSituation();
689 a->Name(c.GetSimulation().Assets().name.Sequential());
690 c.GetGenome().Configure(*a);
691 for (const auto &cmp : c.GetComposition()) {
692 a->AddMass(cmp.resource, cmp.value * 0.5);
694 s.GetPlanet().AddCreature(a);
695 // TODO: duplicate situation somehow
696 a->GetSituation().SetPlanetSurface(
697 s.GetPlanet(), s.Surface(),
698 s.Position() + glm::dvec3(0.0, 0.55 * a->Size(), 0.0));
700 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
701 << a->Name() << " was born" << std::endl;
703 Creature *b = new Creature(c.GetSimulation());
705 b->Name(c.GetSimulation().Assets().name.Sequential());
706 c.GetGenome().Configure(*b);
707 for (const auto &cmp : c.GetComposition()) {
708 b->AddMass(cmp.resource, cmp.value * 0.5);
710 s.GetPlanet().AddCreature(b);
711 b->GetSituation().SetPlanetSurface(
712 s.GetPlanet(), s.Surface(),
713 s.Position() - glm::dvec3(0.0, 0.55 * b->Size(), 0.0));
715 std::cout << "[" << ui::TimeString(c.GetSimulation().Time()) << "] "
716 << b->Name() << " was born" << std::endl;
722 Memory::Memory(Creature &c)
729 void Memory::Erase() {
733 void Memory::Tick(double dt) {
734 Situation &s = c.GetSituation();
736 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
740 void Memory::TrackStay(const Location &l, double t) {
741 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
742 auto entry = known_types.find(type.id);
743 if (entry != known_types.end()) {
744 if (c.GetSimulation().Time() - entry->second.last_been > c.GetProperties().Lifetime() * 0.1) {
746 if (entry->second.time_spent > c.Age() * 0.25) {
747 // the place is very familiar
748 c.GetStats().Boredom().Add(-0.2);
751 c.GetStats().Boredom().Add(-0.1);
754 entry->second.last_been = c.GetSimulation().Time();
755 entry->second.last_loc = l;
756 entry->second.time_spent += t;
758 known_types.emplace(type.id, Stay{
759 c.GetSimulation().Time(),
761 c.GetSimulation().Time(),
765 // completely new place, interesting
766 // TODO: scale by personality trait
767 c.GetStats().Boredom().Add(-0.25);
772 NameGenerator::NameGenerator()
776 NameGenerator::~NameGenerator() {
779 std::string NameGenerator::Sequential() {
780 std::stringstream ss;
781 ss << "Blob " << ++counter;
786 Situation::Situation()
788 , state(glm::dvec3(0.0), glm::dvec3(0.0))
793 Situation::~Situation() {
796 bool Situation::OnPlanet() const noexcept {
797 return type == PLANET_SURFACE;
800 bool Situation::OnSurface() const noexcept {
801 return type == PLANET_SURFACE;
804 bool Situation::OnTile() const noexcept {
805 if (type != PLANET_SURFACE) return false;
806 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
807 return t.x >= 0 && t.x < planet->SideLength()
808 && t.y >= 0 && t.y < planet->SideLength();
811 glm::ivec2 Situation::SurfacePosition() const noexcept {
812 return planet->SurfacePosition(surface, state.pos);
815 world::Tile &Situation::GetTile() const noexcept {
816 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
817 return planet->TileAt(surface, t.x, t.y);
820 const world::TileType &Situation::GetTileType() const noexcept {
821 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
822 return planet->TypeAt(surface, t.x, t.y);
825 void Situation::Move(const glm::dvec3 &dp) noexcept {
827 EnforceConstraints(state);
830 void Situation::Accelerate(const glm::dvec3 &dv) noexcept {
832 EnforceConstraints(state);
835 void Situation::EnforceConstraints(State &s) noexcept {
838 if (s.pos[(Surface() + 2) % 3] < GetPlanet().Radius()) {
839 s.pos[(Surface() + 2) % 3] = GetPlanet().Radius();
840 s.vel[(Surface() + 2) % 3] = std::max(0.0, s.vel[(Surface() + 2) % 3]);
843 if (s.pos[(Surface() + 2) % 3] > -GetPlanet().Radius()) {
844 s.pos[(Surface() + 2) % 3] = -GetPlanet().Radius();
845 s.vel[(Surface() + 2) % 3] = std::min(0.0, s.vel[(Surface() + 2) % 3]);
851 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
852 type = PLANET_SURFACE;
856 EnforceConstraints(state);
860 Steering::Steering(const Creature &c)
874 Steering::~Steering() {
877 void Steering::Off() noexcept {
884 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
886 min_dist = min_distance;
887 max_look = max_lookaround;
890 void Steering::DontSeparate() noexcept {
894 void Steering::ResumeSeparate() noexcept {
898 void Steering::Halt() noexcept {
904 void Steering::Pass(const glm::dvec3 &t) noexcept {
911 void Steering::GoTo(const glm::dvec3 &t) noexcept {
918 glm::dvec3 Steering::Force(const Situation::State &s) const noexcept {
919 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
920 double force = max_speed * glm::clamp(max_force * haste * haste, 0.5, 1.0);
921 glm::dvec3 result(0.0);
923 // TODO: off surface situation
924 glm::dvec3 repulse(0.0);
925 const Situation &s = c.GetSituation();
926 for (auto &other : s.GetPlanet().Creatures()) {
927 if (&*other == &c) continue;
928 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
929 if (length2(diff) > max_look * max_look) continue;
930 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
931 if (sep < min_dist) {
932 repulse += normalize(diff) * (1.0 - sep / min_dist);
938 // break twice as hard
939 result += -2.0 * s.vel * force;
942 glm::dvec3 diff = target - s.pos;
943 if (!allzero(diff)) {
944 result += TargetVelocity(s, (normalize(diff) * speed), force);
948 glm::dvec3 diff = target - s.pos;
949 double dist = length(diff);
950 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
951 result += TargetVelocity(s, diff * std::min(dist * force, speed) / dist, force);
954 if (length2(result) > max_force * max_force) {
955 result = normalize(result) * max_force;
960 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
961 return (vel - s.vel) * acc;