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