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);
358 const TileType &Planet::TypeAt(int srf, int x, int y) const {
359 return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
362 glm::ivec2 Planet::SurfacePosition(int srf, const glm::dvec3 &pos) const noexcept {
364 PositionToTile(pos[(srf + 0) % 3]),
365 PositionToTile(pos[(srf + 1) % 3]));
368 double Planet::SurfaceElevation(int srf, const glm::dvec3 &pos) const noexcept {
370 ? pos[(srf + 2) % 3] - Radius()
371 : -pos[(srf + 2) % 3] - Radius();
374 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
375 glm::dvec3 center(0.0f);
376 center[(srf + 0) % 3] = x + 0.5 - Radius();
377 center[(srf + 1) % 3] = y + 0.5 - Radius();
378 center[(srf + 2) % 3] = srf < 3 ? (Radius() + e) : -(Radius() + e);
382 void Planet::BuildVAO(const Set<TileType> &ts) {
383 vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
385 vao->BindAttributes();
386 vao->EnableAttribute(0);
387 vao->EnableAttribute(1);
388 vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
389 vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, tex_coord));
390 vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
392 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
393 float offset = Radius();
396 // up +Z +X +Y -Z -X -Y
398 for (int index = 0, surface = 0; surface < 6; ++surface) {
399 for (int y = 0; y < sidelength; ++y) {
400 for (int x = 0; x < sidelength; ++x, ++index) {
401 float tex = ts[TileAt(surface, x, y).type].texture;
402 const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
403 const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
404 attrib[4 * index + 0].position[(surface + 0) % 3] = x + 0 - offset;
405 attrib[4 * index + 0].position[(surface + 1) % 3] = y + 0 - offset;
406 attrib[4 * index + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
407 attrib[4 * index + 0].tex_coord[0] = 0.0f;
408 attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
409 attrib[4 * index + 0].tex_coord[2] = tex;
411 attrib[4 * index + 1].position[(surface + 0) % 3] = x + 0 - offset;
412 attrib[4 * index + 1].position[(surface + 1) % 3] = y + 1 - offset;
413 attrib[4 * index + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
414 attrib[4 * index + 1].tex_coord[0] = 0.0f;
415 attrib[4 * index + 1].tex_coord[1] = tex_v_end;
416 attrib[4 * index + 1].tex_coord[2] = tex;
418 attrib[4 * index + 2].position[(surface + 0) % 3] = x + 1 - offset;
419 attrib[4 * index + 2].position[(surface + 1) % 3] = y + 0 - offset;
420 attrib[4 * index + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
421 attrib[4 * index + 2].tex_coord[0] = 1.0f;
422 attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
423 attrib[4 * index + 2].tex_coord[2] = tex;
425 attrib[4 * index + 3].position[(surface + 0) % 3] = x + 1 - offset;
426 attrib[4 * index + 3].position[(surface + 1) % 3] = y + 1 - offset;
427 attrib[4 * index + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
428 attrib[4 * index + 3].tex_coord[0] = 1.0f;
429 attrib[4 * index + 3].tex_coord[1] = tex_v_end;
430 attrib[4 * index + 3].tex_coord[2] = tex;
436 vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
438 auto element = vao->MapElements(GL_WRITE_ONLY);
440 for (int surface = 0; surface < 3; ++surface) {
441 for (int y = 0; y < sidelength; ++y) {
442 for (int x = 0; x < sidelength; ++x, ++index) {
443 element[6 * index + 0] = 4 * index + 0;
444 element[6 * index + 1] = 4 * index + 2;
445 element[6 * index + 2] = 4 * index + 1;
446 element[6 * index + 3] = 4 * index + 1;
447 element[6 * index + 4] = 4 * index + 2;
448 element[6 * index + 5] = 4 * index + 3;
452 for (int surface = 3; surface < 6; ++surface) {
453 for (int y = 0; y < sidelength; ++y) {
454 for (int x = 0; x < sidelength; ++x, ++index) {
455 element[6 * index + 0] = 4 * index + 0;
456 element[6 * index + 1] = 4 * index + 1;
457 element[6 * index + 2] = 4 * index + 2;
458 element[6 * index + 3] = 4 * index + 2;
459 element[6 * index + 4] = 4 * index + 1;
460 element[6 * index + 5] = 4 * index + 3;
468 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
472 const glm::mat4 &MV = assets.shaders.planet_surface.MV();
473 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f)));
474 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 0);
475 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f)));
476 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 1);
477 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)));
478 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 2);
479 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));
480 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 3);
481 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
482 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 4);
483 assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, -1.0f, 0.0f, 0.0f)));
484 vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 5);
488 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
489 math::SimplexNoise elevation_gen(0);
490 math::SimplexNoise variation_gen(45623752346);
492 const int ice = tiles["ice"].id;
493 const int ocean = tiles["ocean"].id;
494 const int water = tiles["water"].id;
495 const int sand = tiles["sand"].id;
496 const int grass = tiles["grass"].id;
497 const int tundra = tiles["tundra"].id;
498 const int taiga = tiles["taiga"].id;
499 const int desert = tiles["desert"].id;
500 const int mntn = tiles["mountain"].id;
501 const int algae = tiles["algae"].id;
502 const int forest = tiles["forest"].id;
503 const int jungle = tiles["jungle"].id;
504 const int rock = tiles["rock"].id;
505 const int wheat = tiles["wheat"].id;
507 constexpr double ocean_thresh = -0.2;
508 constexpr double water_thresh = 0.0;
509 constexpr double beach_thresh = 0.05;
510 constexpr double highland_thresh = 0.4;
511 constexpr double mountain_thresh = 0.5;
513 const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
514 const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
515 const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
516 const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
517 const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
519 for (int surface = 0; surface <= 5; ++surface) {
520 for (int y = 0; y < p.SideLength(); ++y) {
521 for (int x = 0; x < p.SideLength(); ++x) {
522 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
523 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
524 if (near_axis > cap_thresh) {
525 p.TileAt(surface, x, y).type = ice;
528 float elevation = math::OctaveNoise(
530 to_tile / p.Radius(),
533 5 / p.Radius(), // frequency
537 float variation = math::OctaveNoise(
539 to_tile / p.Radius(),
542 16 / p.Radius(), // frequency
546 if (elevation < ocean_thresh) {
547 p.TileAt(surface, x, y).type = ocean;
548 } else if (elevation < water_thresh) {
549 if (variation > 0.3) {
550 p.TileAt(surface, x, y).type = algae;
552 p.TileAt(surface, x, y).type = water;
554 } else if (elevation < beach_thresh) {
555 p.TileAt(surface, x, y).type = sand;
556 } else if (elevation < highland_thresh) {
557 if (near_axis < equ_thresh) {
558 if (variation > 0.6) {
559 p.TileAt(surface, x, y).type = grass;
560 } else if (variation > 0.2) {
561 p.TileAt(surface, x, y).type = sand;
563 p.TileAt(surface, x, y).type = desert;
565 } else if (near_axis < fzone_start) {
566 if (variation > 0.4) {
567 p.TileAt(surface, x, y).type = forest;
568 } else if (variation < -0.5) {
569 p.TileAt(surface, x, y).type = jungle;
570 } else if (variation > -0.02 && variation < 0.02) {
571 p.TileAt(surface, x, y).type = wheat;
573 p.TileAt(surface, x, y).type = grass;
575 } else if (near_axis < fzone_end) {
576 p.TileAt(surface, x, y).type = tundra;
578 p.TileAt(surface, x, y).type = taiga;
580 } else if (elevation < mountain_thresh) {
581 if (variation > 0.3) {
582 p.TileAt(surface, x, y).type = mntn;
584 p.TileAt(surface, x, y).type = rock;
587 p.TileAt(surface, x, y).type = mntn;
595 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
596 for (int surface = 0; surface <= 5; ++surface) {
597 for (int y = 0; y < p.SideLength(); ++y) {
598 for (int x = 0; x < p.SideLength(); ++x) {
599 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
600 p.TileAt(surface, x, y).type = surface;
602 p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
619 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
620 auto yield = resources.cbegin();
621 for (; yield != resources.cend(); ++yield) {
622 if (yield->resource == r) {
629 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
630 auto best = resources.cend();
631 double best_value = 0.0;
632 for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
633 double value = comp.Get(yield->resource);
634 if (value > best_value) {