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>
22 #include <glm/gtx/vector_angle.hpp>
25 #include <glm/gtx/io.hpp>
31 Creature::Creature(world::Simulation &sim)
38 , highlight_color(0.0)
54 Creature::~Creature() {
57 glm::dvec4 Creature::HighlightColor() const noexcept {
58 return glm::dvec4(highlight_color, AgeLerp(CurProps().highlight, NextProps().highlight));
61 void Creature::Ingest(int res, double amount) noexcept {
62 const Genome::Composition *cmp = nullptr;
63 for (const auto &c : genome.composition) {
64 if (c.resource == res) {
70 const double max_mass = AgeLerp(CurProps().mass, NextProps().mass);
71 Mass(std::min(max_mass, mass + amount));
73 // foreign material. poisonous?
77 void Creature::Hurt(double dt) noexcept {
78 health = std::max(0.0, health - dt);
80 std::cout << "[" << int(sim.Time()) << "s] "
81 << name << " died" << std::endl;
86 void Creature::Die() noexcept {
96 double Creature::Size() const noexcept {
100 double Creature::Age() const noexcept {
101 return sim.Time() - birth;
104 std::string Creature::AgeName() const {
123 double Creature::AgeLerp(double from, double to) const noexcept {
124 return glm::mix(from, to, glm::smoothstep(CurProps().age, NextProps().age, Age()));
127 double Creature::Fertility() const noexcept {
128 return AgeLerp(CurProps().fertility, NextProps().fertility) / 3600.0;
131 void Creature::AddGoal(std::unique_ptr<Goal> &&g) {
132 std::cout << "[" << int(sim.Time()) << "s] " << name << " new goal: " << g->Describe() << std::endl;
134 goals.emplace_back(std::move(g));
139 bool GoalCompare(const std::unique_ptr<Goal> &a, const std::unique_ptr<Goal> &b) {
140 return b->Urgency() < a->Urgency();
145 void Creature::Tick(double dt) {
146 if (cur_prop < 5 && Age() > NextProps().age) {
149 std::cout << "[" << int(sim.Time()) << "s] "
150 << name << " died of old age" << std::endl;
156 Situation::State state(situation.GetState());
157 Situation::Derivative a(Step(Situation::Derivative(), 0.0));
158 Situation::Derivative b(Step(a, dt * 0.5));
159 Situation::Derivative c(Step(b, dt * 0.5));
160 Situation::Derivative d(Step(c, dt));
161 Situation::Derivative f(
162 (1.0 / 6.0) * (a.vel + 2.0 * (b.vel + c.vel) + d.vel),
163 (1.0 / 6.0) * (a.acc + 2.0 * (b.acc + c.acc) + d.acc),
164 (1.0 / 6.0) * (a.turn + 2.0 * (b.turn + c.turn) + d.turn)
166 state.pos += f.vel * dt;
167 state.vel += f.acc * dt;
168 constexpr double turn_speed = 10.0;
169 state.dir = glm::normalize(state.dir + f.turn * turn_speed * dt);
170 situation.SetState(state);
174 for (auto &need : needs) {
177 for (auto &goal : goals) {
180 // do background stuff
181 for (auto &need : needs) {
182 need->ApplyEffect(*this, dt);
187 // if active goal can be interrupted, check priorities
188 if (goals.size() > 1 && goals[0]->Interruptible()) {
189 std::sort(goals.begin(), goals.end(), GoalCompare);
192 for (auto goal = goals.begin(); goal != goals.end();) {
193 if ((*goal)->Complete()) {
201 Situation::Derivative Creature::Step(const Situation::Derivative &ds, double dt) const noexcept {
202 Situation::State s = situation.GetState();
203 s.pos += ds.vel * dt;
204 s.vel += ds.acc * dt;
205 s.dir = normalize(s.dir + ds.turn * dt);
208 steering.Acceleration(s),
209 allzero(s.vel) ? glm::dvec3(0.0) : normalize(s.vel) - s.dir
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::dmat4(world::Planet::SurfaceOrientation(situation.Surface()))
219 * glm::rotate(glm::orientedAngle(glm::dvec3(0.0, 0.0, -1.0), situation.Heading(), glm::dvec3(0.0, 1.0, 0.0)), glm::dvec3(0.0, 1.0, 0.0))
220 * glm::scale(glm::dvec3(half_size, half_size, half_size));
223 void Creature::BuildVAO() {
225 vao.BindAttributes();
226 vao.EnableAttribute(0);
227 vao.EnableAttribute(1);
228 vao.EnableAttribute(2);
229 vao.AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
230 vao.AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
231 vao.AttributePointer<glm::vec3>(2, false, offsetof(Attributes, texture));
232 vao.ReserveAttributes(6 * 4, GL_STATIC_DRAW);
234 auto attrib = vao.MapAttributes(GL_WRITE_ONLY);
235 const float offset = 1.0f;
236 for (int surface = 0; surface < 6; ++surface) {
237 const float tex_u_begin = surface < 3 ? 1.0f : 0.0f;
238 const float tex_u_end = surface < 3 ? 0.0f : 1.0f;
240 attrib[4 * surface + 0].position[(surface + 0) % 3] = -offset;
241 attrib[4 * surface + 0].position[(surface + 1) % 3] = -offset;
242 attrib[4 * surface + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
243 attrib[4 * surface + 0].normal[(surface + 0) % 3] = 0.0f;
244 attrib[4 * surface + 0].normal[(surface + 1) % 3] = 0.0f;
245 attrib[4 * surface + 0].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
246 attrib[4 * surface + 0].texture.x = tex_u_begin;
247 attrib[4 * surface + 0].texture.y = 1.0f;
248 attrib[4 * surface + 0].texture.z = surface;
250 attrib[4 * surface + 1].position[(surface + 0) % 3] = -offset;
251 attrib[4 * surface + 1].position[(surface + 1) % 3] = offset;
252 attrib[4 * surface + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
253 attrib[4 * surface + 1].normal[(surface + 0) % 3] = 0.0f;
254 attrib[4 * surface + 1].normal[(surface + 1) % 3] = 0.0f;
255 attrib[4 * surface + 1].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
256 attrib[4 * surface + 1].texture.x = tex_u_end;
257 attrib[4 * surface + 1].texture.y = 1.0f;
258 attrib[4 * surface + 1].texture.z = surface;
260 attrib[4 * surface + 2].position[(surface + 0) % 3] = offset;
261 attrib[4 * surface + 2].position[(surface + 1) % 3] = -offset;
262 attrib[4 * surface + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
263 attrib[4 * surface + 2].normal[(surface + 0) % 3] = 0.0f;
264 attrib[4 * surface + 2].normal[(surface + 1) % 3] = 0.0f;
265 attrib[4 * surface + 2].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
266 attrib[4 * surface + 2].texture.x = tex_u_begin;
267 attrib[4 * surface + 2].texture.y = 0.0f;
268 attrib[4 * surface + 2].texture.z = surface;
270 attrib[4 * surface + 3].position[(surface + 0) % 3] = offset;
271 attrib[4 * surface + 3].position[(surface + 1) % 3] = offset;
272 attrib[4 * surface + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
273 attrib[4 * surface + 3].normal[(surface + 0) % 3] = 0.0f;
274 attrib[4 * surface + 3].normal[(surface + 1) % 3] = 0.0f;
275 attrib[4 * surface + 3].normal[(surface + 2) % 3] = surface < 3 ? 1.0f : -1.0f;
276 attrib[4 * surface + 3].texture.x = tex_u_end;
277 attrib[4 * surface + 3].texture.y = 0.0f;
278 attrib[4 * surface + 3].texture.z = surface;
282 vao.ReserveElements(6 * 6, GL_STATIC_DRAW);
284 auto element = vao.MapElements(GL_WRITE_ONLY);
285 for (int surface = 0; surface < 3; ++surface) {
286 element[6 * surface + 0] = 4 * surface + 0;
287 element[6 * surface + 1] = 4 * surface + 2;
288 element[6 * surface + 2] = 4 * surface + 1;
289 element[6 * surface + 3] = 4 * surface + 1;
290 element[6 * surface + 4] = 4 * surface + 2;
291 element[6 * surface + 5] = 4 * surface + 3;
293 for (int surface = 3; surface < 6; ++surface) {
294 element[6 * surface + 0] = 4 * surface + 0;
295 element[6 * surface + 1] = 4 * surface + 1;
296 element[6 * surface + 2] = 4 * surface + 2;
297 element[6 * surface + 3] = 4 * surface + 2;
298 element[6 * surface + 4] = 4 * surface + 1;
299 element[6 * surface + 5] = 4 * surface + 3;
305 void Creature::Draw(graphics::Viewport &viewport) {
307 vao.DrawTriangles(6 * 6);
311 void Spawn(Creature &c, world::Planet &p) {
313 c.GetSituation().SetPlanetSurface(p, 0, p.TileCenter(0, p.SideLength() / 2, p.SideLength() / 2));
315 // probe surrounding area for common resources
316 int start = p.SideLength() / 2 - 2;
318 std::map<int, double> yields;
319 for (int y = start; y < end; ++y) {
320 for (int x = start; x < end; ++x) {
321 const world::TileType &t = p.TypeAt(0, x, y);
322 for (auto yield : t.resources) {
323 yields[yield.resource] += yield.ubiquity;
329 for (auto e : yields) {
330 if (c.GetSimulation().Resources()[e.first].state == world::Resource::LIQUID) {
331 if (liquid < 0 || e.second > yields[liquid]) {
334 } else if (c.GetSimulation().Resources()[e.first].state == world::Resource::SOLID) {
335 if (solid < 0 || e.second > yields[solid]) {
343 genome.properties.Birth().age = { 0.0, 0.0 };
344 genome.properties.Birth().mass = { 0.5, 0.05 };
345 genome.properties.Birth().fertility = { 0.0, 0.0 };
346 genome.properties.Birth().highlight = { 0.0, 0.0 };
348 genome.properties.Child().age = { 30.0, 1.0 };
349 genome.properties.Child().mass = { 0.7, 0.05 };
350 genome.properties.Child().fertility = { 0.0, 0.0 };
351 genome.properties.Child().highlight = { 0.2, 0.05 };
353 genome.properties.Youth().age = { 60.0, 5.0 };
354 genome.properties.Youth().mass = { 0.9, 0.1 };
355 genome.properties.Youth().fertility = { 0.5, 0.03 };
356 genome.properties.Youth().highlight = { 0.9, 0.1 };
358 genome.properties.Adult().age = { 120.0, 10.0 };
359 genome.properties.Adult().mass = { 1.2, 0.1 };
360 genome.properties.Adult().fertility = { 0.4, 0.01 };
361 genome.properties.Adult().highlight = { 0.7, 0.1 };
363 genome.properties.Elder().age = { 360.0, 30.0 };
364 genome.properties.Elder().mass = { 1.0, 0.05 };
365 genome.properties.Elder().fertility = { 0.1, 0.01 };
366 genome.properties.Elder().highlight = { 0.6, 0.1 };
368 genome.properties.Death().age = { 480.0, 60.0 };
369 genome.properties.Death().mass = { 0.9, 0.05 };
370 genome.properties.Death().fertility = { 0.0, 0.0 };
371 genome.properties.Death().highlight = { 0.5, 0.1 };
373 genome.properties.strength = { 1.0, 0.1 };
374 genome.properties.stamina = { 1.0, 0.1 };
375 genome.properties.dexerty = { 1.0, 0.1 };
376 genome.properties.intelligence = { 1.0, 0.1 };
377 genome.properties.mutability = { 1.0, 0.1 };
379 glm::dvec3 color_avg(0.0);
380 double color_divisor = 0.0;
382 if (p.HasAtmosphere()) {
383 genome.composition.push_back({
384 p.Atmosphere(), // resource
385 { 0.01, 0.00001 }, // mass
386 { 0.5, 0.001 }, // intake
387 { 0.1, 0.0005 }, // penalty
388 { 0.0, 0.0 }, // growth
390 color_avg += c.GetSimulation().Resources()[p.Atmosphere()].base_color * 0.1;
391 color_divisor += 0.1;
394 genome.composition.push_back({
396 { 0.6, 0.01 }, // mass
397 { 0.2, 0.001 }, // intake
398 { 0.01, 0.002 }, // penalty
399 { 0.1, 0.0 }, // growth
401 color_avg += c.GetSimulation().Resources()[liquid].base_color * 0.5;
402 color_divisor += 0.5;
405 genome.composition.push_back({
407 { 0.4, 0.01 }, // mass
408 { 0.4, 0.001 }, // intake
409 { 0.001, 0.0001 }, // penalty
410 { 10.0, 0.002 }, // growth
412 color_avg += c.GetSimulation().Resources()[solid].base_color;
413 color_divisor += 1.0;
416 if (color_divisor > 0.001) {
417 color_avg /= color_divisor;
419 glm::dvec3 hsl = rgb2hsl(color_avg);
420 genome.base_hue = { hsl.x, 0.01 };
421 genome.base_saturation = { hsl.y, 0.01 };
422 genome.base_lightness = { hsl.z, 0.01 };
427 void Genome::Configure(Creature &c) const {
428 c.GetGenome() = *this;
430 math::GaloisLFSR &random = c.GetSimulation().Assets().random;
432 c.GetProperties() = Instantiate(properties, random);
436 for (const auto &comp : composition) {
437 const world::Resource &resource = c.GetSimulation().Resources()[comp.resource];
438 double comp_mass = comp.mass.FakeNormal(random.SNorm());
439 double intake = comp.intake.FakeNormal(random.SNorm());
440 double penalty = comp.penalty.FakeNormal(random.SNorm());
443 volume += comp_mass / c.GetSimulation().Resources()[comp.resource].density;
445 std::unique_ptr<Need> need;
446 if (resource.state == world::Resource::SOLID) {
447 intake *= std::atan(c.GetProperties().strength);
448 need.reset(new IngestNeed(comp.resource, intake, penalty));
449 need->gain = intake * 0.05;
450 } else if (resource.state == world::Resource::LIQUID) {
451 intake *= std::atan(c.GetProperties().stamina);
452 need.reset(new IngestNeed(comp.resource, intake, penalty));
453 need->gain = intake * 0.1;
455 need.reset(new InhaleNeed(comp.resource, intake, penalty));
456 need->gain = intake * 0.5;
458 need->name = c.GetSimulation().Resources()[comp.resource].label;
459 need->inconvenient = 0.5;
460 need->critical = 0.95;
461 c.AddNeed(std::move(need));
464 glm::dvec3 base_color(
465 std::fmod(base_hue.FakeNormal(random.SNorm()) + 1.0, 1.0),
466 glm::clamp(base_saturation.FakeNormal(random.SNorm()), 0.0, 1.0),
467 glm::clamp(base_lightness.FakeNormal(random.SNorm()), 0.0, 1.0)
469 glm::dvec3 highlight_color(
470 std::fmod(base_color.x + 0.5, 1.0),
474 c.BaseColor(hsl2rgb(base_color));
475 c.HighlightColor(hsl2rgb(highlight_color));
477 c.Mass(c.GetProperties().props[0].mass);
478 c.Density(mass / volume);
479 c.GetSteering().MaxAcceleration(1.4 * std::atan(c.GetProperties().strength));
480 c.GetSteering().MaxSpeed(4.4 * std::atan(c.GetProperties().dexerty));
481 c.AddGoal(std::unique_ptr<Goal>(new IdleGoal(c)));
485 void Split(Creature &c) {
486 Creature *a = new Creature(c.GetSimulation());
487 const Situation &s = c.GetSituation();
488 a->Name(c.GetSimulation().Assets().name.Sequential());
490 c.GetGenome().Configure(*a);
491 s.GetPlanet().AddCreature(a);
492 // TODO: duplicate situation somehow
493 a->GetSituation().SetPlanetSurface(
494 s.GetPlanet(), s.Surface(),
495 s.Position() + glm::dvec3(0.0, a->Size() * 0.51, 0.0));
498 Creature *b = new Creature(c.GetSimulation());
499 b->Name(c.GetSimulation().Assets().name.Sequential());
500 c.GetGenome().Configure(*b);
501 s.GetPlanet().AddCreature(b);
502 b->GetSituation().SetPlanetSurface(
503 s.GetPlanet(), s.Surface(),
504 s.Position() + glm::dvec3(0.0, b->Size() * -0.51, 0.0));
511 Memory::Memory(Creature &c)
518 void Memory::Tick(double dt) {
519 Situation &s = c.GetSituation();
521 TrackStay({ &s.GetPlanet(), s.Surface(), s.SurfacePosition() }, dt);
525 void Memory::TrackStay(const Location &l, double t) {
526 const world::TileType &type = l.planet->TypeAt(l.surface, l.coords.x, l.coords.y);
527 auto entry = known_types.find(type.id);
528 if (entry != known_types.end()) {
529 entry->second.last_been = c.GetSimulation().Time();
530 entry->second.last_loc = l;
531 entry->second.time_spent += t;
533 known_types.emplace(type.id, Stay{
534 c.GetSimulation().Time(),
536 c.GetSimulation().Time(),
544 NameGenerator::NameGenerator()
548 NameGenerator::~NameGenerator() {
551 std::string NameGenerator::Sequential() {
552 std::stringstream ss;
553 ss << "Blob " << ++counter;
558 Situation::Situation()
560 , state(glm::dvec3(0.0), glm::dvec3(0.0))
565 Situation::~Situation() {
568 bool Situation::OnPlanet() const noexcept {
569 return type == PLANET_SURFACE;
572 bool Situation::OnSurface() const noexcept {
573 return type == PLANET_SURFACE;
576 bool Situation::OnTile() const noexcept {
577 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
578 return type == PLANET_SURFACE
579 && t.x >= 0 && t.x < planet->SideLength()
580 && t.y >= 0 && t.y < planet->SideLength();
583 glm::ivec2 Situation::SurfacePosition() const noexcept {
584 return planet->SurfacePosition(surface, state.pos);
587 world::Tile &Situation::GetTile() const noexcept {
588 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
589 return planet->TileAt(surface, t.x, t.y);
592 const world::TileType &Situation::GetTileType() const noexcept {
593 glm::ivec2 t(planet->SurfacePosition(surface, state.pos));
594 return planet->TypeAt(surface, t.x, t.y);
597 void Situation::Move(const glm::dvec3 &dp) noexcept {
600 // enforce ground constraint
602 state.pos[(Surface() + 2) % 3] = std::max(0.0, state.pos[(Surface() + 2) % 3]);
604 state.pos[(Surface() + 2) % 3] = std::min(0.0, state.pos[(Surface() + 2) % 3]);
609 void Situation::SetPlanetSurface(world::Planet &p, int srf, const glm::dvec3 &pos) noexcept {
610 type = PLANET_SURFACE;
626 Steering::~Steering() {
629 void Steering::Halt() noexcept {
635 void Steering::Pass(const glm::dvec3 &t) noexcept {
642 void Steering::GoTo(const glm::dvec3 &t) noexcept {
649 glm::dvec3 Steering::Acceleration(const Situation::State &s) const noexcept {
652 SumForce(acc, s.vel * -max_accel);
655 glm::dvec3 diff = target - s.pos;
656 if (!allzero(diff)) {
657 SumForce(acc, TargetVelocity(s, (normalize(diff) * max_speed)));
661 glm::dvec3 diff = target - s.pos;
662 double dist = length(diff);
663 if (!allzero(diff) && dist > std::numeric_limits<double>::epsilon()) {
664 SumForce(acc, TargetVelocity(s, diff * std::min(dist * max_accel, max_speed) / dist));
670 bool Steering::SumForce(glm::dvec3 &out, const glm::dvec3 &in) const noexcept {
671 if (allzero(in) || anynan(in)) {
674 double cur = allzero(out) ? 0.0 : length(out);
675 double rem = max_accel - cur;
679 double add = length(in);
681 // this method is off if in and out are in different
682 // directions, but gives okayish results
683 out += in * (1.0 / add);
691 glm::dvec3 Steering::TargetVelocity(const Situation::State &s, const glm::dvec3 &vel) const noexcept {
692 return (vel - s.vel) * max_accel;