2 #include "CreatureCreatureCollision.hpp"
5 #include "Resource.hpp"
7 #include "Simulation.hpp"
10 #include "TileType.hpp"
12 #include "../app/Assets.hpp"
13 #include "../creature/Composition.hpp"
14 #include "../creature/Creature.hpp"
15 #include "../graphics/Viewport.hpp"
16 #include "../math/const.hpp"
17 #include "../math/geometry.hpp"
18 #include "../math/OctaveNoise.hpp"
19 #include "../math/SimplexNoise.hpp"
24 #include <glm/gtc/matrix_transform.hpp>
25 #include <glm/gtx/euler_angles.hpp>
26 #include <glm/gtx/io.hpp>
27 #include <glm/gtx/transform.hpp>
45 , surface_tilt(0.0, 0.0)
50 , inverse_orbital(1.0)
60 void Body::SetSimulation(Simulation &s) noexcept {
62 for (auto child : children) {
63 child->SetSimulation(s);
67 void Body::SetParent(Body &p) {
72 parent->AddChild(*this);
75 void Body::UnsetParent() {
76 if (!HasParent()) return;
77 parent->RemoveChild(*this);
81 void Body::AddChild(Body &c) {
82 children.push_back(&c);
83 c.SetSimulation(*sim);
86 void Body::RemoveChild(Body &c) {
87 auto entry = std::find(children.begin(), children.end(), &c);
88 if (entry != children.end()) {
89 children.erase(entry);
93 double Body::Inertia() const noexcept {
94 // assume solid sphere for now
95 return (2.0/5.0) * Mass() * pow(Radius(), 2);
98 double Body::GravitationalParameter() const noexcept {
102 double Body::OrbitalPeriod() const noexcept {
104 return PI * 2.0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
110 double Body::RotationalPeriod() const noexcept {
111 if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
112 return std::numeric_limits<double>::infinity();
114 return PI * 2.0 * Inertia() / angular;
118 double Body::DayLength() const noexcept {
120 return RotationalPeriod();
122 double year = OrbitalPeriod();
123 double sidereal = RotationalPeriod();
124 double grade = (angular < 0.0 ? -1.0 : 1.0) * (std::abs(axis_tilt.x) > PI * 0.5 ? -1.0 : 1.0);
125 return std::abs((year * sidereal) / ( year + (grade * sidereal)));
128 double Body::SphereOfInfluence() const noexcept {
130 return orbit.SemiMajorAxis() * std::pow(Mass() / Parent().Mass(), 2.0 / 5.0);
132 return std::numeric_limits<double>::infinity();
136 glm::dmat4 Body::ToUniverse() const noexcept {
138 const Body *b = this;
139 while (b->HasParent()) {
140 m = b->ToParent() * m;
146 glm::dmat4 Body::FromUniverse() const noexcept {
148 const Body *b = this;
149 while (b->HasParent()) {
150 m *= b->FromParent();
157 std::vector<creature::Creature *> ccache;
158 std::vector<CreatureCreatureCollision> collisions;
161 void Body::Tick(double dt) {
162 rotation += dt * AngularMomentum() / Inertia();
164 ccache = Creatures();
165 for (creature::Creature *c : ccache) {
168 // first remove creatures so they don't collide
169 for (auto c = Creatures().begin(); c != Creatures().end();) {
170 if ((*c)->Removable()) {
172 c = Creatures().erase(c);
180 void Body::Cache() noexcept {
183 orbit.Matrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()))
184 * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
186 glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
187 * orbit.InverseMatrix(PI * 2.0 * (GetSimulation().Time() / OrbitalPeriod()));
189 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
190 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
193 glm::eulerAngleY(rotation)
194 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
196 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
197 * glm::eulerAngleY(-rotation);
200 void Body::CheckCollision() noexcept {
201 if (Creatures().size() < 2) return;
203 auto end = Creatures().end();
204 for (auto i = Creatures().begin(); i != end; ++i) {
205 math::AABB i_box((*i)->CollisionBounds());
206 glm::dmat4 i_mat((*i)->CollisionTransform());
207 for (auto j = (i + 1); j != end; ++j) {
208 glm::dvec3 diff((*i)->GetSituation().Position() - (*j)->GetSituation().Position());
209 double max_dist = ((*i)->Size() + (*j)->Size()) * 1.74;
210 if (glm::length2(diff) > max_dist * max_dist) continue;
211 math::AABB j_box((*j)->CollisionBounds());
212 glm::dmat4 j_mat((*j)->CollisionTransform());
215 if (Intersect(i_box, i_mat, j_box, j_mat, normal, depth)) {
216 collisions.push_back({ **i, **j, normal, depth });
220 for (auto &c : collisions) {
221 c.A().OnCollide(c.B());
222 c.B().OnCollide(c.A());
223 c.A().GetSituation().Move(c.Normal() * (c.Depth() * -0.5));
224 c.B().GetSituation().Move(c.Normal() * (c.Depth() * 0.5));
225 c.A().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.AVel()));
226 c.B().GetSituation().Accelerate(c.Normal() * -glm::dot(c.Normal(), c.BVel()));
230 void Body::AddCreature(creature::Creature *c) {
231 creatures.push_back(c);
234 void Body::RemoveCreature(creature::Creature *c) {
235 auto entry = std::find(creatures.begin(), creatures.end(), c);
236 if (entry != creatures.end()) {
237 creatures.erase(entry);
242 CreatureCreatureCollision::~CreatureCreatureCollision() {
245 const glm::dvec3 &CreatureCreatureCollision::APos() const noexcept {
246 return a->GetSituation().Position();
249 const glm::dvec3 &CreatureCreatureCollision::AVel() const noexcept {
250 return a->GetSituation().Velocity();
253 const glm::dvec3 &CreatureCreatureCollision::BPos() const noexcept {
254 return b->GetSituation().Position();
257 const glm::dvec3 &CreatureCreatureCollision::BVel() const noexcept {
258 return b->GetSituation().Velocity();
274 double Orbit::SemiMajorAxis() const noexcept {
278 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
283 double Orbit::Eccentricity() const noexcept {
287 Orbit &Orbit::Eccentricity(double e) noexcept {
292 double Orbit::Inclination() const noexcept {
296 Orbit &Orbit::Inclination(double i) noexcept {
301 double Orbit::LongitudeAscending() const noexcept {
305 Orbit &Orbit::LongitudeAscending(double l) noexcept {
310 double Orbit::ArgumentPeriapsis() const noexcept {
314 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
319 double Orbit::MeanAnomaly() const noexcept {
323 Orbit &Orbit::MeanAnomaly(double m) noexcept {
330 double mean2eccentric(double M, double e) {
331 double E = M; // eccentric anomaly, solve M = E - e sin E
332 // limit to 100 steps to prevent deadlocks in impossible situations
333 for (int i = 0; i < 100; ++i) {
334 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
336 if (std::abs(dE) < 1.0e-6) break;
343 glm::dmat4 Orbit::Matrix(double t) const noexcept {
345 double E = mean2eccentric(M, ecc);
347 // coordinates in orbital plane, P=x, Q=-z
348 double P = sma * (cos(E) - ecc);
349 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
351 return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
354 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
356 double E = mean2eccentric(M, ecc);
357 double P = sma * (cos(E) - ecc);
358 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
359 return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
363 Planet::Planet(int sidelength)
365 , sidelength(sidelength)
366 , tiles(TilesTotal())
368 Radius(double(sidelength) / 2.0);
375 /// map p onto cube, s gives the surface, u and v the position in [-1,1]
376 void cubemap(const glm::dvec3 &p, int &s, double &u, double &v) noexcept {
377 const glm::dvec3 p_abs(glm::abs(p));
378 const glm::bvec3 p_pos(glm::greaterThan(p, glm::dvec3(0.0)));
379 double max_axis = 0.0;
381 if (p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
387 if (!p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
393 if (p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
399 if (!p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
405 if (p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
411 if (!p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
420 /// get p from cube, s being surface, u and v the position in [-1,1],
421 /// gives a vector from the center to the surface
422 glm::dvec3 cubeunmap(int s, double u, double v) {
425 case 0: return glm::dvec3(u, v, 1.0); // +Z
426 case 1: return glm::dvec3(1.0, u, v); // +X
427 case 2: return glm::dvec3(v, 1.0, u); // +Y
428 case 3: return glm::dvec3(-u, -v, -1.0); // -Z
429 case 4: return glm::dvec3(-1.0, -u, -v); // -X
430 case 5: return glm::dvec3(-v, -1.0, -u); // -Y
435 Tile &Planet::TileAt(const glm::dvec3 &p) noexcept {
439 cubemap(p, srf, u, v);
440 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
441 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
442 return TileAt(srf, x, y);
445 const Tile &Planet::TileAt(const glm::dvec3 &p) const noexcept {
449 cubemap(p, srf, u, v);
450 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
451 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
452 return TileAt(srf, x, y);
455 const TileType &Planet::TileTypeAt(const glm::dvec3 &p) const noexcept {
456 return GetSimulation().TileTypes()[TileAt(p).type];
459 Tile &Planet::TileAt(int surface, int x, int y) noexcept {
460 return tiles[IndexOf(surface, x, y)];
463 const Tile &Planet::TileAt(int surface, int x, int y) const noexcept {
464 return tiles[IndexOf(surface, x, y)];
467 const TileType &Planet::TypeAt(int srf, int x, int y) const noexcept {
468 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
471 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
472 double u = (double(x) - Radius() + 0.5) / Radius();
473 double v = (double(y) - Radius() + 0.5) / Radius();
474 return glm::normalize(cubeunmap(srf, u, v)) * (Radius() + e);
477 void Planet::BuildVAO(const Set<TileType> &ts) {
478 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
480 vao->BindAttributes();
481 vao->EnableAttribute(0);
482 vao->EnableAttribute(1);
483 vao->EnableAttribute(2);
484 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
485 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
486 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, tex_coord));
487 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
489 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
490 float offset = Radius();
493 // up +Z +X +Y -Z -X -Y
495 for (int index = 0, surface = 0; surface < 6; ++surface) {
496 for (int y = 0; y < sidelength; ++y) {
497 for (int x = 0; x < sidelength; ++x, ++index) {
499 pos[0][(surface + 0) % 3] = float(x + 0) - offset;
500 pos[0][(surface + 1) % 3] = float(y + 0) - offset;
501 pos[0][(surface + 2) % 3] = offset;
502 pos[1][(surface + 0) % 3] = float(x + 0) - offset;
503 pos[1][(surface + 1) % 3] = float(y + 1) - offset;
504 pos[1][(surface + 2) % 3] = offset;
505 pos[2][(surface + 0) % 3] = float(x + 1) - offset;
506 pos[2][(surface + 1) % 3] = float(y + 0) - offset;
507 pos[2][(surface + 2) % 3] = offset;
508 pos[3][(surface + 0) % 3] = float(x + 1) - offset;
509 pos[3][(surface + 1) % 3] = float(y + 1) - offset;
510 pos[3][(surface + 2) % 3] = offset;
512 float tex = ts[TileAt(surface, x, y).type].texture;
513 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
514 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
516 attrib[4 * index + 0].position = glm::normalize(pos[0]) * (surface < 3 ? offset : -offset);
517 attrib[4 * index + 0].normal = pos[0];
518 attrib[4 * index + 0].tex_coord[0] = 0.0f;
519 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
520 attrib[4 * index + 0].tex_coord[2] = tex;
522 attrib[4 * index + 1].position = glm::normalize(pos[1]) * (surface < 3 ? offset : -offset);
523 attrib[4 * index + 1].normal = pos[1];
524 attrib[4 * index + 1].tex_coord[0] = 0.0f;
525 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
526 attrib[4 * index + 1].tex_coord[2] = tex;
528 attrib[4 * index + 2].position = glm::normalize(pos[2]) * (surface < 3 ? offset : -offset);
529 attrib[4 * index + 2].normal = pos[2];
530 attrib[4 * index + 2].tex_coord[0] = 1.0f;
531 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
532 attrib[4 * index + 2].tex_coord[2] = tex;
534 attrib[4 * index + 3].position = glm::normalize(pos[3]) * (surface < 3 ? offset : -offset);
535 attrib[4 * index + 3].normal = pos[3];
536 attrib[4 * index + 3].tex_coord[0] = 1.0f;
537 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
538 attrib[4 * index + 3].tex_coord[2] = tex;
544 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
546 auto element = vao->MapElements(GL_WRITE_ONLY);
548 for (int surface = 0; surface < 3; ++surface) {
549 for (int y = 0; y < sidelength; ++y) {
550 for (int x = 0; x < sidelength; ++x, ++index) {
551 element[6 * index + 0] = 4 * index + 0;
552 element[6 * index + 1] = 4 * index + 2;
553 element[6 * index + 2] = 4 * index + 1;
554 element[6 * index + 3] = 4 * index + 1;
555 element[6 * index + 4] = 4 * index + 2;
556 element[6 * index + 5] = 4 * index + 3;
560 for (int surface = 3; surface < 6; ++surface) {
561 for (int y = 0; y < sidelength; ++y) {
562 for (int x = 0; x < sidelength; ++x, ++index) {
563 element[6 * index + 0] = 4 * index + 0;
564 element[6 * index + 1] = 4 * index + 1;
565 element[6 * index + 2] = 4 * index + 2;
566 element[6 * index + 3] = 4 * index + 2;
567 element[6 * index + 4] = 4 * index + 1;
568 element[6 * index + 5] = 4 * index + 3;
576 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
580 vao->DrawTriangles(TilesTotal() * 6);
584 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
585 math::SimplexNoise elevation_gen(0);
586 math::SimplexNoise variation_gen(45623752346);
588 const int ice = tiles["ice"].id;
589 const int ocean = tiles["ocean"].id;
590 const int water = tiles["water"].id;
591 const int sand = tiles["sand"].id;
592 const int grass = tiles["grass"].id;
593 const int tundra = tiles["tundra"].id;
594 const int taiga = tiles["taiga"].id;
595 const int desert = tiles["desert"].id;
596 const int mntn = tiles["mountain"].id;
597 const int algae = tiles["algae"].id;
598 const int forest = tiles["forest"].id;
599 const int jungle = tiles["jungle"].id;
600 const int rock = tiles["rock"].id;
601 const int wheat = tiles["wheat"].id;
603 constexpr double ocean_thresh = -0.2;
604 constexpr double water_thresh = 0.0;
605 constexpr double beach_thresh = 0.05;
606 constexpr double highland_thresh = 0.4;
607 constexpr double mountain_thresh = 0.5;
609 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
610 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
611 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
612 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
613 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
615 for (int surface = 0; surface <= 5; ++surface) {
616 for (int y = 0; y < p.SideLength(); ++y) {
617 for (int x = 0; x < p.SideLength(); ++x) {
618 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
619 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
620 if (near_axis > cap_thresh) {
621 p.TileAt(surface, x, y).type = ice;
624 float elevation = math::OctaveNoise(
626 glm::vec3(to_tile / p.Radius()),
629 5 / p.Radius(), // frequency
633 float variation = math::OctaveNoise(
635 glm::vec3(to_tile / p.Radius()),
638 16 / p.Radius(), // frequency
642 if (elevation < ocean_thresh) {
643 p.TileAt(surface, x, y).type = ocean;
644 } else if (elevation < water_thresh) {
645 if (variation > 0.3) {
646 p.TileAt(surface, x, y).type = algae;
648 p.TileAt(surface, x, y).type = water;
650 } else if (elevation < beach_thresh) {
651 p.TileAt(surface, x, y).type = sand;
652 } else if (elevation < highland_thresh) {
653 if (near_axis < equ_thresh) {
654 if (variation > 0.6) {
655 p.TileAt(surface, x, y).type = grass;
656 } else if (variation > 0.2) {
657 p.TileAt(surface, x, y).type = sand;
659 p.TileAt(surface, x, y).type = desert;
661 } else if (near_axis < fzone_start) {
662 if (variation > 0.4) {
663 p.TileAt(surface, x, y).type = forest;
664 } else if (variation < -0.5) {
665 p.TileAt(surface, x, y).type = jungle;
666 } else if (variation > -0.02 && variation < 0.02) {
667 p.TileAt(surface, x, y).type = wheat;
669 p.TileAt(surface, x, y).type = grass;
671 } else if (near_axis < fzone_end) {
672 p.TileAt(surface, x, y).type = tundra;
674 p.TileAt(surface, x, y).type = taiga;
676 } else if (elevation < mountain_thresh) {
677 if (variation > 0.3) {
678 p.TileAt(surface, x, y).type = mntn;
680 p.TileAt(surface, x, y).type = rock;
683 p.TileAt(surface, x, y).type = mntn;
691 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
692 for (int surface = 0; surface <= 5; ++surface) {
693 for (int y = 0; y < p.SideLength(); ++y) {
694 for (int x = 0; x < p.SideLength(); ++x) {
695 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
696 p.TileAt(surface, x, y).type = surface;
698 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
717 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
718 auto yield = resources.cbegin();
719 for (; yield != resources.cend(); ++yield) {
720 if (yield->resource == r) {
727 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
728 auto best = resources.cend();
729 double best_value = 0.0;
730 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
731 double value = comp.Get(yield->resource);
732 if (value > best_value) {