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 const double half_size = size * 0.5;
236 const glm::dvec3 &pos = situation.Position();
237 const glm::dmat3 srf(world::Planet::SurfaceOrientation(situation.Surface()));
238 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
239 * glm::rotate(glm::orientedAngle(-srf[2], situation.Heading(), srf[1]), srf[1])
241 * glm::scale(glm::dvec3(half_size, half_size, half_size));
244 void Creature::BuildVAO() {
246 vao.BindAttributes();
247 vao.EnableAttribute(0);
248 vao.EnableAttribute(1);
249 vao.EnableAttribute(2);
250 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
251 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
252 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
253 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
255 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
256 const float offset = 1.0f;
257 for (int surface = 0; surface < 6; ++surface) {
258 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
259 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
261 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
262 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
263 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
264 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
265 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
266 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
267 attrib[4 * surface + 0].texture.x = tex_u_begin;
268 attrib[4 * surface + 0].texture.y = 1.0f;
269 attrib[4 * surface + 0].texture.z = surface;
271 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
272 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
273 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
274 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
275 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
276 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
277 attrib[4 * surface + 1].texture.x = tex_u_end;
278 attrib[4 * surface + 1].texture.y = 1.0f;
279 attrib[4 * surface + 1].texture.z = surface;
281 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
282 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
283 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
284 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
285 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
286 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
287 attrib[4 * surface + 2].texture.x = tex_u_begin;
288 attrib[4 * surface + 2].texture.y = 0.0f;
289 attrib[4 * surface + 2].texture.z = surface;
291 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
292 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
293 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
294 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
295 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
296 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
297 attrib[4 * surface + 3].texture.x = tex_u_end;
298 attrib[4 * surface + 3].texture.y = 0.0f;
299 attrib[4 * surface + 3].texture.z = surface;
303 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
305 auto element = vao.MapElements(GL_WRITE_ONLY);
306 for (int surface = 0; surface < 3; ++surface) {
307 element[6 * surface + 0] = 4 * surface + 0;
308 element[6 * surface + 1] = 4 * surface + 2;
309 element[6 * surface + 2] = 4 * surface + 1;
310 element[6 * surface + 3] = 4 * surface + 1;
311 element[6 * surface + 4] = 4 * surface + 2;
312 element[6 * surface + 5] = 4 * surface + 3;
314 for (int surface = 3; surface < 6; ++surface) {
315 element[6 * surface + 0] = 4 * surface + 0;
316 element[6 * surface + 1] = 4 * surface + 1;
317 element[6 * surface + 2] = 4 * surface + 2;
318 element[6 * surface + 3] = 4 * surface + 2;
319 element[6 * surface + 4] = 4 * surface + 1;
320 element[6 * surface + 5] = 4 * surface + 3;
326 void Creature::Draw(graphics::Viewport &viewport) {
328 vao.DrawTriangles(6 * 6);
332 void Spawn(Creature &c, world::Planet &p) {
334 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
335 c.GetSituation().Heading(-world::Planet::SurfaceOrientation(0)[2]);
337 // probe surrounding area for common resources
338 int start = p.SideLength() / 2 - 2;
340 std::map<int, double> yields;
341 for (int y = start; y < end; ++y) {
342 for (int x = start; x < end; ++x) {
343 const world::TileType &t = p.TypeAt(0, x, y);
344 for (auto yield : t.resources) {
345 yields[yield.resource] += yield.ubiquity;
351 for (auto e : yields) {
352 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
353 if (liquid < 0 || e.second > yields[liquid]) {
356 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
357 if (solid < 0 || e.second > yields[solid]) {
365 genome.properties.Birth().age = { 0.0, 0.0 };
366 genome.properties.Birth().mass = { 0.5, 0.05 };
367 genome.properties.Birth().fertility = { 0.0, 0.0 };
368 genome.properties.Birth().highlight = { 0.0, 0.0 };
370 genome.properties.Child().age = { 30.0, 1.0 };
371 genome.properties.Child().mass = { 0.7, 0.05 };
372 genome.properties.Child().fertility = { 0.0, 0.0 };
373 genome.properties.Child().highlight = { 0.2, 0.05 };
375 genome.properties.Youth().age = { 60.0, 5.0 };
376 genome.properties.Youth().mass = { 0.9, 0.1 };
377 genome.properties.Youth().fertility = { 0.5, 0.03 };
378 genome.properties.Youth().highlight = { 0.9, 0.1 };
380 genome.properties.Adult().age = { 120.0, 10.0 };
381 genome.properties.Adult().mass = { 1.3, 0.1 };
382 genome.properties.Adult().fertility = { 0.4, 0.01 };
383 genome.properties.Adult().highlight = { 0.7, 0.1 };
385 genome.properties.Elder().age = { 360.0, 30.0 };
386 genome.properties.Elder().mass = { 1.0, 0.05 };
387 genome.properties.Elder().fertility = { 0.1, 0.01 };
388 genome.properties.Elder().highlight = { 0.6, 0.1 };
390 genome.properties.Death().age = { 480.0, 60.0 };
391 genome.properties.Death().mass = { 0.9, 0.05 };
392 genome.properties.Death().fertility = { 0.0, 0.0 };
393 genome.properties.Death().highlight = { 0.5, 0.1 };
395 genome.properties.strength = { 1.0, 0.1 };
396 genome.properties.stamina = { 1.0, 0.1 };
397 genome.properties.dexerty = { 1.0, 0.1 };
398 genome.properties.intelligence = { 1.0, 0.1 };
399 genome.properties.mutability = { 1.0, 0.1 };
401 glm::dvec3 color_avg(0.0);
402 double color_divisor = 0.0;
404 if (p.HasAtmosphere()) {
405 genome.composition.push_back({
406 p.Atmosphere(), // resource
407 { 0.01, 0.00001 }, // mass
408 { 0.5, 0.001 }, // intake
409 { 0.1, 0.0005 }, // penalty
410 { 0.0, 0.0 }, // growth
412 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
413 color_divisor += 0.1;
416 genome.composition.push_back({
418 { 0.6, 0.01 }, // mass
419 { 0.2, 0.001 }, // intake
420 { 0.01, 0.002 }, // penalty
421 { 0.1, 0.0 }, // growth
423 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
424 color_divisor += 0.5;
427 genome.composition.push_back({
429 { 0.4, 0.01 }, // mass
430 { 0.4, 0.001 }, // intake
431 { 0.001, 0.0001 }, // penalty
432 { 10.0, 0.002 }, // growth
434 color_avg += c.GetSimulation().Resources()[solid].base_color;
435 color_divisor += 1.0;
438 if (color_divisor > 0.001) {
439 color_avg /= color_divisor;
441 glm::dvec3 hsl = rgb2hsl(color_avg);
442 genome.base_hue = { hsl.x, 0.01 };
443 genome.base_saturation = { hsl.y, 0.01 };
444 genome.base_lightness = { hsl.z, 0.01 };
449 void Genome::Configure(Creature &c) const {
450 c.GetGenome() = *this;
452 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
454 c.GetProperties() = Instantiate(properties, random);
458 for (const auto &comp : composition) {
459 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
460 double comp_mass = comp.mass.FakeNormal(random.SNorm());
461 double intake = comp.intake.FakeNormal(random.SNorm());
462 double penalty = comp.penalty.FakeNormal(random.SNorm());
465 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
467 std::unique_ptr<Need> need;
468 if (resource.state == world::Resource::SOLID) {
469 intake *= std::atan(c.GetProperties().strength);
470 need.reset(new IngestNeed(comp.resource, intake, penalty));
471 need->gain = intake * 0.05;
472 } else if (resource.state == world::Resource::LIQUID) {
473 intake *= std::atan(c.GetProperties().stamina);
474 need.reset(new IngestNeed(comp.resource, intake, penalty));
475 need->gain = intake * 0.1;
477 need.reset(new InhaleNeed(comp.resource, intake, penalty));
478 need->gain = intake * 0.5;
480 need->name = c.GetSimulation().Resources()[comp.resource].label;
481 need->growth = comp.growth.FakeNormal(random.SNorm());
483 need->inconvenient = 0.5;
484 need->critical = 0.95;
485 c.AddNeed(std::move(need));
488 glm::dvec3 base_color(
489 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
490 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
491 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
493 glm::dvec3 highlight_color(
494 std::fmod(base_color.x + 0.5, 1.0),
498 c.BaseColor(hsl2rgb(base_color));
499 c.HighlightColor(hsl2rgb(highlight_color));
501 c.Mass(c.GetProperties().props[0].mass);
502 c.Density(mass / volume);
503 c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
504 c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
505 c.SetBackgroundTask(std::unique_ptr<Goal>(new BlobBackgroundTask(c)));
506 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
510 void Split(Creature &c) {
511 Creature *a = new Creature(c.GetSimulation());
512 const Situation &s = c.GetSituation();
513 a->Name(c.GetSimulation().Assets().name.Sequential());
514 c.GetGenome().Configure(*a);
515 s.GetPlanet().AddCreature(a);
516 // TODO: duplicate situation somehow
517 a->GetSituation().SetPlanetSurface(
518 s.GetPlanet(), s.Surface(),
519 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
521 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
522 << a->Name() << " was born" << std::endl;
524 Creature *b = new Creature(c.GetSimulation());
525 b->Name(c.GetSimulation().Assets().name.Sequential());
526 c.GetGenome().Configure(*b);
527 s.GetPlanet().AddCreature(b);
528 b->GetSituation().SetPlanetSurface(
529 s.GetPlanet(), s.Surface(),
530 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
532 std::cout << "[" << int(c.GetSimulation().Time()) << "s] "
533 << b->Name() << " was born" << std::endl;
539 Memory::Memory(Creature &c)
546 void Memory::Tick(double dt) {
547 Situation &s = c.GetSituation();
549 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
553 void Memory::TrackStay(const Location &l, double t) {
554 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
555 auto entry = known_types.find(type.id);
556 if (entry != known_types.end()) {
557 entry->second.last_been = c.GetSimulation().Time();
558 entry->second.last_loc = l;
559 entry->second.time_spent += t;
561 known_types.emplace(type.id, Stay{
562 c.GetSimulation().Time(),
564 c.GetSimulation().Time(),
572 NameGenerator::NameGenerator()
576 NameGenerator::~NameGenerator() {
579 std::string NameGenerator::Sequential() {
580 std::stringstream ss;
581 ss << "Blob " << ++counter;
586 Situation::Situation()
588 , state(glm::dvec3(0.0), glm::dvec3(0.0))
593 Situation::~Situation() {
596 bool Situation::OnPlanet() const noexcept {
597 return type == PLANET_SURFACE;
600 bool Situation::OnSurface() const noexcept {
601 return type == PLANET_SURFACE;
604 bool Situation::OnTile() const noexcept {
605 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
606 return type == PLANET_SURFACE
607 && t.x >= 0 && t.x < planet->SideLength()
608 && t.y >= 0 && t.y < planet->SideLength();
611 glm::ivec2 Situation::SurfacePosition() const noexcept {
612 return planet->SurfacePosition(surface, state.pos);
615 world::Tile &Situation::GetTile() const noexcept {
616 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
617 return planet->TileAt(surface, t.x, t.y);
620 const world::TileType &Situation::GetTileType() const noexcept {
621 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
622 return planet->TypeAt(surface, t.x, t.y);
625 void Situation::Move(const glm::dvec3 &dp) noexcept {
628 // enforce ground constraint
630 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
632 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
637 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
638 type = PLANET_SURFACE;
645 Steering::Steering(const Creature &c)
659 Steering::~Steering() {
662 void Steering::Separate(double min_distance, double max_lookaround) noexcept {
664 min_dist = min_distance;
665 max_look = max_lookaround;
668 void Steering::DontSeparate() noexcept {
672 void Steering::Halt() noexcept {
678 void Steering::Pass(const glm::dvec3 &t) noexcept {
685 void Steering::GoTo(const glm::dvec3 &t) noexcept {
692 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
693 double speed = max_speed * glm::clamp(max_speed * haste * haste, 0.25, 1.0);
694 double accel = max_speed * glm::clamp(max_accel * haste * haste, 0.5, 1.0);
695 glm::dvec3 result(0.0);
697 // TODO: off surface situation
698 glm::dvec3 repulse(0.0);
699 const Situation &s = c.GetSituation();
700 for (auto &other : s.GetPlanet().Creatures()) {
701 if (&*other == &c) continue;
702 glm::dvec3 diff = s.Position() - other->GetSituation().Position();
703 if (length2(diff) > max_look * max_look) continue;
704 double sep = length(diff) - other->Size() * 0.707 - c.Size() * 0.707;
705 if (sep < min_dist) {
706 repulse += normalize(diff) * (1.0 - sep / min_dist);
709 SumForce(result, repulse, accel);
712 SumForce(result, s.vel * -accel, accel);
715 glm::dvec3 diff = target - s.pos;
716 if (!allzero(diff)) {
717 SumForce(result, TargetVelocity(s, (normalize(diff) * speed), accel), accel);
721 glm::dvec3 diff = target - s.pos;
722 double dist = length(diff);
723 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
724 SumForce(result, TargetVelocity(s, diff * std::min(dist * accel, speed) / dist, accel), accel);
730 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in, double max) const noexcept {
731 if (allzero(in) || anynan(in)) {
734 double cur = allzero(out) ? 0.0 : length(out);
735 double rem = max - cur;
739 double add = length(in);
741 // this method is off if in and out are in different
742 // directions, but gives okayish results
743 out += in * (1.0 / add);
751 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel, double acc) const noexcept {
752 return (vel - s.vel) * acc;