-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cc
2900 lines (2555 loc) · 75.6 KB
/
main.cc
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
#include "ply_io.h"
#include <unordered_map>
#include "util.hh"
#include "algorithm.hh"
#include "rendering.hh"
#include "block.hh"
#include "auto.hh"
#include "socket.hh"
#include "parse.hh"
#include "message.hh"
#define LODEPNG_COMPILE_CPP
#include "lodepng/lodepng.h"
// GUI
int width;
int height;
// Map
const int RenderDistance = 40;
static_assert(RenderDistance < MapSize / 2, "");
Sphere render_sphere(RenderDistance);
// ============================
namespace Cube
{
glm::ivec3 corner[8];
const int faces[6][4] = { { 0, 4, 6, 2 }/*xmin*/, { 1, 3, 7, 5 }/*xmax*/, { 0, 1, 5, 4 }/*ymin*/, { 2, 6, 7, 3 }/*ymax*/, { 0, 2, 3, 1 }/*zmin*/, { 4, 5, 7, 6 }/*zmax*/ };
glm::i8vec3 lightmap[6/*face*/][8/*vertex*/][4/*four blocks around vertex affecting light of vertex*/];
glm::i8vec3 lightmap2[6/*face*/][8/*vertex*/][4*3/*three blocks around four blocks around vertex affecting light of vertex*/];
Initialize
{
FOR(i, 8)
{
FOR(i, 8) corner[i] = glm::ivec3(i&1, (i>>1)&1, (i>>2)&1);
FOR(f, 6)
{
glm::ivec3 max = corner[i], min = max - ii;
if (f % 2 == 0) max[f / 2] -= 1;
if (f % 2 == 1) min[f / 2] += 1;
int p = 0;
int q = 0;
FOR2(x, min.x, max.x) FOR2(y, min.y, max.y) FOR2(z, min.z, max.z)
{
lightmap[f][i][p++] = glm::i8vec3(x, y, z);
FOR(ff, 6) if (ff != (f ^ 1))
{
glm::ivec3 b = glm::ivec3(x, y, z) + face_dir[ff];
if (!between(min, b, max)) lightmap2[f][i][q++] = glm::i8vec3(b);
}
assert(q == p * 3);
}
}
}
}
}
// ============================
struct Quad
{
glm::u8vec3 pos[4]; // TODO: replace with x y w h
BlockTexture texture; // highest bit: isUnderwater
uint16_t light; // 4 bits per vertex
uint16_t plane; // hi byte: plane normal (face), lo byte: plane offset
};
struct WQuad
{
glm::u16vec3 pos[4]; // TODO: replace with x y w h
BlockTexture texture; // highest bit: isUnderwater
uint16_t light; // 4 bits per vertex
uint16_t plane; // hi byte: plane normal (face), lo byte: plane offset
};
float distance(const Quad& q, glm::vec3 e)
{
glm::vec3 a(q.pos[0]), c(q.pos[2]);
return glm::distance2((a + c) * 0.5f, e);
}
bool operator<(const Quad& a, const Quad& b)
{
if (a.texture != b.texture)
{
int ga = is_blended(a.texture) ? 1 : 0;
int gb = is_blended(b.texture) ? 1 : 0;
if (ga != gb) return ga < gb;
return a.texture < b.texture;
}
if (a.plane != b.plane) return a.plane < b.plane;
return a.light < b.light;
}
const float BlockRadius = sqrtf(3) / 2;
struct VisibleChunks
{
VisibleChunks() : m_frame(0) { set.clear_all(); }
void add(glm::ivec3 v)
{
if (set.xset(v & MapSizeMask))
{
Element e;
e.cpos = v;
e.frame = m_frame;
array.push_back(e);
}
}
void cleanup()
{
m_reset_frame = m_frame;
set.clear_all();
}
void sort(glm::vec3 camera, bool done)
{
camera -= ii * ChunkSize / 2;
camera /= ChunkSize;
if (done)
{
int i = 0;
while (i < array.size())
{
if (array[i].frame - m_frame <= m_reset_frame - m_frame)
{
array[i] = array.back();
array.pop_back();
continue;
}
i += 1;
}
for (Element& e : array) e.distance = glm::distance2(glm::vec3(e.cpos), camera);
std::sort(array.begin(), array.end());
}
else
{
for (Element& e : array) e.distance = glm::distance2(glm::vec3(e.cpos), camera);
std::sort(array.begin(), array.end());
// remove duplicate array entries
uint max_age = (m_reset_frame - m_frame + 10);
int w = 0;
for (int i = 0; i < array.size(); i++)
{
int j = i + 1;
uint frame = array[i].frame;
while (j < array.size() && array[i].cpos == array[j].cpos)
{
if (array[j].frame - m_frame < frame - m_frame) frame = array[j].frame;
j += 1;
}
if (frame - m_frame <= max_age)
{
array[w].cpos = array[i].cpos;
array[w].frame = frame;
w += 1;
}
i = j - 1;
}
array.resize(w);
}
m_frame -= 1;
}
struct Element
{
glm::ivec3 cpos;
float distance;
uint frame;
bool operator<(const Element& b) const { return distance > b.distance; }
};
Element* begin() { return &array[0]; }
Element* end() { return begin() + array.size(); }
private:
uint m_reset_frame;
uint m_frame;
BitCube<MapSize> set;
std::vector<Element> array;
};
struct Chunk;
bool enable_f4 = true;
bool enable_f5 = true;
bool enable_f6 = true;
uint8_t Light(const Quad& q, int i)
{
int s = (i % 4) * 2;
int a = (q.light >> s) & 3;
return (a + 1) * 64 - 1;
}
uint8_t Light2(const Quad& q, int i)
{
int s = (i % 4) * 4;
int a = (q.light >> s) & 15;
return (a + 1) * 16 - 1;
}
struct BlockRenderer
{
std::vector<Quad>* m_quads;
std::vector<Quad> m_quadsp;
glm::ivec3 m_pos;
Block m_block;
std::vector<Quad> m_xy, m_yx;
// V1
glm::ivec3 m_cxpos;
const Blocks** m_chunks; // 3x3x3 cube
// V2
// Idea: if mapchunks are shifted 8 blocks on each axis then each render chunk would only depend on 2x2x2 mapchunks (8 instead of 27)
// Problem: how to parallelize loading when player moves?
// - worker threads only load superchunks and generate chunks (if mapchunk is not ready by buffer time, just use pointer to zero memory or full with some special block types)
// - renderchunks are generated by main thread on demand (if chunk is going to be rendered and is dirty)
// How does it affect the current and replacement raytracers?/
//MapChunkLight m_mcl[3][3][3];
/*Block get_v2(glm::ivec3 rel)
{
glm::ivec3 a = m_fpos + rel;
glm::ivec3 b = (a - corner) >> ChunkSizeBits;
return m_mcl[b.x][b.y][b.z].get(a & ChunkSizeMask);
}*/
Block get(glm::ivec3 rel)
{
glm::ivec3 a = m_pos + rel;
glm::ivec3 b = a >> ChunkSizeBits;
assert(-1 <= b.x && b.x <= 1);
assert(-1 <= b.y && b.y <= 1);
assert(-1 <= b.z && b.z <= 1);
int i = b.x*9 + b.y*3 + b.z + 13; // ((b.x+1)*3 + b.y+1)*3 + b.z+1
assert((uint)i < 27u);
return m_chunks[i] ? (*m_chunks[i])[(a + m_cxpos) & ChunkSizeMask] : Block::none;
}
uint8_t face_light(int face)
{
const int* f = Cube::faces[face];
int q = 0;
FOR(i, 4)
{
glm::i8vec3* map = Cube::lightmap[face][f[i]];
int s = 0;
FOR(j, 4) if (get(glm::ivec3(map[j])) == Block::none) s += 1;
q |= (s - 1) << (i * 2);
}
return q;
}
uint16_t face_light2(int face)
{
const int* f = Cube::faces[face];
int q = 0;
FOR(i, 4)
{
glm::i8vec3* map = Cube::lightmap[face][f[i]];
glm::i8vec3* map2 = Cube::lightmap2[face][f[i]];
int s = 0;
FOR(j, 4)
{
Block b = get(glm::ivec3(map[j]));
if (can_see_through(b))
{
s += (b == Block::none) ? 2 : 1;
FOR(k, 3)
{
Block b2 = get(glm::ivec3(map2[j*3+k]));
if (can_see_through(b2)) s += (b2 == Block::none) ? 2 : 1;
}
}
}
s = s / 2;
q |= (s - 1) << (i * 4);
}
return q;
}
void draw_quad(int face, bool reverse, bool underwater_overlay);
void draw_quad(int face, int zmin, int zmax, bool reverse, bool underwater_overlay);
Block get(int face) { return get(face_dir[face]); }
template<bool side>
void draw_non_water_face(int face)
{
Block q = get(face);
if (side && is_water(q))
{
if (q == Block::water)
{
draw_quad(face, false, true);
}
else if (q != m_block)
{
draw_quad(face, 0, water_level(q), false, true);
draw_quad(face, water_level(q), 15, false, false);
}
return;
}
if (!side && q == Block::water)
{
draw_quad(face, false, true);
return;
}
if (can_see_through(q) && q != m_block)
{
draw_quad(face, false, false);
}
}
void draw_water_side(int face, int w)
{
Block q = get(face);
if (is_water_partial(q))
{
if (w > water_level(q))
{
draw_quad(face, water_level(q), w, false, false);
draw_quad(face, water_level(q), w, true, false);
}
}
else if (can_see_through_non_water(q))
{
draw_quad(face, 0, w, false, false);
draw_quad(face, 0, w, true, false);
}
}
void draw_water_bottom()
{
Block q = get(/*m_pos.z != CMin, 4,*/ -iz);
if (q != Block::water && can_see_through(q)) draw_quad(4, false, false);
if (q == Block::none) draw_quad(4, true, false);
}
void draw_water_top(int w)
{
if (m_block == Block::water)
{
Block q = get(/*m_pos.z != CMax, 5,*/ iz);
if (can_see_through_non_water(q)) draw_quad(5, false, false);
if (q == Block::none) draw_quad(5, true, false);
}
else
{
draw_quad(5, w, w, false, false);
draw_quad(5, w, w, true, false);
}
}
void generate_quads(glm::ivec3 cpos, const Blocks* chunks[27], bool merge, std::vector<Quad>& out, int& blended_quads)
{
out.clear();
m_quadsp.clear();
m_quads = merge ? &m_quadsp : &out;
m_chunks = chunks;
m_cxpos = cpos << ChunkSizeBits;
const Blocks& mc = *chunks[13];
FOR(z, ChunkSize) FOR(y, ChunkSize) FOR(x, ChunkSize)
{
glm::ivec3 p(x, y, z);
Block block = mc[p];
if (block == Block::none) continue;
m_pos = p;
m_block = block;
if (is_water(block))
{
int w = uint(block) - uint(Block::water1) + 1;
draw_water_side(0, w);
draw_water_side(1, w);
draw_water_side(2, w);
draw_water_side(3, w);
draw_water_bottom();
draw_water_top(w);
}
else
{
draw_non_water_face<true>(0);
draw_non_water_face<true>(1);
draw_non_water_face<true>(2);
draw_non_water_face<true>(3);
draw_non_water_face<false>(4);
draw_non_water_face<false>(5);
}
}
if (merge) merge_quads(out);
if (!merge) std::partition(out.begin(), out.end(), [](const Quad& q) { return !is_blended(q.texture); });
blended_quads = 0;
while (blended_quads < out.size() && is_blended(out[out.size() - 1 - blended_quads].texture)) blended_quads += 1;
}
static bool combine(Quad& a, Quad b, int X, int Y)
{
if (a.pos[0][X] == b.pos[0][X] && a.pos[2][X] == b.pos[2][X] && a.pos[2][Y] == b.pos[0][Y])
{
a.pos[2] = b.pos[2];
if (a.pos[1][Y] == b.pos[0][Y]) a.pos[1] = b.pos[1];
if (a.pos[3][Y] == b.pos[0][Y]) a.pos[3] = b.pos[3];
return true;
}
return false;
}
static void merge_axis(std::vector<Quad>& quads, int X, int Y)
{
std::sort(quads.begin(), quads.end(), [X, Y](Quad a, Quad b) { return a.pos[0][X] < b.pos[0][X] || (a.pos[0][X] == b.pos[0][X] && a.pos[0][Y] < b.pos[0][Y]); });
int w = 0;
for (Quad q : quads)
{
if (w == 0 || !combine(quads[w-1], q, X, Y)) quads[w++] = q;
}
quads.resize(w);
}
void merge_quads(std::vector<Quad>& out)
{
std::sort(m_quadsp.begin(), m_quadsp.end());
auto a = m_quadsp.begin();
while (a != m_quadsp.end())
{
auto b = a + 1;
while (b != m_quadsp.end() && a->texture == b->texture && a->plane == b->plane && a->light == b->light) b += 1;
if (is_leaves(a->texture))
{
while (a < b) out.push_back(*a++);
continue;
}
m_xy.clear();
m_yx.clear();
while (a < b)
{
m_xy.push_back(*a);
m_yx.push_back(*a);
a += 1;
}
int axis = m_xy[0].plane >> 9;
int x = (axis == 0) ? 1 : 0;
int y = (axis == 2) ? 1 : 2;
merge_axis(m_xy, x, y);
merge_axis(m_xy, y, x);
merge_axis(m_yx, y, x);
merge_axis(m_yx, x, y);
if (m_xy.size() > m_yx.size()) std::swap(m_xy, m_yx);
for (Quad& q : m_xy)
{
out.push_back(q);
}
}
}
};
typedef uint64_t CompressedIVec3;
uint64_t compress(int v, int bits)
{
uint64_t c = v;
return c & ((1lu << bits) - 1);
}
int decompress(uint64_t c, int bits)
{
int64_t q = c << (64 - bits);
return q >> (64 - bits);
}
CompressedIVec3 compress_ivec3(glm::ivec3 v)
{
uint64_t c = 0;
c |= compress(v.x, 21);
c <<= 21;
c |= compress(v.y, 21);
c <<= 21;
c |= compress(v.z, 21);
return c;
}
glm::ivec3 decompress_ivec3(CompressedIVec3 c)
{
glm::ivec3 v;
v.z = decompress(c, 21);
c >>= 21;
v.y = decompress(c, 21);
c >>= 21;
v.x = decompress(c, 21);
return v;
}
// ===============
class MyConsole : public Console
{
public:
virtual void Execute(const char* command, int length) override;
};
MyConsole console;
struct Player
{
// Persisted
glm::vec3 position;
float yaw, pitch;
glm::vec3 velocity;
bool creative_mode;
Block palette_block;
// TODO: active tool
// TODO: inventory items
// TODO: health
// TODO: armor
// Non-persisted
glm::ivec3 cpos;
std::atomic<CompressedIVec3> atomic_cpos;
glm::mat4 orientation;
bool broadcasted;
bool digging_on;
Timestamp digging_start;
glm::ivec3 digging_block;
bool load();
bool save();
void start_digging(glm::ivec3 cube);
void turn(float dx, float dy);
};
bool g_collision = true;
Player g_player;
double scroll_y = 0, scroll_dy = 0;
void Player::turn(float dx, float dy)
{
yaw += dx;
pitch += dy;
if (pitch > M_PI / 2 * 0.999) pitch = M_PI / 2 * 0.999;
if (pitch < -M_PI / 2 * 0.999) pitch = -M_PI / 2 * 0.999;
orientation = glm::rotate(glm::rotate(glm::mat4(), -yaw, glm::vec3(0, 0, 1)), -pitch, glm::vec3(1, 0, 0));
broadcasted = false;
}
void Player::start_digging(glm::ivec3 cube)
{
digging_on = true;
digging_block = cube;
digging_start = Timestamp();
}
json_t* json_vec3(glm::vec3 a)
{
json_t* v = json_array();
json_array_append(v, json_real(a.x));
json_array_append(v, json_real(a.y));
json_array_append(v, json_real(a.z));
return v;
}
bool Player::save()
{
json_t* doc = json_object();
Auto(json_decref(doc));
json_object_set(doc, "position", json_vec3(position));
json_object_set(doc, "yaw", json_real(yaw));
json_object_set(doc, "pitch", json_real(pitch));
json_object_set(doc, "velocity", json_vec3(velocity));
json_object_set(doc, "creative_mode", json_boolean(creative_mode));
json_object_set(doc, "palette_block", json_integer((int)palette_block - (int)Block::water));
json_object_set(doc, "console", console.save());
CHECK(0 == json_dump_file(doc, "player.json", JSON_INDENT(4) | JSON_PRESERVE_ORDER));
return true;
}
bool json_read(json_t* a, float& out)
{
CHECK(json_is_real(a));
out = json_real_value(a);
return true;
}
bool json_read(json_t* a, glm::vec3& out)
{
CHECK(json_is_array(a));
CHECK(json_array_size(a) == 3);
CHECK(json_read(json_array_get(a, 0), out.x));
CHECK(json_read(json_array_get(a, 1), out.y));
CHECK(json_read(json_array_get(a, 2), out.z));
return true;
}
bool json_read(json_t* a, int64_t& out)
{
CHECK(json_is_integer(a));
out = json_integer_value(a);
return true;
}
bool json_read(json_t* a, bool& out)
{
CHECK(json_is_boolean(a));
out = json_boolean_value(a);
return true;
}
bool Player::load()
{
// load defaults
position = glm::vec3(0, 0, 20);
yaw = 0;
pitch = 0;
velocity = glm::vec3(0, 0, 0);
creative_mode = true;
palette_block = Block::water;
FILE* file = fopen("player.json", "r");
CHECK(file || errno == ENOENT);
if (file)
{
Auto(fclose(file));
json_error_t error;
json_t* doc = json_loadf(file, 0, &error);
if (!doc)
{
fprintf(stderr, "JSON error: line=%d column=%d position=%d source='%s' text='%s'\n", error.line, error.column, error.position, error.source, error.text);
return false;
}
assert(doc->refcount == 1);
Auto(json_decref(doc));
CHECK(json_is_object(doc));
#define read(K, V) { json_t* value = json_object_get(doc, K); CHECK(value); CHECK(json_read(value, V)); }
read("position", position);
read("yaw", yaw);
read("pitch", pitch);
read("velocity", velocity);
read("creative_mode", creative_mode);
CHECK(console.load(json_object_get(doc, "console")));
int64_t pb;
read("palette_block", pb);
CHECK(pb >= 0 && pb < block_count - (int)Block::water);
palette_block = (Block)(pb + (int)Block::water);
#undef read
}
scroll_y = (uint)palette_block - (uint)Block::water;
orientation = glm::rotate(glm::rotate(glm::mat4(), -yaw, glm::vec3(0, 0, 1)), -pitch, glm::vec3(1, 0, 0));
cpos = glm::ivec3(glm::floor(position)) >> ChunkSizeBits;
atomic_cpos = compress_ivec3(cpos);
digging_on = false;
broadcasted = false;
return true;
}
// ===============
struct Mesh
{
bool load(const char* filename);
void bounding_box(glm::vec3& min, glm::vec3& max) const;
struct Face
{
uint verts[3];
};
std::vector<glm::vec3> vertices;
std::vector<Face> faces;
};
bool Mesh::load(const char* filename)
{
FILE* f = fopen(filename, "r");
PlyFile* pf = read_ply(f);
PlyProperty vert_prop_x = { const_cast<char*>("x"), Float32, Float32, offsetof(glm::vec3, x), 0, 0, 0, 0 };
PlyProperty vert_prop_y = { const_cast<char*>("y"), Float32, Float32, offsetof(glm::vec3, y), 0, 0, 0, 0 };
PlyProperty vert_prop_z = { const_cast<char*>("z"), Float32, Float32, offsetof(glm::vec3, z), 0, 0, 0, 0 };
PlyProperty face_prop = { const_cast<char*>("vertex_indices"), Int32, Int32, offsetof(Face, verts), 3/*LIST_FIXED*/, Uint8, Uint8, 3/*num verts*/ };
CHECK(pf->num_elem_types == 2);
// Read vertex list
int count;
char* elem_name = setup_element_read_ply(pf, 0, &count);
CHECK(strcmp(elem_name, "vertex") == 0);
CHECK(count >= 0);
CHECK(pf->elems[0]->nprops == 3);
CHECK(strcmp(pf->elems[0]->props[0]->name, "x") == 0);
CHECK(strcmp(pf->elems[0]->props[1]->name, "y") == 0);
CHECK(strcmp(pf->elems[0]->props[2]->name, "z") == 0);
CHECK(pf->elems[0]->props[0]->is_list == 0);
CHECK(pf->elems[0]->props[1]->is_list == 0);
CHECK(pf->elems[0]->props[2]->is_list == 0);
setup_property_ply(pf, &vert_prop_x);
setup_property_ply(pf, &vert_prop_y);
setup_property_ply(pf, &vert_prop_z);
vertices.resize(count);
for (int i = 0; i < count; i++)
{
get_element_ply(pf, &vertices[i]);
std::swap(vertices[i].y, vertices[i].z);
}
// Read face list
elem_name = setup_element_read_ply(pf, 1, &count);
CHECK(strcmp(elem_name, "face") == 0);
CHECK(count >= 0);
CHECK(pf->elems[1]->nprops == 1);
CHECK(strcmp(pf->elems[1]->props[0]->name, "vertex_indices") == 0);
CHECK(pf->elems[1]->props[0]->is_list == 1);
setup_property_ply(pf, &face_prop);
faces.resize(count);
for (int i = 0; i < count; i++)
{
Face& face = faces[i];
get_element_ply(pf, &face);
CHECK(pf->error == 0);
}
free_ply(pf);
fclose(f);
return true;
}
void Mesh::bounding_box(glm::vec3& min, glm::vec3& max) const
{
min = max = vertices[0];
for (uint i = 1; i < vertices.size(); i++)
{
glm::vec3 v = vertices[i];
if (v.x < min.x) min.x = v.x;
if (v.y < min.y) min.y = v.y;
if (v.z < min.z) min.z = v.z;
if (v.x > max.x) max.x = v.x;
if (v.y > max.y) max.y = v.y;
if (v.z > max.z) max.z = v.z;
}
}
// ===============
struct Chunk
{
Chunk() : m_cpos(x_bad_ivec3) { }
Block get(glm::ivec3 a) const { return m_blocks[a]; }
const Block* getp(glm::ivec3 a) const { return m_blocks.getp(a); }
const Blocks& blocks() const { return m_blocks; }
bool empty() const { return m_empty; }
void update_empty()
{
m_empty = true;
FOR(i, ChunkSize3) if (m_blocks.data()[i] != Block::none)
{
m_empty = false;
break;
}
}
void sort(glm::vec3 camera)
{
if (m_blended_quads > 0)
{
camera -= get_cpos() << ChunkSizeBits;
auto cmp = [camera](const Quad& a, const Quad& b) { return distance(a, camera) > distance(b, camera); };
std::sort(m_quads.end() - m_blended_quads, m_quads.end(), cmp);
}
}
void remesh(BlockRenderer& renderer, const Blocks* chunks[27])
{
renderer.generate_quads(get_cpos(), chunks, true/*!m_active*/, m_quads, m_blended_quads);
m_remesh = false;
}
int render()
{
glBufferData(GL_ARRAY_BUFFER, sizeof(Quad) * m_quads.size(), &m_quads[0], GL_STREAM_DRAW);
glDrawArrays(GL_POINTS, 0, m_quads.size());
return m_quads.size();
}
void init(glm::ivec3 cpos, Block blocks[ChunkSize3])
{
memcpy(m_blocks.data(), blocks, sizeof(Block) * ChunkSize3);
update_empty();
m_quads.clear();
m_cpos = cpos;
m_remesh = true;
}
glm::ivec3 get_cpos() { return m_cpos; }
bool m_remesh;
friend class Chunks;
private:
bool m_empty;
Blocks m_blocks;
glm::ivec3 m_cpos;
std::vector<Quad> m_quads;
int m_blended_quads;
};
class Chunks
{
public:
Chunks(): m_map(new Chunk[MapSize * MapSize * MapSize]) { }
Block get_block(glm::ivec3 pos)
{
Chunk& chunk = get(pos >> ChunkSizeBits);
assert(chunk.get_cpos() == (pos >> ChunkSizeBits));
return chunk.get(pos & ChunkSizeMask);
}
Block get_block(glm::ivec3 pos, Block def)
{
Chunk& chunk = get(pos >> ChunkSizeBits);
if (chunk.get_cpos() != (pos >> ChunkSizeBits)) return def;
return chunk.get(pos & ChunkSizeMask);
}
bool selectable_block(glm::ivec3 pos)
{
Chunk& chunk = get(pos >> ChunkSizeBits);
return chunk.get_cpos() == (pos >> ChunkSizeBits) && chunk.get(pos & ChunkSizeMask) != Block::none;
}
bool can_move_through(glm::ivec3 pos)
{
Chunk& chunk = get(pos >> ChunkSizeBits);
return chunk.get_cpos() == (pos >> ChunkSizeBits) && ::can_move_through(chunk.get(pos & ChunkSizeMask));
}
Chunk& get(glm::ivec3 cpos)
{
cpos &= MapSizeMask;
return m_map[((cpos.x * MapSize) + cpos.y) * MapSize + cpos.z];
}
Chunk* get_opt(glm::ivec3 cpos)
{
Chunk& chunk = get(cpos);
return (chunk.get_cpos() == cpos) ? &chunk : nullptr;
}
private:
Chunk* m_map; // Huge array in memory!
};
Chunks g_chunks;
// ======================
void server_main();
Socket g_client;
SocketBuffer g_recv_buffer;
SocketBuffer g_send_buffer;
bool g_fsync_ack;
void edit_block(glm::ivec3 pos, Block block)
{
write_text_message(g_send_buffer, "block %d %d %d %d", pos.x, pos.y, pos.z, block);
}
// <scale> is size (in blocks) of the largest extent of mesh.
void rasterize_mesh(const Mesh& mesh, glm::ivec3 base, float scale, Block block)
{
glm::vec3 min, max;
mesh.bounding_box(/*out*/min, /*out*/max);
glm::vec3 mesh_size = max - min;
float extent = glm::max(mesh_size.x, mesh_size.y, mesh_size.z);
float mesh_block = extent / scale; // size of block in model space
glm::ivec3 bmax = base + glm::ivec3(glm::floor(mesh_size / mesh_block));
FOR(i, mesh.faces.size())
{
const Mesh::Face& face = mesh.faces[i];
glm::vec3 va = mesh.vertices[face.verts[0]];
glm::vec3 vb = mesh.vertices[face.verts[1]];
glm::vec3 vc = mesh.vertices[face.verts[2]];
FOR(p, 3)
{
glm::vec3 v2 = glm::mix(va, vb, p * 0.5f);
FOR(q, 3)
{
glm::vec3 v3 = glm::mix(v2, vc, q * 0.5f);
glm::ivec3 pos = base + glm::ivec3(glm::floor((v3 - min) / mesh_block));
edit_block(pos, block);
}
}
}
}
// ======================
struct Direction
{
glm::vec3 dir;
glm::vec3 inv_dir;
};
struct Directions : public std::vector<Direction>
{
enum { Bits = 9 };
Directions()
{
const int M = 1 << Bits, N = M - 1;
FOR2(x, 1, M) FOR2(y, 1, M) for(int z = 1; z <= M; z++)
{
int d2 = x*x + y*y + z*z;
if (N*N < d2 && d2 <= M*M) for (int i : {-x, x}) for (int j : {-y, y})
{
add(i, j, z);
add(i, j, -z);
}
}
for (int m : {M, -M})
{
add(m, 0, 0);
add(0, m, 0);
add(0, 0, m);
}
FOR(i, size()) std::swap(operator[](std::rand() % size()), operator[](i));
}
void add(int x, int y, int z)
{
Direction e;
e.dir = glm::normalize(glm::vec3(x, y, z));
e.inv_dir = glm::abs(1.0f / e.dir);
push_back(e);
}
} directions;
int ray_it = 0;
int rays_remaining = 0;
VisibleChunks visible_chunks;
void raytrace(Chunk* chunk, glm::ivec3 pos, glm::ivec3 cpos, const Block* bp, glm::ivec3 id, glm::vec3 dd, glm::vec3 crossing)
{
const float MaxDist = RenderDistance * ChunkSize;
while (true)
{
if (crossing.x < crossing.y)
{
if (crossing.x < crossing.z)
{
if (crossing.x > MaxDist) return;
pos.x += id.x;
crossing.x += dd.x;
if (cpos.x != (pos.x >> ChunkSizeBits)) { cpos.x = pos.x >> ChunkSizeBits; goto next_chunk; }
bp += id.x;
}
else
{
if (crossing.z > MaxDist) return;
pos.z += id.z;
crossing.z += dd.z;
if (cpos.z != (pos.z >> ChunkSizeBits)) { cpos.z = pos.z >> ChunkSizeBits; goto next_chunk; }
bp += id.z * ChunkSize2;
}
}
else
{
if (crossing.y < crossing.z)