-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathrender-data.cc
3082 lines (2529 loc) · 93.5 KB
/
render-data.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache 2.0
// Copyright 2022 - 2023, Syoyo Fujita.
// Copyright 2023 - Present, Light Transport Entertainment Inc.
//
// TODO:
// - [ ] Subdivision surface to polygon mesh conversion.
// - [ ] Correctly handle primvar with 'vertex' interpolation(Use the basis function of subd surface)
// - [ ] Support time-varying shader attribute(timeSamples)
//
#include "image-loader.hh"
#include "image-util.hh"
#include "pprinter.hh"
#include "prim-types.hh"
#include "str-util.hh"
#include "tiny-format.hh"
#include "tinyusdz.hh"
#include "usdGeom.hh"
#include "usdShade.hh"
#include "value-pprint.hh"
#include "linear-algebra.hh"
#if defined(TINYUSDZ_WITH_COLORIO)
#include "external/tiny-color-io.h"
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
// For triangulation.
// TODO: Use tinyobjloader's triangulation
#include "external/mapbox/earcut/earcut.hpp"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
//
#include "common-macros.inc"
#include "math-util.inc"
//
#include "tydra/render-data.hh"
#include "tydra/scene-access.hh"
#include "tydra/shader-network.hh"
#if 0 // not used a.t.m.
#define SET_ERROR_AND_RETURN(msg) \
if (err) { \
(*err) = (msg); \
} \
return false
#endif
namespace tinyusdz {
namespace tydra {
namespace {
inline std::string to_string(const UVTexture::Channel channel) {
if (channel == UVTexture::Channel::RGB) {
return "rgb";
} else if (channel == UVTexture::Channel::R) {
return "r";
} else if (channel == UVTexture::Channel::G) {
return "g";
} else if (channel == UVTexture::Channel::B) {
return "b";
} else if (channel == UVTexture::Channel::A) {
return "a";
}
return "[[InternalError. Invalid UVTexture::Channel]]";
}
#if 0
template <typename T>
inline T Get(const nonstd::optional<T> &nv, const T &default_value) {
if (nv) {
return nv.value();
}
return default_value;
}
#endif
//
// Convert vertex attribute with Uniform variability(interpolation) to facevarying attribute,
// by replicating uniform value per face over face vertices.
//
template <typename T>
nonstd::expected<std::vector<T>, std::string> UniformToFaceVarying(
const std::vector<T> &inputs, const std::vector<uint32_t> &faceVertexCounts)
{
std::vector<T> dst;
if (inputs.size() == faceVertexCounts.size()) {
return nonstd::make_unexpected(
fmt::format("The number of inputs {} must be the same with "
"faceVertexCounts.size() {}",
inputs.size(), faceVertexCounts.size()));
}
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
// repeat cnt times.
for (size_t k = 0; k < cnt; k++) {
dst.emplace_back(inputs[i]);
}
}
return dst;
}
// Generic uniform to facevarying conversion
nonstd::expected<std::vector<uint8_t>, std::string> UniformToFaceVarying(
const std::vector<uint8_t> &src,
const size_t stride_bytes,
const std::vector<uint32_t> &faceVertexCounts)
{
std::vector<uint8_t> dst;
if (stride_bytes == 0) {
return nonstd::make_unexpected("stride_bytes is zero.");
}
if ((src.size() % stride_bytes) != 0) {
return nonstd::make_unexpected(
fmt::format("input bytes {} must be the multiple of stride_bytes {}",
src.size(), stride_bytes));
}
size_t num_uniforms = src.size() / stride_bytes;
if (num_uniforms == faceVertexCounts.size()) {
return nonstd::make_unexpected(
fmt::format("The number of input uniform attributes {} must be the same with "
"faceVertexCounts.size() {}",
num_uniforms, faceVertexCounts.size()));
}
std::vector<uint8_t> buf;
buf.resize(stride_bytes);
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
memcpy(buf.data(), src.data() + i * stride_bytes, stride_bytes);
// repeat cnt times.
for (size_t k = 0; k < cnt; k++) {
dst.insert(dst.end(), buf.begin(), buf.end());
}
}
return dst;
}
//
// Convert vertex attribute with Vertex variability(interpolation) to facevarying attribute,
// by expanding(flatten) the value per vertex per face.
//
template <typename T>
nonstd::expected<std::vector<T>, std::string> VertexToFaceVarying(
const std::vector<T> &inputs, const std::vector<uint32_t> &faceVertexCounts,
const std::vector<uint32_t> &faceVertexIndices) {
std::vector<T> dst;
size_t face_offset{0};
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
for (size_t k = 0; k < cnt; k++) {
size_t idx = k + face_offset;
if (idx >= faceVertexIndices.size()) {
return nonstd::make_unexpected(fmt::format(
"faeVertexIndex out-of-range at faceVertexCount[{}]", i));
}
size_t v_idx = faceVertexIndices[idx];
if (v_idx >= inputs.size()) {
return nonstd::make_unexpected(
fmt::format("faeVertexIndices[{}] {} exceeds input array size {}",
idx, v_idx, inputs.size()));
}
dst.emplace_back(inputs[v_idx]);
}
face_offset += cnt;
}
return dst;
}
// Generic vertex to facevarying conversion
nonstd::expected<std::vector<uint8_t>, std::string> VertexToFaceVarying(
const std::vector<uint8_t> &src,
const size_t stride_bytes,
const std::vector<uint32_t> &faceVertexCounts,
const std::vector<uint32_t> &faceVertexIndices) {
std::vector<uint8_t> dst;
if (src.empty()) {
return nonstd::make_unexpected(
"src data is empty.");
}
if (stride_bytes == 0) {
return nonstd::make_unexpected(
"stride_bytes must be non-zero.");
}
if ((src.size() % stride_bytes) != 0) {
return nonstd::make_unexpected(fmt::format(
"src size {} must be the multiple of stride_bytes {}", src.size(), stride_bytes));
}
const size_t num_vertices = src.size() / stride_bytes;
std::vector<uint8_t> buf;
buf.resize(stride_bytes);
size_t faceVertexIndexOffset{0};
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
for (size_t k = 0; k < cnt; k++) {
size_t fv_idx = k + faceVertexIndexOffset;
if (fv_idx >= faceVertexIndices.size()) {
return nonstd::make_unexpected(fmt::format(
"faeVertexIndex {} out-of-range at faceVertexCount[{}]", fv_idx, i));
}
size_t v_idx = faceVertexIndices[fv_idx];
if (v_idx >= num_vertices) {
return nonstd::make_unexpected(
fmt::format("faeVertexIndices[{}] {} exceeds the number of vertices {}",
fv_idx, v_idx, num_vertices));
}
memcpy(buf.data(), src.data() + v_idx * stride_bytes, stride_bytes);
dst.insert(dst.end(), buf.begin(), buf.end());
}
faceVertexIndexOffset += cnt;
}
return dst;
}
#if 0 // unused a.t.m
// Copy single value to facevarying vertices.
template <typename T>
static nonstd::expected<std::vector<T>, std::string> ConstantToFaceVarying(
const T &input, const std::vector<uint32_t> &faceVertexCounts) {
std::vector<T> dst;
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
for (size_t k = 0; k < cnt; k++) {
dst.emplace_back(input);
}
}
return dst;
}
#endif
static nonstd::expected<std::vector<uint8_t>, std::string> ConstantToFaceVarying(
const std::vector<uint8_t> &src,
const size_t stride_bytes,
const std::vector<uint32_t> &faceVertexCounts) {
std::vector<uint8_t> dst;
if (src.empty()) {
return nonstd::make_unexpected(
"src data is empty.");
}
if (stride_bytes == 0) {
return nonstd::make_unexpected(
"stride_bytes must be non-zero.");
}
if ((src.size() != stride_bytes)) {
return nonstd::make_unexpected(fmt::format(
"src size {} must be equal to stride_bytes {}", src.size(), stride_bytes));
}
std::vector<uint8_t> buf;
buf.resize(stride_bytes);
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
size_t cnt = faceVertexCounts[i];
for (size_t k = 0; k < cnt; k++) {
dst.insert(dst.end(), buf.begin(), buf.end());
}
}
return dst;
}
//
// name does not include "primvars:" prefix.
// TODO: timeSamples, connected attribute.
//
nonstd::expected<VertexAttribute, std::string> GetTextureCoordinate(
const Stage &state, const GeomMesh &mesh, const std::string &name) {
VertexAttribute vattr;
(void)state;
GeomPrimvar primvar;
if (!mesh.get_primvar(name, &primvar)) {
return nonstd::make_unexpected(fmt::format("No primvars:{}\n", name));
}
if (!primvar.has_value()) {
return nonstd::make_unexpected("No value exist for primvars:" + name +
"\n");
}
if (primvar.get_type_id() !=
value::TypeTraits<std::vector<value::texcoord2f>>::type_id()) {
return nonstd::make_unexpected(
"Texture coordinate primvar must be texCoord2f[] type, but got " +
primvar.get_type_name() + "\n");
}
if (primvar.get_interpolation() == Interpolation::Varying) {
vattr.variability = VertexVariability::Varying;
} else if (primvar.get_interpolation() == Interpolation::Constant) {
vattr.variability = VertexVariability::Constant;
} else if (primvar.get_interpolation() == Interpolation::Uniform) {
vattr.variability = VertexVariability::Uniform;
} else if (primvar.get_interpolation() == Interpolation::Vertex) {
vattr.variability = VertexVariability::Vertex;
} else if (primvar.get_interpolation() == Interpolation::FaceVarying) {
vattr.variability = VertexVariability::FaceVarying;
}
std::vector<value::texcoord2f> uvs;
if (!primvar.flatten_with_indices(&uvs)) {
return nonstd::make_unexpected(
"Failed to retrieve texture coordinate primvar with concrete type.\n");
}
vattr.format = VertexAttributeFormat::Vec2;
vattr.data.resize(uvs.size() * sizeof(value::texcoord2f));
memcpy(vattr.data.data(), uvs.data(), vattr.data.size());
vattr.indices.clear(); // just in case.
return std::move(vattr);
}
#if 0 // not used at the moment.
///
/// For GeomSubset. Build offset table to corresponding array index in
/// mesh.faceVertexIndices. No need to use this function for triangulated mesh,
/// since the index can be easily computed as `3 * subset.indices[i]`
///
bool BuildFaceVertexIndexOffsets(const std::vector<uint32_t> &faceVertexCounts,
std::vector<size_t> &faceVertexIndexOffsets) {
size_t offset = 0;
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
uint32_t npolys = faceVertexCounts[i];
faceVertexIndexOffsets.push_back(offset);
offset += npolys;
}
return true;
}
#endif
#if 0 // unused a.t.m.
bool ToVertexAttributeData(const GeomPrimvar &primvar, VertexAttribute *dst, std::string *err)
{
size_t elementSize = primvar.get_elementSize();
if (elementSize == 0) {
SET_ERROR_AND_RETURN(fmt::format("elementSize is zero for primvar: {}", primvar.name()));
}
VertexAttribute vattr;
const tinyusdz::Attribute &attr = primvar.get_attribute();
#define TO_TYPED_VALUE(__ty, __va_ty) \
if (attr.type_id() == value::TypeTraits<__ty>::type_id()) { \
if (sizeof(__ty) != VertexAttributeFormatSize(__va_ty)) { \
SET_ERROR_AND_RETURN("Internal error. type size mismatch.\n"); \
} \
__ty value; \
if (!primvar.get_value(&value, err)) { \
return false; \
} \
vattr.format = __va_ty; \
} else if (attr.type_id() == (value::TypeTraits<__ty>::type_id() & value::TYPE_ID_1D_ARRAY_BIT)) { \
std::vector<__ty> flattened; \
if (!primvar.flatten_with_indices(&flattened, err)) { \
return false; \
} \
} else
TO_TYPED_VALUE(int, VertexAttributeFormat::Int)
{
SET_ERROR_AND_RETURN(fmt::format("Unknown or unsupported data type for Geom PrimVar: {}", attr.type_name()));
}
#undef TO_TYPED_VALUE
if (primvar.get_interpolation() == Interpolation::Varying) {
vattr.variability = VertexVariability::Varying;
} else if (primvar.get_interpolation() == Interpolation::Constant) {
vattr.variability = VertexVariability::Constant;
} else if (primvar.get_interpolation() == Interpolation::Uniform) {
vattr.variability = VertexVariability::Uniform;
} else if (primvar.get_interpolation() == Interpolation::Vertex) {
vattr.variability = VertexVariability::Vertex;
} else if (primvar.get_interpolation() == Interpolation::FaceVarying) {
vattr.variability = VertexVariability::FaceVarying;
}
// TODO
vattr.indices.clear(); // just in case.
(*dst) = std::move(vattr);
return false;
}
#endif
#if 0 // TODO: Remove
///
/// Triangulate Geom primvar.
///
/// triangulatted indices are computed in `TriangulatePolygon` API.
///
/// @param[in] mesh Geom mesh
/// @param[in] name Geom Primvar name.
/// @param[in] triangulatedFaceVertexIndices Triangulated faceVertexIndices(len
/// = 3 * triangles)
/// @param[in] triangulatedToOrigFaceVertexIndexMap Triangulated faceVertexIndex
/// to original faceVertexIndex remapping table. len = 3 * triangles.
///
nonstd::expected<VertexAttribute, std::string> TriangulateGeomPrimvar(
const GeomMesh &mesh, const std::string &name,
const std::vector<uint32_t> &faceVertexCounts,
const std::vector<uint32_t> &faceVertexIndices,
const std::vector<uint32_t> &triangulatedFaceVertexIndices,
const std::vector<size_t> &triangulatedToOrigFaceVertexIndexMap) {
GeomPrimvar primvar;
if (triangulatedFaceVertexIndices.size() % 3 != 0) {
return nonstd::make_unexpected(fmt::format(
"triangulatedFaceVertexIndices.size {} must be the multiple of 3.\n",
triangulatedFaceVertexIndices.size()));
}
if (!mesh.get_primvar(name, &primvar)) {
return nonstd::make_unexpected(
fmt::format("No primvars:{} found in GeomMesh {}\n", name, mesh.name));
}
if (!primvar.has_value()) {
// TODO: Create empty VertexAttribute?
return nonstd::make_unexpected(
fmt::format("No value exist for primvars:{}\n", name));
}
//
// Flatten Indexed PrimVar(return raw primvar for non-Indexed PrimVar)
//
std::string err;
value::Value flattened;
if (!primvar.flatten_with_indices(&flattened, &err)) {
return nonstd::make_unexpected(fmt::format(
"Failed to flatten Indexed PrimVar: {}. Error = {}\n", name, err));
}
VertexAttribute vattr;
if (!ToVertexAttributeData(primvar, &vattr, &err)) {
return nonstd::make_unexpected(fmt::format(
"Failed to convert Geom PrimVar to VertexAttribute for {}. Error = {}\n", name, err));
}
return vattr;
}
#endif
///
/// Input: points, faceVertexCounts, faceVertexIndices
/// Output: triangulated faceVertexCounts(all filled with 3), triangulated
/// faceVertexIndices, triangulatedToOrigFaceVertexIndexMap (length =
/// triangulated faceVertexIndices. triangulatedToOrigFaceVertexIndexMap[i]
/// stores array index in original faceVertexIndices. For remapping primvar
/// attributes.)
///
/// Return false when a polygon is degenerated.
/// No overlap check at the moment
///
/// T = value::float3 or value::double3
/// BaseTy = float or double
template <typename T, typename BaseTy>
bool TriangulatePolygon(
const std::vector<T> &points, const std::vector<uint32_t> &faceVertexCounts,
const std::vector<uint32_t> &faceVertexIndices,
std::vector<uint32_t> &triangulatedFaceVertexCounts,
std::vector<uint32_t> &triangulatedFaceVertexIndices,
std::vector<size_t> &triangulatedToOrigFaceVertexIndexMap,
std::string &err) {
triangulatedFaceVertexCounts.clear();
triangulatedFaceVertexIndices.clear();
triangulatedToOrigFaceVertexIndexMap.clear();
size_t faceIndexOffset = 0;
// For each polygon(face)
for (size_t i = 0; i < faceVertexCounts.size(); i++) {
uint32_t npolys = faceVertexCounts[i];
if (npolys < 3) {
err = fmt::format(
"faceVertex count must be 3(triangle) or "
"more(polygon), but got faceVertexCounts[{}] = {}\n",
i, npolys);
return false;
}
if (faceIndexOffset + npolys > faceVertexIndices.size()) {
err = fmt::format(
"Invalid faceVertexIndices or faceVertexCounts. faceVertex index "
"exceeds faceVertexIndices.size() at [{}]\n",
i);
return false;
}
if (npolys == 3) {
// No need for triangulation.
triangulatedFaceVertexCounts.push_back(3);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 0]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 1]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 2]);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 0);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 1);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 2);
#if 1
} else if (npolys == 4) {
// Use simple split
// TODO: Split at shortest edge for better triangulation.
triangulatedFaceVertexCounts.push_back(3);
triangulatedFaceVertexCounts.push_back(3);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 0]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 1]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 2]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 0]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 2]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + 3]);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 0);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 1);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 2);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 0);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 2);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset + 3);
#endif
} else {
// Find the normal axis of the polygon using Newell's method
T n = {BaseTy(0), BaseTy(0), BaseTy(0)};
size_t vi0;
size_t vi0_2;
for (size_t k = 0; k < npolys; ++k) {
vi0 = faceVertexIndices[faceIndexOffset + k];
size_t j = (k + 1) % npolys;
vi0_2 = faceVertexIndices[faceIndexOffset + j];
if (vi0 >= points.size()) {
err = fmt::format("Invalid vertex index.\n");
return false;
}
if (vi0_2 >= points.size()) {
err = fmt::format("Invalid vertex index.\n");
return false;
}
T v0 = points[vi0];
T v1 = points[vi0_2];
const T point1 = {v0[0], v0[1], v0[2]};
const T point2 = {v1[0], v1[1], v1[2]};
T a = {point1[0] - point2[0], point1[1] - point2[1],
point1[2] - point2[2]};
T b = {point1[0] + point2[0], point1[1] + point2[1],
point1[2] + point2[2]};
n[0] += (a[1] * b[2]);
n[1] += (a[2] * b[0]);
n[2] += (a[0] * b[1]);
}
BaseTy length_n = vlength(n);
// Check if zero length normal
if (std::fabs(length_n) < std::numeric_limits<BaseTy>::epsilon()) {
err = "Degenerated polygon found.\n";
return false;
}
// Negative is to flip the normal to the correct direction
n = vnormalize(n);
T axis_w, axis_v, axis_u;
axis_w = n;
T a;
if (std::fabs(axis_w[0]) > BaseTy(0.9999999)) { // TODO: use 1.0 - eps?
a = {BaseTy(0), BaseTy(1), BaseTy(0)};
} else {
a = {BaseTy(1), BaseTy(0), BaseTy(0)};
}
axis_v = vnormalize(vcross(axis_w, a));
axis_u = vcross(axis_w, axis_v);
using Point3D = std::array<BaseTy, 3>;
using Point2D = std::array<BaseTy, 2>;
std::vector<Point2D> polyline;
// TMW change: Find best normal and project v0x and v0y to those
// coordinates, instead of picking a plane aligned with an axis (which
// can flip polygons).
// Fill polygon data.
for (size_t k = 0; k < npolys; k++) {
size_t vidx = faceVertexIndices[faceIndexOffset + k];
value::float3 v = points[vidx];
// Point3 polypoint = {v0[0],v0[1],v0[2]};
// world to local
Point3D loc = {vdot(v, axis_u), vdot(v, axis_v), vdot(v, axis_w)};
polyline.push_back({loc[0], loc[1]});
}
std::vector<std::vector<Point2D>> polygon_2d;
// Single polygon only(no holes)
std::vector<uint32_t> indices = mapbox::earcut<uint32_t>(polygon_2d);
// => result = 3 * faces, clockwise
if ((indices.size() % 3) != 0) {
// This should not be happen, though.
err = "Failed to triangulate.\n";
return false;
}
size_t ntris = indices.size() / 3;
for (size_t k = 0; k < ntris; k++) {
triangulatedFaceVertexCounts.push_back(3);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + indices[3 * k + 0]]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + indices[3 * k + 1]]);
triangulatedFaceVertexIndices.push_back(
faceVertexIndices[faceIndexOffset + indices[3 * k + 2]]);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset +
indices[3 * k + 0]);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset +
indices[3 * k + 1]);
triangulatedToOrigFaceVertexIndexMap.push_back(faceIndexOffset +
indices[3 * k + 2]);
}
}
faceIndexOffset += npolys;
}
return true;
}
#if 0
//
// `Shader` may be nested, so first list up all Shader nodes under Material.
//
struct ShaderNode
{
std::name
};
nonstd::optional<UsdPrimvarReader_float2> FindPrimvarReader_float2Rec(
const Prim &root,
RenderMesh &mesh)
{
if (auto sv = root.data.as<Shader>()) {
const Shader &shader = (*sv);
if (auto pv = shader.value.as<UsdUVTexture>()) {
const UsdUVTexture &tex = (*pv);
(void)tex;
}
}
for (const auto &child : root.children) {
auto ret = ListUpShaderGraphRec(child, mesh);
if (!ret) {
return nonstd::make_unexpected(ret.error());
}
}
return true;
}
#endif
#if 0 // not used a.t.m.
// Building an Orthonormal Basis, Revisited
// http://jcgt.org/published/0006/01/01/
static void GenerateBasis(const vec3 &n, vec3 *tangent,
vec3 *binormal)
{
if (n[2] < 0.0f) {
const float a = 1.0f / (1.0f - n[2]);
const float b = n[0] * n[1] * a;
(*tangent) = vec3{1.0f - n[0] * n[0] * a, -b, n[0]};
(*binormal) = vec3{b, n[1] * n[1] * a - 1.0f, -n[1]};
} else {
const float a = 1.0f / (1.0f + n[2]);
const float b = -n[0] * n[1] * a;
(*tangent) = vec3{1.0f - n[0] * n[0] * a, b, -n[0]};
(*binormal) = vec3{b, 1.0f - n[1] * n[1] * a, -n[1]};
}
}
///
/// Compute facevarying tangent and facevarying binormal.
///
/// Reference:
/// http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-13-normal-mapping
///
/// Implemented code uses two adjacent edge composed from three vertices v_{i}, v_{i+1}, v_{i+2} for i < (N - 1)
/// , where N is the number of vertices per facet.
///
/// This may produce unwanted tangent/binormal frame for ill-defined polygon(quad, pentagon, ...).
/// Also, we assume input mesh has well-formed and has no or few vertices with similar property(position, uvs and normals)
///
/// TODO:
/// - [ ] Implement getSimilarVertexIndex in the above opengl-tutorial to better average tangent/binormal.
/// - https://github.com/huamulan/OpenGL-tutorial/blob/master/common/vboindexer.cpp uses simple linear-search,
/// - so could become quite slow when the input mesh has large number of vertices.
/// - Use kNN search(e.g. nanoflann https://github.com/jlblancoc/nanoflann ), or point-query by building BVH over the mesh points.
/// - BVH builder candidate:
/// - NanoRT https://github.com/lighttransport/nanort
/// - bvh https://github.com/madmann91/bvh
/// - Or we can quantize vertex attributes and compute locally sensitive hashsing? https://dl.acm.org/doi/10.1145/3188745.3188846
/// - [ ] Implement more robust tangent/binormal frame computation algorithm for arbitrary mesh?
///
///
static bool ComputeTangentsAndBinormals(
const std::vector<vec3> &vertices,
const std::vector<uint32_t> &faceVertexCounts,
const std::vector<uint32_t> &faceVertexIndices,
const std::vector<vec2> &facevarying_texcoords,
const std::vector<vec3> &facevarying_normals,
std::vector<vec3> *facevarying_tangents,
std::vector<vec3> *facevarying_binormals,
std::string *err) {
if (vertices.empty()) {
SET_ERROR_AND_RETURN("vertices is empty.");
}
// At least 1 triangle face should exist.
if (faceVertexIndices.size() < 9) {
SET_ERROR_AND_RETURN("faceVertexIndices.size < 9");
}
if (facevarying_texcoords.empty()) {
SET_ERROR_AND_RETURN("facevarying_texcoords is empty");
}
if (facevarying_normals.empty()) {
SET_ERROR_AND_RETURN("facevarying_normals is empty");
}
std::vector<value::normal3f> tn(vertices.size());
memset(&tn.at(0), 0, sizeof(value::normal3f) * tn.size());
std::vector<value::normal3f> bn(vertices.size());
memset(&bn.at(0), 0, sizeof(value::normal3f) * bn.size());
bool hasFaceVertexCounts{true};
size_t num_faces = faceVertexCounts.size();
if (num_faces == 0) {
// Assume all triangle faces.
if ((faceVertexIndices.size() % 3) != 0) {
SET_ERROR_AND_RETURN("Invalid faceVertexIndices. It must be all triangles: faceVertexIndices.size % 3 == 0");
}
num_faces = faceVertexIndices.size() / 3;
hasFaceVertexCounts = false;
}
//
// 1. Compute tangent/binormal for each faceVertex.
//
size_t faceVertexIndexOffset{0};
for (size_t i = 0; i < num_faces; i++) {
size_t nv = hasFaceVertexCounts ? faceVertexCounts[i] : 3;
if ((faceVertexIndexOffset + nv) >= faceVertexIndices.size()) {
// Invalid faceVertexIndices
SET_ERROR_AND_RETURN("Invalid value in faceVertexOffset.");
}
if (nv < 3) {
SET_ERROR_AND_RETURN("Degenerated facet found.");
}
// Process each two-edges per facet.
//
// Example:
//
// fv3
// o----------------o fv2
// \ /
// \ /
// o----------o
// fv0 fv1
// facet0: fv0, fv1, fv2
// facet1: fv1, fv2, fv3
for (size_t f = 0; f < nv - 2; f++) {
size_t fid0 = f;
size_t fid1 = f+1;
size_t fid2 = f+2;
uint32_t vf0 = faceVertexIndices[fid0];
uint32_t vf1 = faceVertexIndices[fid1];
uint32_t vf2 = faceVertexIndices[fid2];
if ((vf0 >= vertices.size()) ||
(vf1 >= vertices.size()) ||
(vf2 >= vertices.size()) ) {
// index out-of-range
SET_ERROR_AND_RETURN("Invalid value in faceVertexIndices. some exceeds vertices.size()");
}
vec3 v1 = vertices[vf0];
vec3 v2 = vertices[vf1];
vec3 v3 = vertices[vf2];
float v1x = v1[0];
float v1y = v1[1];
float v1z = v1[2];
float v2x = v2[0];
float v2y = v2[1];
float v2z = v2[2];
float v3x = v3[0];
float v3y = v3[1];
float v3z = v3[2];
float w1x = 0.0f;
float w1y = 0.0f;
float w2x = 0.0f;
float w2y = 0.0f;
float w3x = 0.0f;
float w3y = 0.0f;
if ((fid0 >= facevarying_texcoords.size()) ||
(fid1 >= facevarying_texcoords.size()) ||
(fid2 >= facevarying_texcoords.size()) ) {
// index out-of-range
SET_ERROR_AND_RETURN("Invalid value in faceVertexCounts. some exceeds facevarying_texcoords.size()");
}
{
vec2 uv1 = facevarying_texcoords[fid0];
vec2 uv2 = facevarying_texcoords[fid1];
vec2 uv3 = facevarying_texcoords[fid2];
w1x = uv1[0];
w1y = uv1[1];
w2x = uv2[0];
w2y = uv2[1];
w3x = uv3[0];
w3y = uv3[1];
}
float x1 = v2x - v1x;
float x2 = v3x - v1x;
float y1 = v2y - v1y;
float y2 = v3y - v1y;
float z1 = v2z - v1z;
float z2 = v3z - v1z;
float s1 = w2x - w1x;
float s2 = w3x - w1x;
float t1 = w2y - w1y;
float t2 = w3y - w1y;
float r = 1.0;
if (std::fabs(double(s1 * t2 - s2 * t1)) > 1.0e-20) {
r /= (s1 * t2 - s2 * t1);
}
vec3 tdir{(t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r};
vec3 bdir{(s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r};
tn[vf0][0] += tdir[0];
tn[vf0][1] += tdir[1];
tn[vf0][2] += tdir[2];
tn[vf1][0] += tdir[0];
tn[vf1][1] += tdir[1];
tn[vf1][2] += tdir[2];
tn[vf2][0] += tdir[0];
tn[vf2][1] += tdir[1];
tn[vf2][2] += tdir[2];
bn[vf0][0] += bdir[0];
bn[vf0][1] += bdir[1];
bn[vf0][2] += bdir[2];
bn[vf1][0] += bdir[0];
bn[vf1][1] += bdir[1];
bn[vf1][2] += bdir[2];
bn[vf2][0] += bdir[0];
bn[vf2][1] += bdir[1];
bn[vf2][2] += bdir[2];
}
faceVertexIndexOffset += nv;
}
//
// 2. normalize * orthogonalize;
//
facevarying_tangents->resize(facevarying_normals.size());
facevarying_binormals->resize(facevarying_normals.size());
faceVertexIndexOffset = 0;
for (size_t i = 0; i < num_faces; i++) {
size_t nv = hasFaceVertexCounts ? faceVertexCounts[i] : 3;
for (size_t f = 0; f < nv - 2; f++) {
uint32_t vf[3];
vf[0] = faceVertexIndices[faceVertexIndexOffset + f];
vf[1] = faceVertexIndices[faceVertexIndexOffset + f + 1];
vf[2] = faceVertexIndices[faceVertexIndexOffset + f + 2];
value::normal3f n[3];
// http://www.terathon.com/code/tangent.html
{
n[0][0] = facevarying_normals[faceVertexIndexOffset + f + 0][0];