-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvorowrap.cpp
1533 lines (1345 loc) · 56 KB
/
vorowrap.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
// this will be a wrapper around voro++ functionality, helping exposing it to js (and threejs specifically)
#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <stdlib.h>
#include <math.h>
#ifdef EMSCRIPTEN
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#endif
#include "voro++/voro++.hh"
#include "glm/vec3.hpp"
#include "glm/gtx/norm.hpp"
using namespace std;
using namespace emscripten;
// define this to disable all (expensive, debugging-only) sanity checking; INSANITY is recommended for a final build
#define INSANITY
// define this to 1 to add the shared faces of neighboring cells that are both toggled 'on'; if the cells are solid, 0 is preferred
#define ADD_ALL_FACES_ALL_THE_TIME 0
// the minimum squared distance between two cells. If you try to move or add a cell closer to another cell than this threshold, the cell will be 'jittered' away from the colliding cell
#define SHADOW_SEP_DIST .003
#define SHADOW_THRESHOLD (SHADOW_SEP_DIST*SHADOW_SEP_DIST)
inline void jitter(glm::vec3 &pt, double amt) {
pt.x+=amt*(rand()%10000)/10000.0;
pt.y+=amt*(rand()%10000)/10000.0;
pt.z+=amt*(rand()%10000)/10000.0;
}
#ifdef INSANITY
#define SANITY(WHEN) {}
#else
#define SANITY(WHEN) {sanity(WHEN);}
#endif
// main is called once emscripten has asynchronously loaded all it needs to call the other C functions
// so we wait for its call to run the js init
int main() {
emscripten_run_script("ready_for_emscripten_calls = true;");
}
// indices to connect cell to voro++ container
struct CellConLink {
int ijk; // block index in voro++ container
int q; // index of the cell within the block (following var naming from c_loops.hh)
CellConLink() : ijk(-1), q(-1) {} // invalid / fail-fast defaults
CellConLink(const voro::c_loop_base &loop) : ijk(loop.ijk), q(loop.q) {}
CellConLink(int ijk, int q) : ijk(ijk), q(q) {}
bool valid() {
return ijk >= 0 && q >= 0;
}
void set(const voro::c_loop_base &loop) {
ijk = loop.ijk;
q = loop.q;
}
};
// defining information about cell
struct Cell {
glm::vec3 pos;
int type; // 0 is empty, non-zero is non-empty; can use different numbers as tags or material types
Cell() {}
Cell(glm::vec3 pos, int type) : pos(pos), type(type) {}
};
struct CellCache { // computations from a voro++ computed cell
vector<int> faces; // faces as voro++ likes to store them -- packed as [#vs in f0, f0 v0, f0 v1, ..., #vs in f1, ...]
vector<double> vertices; // vertex coordinates, indexed by faces array
vector<int> neighbors; // cells neighboring each face
void clear() { faces.clear(); vertices.clear(); neighbors.clear(); }
void create(const glm::vec3 &pos, voro::voronoicell_neighbor &c) {
c.neighbors(neighbors);
// fills facev w/ faces as (#verts in face 1, face vert ind 1, ind 2, ..., #vs in f 2, f v ind 1, etc)
c.face_vertices(faces);
// makes all the vertices for the faces to reference
c.vertices(pos.x, pos.y, pos.z, vertices);
}
double doublearea(int i, int j, int k) {
double a[3] = {
vertices[j*3+0]-vertices[i*3+0],
vertices[j*3+1]-vertices[i*3+1],
vertices[j*3+2]-vertices[i*3+2]
};
double b[3] = {
vertices[k*3+0]-vertices[i*3+0],
vertices[k*3+1]-vertices[i*3+1],
vertices[k*3+2]-vertices[i*3+2]
};
double o[3] = {
a[1]*b[2]-a[2]*b[1],
a[2]*b[0]-a[0]*b[2],
a[0]*b[1]-a[1]*b[0]
};
return sqrt(o[0]*o[0]+o[1]*o[1]+o[2]*o[2]);
}
double face_size(int face) {
size_t i=0, fi=0;
for (; fi<face && i<faces.size(); fi++,i+=faces[i]+1) {}
double area = 0;
if (i<faces.size()) {
int vicount = faces[i];
int vs[3] = {faces[i+1], 0, faces[i+2]};
for (int j = i+3; j < i+vicount+1; j++) { // facev
vs[1] = faces[j];
area += doublearea(vs[0],vs[1],vs[2]);
vs[2] = vs[1];
}
}
return area*.5;
}
};
struct CellToTris {
vector<int> tri_inds; // indices into the GLBufferManager's vertices array, indicating which triangles are from this cell
// i.e. if tri_inds[0]==47, then vertices[47*3] ... vertices[47*3+2] (incl.) are from this cell
vector<short> tri_faces;
CellCache cache;
};
struct Voro;
struct GLBufferManager {
vector<float> vertices, wire_vertices, cell_sites, cell_site_sizes, colors;
bool want_colors;
int tri_count, max_tris, max_sites;
int wire_vert_count, wire_max_verts;
vector<int> cell_inds; // map from tri indices to cell indices
vector<short> cell_internal_inds; // map from tri indices to internal tri backref
voro::voronoicell_neighbor vorocell; // reused temp var, holds computed cell info
vector<CellToTris*> info;
GLBufferManager() : wire_vert_count(0), wire_max_verts(0), tri_count(0), max_tris(0), cell_inds(0), want_colors(false) {}
explicit operator bool() { return !info.empty(); }
bool sanity(string when, bool doassert=true) {
bool valid = true;
if (vertices.size() != colors.size() && want_colors) {
valid = false;
cout << "want vertex colors, but they're not matched to vertices" << endl;
}
if (!colors.empty() && !want_colors) {
valid = false;
cout << "don't want vertex colors, but somehow we still have " << colors.size() << " of them" << endl;
}
for (int ci=0; ci<tri_count; ci++) {
if (cell_inds[ci] < 0 || cell_inds[ci] >= info.size()) {
valid = false;
cout << "invalid cell! " << cell_inds[ci] << " vs " << info.size() << endl;
}
}
for (int i=0; i<info.size(); i++) {
if (info[i]) {
for (int ti : info[i]->tri_inds) {
if (cell_inds[ti] != i) {
valid = false;
cout << "invalid backlink " << cell_inds[ti] << " vs " << i << endl;
}
}
for (size_t nii=0; nii<info[i]->cache.neighbors.size(); nii++) {//(int ni : info[i]->cache.neighbors) {
int ni = info[i]->cache.neighbors[nii];
if (ni >= int(info.size())) {
valid = false;
cout << "neighbor index is out of bounds: " << i << ": " << ni << " vs " << info.size() << endl;
}
if (ni >= 0 && ni < int(info.size()) && info[ni]) {
bool backlink = false;
for (int nni : info[ni]->cache.neighbors) {
if (nni == i) {
backlink = true;
}
}
if (!backlink) {
cout << "neighbor " << i << " -> " << ni << " lacks backlink" << endl;
double face_area = info[i]->cache.face_size(nii);
if (face_area < 4.84704e-14) {
cout << "backlink error on face so small (" << face_area << ") so maybe we don't care?" << endl;
} else {
valid = false;
}
}
}
}
}
}
if (!valid) {
cout << "invalid " << when << endl;
}
assert(!doassert || valid);
return valid;
}
void resize_buffers() {
vertices.resize(max_tris*9);
cell_inds.resize(max_tris);
cell_internal_inds.resize(max_tris);
if (want_colors) {
colors.resize(vertices.size());
}
}
void resize_wire_buffers() {
wire_vertices.resize(wire_max_verts*3);
}
void resize_sites_buffers() {
cell_sites.resize(max_sites*3);
cell_site_sizes.resize(max_sites);
}
void set_want_colors(Voro &src, bool yes_colors); // call to change whether you want colors
void update_colors(Voro &src); // call whenever the palette changes to fix all existing colors
void init(int numCells, int triCapacity, int wiresCapacity, int sitesCapacity, bool want_colors) {
clear();
this->want_colors = want_colors;
max_tris = triCapacity;
wire_max_verts = wiresCapacity;
max_sites = numCells*2;
if (max_sites < sitesCapacity) max_sites = sitesCapacity;
resize_buffers();
resize_wire_buffers();
resize_sites_buffers();
tri_count = 0;
wire_vert_count = 0;
info.resize(numCells, 0);
}
void add_cell(Voro &src);
int vert2cell(int vi) {
if (vi < 0 || vi >= tri_count*3)
return -1;
return cell_inds[vi/3];
}
int vert2cell_neighbor(int vi) {
if (vi < 0 || vi >= tri_count*3) return -1;
int tri = vi / 3;
int cell = cell_inds[tri];
CellToTris *in = info[cell];
if (!in) return -1;
int fi = in->tri_faces[cell_internal_inds[tri]];
return in->cache.neighbors[fi];
}
inline void clear_cell_tris(CellToTris &c2t) {
for (int tri : c2t.tri_inds) {
swapnpop_tri(tri);
}
c2t.tri_inds.clear();
c2t.tri_faces.clear();
}
inline void clear_cell_cache(CellToTris &c2t) {
c2t.cache.clear();
}
inline void clear_cell_all(CellToTris &c2t) {
clear_cell_tris(c2t);
clear_cell_cache(c2t);
}
inline CellToTris& get_clean_cell(int cell) {
if (!info[cell]) {
info[cell] = new CellToTris();
} else {
clear_cell_all(*info[cell]);
}
return *info[cell];
}
void recompute_neighbors(Voro &src, int cell);
CellCache *get_cache(int cell) {
if (cell < 0 || cell >= info.size() || !info[cell]) {
return 0;
}
return &info[cell]->cache;
}
inline bool add_tri(const vector<double> &input_v, int* vs, int cell, CellToTris &c2t, int f, const glm::vec3 &color) {
if (tri_count+1 >= max_tris) {
max_tris *= 2;
resize_buffers();
}
float *v = &vertices[0] + tri_count*9;
for (int vii=0; vii<3; vii++) {
int ibase = vs[vii]*3;
for (int ii=0; ii<3; ii++) {
*v = input_v[ibase+ii];
v++;
}
}
if (want_colors) {
assert(vertices.size() == colors.size());
float *c = &colors[0] + tri_count*9;
for (int vii=0; vii<3; vii++) {
int ibase = vs[vii]*3;
for (int ii=0; ii<3; ii++) {
*c = color[ii];
c++;
}
}
}
cell_inds[tri_count] = cell;
cell_internal_inds[tri_count] = (short)c2t.tri_inds.size();
c2t.tri_inds.push_back(tri_count);
c2t.tri_faces.push_back(f);
tri_count++;
return true;
}
void set_cell(Voro &src, int cell, int oldtype);
void compute_cell(Voro &src, int cell); // compute caches for all cells and add tris for non-zero cells
void compute_all(Voro &src, int tricap, int wirecap, int sitescap, bool want_colors);
void compute_on(Voro &src, int tricap, int wirecap, int sitescap, bool want_colors);
void add_cell_tris(Voro &src, int cell, CellToTris &c2t);
void swapnpop_tri(int tri) {
if (tri+1 != tri_count) {
int ts = tri_count-1;
assert(ts > 0);
for (int ii=0; ii<9; ii++) {
vertices[tri*9+ii] = vertices[ts*9+ii];
}
if (want_colors) {
assert(vertices.size() == colors.size());
for (int ii=0; ii<9; ii++) {
colors[tri*9+ii] = colors[ts*9+ii];
}
}
cell_inds[tri] = cell_inds[ts];
cell_internal_inds[tri] = cell_internal_inds[ts];
info[cell_inds[tri]]->tri_inds[cell_internal_inds[tri]] = tri;
}
tri_count--;
}
void ensure_computed(Voro &src, int cell); // if src is ready to compute things, ensures that the cell is computed
void swapnpop_cell(Voro &src, int cell, int lasti);
void move_cell(Voro &src, int cell);
void move_cells(Voro &src, const unordered_set<int> &cells);
void update_site(Voro &src, int cell);
inline void update_site_pos(const glm::vec3 &pos, int cell) {
assert(cell >= 0 && cell < cell_sites.size());
cell_sites[cell*3] = pos.x;
cell_sites[cell*3+1] = pos.y;
cell_sites[cell*3+2] = pos.z;
}
inline void update_site_size(float size, int cell) {
cell_site_sizes[cell] = size;
}
void add_wires(Voro &src, int cell);
inline void add_wire_vert(const vector<double> &vertices, int vi) {
assert(vi*3+2 < vertices.size());
if (wire_vert_count >= wire_max_verts) {
wire_max_verts *= 2;
resize_wire_buffers();
}
float *buf = &wire_vertices[0] + (wire_vert_count*3);
*buf = vertices[vi*3]; buf++;
*buf = vertices[vi*3+1]; buf++;
*buf = vertices[vi*3+2]; buf++;
wire_vert_count++;
}
void clear_wires() {
wire_vert_count = 0;
}
void clear() {
vertices.clear();
cell_inds.clear();
wire_vertices.clear();
cell_sites.clear();
cell_site_sizes.clear();
colors.clear();
tri_count = max_tris = max_sites = 0;
for (auto *c : info) {
delete c;
}
info.clear();
}
};
// simple index mesh struct, to be used for export to an index mesh format
struct SimpleIndexMesh {
std::vector<int> faces; // voro-style face list: [size1, v1, v2, v3, ..., vSize, size2, etc]
std::vector<int> palette; // palette index per face
std::vector<double> vertices;
};
enum { SANITY_MINIMAL, SANITY_FULL, SANITY_EXCESSIVE };
struct Voro {
Voro()
: b_min(glm::vec3(-10)), b_max(glm::vec3(10)), con(0), sanity_level(SANITY_FULL), tracked_ids(0) {}
Voro(glm::vec3 bound_min, glm::vec3 bound_max)
: b_min(bound_min), b_max(bound_max), con(0), sanity_level(SANITY_FULL), tracked_ids(0) {}
~Voro() {
clear_all();
}
template<typename T> bool compare_vecs(vector<T> a, vector<T> b, string name, int tag) {
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (!equal(a.begin(), a.end(), b.begin())) {
cout << name << " mismatched on " << tag << endl << "F: ";
for (const auto &i: a)
cout << i << ' ';
cout << endl << "T: ";
for (const auto &i: b)
cout << i << ' ';
cout << endl;
return false;
} else {
return true;
}
}
bool sanity(string when) {
bool valid = true;
if (sanity_level > 0) {
valid = gl_computed.sanity(when, false);
}
for (int cell=0; cell<links.size(); cell++) {
const auto &link = links[cell];
if (link.ijk >= 0 && link.q < 0) {
cout << "partially valid link " << cell << ": " << link.ijk << " " << link.q << endl;
valid = false;
}
}
if (sanity_level > 0) {
if (gl_computed.info.size() > 0) {
if (gl_computed.info.size() != cells.size()) {
cout << "computed info cells mismatch voro cells: " << gl_computed.info.size() << " vs " << cells.size() << endl;
valid = false;
}
for (int i=0; i<cells.size(); i++) {
CellCache cache;
if (gl_computed.info[i]) {
auto &link = links[i];
if (link.valid()) {
if (con->compute_cell(gl_computed.vorocell, link.ijk, link.q)) {
cache.create(cells[i].pos, gl_computed.vorocell);
auto &vs = gl_computed.info[i]->cache;
valid = compare_vecs(vs.neighbors, cache.neighbors, "neighbors", i) && valid;
// bool fvalid = compare_vecs(vs.faces, cache.faces, "faces", i);
// valid = fvalid && valid;
// valid = compare_vecs(vs.vertices, cache.vertices, "vertices", i) && valid;
}
}
}
}
if (sanity_level > 1) {
// Use a pre_container to automatically figure out the right settings for the container we create
voro::pre_container pcon(b_min.x,b_max.x,b_min.y,b_max.y,b_min.z,b_max.z,false,false,false);
{
// iterating through particles && try to match order in the blocks to guarantee same numerical result
voro::c_loop_all vl(*con);
if (vl.start()) do {
int i = vl.pid();
pcon.put(i,cells[i].pos.x,cells[i].pos.y,cells[i].pos.z);
} while(vl.inc());
}
// Set up the number of blocks that the container is divided into
int n_x, n_y, n_z;
pcon.guess_optimal(n_x,n_y,n_z);
// Set up the container class and import the particles from the pre-container
voro::container dcon(pcon.ax,pcon.bx,pcon.ay,pcon.by,pcon.az,pcon.bz,n_x,n_y,n_z,false,false,false,10);
pcon.setup(dcon);
// build links
voro::c_loop_all vl(dcon);
voro::voronoicell_neighbor vorocell;
CellCache cache;
if(vl.start()) do {
int i = vl.pid();
if (dcon.compute_cell(vorocell, vl.ijk, vl.q)) {
cache.create(cells[i].pos, vorocell);
if (gl_computed.info[i]) {
auto &vs = gl_computed.info[i]->cache;
bool nvalid = compare_vecs(vs.neighbors, cache.neighbors, " full-recon neighbors", i);
bool fvalid = compare_vecs(vs.faces, cache.faces, " full-recon faces", i);
valid = valid && nvalid && fvalid;
if (!nvalid || !fvalid) {
cout << "cell[" << i << "].pos = " << cells[i].pos.x << ", " << cells[i].pos.y << ", " << cells[i].pos.z << endl;
}
} else {
cout << "no info for valid cell?" << endl;
valid = false;
}
}
} while(vl.inc());
}
}
}
if (!valid) {
cout << "sanity check on Voro failed: " << when << endl;
}
assert(valid);
return valid;
}
void clear_all() {
clear_computed();
clear_input();
}
// clears the input from which the voronoi diagram would be build (the point set)
void clear_input() {
cells.clear();
}
// clears out just the buffers + cached cell computations used for rendering
void clear_gl() {
gl_computed.clear();
}
// clears out all computed structures of the voronoi diagram.
void clear_computed() {
delete con; con = 0;
links.clear();
gl_computed.clear();
}
void set_only_centermost(int centermost_type, int other_type) {
if (cells.empty()) return;
int minc = 0;
double minl = glm::length2(cells[0].pos);
set_cell(0, other_type);
for (size_t i=1; i<cells.size(); i++) {
double pl = glm::length2(cells[i].pos);
if (pl < minl) {
minc = i;
minl = pl;
}
set_cell(i, other_type);
}
set_cell(minc, centermost_type);
}
void set_all(int type) {
for (size_t i=0; i<cells.size(); i++) {
set_cell(i, type);
}
}
void set_fill(double target_fill, int rand_seed) {
if (cells.empty()) return;
srand(rand_seed);
if (target_fill <= 0 || target_fill >= 1) {
set_all(target_fill >= 1);
return;
}
float fill = get_fill();
float newfill = fill;
const float one_cell_fill = (1.0/float(cells.size()));
int needs_more_fill = fill < target_fill;
while (needs_more_fill == (newfill < target_fill)) {
int ci = rand() % cells.size();
if ((!cells[ci].type) == needs_more_fill) {
set_cell(ci, needs_more_fill);
newfill = newfill + (2*needs_more_fill-1)*one_cell_fill;
}
}
}
float get_fill() {
int nonz = 0;
for (size_t i=0; i<cells.size(); i++) {
nonz += !!cells[i].type;
}
return float(nonz) / float(cells.size());
}
// assuming cells vector is already created, now create the container for holding the cells
void build_container() {
clear_computed(); // clear out any existing computation
auto d = b_max-b_min;
float ilscale = pow(double(cells.size())/(voro::optimal_particles*d.x*d.y*d.z),1.0/3.0);
auto n = d*ilscale;
con = new voro::container(b_min.x,b_max.x,b_min.y,b_max.y,b_min.z,b_max.z,int(n.x+1),int(n.y+1),int(n.z+1),false,false,false,10);
// build links
assert(links.size() == 0);
links.resize(cells.size());
for (int i=0; i<cells.size(); i++) {
auto &link = links[i];
auto &pt = cells[i].pos;
while (con->already_in_container(pt.x, pt.y, pt.z, SHADOW_THRESHOLD) >= 0) {
jitter(pt, SHADOW_SEP_DIST);
}
bool ret = con->put(i, pt.x, pt.y, pt.z, link.ijk, link.q);
if (!ret) { link = CellConLink(); } // reset link if put fails
}
}
int cell_at_pos(glm::vec3 pt) {
assert(con);
return con->already_in_container(pt.x, pt.y, pt.z, SHADOW_THRESHOLD);
}
int add_cell(glm::vec3 pt, int type) {
while (con && con->already_in_container(pt.x, pt.y, pt.z, SHADOW_THRESHOLD) >= 0) {
jitter(pt, SHADOW_SEP_DIST);
}
int id = int(cells.size());
cells.push_back(Cell(pt, type));
if (con) {
CellConLink link;
bool ret = con->put(id, pt.x, pt.y, pt.z, link.ijk, link.q);
if (!ret) { link = CellConLink(); } // reset to invalid default when put fails
links.push_back(link);
assert(cells.size() == links.size());
gl_computed.add_cell(*this);
}
SANITY("after add_cell");
return id;
}
void debug_print_block(int ijk, int q) {
if (con) {
con->print_block(ijk, q);
} else {
cout << "no con; cannot print any block yet!" << endl;
}
}
bool move_cell(int cell, glm::vec3 pt) { // similar to a delete+add, but w/ no swapping and less recomputation
if (cell < 0 || cell >= cells.size()) {
cout << "move_cell called w/ invalid cell (index out of range): " << cell << endl;
return false;
}
while (con && con->already_in_container(pt.x, pt.y, pt.z, SHADOW_THRESHOLD, cell) >= 0) {
jitter(pt, SHADOW_SEP_DIST);
}
gl_computed.ensure_computed(*this, cell);
cells[cell].pos = pt;
if (!links.empty()) {
assert(links.size() == cells.size());
if (con) {
int needsupdate_q;
int needsupdate = con->move(links[cell].ijk, links[cell].q, cell, pt.x, pt.y, pt.z, needsupdate_q);
if (needsupdate > -1) { // we updated q of this element, so we need to update external backrefs to reflect that
links[needsupdate].q = needsupdate_q; // only updating q is ok, since the swapnpop won't change the ijk
}
}
gl_computed.move_cell(*this, cell);
}
SANITY("after move_cell");
return true;
}
void set_palette(val p) {
int len = p["length"].as<int>();
palette.clear();
for (int i=0; i<len; i++) {
glm::vec3 color(p[i][0].as<float>(), p[i][1].as<float>(), p[i][2].as<float>());
palette.push_back(color);
}
if (gl_computed) {
gl_computed.set_want_colors(*this, has_colors());
}
}
bool move_cells(val cells_to_move, val posns) { // similar to a delete+add, but w/ no swapping and less recomputation'
int len = cells_to_move["length"].as<int>();
unordered_set<int> moved_cells;
for (int i=0; i<len; i++) {
int cell = cells_to_move[i].as<int>();
if (cell < 0 || cell >= cells.size()) {
cout << "move_cell called w/ invalid cell (index out of range): " << cell << endl;
continue;
}
gl_computed.ensure_computed(*this, cell);
glm::vec3 pt(posns[i][0].as<float>(), posns[i][1].as<float>(), posns[i][2].as<float>());
while (con && con->already_in_container(pt.x, pt.y, pt.z, SHADOW_THRESHOLD, cell) >= 0) {
jitter(pt, SHADOW_SEP_DIST);
}
cells[cell].pos = pt;
moved_cells.insert(cell);
if (!links.empty()) {
assert(links.size() == cells.size());
if (con) {
int needsupdate_q;
int needsupdate = con->move(links[cell].ijk, links[cell].q, cell, pt.x, pt.y, pt.z, needsupdate_q);
if (needsupdate > -1) { // we updated q of this element, so we need to update external backrefs to reflect that
links[needsupdate].q = needsupdate_q; // only updating q is ok, since the swapnpop won't change the ijk
}
}
}
}
gl_computed.move_cells(*this, moved_cells);
SANITY("after move_cells");
return true;
}
bool delete_cell(int cell) { // this is a swapnpop deletion
if (cell < 0 || cell >= cells.size()) { // can't delete out of range
cout << "trying to delete out of range " << cell << " vs " << cells.size() << endl;
return false;
}
int end_ind = int(cells.size())-1;
// if we're deleting a cell that wasn't computed, but we've built links and all, compute it so we have valid nbr info there
gl_computed.ensure_computed(*this, cell);
if (end_ind != cell) {
gl_computed.ensure_computed(*this, end_ind);
}
cells[cell] = cells[end_ind];
update_stable_id(end_ind, cell);
cells.pop_back();
if (!links.empty()) {
assert(links.size() == cells.size()+1);
if (con) { // swapnpop inside the container
if (links[cell].valid()) {
int needsupdate = con->swapnpop(links[cell].ijk, links[cell].q);
if (needsupdate > -1) { // we updated q of this element, so we need to update external backrefs to reflect that
links[needsupdate].q = links[cell].q;
}
}
if (end_ind != cell && links[end_ind].valid()) {
con->id[links[end_ind].ijk][links[end_ind].q] = cell; // update the id of the cell we're swapping back
}
}
links[cell] = links[end_ind];
links.pop_back();
gl_computed.swapnpop_cell(*this, cell, end_ind);
}
SANITY("after delete_cell");
return true;
}
void gl_build(int max_tris_guess, int max_wire_verts_guess, int max_sites_guess) {
// populate gl_computed with current whole voronoi diagram
gl_computed.compute_on(*this, max_tris_guess, max_wire_verts_guess, max_sites_guess, has_colors());
}
uintptr_t gl_vertices() {
return reinterpret_cast<uintptr_t>(&gl_computed.vertices[0]);
}
void gl_add_wires(int cell) {
gl_computed.add_wires(*this, cell);
SANITY("after gl_add_wires");
}
void gl_clear_wires() {
gl_computed.clear_wires();
}
uintptr_t gl_wire_vertices() {
return reinterpret_cast<uintptr_t>(&gl_computed.wire_vertices[0]);
}
int gl_wire_vert_count() {
return gl_computed.wire_vert_count;
}
int gl_wire_max_verts() {
return gl_computed.wire_max_verts;
}
uintptr_t gl_cell_sites() {
return reinterpret_cast<uintptr_t>(&gl_computed.cell_sites[0]);
}
uintptr_t gl_cell_site_sizes() {
return reinterpret_cast<uintptr_t>(&gl_computed.cell_site_sizes[0]);
}
bool gl_is_live() {
return !!gl_computed;
}
int gl_max_sites() {
return gl_computed.max_sites;
}
int gl_tri_count() {
return gl_computed.tri_count;
}
int gl_max_tris() {
return gl_computed.max_tris;
}
int cell_count() {
return cells.size();
}
uintptr_t gl_colors() {
return reinterpret_cast<uintptr_t>(&gl_computed.colors[0]);
}
bool has_colors() {
return !palette.empty();
}
inline glm::vec3 get_color(int type) {
assert((type >= 1 && type <= palette.size()) || palette.empty());
if (type < 1 || type > palette.size()) {
return glm::vec3(1,1,1);
} else {
return palette[type-1];
}
}
void set_sanity_level(int sanity) {
sanity_level = sanity;
}
void toggle_cell(int cell, int nonzero_type) {
if (cell < 0 || cell >= cells.size())
return;
int oldtype = cells[cell].type;
cells[cell].type = oldtype ? 0 : nonzero_type;
gl_computed.set_cell(*this, cell, oldtype);
}
void set_cell(int cell, int type) {
if (cell < 0 || cell >= cells.size() || type==cells[cell].type)
return;
int oldtype = cells[cell].type;
cells[cell].type = type;
if (cell < gl_computed.info.size()) {
gl_computed.set_cell(*this, cell, oldtype);
}
}
int cell_from_vertex(int vert_ind) {
return gl_computed.vert2cell(vert_ind);
}
int cell_neighbor_from_vertex(int vert_ind) {
return gl_computed.vert2cell_neighbor(vert_ind);
}
glm::vec3 cell_pos(int cell) {
assert(cell>=0 && cell<cells.size());
return cells[cell].pos;
}
int cell_type(int cell) {
assert(cell>=0 && cell<cells.size());
return cells[cell].type;
}
bool cell_affects_shape(int cell) {
assert(cell>=0 && cell<cells.size());
auto cellType = cells[cell].type;
if (gl_computed.info[cell]) {
for (auto ni : gl_computed.info[cell]->cache.neighbors) {
if (ni >= 0 && cells[ni].type != cellType) {
return true;
}
}
}
return false;
}
Cell cell(int c) {
assert(c>=0 && c<cells.size());
return cells[c];
}
size_t stable_id(int cell) {
if (!cell_to_id.count(cell)) {
auto id = tracked_ids++;
cell_to_id[cell] = id;
id_to_cell[id] = cell;
}
assert(id_to_cell[cell_to_id[cell]] == cell);
return cell_to_id[cell];
}
// use this to re-associate cells to ids, e.g. if you undo a deletion.
// cell and id must both be unmapped when this is called.
// id must be one that has already been used (< tracked_ids) so that it will not collide with new ids.
void set_stable_id(int cell, size_t id) {
// only allow setting id for cells that do not have an id yet
assert(!id_to_cell.count(id));
assert(!cell_to_id.count(cell));
assert(id < tracked_ids);
id_to_cell[id] = cell;
cell_to_id[cell] = id;
}
int index_from_id(size_t id) {
if (!id_to_cell.count(id)) {
return -1;
} else {
assert(cell_to_id[id_to_cell[id]] == id);
return id_to_cell[id];
}
}
// exports from gl_computed's cached cells; won't work if there is no cache yet
SimpleIndexMesh export_index_mesh() {
SimpleIndexMesh m;
double coincidentVertTolerance = 1e-7;
vector<vector<pair<int,int>>> cnf; // cnf==CellNeighborFace: cnf[cell_index] = unordered vector of pair<neighbor cell index, index of face in cell that goes to that neighbor>
vector<vector<pair<int,int>>> clg; // clg==CellLocalGlobal: clg[cell_index] = unordered vector of pair<local_vertex_index, global_vertex_index>
cnf.resize(cells.size());
clg.resize(cells.size());
auto findPair = [](vector<pair<int, int>> &pairs, int target) {
for (int i=0, n=(int)pairs.size(); i<n; i++) {
if (pairs[i].first == target) {
return i;
}
}
return -1;
};
auto getOrAddCNF = [&](int cell, int neighborIndex, int localFaceIndex) {
int pairi = findPair(cnf[cell], neighborIndex);
if (pairi > -1) {
return cnf[cell][pairi].second;
}
// face not found; add to neighbor a back ref to this cell's face index
cnf[neighborIndex].push_back(pair<int,int>(cell, localFaceIndex));
return -1;
};
auto tovec = [](const vector<double> &vts, int i) {
return glm::vec3(vts[i*3], vts[i*3+1], vts[i*3+2]);
};
vector<int> gvp; // global vertex parent indices
vector<double> gv; // global vertices (x,y,z)*num_verts
auto mergev = [&](int ai, int bi) {
if (ai == bi) return; // no merge needed
assert(glm::distance2(tovec(gv, ai), tovec(gv, bi)) < coincidentVertTolerance);
// find the great grandparent of b
int btop = bi;
while (gvp[btop] != -1) {
btop = gvp[btop];
}
// set the parent of everything in a to the gp of b
int atraverse = ai;
while (atraverse != -1) {
int nexta = gvp[atraverse];
if (atraverse == btop) { // they were already merged ...
return;
}
gvp[atraverse] = btop;
atraverse = nexta;
}
};
auto addVToExisting = [&](int newCell, int newLocalIndex, int oldCell, int oldLocalIndex) {
int pairi = findPair(clg[oldCell], oldLocalIndex);
assert(pairi > -1);
int alreadyMatchedPairi = findPair(clg[newCell], newLocalIndex);
if (alreadyMatchedPairi == -1) {
clg[newCell].push_back(pair<int,int>(newLocalIndex, clg[oldCell][pairi].second));
} else {
mergev(clg[newCell][alreadyMatchedPairi].second, clg[oldCell][pairi].second);