]> git.localhorst.tv Git - blobs.git/blob - src/world/world.cpp
overhaul need system
[blobs.git] / src / world / world.cpp
1 #include "Body.hpp"
2 #include "Orbit.hpp"
3 #include "Planet.hpp"
4 #include "Resource.hpp"
5 #include "Set.hpp"
6 #include "Simulation.hpp"
7 #include "Sun.hpp"
8 #include "Tile.hpp"
9 #include "TileType.hpp"
10
11 #include "../app/Assets.hpp"
12 #include "../creature/Composition.hpp"
13 #include "../creature/Creature.hpp"
14 #include "../graphics/Viewport.hpp"
15 #include "../math/const.hpp"
16 #include "../math/OctaveNoise.hpp"
17 #include "../math/SimplexNoise.hpp"
18
19 #include <algorithm>
20 #include <cmath>
21 #include <iostream>
22 #include <glm/gtc/matrix_transform.hpp>
23 #include <glm/gtx/euler_angles.hpp>
24 #include <glm/gtx/io.hpp>
25 #include <glm/gtx/transform.hpp>
26
27 using blobs::G;
28 using blobs::PI_2p0;
29
30 using std::sin;
31 using std::cos;
32 using std::pow;
33 using std::sqrt;
34
35
36 namespace blobs {
37 namespace world {
38
39 Body::Body()
40 : sim(nullptr)
41 , parent(nullptr)
42 , children()
43 , mass(1.0)
44 , radius(1.0)
45 , orbit()
46 , surface_tilt(0.0, 0.0)
47 , axis_tilt(0.0, 0.0)
48 , rotation(0.0)
49 , angular(0.0)
50 , orbital(1.0)
51 , inverse_orbital(1.0)
52 , local(1.0)
53 , inverse_local(1.0)
54 , creatures()
55 , atmosphere(-1) {
56 }
57
58 Body::~Body() {
59         for (creature::Creature *c : creatures) {
60                 delete c;
61         }
62 }
63
64 void Body::SetSimulation(Simulation &s) noexcept {
65         sim = &s;
66         for (auto child : children) {
67                 child->SetSimulation(s);
68         }
69 }
70
71 void Body::SetParent(Body &p) {
72         if (HasParent()) {
73                 UnsetParent();
74         }
75         parent = &p;
76         parent->AddChild(*this);
77 }
78
79 void Body::UnsetParent() {
80         if (!HasParent()) return;
81         parent->RemoveChild(*this);
82         parent = nullptr;
83 }
84
85 void Body::AddChild(Body &c) {
86         children.push_back(&c);
87         c.SetSimulation(*sim);
88 }
89
90 void Body::RemoveChild(Body &c) {
91         auto entry = std::find(children.begin(), children.end(), &c);
92         if (entry != children.end()) {
93                 children.erase(entry);
94         }
95 }
96
97 double Body::Inertia() const noexcept {
98         // assume solid sphere for now
99         return (2.0/5.0) * Mass() * pow(Radius(), 2);
100 }
101
102 double Body::GravitationalParameter() const noexcept {
103         return G * Mass();
104 }
105
106 double Body::OrbitalPeriod() const noexcept {
107         if (parent) {
108                 return PI_2p0 * sqrt(pow(orbit.SemiMajorAxis(), 3) / (G * (parent->Mass() + Mass())));
109         } else {
110                 return 0.0;
111         }
112 }
113
114 double Body::RotationalPeriod() const noexcept {
115         if (std::abs(angular) < std::numeric_limits<double>::epsilon()) {
116                 return std::numeric_limits<double>::infinity();
117         } else {
118                 return PI_2p0 * Inertia() / angular;
119         }
120 }
121
122 glm::dmat4 Body::ToUniverse() const noexcept {
123         glm::dmat4 m(1.0);
124         const Body *b = this;
125         while (b->HasParent()) {
126                 m = b->ToParent() * m;
127                 b = &b->Parent();
128         }
129         return m;
130 }
131
132 glm::dmat4 Body::FromUniverse() const noexcept {
133         glm::dmat4 m(1.0);
134         const Body *b = this;
135         while (b->HasParent()) {
136                 m *= b->FromParent();
137                 b = &b->Parent();
138         }
139         return m;
140 }
141
142 namespace {
143 std::vector<creature::Creature *> ccache;
144 }
145
146 void Body::Tick(double dt) {
147         rotation += dt * AngularMomentum() / Inertia();
148         Cache();
149         ccache = Creatures();
150         for (creature::Creature *c : ccache) {
151                 c->Tick(dt);
152         }
153         for (auto c = Creatures().begin(); c != Creatures().end();) {
154                 if ((*c)->Removable()) {
155                         delete *c;
156                         c = Creatures().erase(c);
157                 } else {
158                         ++c;
159                 }
160         }
161 }
162
163 void Body::Cache() noexcept {
164         if (parent) {
165                 orbital =
166                         orbit.Matrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()))
167                         * glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
168                 inverse_orbital =
169                         glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x)
170                         * orbit.InverseMatrix(PI_2p0 * (GetSimulation().Time() / OrbitalPeriod()));
171         } else {
172                 orbital = glm::eulerAngleXY(axis_tilt.x, axis_tilt.y);
173                 inverse_orbital = glm::eulerAngleYX(-axis_tilt.y, -axis_tilt.x);
174         }
175         local =
176                 glm::eulerAngleY(rotation)
177                 * glm::eulerAngleXY(surface_tilt.x, surface_tilt.y);
178         inverse_local =
179                 glm::eulerAngleYX(-surface_tilt.y, -surface_tilt.x)
180                 * glm::eulerAngleY(-rotation);
181 }
182
183 void Body::AddCreature(creature::Creature *c) {
184         creatures.push_back(c);
185 }
186
187 void Body::RemoveCreature(creature::Creature *c) {
188         auto entry = std::find(creatures.begin(), creatures.end(), c);
189         if (entry != creatures.end()) {
190                 creatures.erase(entry);
191         }
192 }
193
194
195 Orbit::Orbit()
196 : sma(1.0)
197 , ecc(0.0)
198 , inc(0.0)
199 , asc(0.0)
200 , arg(0.0)
201 , mna(0.0) {
202 }
203
204 Orbit::~Orbit() {
205 }
206
207 double Orbit::SemiMajorAxis() const noexcept {
208         return sma;
209 }
210
211 Orbit &Orbit::SemiMajorAxis(double s) noexcept {
212         sma = s;
213         return *this;
214 }
215
216 double Orbit::Eccentricity() const noexcept {
217         return ecc;
218 }
219
220 Orbit &Orbit::Eccentricity(double e) noexcept {
221         ecc = e;
222         return *this;
223 }
224
225 double Orbit::Inclination() const noexcept {
226         return inc;
227 }
228
229 Orbit &Orbit::Inclination(double i) noexcept {
230         inc = i;
231         return *this;
232 }
233
234 double Orbit::LongitudeAscending() const noexcept {
235         return asc;
236 }
237
238 Orbit &Orbit::LongitudeAscending(double l) noexcept {
239         asc = l;
240         return *this;
241 }
242
243 double Orbit::ArgumentPeriapsis() const noexcept {
244         return arg;
245 }
246
247 Orbit &Orbit::ArgumentPeriapsis(double a) noexcept {
248         arg = a;
249         return *this;
250 }
251
252 double Orbit::MeanAnomaly() const noexcept {
253         return mna;
254 }
255
256 Orbit &Orbit::MeanAnomaly(double m) noexcept {
257         mna = m;
258         return *this;
259 }
260
261 namespace {
262
263 double mean2eccentric(double M, double e) {
264         double E = M; // eccentric anomaly, solve M = E - e sin E
265         // limit to 100 steps to prevent deadlocks in impossible situations
266         for (int i = 0; i < 100; ++i) {
267                 double dE = (E - e * sin(E) - M) / (1 - e * cos(E));
268                 E -= dE;
269                 if (abs(dE) < 1.0e-6) break;
270         }
271         return E;
272 }
273
274 }
275
276 glm::dmat4 Orbit::Matrix(double t) const noexcept {
277         double M = mna + t;
278         double E = mean2eccentric(M, ecc);
279
280         // coordinates in orbital plane, P=x, Q=-z
281         double P = sma * (cos(E) - ecc);
282         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
283
284         return glm::yawPitchRoll(asc, inc, arg) * glm::translate(glm::dvec3(P, 0.0, -Q));
285 }
286
287 glm::dmat4 Orbit::InverseMatrix(double t) const noexcept {
288         double M = mna + t;
289         double E = mean2eccentric(M, ecc);
290         double P = sma * (cos(E) - ecc);
291         double Q = sma * sin(E) * sqrt(1 - (ecc * ecc));
292         return glm::translate(glm::dvec3(-P, 0.0, Q)) * glm::transpose(glm::yawPitchRoll(asc, inc, arg));
293 }
294
295
296 Planet::Planet(int sidelength)
297 : Body()
298 , sidelength(sidelength)
299 , tiles(TilesTotal())
300 , vao() {
301         Radius(double(sidelength) / 2.0);
302 }
303
304 Planet::~Planet() {
305 }
306
307 const TileType &Planet::TypeAt(int srf, int x, int y) const {
308         return GetSimulation().TileTypes()[TileAt(srf, x, y).type];
309 }
310
311 glm::ivec2 Planet::SurfacePosition(int srf, const glm::dvec3 &pos) const noexcept {
312         return glm::ivec2(
313                 PositionToTile(pos[(srf + 0) % 3]),
314                 PositionToTile(pos[(srf + 1) % 3]));
315 }
316
317 double Planet::SurfaceElevation(int srf, const glm::dvec3 &pos) const noexcept {
318         return srf < 3
319                 ? pos[(srf + 2) % 3] - Radius()
320                 : -pos[(srf + 2) % 3] - Radius();
321 }
322
323 glm::dvec3 Planet::TileCenter(int srf, int x, int y, double e) const noexcept {
324         glm::dvec3 center(0.0f);
325         center[(srf + 0) % 3] = x + 0.5 - Radius();
326         center[(srf + 1) % 3] = y + 0.5 - Radius();
327         center[(srf + 2) % 3] = srf < 3 ? (Radius() + e) : -(Radius() + e);
328         return center;
329 }
330
331 void Planet::BuildVAO(const Set<TileType> &ts) {
332         vao.reset(new graphics::SimpleVAO<Attributes, unsigned int>);
333         vao->Bind();
334         vao->BindAttributes();
335         vao->EnableAttribute(0);
336         vao->EnableAttribute(1);
337         vao->AttributePointer<glm::vec3>(0, false, offsetof(Attributes, position));
338         vao->AttributePointer<glm::vec3>(1, false, offsetof(Attributes, tex_coord));
339         vao->ReserveAttributes(TilesTotal() * 4, GL_STATIC_DRAW);
340         {
341                 auto attrib = vao->MapAttributes(GL_WRITE_ONLY);
342                 float offset = Radius();
343
344                 // srf  0  1  2  3  4  5
345                 //  up +Z +X +Y -Z -X -Y
346
347                 for (int index = 0, surface = 0; surface < 6; ++surface) {
348                         for (int y = 0; y < sidelength; ++y) {
349                                 for (int x = 0; x < sidelength; ++x, ++index) {
350                                         float tex = ts[TileAt(surface, x, y).type].texture;
351                                         const float tex_v_begin = surface < 3 ? 1.0f : 0.0f;
352                                         const float tex_v_end = surface < 3 ? 0.0f : 1.0f;
353                                         attrib[4 * index + 0].position[(surface + 0) % 3] = x + 0 - offset;
354                                         attrib[4 * index + 0].position[(surface + 1) % 3] = y + 0 - offset;
355                                         attrib[4 * index + 0].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
356                                         attrib[4 * index + 0].tex_coord[0] = 0.0f;
357                                         attrib[4 * index + 0].tex_coord[1] = tex_v_begin;
358                                         attrib[4 * index + 0].tex_coord[2] = tex;
359
360                                         attrib[4 * index + 1].position[(surface + 0) % 3] = x + 0 - offset;
361                                         attrib[4 * index + 1].position[(surface + 1) % 3] = y + 1 - offset;
362                                         attrib[4 * index + 1].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
363                                         attrib[4 * index + 1].tex_coord[0] = 0.0f;
364                                         attrib[4 * index + 1].tex_coord[1] = tex_v_end;
365                                         attrib[4 * index + 1].tex_coord[2] = tex;
366
367                                         attrib[4 * index + 2].position[(surface + 0) % 3] = x + 1 - offset;
368                                         attrib[4 * index + 2].position[(surface + 1) % 3] = y + 0 - offset;
369                                         attrib[4 * index + 2].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
370                                         attrib[4 * index + 2].tex_coord[0] = 1.0f;
371                                         attrib[4 * index + 2].tex_coord[1] = tex_v_begin;
372                                         attrib[4 * index + 2].tex_coord[2] = tex;
373
374                                         attrib[4 * index + 3].position[(surface + 0) % 3] = x + 1 - offset;
375                                         attrib[4 * index + 3].position[(surface + 1) % 3] = y + 1 - offset;
376                                         attrib[4 * index + 3].position[(surface + 2) % 3] = surface < 3 ? offset : -offset;
377                                         attrib[4 * index + 3].tex_coord[0] = 1.0f;
378                                         attrib[4 * index + 3].tex_coord[1] = tex_v_end;
379                                         attrib[4 * index + 3].tex_coord[2] = tex;
380                                 }
381                         }
382                 }
383         }
384         vao->BindElements();
385         vao->ReserveElements(TilesTotal() * 6, GL_STATIC_DRAW);
386         {
387                 auto element = vao->MapElements(GL_WRITE_ONLY);
388                 int index = 0;
389                 for (int surface = 0; surface < 3; ++surface) {
390                         for (int y = 0; y < sidelength; ++y) {
391                                 for (int x = 0; x < sidelength; ++x, ++index) {
392                                         element[6 * index + 0] = 4 * index + 0;
393                                         element[6 * index + 1] = 4 * index + 2;
394                                         element[6 * index + 2] = 4 * index + 1;
395                                         element[6 * index + 3] = 4 * index + 1;
396                                         element[6 * index + 4] = 4 * index + 2;
397                                         element[6 * index + 5] = 4 * index + 3;
398                                 }
399                         }
400                 }
401                 for (int surface = 3; surface < 6; ++surface) {
402                         for (int y = 0; y < sidelength; ++y) {
403                                 for (int x = 0; x < sidelength; ++x, ++index) {
404                                         element[6 * index + 0] = 4 * index + 0;
405                                         element[6 * index + 1] = 4 * index + 1;
406                                         element[6 * index + 2] = 4 * index + 2;
407                                         element[6 * index + 3] = 4 * index + 2;
408                                         element[6 * index + 4] = 4 * index + 1;
409                                         element[6 * index + 5] = 4 * index + 3;
410                                 }
411                         }
412                 }
413         }
414         vao->Unbind();
415 }
416
417 void Planet::Draw(app::Assets &assets, graphics::Viewport &viewport) {
418         if (!vao) return;
419
420         vao->Bind();
421         const glm::mat4 &MV = assets.shaders.planet_surface.MV();
422         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f)));
423         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 0);
424         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(1.0f, 0.0f, 0.0f, 0.0f)));
425         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 1);
426         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)));
427         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 2);
428         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)));
429         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 3);
430         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)));
431         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 4);
432         assets.shaders.planet_surface.SetNormal(glm::vec3(MV * glm::vec4(0.0f, -1.0f, 0.0f, 0.0f)));
433         vao->DrawTriangles(TilesPerSurface() * 6, TilesPerSurface() * 6 * 5);
434 }
435
436
437 void GenerateEarthlike(const Set<TileType> &tiles, Planet &p) noexcept {
438         math::SimplexNoise elevation_gen(0);
439         math::SimplexNoise variation_gen(45623752346);
440
441         const int ice = tiles["ice"].id;
442         const int ocean = tiles["ocean"].id;
443         const int water = tiles["water"].id;
444         const int sand = tiles["sand"].id;
445         const int grass = tiles["grass"].id;
446         const int tundra = tiles["tundra"].id;
447         const int taiga = tiles["taiga"].id;
448         const int desert = tiles["desert"].id;
449         const int mntn = tiles["mountain"].id;
450         const int algae = tiles["algae"].id;
451         const int forest = tiles["forest"].id;
452         const int jungle = tiles["jungle"].id;
453         const int rock = tiles["rock"].id;
454         const int wheat = tiles["wheat"].id;
455
456         constexpr double ocean_thresh = -0.2;
457         constexpr double water_thresh = 0.0;
458         constexpr double beach_thresh = 0.05;
459         constexpr double highland_thresh = 0.4;
460         constexpr double mountain_thresh = 0.5;
461
462         const glm::dvec3 axis(glm::dvec4(0.0, 1.0, 0.0, 0.0) * glm::eulerAngleXY(p.SurfaceTilt().x, p.SurfaceTilt().y));
463         const double cap_thresh = std::abs(std::cos(p.AxialTilt().x));
464         const double equ_thresh = std::abs(std::sin(p.AxialTilt().x)) / 2.0;
465         const double fzone_start = equ_thresh - (equ_thresh - cap_thresh) / 3.0;
466         const double fzone_end = cap_thresh + (equ_thresh - cap_thresh) / 3.0;
467
468         for (int surface = 0; surface <= 5; ++surface) {
469                 for (int y = 0; y < p.SideLength(); ++y) {
470                         for (int x = 0; x < p.SideLength(); ++x) {
471                                 glm::dvec3 to_tile = p.TileCenter(surface, x, y);
472                                 double near_axis = std::abs(glm::dot(glm::normalize(to_tile), axis));
473                                 if (near_axis > cap_thresh) {
474                                         p.TileAt(surface, x, y).type = ice;
475                                         continue;
476                                 }
477                                 float elevation = math::OctaveNoise(
478                                         elevation_gen,
479                                         to_tile / p.Radius(),
480                                         3,   // octaves
481                                         0.5, // persistence
482                                         5 / p.Radius(), // frequency
483                                         2,   // amplitude
484                                         2    // growth
485                                 );
486                                 float variation = math::OctaveNoise(
487                                         variation_gen,
488                                         to_tile / p.Radius(),
489                                         3,   // octaves
490                                         0.5, // persistence
491                                         16 / p.Radius(), // frequency
492                                         2,   // amplitude
493                                         2    // growth
494                                 );
495                                 if (elevation < ocean_thresh) {
496                                         p.TileAt(surface, x, y).type = ocean;
497                                 } else if (elevation < water_thresh) {
498                                         if (variation > 0.3) {
499                                                 p.TileAt(surface, x, y).type = algae;
500                                         } else {
501                                                 p.TileAt(surface, x, y).type = water;
502                                         }
503                                 } else if (elevation < beach_thresh) {
504                                         p.TileAt(surface, x, y).type = sand;
505                                 } else if (elevation < highland_thresh) {
506                                         if (near_axis < equ_thresh) {
507                                                 if (variation > 0.6) {
508                                                         p.TileAt(surface, x, y).type = grass;
509                                                 } else if (variation > 0.2) {
510                                                         p.TileAt(surface, x, y).type = sand;
511                                                 } else {
512                                                         p.TileAt(surface, x, y).type = desert;
513                                                 }
514                                         } else if (near_axis < fzone_start) {
515                                                 if (variation > 0.4) {
516                                                         p.TileAt(surface, x, y).type = forest;
517                                                 } else if (variation < -0.5) {
518                                                         p.TileAt(surface, x, y).type = jungle;
519                                                 } else if (variation > -0.02 && variation < 0.02) {
520                                                         p.TileAt(surface, x, y).type = wheat;
521                                                 } else {
522                                                         p.TileAt(surface, x, y).type = grass;
523                                                 }
524                                         } else if (near_axis < fzone_end) {
525                                                 p.TileAt(surface, x, y).type = tundra;
526                                         } else {
527                                                 p.TileAt(surface, x, y).type = taiga;
528                                         }
529                                 } else if (elevation < mountain_thresh) {
530                                         if (variation > 0.3) {
531                                                 p.TileAt(surface, x, y).type = mntn;
532                                         } else {
533                                                 p.TileAt(surface, x, y).type = rock;
534                                         }
535                                 } else {
536                                         p.TileAt(surface, x, y).type = mntn;
537                                 }
538                         }
539                 }
540         }
541         p.BuildVAO(tiles);
542 }
543
544 void GenerateTest(const Set<TileType> &tiles, Planet &p) noexcept {
545         for (int surface = 0; surface <= 5; ++surface) {
546                 for (int y = 0; y < p.SideLength(); ++y) {
547                         for (int x = 0; x < p.SideLength(); ++x) {
548                                 if (x == p.SideLength() / 2 && y == p.SideLength() / 2) {
549                                         p.TileAt(surface, x, y).type = surface;
550                                 } else {
551                                         p.TileAt(surface, x, y).type = (x == p.SideLength()/2) + (y == p.SideLength()/2) + 6;
552                                 }
553                         }
554                 }
555         }
556         p.BuildVAO(tiles);
557 }
558
559
560 Sun::Sun()
561 : Body() {
562 }
563
564 Sun::~Sun() {
565 }
566
567
568 std::vector<TileType::Yield>::const_iterator TileType::FindResource(int r) const {
569         auto yield = resources.cbegin();
570         for (; yield != resources.cend(); ++yield) {
571                 if (yield->resource == r) {
572                         break;
573                 }
574         }
575         return yield;
576 }
577
578 std::vector<TileType::Yield>::const_iterator TileType::FindBestResource(const creature::Composition &comp) const {
579         auto best = resources.cend();
580         double best_value = 0.0;
581         for (auto yield = resources.cbegin(); yield != resources.cend(); ++yield) {
582                 double value = comp.Get(yield->resource);
583                 if (value > best_value) {
584                         best = yield;
585                         best_value = value;
586                 }
587         }
588         return best;
589 }
590
591 }
592 }