forked from Lasercake/Lasercake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtile_physics.cpp
1867 lines (1646 loc) · 93.5 KB
/
tile_physics.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#include "world.hpp"
#include "tile_physics.hpp"
#include "data_structures/deque.hpp"
#include <queue>
/*
This file describes the tile-based physics system.
We use a 3D grid of tiles for some parts of our physics.
The main tile-based part of the physics is FLUID MOTION.
Real-life fluid motion is very complicated, so we use a wide variety of
simplifications in order to simulate it quickly on a large scale.
There are also many rules to cover specific situations; this comment will be
a general overview, not a complete description. Comments elsewhere in the file
describe the nature and purpose of some of those specific rules.
=== OVERVIEW ===
Each tile is a solid mass of some type of substance (rock, water, air, etc);
When they move, they move by exactly an entire tile at a time, and swap with
whatever substance was in the other tile.
Fluid tiles carry a "velocity" with them, which is fairly self-explanatory.
In order to reconcile the fine-grained velocity with the granular tile movement,
fluid tiles also carry "progress" in each of the six directions - when the
progress exceeds a certain threshold, the tile makes a step in that direction.
A tile can have 'progress' in two opposite directions at once.
When a tile runs into something that it can't pass, it gets blocked, and loses
most of its velocity in that direction. Also, if there's room for it to
go past the blocking tile diagonally, then the amount of excess "progress"
that was blocked gets added to its "progress" in each of the four perpendicular
directions. Tiles can't actually move diagonally, but the perpendicular progress
will eventually build up to be enough to move it into the corner, whereupon
its original velocity/progress in the original direction will carry it around
the corner. I call this rule the "fall off pillars" rule, because its original
purpose was to make it so that a stack of single tiles of water wouldn't
stay stacked.
When a tile makes a step in a direction, the threshold amount is subtracted
from its progress in that direction. Lingering progress in unused directions
decays over time.
For some fluids, that's it. Sand is considered a fluid, and it obeys only
the above rules. It falls down due to gravity, and pours off shallow slopes,
but even if there's a huge pile of sand in one side of a J tube, it won't
go up the other side of the J tube, because it doesn't consider pressure.
The main exception is water, which has lots of special rules to deal with
pressure. We mark some water as "groupable", and we keep caches of water
"groups" - masses of "groupable water" that are conneced through direct
cardinal-direction adjacency. And we compute the "pressure" at each level
from the depth of tiles in the group, and at each open surface, we push
water out, and at the top surfaces, we pull water in to replace it.
For optimization, we merely keep a list (actually a hash table from
location to active fluid info) of the active fluid tiles, with their velocity
and progress and stuff. And we carefully remove tiles from the list when
they become inactive, so that our basic computations are no slower than
linear in the number of tiles that are *actually* moving.
=== GROUPS AND PRESSURE: RULES ===
Tiles at the top of a group, which have fallen enough to run into the
next tile down, are considered "suckable".
Air tiles just outside the mass of a group are considered "pushable".
Whenever a single group has pushable and suckable tiles at the same time,
if the pushable tiles are at a lower height than the suckable tiles,
it immediately teleports the topmost suckable waters to the locations of the
bottommost pushable tiles until it's in a stable situation again.
If there's a tile that *would* be pushable but has a fluid tile in it, that
fluid tile gets a velocity related to the pressure at its height.
(This is actually done in the external fluid tile's computation, not the
group's computation. In fact, groups themselves never do any computation per
frame; they just react to things that happen around them.)
There's one catch here: If all water was groupable all the time, a weird
thing would happen when you tried to dump a large lake through a small tube
into an open area. When it first came out of the small tube, it would move
slowly, because the tube only had a small surface area. But when it had gotten
out a little, it would suddenly have more surface area, and shed water much
faster. So there would be a slowly building explosion, which is nothing like
the way water works in real life.
To avoid that, we make it so that water that's *moving* fast enough
is marked not-groupable. So as it pours out of a hole, it becomes ungroupable
until later, and never allows the group to dump its high pressure onto any
tile except the ones right at the mouth of the tube.
So, in the J-tube situation, here's what happens.
The lower end has pushable tiles, and the higher end has suckable tiles,
so it pushes a lot of water out the lower end. That water is probably moving
quickly upwards. So it's not groupable right away. As soon as it moves one
tile upwards, though, it frees up the space it was at, and if there are
suckable tiles left, those spaces are refilled again. And the water moving
upwards eventually stops due to gravity and becomes groupable. This continues
until the tube has levelled off.
=== GROUPS AND PRESSURE: HOW THE CACHING WORKS ===
We don't keep a cache of all the internal tiles of a group. In fact, our
algorithms are designed so that we never have to do any computation for
the interior tiles at all; the worst-case computation issues are only
proportional to the surface area (including water-to-rock surfaces) of
the group. Typical-use cases are proportional to the surface area in
water-to-air surfaces that are actually moving.
For each group, we DO keep a cache of all the surface tiles of the group.
(i.e. tiles that are groupable water but have a neighbor which is not;
that is the meaning of "surface tile" wherever we use that phrase.)
In fact, each surface tile is stored in 2-3 places, for different purposes.
There's a hash table that maps surface tiles to group IDs, so that you can
look up the groups by surface tile. The group info (which you can look up
by ID) contains a hashset of surface tiles, so that you can look up surface
tiles by group. There's a third set that takes the tiles that are surfaces
specifically in the X dimension, and is ordered within each row, so that
we can take an arbitrary interior tile and find the "next" surface tile,
in order to look up what group the interior tile is in, in log(n) time even
if the interior tile is a long way from any surface. That set also allows us
to measure the volume of a group in less-than-linear-in-the-total-volume
time (there's a comment later in the file describing how that works.)
When a new groupable-water tile appears, if it's next to an existing surface,
it joins that group. If it isn't, then it makes its own new group.
("A groupable water tile appears" describes situations in which one appears
from thin air, or one moves from one tile to another, or an existing tile
becomes groupable. Actually, we currently never allow water to remain
groupable when it moves, but anyway.)
When a groupable-water tile disappears, it removes itself from its group.
So, in most cases, a tile moving only takes constant time to compute, and we
never actually have to iterate through all the surface tiles of a group -
just handle the local situation when individual tiles move.
However, there are two problem cases:
1) When a tile is added next to TWO DIFFERENT groups. In this case, we have
to merge the groups; this operation takes time proportional to the surface
area of the smaller group, because we have to update the cached group info
for all of those surface tiles, to have them join the larger group.
2) When a tile is removed in such a way that it SPLITS a group. In fact, when
we remove a tile, we CAN'T IMMEDIATELY KNOW whether the group is being split.
In this case, we use a flood-fill algorithm from each adjacent tile, over
group surface tiles, to figure out the total area of the split groups (and if
the flood-fills run into each other, then we know that the group is still
in one piece.) Under normal circumstances, the group isn't split, and the
flood-fills run into each other almost immediately, so removing a tile is still
no worse than constant time. When the group actually DOES split, we have to take
time proportional to the total surface area of the *smaller* group. (It also
takes time proportional to the size of the group in certain ugly cases, like
when there's a circle of water that splits at one side - it's technically still
the same group, but you have to look all the way around to discover that.
=== INFINITE OCEANS ===
(Infinite oceans aren't implemented yet, but this will be correct once they are.)
Both of those cases have a worst-case scenario that takes the size of the
SMALLER group - which means that water merging or joining with an infinite ocean
does not take infinite time! And since an ocean is almost entirely inactive,
we don't need to do infinite computations to figure out how it moves each frame,
either.
But what about the "pushable" and "suckable" tiles? For infinite oceans, we just
assume that they have infinitely many pushable tiles at their surface height,
and infinitely many suckable tiles at their surface height. This actually
makes computations *simpler* for the rest of the group - you never have to check
for the real pushable or suckable tiles, just the assumed ones - and since they're,
on average, infinitely far away, you don't have to figure out what actually happens
at their locations - just pull water out of thin air, or push it into nonexistence.
In fact, if you know that a tile is connected to an infinite ocean, you don't need
ANY of its other group information at all - because of the way the pressure is
computed, its pressure is directly proportional to its depth from the ocean height.
This also solves the "two infinite oceans split from each other" case that could
take infinite time if we didn't handle it specially - if two groups are connected
to an infinite ocean, we can just assume that that means they're connected to each
other, because the group info doesn't matter.
So how do we learn, when we're pathfinding over a group, whether it's connected to
an infinite ocean, without looking infinitely far?
TODO: Figure out a good way to do that (I can think of some, but they all have
worst-case scenarios that get really bad in the case of an infinitely long dike
dividing two infinite oceans.)
*/
using namespace tile_physics_impl;
// This synonym is not in utils.hpp because libc++ (Clang-affiliated std C++ lib)
// needed std::queue and its argument types to be included at the time of
// synonym definition (or similar), which we don't want to do in utils.hpp
// because it costs compilation time for the majority of our .cpp files, which
// don't use this.
template<typename T>
struct lasercake_queue {
typedef std::queue<T, deque<T, typename lasercake_nice_allocator<T>::type> > type;
};
////////////////////////////////////////////
// Miscellaneous helpful stuff.
// This is the only file that's allowed to change the contents of tiles at locations.
// Other files should change tile contents through replace_substance,
// and shouldn't be in the business of altering tile caches at all.
// (TODO: also add something for the there_is_an_object_here_that_affects_the_tile_based_physics thing)
namespace tile_physics_impl {
tile& mutable_stuff_at(tile_location const& loc) {
return loc.wb_->tiles_[loc.idx_];
}
inline void set_tile_interiorness(tile_location const& loc, bool interior) {
if(interior) loc.wb_->set_tile_interior(loc.v_, loc.idx_);
else loc.wb_->set_tile_non_interior(loc.v_, loc.idx_);
}
}
namespace tile_physics_impl {
state_t& get_state(world& w) {
return get_state(w.tile_physics());
}
state_t const& get_state(world const& w) {
return get_state(w.tile_physics());
}
template<typename AssociativeContainer, typename Inserted>
inline void unique_insert(AssociativeContainer& container, Inserted&& new_pair) {
const bool was_new = container.insert(new_pair).second;
assert(was_new); // asserts must never contain side-effects
// because they can be defined away
}
template<typename AssociativeContainer, typename Deleted>
inline void unique_erase(AssociativeContainer& container, Deleted&& old_pair) {
const bool existed = container.erase(old_pair);
assert(existed); // asserts must never contain side-effects
// because they can be defined away
}
water_group_identifier make_new_water_group(
water_group_identifier& next_water_group_identifier,
persistent_water_groups_t& persistent_water_groups) {
water_group_identifier this_id = next_water_group_identifier++;
persistent_water_groups[this_id]; // operator[] inserts a default-constructed one
return this_id;
}
tile_physics_state_t::tile_physics_state_t(world& w) : state_(new state_t(w)) {}
tile_physics_state_t::tile_physics_state_t(tile_physics_state_t const& other)
: state_(new state_t(*other.state_)) {}
tile_physics_state_t& tile_physics_state_t::operator=(tile_physics_state_t const& other) {
state_.reset(new state_t(*other.state_));
return *this;
}
tile_physics_state_t::~tile_physics_state_t() BOOST_NOEXCEPT {}
void replace_substance(
state_t& state,
tile_location const& loc,
tile_contents old_substance_type,
tile_contents new_substance_type) {
state.access_the_world.replace_substance(loc, old_substance_type, new_substance_type);
}
water_group_identifier get_water_group_id_by_grouped_tile(state_t const& state, tile_location const& loc) {
maybe_assert(loc.stuff_at().contents() == GROUPABLE_WATER);
{
water_groups_by_location_t::const_iterator i = state.water_groups_by_surface_tile.find(loc);
if (i != state.water_groups_by_surface_tile.end()) {
return i->second;
}
}
// Crap, we don't know what group we're part of unless we find a surface tile!
// Find the next surface tile in some arbitrary direction.
// That tile will tell us what group we're in.
auto iter = state.groupable_water_volume_calipers.boundary_tiles_in_dimension.lower_bound(loc);
if (iter == state.groupable_water_volume_calipers.boundary_tiles_in_dimension.end()) {
return NO_WATER_GROUP;
}
tile_location const& surface_loc = *iter;
if (surface_loc.coords().y != loc.coords().y || surface_loc.coords().z != loc.coords().z) {
return NO_WATER_GROUP;
}
maybe_assert(surface_loc.stuff_at().contents() == GROUPABLE_WATER);
maybe_assert(surface_loc.get_neighbor<xminus>(CONTENTS_ONLY).stuff_at().contents() == GROUPABLE_WATER);
maybe_assert(surface_loc.get_neighbor<xplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER);
return state.water_groups_by_surface_tile.find(surface_loc)->second;
}
persistent_water_group_info const& get_water_group_by_grouped_tile(state_t const& state, tile_location const& loc) {
return state.persistent_water_groups.find(get_water_group_id_by_grouped_tile(state, loc))->second;
}
///////////////////////////////
// Debugging functions:
void dump_boundary_stuff(groupable_water_volume_calipers_t& g) {
for (auto const& foo : g.boundary_tiles_in_dimension)
LOG << " " << foo.coords() << "\n";
}
void dump_group_info(persistent_water_group_info const& g) {
LOG << "Suckable tiles by height:\n";
for (auto const& foo : g.suckable_tiles_by_height.as_map()) {
LOG << " At height " << foo.first << ":\n";
for(auto const& bar : foo.second) {
LOG << " " << bar.coords() << "\n";
}
}
LOG << "Pushable tiles by height:\n";
for (auto const& foo : g.pushable_tiles_by_height.as_map()) {
LOG << " At height " << foo.first << ":\n";
for(auto const& bar : foo.second) {
LOG << " " << bar.coords() << "\n";
}
}
LOG << "Surface tiles:\n";
for (auto const& foo : g.surface_tiles) {
LOG << " " << foo.coords() << "\n";
}
LOG << "Width-of-widest-level-so-far caches:\n";
for (auto const& foo : g.width_of_widest_level_so_far_caches) {
LOG << " " << foo.first << ": " << foo.second << "\n";
}
LOG << "Pressure caches:\n";
for (auto const& foo : g.pressure_caches) {
LOG << " " << foo.first << ": " << foo.second << "\n";
}
LOG << "Num tiles by height:\n";
for (auto const& foo : g.num_tiles_by_height) {
LOG << " " << foo.first << ": " << foo.second << "\n";
}
}
void dump_all_groups(state_t& state) {
for (auto const& p : state.persistent_water_groups) {
LOG << "\n==GROUP "<< p.first<<"==\n";
dump_group_info(p.second);
}
}
/*void check_pushable_tiles_sanity(state_t& state) {
for (auto const& p : state.persistent_water_groups) {
auto const& g = p.second;
for (auto const& foo : g.pushable_tiles_by_height.as_map()) {
for(auto const& bar : foo.second) {
bool sane = false;
for(cardinal_direction dir = 0; dir < num_cardinal_directions; ++dir) {
if(g.surface_tiles.find(bar + dir) != g.surface_tiles.end()) {
sane = true;
break;
}
}
assert(sane);
}
}
}
}*/
// Hacky debugging function that duplicates code from elsewhere.
void check_group_surface_tiles_cache_and_layer_size_caches(state_t& state, persistent_water_group_info const& g) {
persistent_water_group_info h;
// Scan from an arbitrary surface tile of g
if (g.surface_tiles.empty()) {
LOG << "Checking an empty group, why the hell...?";
return;
}
struct group_collecting_info {
group_collecting_info(tile_location const& start_loc, persistent_water_group_info& new_group):new_group(new_group) {
try_collect_loc(start_loc);
}
persistent_water_group_info& new_group;
std::vector<tile_location> frontier;
void try_collect_loc(tile_location const& loc) {
if (loc.stuff_at().contents() == GROUPABLE_WATER && !loc.stuff_at().is_interior() && new_group.surface_tiles.find(loc) == new_group.surface_tiles.end()) {
frontier.push_back(loc);
new_group.surface_tiles.insert(loc);
if (loc.get_neighbor<zplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER) new_group.suckable_tiles_by_height.insert(loc);
}
}
};
group_collecting_info inf(*g.surface_tiles.begin(), h);
while(!inf.frontier.empty()) {
const tile_location search_loc = inf.frontier.back();
inf.frontier.pop_back();
array<tile_location, num_cardinal_directions> search_neighbors = get_all_neighbors(search_loc, CONTENTS_AND_LOCAL_CACHES_ONLY);
for (cardinal_direction dir = 0; dir < num_cardinal_directions; ++dir) {
tile_location const& adj_loc = search_neighbors[dir];
inf.try_collect_loc(adj_loc);
if (adj_loc.stuff_at().contents() == GROUPABLE_WATER && adj_loc.stuff_at().is_interior()) {
const auto adj_neighbors = get_perpendicular_neighbors(adj_loc, dir, CONTENTS_AND_LOCAL_CACHES_ONLY);
for (tile_location adj_neighbor : adj_neighbors) {
inf.try_collect_loc(adj_neighbor);
}
}
}
}
h.recompute_num_tiles_by_height_from_surface_tiles(state);
bool check_succeeded = true;
for (auto const& s : h.surface_tiles) {
if(g.surface_tiles.find(s) == g.surface_tiles.end()) {
LOG << "Missing surface tile: " << s.coords() << "\n";
check_succeeded = false;
}
}
for (auto const& s : g.surface_tiles) {
if(h.surface_tiles.find(s) == h.surface_tiles.end()) {
LOG << "Extra surface tile: " << s.coords() << "\n";
check_succeeded = false;
}
}
for (auto const& p : h.num_tiles_by_height) {
auto i = g.num_tiles_by_height.find(p.first);
if (i == g.num_tiles_by_height.end()) {
LOG << "Missing height listing: " << p.first << "\n";
check_succeeded = false;
}
else {
if (i->second != p.second) {
LOG << "Number of tiles at height " << p.first << " listed as " << i->second << " when it should be " << p.second << "\n";
check_succeeded = false;
}
}
}
for (auto const& p : g.num_tiles_by_height) {
auto i = h.num_tiles_by_height.find(p.first);
if (i == h.num_tiles_by_height.end()) {
LOG << "Extra height listing: " << p.first << "\n";
check_succeeded = false;
}
}
if (!check_succeeded) {
LOG << "All surface tiles:\n";
for (auto const& s : h.surface_tiles) {
LOG << s.coords() << "\n";
}
}
assert(check_succeeded);
}
// Initialization.
// When we initialize a tile...
// If it's not groupable water, we only need to compute its interiorness.
// If it is, then we need to make sure the caches of the group it's in are in order.
// We can check whether the tile is in a group that's already been computed, but otherwise,
// that means doing a flood-fill search to find the group's entire surface, then computing stuff about it.
// The complication comes when the water tile in question is attached to an infinite ocean - we can't
// flood-fill an entire infinite ocean.
//
// Infinite oceans simplify the group computations significantly. One thing they don't simplify is this:
// If a tile, for some reason, disappears from the middle of an infinite ocean, then we still want to be
// able to quickly find out which group it's part of, using the dimensional-boundary-tile thing.
// Which means that *either* we need to make an arbitrary end-surface for infinity (and keep updating
// it every time the player reaches a location that far away)... *or* we can make the infinite groups
// not have a surface *at all*, so that if a tile searches for a surface and finds a badly-formed one,
// then it knows it's part of an infinite group. (Or we could combine those - mark all the real surface
// tiles - if you hit one, it tells you you're in the infinite group, and if you don't, you know from
// that fact.)
//
// I haven't actually implemented infinite oceans yet - TODO do that sometime
//
// Technically, we don't have to initialize a group when it is generated - we only have to initialize it
// when it would DO anything. That's a highly unnecessary optimization, considering that initalizing a
// single group hardly takes any time.
bool is_ungrouped_surface_tile(tile_location const& loc, water_groups_by_location_t const& water_groups_by_surface_tile) { return loc.stuff_at().contents() == GROUPABLE_WATER && !loc.stuff_at().is_interior() && water_groups_by_surface_tile.find(loc) == water_groups_by_surface_tile.end(); }
void initialize_water_group_from_tile_if_necessary(state_t& state, tile_location const& loc) {
// For short:
groupable_water_volume_calipers_t& groupable_water_volume_calipers = state.groupable_water_volume_calipers;
water_group_identifier& next_water_group_identifier = state.next_water_group_identifier;
persistent_water_groups_t& persistent_water_groups = state.persistent_water_groups;
water_groups_by_location_t& water_groups_by_surface_tile = state.water_groups_by_surface_tile;
// Check if we're already initialized, by trying the "jump to a surface tile" thing or just looking up our location.
{
maybe_assert(loc.stuff_at().contents() == GROUPABLE_WATER);
if (state.water_groups_by_surface_tile.find(loc) != state.water_groups_by_surface_tile.end()) return;
auto iter = state.groupable_water_volume_calipers.boundary_tiles_in_dimension.lower_bound(loc);
if (iter != state.groupable_water_volume_calipers.boundary_tiles_in_dimension.end()) {
tile_location const& surface_loc = *iter;
if (surface_loc.coords().y == loc.coords().y && surface_loc.coords().z == loc.coords().z) {
if (surface_loc.get_neighbor<xminus>(CONTENTS_ONLY).stuff_at().contents() == GROUPABLE_WATER) {
maybe_assert(surface_loc.get_neighbor<xplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER);
maybe_assert(state.water_groups_by_surface_tile.find(surface_loc) != state.water_groups_by_surface_tile.end());
maybe_assert(state.water_groups_by_surface_tile.find(surface_loc)->second != NO_WATER_GROUP);
return;
}
}
}
}
// Walk until we get a location on the surface.
// We *could* just ignore interior tiles and only do the initialization if we started from a surface
// tile, since we never initialize interior tiles without also initializing surface tiles... well,
// unless we started in the middle of a giant ocean or something. Anyway, it's cleaner to handle
// interior tiles, and the cost is trivial since we only ever do this once per group-initialization.
tile_location surface_loc = loc;
while (true) {
const tile_location next_loc = surface_loc.get_neighbor<zplus>(CONTENTS_AND_LOCAL_CACHES_ONLY);
if (next_loc.stuff_at().contents() != GROUPABLE_WATER) break;
surface_loc = next_loc;
}
// Flood-fill the surface tiles.
// This partially duplicates the "groups splitting" algorithm later in this file.
const water_group_identifier new_group_id = make_new_water_group(next_water_group_identifier, persistent_water_groups);
persistent_water_group_info& new_group = persistent_water_groups.find(new_group_id)->second;
struct group_collecting_info {
group_collecting_info(tile_location const& start_loc, water_group_identifier new_group_id,
persistent_water_group_info& new_group,
groupable_water_volume_calipers_t& groupable_water_volume_calipers,
water_groups_by_location_t& water_groups_by_surface_tile)
: new_group_id(new_group_id), new_group(new_group),
groupable_water_volume_calipers(groupable_water_volume_calipers),
water_groups_by_surface_tile(water_groups_by_surface_tile) {
try_collect_loc(start_loc);
}
water_group_identifier new_group_id;
persistent_water_group_info& new_group;
groupable_water_volume_calipers_t& groupable_water_volume_calipers;
water_groups_by_location_t& water_groups_by_surface_tile;
std::vector<tile_location> frontier;
void try_collect_loc(tile_location const& loc) {
if (is_ungrouped_surface_tile(loc, water_groups_by_surface_tile)) {
frontier.push_back(loc);
unique_insert(new_group.surface_tiles, loc);
unique_insert(water_groups_by_surface_tile, make_pair(loc, new_group_id));
if (loc.get_neighbor<zplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER) new_group.suckable_tiles_by_height.insert(loc);
// This DOES handle first-initialization properly; it makes some unnecessary checks, but
// we're not worried about super speed here.
groupable_water_volume_calipers.handle_tile_insertion(loc);
}
}
};
group_collecting_info inf(surface_loc, new_group_id, new_group, groupable_water_volume_calipers, water_groups_by_surface_tile);
while(!inf.frontier.empty()) {
const tile_location search_loc = inf.frontier.back();
inf.frontier.pop_back();
array<tile_location, num_cardinal_directions> neighbors = get_all_neighbors(search_loc, CONTENTS_AND_LOCAL_CACHES_ONLY);
for (cardinal_direction dir = 0; dir < num_cardinal_directions; ++dir) {
tile_location const& adj_loc = neighbors[dir];
inf.try_collect_loc(adj_loc);
if (adj_loc.stuff_at().contents() == GROUPABLE_WATER && adj_loc.stuff_at().is_interior()) {
const auto adj_neighbors = get_perpendicular_neighbors(adj_loc, dir, CONTENTS_AND_LOCAL_CACHES_ONLY);
for (tile_location adj_neighbor : adj_neighbors) {
inf.try_collect_loc(adj_neighbor);
}
}
}
}
new_group.recompute_num_tiles_by_height_from_surface_tiles(state);
//check_group_surface_tiles_cache_and_layer_size_caches(state, new_group);
}
void persistent_water_group_info::recompute_num_tiles_by_height_from_surface_tiles(state_t const& state) {
// Here's how we compute the total volume in less than linear time:
// We take each contiguous row of surface tiles and compute its total length by
// using a cleverly sorted set, so that we can start with a tile at the beginning
// of the row and just jump to the tile at the other end.
//
// Here, we look up all "low-x ends of x-rows" and jump to the high-x ends
num_tiles_by_height.clear();
auto const& groupable_water_volume_calipers = state.groupable_water_volume_calipers;
for (tile_location const& surface_loc : surface_tiles) {
// We're only interested in starting at low-x boundaries
if (surface_loc.get_neighbor<xminus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER) {
// If we're *also* the high-x boundary, there's only one water tile in this row
if (surface_loc.get_neighbor<xplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER) {
num_tiles_by_height[surface_loc.coords().z] += 1;
}
else {
// Otherwise, we have to jump to the end of the row using the fancy sorted caches.
auto surface_loc_iter = groupable_water_volume_calipers.boundary_tiles_in_dimension.find(surface_loc);
assert (surface_loc_iter != groupable_water_volume_calipers.boundary_tiles_in_dimension.end());
++surface_loc_iter;
assert (surface_loc_iter != groupable_water_volume_calipers.boundary_tiles_in_dimension.end());
tile_location const& end_tile = *surface_loc_iter;
maybe_assert(end_tile.coords().y == surface_loc.coords().y && end_tile.coords().z == surface_loc.coords().z);
maybe_assert(end_tile.coords().x > surface_loc.coords().x);
maybe_assert(surface_tiles.find(end_tile) != surface_tiles.end());
maybe_assert(end_tile.get_neighbor<xplus>(CONTENTS_ONLY).stuff_at().contents() != GROUPABLE_WATER);
num_tiles_by_height[surface_loc.coords().z] += 1 + end_tile.coords().x - surface_loc.coords().x;
}
}
}
}
pressure persistent_water_group_info::get_pressure_at_height(tile_coordinate height)const {
// The pressure computation here is a kludge. The main difference between it and "the height of the top level minus the height of the current level" is that it doesn't make teeny water towers on top of oceans exert pressure over the whole ocean.
map<tile_coordinate, pressure>::iterator iter = pressure_caches.lower_bound(height);
tile_coordinate current_height = 0;
pressure current_pressure = 0;
if (iter == pressure_caches.end()) {
auto foo = num_tiles_by_height.rbegin();
maybe_assert(foo != num_tiles_by_height.rend());
current_height = foo->first;
if (height > current_height) return 0;
pressure_caches.insert(pressure_caches_t::value_type(current_height, 0));
// TODO make less stupid
width_of_widest_level_so_far_caches.erase(current_height);
width_of_widest_level_so_far_caches.insert(make_pair(current_height, foo->second));
}
else {
current_height = iter->first;
current_pressure = iter->second;
}
while (current_height != height) {
--current_height;
water_tile_count last_count = width_of_widest_level_so_far_caches.find(current_height+1)->second;
auto foo = num_tiles_by_height.find(current_height);
water_tile_count new_count = std::max(last_count, (foo != num_tiles_by_height.end()) ? foo->second : 0);
width_of_widest_level_so_far_caches.erase(current_height);
width_of_widest_level_so_far_caches.insert(make_pair(current_height, new_count));
current_pressure = (current_pressure + pressure_per_depth_in_tile_heights) * std::min(new_count, last_count) / new_count;
pressure_caches.insert(make_pair(current_height, current_pressure));
}
return current_pressure;
}
void suck_out_suckable_water(state_t& state,
tile_location const& loc,
active_fluids_t& active_fluids)
{
// Suckable water works like this:
// The idle/inactive state of water, including groupable water, is
// to have maximum downward progress and a little downward velocity.
// Water is considered "suckable" if it has enough downward progress to
// immediately enter another tile of the group - so all idle water is, by default, suckable.
//
// BUT...
//
// We don't want it to cascade downwards. If there's a huge suck at the bottom, we *don't* want
// a huge mass of water to suddenly vanish from the top - that would make the top layer move
// way faster than gravity, and the fiction is that it's really being moved by gravity,
// so that would be bizarre and/or immersion-breaking. The top layer shouldn't move faster
// than gravity.
//
// SO...
//
// 1) Water is only considered suckable if it has the right progress AND has no other water above it, and...
// 2) When a water gets sucked from above another water, we behave as if the *lower* water got teleported away
// and the *upper* water just fell naturally. That way, the upper water (now in the location of the lower
// water) has no downwards progress left, and has to build up progress again using gravity.
const tile_location downward_loc = loc.get_neighbor<zminus>(FULL_REALIZATION);
if (downward_loc.stuff_at().contents() == GROUPABLE_WATER) {
auto here_af_iter = active_fluids.find(loc);
auto down_af_iter = active_fluids.find(downward_loc);
active_fluid_tile_info here_info = ((here_af_iter == active_fluids.end()) ? active_fluid_tile_info() : here_af_iter->second);
here_info.progress[zminus] -= progress_necessary(zminus); // The usual effect of moving downwards
maybe_assert(here_info.progress[zminus] >= 0);
if (down_af_iter == active_fluids.end()) {
active_fluids.insert(make_pair(downward_loc, here_info));
}
else {
// If the downward water is active, we *could* combine its values with ours somehow.
// However, the downward water is groupable, so it should already be pretty slow,
// and combining them would make it more complicated to understand how sucking works -
// I feel like it would invite weird corner cases.
down_af_iter->second = here_info;
}
if (here_af_iter != active_fluids.end()) active_fluids.erase(here_af_iter);
}
else {
// If there's no groupable water below us, then we've gotten to the bottom of the barrel
// and so the system doesn't need to make any extra accomodations. (If all the water is
// gone, then there isn't enough left to be unrealistic when it moves fast...)
active_fluids.erase(loc);
}
// replace_substance handles marking the water no-longer-suckable.
replace_substance(state, loc, GROUPABLE_WATER, AIR);
}
void push_water_into_pushable_tile(state_t& state,
tile_location const& loc,
active_fluids_t& active_fluids)
{
// We always create ungroupable water at first when it moves due to pressure;
// creating groupable water runs the risk
// of creating explosions where more and more water is drawn out.
// The water will become groupable in its own time.
// replace_substance automatically makes the tile no-longer-pushable.
// (Or maybe the tile was already made non-pushable by what called this.)
//
// Semi-hack - we trust that this has been called on a reasonable tile,
// so we just copy the tile's contents into old_substance_type.
replace_substance(state, loc, loc.stuff_at().contents(), UNGROUPABLE_WATER);
// Activate it.
// The [] operator creates a default-constructed version.
// In this case, we don't want the default attributes - water moved by pressure
// starts with no downward progress or velocity.
// It'll be given its new velocity in the next frame, by the normal pressure-pushes-water rules.
active_fluids[loc].progress[zminus] = 0;
active_fluids[loc].velocity.z = 0;
}
bool persistent_water_group_info::mark_tile_as_suckable_and_return_true_if_it_is_immediately_sucked_away(
state_t& state, tile_location const& loc, active_fluids_t& active_fluids) {
if (!pushable_tiles_by_height.any_below(loc.coords().z)) {
suckable_tiles_by_height.insert(loc);
return false;
}
const tile_location pushed_tile = pushable_tiles_by_height.get_and_erase_random_from_the_bottom(state.rng);
suck_out_suckable_water(state, loc, active_fluids);
push_water_into_pushable_tile(state, pushed_tile, active_fluids);
return true;
}
bool persistent_water_group_info::mark_tile_as_pushable_and_return_true_if_it_is_immediately_pushed_into(
state_t& state, tile_location const& loc, active_fluids_t& active_fluids) {
if (!suckable_tiles_by_height.any_above(loc.coords().z)) {
pushable_tiles_by_height.insert(loc);
return false;
}
const tile_location sucked_tile = suckable_tiles_by_height.get_and_erase_random_from_the_top(state.rng);
suck_out_suckable_water(state, sucked_tile, active_fluids);
push_water_into_pushable_tile(state, loc, active_fluids);
return true;
}
void correct_all_suckable_pushable_pairs(state_t& state, persistent_water_group_info& g, active_fluids_t& active_fluids) {
while (!g.suckable_tiles_by_height.as_map().empty() && !g.pushable_tiles_by_height.as_map().empty() && g.suckable_tiles_by_height.as_map().rbegin()->first > g.pushable_tiles_by_height.as_map().begin()->first) {
const tile_location sucked_tile = g.suckable_tiles_by_height.get_and_erase_random_from_the_top(state.rng);
const tile_location pushed_tile = g.pushable_tiles_by_height.get_and_erase_random_from_the_bottom(state.rng);
suck_out_suckable_water (state, sucked_tile, active_fluids);
push_water_into_pushable_tile(state, pushed_tile, active_fluids);
}
}
// ONLY to be called by replace_substance
water_group_identifier merge_water_groups(water_group_identifier id_1, water_group_identifier id_2,
persistent_water_groups_t& persistent_water_groups,
water_groups_by_location_t& water_groups_by_surface_tile) {
persistent_water_group_info& group_1 = persistent_water_groups.find(id_1)->second;
persistent_water_group_info& group_2 = persistent_water_groups.find(id_2)->second;
bool group_1_is_smaller = group_1.surface_tiles.size() < group_2.surface_tiles.size();
persistent_water_group_info& smaller_group = (group_1_is_smaller ? group_1 : group_2);
persistent_water_group_info& larger_group = (group_1_is_smaller ? group_2 : group_1);
water_group_identifier remaining_group_id = (group_1_is_smaller ? id_2 : id_1);
water_group_identifier destroyed_group_id = (group_1_is_smaller ? id_1 : id_2);
for (auto const& s : smaller_group.suckable_tiles_by_height.as_map()) {
for (auto const& t : s.second) {
larger_group.suckable_tiles_by_height.insert(t);
}
}
for (auto const& s : smaller_group.pushable_tiles_by_height.as_map()) {
for (auto const& t : s.second) {
maybe_assert(t.stuff_at().contents() == AIR);
larger_group.pushable_tiles_by_height.insert(t);
}
}
for (auto const& p : smaller_group.num_tiles_by_height) {
// Note: the [] operator default-constructs a zero if there's nothing there
maybe_assert(p.second > 0);
larger_group.num_tiles_by_height[p.first] += p.second;
}
for (auto const& l : smaller_group.surface_tiles) {
unique_insert(larger_group.surface_tiles, l);
auto foo = water_groups_by_surface_tile.find(l);
maybe_assert(foo != water_groups_by_surface_tile.end());
maybe_assert(foo->second == destroyed_group_id);
foo->second = remaining_group_id;
}
larger_group.pressure_caches.erase(larger_group.pressure_caches.begin(), larger_group.pressure_caches.upper_bound(smaller_group.num_tiles_by_height.rbegin()->first));
persistent_water_groups.erase(destroyed_group_id);
return remaining_group_id;
}
void replace_substance_impl(
state_t& state,
tile_location const& loc,
tile_contents old_substance_type,
tile_contents new_substance_type
) {
// For short:
groupable_water_volume_calipers_t& groupable_water_volume_calipers = state.groupable_water_volume_calipers;
active_fluids_t& active_fluids = state.active_fluids;
water_group_identifier& next_water_group_identifier = state.next_water_group_identifier;
persistent_water_groups_t& persistent_water_groups = state.persistent_water_groups;
water_groups_by_location_t& water_groups_by_surface_tile = state.water_groups_by_surface_tile;
//maybe_assert(loc.wb_->current_tile_realization_ == FULL_REALIZATION);
maybe_assert(loc.stuff_at().contents() == old_substance_type);
//check_pushable_tiles_sanity(state);
array<tile_location, num_cardinal_directions> neighbors = get_all_neighbors(loc);
if (old_substance_type != AIR && new_substance_type == AIR) {
// We might have moved away from a tile that was trying to push water into us.
// This system formerly used rules where the emptied tile naturally didn't refill until the following frame.
// The downside of those rules was that the simulation could immediately mark the tile that had been trying
// to exert pressure as having too much air next to it, which would make it stop exerting pressure;
// To combat that effect, we made the pressure-exertingness linger for a frame, but that was a kludge.
//
// So the rule now is that the tile *immediately* fills with the pressure-moved water as soon as it empties.
// This saves us a kludge, and also saves us from having to do the "deleted water" and "inserted water" recomputations
// in the cases where the water would just be replaced anyway.
// TODO prefer: is opposite the direction we moved (can we do that...?)
// TODO prefer: is where our velocity is leaving
vector<tile_location> adj_tiles_that_want_to_fill_us_via_pressure;
for (tile_location const& adj_loc : neighbors) {
if (adj_loc.stuff_at().contents() == GROUPABLE_WATER) {
water_group_identifier group_id = get_water_group_id_by_grouped_tile(state, adj_loc);
persistent_water_group_info const& group = persistent_water_groups.find(group_id)->second;
if (group.suckable_tiles_by_height.any_above(loc.coords().z)) {
adj_tiles_that_want_to_fill_us_via_pressure.push_back(adj_loc);
}
}
}
if (!adj_tiles_that_want_to_fill_us_via_pressure.empty()) {
tile_location const& tile_pulled_from = *random_element_of_sequence(adj_tiles_that_want_to_fill_us_via_pressure, state.rng);
water_group_identifier group_id = get_water_group_id_by_grouped_tile(state, tile_pulled_from);
persistent_water_group_info& group = persistent_water_groups.find(group_id)->second;
const bool pushed = group.mark_tile_as_pushable_and_return_true_if_it_is_immediately_pushed_into(state, loc, active_fluids);
assert(pushed);
// That function will have run the body of replace_substance on this tile; we don't need to.
return;
}
else {
for (tile_location const& adj_loc : neighbors) {
if (adj_loc.stuff_at().contents() == GROUPABLE_WATER) {
water_group_identifier group_id = get_water_group_id_by_grouped_tile(state, adj_loc);
persistent_water_group_info& group = persistent_water_groups.find(group_id)->second;
const bool pushed = group.mark_tile_as_pushable_and_return_true_if_it_is_immediately_pushed_into(state, loc, active_fluids);
assert(!pushed);
}
}
}
}
// Or, if we've become non-air, pressure can no longer push water into us.
if (old_substance_type == AIR && new_substance_type != AIR) {
for (tile_location const& adj_loc : neighbors) {
if (adj_loc.stuff_at().contents() == GROUPABLE_WATER) {
water_group_identifier group_id = get_water_group_id_by_grouped_tile(state, adj_loc);
maybe_assert(group_id != NO_WATER_GROUP);
auto foo = persistent_water_groups.find(group_id);
maybe_assert(foo != persistent_water_groups.end());
persistent_water_group_info& group = foo->second;
group.pushable_tiles_by_height.erase(loc);
}
}
//check_pushable_tiles_sanity(state);
}
// If we're removing water, we have complicated computations to do. We do it in this order:
// 1) Gather as much information as possible BEFORE physically changing anything (while we're still marked as water)
// 2) Physically change us
// 3) Update the relatively-isolated cached info like interiorness
// 4) Update the relatively-interconnected cached info of our group
persistent_water_group_info *water_group = nullptr;
water_group_identifier water_group_id = NO_WATER_GROUP;
if (old_substance_type == GROUPABLE_WATER && new_substance_type != GROUPABLE_WATER) {
// ==============================================================================
// 1) Gather as much information as possible without physically changing anything
// (while we're still marked as water)
// ==============================================================================
water_group_id = get_water_group_id_by_grouped_tile(state, loc);
maybe_assert(water_group_id != NO_WATER_GROUP);
auto iter = persistent_water_groups.find(water_group_id);
maybe_assert(iter != persistent_water_groups.end());
water_group = &iter->second;
//check_group_surface_tiles_cache_and_layer_size_caches(state, *water_group);
}
// For inserting water, we check group membership BEFORE
// updating the caches, because the adjacent tiles won't know their group
// membership if they've all become interior. (We could look it up, but
// it's easier this way.) And it's more convenient to merge the groups
// now, too.
if (new_substance_type == GROUPABLE_WATER && old_substance_type != GROUPABLE_WATER) {
// Inserting water: Are we adjacent to an existing group?
// If we're next to one adjacent group, we will merely join that group.
// If we're adjacent to more than one adjacent group, then our existence
// constitutes a merger of those two groups, so we execute that.
for (tile_location const& adj_loc : neighbors) {
water_groups_by_location_t::const_iterator iter = water_groups_by_surface_tile.find(adj_loc);
if (iter != water_groups_by_surface_tile.end()) {
if (water_group_id == NO_WATER_GROUP) {
water_group_id = iter->second;
}
else if (iter->second != water_group_id) {
// Two groups we join! Merge them. merge_water_groups() automatically
// handles the "merge the smaller one into the larger one" optimization
// and returns the ID of the group that remains.
water_group_id = merge_water_groups(water_group_id, iter->second, persistent_water_groups, water_groups_by_surface_tile);
}
}
}
// Now we're either adjacent to one water group or none. If none, we have to create a new one for ourself.
if (water_group_id == NO_WATER_GROUP) {
water_group_id = make_new_water_group(next_water_group_identifier, persistent_water_groups);
}
water_group = &persistent_water_groups.find(water_group_id)->second;
}
// ==============================================================================
// 2) Physically change us
// ==============================================================================
mutable_stuff_at(loc).set_contents(new_substance_type);
if (!is_fluid(new_substance_type)) {
active_fluids.erase(loc);
}
// Hack - assign minerals to rubble
if (old_substance_type == ROCK && new_substance_type == RUBBLE) {
state.altered_minerals_info.insert(std::make_pair(loc.coords(), initial_minerals(loc.coords())));
}
if (old_substance_type == RUBBLE && new_substance_type != RUBBLE) {
state.altered_minerals_info.erase(loc.coords());
}
// ==============================================================================
// 3) Update the relatively-isolated cached info like interiorness
// ==============================================================================
if (old_substance_type == GROUPABLE_WATER && new_substance_type != GROUPABLE_WATER) {
groupable_water_volume_calipers.handle_tile_removal(loc);
}
if (new_substance_type == GROUPABLE_WATER && old_substance_type != GROUPABLE_WATER) {
groupable_water_volume_calipers.handle_tile_insertion(loc);
}
if (new_substance_type != old_substance_type) {
// Changes can activate nearby water.
// NOTE "Adjacent tile conditions for activation/deactivation": The only relevant ones are
// the one directly below, the ones cardinally-horizontally, and the ones horizontally-and-below.
// at the 2-diagonals. This comment is duplicated one one other place in this file.
// Here, that means we need to check the opposite - the tiles horizontally, above, and above-horizontally.
// Water is activated-if-necessary by calling unordered_set::operator[], which default-constructs one
// if there isn't one there already.