1 #include "Creature.hpp"
4 #include "NameGenerator.hpp"
5 #include "Situation.hpp"
6 #include "Steering.hpp"
9 #include "IdleGoal.hpp"
10 #include "InhaleNeed.hpp"
11 #include "IngestNeed.hpp"
13 #include "../app/Assets.hpp"
14 #include "../world/Body.hpp"
15 #include "../world/Planet.hpp"
16 #include "../world/Simulation.hpp"
17 #include "../world/TileType.hpp"
21 #include <glm/gtx/transform.hpp>
24 #include <glm/gtx/io.hpp>
30 Creature::Creature(world::Simulation &sim)
37 , highlight_color(0.0)
53 Creature::~Creature() {
56 glm::dvec4 Creature::HighlightColor() const noexcept {
57 return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
60 void Creature::Ingest(int res, double amount) noexcept {
61 const Genome::Composition *cmp = nullptr;
62 for (const auto &c : genome.composition) {
63 if (c.resource == res) {
69 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
70 Mass(std::min(max_mass, mass + amount));
72 // foreign material. poisonous?
76 void Creature::Hurt(double dt) noexcept {
77 health = std::max(0.0, health - dt);
79 std::cout << "[" << int(sim.Time()) << "s] "
80 << name << " died" << std::endl;
85 void Creature::Die() noexcept {
95 double Creature::Size() const noexcept {
99 double Creature::Age() const noexcept {
100 return sim.Time() - birth;
103 std::string Creature::AgeName() const {
122 double Creature::AgeLerp(double from, double to) const noexcept {
123 return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
126 double Creature::Fertility() const noexcept {
127 return AgeLerp(CurProps().fertility, NextProps().fertility) / 3600.0;
130 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
131 std::cout << "[" << int(sim.Time()) << "s] " << name << " new goal: " << g->Describe() << std::endl;
133 goals.emplace_back(std::move(g));
138 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
139 return b->Urgency() < a->Urgency();
144 void Creature::Tick(double dt) {
145 if (cur_prop < 5 && Age() > NextProps().age) {
148 std::cout << "[" << int(sim.Time()) << "s] "
149 << name << " died of old age" << std::endl;
155 Situation::State state(situation.GetState());
156 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
157 Situation::Derivative b(Step(a, dt * 0.5));
158 Situation::Derivative c(Step(b, dt * 0.5));
159 Situation::Derivative d(Step(c, dt));
160 Situation::Derivative f(
161 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
162 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc)
164 state.pos += f.vel * dt;
165 state.vel += f.acc * dt;
166 situation.SetState(state);
170 for (auto &need : needs) {
173 for (auto &goal : goals) {
176 // do background stuff
177 for (auto &need : needs) {
178 need->ApplyEffect(*this, dt);
183 // if active goal can be interrupted, check priorities
184 if (goals.size() > 1 && goals[0]->Interruptible()) {
185 Goal *old_top = &*goals[0];
186 std::sort(goals.begin(), goals.end(), GoalCompare);
187 Goal *new_top = &*goals[0];
188 if (new_top != old_top) {
189 std::cout << "[" << int(sim.Time()) << "s] " << name
190 << " changing goal from " << old_top->Describe()
191 << " to " << new_top->Describe() << std::endl;
195 for (auto goal = goals.begin(); goal != goals.end();) {
196 if ((*goal)->Complete()) {
197 std::cout << "[" << int(sim.Time()) << "s] " << name
198 << " complete goal: " << (*goal)->Describe() << std::endl;
206 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
207 Situation::State s = situation.GetState();
208 s.pos += ds.vel * dt;
209 s.vel += ds.acc * dt;
210 return { s.vel, steering.Acceleration(s) };
213 glm::dmat4 Creature::LocalTransform() noexcept {
214 // TODO: surface transform
215 const double half_size = size * 0.5;
216 const glm::dvec3 &pos = situation.Position();
217 return glm::translate(glm::dvec3(pos.x, pos.y, pos.z + half_size))
218 * glm::scale(glm::dvec3(half_size, half_size, half_size));
221 void Creature::BuildVAO() {
223 vao.BindAttributes();
224 vao.EnableAttribute(0);
225 vao.EnableAttribute(1);
226 vao.EnableAttribute(2);
227 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
228 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
229 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
230 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
232 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
233 const float offset = 1.0f;
234 for (int surface = 0; surface < 6; ++surface) {
235 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
236 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
238 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
239 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
240 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
241 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
242 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
243 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
244 attrib[4 * surface + 0].texture.x = tex_u_begin;
245 attrib[4 * surface + 0].texture.y = 1.0f;
246 attrib[4 * surface + 0].texture.z = surface;
248 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
249 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
250 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
251 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
252 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
253 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
254 attrib[4 * surface + 1].texture.x = tex_u_end;
255 attrib[4 * surface + 1].texture.y = 1.0f;
256 attrib[4 * surface + 1].texture.z = surface;
258 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
259 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
260 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
261 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
262 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
263 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
264 attrib[4 * surface + 2].texture.x = tex_u_begin;
265 attrib[4 * surface + 2].texture.y = 0.0f;
266 attrib[4 * surface + 2].texture.z = surface;
268 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
269 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
270 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
271 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
272 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
273 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
274 attrib[4 * surface + 3].texture.x = tex_u_end;
275 attrib[4 * surface + 3].texture.y = 0.0f;
276 attrib[4 * surface + 3].texture.z = surface;
280 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
282 auto element = vao.MapElements(GL_WRITE_ONLY);
283 for (int surface = 0; surface < 3; ++surface) {
284 element[6 * surface + 0] = 4 * surface + 0;
285 element[6 * surface + 1] = 4 * surface + 2;
286 element[6 * surface + 2] = 4 * surface + 1;
287 element[6 * surface + 3] = 4 * surface + 1;
288 element[6 * surface + 4] = 4 * surface + 2;
289 element[6 * surface + 5] = 4 * surface + 3;
291 for (int surface = 3; surface < 6; ++surface) {
292 element[6 * surface + 0] = 4 * surface + 0;
293 element[6 * surface + 1] = 4 * surface + 1;
294 element[6 * surface + 2] = 4 * surface + 2;
295 element[6 * surface + 3] = 4 * surface + 2;
296 element[6 * surface + 4] = 4 * surface + 1;
297 element[6 * surface + 5] = 4 * surface + 3;
303 void Creature::Draw(graphics::Viewport &viewport) {
305 vao.DrawTriangles(6 * 6);
309 void Spawn(Creature &c, world::Planet &p) {
311 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
313 // probe surrounding area for common resources
314 int start = p.SideLength() / 2 - 2;
316 std::map<int, double> yields;
317 for (int y = start; y < end; ++y) {
318 for (int x = start; x < end; ++x) {
319 const world::TileType &t = p.TypeAt(0, x, y);
320 for (auto yield : t.resources) {
321 yields[yield.resource] += yield.ubiquity;
327 for (auto e : yields) {
328 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
329 if (liquid < 0 || e.second > yields[liquid]) {
332 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
333 if (solid < 0 || e.second > yields[solid]) {
341 genome.properties.Birth().age = { 0.0, 0.0 };
342 genome.properties.Birth().mass = { 0.5, 0.05 };
343 genome.properties.Birth().fertility = { 0.0, 0.0 };
344 genome.properties.Birth().highlight = { 0.0, 0.0 };
346 genome.properties.Child().age = { 30.0, 1.0 };
347 genome.properties.Child().mass = { 0.7, 0.05 };
348 genome.properties.Child().fertility = { 0.0, 0.0 };
349 genome.properties.Child().highlight = { 0.2, 0.05 };
351 genome.properties.Youth().age = { 60.0, 5.0 };
352 genome.properties.Youth().mass = { 0.9, 0.1 };
353 genome.properties.Youth().fertility = { 0.5, 0.03 };
354 genome.properties.Youth().highlight = { 0.9, 0.1 };
356 genome.properties.Adult().age = { 120.0, 10.0 };
357 genome.properties.Adult().mass = { 1.2, 0.1 };
358 genome.properties.Adult().fertility = { 0.4, 0.01 };
359 genome.properties.Adult().highlight = { 0.7, 0.1 };
361 genome.properties.Elder().age = { 360.0, 30.0 };
362 genome.properties.Elder().mass = { 1.0, 0.05 };
363 genome.properties.Elder().fertility = { 0.1, 0.01 };
364 genome.properties.Elder().highlight = { 0.6, 0.1 };
366 genome.properties.Death().age = { 480.0, 60.0 };
367 genome.properties.Death().mass = { 0.9, 0.05 };
368 genome.properties.Death().fertility = { 0.0, 0.0 };
369 genome.properties.Death().highlight = { 0.5, 0.1 };
371 genome.properties.strength = { 1.0, 0.1 };
372 genome.properties.stamina = { 1.0, 0.1 };
373 genome.properties.dexerty = { 1.0, 0.1 };
374 genome.properties.intelligence = { 1.0, 0.1 };
375 genome.properties.mutability = { 1.0, 0.1 };
377 glm::dvec3 color_avg(0.0);
378 double color_divisor = 0.0;
380 if (p.HasAtmosphere()) {
381 genome.composition.push_back({
382 p.Atmosphere(), // resource
383 { 0.01, 0.00001 }, // mass
384 { 0.5, 0.001 }, // intake
385 { 0.1, 0.0005 }, // penalty
386 { 0.0, 0.0 }, // growth
388 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
389 color_divisor += 0.1;
392 genome.composition.push_back({
394 { 0.6, 0.01 }, // mass
395 { 0.2, 0.001 }, // intake
396 { 0.01, 0.002 }, // penalty
397 { 0.1, 0.0 }, // growth
399 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
400 color_divisor += 0.5;
403 genome.composition.push_back({
405 { 0.4, 0.01 }, // mass
406 { 0.4, 0.001 }, // intake
407 { 0.001, 0.0001 }, // penalty
408 { 10.0, 0.002 }, // growth
410 color_avg += c.GetSimulation().Resources()[solid].base_color;
411 color_divisor += 1.0;
414 if (color_divisor > 0.001) {
415 color_avg /= color_divisor;
417 glm::dvec3 hsl = rgb2hsl(color_avg);
418 genome.base_hue = { hsl.x, 0.01 };
419 genome.base_saturation = { hsl.y, 0.01 };
420 genome.base_lightness = { hsl.z, 0.01 };
425 void Genome::Configure(Creature &c) const {
426 c.GetGenome() = *this;
428 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
430 c.GetProperties() = Instantiate(properties, random);
434 for (const auto &comp : composition) {
435 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
436 double comp_mass = comp.mass.FakeNormal(random.SNorm());
437 double intake = comp.intake.FakeNormal(random.SNorm());
438 double penalty = comp.penalty.FakeNormal(random.SNorm());
441 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
443 std::unique_ptr<Need> need;
444 if (resource.state == world::Resource::SOLID) {
445 intake *= std::atan(c.GetProperties().strength);
446 need.reset(new IngestNeed(comp.resource, intake, penalty));
447 need->gain = intake * 0.05;
448 } else if (resource.state == world::Resource::LIQUID) {
449 intake *= std::atan(c.GetProperties().stamina);
450 need.reset(new IngestNeed(comp.resource, intake, penalty));
451 need->gain = intake * 0.1;
453 need.reset(new InhaleNeed(comp.resource, intake, penalty));
454 need->gain = intake * 0.5;
456 need->name = c.GetSimulation().Resources()[comp.resource].label;
457 need->inconvenient = 0.5;
458 need->critical = 0.95;
459 c.AddNeed(std::move(need));
462 glm::dvec3 base_color(
463 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
464 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
465 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
467 glm::dvec3 highlight_color(
468 std::fmod(base_color.x + 0.5, 1.0),
472 c.BaseColor(hsl2rgb(base_color));
473 c.HighlightColor(hsl2rgb(highlight_color));
475 c.Mass(c.GetProperties().props[0].mass);
476 c.Density(mass / volume);
477 c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
478 c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
479 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
483 void Split(Creature &c) {
484 Creature *a = new Creature(c.GetSimulation());
485 const Situation &s = c.GetSituation();
486 a->Name(c.GetSimulation().Assets().name.Sequential());
488 c.GetGenome().Configure(*a);
489 s.GetPlanet().AddCreature(a);
490 // TODO: duplicate situation somehow
491 a->GetSituation().SetPlanetSurface(
492 s.GetPlanet(), s.Surface(),
493 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
496 Creature *b = new Creature(c.GetSimulation());
497 b->Name(c.GetSimulation().Assets().name.Sequential());
498 c.GetGenome().Configure(*b);
499 s.GetPlanet().AddCreature(b);
500 b->GetSituation().SetPlanetSurface(
501 s.GetPlanet(), s.Surface(),
502 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
509 Memory::Memory(Creature &c)
516 void Memory::Tick(double dt) {
517 Situation &s = c.GetSituation();
519 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
523 void Memory::TrackStay(const Location &l, double t) {
524 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
525 auto entry = known_types.find(type.id);
526 if (entry != known_types.end()) {
527 entry->second.last_been = c.GetSimulation().Time();
528 entry->second.last_loc = l;
529 entry->second.time_spent += t;
531 known_types.emplace(type.id, Stay{
532 c.GetSimulation().Time(),
534 c.GetSimulation().Time(),
542 NameGenerator::NameGenerator()
546 NameGenerator::~NameGenerator() {
549 std::string NameGenerator::Sequential() {
550 std::stringstream ss;
551 ss << "Blob " << ++counter;
556 Situation::Situation()
558 , state(glm::dvec3(0.0), glm::dvec3(0.0))
563 Situation::~Situation() {
566 bool Situation::OnPlanet() const noexcept {
567 return type == PLANET_SURFACE;
570 bool Situation::OnSurface() const noexcept {
571 return type == PLANET_SURFACE;
574 bool Situation::OnTile() const noexcept {
575 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
576 return type == PLANET_SURFACE
577 && t.x >= 0 && t.x < planet->SideLength()
578 && t.y >= 0 && t.y < planet->SideLength();
581 glm::ivec2 Situation::SurfacePosition() const noexcept {
582 return planet->SurfacePosition(surface, state.pos);
585 world::Tile &Situation::GetTile() const noexcept {
586 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
587 return planet->TileAt(surface, t.x, t.y);
590 const world::TileType &Situation::GetTileType() const noexcept {
591 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
592 return planet->TypeAt(surface, t.x, t.y);
595 void Situation::Move(const glm::dvec3 &dp) noexcept {
598 // enforce ground constraint
600 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
602 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
607 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
608 type = PLANET_SURFACE;
624 Steering::~Steering() {
627 void Steering::Halt() noexcept {
633 void Steering::Pass(const glm::dvec3 &t) noexcept {
640 void Steering::GoTo(const glm::dvec3 &t) noexcept {
647 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
650 SumForce(acc, s.vel * -max_accel);
653 glm::dvec3 diff = target - s.pos;
654 if (!allzero(diff)) {
655 SumForce(acc, TargetVelocity(s, (normalize(diff) * max_speed)));
659 glm::dvec3 diff = target - s.pos;
660 double dist = length(diff);
661 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
662 SumForce(acc, TargetVelocity(s, diff * std::min(dist * max_accel, max_speed) / dist));
668 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
669 if (allzero(in) || anynan(in)) {
672 double cur = allzero(out) ? 0.0 : length(out);
673 double rem = max_accel - cur;
677 double add = length(in);
679 // this method is off if in and out are in different
680 // directions, but gives okayish results
681 out += in * (1.0 / add);
689 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel) const noexcept {
690 return (vel - s.vel) * max_accel;