-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSUMA_GeomComp.c
15772 lines (14037 loc) · 589 KB
/
SUMA_GeomComp.c
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 "SUMA_suma.h"
extern int *z_rand_order(int bot, int top, long int seed) ;
/*!
Fill a 3x4 affine matrix that performs a rotation
about an axis Ax passing though point C
if C is NULL rotation it is set to 0, 0, 0
Ax should be a unit vector
rotation angle is in radians
*/
SUMA_Boolean SUMA_BuildRotationMatrix(double *C, double *Ax,
double alpha, double mat[4][4])
{
static char FuncName[] = {"SUMA_BuildRotationMatrix"};
double mm[3], Cr[3];
SUMA_ENTRY;
if (!mat || !Ax) SUMA_RETURN(NOPE);
SUMA_3Dax_Rotation_Matrix(Ax, alpha, mat);
if (C) {
SUMA_ROTATE_ABOUT_AXIS(C, Ax, alpha, Cr);
mat[0][3] = -Cr[0]+C[0];
mat[1][3] = -Cr[1]+C[1];
mat[2][3] = -Cr[2]+C[2];
} else {
mat[0][3] = mat[1][3] = mat[2][3] = 0.0;
}
mat[3][0] = mat[3][1] = mat[3][2] = 0.0; mat[3][3] = 1.0;
SUMA_RETURN(YUP);
}
/*!
\brief Find boundary triangles,
those that have an edge that is shared by less than 2 triangles.
\param SO
\param boundt if not NULL, it is a pre-allocated vector that will
contain the boundary triangles on return
If bount_asmask then boundt should be SO->N_FaceSet long
and upon return, if bount[k] then triangle k is a boundary
triangle.
If ! boundt_asmask then boundt the 1st N_boundt values
of boundt contain indices to the boundary triangles.
\param boundt_asmask: Flag indicating how boundt is to be interpreted.
\return N_boundt: total number of boundary triangles
*/
int SUMA_BoundaryTriangles (SUMA_SurfaceObject *SO, int *boundt,
int boundt_asmask )
{
static char FuncName[]={"SUMA_BoundaryTriangles"};
int k, N_boundt=0;
byte *visited=NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (!SO->EL) SUMA_SurfaceMetrics(SO, "EdgeList", NULL);
if (!(visited = (byte *)SUMA_calloc(SO->N_FaceSet, sizeof(byte)))) {
SUMA_S_Err("Failed to allocate");
SUMA_RETURN(0);
}
if (boundt) {
if (boundt_asmask) for (k=0; k<SO->N_FaceSet; ++k) boundt[k]=0;
}
N_boundt=0;
k=0;
while (k<SO->EL->N_EL) {
/* find edges that form boundaries */
if (SO->EL->ELps[k][2] == 1 && !visited[SO->EL->ELps[k][1]]) {
if (boundt) {
if (boundt_asmask) boundt[SO->EL->ELps[k][1]] = 1;
else {
boundt[N_boundt] = SO->EL->ELps[k][1];
}
}
visited[SO->EL->ELps[k][1]]=1;
++N_boundt;
}
++k;
}
if (visited) SUMA_free(visited); visited=NULL;
SUMA_RETURN(N_boundt);
}
/*!
\brief Calculate the sine and cosines of angles in a triangle
return -2 where calculation fails
*/
SUMA_Boolean SUMA_TriTrig( float *p1, float *p2, float *p3,
double *s, double *c, double *a)
{
static char FuncName[]={"SUMA_TriTrig"};
double U13[3], U12[3], U23[3], U21[3], X[3];
double Xn, Un13, Un12, Un23, Up1, Up2, Up3;
int k;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (!p1 || !p2 || !p3 || !s || !c) SUMA_RETURN(NOPE);
#if 0
if (LocalHead) {
fprintf(SUMA_STDERR, "%s:\n"
"n1=[%f, %f, %f];\n"
"n2=[%f, %f, %f];\n"
"n3=[%f, %f, %f];\n",
FuncName,
p1[0], p1[1], p1[2],
p2[0], p2[1], p2[2],
p3[0], p3[1], p3[2]);
}
#endif
/* vectors and their norms */
Un12 = Un13 = Un23 = 0.0f;
for (k=0;k<3;++k) {
U12[k] = p2[k] - p1[k]; Un12 += (U12[k]*U12[k]);
U21[k] = p1[k] - p2[k];
U13[k] = p3[k] - p1[k]; Un13 += (U13[k]*U13[k]);
U23[k] = p3[k] - p2[k]; Un23 += (U23[k]*U23[k]);
}
#if 0
if (LocalHead) {
fprintf(SUMA_STDERR, "%s:\n"
"U12=[%f, %f, %f]; Un12^2=%f;\n"
"U13=[%f, %f, %f]; Un13^2=%f;\n"
"U23=[%f, %f, %f]; Un23^2=%f;\n",
FuncName,
U12[0], U12[1], U12[2], Un12,
U13[0], U13[1], U13[2], Un13,
U23[0], U23[1], U23[2], Un23);
}
#endif
Up1 = Un12*Un13;
Up2 = Un12*Un23;
Up3 = Un13*Un23;
if (Up1 > 0.0f) {
/* sine of angle at n1 */
SUMA_MT_CROSS(X, U12, U13);
Xn = X[0]*X[0] + X[1]*X[1] + X[2]*X[2];
s[0] = sqrtf(Xn/Up1);
/* now cosine */
c[0] = SUMA_MT_DOT(U12,U13)/(sqrtf(Up1));
} else {
s[0] = -2.0;
c[0] = -2.0;
}
if (Up2 > 0.0f) {
/* sine of angle at n2 */
SUMA_MT_CROSS(X, U23, U21);
Xn = X[0]*X[0] + X[1]*X[1] + X[2]*X[2];
s[1] = sqrtf(Xn/Up2);
/* now cosine */
c[1] = SUMA_MT_DOT(U23,U21)/(sqrtf(Up2));
} else {
s[1] = -2.0;
c[1] = -2.0;
}
if (Up3 > 0.0f) {
/* sine of angle at n3 */
SUMA_MT_CROSS(X, U13, U23);
Xn = X[0]*X[0] + X[1]*X[1] + X[2]*X[2];
s[2] = sqrtf(Xn/Up3);
/* now cosine */
c[2] = SUMA_MT_DOT(U13,U23)/(sqrtf(Up3));
} else {
s[2] = -2.0;
c[2] = -2.0;
}
/* now angles */
if (a) {
for (k=0; k<3; ++k) {
if (s[k] >= 0.0f) { /* always the case, unless you have a reference
direction to compare with cross product.
Unsigned angles only then.*/
a[k] = acos(c[k]); /* You could do 180-a1-a2 but that goes awry
is calculations fail on a1 or a2... */
} else { a[k] = -2.0; }
}
}
#if 0
if (LocalHead) {
fprintf(SUMA_STDERR, "%s:\n"
"s =[%f, %f, %f]; \n"
"c =[%f, %f, %f]; \n"
,FuncName,
s[0], s[1], s[2],
c[0], c[1], c[2]);
}
#endif
SUMA_RETURN(YUP);
}
/*!
\brief A function to calculate the geodesic distance of nodes connected to node n
See labbook NIH-3 pp 138 and on for notes on algorithm
\param n (int) index of center node
\param SO (SUMA_SurfaceObject *) structure containing surface object
\param off (float *) a vector such that off[i] = the geodesic distance of node i
to node n. The vector should be initialized to -1.0
\param lim (float) maximum geodesic distance to travel
- This function is too slow. See SUMA_getoffsets2
\sa SUMA_getoffsets2
*/
#define DBG 1
#define DoCheck 1
#if 0 /* now set in default arguments */
int SUMA_GEOMCOMP_NI_MODE = NI_BINARY_MODE;
#endif
void SUMA_Set_SurfSmooth_NodeDebug(int n)
{
SUMA_SSidbg = n;
}
/*!
\brief function to subdivide triangles to meet a maxarea criterion
Divisions are done by adding a node at the centroid of the triangle
to be subdivided. Bad idea, for very large triangles, such as produced
by convex hull, you could end up with nodes that have hundreds of neighbors...
*/
int SUMA_Subdivide_Mesh( float **NodeListp, int *N_Nodep, int **FaceSetListp,
int *N_FaceSetp, float maxarea)
{
static char FuncName[]={"SUMA_Subdivide_Mesh"};
int in, it, N_NodeAlloc, N_FaceSetAlloc, N_Node,
N_FaceSet, it3, in0, in1, in2, inc3, inc, itn, itn3;
float c[3];
float *NodeList = NULL, a, *n1, *n2, *n0;
int *FaceSetList = NULL;
SUMA_SurfaceObject SObuf, *SO=NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
SUMA_S_Warn("Function is very basic\n"
"Divisions are done by adding a node at the centroid of the\n"
"triangle to be subdivided. Bad idea, for very large triangles,\n"
"such as those produced by convex hull. You could end up with\n"
"nodes that have hundreds of neighbors\n");
SO = &SObuf;
N_NodeAlloc = N_Node = *N_Nodep;
N_FaceSetAlloc = N_FaceSet = *N_FaceSetp;
NodeList = *NodeListp;
FaceSetList = *FaceSetListp;
SO->NodeList = NodeList; SO->FaceSetList = FaceSetList;
if (!NodeList || !FaceSetList) {
SUMA_SL_Err("NULL input"); SUMA_RETURN(NOPE); }
it = 0; /* triangle index */
while (it < N_FaceSet) {
it3 = 3*it;
in0 = FaceSetList[it3]; in1 = FaceSetList[it3+1]; in2 = FaceSetList[it3+2]; /* node indices */
n0 = &(NodeList[3*in0]); n1 = &(NodeList[3*in1]); n2 = &(NodeList[3*in2]); /* node coordinates */
SUMA_TRI_AREA(n0, n1, n2, a); /* area of triangle */
if (a > maxarea) {
if (N_NodeAlloc <= N_Node) { /* need to realloc ?*/
N_NodeAlloc += 20000;
NodeList = (float *)SUMA_realloc(NodeList, N_NodeAlloc * 3 * sizeof(float));
/* you always add 2 triangles per new node here */
N_FaceSetAlloc += 40000;
FaceSetList = (int *)SUMA_realloc(FaceSetList, N_FaceSetAlloc * 3 * sizeof(int));
if (!NodeList || !FaceSetList) { SUMA_SL_Crit("Failed to realloc"); SUMA_RETURN(NOPE); }
SO->NodeList = NodeList; SO->FaceSetList = FaceSetList;
}
SUMA_FACE_CENTROID(SO, it, c); /* c is the centroid of triangle it */
inc = N_Node; inc3 = inc*3; ++N_Node; /* index of new centroid node */
NodeList[inc3] = c[0]; NodeList[inc3+1] = c[1]; NodeList[inc3+2] = c[2]; /* add new centroid to bottom of list */
FaceSetList[it3+2] = inc; /* old triangle is now 1st new triangle in0 in1 inc */
itn = N_FaceSet; itn3 = 3 * itn; ++N_FaceSet; /* index of new second triangle */
FaceSetList[itn3] = inc; FaceSetList[itn3+1] = in1; FaceSetList[itn3+2] = in2;
itn = N_FaceSet; itn3 = 3 * itn; ++N_FaceSet; /* index of new third triangle */
FaceSetList[itn3] = inc; FaceSetList[itn3+1] = in2; FaceSetList[itn3+2] = in0;
} else {
++it;
}
}
/* reallocate */
FaceSetList = (int *)SUMA_realloc(FaceSetList, N_FaceSet * 3 * sizeof(int));
NodeList = (float *)SUMA_realloc(NodeList, N_Node * 3 * sizeof(float));
*NodeListp = NodeList;
*FaceSetListp = FaceSetList;
*N_FaceSetp = N_FaceSet;
*N_Nodep = N_Node;
SUMA_RETURN(YUP);
}
/*!
\brief Function to allocate and initialize a SUMA_VTI * structure
\param N_TriIndex (int): Number of triangles whose intersections will
be sought
\param *TriIndex (int *):
Pointer to vector containing indices of triangles
whose intersections will be sought. This vector will
be duplicated into vti if you supply it.
If this parameter is NULL, then an empty vti->TriIndex is
created and initialized from 0 to N_TriIndex - 1
\return vti (SUMA_VTI *): Initialized structure containing allocated
TriIndex, N_IntersectedVoxels, IntersectedVoxels vectors.
- Free with SUMA_FreeVTI
*/
SUMA_VTI *SUMA_CreateVTI(int N_TriIndex, int *TriIndexU)
{
static char FuncName[]={"SUMA_CreateVTI"};
SUMA_VTI *vti = NULL;
int i;
SUMA_ENTRY;
if (!N_TriIndex) {
SUMA_SL_Err("Nothing to do !");
SUMA_RETURN(vti);
}
vti = (SUMA_VTI *)SUMA_malloc(sizeof(SUMA_VTI));
vti->N_TriIndex = N_TriIndex;
vti->TriIndex = (int *)SUMA_calloc(N_TriIndex, sizeof(int));
if (!vti->TriIndex) {
SUMA_SL_Crit("Failed to allocate for vti->TriIndex");
SUMA_RETURN(NULL);
}
if (TriIndexU ) {
memcpy(vti->TriIndex, TriIndexU, N_TriIndex*sizeof(int));
}else {
/* init default */
for (i=0; i<N_TriIndex; ++i) vti->TriIndex[i]=i;
}
vti->N_IntersectedVoxels = (int *)SUMA_calloc(N_TriIndex, sizeof(int));
vti->IntersectedVoxels = (int **)SUMA_calloc(N_TriIndex, sizeof(int*));
vti->SignedIJKDistance = (float **)SUMA_calloc(N_TriIndex, sizeof(float*));
if (!vti->N_IntersectedVoxels || !vti->IntersectedVoxels) {
SUMA_SL_Crit("Failed to allocate for vti's innerds");
SUMA_RETURN(NULL);
}
SUMA_RETURN(vti);
}
SUMA_VTI * SUMA_FreeVTI(SUMA_VTI *vti)
{
static char FuncName[]={"SUMA_FreeVTI"};
int i;
SUMA_ENTRY;
if (!vti) SUMA_RETURN(NULL);
if (vti->TriIndex) SUMA_free(vti->TriIndex);
if (vti->IntersectedVoxels) {
for (i=0; i<vti->N_TriIndex; ++i) {
if (vti->IntersectedVoxels[i]) free(vti->IntersectedVoxels[i]);
if (vti->SignedIJKDistance[i]) free(vti->SignedIJKDistance[i]);
}
SUMA_free(vti->IntersectedVoxels);
}
if (vti->N_IntersectedVoxels) SUMA_free(vti->N_IntersectedVoxels);
SUMA_free(vti);
SUMA_RETURN(NULL);
}
/*!
\brief Function to return a set of voxels that are intersected by
a triangle.
\param SO (SUMA_SurfaceObject *)
\param VolPar (SUMA_VOLPAR *)
\param NodeIJKlist (float *) the equivalent of SO->NodeList
only in i,j,k indices into VolPar's grid.
Set it to NULL to have this function generate it from
SO->NodeList and VolPar.
\param vti (SUMA_VTI *) properly initialized Voxel Triangle Intersection structure
\return vti (SUMA_VTI *) filled up VTI structure.
- Closely based on section in function SUMA_SurfGridIntersect
If you find bugs here, fix them there too.
Significant bug fixes Oct. 2012
*/
SUMA_VTI *SUMA_GetVoxelsIntersectingTriangle(
SUMA_SurfaceObject *SO, SUMA_VOLPAR *VolPar, float *NodeIJKlistU,
SUMA_VTI *vti)
{
static char FuncName[]={"SUMA_GetVoxelsIntersectingTriangle"};
int ti, nx, ny, nz, nxy, nxyz, N_inbox, n1, n2, n3, nt, nt3, nijk, nf;
int N_alloc, N_realloc, en, *voxelsijk=NULL, N_voxels1d = 0, *voxels1d = NULL;
int *TriIndex=NULL, N_TriIndex;
int tdebug=-1; /* Pick a triangle index to debug. Set to -1 to keep mum */
float dxyz[3];
float tol_dist = 0; /* A way to fatten up the shell a little bit.
Set to 0 if no fat is needed */
int inside_only = 0; /* if 1, look for voxels located opposite
normal direction only */
float *p1, *p2, *p3, min_v[3], max_v[3], p[3], dist,
*NodeIJKlist=NULL, *signdist=NULL;
FILE *fp=NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (SO->FaceSetDim != 3 || SO->NodeDim != 3) {
SUMA_SL_Err("SO->FaceSetDim != 3 || SO->NodeDim != 3");
SUMA_RETURN(NULL);
}
if (!vti) {
SUMA_SL_Err("vti must be non NULL");
SUMA_RETURN(NULL);
}
if (vti->N_TriIndex <= 0) {
SUMA_SL_Err("vti must be initialized");
SUMA_RETURN(NULL);
}
nx = VolPar->nx;
ny = VolPar->ny;
nz = VolPar->nz;
nxy = nx * ny; nxyz = nx * ny * nz;
if (!NodeIJKlistU) {
NodeIJKlist = (float *)SUMA_malloc(SO->N_Node * 3 * sizeof(float));
memcpy ((void*)NodeIJKlist, (void *)SO->NodeList,
SO->N_Node * 3 * sizeof(float));
/* transform the surface's coordinates from RAI to 3dfind */
if (!SUMA_vec_dicomm_to_3dfind (NodeIJKlist, SO->N_Node, VolPar)) {
SUMA_SL_Err("Failed to effectuate coordinate transform.");
SUMA_free(NodeIJKlist); NodeIJKlist = NULL;
SUMA_RETURN(NULL);
}
} else {
NodeIJKlist = NodeIJKlistU;
for (ti=0; ti<SO->N_Node ; ++ti) { /* check */
if (NodeIJKlist[3*ti ] < 0 || NodeIJKlist[3*ti ]>= nx ||
NodeIJKlist[3*ti+1] < 0 || NodeIJKlist[3*ti+1]>= ny ||
NodeIJKlist[3*ti+2] < 0 || NodeIJKlist[3*ti+2]>= nz ) {
SUMA_S_Errv("Looks like NodeIJKlist is not in index units.\n"
"At node %d, have %f %f %f\n"
, ti,
NodeIJKlist[3*ti ],
NodeIJKlist[3*ti+1],
NodeIJKlist[3*ti+2]);
SUMA_RETURN(NULL);
}
}
}
TriIndex = vti->TriIndex;
N_TriIndex = vti->N_TriIndex;
if (LocalHead) {
SUMA_LH("Debug mode, writing file: SUMA_GetVoxelsIntersectingTriangle.1D");
fp = fopen("SUMA_GetVoxelsIntersectingTriangle.1D","w");
if (fp) fprintf(fp, "# Voxels from %s that intersect the triangles \n",
VolPar->filecode);
}
/* cycle through all triangles and find voxels that intersect them */
N_alloc = 2000; /* expected maximum # of voxels in triangle's bounding box */
N_realloc = 0;
voxelsijk = (int *)SUMA_malloc(sizeof(int)*N_alloc*3);
if (!voxelsijk) { SUMA_SL_Crit("Failed to Allocate!"); SUMA_RETURN(NULL); }
/* ZSS Oct 2012, see similar comment in SUMA_SurfGridIntersect
dxyz[0] = VolPar->dx; dxyz[1] = VolPar->dy; dxyz[2] = VolPar->dz;
*/
dxyz[0] = dxyz[1] = dxyz[2] = 1.0; /* Now we're in ijk coordinate system */
for (ti=0; ti<N_TriIndex; ++ti) {
nf = TriIndex[ti];
n1 = SO->FaceSetList[SO->FaceSetDim*nf];
n2 = SO->FaceSetList[SO->FaceSetDim*nf+1];
n3 = SO->FaceSetList[SO->FaceSetDim*nf+2];
if (LocalHead || nf == tdebug)
fprintf(SUMA_STDERR,
"%s: Now processing %dth triangle indexed %d "
"made up of nodes %d, %d. %d .\n",
FuncName, ti, nf, n1, n2, n3);
/* find the bounding box of the triangle */
p1 = &(NodeIJKlist[3*n1]);
p2 = &(NodeIJKlist[3*n2]);
p3 = &(NodeIJKlist[3*n3]);
SUMA_TRIANGLE_BOUNDING_BOX(p1, p2, p3, min_v, max_v);
/* quick check of preallocate size of voxelsijk */
en =( (int)(max_v[0] - min_v[0] + 5) *
(int)(max_v[1] - min_v[1] + 5) *
(int)(max_v[2] - min_v[2] + 5) );
if ( en > N_alloc) {
++N_realloc;
if (N_realloc > 5) {
SUMA_SL_Warn("Reallocating, increase limit to improve speed.\n"
"Either triangles too large or grid too small");
}
N_alloc = 2*en;
voxelsijk = (int *)SUMA_realloc(voxelsijk, 3*N_alloc*sizeof(int));
if (!voxelsijk) {
SUMA_SL_Crit("Failed to Allocate!");
SUMA_RETURN(NULL);
}
}
/* find the list of voxels inhabiting this box */
N_inbox = 0;
if (!SUMA_VoxelsInBox(voxelsijk, &N_inbox, min_v, max_v)) {
SUMA_SL_Err("Unexpected error!"); SUMA_RETURN(NULL);
}
if (!N_inbox) {
SUMA_SL_Err("Unexpected error, no voxels in box!");
SUMA_RETURN(NULL);
}
if (N_inbox >= N_alloc) {
SUMA_SL_Err("Allocation trouble!");
SUMA_RETURN(NULL);
}
if (LocalHead || nf == tdebug) {
fprintf(SUMA_STDERR,"\t\t%d nodes in box\n", N_inbox);
if (nf == tdebug) {
FILE *ffout=fopen("voxelsinbox.1D","w");
if (ffout) {
SUMA_S_Warn("Dumping debugging file: voxelsinbox.1D");
fprintf(ffout,
"#IJK of Voxels to be considered for triangle %d\n",nf);
fprintf(ffout,"#%d %f %f %f\n"
"#%d %f %f %f\n"
"#%d %f %f %f\n",
n1, p1[0], p1[1], p1[2],
n2, p2[0], p2[1], p2[2],
n3, p3[0], p3[1], p3[2]);
for (nt=0; nt < N_inbox; ++nt) {
nt3 = 3*nt;
fprintf(ffout,"%d %d %d\n",
voxelsijk[nt3 ], voxelsijk[nt3+1], voxelsijk[nt3+2]);
}
fclose(ffout); ffout=NULL;
}
}
}
/* allocate for 1D indices of voxels intersecting the triangle */
if (voxels1d) {
SUMA_SL_Err("NULL pointer expected here");
SUMA_RETURN(NULL);
}
voxels1d = (int *)malloc(N_inbox * sizeof(int)); /* Too many SUMA_mallocs
keep it simple here, this function is called many many times */
signdist = (float *)malloc(N_inbox * sizeof(float));
if (LocalHead || nf == tdebug)
fprintf(SUMA_STDERR,"\t\tabout to process %d voxels in box\n", N_inbox);
N_voxels1d=0;
if (!voxels1d || !signdist) {
SUMA_SL_Crit("Failed to allocate voxels1d");
SUMA_RETURN(NULL);
}
/* mark these voxels as inside the business */
for (nt=0; nt < N_inbox; ++nt) {
nt3 = 3*nt;
if ( voxelsijk[nt3 ] >= 0 && voxelsijk[nt3] < nx &&
voxelsijk[nt3+1] >= 0 && voxelsijk[nt3+1] < ny &&
voxelsijk[nt3+2] >= 0 && voxelsijk[nt3+2] < nz) {
nijk = SUMA_3D_2_1D_index( voxelsijk[nt3],
voxelsijk[nt3+1],
voxelsijk[nt3+2], nx , nxy);
{
/* what side of the plane is this voxel on ? */
p[0] = (float)voxelsijk[nt3];
p[1] = (float)voxelsijk[nt3+1];
p[2] = (float)voxelsijk[nt3+2];
SUMA_DIST_FROM_PLANE(p1, p2, p3, p, dist);
if (nf == tdebug) {
fprintf(SUMA_STDERR,
"\t\tVox %f %f %f at dist %f\n",
p[0], p[1], p[2], dist);
}
/* Does voxel contain any of the nodes ? */
if (tol_dist && SUMA_ABS(dist) < tol_dist) dist = tol_dist;
/* Fatten the representation a little bit
There are holes in the mask created using
the condition below alone. I am not sure
why that is the case but whatever gap there
is in one plane, results from a thick line in
the other. Don't know if that is a bug yet
or an effect of discretization. At any rate
it should not affect what I plan to do with
this. Could the bug be in
SUMA_isVoxelIntersect_Triangle?
Thu Dec 22 17:03:48 EST 2005, Update:
SUMA_isVoxelIntersect_Triangle had a precision
bug. It has been fixed but I have not reexamined
this block yet*/
if (!inside_only || !(SUMA_IS_STRICT_NEG(VolPar->Hand * dist))) {
/* voxel is outside (along normal) */
/* does this triangle actually intersect this voxel ?*/
if (SUMA_isVoxelIntersect_Triangle (p, dxyz, p1, p2, p3)) {
/* looks good, store it */
if (LocalHead || nf == tdebug)
fprintf(SUMA_STDERR,
"\tnt %d, N_voxels1d %d\n", nt, N_voxels1d);
voxels1d[N_voxels1d] = nijk; ++N_voxels1d;
signdist[N_voxels1d] = VolPar->Hand * dist;
if (fp) fprintf(fp, "%d %d %d\n",
voxelsijk[nt3], voxelsijk[nt3+1], voxelsijk[nt3+2]);
}
}
}
}
}
/* store the results */
vti->IntersectedVoxels[ti] = voxels1d;
vti->N_IntersectedVoxels[ti] = N_voxels1d;
vti->SignedIJKDistance[ti] = signdist;
voxels1d = NULL; N_voxels1d = 0; signdist = NULL;
}
if (LocalHead) {
if (fp) fclose(fp); fp = NULL;
}
if (!NodeIJKlistU) SUMA_free(NodeIJKlist);
SUMA_RETURN(vti);
}
/*!
A function to create a volume mask from the interestction
of triangles with a volumetric grid.
This function is meant to work with a bunch of triangles
that are not necessarily consistently wound.
The returned volume contains the shorted distance* of a voxel's centroid
from any triangle it touches.
The sign of the distance is relative to the triangle's normal and
is likely not consistent across voxels or triangles because the surface
may not be consistenly wound.
*The distance is in index units, not mm, so the value is not
quite accurate for non-cubic voxels.
If this is not a function you like, you are probably looking for:
SUMA_SurfGridIntersect
\sa SUMA_VoxelizeSurface
*/
THD_3dim_dataset *SUMA_SurfaceIntersectionVolume(
SUMA_SurfaceObject *SOo, THD_3dim_dataset *gdset)
{
static char FuncName[]={"SUMA_SurfaceIntersectionVolume"};
THD_3dim_dataset *odset=NULL;
SUMA_VOLPAR *vp=NULL;
SUMA_VTI *vti=NULL;
int ti, vi, ivox;
short *sbr=NULL;
float *fv=NULL, factor;
SUMA_ENTRY;
if (!SOo || !gdset) {
SUMA_S_Err("NULL input");
SUMA_RETURN(NULL);
}
if (!(vp = SUMA_VolParFromDset(gdset))) {
SUMA_S_Err("Failed to create volpar");
SUMA_RETURN(NULL);
}
vti = SUMA_CreateVTI(SOo->N_FaceSet, NULL);
vti = SUMA_GetVoxelsIntersectingTriangle(SOo, vp, NULL, vti);
if (!vti) {
SUMA_S_Err("Failed to get interesctions");
SUMA_RETURN(NULL);
}
odset = EDIT_empty_copy(gdset);
EDIT_dset_items( odset ,
ADN_prefix , FuncName ,
ADN_datum_all , MRI_short ,
ADN_nvals , 1 ,
ADN_ntt , 0 ,
ADN_none ) ;
fv = (float *)SUMA_calloc(DSET_NVOX(odset), sizeof(float));
for (ti=0; ti<vti->N_TriIndex; ++ti) {
for (vi=0; vi<vti->N_IntersectedVoxels[ti]; ++vi) {
ivox = vti->IntersectedVoxels[ti][vi];
if (fv[ivox] == 0.0f ||
SUMA_ABS(fv[ivox]) > SUMA_ABS(vti->SignedIJKDistance[ti][vi])){
fv[ivox] = vti->SignedIJKDistance[ti][vi];
}
}
}
EDIT_substitute_brick( odset , 0 , MRI_short , NULL ) ;
sbr = DSET_BRICK_ARRAY(odset,0);
factor = EDIT_coerce_autoscale_new( DSET_NVOX(odset), MRI_float, fv,
MRI_short, sbr);
if (factor > 0.0f) {
factor = 1.0 / factor;
} else factor = 0.0;
EDIT_BRICK_LABEL (odset, 0, "minIJKdistance");
EDIT_BRICK_FACTOR (odset, 0, factor);
SUMA_free(fv); fv = NULL;
vti = SUMA_FreeVTI(vti);
SUMA_Free_VolPar(vp); vp=NULL;
SUMA_RETURN(odset);
}
/*!
\sa SUMA_VoxelizeSurface
*/
THD_3dim_dataset *SUMA_MaskizeSurface(SUMA_SurfaceObject *SO,
THD_3dim_dataset *gdset,
int method)
{
static char FuncName[]={"SUMA_MaskizeSurface"};
short *is_in=NULL;
int N_in=0, ii=0;
THD_3dim_dataset *dset=NULL;
SUMA_VOLPAR *vp=NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (!SO || !gdset) SUMA_RETURN(NULL);
if (!(vp = SUMA_VolParFromDset(gdset))) {
SUMA_S_Err("Failed to create volpar");
SUMA_RETURN(NULL);
}
switch (method) {
case 1:
SUMA_LH("Voxel mask, fast, OK for good closed surfaces");
if (!(is_in = SUMA_FindVoxelsInSurface(SO, vp, &N_in, 1, NULL))) {
SUMA_S_Err("No voxels in closed surface!");
SUMA_RETURN(NULL);
}
break;
case 2:
SUMA_LH("Voxel mask, slow but more robust for closed surfaces");
if (!(is_in = SUMA_FindVoxelsInSurface_SLOW(SO, vp, &N_in, 0))) {
SUMA_S_Err("No voxels in closed surface!");
SUMA_RETURN(NULL);
}
break;
default:
SUMA_S_Errv("Bad method of %d\n", method);
SUMA_RETURN(NULL);
}
dset = EDIT_empty_copy(gdset);
tross_Copy_History( gdset , dset ) ;
EDIT_dset_items( dset ,
ADN_prefix , FuncName ,
ADN_type , HEAD_ANAT_TYPE ,
ADN_func_type , ANAT_BUCK_TYPE ,
ADN_none ) ;
EDIT_substitute_brick(dset, 0, MRI_short, is_in); is_in = NULL;
SUMA_Free_VolPar(vp); vp=NULL;
SUMA_RETURN(dset);
}
/*! Voxelize a surface.
gdset: Provides voxel grid
automask: Different methods for restricting voxel set
if mask is NULL.
0: No automasking
1: find voxels inside surface first using fast
method. Needs closed surfaces, might get some
holes left.
2: find voxels inside surface first using slow
method. Needs closed surfaces. More accurate
interiosity.
3: find voxels in bounding box. Need not worry
about closed surfaces, but sign of distance
is not reliable in places where normals are
bad. Sign is determined by the voxelizing function.
mask: If provided, restrict analysis to voxels in mask
If not provided and automask != 0, a mask is created
Otherwise all voxels are processed
\sa SUMA_SurfaceIntersectionVolume or SUMA_SurfGridIntersect
\sa SUMA_MaskizeSurface
*/
THD_3dim_dataset *SUMA_VoxelizeSurface(SUMA_SurfaceObject *SO,
THD_3dim_dataset *gdset,
int automask,
byte *mask)
{
static char FuncName[]={"SUMA_VoxelizeSurface"};
short *is_in=NULL;
int N_in=0, ii=0;
THD_3dim_dataset *dset=NULL;
SUMA_VOLPAR *vp=NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (!SO || !gdset) SUMA_RETURN(NULL);
if (!(vp = SUMA_VolParFromDset(gdset))) {
SUMA_S_Err("Failed to create volpar");
SUMA_RETURN(NULL);
}
if (!mask) {
switch (automask) {
case 1:
SUMA_LH("Voxel mask, fast, OK for good closed surfaces");
if (!(is_in = SUMA_FindVoxelsInSurface(SO, vp, &N_in, 1, NULL))) {
SUMA_S_Err("No voxels in closed surface!");
SUMA_RETURN(NULL);
}
SUMA_LH("Now Voxelizing, this is slow...");
dset = SUMA_VoxelToSurfDistances(SO, gdset, NULL, is_in, 0);
SUMA_free(is_in);
break;
case 2:
SUMA_LH("Voxel mask, slow but more robust for closed surfaces");
if (!(is_in = SUMA_FindVoxelsInSurface_SLOW(SO, vp, &N_in, 0))) {
SUMA_S_Err("No voxels in closed surface!");
SUMA_RETURN(NULL);
}
SUMA_LH("Now Voxelizing, this is slow...");
dset = SUMA_VoxelToSurfDistances(SO, gdset, NULL, is_in, 2);
SUMA_free(is_in);
break;
case 3:
SUMA_LH("Voxel mask, very fast, rely on voxelize for interiosity\n"
"But that may not be quite accurate at bad normals\n");
if (!(is_in = SUMA_FindVoxelsInSurface_SLOW(SO, vp, &N_in, 1))) {
SUMA_S_Err("No voxels in closed surface!");
SUMA_RETURN(NULL);
}
mask = (byte *)SUMA_calloc(DSET_NVOX(gdset),sizeof(byte));
for (ii=0; ii<DSET_NVOX(gdset); ++ii) {
if (is_in[ii]) mask[ii] = 1;
}
SUMA_free(is_in);
SUMA_LH("Now Voxelizing, this is slow, sign may not be accurate\n");
dset = SUMA_VoxelToSurfDistances(SO, gdset, mask, NULL, 0);
SUMA_free(mask); mask=NULL;
break;
case 0:
SUMA_LH("No mask, get a drink");
dset = SUMA_VoxelToSurfDistances(SO, gdset, NULL, NULL, 0);
break;
default:
SUMA_S_Errv("Bad automask of %d\n", automask);
SUMA_RETURN(NULL);
}
} else {
SUMA_LH("Voxelizing, with user mask this is slow...");
dset = SUMA_VoxelToSurfDistances(SO, gdset, mask, NULL, 0);
}
/* I want shorts back */
{
float *fv = (float *)SUMA_malloc(sizeof(float)*DSET_NVOX(dset));
memcpy(fv, DSET_ARRAY(dset,0), sizeof(float)*DSET_NVOX(dset));
EDIT_substscale_brick(dset, 0, MRI_float,
fv, MRI_short, -1.0);
SUMA_free(fv); fv = NULL;
}
SUMA_Free_VolPar(vp); vp=NULL;
SUMA_RETURN(dset);
}
THD_3dim_dataset *SUMA_VoxelToSurfDistances(SUMA_SurfaceObject *SO,
THD_3dim_dataset *master, byte *mask, short *isin,
short inval) {
static char FuncName[]={"SUMA_VoxelToSurfDistances"};
int i, j, k, n, nxyz, ijk, *closest=NULL, n_mask, n3;
float *dist=NULL, *Points=NULL;
byte *sgn=NULL;
THD_fvec3 ncoord, ndicom;
THD_ivec3 nind3;
THD_3dim_dataset *dset=NULL;
SUMA_FORM_AFNI_DSET_STRUCT *OptDs = NULL;
SUMA_Boolean LocalHead = NOPE;
SUMA_ENTRY;
if (isin && mask) {
SUMA_S_Err("Not supposed to mix the two ");
SUMA_RETURN(NULL);
}
/* get Points vectors */
nxyz = DSET_NVOX(master);
n_mask=0;
if (isin) {
mask = (byte *)SUMA_calloc(nxyz, sizeof(byte));
for (i=0; i<nxyz; ++i) {
if (isin[i]) { mask[i] = 1; ++n_mask;}
}
if (inval) {
sgn = (byte *)SUMA_calloc(n_mask, sizeof(byte));
j = 0;
for (i=0; i<nxyz; ++i) {
if (isin[i]) {
if (isin[i]>=inval) sgn[j] = 2;
else sgn[j] = 1;
++j;
}
}
}
} else {
if (!mask) {
n_mask = nxyz;
} else {
for (i=0; i<nxyz; ++i) if (mask[i]) ++n_mask;
}
}
SUMA_LHv("Have %d points in mask on %dx%dx%d grid\n",
n_mask, DSET_NX(master), DSET_NY(master), DSET_NZ(master));
Points = (float *)SUMA_calloc(3*n_mask, sizeof(float));
n = 0; ijk=0;
for (k=0; k<DSET_NZ(master); ++k) {
for (j=0; j<DSET_NY(master); ++j ) {
for (i=0; i<DSET_NX(master); ++i) {
if (!mask || mask[ijk]) {
n3 = 3*n;
nind3.ijk[0] = i; nind3.ijk[1] = j; nind3.ijk[2] = k;
ncoord = THD_3dind_to_3dmm(master, nind3);
ndicom = THD_3dmm_to_dicomm(master,ncoord);
Points[n3 ] = ndicom.xyz[0];
Points[n3+1] = ndicom.xyz[1];
Points[n3+2] = ndicom.xyz[2];
SUMA_LHv("Added [%f %f %f]\n",
Points[n3 ], Points[n3+1], Points[n3+2]);
++n;
}
++ijk;
}
}
}
/* get distance of each point to surface */
if (sgn == NULL) { /* Don't have sign yet.
Let SUMA_Shortest_Point_To_Triangles_Distance compute sign
based on dot product with normals.
This computation is not accurate everywhere ... */
if (!SUMA_Shortest_Point_To_Triangles_Distance(
Points, n_mask,
SO->NodeList, SO->FaceSetList, SO->N_FaceSet,
SO->FaceNormList, &dist, &closest, &sgn, 0)) {
SUMA_S_Err("Failed to get shortys");
SUMA_RETURN(NULL);
}
} else {/* have sign already */
if (!SUMA_Shortest_Point_To_Triangles_Distance(
Points, n_mask,
SO->NodeList, SO->FaceSetList, SO->N_FaceSet,
NULL, &dist, &closest, NULL , 0)) {
SUMA_S_Err("Failed to get shortys");
SUMA_RETURN(NULL);
}
}
for (i=0; i<n_mask; ++i) {
if (sgn[i]==2) dist[i] = sqrt(dist[i]);
else dist[i] = -sqrt(dist[i]);
}
SUMA_LHv("Point 0: [%f %f %f], Node 0: [%f %f %f]\n"
"dist %f, closest triangle %d, sign %d\n",
Points[0], Points[1], Points[2],
SO->NodeList[0], SO->NodeList[1], SO->NodeList[2],
dist[0], closest[0], sgn[0]);
OptDs = SUMA_New_FormAfniDset_Opt();
OptDs->prefix = SUMA_copy_string("3dVoxelToSurfDistances");
OptDs->prefix_path = SUMA_copy_string("./");
/* master dset */
OptDs->datum = MRI_float; /* you have to do the scaling yourself otherwise */
OptDs->full_list = 0;
OptDs->do_ijk = 0;
OptDs->coorder_xyz = 0;
OptDs->fval = 0.0;
OptDs->mset = master;
dset = SUMA_FormAfnidset (Points, dist, n_mask, OptDs);
OptDs->mset=NULL; OptDs = SUMA_Free_FormAfniDset_Opt(OptDs);
if (!dset) {
SUMA_SL_Err("Failed to create output dataset!");
}
/* free if needed */
if (isin) SUMA_free(mask); mask=NULL;
SUMA_RETURN(dset);
}
/*!
\brief Function to detect surface self intersection
returns -1 in case of error,
0 in case of no intersection
1 in case of intersection