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>
48 , surface_tilt(0.0, 0.0)
53 , inverse_orbital(1.0)
63 void Body::SetSimulation(Simulation &s) noexcept {
65 for (auto child : children) {
66 child->SetSimulation(s);
70 void Body::SetParent(Body &p) {
75 parent->AddChild(*this);
78 void Body::UnsetParent() {
79 if (!HasParent()) return;
80 parent->RemoveChild(*this);
84 void Body::AddChild(Body &c) {
85 children.push_back(&c);
86 c.SetSimulation(*sim);
89 void Body::RemoveChild(Body &c) {
90 auto entry = std::find(children.begin(), children.end(), &c);
91 if (entry != children.end()) {
92 children.erase(entry);
96 double Body::Inertia() const noexcept {
97 // assume solid sphere for now
98 return (2.0/5.0) * Mass() * pow(Radius(), 2);
101 double Body::GravitationalParameter() const noexcept {
105 double Body::OrbitalPeriod() const noexcept {
107 return PI_2p0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
113 double Body::RotationalPeriod() const noexcept {
114 if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
115 return std::numeric_limits<double>::infinity();
117 return PI_2p0 * Inertia() / angular;
121 glm::dmat4 Body::ToUniverse() const noexcept {
123 const Body *b = this;
124 while (b->HasParent()) {
125 m = b->ToParent() * m;
131 glm::dmat4 Body::FromUniverse() const noexcept {
133 const Body *b = this;
134 while (b->HasParent()) {
135 m *= b->FromParent();
142 std::vector<creature::Creature *> ccache;
143 std::vector<CreatureCreatureCollision> collisions;
146 void Body::Tick(double dt) {
147 rotation += dt * AngularMomentum() / Inertia();
149 ccache = Creatures();
150 for (creature::Creature *c : ccache) {
153 // first remove creatures so they don't collide
154 for (auto c = Creatures().begin(); c != Creatures().end();) {
155 if ((*c)->Removable()) {
157 c = Creatures().erase(c);
165 void Body::Cache() noexcept {
168 orbit.Matrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()))
169 * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
171 glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
172 * orbit.InverseMatrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()));
174 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
175 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
178 glm::eulerAngleY(rotation)
179 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
181 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
182 * glm::eulerAngleY(-rotation);
185 void Body::CheckCollision() noexcept {
186 if (Creatures().size() < 2) return;
188 auto end = Creatures().end();
189 for (auto i = Creatures().begin(); i != end; ++i) {
190 math::AABB i_box((*i)->CollisionBox());
191 glm::dmat4 i_mat((*i)->CollisionTransform());
192 for (auto j = (i + 1); j != end; ++j) {
193 glm::dvec3 diff((*i)->GetSituation().Position() - (*j)->GetSituation().Position());
194 double max_dist = ((*i)->Size() + (*j)->Size()) * 1.74;
195 if (length2(diff) > max_dist * max_dist) continue;
196 math::AABB j_box((*j)->CollisionBox());
197 glm::dmat4 j_mat((*j)->CollisionTransform());
200 if (Intersect(i_box, i_mat, j_box, j_mat, normal, depth)) {
201 collisions.push_back({ **i, **j, normal, depth });
205 for (auto &c : collisions) {
206 c.A().GetSituation().Move(c.Normal() * (c.Depth() * -0.5));
207 c.B().GetSituation().Move(c.Normal() * (c.Depth() * 0.5));
208 c.A().GetSituation().Accelerate(c.Normal() * -dot(c.Normal(), c.AVel()));
209 c.B().GetSituation().Accelerate(c.Normal() * -dot(c.Normal(), c.BVel()));
210 // TODO: notify participants so they can be annoyed
214 void Body::AddCreature(creature::Creature *c) {
215 creatures.push_back(c);
218 void Body::RemoveCreature(creature::Creature *c) {
219 auto entry = std::find(creatures.begin(), creatures.end(), c);
220 if (entry != creatures.end()) {
221 creatures.erase(entry);
226 CreatureCreatureCollision::~CreatureCreatureCollision() {
229 const glm::dvec3 &CreatureCreatureCollision::APos() const noexcept {
230 return a->GetSituation().Position();
233 const glm::dvec3 &CreatureCreatureCollision::AVel() const noexcept {
234 return a->GetSituation().Velocity();
237 const glm::dvec3 &CreatureCreatureCollision::BPos() const noexcept {
238 return b->GetSituation().Position();
241 const glm::dvec3 &CreatureCreatureCollision::BVel() const noexcept {
242 return b->GetSituation().Velocity();
258 double Orbit::SemiMajorAxis() const noexcept {
262 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
267 double Orbit::Eccentricity() const noexcept {
271 Orbit &Orbit::Eccentricity(double e) noexcept {
276 double Orbit::Inclination() const noexcept {
280 Orbit &Orbit::Inclination(double i) noexcept {
285 double Orbit::LongitudeAscending() const noexcept {
289 Orbit &Orbit::LongitudeAscending(double l) noexcept {
294 double Orbit::ArgumentPeriapsis() const noexcept {
298 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
303 double Orbit::MeanAnomaly() const noexcept {
307 Orbit &Orbit::MeanAnomaly(double m) noexcept {
314 double mean2eccentric(double M, double e) {
315 double E = M; // eccentric anomaly, solve M = E - e sin E
316 // limit to 100 steps to prevent deadlocks in impossible situations
317 for (int i = 0; i < 100; ++i) {
318 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
320 if (abs(dE) < 1.0e-6) break;
327 glm::dmat4 Orbit::Matrix(double t) const noexcept {
329 double E = mean2eccentric(M, ecc);
331 // coordinates in orbital plane, P=x, Q=-z
332 double P = sma * (cos(E) - ecc);
333 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
335 return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
338 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
340 double E = mean2eccentric(M, ecc);
341 double P = sma * (cos(E) - ecc);
342 double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
343 return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
347 Planet::Planet(int sidelength)
349 , sidelength(sidelength)
350 , tiles(TilesTotal())
352 Radius(double(sidelength) / 2.0);
359 /// map p onto cube, s gives the surface, u and v the position in [-1,1]
360 void cubemap(const glm::dvec3 &p, int &s, double &u, double &v) noexcept {
361 const glm::dvec3 p_abs(abs(p));
362 const glm::bvec3 p_pos(greaterThan(p, glm::dvec3(0.0)));
363 double max_axis = 0.0;
365 if (p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
371 if (!p_pos.x && p_abs.x >= p_abs.y && p_abs.x >= p_abs.z) {
377 if (p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
383 if (!p_pos.y && p_abs.y >= p_abs.x && p_abs.y >= p_abs.z) {
389 if (p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
395 if (!p_pos.z && p_abs.z >= p_abs.x && p_abs.z >= p_abs.y) {
404 /// get p from cube, s being surface, u and v the position in [-1,1],
405 /// gives a vector from the center to the surface
406 glm::dvec3 cubeunmap(int s, double u, double v) {
409 case 0: return glm::dvec3(u, v, 1.0); // +Z
410 case 1: return glm::dvec3(1.0, u, v); // +X
411 case 2: return glm::dvec3(v, 1.0, u); // +Y
412 case 3: return glm::dvec3(-u, -v, -1.0); // -Z
413 case 4: return glm::dvec3(-1.0, -u, -v); // -X
414 case 5: return glm::dvec3(-v, -1.0, -u); // -Y
419 Tile &Planet::TileAt(const glm::dvec3 &p) noexcept {
423 cubemap(p, srf, u, v);
424 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
425 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
426 return TileAt(srf, x, y);
429 const Tile &Planet::TileAt(const glm::dvec3 &p) const noexcept {
433 cubemap(p, srf, u, v);
434 int x = glm::clamp(int(u * Radius() + Radius()), 0, sidelength - 1);
435 int y = glm::clamp(int(v * Radius() + Radius()), 0, sidelength - 1);
436 return TileAt(srf, x, y);
439 const TileType &Planet::TileTypeAt(const glm::dvec3 &p) const noexcept {
440 return GetSimulation().TileTypes()[TileAt(p).type];
443 Tile &Planet::TileAt(int surface, int x, int y) noexcept {
444 return tiles[IndexOf(surface, x, y)];
447 const Tile &Planet::TileAt(int surface, int x, int y) const noexcept {
448 return tiles[IndexOf(surface, x, y)];
451 const TileType &Planet::TypeAt(int srf, int x, int y) const noexcept {
452 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
455 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
456 double u = (double(x) - Radius() + 0.5) / Radius();
457 double v = (double(y) - Radius() + 0.5) / Radius();
458 return normalize(cubeunmap(srf, u, v)) * (Radius() + e);
461 void Planet::BuildVAO(const Set<TileType> &ts) {
462 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
464 vao->BindAttributes();
465 vao->EnableAttribute(0);
466 vao->EnableAttribute(1);
467 vao->EnableAttribute(2);
468 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
469 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, normal));
470 vao->AttributePointer<glm::vec3>(2, false, offsetof(Attributes, tex_coord));
471 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
473 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
474 float offset = Radius();
477 // up +Z +X +Y -Z -X -Y
479 for (int index = 0, surface = 0; surface < 6; ++surface) {
480 for (int y = 0; y < sidelength; ++y) {
481 for (int x = 0; x < sidelength; ++x, ++index) {
483 pos[0][(surface + 0) % 3] = x + 0 - offset;
484 pos[0][(surface + 1) % 3] = y + 0 - offset;
485 pos[0][(surface + 2) % 3] = offset;
486 pos[1][(surface + 0) % 3] = x + 0 - offset;
487 pos[1][(surface + 1) % 3] = y + 1 - offset;
488 pos[1][(surface + 2) % 3] = offset;
489 pos[2][(surface + 0) % 3] = x + 1 - offset;
490 pos[2][(surface + 1) % 3] = y + 0 - offset;
491 pos[2][(surface + 2) % 3] = offset;
492 pos[3][(surface + 0) % 3] = x + 1 - offset;
493 pos[3][(surface + 1) % 3] = y + 1 - offset;
494 pos[3][(surface + 2) % 3] = offset;
496 float tex = ts[TileAt(surface, x, y).type].texture;
497 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
498 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
500 attrib[4 * index + 0].position = normalize(pos[0]) * (surface < 3 ? offset : -offset);
501 attrib[4 * index + 0].normal = pos[0];
502 attrib[4 * index + 0].tex_coord[0] = 0.0f;
503 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
504 attrib[4 * index + 0].tex_coord[2] = tex;
506 attrib[4 * index + 1].position = normalize(pos[1]) * (surface < 3 ? offset : -offset);
507 attrib[4 * index + 1].normal = pos[1];
508 attrib[4 * index + 1].tex_coord[0] = 0.0f;
509 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
510 attrib[4 * index + 1].tex_coord[2] = tex;
512 attrib[4 * index + 2].position = normalize(pos[2]) * (surface < 3 ? offset : -offset);
513 attrib[4 * index + 2].normal = pos[2];
514 attrib[4 * index + 2].tex_coord[0] = 1.0f;
515 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
516 attrib[4 * index + 2].tex_coord[2] = tex;
518 attrib[4 * index + 3].position = normalize(pos[3]) * (surface < 3 ? offset : -offset);
519 attrib[4 * index + 3].normal = pos[3];
520 attrib[4 * index + 3].tex_coord[0] = 1.0f;
521 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
522 attrib[4 * index + 3].tex_coord[2] = tex;
528 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
530 auto element = vao->MapElements(GL_WRITE_ONLY);
532 for (int surface = 0; surface < 3; ++surface) {
533 for (int y = 0; y < sidelength; ++y) {
534 for (int x = 0; x < sidelength; ++x, ++index) {
535 element[6 * index + 0] = 4 * index + 0;
536 element[6 * index + 1] = 4 * index + 2;
537 element[6 * index + 2] = 4 * index + 1;
538 element[6 * index + 3] = 4 * index + 1;
539 element[6 * index + 4] = 4 * index + 2;
540 element[6 * index + 5] = 4 * index + 3;
544 for (int surface = 3; surface < 6; ++surface) {
545 for (int y = 0; y < sidelength; ++y) {
546 for (int x = 0; x < sidelength; ++x, ++index) {
547 element[6 * index + 0] = 4 * index + 0;
548 element[6 * index + 1] = 4 * index + 1;
549 element[6 * index + 2] = 4 * index + 2;
550 element[6 * index + 3] = 4 * index + 2;
551 element[6 * index + 4] = 4 * index + 1;
552 element[6 * index + 5] = 4 * index + 3;
560 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
564 vao->DrawTriangles(TilesTotal() * 6);
568 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
569 math::SimplexNoise elevation_gen(0);
570 math::SimplexNoise variation_gen(45623752346);
572 const int ice = tiles["ice"].id;
573 const int ocean = tiles["ocean"].id;
574 const int water = tiles["water"].id;
575 const int sand = tiles["sand"].id;
576 const int grass = tiles["grass"].id;
577 const int tundra = tiles["tundra"].id;
578 const int taiga = tiles["taiga"].id;
579 const int desert = tiles["desert"].id;
580 const int mntn = tiles["mountain"].id;
581 const int algae = tiles["algae"].id;
582 const int forest = tiles["forest"].id;
583 const int jungle = tiles["jungle"].id;
584 const int rock = tiles["rock"].id;
585 const int wheat = tiles["wheat"].id;
587 constexpr double ocean_thresh = -0.2;
588 constexpr double water_thresh = 0.0;
589 constexpr double beach_thresh = 0.05;
590 constexpr double highland_thresh = 0.4;
591 constexpr double mountain_thresh = 0.5;
593 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
594 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
595 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
596 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
597 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
599 for (int surface = 0; surface <= 5; ++surface) {
600 for (int y = 0; y < p.SideLength(); ++y) {
601 for (int x = 0; x < p.SideLength(); ++x) {
602 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
603 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
604 if (near_axis > cap_thresh) {
605 p.TileAt(surface, x, y).type = ice;
608 float elevation = math::OctaveNoise(
610 to_tile / p.Radius(),
613 5 / p.Radius(), // frequency
617 float variation = math::OctaveNoise(
619 to_tile / p.Radius(),
622 16 / p.Radius(), // frequency
626 if (elevation < ocean_thresh) {
627 p.TileAt(surface, x, y).type = ocean;
628 } else if (elevation < water_thresh) {
629 if (variation > 0.3) {
630 p.TileAt(surface, x, y).type = algae;
632 p.TileAt(surface, x, y).type = water;
634 } else if (elevation < beach_thresh) {
635 p.TileAt(surface, x, y).type = sand;
636 } else if (elevation < highland_thresh) {
637 if (near_axis < equ_thresh) {
638 if (variation > 0.6) {
639 p.TileAt(surface, x, y).type = grass;
640 } else if (variation > 0.2) {
641 p.TileAt(surface, x, y).type = sand;
643 p.TileAt(surface, x, y).type = desert;
645 } else if (near_axis < fzone_start) {
646 if (variation > 0.4) {
647 p.TileAt(surface, x, y).type = forest;
648 } else if (variation < -0.5) {
649 p.TileAt(surface, x, y).type = jungle;
650 } else if (variation > -0.02 && variation < 0.02) {
651 p.TileAt(surface, x, y).type = wheat;
653 p.TileAt(surface, x, y).type = grass;
655 } else if (near_axis < fzone_end) {
656 p.TileAt(surface, x, y).type = tundra;
658 p.TileAt(surface, x, y).type = taiga;
660 } else if (elevation < mountain_thresh) {
661 if (variation > 0.3) {
662 p.TileAt(surface, x, y).type = mntn;
664 p.TileAt(surface, x, y).type = rock;
667 p.TileAt(surface, x, y).type = mntn;
675 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
676 for (int surface = 0; surface <= 5; ++surface) {
677 for (int y = 0; y < p.SideLength(); ++y) {
678 for (int x = 0; x < p.SideLength(); ++x) {
679 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
680 p.TileAt(surface, x, y).type = surface;
682 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
699 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
700 auto yield = resources.cbegin();
701 for (; yield != resources.cend(); ++yield) {
702 if (yield->resource == r) {
709 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
710 auto best = resources.cend();
711 double best_value = 0.0;
712 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
713 double value = comp.Get(yield->resource);
714 if (value > best_value) {