-
Notifications
You must be signed in to change notification settings - Fork 2
/
octree.cpp
1430 lines (1251 loc) · 54.2 KB
/
octree.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
#include "cad.h"
#include "octree.h"
// #include "glut-c.h"
// #include "c-stub.h"
const bool is_print = false;
extern bool is_interpolating;
inline Octree* mark_leaf(Octree* tree, bool is_empty, bool is_filled, bool is_reproducible) {
if (is_print) printf("REPRODUCIBLE %d\n", is_reproducible);
tree->kind = is_empty ? voxel_empty_kind : (is_filled ? voxel_filled_kind : voxel_leaf_kind);
return tree;
}
extern bool is_epsilon_target;
Octree* do_octree(Octree* parent, Fun* g, const Vec &lo, const Vec &hi, const flo_t r, flo_t t, int d) {
// Octree* octree(Octree* parent, Geom* g, const Vec &p, const flo_t r, flo_t t, int d) {
const Vec p = (lo + hi) * 0.5;
auto bounds = box(lo, hi);
// auto i = g->range(bounds);
// printf("PRUNING ");
// auto ng = g->is_prune() ? g->prune(d) : g;
Interval i;
auto ng = g->maybe_prune(d, i, bounds);
// if (ng == g) printf("-->NO\n"); else printf("-->YES\n");
// auto ng = g;
if (is_print) for (int i = 0; i < d; i++) printf(" ");
if (is_print) printf("VOX %f,%f,%f I %f,%f R %f ", p.x, p.y, p.z, i.lo, i.hi, r);
if (i.lo >= 0.0) {
if (is_print) printf("EMPTY\n");
return new Octree(ng, parent, lo, hi, voxel_empty_kind);
} else if (i.hi < 0.0) {
if (is_print) printf("FILLED\n");
return new Octree(ng, parent, lo, hi, voxel_filled_kind);
} else {
auto res = new Octree(ng, parent, lo, hi, voxel_parent_kind);
bool is_empty = true;
bool is_filled = true;
int i = 0;
// printf("GEOM %s\n", ng->to_str().c_str());
for (int dx = -1; dx <= 1; dx += 2) {
for (int dy = -1; dy <= 1; dy += 2) {
for (int dz = -1; dz <= 1; dz += 2) {
auto tp = p + vec((T)dx,(T)dy,(T)dz) * r;
auto dv = res->u.d[i++] = ng->dist(tp);
if (dv < 0)
is_empty = false;
else
is_filled = false;
}
}
}
if (r <= t)
return mark_leaf(res, is_empty, is_filled, false);
if (is_interpolating) {
bool is_reproducible = true;
auto target = is_epsilon_target ? EPSILON : t; // TODO: > t EPSILON
for (int dx = -1; dx <= 1; dx += 1) {
for (int dy = -1; dy <= 1; dy += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
if (dx == 0 || dy == 0 || dz == 0) {
auto tp = p + vec((T)dx,(T)dy,(T)dz) * r;
auto cd = ng->dist(tp);
auto id = res->interpolate_one(tp);
if (fabs(cd - id) > target || ((id < 0) != (cd < 0)))
is_reproducible = false;
}
}
}
}
if (is_reproducible)
return mark_leaf(res, is_empty, is_filled, true);
}
if (is_print) printf("INTERNAL\n");
auto r2 = r * 0.5;
int k = 0;
for (int dx = -1; dx <= 1; dx += 2) {
for (int dy = -1; dy <= 1; dy += 2) {
for (int dz = -1; dz <= 1; dz += 2) {
const Vec c_lo(dx<0?lo.x:p.x, dy<0?lo.y:p.y, dz<0?lo.z:p.z);
const Vec c_hi(dx<0?p.x:hi.x, dy<0?p.y:hi.y, dz<0?p.z:hi.z);
res->u.children[k++] = do_octree(res, ng, c_lo, c_hi, r2, t, d + 1);
}
}
}
return res;
}
}
Octree* octree(Fun* g, const Vec &lo, const Vec &hi, const flo_t r, flo_t t) {
return do_octree(NULL, g, lo, hi, r, t, 0);
}
Octree* Octree::do_slice(Octree* parent, const flo_t z) {
auto out = new Octree(g, parent, vec(lo.x, lo.y, z), vec(hi.x, hi.y, z), voxel_parent_kind);
if (kind == voxel_leaf_kind) {
out->kind = voxel_leaf_kind;
for (int i=0; i < 8; ++i) {
out->u.d[i] = interpolate_one(vec(i & 4 ? hi.x : lo.x, i & 2 ? hi.y : lo.y, z));
}
} else if (kind == voxel_filled_kind) {
out->kind = voxel_filled_kind;
} else if (kind == voxel_empty_kind) {
out->kind = voxel_empty_kind;
} else if (kind == voxel_parent_kind) {
uint8_t upper = u.children[1] && z > u.children[1]->lo.z;
for (int i=0; i < 8; i += 1) {
out->u.children[i] = i&1 ? NULL : u.children[i+upper]->do_slice(out, z);
}
}
return out;
}
Octree* Octree::slice(const flo_t z) {
return do_slice(NULL, z);
}
Octree* Octree::lookup(const Vec &p) {
if (is_inside(p))
return leaf(p);
else
return NULL;
}
Octree* Octree::leaf(const Vec &p) {
if (kind == voxel_parent_kind)
return u.children[child_index(p)]->leaf(p);
else
return this;
}
static flo_t max_double = 1e9;
flo_t Octree::interpolate(const Vec &p) {
if (is_inside(p))
return do_interpolate(p);
else
return max_double;
}
flo_t Octree::do_interpolate(const Vec &p) {
if (kind == voxel_parent_kind)
return u.children[child_index(p)]->do_interpolate(p);
else
return interpolate_one(p);
}
void Octree::all_voxels(std::vector<Octree*> &voxels) {
voxels.push_back(this);
if (kind == voxel_parent_kind)
for (int i = 0; i < 8; i++)
u.children[i]->all_voxels(voxels);
}
void Octree::boundary_voxels(std::vector<Octree*> &voxels) {
if (kind == voxel_leaf_kind)
voxels.push_back(this);
if (kind == voxel_parent_kind)
for (int i = 0; i < 8; i++)
u.children[i]->boundary_voxels(voxels);
}
void two_tris(const Vec &p00, const Vec &p01, const Vec &p10, const Vec &p11, std::vector<Tri> &tris) {
tris.push_back(tri(p00, p10, p11));
tris.push_back(tri(p00, p11, p01));
}
std::vector<Tri> voxels_triangles(std::vector<Octree*> &voxels) {
std::vector<Tri> res;
for (auto v : voxels) {
const Vec l = v->lo;
const Vec h = v->hi;
two_tris(vec(l.x,l.y,l.z),vec(l.x,l.y,h.z),vec(l.x,h.y,l.z),vec(l.x,h.y,h.z),res);
two_tris(vec(l.x,l.y,l.z),vec(l.x,l.y,h.z),vec(h.x,l.y,l.z),vec(h.x,l.y,h.z),res);
two_tris(vec(l.x,l.y,l.z),vec(l.x,h.y,l.z),vec(h.x,l.y,l.z),vec(h.x,h.y,l.z),res);
two_tris(vec(h.x,l.y,l.z),vec(h.x,l.y,h.z),vec(h.x,h.y,l.z),vec(h.x,h.y,h.z),res);
two_tris(vec(l.x,h.y,l.z),vec(l.x,h.y,h.z),vec(h.x,h.y,l.z),vec(h.x,h.y,h.z),res);
two_tris(vec(l.x,l.y,h.z),vec(l.x,h.y,h.z),vec(h.x,l.y,h.z),vec(h.x,h.y,h.z),res);
}
return res;
}
void Octree::get_neighbors_3d
(const Octree* const old_nbrs[6], const Octree* new_nbrs[6], const uint8_t b) {
for (int i=0; i < 6; ++i) new_nbrs[i] = NULL;
if (!u.children[b]) return;
for (uint8_t axis=0; axis < 6; ++axis) {
uint8_t mask = 1 << (axis/2);
uint8_t dir = mask * (axis % 2);
// If we're pointing to within our own cell, then
// pick the interior neighbor.
if ( (b&mask)^dir && u.children[b^mask]) {
new_nbrs[axis] = u.children[b^mask];
}
// Correctly handle situations where a non-branch is
// next to a branch, but the branch only splits on
// the parallel axis. Ascii art:
//
// |---|---:---|
// | N | A : B |
// |---|---:---|
//
// N is the neighbor, the larger cell is splitting into
// A and B on the axis along which it touches N (and no
// others axes) so N remains a valid neighbor.
else if (old_nbrs[axis] && old_nbrs[axis]->kind == voxel_leaf_kind) {
bool crack = false;
for (int split=0; split < 3; ++split) {
if ((1 << split) & mask) continue;
if (u.children[1<<split] != NULL) crack = true;
}
new_nbrs[axis] = crack ? NULL : old_nbrs[axis];
}
// Otherwise, check to see that the neighbor splits on
// the same axes (other than the one along which we're
// joining).
else if (old_nbrs[axis] && old_nbrs[axis]->kind == voxel_parent_kind) {
uint8_t split_mask = (old_nbrs[axis]->u.children[1] ? 1 : 0) |
(old_nbrs[axis]->u.children[2] ? 2 : 0) |
(old_nbrs[axis]->u.children[4] ? 4 : 0);
bool crack = false;
for (int split=0; split < 3; ++split) {
// If we split differently than our neighbor and
// this split isn't along the relevant axis, record
// that there's a crack here.
bool split_A = u.children[1<<split] != NULL;
bool split_B = old_nbrs[axis]->u.children[1<<split] != NULL;
if ((split_A ^ split_B) && !((1 << split) & mask)) {
crack = true;
}
}
// Pick the appropriate cell in the neighbor
if (crack) {
new_nbrs[axis] = NULL;
} else if (dir) {
new_nbrs[axis] = old_nbrs[axis]->u.children[(b &~mask) & split_mask];
} else {
new_nbrs[axis] = old_nbrs[axis]->u.children[(b | mask) & split_mask];
}
}
}
}
void Octree::get_neighbors_2d
(const Octree* const old_nbrs[4], const Octree* new_nbrs[4], uint8_t b) {
// Zero out the array elements
for (int i=0; i < 4; ++i) new_nbrs[i] = NULL;
if (!u.children[b]) return;
for (uint8_t axis=0; axis < 4; ++axis) {
uint8_t mask = 1 << (axis/2 + 1);
uint8_t dir = mask * (axis % 2);
// If we're pointing to within our own cell, then
// pick the interior neighbor.
if ( (b&mask)^dir && u.children[b^mask]) {
new_nbrs[axis] = u.children[b^mask];
}
else if (old_nbrs[axis] && old_nbrs[axis]->kind != voxel_parent_kind) {
new_nbrs[axis] = old_nbrs[axis];
}
// Otherwise, check to see that the neighbor splits on
// the same axes (other than the one along which we're
// joining).
else if (old_nbrs[axis] && old_nbrs[axis]->kind == voxel_parent_kind) {
uint8_t split_mask = (old_nbrs[axis]->u.children[2] ? 2 : 0) |
(old_nbrs[axis]->u.children[4] ? 4 : 0);
bool crack = false;
for (int split=0; split < 3; ++split) {
// If we split differently than our neighbor and
// this split isn't along the relevant axis, record
// that there's a crack here.
bool split_A = u.children[1<<split] != NULL;
bool split_B = old_nbrs[axis]->u.children[1<<split] != NULL;
if ((split_A ^ split_B) && !((1 << split) & mask)) {
crack = true;
}
}
if (crack) { // Multi-scale stitching is okay in 2D
new_nbrs[axis] = old_nbrs[axis];
} else if (dir) {
new_nbrs[axis] = old_nbrs[axis]->u.children[(b &~mask) & split_mask];
} else {
new_nbrs[axis] = old_nbrs[axis]->u.children[(b | mask) & split_mask];
}
}
}
}
static int rndi () {
return rand();
}
static int rndi (int mn, int mx) {
return (rndi() % (mx-mn+1)) + mn;
}
std::vector<Vec> voxels_points(std::vector<Octree*> &voxels, int n) {
flo_t tot_area = 0.0;
for (auto voxel : voxels)
tot_area += sqr(voxel->rad());
std::vector<Vec> res;
for (auto voxel : voxels) {
auto area = sqr(voxel->rad());
int vn = roundf(n * area / tot_area);
for (int i = 0; i < vn; i++) {
// res.push_back(voxel->rnd_vec());
res.push_back(voxel->sample_point());
}
}
return res;
}
std::vector< Segment<TV3> > voxels_gradients(std::vector<Octree*> &voxels, int n) {
flo_t tot_area = 0.0;
for (auto voxel : voxels)
tot_area += sqr(voxel->rad());
std::vector< Segment<TV3> > res;
for (auto voxel : voxels) {
auto area = sqr(voxel->rad());
int vn = roundf(n * area / tot_area);
for (int i = 0; i < vn; i++) {
res.push_back(voxel->sample_gradient());
}
}
return res;
}
// inline bool is_border (int ov, int cv) {
// return ov != -1 && ov != cv;
// }
inline bool is_border (Octree *ov, Octree *cv) {
return ov == NULL || (ov->kind != voxel_leaf_kind && ov->kind != voxel_filled_kind);
}
void print_voxel_box(Octree* voxel, const Boxy &box) {
/*
printf("CHECKING %p LO %f,%f,%f HI %f,%f,%f BOX LO %f,%f,%f HI %f,%f,%f -> %d\n",
voxel, voxel->lo.x, voxel->lo.y, voxel->lo.z, voxel->hi.x, voxel->hi.y, voxel->hi.z,
box.lo.x, box.lo.y, box.lo.z, box.hi.x, box.hi.y, box.hi.z,
voxel->is_overlap(box));
*/
}
void Octree::boundaries(const Boxy &box, std::vector< Octree* > &leaves) {
if (kind == voxel_leaf_kind) {
print_voxel_box(this, box);
if (is_overlap(box)) {
leaves.push_back(this);
}
} else if (kind == voxel_parent_kind) {
for (int i = 0; i < 8; i++) {
if (u.children[i]->is_overlap(box)) {
u.children[i]->boundaries(box, leaves);
}
}
}
}
void Octree::nbrs (const Boxy &box, std::vector< Octree* > &nbrs) {
Octree* p = parent;
if (p != NULL)
print_voxel_box(p, box);
while (p != NULL && !p->is_overlap(box)) {
print_voxel_box(p, box);
p = p->parent;
}
if (p != NULL) {
print_voxel_box(p, box);
p->boundaries(box, nbrs);
}
}
std::vector< Octree* > Octree::all_nbrs (void) {
std::vector< Octree* > res;
// nbrs(box(vec(lo.x+EPSILON,lo.y+EPSILON,lo.z-EPSILON),vec(hi.x-EPSILON,hi.y-EPSILON,lo.z-EPSILON)), res);
if (has_z_nbr())
nbrs(box(vec(lo.x+EPSILON,lo.y+EPSILON,hi.z+EPSILON),vec(hi.x-EPSILON,hi.y-EPSILON,hi.z+EPSILON)), res);
// nbrs(box(vec(lo.x+EPSILON,lo.y-EPSILON,lo.z+EPSILON),vec(hi.x-EPSILON,lo.y-EPSILON,hi.z-EPSILON)), res);
if (has_y_nbr())
nbrs(box(vec(lo.x+EPSILON,hi.y+EPSILON,lo.z+EPSILON),vec(hi.x-EPSILON,hi.y+EPSILON,hi.z-EPSILON)), res);
// nbrs(box(vec(lo.x-EPSILON,lo.y+EPSILON,lo.z+EPSILON),vec(lo.x-EPSILON,hi.y-EPSILON,hi.z-EPSILON)), res);
if (has_x_nbr())
nbrs(box(vec(hi.x+EPSILON,lo.y+EPSILON,lo.z+EPSILON),vec(hi.x+EPSILON,hi.y-EPSILON,hi.z-EPSILON)), res);
return res;
}
std::vector<Tri> Octree::boundary_voxel_triangles(flo_t r) {
std::vector<Octree*> voxels;
boundary_voxels(voxels);
printf("%d BOUNDARY VOXELS R %f\n", (int)voxels.size(), r);
return voxels_triangles(voxels);
}
std::vector<Tri> Octree::boundary_triangles(flo_t r) {
std::vector<Octree*> voxels;
boundary_voxels(voxels);
printf("%d BOUNDARY VOXELS R %f\n", (int)voxels.size(), r);
std::vector<Tri> res;
for (auto voxel : voxels) {
Vec off = voxel->hi - voxel->lo;
Vec c = voxel->center();
Vec l1 = c - off;
Vec h1 = c + off;
Vec l2 = voxel->lo;
Vec h2 = voxel->hi;
// int lc = lookup(c);
auto lc = voxel;
if (is_border(lookup(vec(l1.x, c.y, c.z)), lc))
two_tris(vec(l2.x,l2.y,l2.z),vec(l2.x,l2.y,h2.z),vec(l2.x,h2.y,l2.z),vec(l2.x,h2.y,h2.z),res);
if (is_border(lookup(vec(c.x, l1.y, c.z)), lc))
two_tris(vec(l2.x,l2.y,l2.z),vec(l2.x,l2.y,h2.z),vec(h2.x,l2.y,l2.z),vec(h2.x,l2.y,h2.z),res);
if (is_border(lookup(vec(c.x, c.y, l1.z)), lc))
two_tris(vec(l2.x,l2.y,l2.z),vec(l2.x,h2.y,l2.z),vec(h2.x,l2.y,l2.z),vec(h2.x,h2.y,l2.z),res);
if (is_border(lookup(vec(h1.x, c.y, c.z)), lc))
two_tris(vec(h2.x,l2.y,l2.z),vec(h2.x,l2.y,h2.z),vec(h2.x,h2.y,l2.z),vec(h2.x,h2.y,h2.z),res);
if (is_border(lookup(vec(c.x, h1.y, c.z)), lc))
two_tris(vec(l2.x,h2.y,l2.z),vec(l2.x,h2.y,h2.z),vec(h2.x,h2.y,l2.z),vec(h2.x,h2.y,h2.z),res);
if (is_border(lookup(vec(c.x, c.y, h1.z)), lc))
two_tris(vec(l2.x,l2.y,h2.z),vec(l2.x,h2.y,h2.z),vec(h2.x,l2.y,h2.z),vec(h2.x,h2.y,h2.z),res);
}
return res;
}
std::vector< Segment<TV3> > voxels_boundary_lines(std::vector< Octree* > &voxels) {
std::vector< Segment<TV3> > res;
std::map< Octree*, Vec > centers;
for (auto voxel : voxels) {
centers[voxel] = voxel->boundary_point();
/*
do {
voxel->boundary_ctr = voxel->boundary_point(voxel->ctr + (rnd_vec_of(-voxel->rad, voxel->rad) * 0.1));
// voxel->boundary_ctr = voxel->sample_point();
} while (false && voxel->boundary_ctr.x == INFTY);
if (voxel->boundary_ctr.x == INFTY) {
// printf("FAILED\n");
voxel->boundary_ctr = voxel->ctr;
}
*/
// printf("BC %f,%f,%f\n", voxel->boundary_ctr.x, voxel->boundary_ctr.y, voxel->boundary_ctr.z);
}
for (auto voxel : voxels) {
auto nbrs = voxel->all_nbrs();
for (auto nbr : nbrs) {
res.push_back(segment(centers[voxel], centers[nbr]));
}
}
return res;
}
static const uint8_t VERTEX_LOOP[] = {6, 4, 5, 1, 3, 2, 6};
// Based on which vertices are filled, this map tells you which
// edges to interpolate between when forming zero, one, or two
// triangles.
// (filled vertex is first in the pair)
static const int EDGE_MAP[16][2][3][2] = {
{{{-1,-1}, {-1,-1}, {-1,-1}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // ----
{{{ 0, 2}, { 0, 1}, { 0, 3}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // ---0
{{{ 1, 0}, { 1, 2}, { 1, 3}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // --1-
{{{ 1, 2}, { 1, 3}, { 0, 3}}, {{ 0, 3}, { 0, 2}, { 1, 2}}}, // --10
{{{ 2, 0}, { 2, 3}, { 2, 1}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // -2--
{{{ 0, 3}, { 2, 3}, { 2, 1}}, {{ 2, 1}, { 0, 1}, { 0, 3}}}, // -2-0
{{{ 1, 0}, { 2, 0}, { 2, 3}}, {{ 2, 3}, { 1, 3}, { 1, 0}}}, // -21-
{{{ 2, 3}, { 1, 3}, { 0, 3}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // -210
{{{ 3, 0}, { 3, 1}, { 3, 2}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // 3---
{{{ 3, 2}, { 0, 2}, { 0, 1}}, {{ 0, 1}, { 3, 1}, { 3, 2}}}, // 3--0
{{{ 1, 2}, { 3, 2}, { 3, 0}}, {{ 3, 0}, { 1, 0}, { 1, 2}}}, // 3-1-
{{{ 1, 2}, { 3, 2}, { 0, 2}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // 3-10
{{{ 3, 0}, { 3, 1}, { 2, 1}}, {{ 2, 1}, { 2, 0}, { 3, 0}}}, // 32--
{{{ 3, 1}, { 2, 1}, { 0, 1}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // 32-0
{{{ 3, 0}, { 1, 0}, { 2, 0}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // 321-
{{{-1,-1}, {-1,-1}, {-1,-1}}, {{-1,-1}, {-1,-1}, {-1,-1}}}, // 3210
};
////////////////////////////////////////////////////////////////////////////////
/* mesh_zero_crossing
*
* Finds a zero crossing for a given leaf. May store new vertices in the
* vdata buffer (if we haven't already solved for this crossing).
*
* Returns an index into the vdata buffer.
*/
uint32_t Octree::mesh_zero_crossing(const Octree* const neighbors[6],
const uint8_t v0, const uint8_t v1,
Meshy* mesh) {
if (!data.tri) {
data.tri = (uint32_t*)calloc(64, sizeof(uint32_t));
}
// If we've already solved for this zero crossing then return
// the appropriate vertex id
if (data.tri[(v0<<3)|v1]) {
return data.tri[(v0<<3)|v1] - 1;
}
// First, look up this edge in our neighbors to see if we
// find a match. If we do, then save the vertex ID and set
// found to 'true'
bool found = false;
uint32_t id;
for (uint8_t axis=0; axis < 3 && !found; ++axis) {
// If the edge doesn't vary along this axis, we can compare
// with the appropriate neighbor.
uint8_t mask = 1 << axis;
if (!(mask & ~(v0 ^ v1))) continue;
// Find the appropriate neighbor
const Octree* neighbor = neighbors[axis*2 + ((v0 & mask) ? 1 : 0)];
// If we don't have this neighbor or this neighbor doesn't have
// a vertex cache, then keep going.
if (!neighbor || !neighbor->data.tri) continue;
// Look up this vertex in the neighbor's edge cache
uint16_t index = ((v0 ^ mask)<<3) | (v1 ^ mask);
// If we don't find it, keep going
if (!neighbor->data.tri[index]) continue;
// We found the vertex! Save it in the id variable.
found = true;
id = neighbor->data.tri[index] - 1;
data.tri[(v0 << 3)|v1] = id + 1;
data.tri[(v1 << 3)|v0] = id + 1;
}
// If we didn't find a match among neighbors, solve for the
// zero crossing via interpolation.
if (!found) {
auto c = zero_crossing(v0, v1);
id = mesh->vdata.size();
data.tri[(v0<<3)|v1] = id+1;
data.tri[(v1<<3)|v0] = id+1;
mesh->vdata.append(c);
mesh->gdata.append(vec(0.0, 0.0, 0.0));
// printf(" C [%f,%f,%f]\n", c.x, c.y, c.z);
}
// The gradient will be a sum from all of the cells
// that share this vertex.
auto g = gradient_one(mesh->vdata[id]);
mesh->gdata[id] = mesh->gdata[id] + g;
// printf("ID %d [%f,%f,%f] -> [%f,%f,%f]\n", id, g.x, g.y, g.z, mesh->gdata[id].x, mesh->gdata[id].y, mesh->gdata[id].z);
return id;
}
////////////////////////////////////////////////////////////////////////////////
/* evaluate_voxel
*
* Uses marching tetrahedrons to generate a set of triangles
* for a given leaf cell. Triangle vertices in idata as indexes into
* the vdata list, and icount is updated appropriately.
*/
void Octree::evaluate_voxel(const Octree* const neighbors[6], Meshy* mesh) {
// Loop over the six tetrahedra that make up a voxel cell
for (int t = 0; t < 6; ++t) {
// Find vertex positions for this tetrahedron
uint8_t vertices[] = {0, 7, VERTEX_LOOP[t], VERTEX_LOOP[t+1]};
// Figure out which of the sixteen possible combinations
// we're currently experiencing.
uint8_t lookup = 0;
for (int vertex = 3; vertex >= 0; --vertex) {
lookup = (lookup << 1) + (u.d[vertices[vertex]] < 0);
}
if (EDGE_MAP[lookup][0][0][0] == -1) continue;
// Store the first triangle in the vertex array
IV3 tri;
for (int v=0; v < 3; ++v) {
tri[v] = mesh_zero_crossing(neighbors,
vertices[EDGE_MAP[lookup][0][v][0]],
vertices[EDGE_MAP[lookup][0][v][1]],
mesh);
}
mesh->tdata.append(tri);
// Move on to the second triangle, aborting if there isn't one.
if (EDGE_MAP[lookup][1][0][0] == -1) continue;
// Store the second triangle in the vertex array
for (int v=0; v < 3; ++v) {
tri[v] = mesh_zero_crossing(neighbors,
vertices[EDGE_MAP[lookup][1][v][0]],
vertices[EDGE_MAP[lookup][1][v][1]],
mesh);
}
mesh->tdata.append(tri);
}
}
////////////////////////////////////////////////////////////////////////////////
void Octree::do_triangulate(const Octree* const neighbors[6], Meshy* mesh, volatile int* const halt) {
if (*halt) return;
if (kind == voxel_leaf_kind) {
evaluate_voxel(neighbors, mesh);
} else if (kind == voxel_parent_kind) {
const Octree* new_neighbors[6];
for (int i=0; i < 8; ++i) {
get_neighbors_3d(neighbors, new_neighbors, i);
u.children[i]->do_triangulate(new_neighbors, mesh, halt);
}
}
}
////////////////////////////////////////////////////////////////////////////////
Meshy* Octree::triangulate(volatile int* const halt) {
Meshy* mesh = new Meshy();
const Octree* neighbors[6] = {NULL, NULL, NULL, NULL, NULL, NULL};
do_triangulate(neighbors, mesh, halt);
return mesh;
}
/*
Data tables for marching squares
Vertices have the following IDs
1 3
--------
| |
| | ^ Y
| | |
-------- --> X
0 2
(divided by two from d[i] indices, since we're
looking at a flat ASDF and we don't care about z)
Edges are numbered as follows:
1
--------
| |
2 | | 3 ^ Y
| | |
-------- --> X
0
*/
// For a given set of filled corners, this array defines
// the cell edges from which we draw interior edges
static const int8_t EDGE_MAP2[16][2][2] = {
{{-1, -1}, {-1, -1}}, // ----
{{0, 2}, {-1, -1}}, // ---0
{{2, 1}, {-1, -1}}, // --1-
{{0, 1}, {-1, -1}}, // --10
{{3, 0}, {-1, -1}}, // -2--
{{3, 2}, {-1, -1}}, // -2-0
{{3, 0}, { 2, 1}}, // -21-
{{3, 1}, {-1, -1}}, // -210
{{1, 3}, {-1, -1}}, // 3---
{{1, 3}, { 0, 2}}, // 3--0
{{2, 3}, {-1, -1}}, // 3-1-
{{0, 3}, {-1, -1}}, // 3-10
{{1, 0}, {-1, -1}}, // 32--
{{1, 2}, {-1, -1}}, // 32-0
{{2, 0}, {-1, -1}}, // 321-
{{-1,-1}, {-1, -1}} // 3210
};
// Indexed by edge number, returns vertex index
static const int8_t VERTEX_MAP2[4][2] = {
{0, 2},
{3, 1},
{1, 0},
{2, 3}
};
std::vector<Path*> Octree::contour(volatile int* const halt) {
const Octree* neighbors[4] = {NULL, NULL, NULL, NULL};
find_edges(neighbors, halt);
std::vector<Path*> paths;
write_edges(paths);
// TODO: free_data(tree);
return paths;
}
void Octree::write_edges (std::vector<Path*>& paths) {
// printf("WRITE-EDGES %d [%f,%f][%f,%f]\n",
// kind, lo.x, lo.y, hi.x, hi.y);
if (kind == voxel_leaf_kind) {
for (int e=0; e < 4; ++e) {
Path* p = data.contour[e];
if (!p) continue;
// Grab the path and trace it out
// printf("BACKTRACE PATH %d\n", p->id);
Path* start = backtrace_path(p->prev, p);
// printf("DECIMATE PATH %lx\n", start);
start = decimate_path(start, EPSILON);
paths.push_back(start);
// printf("DISCONNECT PATH %d\n", start->id);
disconnect_path(start);
}
} else if (kind == voxel_parent_kind) {
// Otherwise, recurse.
for (int i=0; i < 8; i += 2) {
u.children[i]->write_edges(paths);
}
}
}
void Octree::find_edges(const Octree* const neighbors[4],volatile int* const halt) {
if (*halt) return;
if (kind == voxel_leaf_kind) {
evaluate_pixel(neighbors);
} else if (kind == voxel_parent_kind) {
// Evaluate the children
for (int i=0; i < 8; i+=2) {
const Octree* new_neighbors[4];
get_neighbors_2d(neighbors, new_neighbors, i);
u.children[i]->find_edges(new_neighbors, halt);
}
// Upgrade disconnected edges from children
// (necessary for multi-scale path merging; trust me on this)
data.contour = (Path**)calloc(4, sizeof(Path*));
for (int e=0; e < 4; ++e) {
for (int i=0; i < 8; i += 2) {
// Only pull from children that touch this edge.
if (e == 0 && (i & 2)) continue;
if (e == 1 && !(i & 2)) continue;
if (e == 2 && (i & 4)) continue;
if (e == 3 && !(i & 4)) continue;
// If we've already filled this edge or
// this cell doesn't exist or doesn't have data,
// or doesn't have data on this edge, then skip it.
if (data.contour[e] ||
!u.children[i] ||
!u.children[i]->data.contour ||
!u.children[i]->data.contour[e]) {
continue;
}
// If this edge has a loose end, upgrade it
Path* p = u.children[i]->data.contour[e];
data.contour[e] = p;
// printf("WRITE CONTOUR %d\n", p->id);
// Add a pointer so that this path can disconnect
// itself from the grid when needed
p->ptrs.push_back(&(data.contour[e]));
}
}
}
}
void Octree::evaluate_pixel(const Octree* const neighbors[4]) {
if (!data.contour) {
data.contour = (Path**)calloc(4, sizeof(Path*));
}
// Figure out which of the 16 possible cases we've encountered.
// (ignore the z levels, just check xy)
uint8_t lookup = 0;
for (int vertex=3; vertex >= 0; --vertex) {
lookup = (lookup << 1) + (u.d[vertex << 1] < 0);
}
if (EDGE_MAP2[lookup][0][0] != -1) {
Path *p1 = contour_zero_crossing(neighbors, EDGE_MAP2[lookup][0][0]),
*p2 = contour_zero_crossing(neighbors, EDGE_MAP2[lookup][0][1]);
p1->next = p2;
p2->prev = p1;
}
if (EDGE_MAP2[lookup][1][0] != -1) {
Path *p1 = contour_zero_crossing(neighbors, EDGE_MAP2[lookup][1][0]),
*p2 = contour_zero_crossing(neighbors, EDGE_MAP2[lookup][1][1]);
p1->next = p2;
p2->prev = p1;
}
}
static int id = 0;
Path* Octree::contour_zero_crossing (const Octree* const neighbors[4], const uint8_t edge) {
Path* t = NULL;
// Check for edge intersections among neighbors:
// Neighbors are in the order -y, +y, -x, +x
// Lower edge
if (edge == 0 && neighbors[0] && neighbors[0]->data.contour) {
t = neighbors[0]->data.contour[1];
// Upper edge
} else if (edge == 1 && neighbors[1] && neighbors[1]->data.contour) {
t = neighbors[1]->data.contour[0];
// Left edge
} else if (edge == 2 && neighbors[2] && neighbors[2]->data.contour) {
t = neighbors[2]->data.contour[3];
// Right edge
} else if (edge == 3 && neighbors[3] && neighbors[3]->data.contour) {
t = neighbors[3]->data.contour[2];
}
// If we've found one, then we're done.
if (t) {
data.contour[edge] = t;
t->ptrs.push_back(&(data.contour[edge]));
return t;
}
// If we didn't find a match among neighbors, solve for the
// zero crossing via interpolation.
const uint8_t v0 = VERTEX_MAP2[edge][0]<<1,
v1 = VERTEX_MAP2[edge][1]<<1;
const flo_t d0 = u.d[v0],
d1 = u.d[v1];
// Interpolation from d0 to d1
const flo_t d = (d0)/(d0-d1);
// Find interpolated coordinates
const flo_t x0 = (v0 & 4) ? hi.x : lo.x,
y0 = (v0 & 2) ? hi.y : lo.y;
const flo_t x1 = (v1 & 4) ? hi.x : lo.x,
y1 = (v1 & 2) ? hi.y : lo.y;
auto c = vec(x0*(1-d)+x1*d, y0*(1-d)+y1*d, 0.0);
// Create a point
// printf("CREATING PATH %d [%f,%f]\n", id, c.x, c.y);
t = new Path(c.x, c.y, id++);
data.contour[edge] = t;
// Add a back-reference to the containing Octree's edge pointer
// (so that the path can disconnect itself when needed)
t->ptrs.push_back(&(data.contour[edge]));
return t;
}
//// MARCHING CUBES ON VOXELS
// These tables are used so that everything can be done in little loops that you can look at all at once
// rather than in pages and pages of unrolled code.
//a2fVertexOffset lists the positions, relative to vertex0, of each of the 8 vertices of a cube
static std::vector< Vec > a2fVertexOffset;
//a2fEdgeDirection lists the direction vector (vertex1-vertex0) for each edge in the cube
static std::vector< Vec > a2fEdgeDirection;
static bool isInitMesher = false;
static void initMesher (void) {
std::vector< Vec > r;
r.push_back(vec(0.0, 0.0, 0.0));
r.push_back(vec(1.0, 0.0, 0.0));
r.push_back(vec(1.0, 1.0, 0.0));
r.push_back(vec(0.0, 1.0, 0.0));
r.push_back(vec(0.0, 0.0, 1.0));
r.push_back(vec(1.0, 0.0, 1.0));
r.push_back(vec(1.0, 1.0, 1.0));
r.push_back(vec(0.0, 1.0, 1.0));
a2fVertexOffset = r;
r.clear();
r.push_back(vec(1.0, 0.0, 0.0));
r.push_back(vec(0.0, 1.0, 0.0));
r.push_back(vec(-1.0, 0.0, 0.0));
r.push_back(vec(0.0, -1.0, 0.0));
r.push_back(vec(1.0, 0.0, 0.0));
r.push_back(vec(0.0, 1.0, 0.0));
r.push_back(vec(-1.0, 0.0, 0.0));
r.push_back(vec(0.0, -1.0, 0.0));
r.push_back(vec(0.0, 0.0, 1.0));
r.push_back(vec(0.0, 0.0, 1.0));
r.push_back(vec(0.0, 0.0, 1.0));
r.push_back(vec(0.0, 0.0, 1.0));
a2fEdgeDirection = r;
};
//a2iEdgeConnection lists the index of the endpoint vertices for each of the 12 edges of the cube
static const int a2iEdgeConnection[12][2] = {
{0,1}, {1,2}, {2,3}, {3,0},
{4,5}, {5,6}, {6,7}, {7,4},
{0,4}, {1,5}, {2,6}, {3,7}
};
//get_offset finds the approximate point of intersection of the surface
// between two points with the values fValue1 and fValue2
double get_offset(double fValue1, double fValue2, double fValueDesired) {
double fDelta = fValue2 - fValue1;
if(fDelta == 0.0)
return 0.5;
else
return (fValueDesired - fValue1)/fDelta;
}
static Vec normalize_vector(Vec &rfVectorSource) {
double fOldLength = rfVectorSource.magnitude();
if (fOldLength == 0.0) {
return rfVectorSource;
} else {
return rfVectorSource * (1.0 / fOldLength);
}
}
//vGetNormal() finds the gradient of the scalar field at a point
//This gradient can be used as a very accurate vertx normal for lighting calculations
Vec Octree::get_normal(Vec pos) {
auto v = vec(g->dist(vec(pos.x-0.01, pos.y, pos.z)) - g->dist(vec(pos.x+0.01, pos.y, pos.z)),
g->dist(vec(pos.x, pos.y-0.01, pos.z)) - g->dist(vec(pos.x, pos.y+0.01, pos.z)),
g->dist(vec(pos.x, pos.y, pos.z-0.01)) - g->dist(vec(pos.x, pos.y, pos.z+0.01)));
return normalize_vector(v);
}
void marching_cubes(std::vector<Octree*>& voxels,
std::vector<Tri> &tris, std::vector<Tri> &colors, std::vector<Tri> &normals) {
for (auto voxel : voxels) {
voxel->march_cube(0.0, tris, normals, colors);
}
}
//march_cube performs the Marching Cubes algorithm on a single cube
double Octree::march_cube
(double target_value, std::vector< Tri >& tris, std::vector< Tri >& normals, std::vector< Tri >& colors) {
extern int aiCubeEdgeFlags[256];
extern int a2iTriangleConnectionTable[256][16];
// double fX = lo.x;
// double fY = lo.y;
// double fZ = lo.z;
double fScale = rad();
int iEdgeFlags;
Vec sColor;
double afCubeValue[8];
Vec asEdgeVertex[12];
Vec asEdgeNorm[12];
if (!isInitMesher) {
initMesher(); isInitMesher = true;