-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmikktspace.odin
1782 lines (1533 loc) · 50.3 KB
/
mikktspace.odin
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
/**
* Port of Morten S. Mikkelsen's original tangent space algorithm
* implementation written in C, with some style changes to fit idiomatic
* Odin style. Original source: https://github.com/mmikk/MikkTSpace
*
* Original work: Copyright (C) 2011 by Morten S. Mikkelsen
* Modified work: Copyright (C) 2024 by Matthew Taylor
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package mikktspace
import "core:math"
import "core:math/linalg"
Interface :: struct {
// Returns the number of faces (triangles/quads) on the mesh to be processed.
get_num_faces: proc(pContext: ^Context) -> int,
// Returns the number of vertices on face number iFace
// iFace is a number in the range {0, 1, ..., getNumFaces()-1}
get_num_vertices_of_face: proc(pContext: ^Context, iFace: int) -> int,
// returns the position/normal/texcoord of the referenced face of vertex number iVert.
// iVert is in the range {0,1,2} for triangles and {0,1,2,3} for quads.
get_position: proc(pContext: ^Context, iFace: int, iVert: int) -> [3]f32,
get_normal: proc(pContext: ^Context, iFace: int, iVert: int) -> [3]f32,
get_tex_coord: proc(pContext: ^Context, iFace: int, iVert: int) -> [2]f32,
// either (or both) of the two setTSpace callbacks can be set.
// The call-back m_setTSpaceBasic() is sufficient for basic normal mapping.
// This function is used to return the tangent and fSign to the application.
// fvTangent is a unit length vector.
// For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level.
// bitangent = fSign * cross(vN, tangent);
// Note that the results are returned unindexed. It is possible to generate a new index list
// But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCORRECT results.
// DO NOT! use an already existing index list.
set_t_space_basic: proc(pContext: ^Context, fvTangent: [3]f32, fSign: f32, iFace: int, iVert: int),
// This function is used to return tangent space results to the application.
// fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their
// true magnitudes which can be used for relief mapping effects.
// fvBiTangent is the "real" bitangent and thus may not be perpendicular to fvTangent.
// However, both are perpendicular to the vertex normal.
// For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level.
// fSign = bIsOrientationPreserving ? 1.0f : (-1.0f);
// bitangent = fSign * cross(vN, tangent);
// Note that the results are returned unindexed. It is possible to generate a new index list
// But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results.
// DO NOT! use an already existing index list.
set_t_space: proc(
pContext: ^Context,
fvTangent: [3]f32,
fvBiTangent: [3]f32,
fMagS: f32,
fMagT: f32,
bIsOrientationPreserving: bool,
iFace: int,
iVert: int,
),
}
Context :: struct {
interface: ^Interface, // initialized with callback functions
user_data: rawptr, // pointer to client side mesh data etc. (passed as the first parameter with every interface call)
}
// Generates tangents using the provided interface and user data.
// Returns true if the operation succeeded, otherwise false.
generate_tangents :: proc(pContext: ^Context, fAngularThreshold: f32 = 180.0, allocator := context.allocator) -> bool {
// count nr_triangles
iNrTrianglesIn: int
iNrTSPaces, iTotTris, iDegenTriangles, iNrMaxGroups: int
iNrActiveGroups, index: int
iNrFaces := pContext.interface.get_num_faces(pContext)
bRes: bool
fThresCos := math.cos((fAngularThreshold * f32(math.PI)) / 180.0)
// verify all call-backs have been set
if pContext.interface.get_num_faces == nil ||
pContext.interface.get_num_vertices_of_face == nil ||
pContext.interface.get_position == nil ||
pContext.interface.get_normal == nil ||
pContext.interface.get_tex_coord == nil {
return false
}
// count triangles on supported faces
for f in 0 ..< iNrFaces {
verts := pContext.interface.get_num_vertices_of_face(pContext, f)
if verts == 3 do iNrTrianglesIn += 1
else if verts == 4 do iNrTrianglesIn += 2
}
if iNrTrianglesIn <= 0 do return false
// allocate memory for an index list
piTriListIn := make([]int, 3 * iNrTrianglesIn, allocator)
if piTriListIn == nil {
return false
}
defer delete(piTriListIn)
pTriInfos := make([]Tri_Info, iNrTrianglesIn, allocator)
if pTriInfos == nil {
return false
}
defer delete(pTriInfos)
// make an initial triangle . face index list
iNrTSPaces = generate_initial_vertices_index_list(pTriInfos, piTriListIn, pContext, iNrTrianglesIn)
// make a welded index list of identical positions and attributes (pos, norm, texc)
generate_shared_vertices_index_list(piTriListIn, pContext, iNrTrianglesIn, allocator)
// Mark all degenerate triangles
iTotTris = iNrTrianglesIn
iDegenTriangles = 0
for t in 0 ..< iTotTris {
i0 := piTriListIn[t * 3 + 0]
i1 := piTriListIn[t * 3 + 1]
i2 := piTriListIn[t * 3 + 2]
p0 := get_position(pContext, i0)
p1 := get_position(pContext, i1)
p2 := get_position(pContext, i2)
if (p0 == p1) || (p0 == p2) || (p1 == p2) { // degenerate
pTriInfos[t].iFlag |= {.MarkDegenerate}
iDegenTriangles += 1
}
}
iNrTrianglesIn = iTotTris - iDegenTriangles
// mark all triangle pairs that belong to a quad with only one
// good triangle. These need special treatment in DegenEpilogue().
// Additionally, move all good triangles to the start of
// pTriInfos[] and piTriListIn[] without changing order and
// put the degenerate triangles last.
degen_prologue(pTriInfos, piTriListIn, iNrTrianglesIn, iTotTris)
// evaluate triangle level attributes and neighbor list
init_tri_info(pTriInfos, piTriListIn, pContext, iNrTrianglesIn, allocator)
// based on the 4 rules, identify groups based on connectivity
iNrMaxGroups = iNrTrianglesIn * 3
pGroups := make([]Group, iNrMaxGroups, allocator)
defer delete(pGroups)
piGroupTrianglesBuffer := make([]int, iNrTrianglesIn * 3, allocator)
defer delete(piGroupTrianglesBuffer)
if pGroups == nil || piGroupTrianglesBuffer == nil {
return false
}
iNrActiveGroups = build_4_rule_groups(pTriInfos, pGroups, piGroupTrianglesBuffer, piTriListIn, iNrTrianglesIn)
psTspace := make([]T_Space, iNrTSPaces, allocator)
defer delete(psTspace)
if psTspace == nil {
return false
}
for t in 0 ..< iNrTSPaces {
psTspace[t].vOs.x = 1.0
psTspace[t].vOs.y = 0.0
psTspace[t].vOs.z = 0.0
psTspace[t].fMagS = 1.0
psTspace[t].vOt.x = 0.0
psTspace[t].vOt.y = 1.0
psTspace[t].vOt.z = 0.0
psTspace[t].fMagT = 1.0
}
// make tspaces, each group is split up into subgroups if necessary
// based on fAngularThreshold. Finally a tangent space is made for
// every resulting subgroup
bRes = generate_t_spaces(psTspace, pTriInfos, pGroups, iNrActiveGroups, piTriListIn, fThresCos, pContext, allocator)
// clean up
if !bRes {
return false
}
// degenerate quads with one good triangle will be fixed by copying a space from
// the good triangle to the coinciding vertex.
// all other degenerate triangles will just copy a space from any good triangle
// with the same welded index in piTriListIn[].
degen_epilogue(psTspace, pTriInfos, piTriListIn, pContext, iNrTrianglesIn, iTotTris)
index = 0
for f in 0 ..< iNrFaces {
verts := pContext.interface.get_num_vertices_of_face(pContext, f)
if verts != 3 && verts != 4 do continue
// I've decided to let degenerate triangles and group-with-anythings
// vary between left/right hand coordinate systems at the vertices.
// All healthy triangles on the other hand are built to always be either or.
/*// force the coordinate system orientation to be uniform for every face.
// (this is already the case for good triangles but not for
// degenerate ones and those with bGroupWithAnything==true)
bool bOrient = psTspace[index].bOrient;
if psTspace[index].iCounter == 0 do // tspace was not derived from a group
{
// look for a space created in GenerateTSpaces() by iCounter>0
bool bNotFound = true;
int i=1;
for (i<verts && bNotFound)
{
if psTspace[index+i].iCounter > 0 do bNotFound=false;
else ++i;
}
if !bNotFound do bOrient = psTspace[index+i].bOrient;
}*/
// set data
for i in 0 ..< verts {
pTSpace: ^T_Space = &psTspace[index]
tang: [3]f32 = {pTSpace.vOs.x, pTSpace.vOs.y, pTSpace.vOs.z}
bitang: [3]f32 = {pTSpace.vOt.x, pTSpace.vOt.y, pTSpace.vOt.z}
if pContext.interface.set_t_space != nil {
pContext.interface.set_t_space(pContext, tang, bitang, pTSpace.fMagS, pTSpace.fMagT, pTSpace.bOrient, f, i)
}
if pContext.interface.set_t_space_basic != nil {
pContext.interface.set_t_space_basic(pContext, tang, pTSpace.bOrient == true ? 1.0 : (-1.0), f, i)
}
index += 1
}
}
return true
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@(private)
INTERNAL_RND_SORT_SEED: u32 : 39871946
@(private)
Vec3 :: [3]f32
@(private)
Sub_Group :: struct {
iNrFaces: int,
pTriMembers: []int,
}
@(private)
Group :: struct {
iNrFaces: int,
pFaceIndices: []int,
iVertexRepresentitive: int,
bOrientPreservering: bool,
}
@(private)
Tri_Flag :: enum {
MarkDegenerate,
QuadOneDegenTri,
GroupWithAny,
OrientPreserving,
}
@(private)
Tri_Flags :: bit_set[Tri_Flag]
@(private)
Tri_Info :: struct {
FaceNeighbors: [3]int,
AssignedGroup: [3]^Group,
// normalized first order face derivatives
vOs, vOt: Vec3,
fMagS, fMagT: f32,
// determines if the current and the next triangle are a quad.
iOrgFaceNumber: int,
iFlag: Tri_Flags,
iTSpacesOffs: int,
vert_num: [4]u8,
}
@(private)
T_Space :: struct {
vOs: Vec3,
fMagS: f32,
vOt: Vec3,
fMagT: f32,
iCounter: int, // this is to average back into quads.
bOrient: bool,
}
@(private)
make_index :: proc(iFace: int, iVert: int) -> int {
assert(iVert >= 0 && iVert < 4 && iFace >= 0)
return (iFace << 2) | (iVert & 0x3)
}
@(private)
index_to_data :: proc(piFace: ^int, piVert: ^int, iIndexIn: int) {
piVert^ = iIndexIn & 0x3
piFace^ = iIndexIn >> 2
}
@(private)
avg_t_space :: proc(pTS0: ^T_Space, pTS1: ^T_Space) -> T_Space {
ts_res: T_Space
// this if is important. Due to floating point precision
// averaging when ts0==ts1 will cause a slight difference
// which results in tangent space splits later on
if pTS0.fMagS == pTS1.fMagS && pTS0.fMagT == pTS1.fMagT && pTS0.vOs == pTS1.vOs && pTS0.vOt == pTS1.vOt {
ts_res.fMagS = pTS0.fMagS
ts_res.fMagT = pTS0.fMagT
ts_res.vOs = pTS0.vOs
ts_res.vOt = pTS0.vOt
} else {
ts_res.fMagS = 0.5 * (pTS0.fMagS + pTS1.fMagS)
ts_res.fMagT = 0.5 * (pTS0.fMagT + pTS1.fMagT)
ts_res.vOs = pTS0.vOs + pTS1.vOs
ts_res.vOt = pTS0.vOt + pTS1.vOt
if ts_res.vOs != 0 do ts_res.vOs = linalg.normalize(ts_res.vOs)
if ts_res.vOt != 0 do ts_res.vOt = linalg.normalize(ts_res.vOt)
}
return ts_res
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@(private)
Tmp_Vert :: struct {
vert: [3]f32,
index: int,
}
@(private)
G_CELLS :: 2048
// it is IMPORTANT that this function is called to evaluate the hash since
// inlining could potentially reorder instructions and generate different
// results for the same effective input value fVal.
// FindGridCell
@(private)
find_grid_cell :: #force_no_inline proc(fMin: f32, fMax: f32, fVal: f32) -> int {
fIndex := f32(G_CELLS) * ((fVal - fMin) / (fMax - fMin))
iIndex := int(fIndex)
return iIndex < G_CELLS ? (iIndex >= 0 ? iIndex : 0) : (G_CELLS - 1)
}
@(private)
generate_shared_vertices_index_list :: proc(piTriList_in_and_out: []int, pContext: ^Context, iNrTrianglesIn: int, allocator := context.allocator) {
// Generate bounding box
iChannel: int
iMaxCount: int
vMin := get_position(pContext, 0)
vMax := vMin
vDim: Vec3
fMin, fMax: f32
for i in 1 ..< (iNrTrianglesIn * 3) {
index := piTriList_in_and_out[i]
vP := get_position(pContext, index)
if vMin.x > vP.x do vMin.x = vP.x
else if vMax.x < vP.x do vMax.x = vP.x
if vMin.y > vP.y do vMin.y = vP.y
else if vMax.y < vP.y do vMax.y = vP.y
if vMin.z > vP.z do vMin.z = vP.z
else if vMax.z < vP.z do vMax.z = vP.z
}
vDim = vMax - vMin
iChannel = 0
fMin = vMin.x
fMax = vMax.x
if vDim.y > vDim.x && vDim.y > vDim.z {
iChannel = 1
fMin = vMin.y
fMax = vMax.y
} else if vDim.z > vDim.x {
iChannel = 2
fMin = vMin.z
fMax = vMax.z
}
// make allocations
piHashTable := make([]int, iNrTrianglesIn * 3, allocator)
defer delete(piHashTable)
piHashCount := make([]int, G_CELLS, allocator)
defer delete(piHashCount)
piHashOffsets := make([]int, G_CELLS, allocator)
defer delete(piHashOffsets)
piHashCount2 := make([]int, G_CELLS, allocator)
defer delete(piHashCount2)
if piHashTable == nil || piHashCount == nil || piHashOffsets == nil || piHashCount2 == nil {
generate_shared_vertices_index_list_slow(piTriList_in_and_out, pContext, iNrTrianglesIn)
return
}
// count amount of elements in each cell unit
for i in 0 ..< (iNrTrianglesIn * 3) {
index := piTriList_in_and_out[i]
vP := get_position(pContext, index)
fVal := iChannel == 0 ? vP.x : (iChannel == 1 ? vP.y : vP.z)
iCell := find_grid_cell(fMin, fMax, fVal)
piHashCount[iCell] += 1
}
// evaluate start index of each cell.
piHashOffsets[0] = 0
for k in 1 ..< G_CELLS {
piHashOffsets[k] = piHashOffsets[k - 1] + piHashCount[k - 1]
}
// insert vertices
for i in 0 ..< (iNrTrianglesIn * 3) {
index := piTriList_in_and_out[i]
vP := get_position(pContext, index)
fVal := iChannel == 0 ? vP.x : (iChannel == 1 ? vP.y : vP.z)
iCell := find_grid_cell(fMin, fMax, fVal)
assert(piHashCount2[iCell] < piHashCount[iCell])
pTable := piHashTable[piHashOffsets[iCell]:]
pTable[piHashCount2[iCell]] = i // vertex i has been inserted.
piHashCount2[iCell] += 1
}
for k in 0 ..< G_CELLS {
assert(piHashCount2[k] == piHashCount[k]) // verify the count
}
// find maximum amount of entries in any hash entry
iMaxCount = piHashCount[0]
for k in 1 ..< G_CELLS {
if iMaxCount < piHashCount[k] {
iMaxCount = piHashCount[k]
}
}
pTmpVert := make([]Tmp_Vert, iMaxCount, allocator)
defer delete(pTmpVert)
// complete the merge
for k in 0 ..< G_CELLS {
// extract table of cell k and amount of entries in it
pTable := piHashTable[piHashOffsets[k]:]
iEntries := piHashCount[k]
if iEntries < 2 do continue
if pTmpVert != nil {
for e in 0 ..< iEntries {
i := pTable[e]
vP := get_position(pContext, piTriList_in_and_out[i])
pTmpVert[e].vert[0] = vP.x
pTmpVert[e].vert[1] = vP.y
pTmpVert[e].vert[2] = vP.z
pTmpVert[e].index = i
}
merge_verts_fast(piTriList_in_and_out, pTmpVert, pContext, 0, iEntries - 1)
} else {
merge_verts_slow(piTriList_in_and_out, pContext, pTable, iEntries)
}
}
}
@(private)
merge_verts_fast :: proc(piTriList_in_and_out: []int, pTmpVert: []Tmp_Vert, pContext: ^Context, iL_in: int, iR_in: int) {
// make bbox
fvMin, fvMax: [3]f32
dx, dy, dz, fSep: f32
for c in 0 ..< 3 {
fvMin[c] = pTmpVert[iL_in].vert[c]
fvMax[c] = fvMin[c]
}
for l in (iL_in + 1) ..= iR_in {
for c in 0 ..< 3 {
if fvMin[c] > pTmpVert[l].vert[c] do fvMin[c] = pTmpVert[l].vert[c]
if fvMax[c] < pTmpVert[l].vert[c] do fvMax[c] = pTmpVert[l].vert[c]
}
}
dx = fvMax[0] - fvMin[0]
dy = fvMax[1] - fvMin[1]
dz = fvMax[2] - fvMin[2]
channel := 0
if dy > dx && dy > dz do channel = 1
else if dz > dx do channel = 2
fSep = 0.5 * (fvMax[channel] + fvMin[channel])
// stop if all vertices are NaNs
if math.is_nan(fSep) || math.is_inf(fSep) do return
// terminate recursion when the separation/average value
// is no longer strictly between fMin and fMax values.
if fSep >= fvMax[channel] || fSep <= fvMin[channel] {
// complete the weld
for l in 0 ..= iR_in {
i := pTmpVert[l].index
index := piTriList_in_and_out[i]
vP := get_position(pContext, index)
vN := get_normal(pContext, index)
vT := get_tex_coord(pContext, index)
bNotFound := true
l2 := iL_in
i2rec := -1
for l2 < l && bNotFound {
i2 := pTmpVert[l2].index
index2 := piTriList_in_and_out[i2]
vP2 := get_position(pContext, index2)
vN2 := get_normal(pContext, index2)
vT2 := get_tex_coord(pContext, index2)
i2rec = i2
if vP == vP2 && vN == vN2 && vT == vT2 {
bNotFound = false
} else {
l2 += 1
}
}
// merge if previously found
if !bNotFound {
piTriList_in_and_out[i] = piTriList_in_and_out[i2rec]
}
}
} else {
iL := iL_in
iR := iR_in
assert((iR_in - iL_in) > 0) // at least 2 entries
// separate (by fSep) all points between iL_in and iR_in in pTmpVert[]
for (iL < iR) {
bReadyLeftSwap := false
bReadyRightSwap := false
for ((!bReadyLeftSwap) && iL < iR) {
assert(iL >= iL_in && iL <= iR_in)
bReadyLeftSwap = !(pTmpVert[iL].vert[channel] < fSep)
if !bReadyLeftSwap do iL += 1
}
for ((!bReadyRightSwap) && iL < iR) {
assert(iR >= iL_in && iR <= iR_in)
bReadyRightSwap = pTmpVert[iR].vert[channel] < fSep
if !bReadyRightSwap do iR -= 1
}
assert((iL < iR) || !(bReadyLeftSwap && bReadyRightSwap))
if bReadyLeftSwap && bReadyRightSwap {
sTmp: Tmp_Vert = pTmpVert[iL]
assert(iL < iR)
pTmpVert[iL] = pTmpVert[iR]
pTmpVert[iR] = sTmp
iL += 1
iR -= 1
}
}
assert(iL == (iR + 1) || (iL == iR))
if iL == iR {
bReadyRightSwap := pTmpVert[iR].vert[channel] < fSep
if bReadyRightSwap {
iL += 1
} else {
iR -= 1
}
}
// only need to weld when there is more than 1 instance of the (x,y,z)
if iL_in < iR {
merge_verts_fast(piTriList_in_and_out, pTmpVert, pContext, iL_in, iR) // weld all left of fSep
}
if iL < iR_in {
merge_verts_fast(piTriList_in_and_out, pTmpVert, pContext, iL, iR_in) // weld all right of (or equal to) fSep
}
}
}
@(private)
merge_verts_slow :: proc(piTriList_in_and_out: []int, pContext: ^Context, pTable: []int, iEntries: int) {
// this can be optimized further using a tree structure or more hashing.
for e in 0 ..< iEntries {
i := pTable[e]
index := piTriList_in_and_out[i]
vP := get_position(pContext, index)
vN := get_normal(pContext, index)
vT := get_tex_coord(pContext, index)
bNotFound := true
e2 := 0
i2rec := -1
for e2 < e && bNotFound {
i2 := pTable[e2]
index2 := piTriList_in_and_out[i2]
vP2 := get_position(pContext, index2)
vN2 := get_normal(pContext, index2)
vT2 := get_tex_coord(pContext, index2)
i2rec = i2
if (vP == vP2) && (vN == vN2) && (vT == vT2) {
bNotFound = false
} else {
e2 += 1
}
}
// merge if previously found
if !bNotFound {
piTriList_in_and_out[i] = piTriList_in_and_out[i2rec]
}
}
}
@(private)
generate_shared_vertices_index_list_slow :: proc(piTriList_in_and_out: []int, pContext: ^Context, iNrTrianglesIn: int) {
iNumUniqueVerts := 0
for t in 0 ..< iNrTrianglesIn {
for i in 0 ..< 3 {
offs := t * 3 + i
index := piTriList_in_and_out[offs]
vP: Vec3 = get_position(pContext, index)
vN: Vec3 = get_normal(pContext, index)
vT: Vec3 = get_tex_coord(pContext, index)
bFound := false
t2 := 0
index2rec := -1
for !bFound && t2 <= t {
j := 0
for (!bFound && j < 3) {
index2 := piTriList_in_and_out[t2 * 3 + j]
vP2 := get_position(pContext, index2)
vN2 := get_normal(pContext, index2)
vT2 := get_tex_coord(pContext, index2)
if (vP == vP2) && (vN == vN2) && (vT == vT2) {
bFound = true
} else {
j += 1
}
}
if !bFound do t2 += 1
}
assert(bFound)
// if we found our own
if index2rec == index do iNumUniqueVerts += 1
piTriList_in_and_out[offs] = index2rec
}
}
}
@(private)
generate_initial_vertices_index_list :: proc(pTriInfos: []Tri_Info, piTriList_out: []int, pContext: ^Context, iNrTrianglesIn: int) -> int {
iTSpacesOffs := 0
iDstTriIndex := 0
for f in 0 ..< pContext.interface.get_num_faces(pContext) {
verts := pContext.interface.get_num_vertices_of_face(pContext, f)
if verts != 3 && verts != 4 do continue
pTriInfos[iDstTriIndex].iOrgFaceNumber = f
pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs
if verts == 3 {
pVerts := &pTriInfos[iDstTriIndex].vert_num
pVerts[0] = 0
pVerts[1] = 1
pVerts[2] = 2
piTriList_out[iDstTriIndex * 3 + 0] = make_index(f, 0)
piTriList_out[iDstTriIndex * 3 + 1] = make_index(f, 1)
piTriList_out[iDstTriIndex * 3 + 2] = make_index(f, 2)
iDstTriIndex += 1 // next
} else {
{
pTriInfos[iDstTriIndex + 1].iOrgFaceNumber = f
pTriInfos[iDstTriIndex + 1].iTSpacesOffs = iTSpacesOffs
}
{
// need an order independent way to evaluate
// tspace on quads. This is done by splitting
// along the shortest diagonal.
i0 := make_index(f, 0)
i1 := make_index(f, 1)
i2 := make_index(f, 2)
i3 := make_index(f, 3)
T0 := get_tex_coord(pContext, i0)
T1 := get_tex_coord(pContext, i1)
T2 := get_tex_coord(pContext, i2)
T3 := get_tex_coord(pContext, i3)
distSQ_02 := linalg.length2(T2 - T0)
distSQ_13 := linalg.length2(T3 - T1)
bQuadDiagIs_02: bool
if distSQ_02 < distSQ_13 {
bQuadDiagIs_02 = true
} else if distSQ_13 < distSQ_02 {
bQuadDiagIs_02 = false
} else {
P0 := get_position(pContext, i0)
P1 := get_position(pContext, i1)
P2 := get_position(pContext, i2)
P3 := get_position(pContext, i3)
distSQ_02 = linalg.length2(P2 - P0)
distSQ_13 = linalg.length2(P3 - P1)
bQuadDiagIs_02 = distSQ_13 < distSQ_02 ? false : true
}
if bQuadDiagIs_02 {
{
pVerts_A := &pTriInfos[iDstTriIndex].vert_num
pVerts_A[0] = 0
pVerts_A[1] = 1
pVerts_A[2] = 2
}
piTriList_out[iDstTriIndex * 3 + 0] = i0
piTriList_out[iDstTriIndex * 3 + 1] = i1
piTriList_out[iDstTriIndex * 3 + 2] = i2
iDstTriIndex += 1 // next
{
pVerts_B := &pTriInfos[iDstTriIndex].vert_num
pVerts_B[0] = 0
pVerts_B[1] = 2
pVerts_B[2] = 3
}
piTriList_out[iDstTriIndex * 3 + 0] = i0
piTriList_out[iDstTriIndex * 3 + 1] = i2
piTriList_out[iDstTriIndex * 3 + 2] = i3
iDstTriIndex += 1 // next
} else {
{
pVerts_A := &pTriInfos[iDstTriIndex].vert_num
pVerts_A[0] = 0
pVerts_A[1] = 1
pVerts_A[2] = 3
}
piTriList_out[iDstTriIndex * 3 + 0] = i0
piTriList_out[iDstTriIndex * 3 + 1] = i1
piTriList_out[iDstTriIndex * 3 + 2] = i3
iDstTriIndex += 1 // next
{
pVerts_B := &pTriInfos[iDstTriIndex].vert_num
pVerts_B[0] = 1
pVerts_B[1] = 2
pVerts_B[2] = 3
}
piTriList_out[iDstTriIndex * 3 + 0] = i1
piTriList_out[iDstTriIndex * 3 + 1] = i2
piTriList_out[iDstTriIndex * 3 + 2] = i3
iDstTriIndex += 1 // next
}
}
}
iTSpacesOffs += verts
assert(iDstTriIndex <= iNrTrianglesIn)
}
for t in 0 ..< iNrTrianglesIn {
pTriInfos[t].iFlag = {}
}
// return total amount of tspaces
return iTSpacesOffs
}
@(private)
get_position :: proc(pContext: ^Context, index: int) -> Vec3 {
iF, iI: int
index_to_data(&iF, &iI, index)
pos := pContext.interface.get_position(pContext, iF, iI)
return pos
}
@(private)
get_normal :: proc(pContext: ^Context, index: int) -> Vec3 {
iF, iI: int
index_to_data(&iF, &iI, index)
norm := pContext.interface.get_normal(pContext, iF, iI)
return norm
}
@(private)
get_tex_coord :: proc(pContext: ^Context, index: int) -> Vec3 {
iF, iI: int
res: Vec3
index_to_data(&iF, &iI, index)
texc := pContext.interface.get_tex_coord(pContext, iF, iI)
res.xy = texc.xy
res.z = 1.0
return res
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
@(private)
Edge :: struct #raw_union {
using a: struct {
i0, i1, f: int,
},
array: [3]int,
}
// returns the texture area times 2
@(private)
calc_tex_area :: proc(pContext: ^Context, indices: []int) -> f32 {
t1: Vec3 = get_tex_coord(pContext, indices[0])
t2: Vec3 = get_tex_coord(pContext, indices[1])
t3: Vec3 = get_tex_coord(pContext, indices[2])
t21x := t2.x - t1.x
t21y := t2.y - t1.y
t31x := t3.x - t1.x
t31y := t3.y - t1.y
fSignedAreaSTx2 := t21x * t31y - t21y * t31x
return fSignedAreaSTx2 < 0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2
}
@(private)
init_tri_info :: proc(pTriInfos: []Tri_Info, piTriListIn: []int, pContext: ^Context, iNrTrianglesIn: int, allocator := context.allocator) {
// pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function.
// generate neighbor info list
for f in 0 ..< iNrTrianglesIn {
for i in 0 ..< 3 {
pTriInfos[f].FaceNeighbors[i] = -1
pTriInfos[f].AssignedGroup[i] = nil
pTriInfos[f].vOs.x = 0.0
pTriInfos[f].vOs.y = 0.0
pTriInfos[f].vOs.z = 0.0
pTriInfos[f].vOt.x = 0.0
pTriInfos[f].vOt.y = 0.0
pTriInfos[f].vOt.z = 0.0
pTriInfos[f].fMagS = 0
pTriInfos[f].fMagT = 0
// assumed bad
pTriInfos[f].iFlag |= {.GroupWithAny}
}
}
// evaluate first order derivatives
for f in 0 ..< iNrTrianglesIn {
// initial values
v1 := get_position(pContext, piTriListIn[f * 3 + 0])
v2 := get_position(pContext, piTriListIn[f * 3 + 1])
v3 := get_position(pContext, piTriListIn[f * 3 + 2])
t1 := get_tex_coord(pContext, piTriListIn[f * 3 + 0])
t2 := get_tex_coord(pContext, piTriListIn[f * 3 + 1])
t3 := get_tex_coord(pContext, piTriListIn[f * 3 + 2])
t21x := t2.x - t1.x
t21y := t2.y - t1.y
t31x := t3.x - t1.x
t31y := t3.y - t1.y
d1 := v2 - v1
d2 := v3 - v1
fSignedAreaSTx2 := t21x * t31y - t21y * t31x
vOs := (t31y * d1) - (t21y * d2)
vOt := (-t31x * d1) - (t21x * d2)
if fSignedAreaSTx2 > 0.0 {
pTriInfos[f].iFlag |= {.OrientPreserving}
}
if fSignedAreaSTx2 != 0 {
fAbsArea := math.abs(fSignedAreaSTx2)
fLenOs := linalg.length(vOs)
fLenOt := linalg.length(vOt)
fS: f32 = .OrientPreserving in pTriInfos[f].iFlag ? (-1.0) : 1.0
if fLenOs != 0.0 do pTriInfos[f].vOs = (fS / fLenOs) * vOs
if fLenOt != 0.0 do pTriInfos[f].vOt = (fS / fLenOt) * vOt
// evaluate magnitudes prior to normalization of vOs and vOt
pTriInfos[f].fMagS = fLenOs / fAbsArea
pTriInfos[f].fMagT = fLenOt / fAbsArea
// if this is a good triangle
if pTriInfos[f].fMagS != 0.0 && pTriInfos[f].fMagT != 0.0 {
pTriInfos[f].iFlag -= {.GroupWithAny}
}
}
}
t: int
// force otherwise healthy quads to a fixed orientation
for (t < (iNrTrianglesIn - 1)) {
iFO_a := pTriInfos[t].iOrgFaceNumber
iFO_b := pTriInfos[t + 1].iOrgFaceNumber
if iFO_a == iFO_b { // this is a quad
bIsDeg_a := .MarkDegenerate in pTriInfos[t].iFlag
bIsDeg_b := .MarkDegenerate in pTriInfos[t + 1].iFlag
// bad triangles should already have been removed by
// DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false
if bIsDeg_a || bIsDeg_b {
bOrientA := .OrientPreserving in pTriInfos[t].iFlag
bOrientB := .OrientPreserving in pTriInfos[t + 1].iFlag
// if this happens the quad has extremely bad mapping!!
if bOrientA != bOrientB {
bChooseOrientFirstTri := false
if .GroupWithAny in pTriInfos[t + 1].iFlag {
bChooseOrientFirstTri = true
} else if calc_tex_area(pContext, piTriListIn[t * 3 + 0:]) >= calc_tex_area(pContext, piTriListIn[(t + 1) * 3 + 0:]) {
bChooseOrientFirstTri = true
}
// force match
{
t0 := bChooseOrientFirstTri ? t : (t + 1)
t1 := bChooseOrientFirstTri ? (t + 1) : t
pTriInfos[t1].iFlag -= {.OrientPreserving} // clear first
pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag & {.OrientPreserving}) // copy bit
}
}
}
t += 2
} else {
t += 1
}
}
// match up edge pairs
{
pEdges := make([]Edge, iNrTrianglesIn * 3, allocator)
defer delete(pEdges)
if pEdges == nil {
build_neighbors_slow(pTriInfos, piTriListIn, iNrTrianglesIn)
} else {
build_neighbors_fast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn)
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
@(private)
build_4_rule_groups :: proc(
pTriInfos: []Tri_Info,
pGroups: []Group,
piGroupTrianglesBuffer: []int,
piTriListIn: []int,
iNrTrianglesIn: int,
) -> int {
iNrMaxGroups := iNrTrianglesIn * 3
iNrActiveGroups: int
iOffset: int
for f in 0 ..< iNrTrianglesIn {
for i in 0 ..< 3 {
// if not assigned to a group
if .GroupWithAny not_in pTriInfos[f].iFlag && pTriInfos[f].AssignedGroup[i] == nil {
bOrPre: bool
neigh_indexL, neigh_indexR: int
vert_index := piTriListIn[f * 3 + i]
assert(iNrActiveGroups < iNrMaxGroups)
pTriInfos[f].AssignedGroup[i] = &pGroups[iNrActiveGroups]