1 #include "Creature.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
8 #include "BlobBackgroundTask.hpp"
10 #include "IdleGoal.hpp"
11 #include "InhaleNeed.hpp"
12 #include "IngestNeed.hpp"
14 #include "../app/Assets.hpp"
15 #include "../math/const.hpp"
16 #include "../world/Body.hpp"
17 #include "../world/Planet.hpp"
18 #include "../world/Simulation.hpp"
19 #include "../world/TileType.hpp"
23 #include <glm/gtx/transform.hpp>
24 #include <glm/gtx/vector_angle.hpp>
27 #include <glm/gtx/io.hpp>
33 Creature::Creature(world::Simulation &sim)
40 , highlight_color(0.0)
55 // all creatures avoid each other for now
56 steering.Separate(0.1, 1.5);
59 Creature::~Creature() {
62 glm::dvec4 Creature::HighlightColor() const noexcept {
63 return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
66 void Creature::Ingest(int res, double amount) noexcept {
67 const Genome::Composition *cmp = nullptr;
68 for (const auto &c : genome.composition) {
69 if (c.resource == res) {
75 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
76 Mass(std::min(max_mass, mass + amount));
78 // foreign material. poisonous?
82 void Creature::Hurt(double dt) noexcept {
83 health = std::max(0.0, health - dt);
85 std::cout << "[" << int(sim.Time()) << "s] "
86 << name << " died" << std::endl;
91 void Creature::Die() noexcept {
101 double Creature::Size() const noexcept {
105 double Creature::Age() const noexcept {
106 return sim.Time() - birth;
109 std::string Creature::AgeName() const {
128 double Creature::AgeLerp(double from, double to) const noexcept {
129 return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
132 double Creature::Fertility() const noexcept {
133 return AgeLerp(CurProps().fertility, NextProps().fertility) * (1.0 / 3600.0);
136 double Creature::Mutability() const noexcept {
137 return GetProperties().mutability * (1.0 / 3600.0);
140 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
142 goals.emplace_back(std::move(g));
147 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
148 return b->Urgency() < a->Urgency();
153 void Creature::Tick(double dt) {
154 if (cur_prop < 5 && Age() > NextProps().age) {
157 std::cout << "[" << int(sim.Time()) << "s] "
158 << name << " died of old age" << std::endl;
161 std::cout << "[" << int(sim.Time()) << "s] "
162 << name << " grew up to " << AgeName() << std::endl;
167 Situation::State state(situation.GetState());
168 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
169 Situation::Derivative b(Step(a, dt * 0.5));
170 Situation::Derivative c(Step(b, dt * 0.5));
171 Situation::Derivative d(Step(c, dt));
172 Situation::Derivative f(
173 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
174 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
176 state.pos += f.vel * dt;
177 state.vel += f.acc * dt;
178 if (length2(state.vel) > 0.000001) {
179 glm::dvec3 nvel(normalize(state.vel));
180 double ang = angle(nvel, state.dir);
181 double turn_rate = PI * dt;
182 if (ang < turn_rate) {
183 state.dir = normalize(state.vel);
184 } else if (std::abs(ang - PI) < 0.001) {
185 state.dir = rotate(state.dir, turn_rate, world::Planet::SurfaceNormal(situation.Surface()));
187 state.dir = rotate(state.dir, turn_rate, normalize(cross(state.dir, nvel)));
191 situation.SetState(state);
197 for (auto &need : needs) {
200 for (auto &goal : goals) {
203 // do background stuff
204 for (auto &need : needs) {
205 need->ApplyEffect(*this, dt);
210 // if active goal can be interrupted, check priorities
211 if (goals.size() > 1 && goals[0]->Interruptible()) {
212 std::sort(goals.begin(), goals.end(), GoalCompare);
215 for (auto goal = goals.begin(); goal != goals.end();) {
216 if ((*goal)->Complete()) {
224 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
225 Situation::State s = situation.GetState();
226 s.pos += ds.vel * dt;
227 s.vel += ds.acc * dt;
230 steering.Acceleration(s)
234 glm::dmat4 Creature::LocalTransform() noexcept {
235 // TODO: surface transform
236 const double half_size = size * 0.5;
237 const glm::dvec3 &pos = situation.Position();
238 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
239 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
240 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
242 * glm::scale(glm::dvec3(half_size, half_size, half_size));
245 void Creature::BuildVAO() {
247 vao.BindAttributes();
248 vao.EnableAttribute(0);
249 vao.EnableAttribute(1);
250 vao.EnableAttribute(2);
251 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
252 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
253 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
254 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
256 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
257 const float offset = 1.0f;
258 for (int surface = 0; surface < 6; ++surface) {
259 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
260 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
262 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
263 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
264 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
265 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
266 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
267 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
268 attrib[4 * surface + 0].texture.x = tex_u_begin;
269 attrib[4 * surface + 0].texture.y = 1.0f;
270 attrib[4 * surface + 0].texture.z = surface;
272 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
273 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
274 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
275 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
276 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
277 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
278 attrib[4 * surface + 1].texture.x = tex_u_end;
279 attrib[4 * surface + 1].texture.y = 1.0f;
280 attrib[4 * surface + 1].texture.z = surface;
282 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
283 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
284 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
285 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
286 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
287 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
288 attrib[4 * surface + 2].texture.x = tex_u_begin;
289 attrib[4 * surface + 2].texture.y = 0.0f;
290 attrib[4 * surface + 2].texture.z = surface;
292 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
293 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
294 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
295 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
296 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
297 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
298 attrib[4 * surface + 3].texture.x = tex_u_end;
299 attrib[4 * surface + 3].texture.y = 0.0f;
300 attrib[4 * surface + 3].texture.z = surface;
304 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
306 auto element = vao.MapElements(GL_WRITE_ONLY);
307 for (int surface = 0; surface < 3; ++surface) {
308 element[6 * surface + 0] = 4 * surface + 0;
309 element[6 * surface + 1] = 4 * surface + 2;
310 element[6 * surface + 2] = 4 * surface + 1;
311 element[6 * surface + 3] = 4 * surface + 1;
312 element[6 * surface + 4] = 4 * surface + 2;
313 element[6 * surface + 5] = 4 * surface + 3;
315 for (int surface = 3; surface < 6; ++surface) {
316 element[6 * surface + 0] = 4 * surface + 0;
317 element[6 * surface + 1] = 4 * surface + 1;
318 element[6 * surface + 2] = 4 * surface + 2;
319 element[6 * surface + 3] = 4 * surface + 2;
320 element[6 * surface + 4] = 4 * surface + 1;
321 element[6 * surface + 5] = 4 * surface + 3;
327 void Creature::Draw(graphics::Viewport &viewport) {
329 vao.DrawTriangles(6 * 6);
333 void Spawn(Creature &c, world::Planet &p) {
335 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
336 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
338 // probe surrounding area for common resources
339 int start = p.SideLength() / 2 - 2;
341 std::map<int, double> yields;
342 for (int y = start; y < end; ++y) {
343 for (int x = start; x < end; ++x) {
344 const world::TileType &t = p.TypeAt(0, x, y);
345 for (auto yield : t.resources) {
346 yields[yield.resource] += yield.ubiquity;
352 for (auto e : yields) {
353 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
354 if (liquid < 0 || e.second > yields[liquid]) {
357 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
358 if (solid < 0 || e.second > yields[solid]) {
366 genome.properties.Birth().age = { 0.0, 0.0 };
367 genome.properties.Birth().mass = { 0.5, 0.05 };
368 genome.properties.Birth().fertility = { 0.0, 0.0 };
369 genome.properties.Birth().highlight = { 0.0, 0.0 };
371 genome.properties.Child().age = { 30.0, 1.0 };
372 genome.properties.Child().mass = { 0.7, 0.05 };
373 genome.properties.Child().fertility = { 0.0, 0.0 };
374 genome.properties.Child().highlight = { 0.2, 0.05 };
376 genome.properties.Youth().age = { 60.0, 5.0 };
377 genome.properties.Youth().mass = { 0.9, 0.1 };
378 genome.properties.Youth().fertility = { 0.5, 0.03 };
379 genome.properties.Youth().highlight = { 0.9, 0.1 };
381 genome.properties.Adult().age = { 120.0, 10.0 };
382 genome.properties.Adult().mass = { 1.3, 0.1 };
383 genome.properties.Adult().fertility = { 0.4, 0.01 };
384 genome.properties.Adult().highlight = { 0.7, 0.1 };
386 genome.properties.Elder().age = { 360.0, 30.0 };
387 genome.properties.Elder().mass = { 1.0, 0.05 };
388 genome.properties.Elder().fertility = { 0.1, 0.01 };
389 genome.properties.Elder().highlight = { 0.6, 0.1 };
391 genome.properties.Death().age = { 480.0, 60.0 };
392 genome.properties.Death().mass = { 0.9, 0.05 };
393 genome.properties.Death().fertility = { 0.0, 0.0 };
394 genome.properties.Death().highlight = { 0.5, 0.1 };
396 genome.properties.strength = { 1.0, 0.1 };
397 genome.properties.stamina = { 1.0, 0.1 };
398 genome.properties.dexerty = { 1.0, 0.1 };
399 genome.properties.intelligence = { 1.0, 0.1 };
400 genome.properties.mutability = { 1.0, 0.1 };
402 glm::dvec3 color_avg(0.0);
403 double color_divisor = 0.0;
405 if (p.HasAtmosphere()) {
406 genome.composition.push_back({
407 p.Atmosphere(), // resource
408 { 0.01, 0.00001 }, // mass
409 { 0.5, 0.001 }, // intake
410 { 0.1, 0.0005 }, // penalty
411 { 0.0, 0.0 }, // growth
413 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
414 color_divisor += 0.1;
417 genome.composition.push_back({
419 { 0.6, 0.01 }, // mass
420 { 0.2, 0.001 }, // intake
421 { 0.01, 0.002 }, // penalty
422 { 0.1, 0.0 }, // growth
424 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
425 color_divisor += 0.5;
428 genome.composition.push_back({
430 { 0.4, 0.01 }, // mass
431 { 0.4, 0.001 }, // intake
432 { 0.001, 0.0001 }, // penalty
433 { 10.0, 0.002 }, // growth
435 color_avg += c.GetSimulation().Resources()[solid].base_color;
436 color_divisor += 1.0;
439 if (color_divisor > 0.001) {
440 color_avg /= color_divisor;
442 glm::dvec3 hsl = rgb2hsl(color_avg);
443 genome.base_hue = { hsl.x, 0.01 };
444 genome.base_saturation = { hsl.y, 0.01 };
445 genome.base_lightness = { hsl.z, 0.01 };
450 void Genome::Configure(Creature &c) const {
451 c.GetGenome() = *this;
453 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
455 c.GetProperties() = Instantiate(properties, random);
459 for (const auto &comp : composition) {
460 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
461 double comp_mass = comp.mass.FakeNormal(random.SNorm());
462 double intake = comp.intake.FakeNormal(random.SNorm());
463 double penalty = comp.penalty.FakeNormal(random.SNorm());
466 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
468 std::unique_ptr<Need> need;
469 if (resource.state == world::Resource::SOLID) {
470 intake *= std::atan(c.GetProperties().strength);
471 need.reset(new IngestNeed(comp.resource, intake, penalty));
472 need->gain = intake * 0.05;
473 } else if (resource.state == world::Resource::LIQUID) {
474 intake *= std::atan(c.GetProperties().stamina);
475 need.reset(new IngestNeed(comp.resource, intake, penalty));
476 need->gain = intake * 0.1;
478 need.reset(new InhaleNeed(comp.resource, intake, penalty));
479 need->gain = intake * 0.5;
481 need->name = c.GetSimulation().Resources()[comp.resource].label;
482 need->growth = comp.growth.FakeNormal(random.SNorm());
484 need->inconvenient = 0.5;
485 need->critical = 0.95;
486 c.AddNeed(std::move(need));
489 glm::dvec3 base_color(
490 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
491 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
492 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
494 glm::dvec3 highlight_color(
495 std::fmod(base_color.x + 0.5, 1.0),
499 c.BaseColor(hsl2rgb(base_color));
500 c.HighlightColor(hsl2rgb(highlight_color));
502 c.Mass(c.GetProperties().props[0].mass);
503 c.Density(mass / volume);
504 c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
505 c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
506 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
507 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
511 void Split(Creature &c) {
512 Creature *a = new Creature(c.GetSimulation());
513 const Situation &s = c.GetSituation();
514 a->Name(c.GetSimulation().Assets().name.Sequential());
516 c.GetGenome().Configure(*a);
517 s.GetPlanet().AddCreature(a);
518 // TODO: duplicate situation somehow
519 a->GetSituation().SetPlanetSurface(
520 s.GetPlanet(), s.Surface(),
521 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
523 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
524 << a->Name() << " was born" << std::endl;
526 Creature *b = new Creature(c.GetSimulation());
527 b->Name(c.GetSimulation().Assets().name.Sequential());
528 c.GetGenome().Configure(*b);
529 s.GetPlanet().AddCreature(b);
530 b->GetSituation().SetPlanetSurface(
531 s.GetPlanet(), s.Surface(),
532 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
534 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
535 << b->Name() << " was born" << std::endl;
541 Memory::Memory(Creature &c)
548 void Memory::Tick(double dt) {
549 Situation &s = c.GetSituation();
551 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
555 void Memory::TrackStay(const Location &l, double t) {
556 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
557 auto entry = known_types.find(type.id);
558 if (entry != known_types.end()) {
559 entry->second.last_been = c.GetSimulation().Time();
560 entry->second.last_loc = l;
561 entry->second.time_spent += t;
563 known_types.emplace(type.id, Stay{
564 c.GetSimulation().Time(),
566 c.GetSimulation().Time(),
574 NameGenerator::NameGenerator()
578 NameGenerator::~NameGenerator() {
581 std::string NameGenerator::Sequential() {
582 std::stringstream ss;
583 ss << "Blob " << ++counter;
588 Situation::Situation()
590 , state(glm::dvec3(0.0), glm::dvec3(0.0))
595 Situation::~Situation() {
598 bool Situation::OnPlanet() const noexcept {
599 return type == PLANET_SURFACE;
602 bool Situation::OnSurface() const noexcept {
603 return type == PLANET_SURFACE;
606 bool Situation::OnTile() const noexcept {
607 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
608 return type == PLANET_SURFACE
609 && t.x >= 0 && t.x < planet->SideLength()
610 && t.y >= 0 && t.y < planet->SideLength();
613 glm::ivec2 Situation::SurfacePosition() const noexcept {
614 return planet->SurfacePosition(surface, state.pos);
617 world::Tile &Situation::GetTile() const noexcept {
618 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
619 return planet->TileAt(surface, t.x, t.y);
622 const world::TileType &Situation::GetTileType() const noexcept {
623 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
624 return planet->TypeAt(surface, t.x, t.y);
627 void Situation::Move(const glm::dvec3 &dp) noexcept {
630 // enforce ground constraint
632 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
634 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
639 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
640 type = PLANET_SURFACE;
647 Steering::Steering(const Creature &c)
661 Steering::~Steering() {
664 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
666 min_dist = min_distance;
667 max_look = max_lookaround;
670 void Steering::DontSeparate() noexcept {
674 void Steering::Halt() noexcept {
680 void Steering::Pass(const glm::dvec3 &t) noexcept {
687 void Steering::GoTo(const glm::dvec3 &t) noexcept {
694 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
695 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
696 double accel = max_speed * glm::clamp(max_accel * haste * haste, 0.5, 1.0);
697 glm::dvec3 result(0.0);
699 // TODO: off surface situation
700 glm::dvec3 repulse(0.0);
701 const Situation &s = c.GetSituation();
702 for (auto &other : s.GetPlanet().Creatures()) {
703 if (&*other == &c) continue;
704 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
705 if (length2(diff) > max_look * max_look) continue;
706 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
707 if (sep < min_dist) {
708 repulse += normalize(diff) * (1.0 - sep / min_dist);
711 SumForce(result, repulse, accel);
714 SumForce(result, s.vel * -accel, accel);
717 glm::dvec3 diff = target - s.pos;
718 if (!allzero(diff)) {
719 SumForce(result, TargetVelocity(s, (normalize(diff) * speed), accel), accel);
723 glm::dvec3 diff = target - s.pos;
724 double dist = length(diff);
725 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
726 SumForce(result, TargetVelocity(s, diff * std::min(dist * accel, speed) / dist, accel), accel);
732 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
733 if (allzero(in) || anynan(in)) {
736 double cur = allzero(out) ? 0.0 : length(out);
737 double rem = max - cur;
741 double add = length(in);
743 // this method is off if in and out are in different
744 // directions, but gives okayish results
745 out += in * (1.0 / add);
753 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
754 return (vel - s.vel) * acc;