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