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