-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathgltfExport.cpp
More file actions
2254 lines (2052 loc) · 98 KB
/
gltfExport.cpp
File metadata and controls
2254 lines (2052 loc) · 98 KB
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
/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
#include "gltfExport.h"
#include "debugCodes.h"
#include "gltfAnisotropy.h"
#include <fileformatutils/common.h>
#include <fileformatutils/geometry.h>
#include <fileformatutils/images.h>
#include <fileformatutils/neuralAssetsHelper.h>
#include <pxr/base/tf/token.h>
#include <pxr/usd/ar/asset.h>
#include <pxr/usd/ar/defaultResolver.h>
#include <pxr/usd/ar/resolverContextBinder.h>
#include <pxr/usd/kind/registry.h>
#include <pxr/usd/pcp/cache.h>
#include <pxr/usd/sdf/assetPath.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/sdf/payload.h>
#include <pxr/usd/sdf/reference.h>
#include <pxr/usd/sdf/types.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usd/payloads.h>
#include <pxr/usd/usd/primCompositionQuery.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/references.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usd/schemaRegistry.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/typed.h>
#include <pxr/usd/usd/zipFile.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usd/usdGeom/primvarsAPI.h>
#include <pxr/usd/usdGeom/tokens.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/xformCommonAPI.h>
#include <pxr/usd/usdGeom/xformable.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/materialBindingAPI.h>
#include <pxr/usd/usdShade/output.h>
#include <pxr/usd/usdShade/tokens.h>
#include <pxr/usd/usdSkel/animation.h>
#include <pxr/usd/usdSkel/bindingAPI.h>
#include <pxr/usd/usdSkel/cache.h>
#include <pxr/usd/usdSkel/root.h>
#include <pxr/usd/usdSkel/skeleton.h>
#include <pxr/usd/usdSkel/skeletonQuery.h>
#include <pxr/usd/usdSkel/utils.h>
// TODO refine this description
/**
* Export usd to gltf.
*
* Scene settings:
* glTF always has upAxis = +y and units are in meters, and there is no specific property to change
* that, in contrast to USD's upAxis and metersPerUnit tokens. So we instead add a correction node
* at the root of the glTF node hierarchy to adjust for that.
*
* Materials:
* Cameras:
* Meshes:
*
*
*
*
*
*
*/
using namespace PXR_NS;
namespace adobe::usd {
void
addExtension(ExportGltfContext& ctx,
tinygltf::ExtensionMap& extensionMap,
const std::string& extensionName,
const ExtMap& ext,
bool addToRequired = false)
{
extensionMap[extensionName] = tinygltf::Value(ext);
ctx.extensionsUsed.insert(extensionName);
if (addToRequired) {
ctx.extensionsRequired.insert(extensionName);
}
}
void
exportAnimationTracks(ExportGltfContext& ctx)
{
if (ctx.usd->hasAnimations) {
ctx.gltf->animations.resize(ctx.usd->animationTracks.size());
for (int animationTrackIndex = 0; animationTrackIndex < ctx.usd->animationTracks.size();
animationTrackIndex++) {
const AnimationTrack& track = ctx.usd->animationTracks[animationTrackIndex];
ctx.gltf->animations[animationTrackIndex].name = getNodeName(track);
}
}
}
void
exportMetadata(ExportGltfContext& ctx)
{
std::set<std::string> ignoredProperties = { "filenames", "hasAdobeProperties" };
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "glTF::write metadata: {\n");
std::map<std::string, tinygltf::Value> extras;
for (auto it = ctx.usd->metadata.begin(); it != ctx.usd->metadata.end(); it++) {
if (ignoredProperties.find(it->first) != ignoredProperties.end()) {
continue;
}
TF_DEBUG_MSG(FILE_FORMAT_GLTF, " %s: ", it->first.c_str());
if (it->second.IsHolding<bool>()) {
bool x = it->second.UncheckedGet<bool>();
extras[it->first] = tinygltf::Value(x);
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "%s\n", x ? "true" : "false");
} else if (it->second.IsHolding<int>()) {
int x = it->second.UncheckedGet<int>();
extras[it->first] = tinygltf::Value(x);
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "%s\n", std::to_string(x).c_str());
} else if (it->second.IsHolding<float>()) {
float x = it->second.UncheckedGet<float>();
extras[it->first] = tinygltf::Value(x);
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "%s\n", std::to_string(x).c_str());
} else if (it->second.IsHolding<std::string>()) {
const std::string& x = it->second.UncheckedGet<std::string>();
extras[it->first] = tinygltf::Value(x);
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "%s\n", x.c_str());
} else {
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "unsupported type not exported");
}
}
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "}\n");
ctx.gltf->asset.extras = tinygltf::Value(extras);
}
// Returns the index of the offset node, otherwise -1
int
exportOffsetNode(tinygltf::Model& model, TfToken upAxis, float metersPerUnit)
{
if (upAxis == UsdGeomTokens->z || (metersPerUnit != 1 && metersPerUnit > 0)) {
int nodeIndex = model.nodes.size();
model.nodes.push_back(tinygltf::Node());
tinygltf::Node& node = model.nodes[nodeIndex];
node.name = "correctionNode";
if (upAxis == UsdGeomTokens->z) {
node.rotation = { -0.7071068, 0, 0, 0.7071068 }; // rotate -90 deg in x
}
// If metersPerUnit is not initialized (ie. equals 0), we don't want to apply
// a scale factor
if (metersPerUnit != 1 && metersPerUnit > 0) {
float scale = metersPerUnit;
node.scale = std::vector<double>{ scale, scale, scale };
}
TF_DEBUG_MSG(FILE_FORMAT_GLTF,
"gltf::write node { %s, rotX: %s, metersPerUnit: %f }\n",
node.name.c_str(),
upAxis == UsdGeomTokens->z ? "-90deg" : "0deg",
metersPerUnit);
return nodeIndex;
}
return -1;
}
bool
nodeContainsNgp(ExportGltfContext& ctx, std::int32_t index)
{
const Node& n = ctx.usd->nodes[index];
if (n.ngp >= 0)
return true;
for (std::int32_t childIndex : n.children) {
if (nodeContainsNgp(ctx, childIndex))
return true;
}
return false;
}
int
exportCamera(ExportGltfContext& ctx, int camera)
{
const Camera& usdCamera = ctx.usd->cameras[camera];
int cameraIndex = ctx.gltf->cameras.size();
ctx.gltf->cameras.push_back(tinygltf::Camera());
tinygltf::Camera& gCamera = ctx.gltf->cameras[cameraIndex];
gCamera.name = getNodeName(usdCamera);
const GfCamera& uCamera = usdCamera.camera;
float znear = usdCamera.nearZ;
float zfar = usdCamera.farZ;
if (usdCamera.projection == GfCamera::Projection::Perspective) {
gCamera.type = "perspective";
gCamera.perspective.znear = znear;
gCamera.perspective.zfar = zfar;
gCamera.perspective.aspectRatio = usdCamera.horizontalAperture / usdCamera.verticalAperture;
gCamera.perspective.yfov = uCamera.GetFieldOfView(GfCamera::FOVVertical) * deg2rad;
} else {
gCamera.type = "orthographic";
gCamera.orthographic.xmag = usdCamera.horizontalAperture * GfCamera::APERTURE_UNIT;
gCamera.orthographic.ymag = usdCamera.verticalAperture * GfCamera::APERTURE_UNIT;
gCamera.orthographic.znear = znear;
gCamera.orthographic.zfar = zfar;
}
return cameraIndex;
}
bool
exportLightExtension(ExportGltfContext& ctx, int lightIndex, ExtMap& extensions)
{
extensions["light"] = tinygltf::Value(lightIndex);
return true;
}
bool
exportLights(ExportGltfContext& ctx)
{
ctx.gltf->lights.resize(ctx.usd->lights.size());
for (size_t i = 0; i < ctx.usd->lights.size(); ++i) {
const Light& light = ctx.usd->lights[i];
tinygltf::Light& gltfLight = ctx.gltf->lights[i];
float radius = light.radius;
GfVec2f length = light.length;
// Modify light values if the incoming USD values are in different units
if (ctx.usd->metersPerUnit > 0) {
if (radius > 0) {
radius *= ctx.usd->metersPerUnit;
}
if (length[0] > 0) {
length[0] *= ctx.usd->metersPerUnit;
}
if (length[1] > 0) {
length[1] *= ctx.usd->metersPerUnit;
}
}
// glTF doesn't use lights that emit based on their surface area, so will multiply the
// intensity below based on the light type
float intensity = light.intensity;
switch (light.type) {
case LightType::Disk: {
gltfLight.type = "spot";
// glTF inner cone angle is from the center to where falloff begins, and outer cone
// angle is from the center to where falloff ends. Meanwhile, in USD, angle is from
// the center to the edge of the cone, and softness is a number from 0 to 1
// indicating how close to the center the falloff begins.
// glTF outer cone angle is equivalent to USD cone angle
gltfLight.spot.outerConeAngle = GfDegreesToRadians(light.coneAngle);
// Use the fraction of the cone containing the falloff to calculate the inner cone
gltfLight.spot.innerConeAngle =
(1 - ctx.usd->lights[i].coneFalloff) * gltfLight.spot.outerConeAngle;
// inner cone angle must always be less than outer cone angle, according to the
// glTF spec. If it isn't, set it to be just less than the outer cone angle
const float epsilon = 1e-6;
if (gltfLight.spot.innerConeAngle >= gltfLight.spot.outerConeAngle &&
gltfLight.spot.outerConeAngle >= epsilon) {
gltfLight.spot.innerConeAngle = gltfLight.spot.outerConeAngle - epsilon;
}
if (radius > 0) { // Disk light, area = pi r^2
intensity *= (M_PI * radius * radius);
}
intensity *= GLTF_SPOT_LIGHT_INTENSITY_MULT;
break;
}
case LightType::Sun:
gltfLight.type = "directional";
intensity *= GLTF_DIRECTIONAL_LIGHT_INTENSITY_MULT;
break;
default:
// All other light types are encoded as point lights, since gltf supports fewer
// light types
gltfLight.type = "point";
if (radius > 0) { // Sphere light, area = 4 pi r^2
intensity *= (4.0 * M_PI * radius * radius);
} else if (length[0] > 0 && length[1] > 0) { // Rectangle light, area = l * w
intensity *= (length[0] * length[1]);
}
intensity *= GLTF_POINT_LIGHT_INTENSITY_MULT;
// TODO: Address environment lights separately
break;
}
gltfLight.name = getNodeName(light);
gltfLight.intensity = intensity;
gltfLight.color.resize(3);
gltfLight.color[0] = light.color[0];
gltfLight.color[1] = light.color[1];
gltfLight.color[2] = light.color[2];
}
return true;
}
void
exportNgpExtension(ExportGltfContext& ctx,
int ngpIndex,
tinygltf::Value::Object& gngpObj,
std::vector<double>& restTransform)
{
// Refer to README_NGP.md for documentation.
auto exportUncompressedFloatArray = [&gngpObj](const char* name,
const PXR_NS::VtFloatArray& src,
std::size_t d1 = 0,
std::size_t d2 = 0) {
std::string b64Str;
if (d1 == 0 || d2 == 0) {
packBase64String(reinterpret_cast<const uint8_t*>(src.data()),
src.size() * sizeof(float),
false,
b64Str);
} else {
std::vector<uint8_t> data(src.size() * sizeof(float));
packMLPWeight(src.data(), reinterpret_cast<float*>(data.data()), d1, d2);
packBase64String(data.data(), data.size(), false, b64Str);
}
gngpObj[name] = tinygltf::Value(b64Str);
tinygltf::Value::Array shapeArray = { tinygltf::Value(static_cast<int>(src.size())) };
gngpObj[std::string(name) + "_shape"] = tinygltf::Value(shapeArray);
};
const NgpData& ngpData = ctx.usd->ngps[ngpIndex];
// The numbers below indicate the shapes of the multilayer perceptron (MLP).
exportUncompressedFloatArray("spatial_mlp_l0_weight", ngpData.densityMlpLayer0Weight, 24, 32);
exportUncompressedFloatArray("spatial_mlp_l0_bias", ngpData.densityMlpLayer0Bias);
exportUncompressedFloatArray("spatial_mlp_l1_weight", ngpData.densityMlpLayer1Weight, 16, 24);
exportUncompressedFloatArray("spatial_mlp_l1_bias", ngpData.densityMlpLayer1Bias);
exportUncompressedFloatArray("vdep_mlp_l0_weight", ngpData.colorMlpLayer0Weight, 24, 36);
exportUncompressedFloatArray("vdep_mlp_l0_bias", ngpData.colorMlpLayer0Bias);
exportUncompressedFloatArray("vdep_mlp_l1_weight", ngpData.colorMlpLayer1Weight, 24, 24);
exportUncompressedFloatArray("vdep_mlp_l1_bias", ngpData.colorMlpLayer1Bias);
exportUncompressedFloatArray("vdep_mlp_l2_weight", ngpData.colorMlpLayer2Weight, 4, 24);
exportUncompressedFloatArray("vdep_mlp_l2_bias", ngpData.colorMlpLayer2Bias);
std::vector<uint8_t> bufHashGrid(ngpData.hashGrid.size() * sizeof(std::uint16_t));
float32ToFloat16(ngpData.hashGrid.data(),
reinterpret_cast<std::uint16_t*>(bufHashGrid.data()),
ngpData.hashGrid.size());
std::string b64StrHashGrid;
packBase64String(bufHashGrid.data(), bufHashGrid.size(), true, b64StrHashGrid);
gngpObj["hash_grid"] = tinygltf::Value(b64StrHashGrid);
tinygltf::Value::Array hashGridResArray(ngpData.hashGridResolution.size());
for (size_t i = 0; i < hashGridResArray.size(); ++i) {
hashGridResArray[i] = tinygltf::Value(static_cast<int>(ngpData.hashGridResolution[i]));
}
gngpObj["hash_grid_res"] = tinygltf::Value(hashGridResArray);
// The numbers indicate the shape of the hash grid, meaning there are 8 levels, 524288 entrys
// per level, and 4 channels per value.
tinygltf::Value::Array hashGridShapeArray = { tinygltf::Value(8),
tinygltf::Value(524288),
tinygltf::Value(4) };
gngpObj["hash_grid_shape"] = tinygltf::Value(hashGridShapeArray);
std::vector<std::uint8_t> bufDistanceGrid(ngpData.distanceGrid.size());
float maxDistance = maxOfFloatArray(ngpData.distanceGrid.data(), ngpData.distanceGrid.size());
for (size_t i = 0; i < bufDistanceGrid.size(); ++i) {
bufDistanceGrid[i] = static_cast<std::uint8_t>(
std::clamp(std::sqrt(ngpData.distanceGrid[i] / maxDistance) * 255.0f, 0.0f, 255.0f));
}
std::string b64StrDistanceGrid;
packBase64String(bufDistanceGrid.data(), bufDistanceGrid.size(), true, b64StrDistanceGrid);
gngpObj["distance_grid"] = tinygltf::Value(b64StrDistanceGrid);
gngpObj["distance_max"] = tinygltf::Value(maxDistance);
// The shape of distance grid is hard-coded as 128^3. Refer to README_NGP.md for more details.
tinygltf::Value::Array distanceShapeArray = { tinygltf::Value(128),
tinygltf::Value(128),
tinygltf::Value(128) };
gngpObj["distance_grid_shape"] = tinygltf::Value(distanceShapeArray);
std::vector<std::uint8_t> bufDensityGrid(ngpData.densityGrid.size());
float maxDensity = maxOfFloatArray(ngpData.densityGrid.data(), ngpData.densityGrid.size());
for (size_t i = 0; i < bufDensityGrid.size(); ++i) {
bufDensityGrid[i] = static_cast<std::uint8_t>(
std::clamp(ngpData.densityGrid[i] / maxDensity * 255.0f, 0.0f, 255.0f));
}
std::string b64StrDensityGrid;
packBase64String(bufDensityGrid.data(), bufDensityGrid.size(), true, b64StrDensityGrid);
gngpObj["density"] = tinygltf::Value(b64StrDensityGrid);
gngpObj["density_max"] = tinygltf::Value(maxDensity);
gngpObj["sigma_threshold"] = tinygltf::Value(ngpData.densityThreshold);
// The shape of density grid is hard-coded as 512^3. Refer to README_NGP.md for more details.
tinygltf::Value::Array densityShapeArray = { tinygltf::Value(512),
tinygltf::Value(512),
tinygltf::Value(512) };
gngpObj["density_shape"] = tinygltf::Value(densityShapeArray);
auto transMatrix = GfMatrix4d(GfRotation(GfVec3d(1.0, 0.0, 0.0), 90.0), GfVec3d(0.0, 0.0, 0.0));
if (ngpData.hasTransform) {
transMatrix *= ngpData.transform;
}
auto diffMatrix = transMatrix - GfMatrix4d(1.0);
if (infNormOfFloatArray(diffMatrix.data(), 16) > std::numeric_limits<double>::epsilon()) {
if (restTransform.size()) {
GfMatrix4d totalTransform;
copyMatrix(restTransform, totalTransform);
totalTransform *= transMatrix;
copyMatrix(totalTransform, restTransform);
} else {
copyMatrix(transMatrix, restTransform);
}
}
}
size_t
createGltfMesh(ExportGltfContext& ctx, const Node& node)
{
// If there are multiple usd meshes, we create one gltf mesh but add all the primitives
// of all the usd meshes to the single gltf mesh
size_t meshIndex = ctx.gltf->meshes.size();
ctx.gltf->meshes.push_back(tinygltf::Mesh());
tinygltf::Mesh& gmesh = ctx.gltf->meshes[meshIndex];
for (int usdMeshIndex : node.staticMeshes) {
// Primitives previously written to ctx.primitiveMap
std::vector<tinygltf::Primitive>& primitives = ctx.primitiveMap[usdMeshIndex];
for (size_t j = 0; j < primitives.size(); j++) {
gmesh.primitives.push_back(primitives[j]);
}
}
return meshIndex;
}
void
exportNode(ExportGltfContext& ctx, int usdNodeIndex, int offset)
{
const Node& node = ctx.usd->nodes[usdNodeIndex];
int gltfNodeIndex = ctx.gltf->nodes.size();
ctx.gltf->nodes.push_back(tinygltf::Node());
tinygltf::Node& gnode = ctx.gltf->nodes[gltfNodeIndex];
ctx.usdNodesToGltfNodes[usdNodeIndex] = gltfNodeIndex;
gnode.name = getNodeName(node);
TF_DEBUG_MSG(FILE_FORMAT_GLTF,
"glTF::write node: { %s } path=%s\n",
gnode.name.c_str(),
node.path.c_str());
bool hasAnimation = false;
for (const NodeAnimation& nodeAnimation : node.animations) {
if (!nodeAnimation.translations.times.empty() || !nodeAnimation.rotations.times.empty() ||
!nodeAnimation.scales.times.empty()) {
hasAnimation = true;
break;
}
}
// from the glTF spec: "When a node is targeted for animation (referenced by an
// animation.channel.target), only TRS properties MAY be present; matrix MUST NOT be present."
if (node.hasTransform) {
if (!hasAnimation) {
copyMatrix(node.transform, gnode.matrix);
} else {
// Extract the translation, rotation, and scale values from the USD node and apply them
// to a given glTF node. If the USD node has a transformation matrix, that matrix is
// usually copied directly. But if the node is animated (and not allowed to have a
// transformation matrix per the glTF spec), we must set static transformation values,
// so that when animations aren't playing, nodes are still in the correct orientation.
GfVec3d translation;
GfQuatd rotation;
GfVec3d scale;
// Factor the matrix into components. The matrix u holds rotation information, so that
// must be extracted further below into a normalized quaternion
GfMatrix4d r, u, p;
node.transform.Factor(&r, &scale, &u, &translation, &p);
// TODO: Investigate the "u" matrix further, and stress test to ensure it works with
// non-uniform scaling (which could cause shearing).
rotation = u.ExtractRotationQuat().GetNormalized();
gnode.translation = { translation[0], translation[1], translation[2] };
gnode.rotation = { rotation.GetImaginary()[0],
rotation.GetImaginary()[1],
rotation.GetImaginary()[2],
rotation.GetReal() };
gnode.scale = { scale[0], scale[1], scale[2] };
}
} else {
GfQuatf rotation = node.rotation.GetNormalized();
gnode.translation = { node.translation[0], node.translation[1], node.translation[2] };
gnode.rotation = { rotation.GetImaginary()[0],
rotation.GetImaginary()[1],
rotation.GetImaginary()[2],
rotation.GetReal() };
gnode.scale = { node.scale[0], node.scale[1], node.scale[2] };
}
if (node.camera != -1) {
gnode.camera = exportCamera(ctx, node.camera);
}
if (node.ngp != -1) {
tinygltf::Value::Object nerfExt;
exportNgpExtension(ctx, node.ngp, nerfExt, gnode.matrix);
addExtension(ctx, gnode.extensions, getNerfExtString(), nerfExt, true);
}
if (node.light != -1) {
gnode.light = node.light;
// Add the extension info to the node indicating that it has a light. This ensures that the
// lights extension is properly added as a required extension
tinygltf::Value::Object lightExt;
exportLightExtension(ctx, node.light, lightExt);
addExtension(ctx, gnode.extensions, "KHR_lights_punctual", lightExt, true);
}
if (node.staticMeshes.size()) {
// Skinned meshes are written in exportSkeletons, process only staticMeshes here.
if (node.staticMeshes.size() == 1) {
// If there is only one usd mesh, we can use the same gltf mesh index as an instanced
// mesh. We check if there is an entry in the map of usd mesh index to gltf mesh index.
// If there isn't an entry, we need to create the gltf mesh from the usd mesh.
int usdMeshIndex = node.staticMeshes[0];
auto it = ctx.usdMeshIndexToGltfMeshIndexMap.find(usdMeshIndex);
if (it == ctx.usdMeshIndexToGltfMeshIndexMap.end()) {
size_t meshIndex = createGltfMesh(ctx, node);
gnode.mesh = meshIndex;
// Add a mapping of usd mesh index to gltf mesh index of possible re-use
ctx.usdMeshIndexToGltfMeshIndexMap[usdMeshIndex] = meshIndex;
} else {
// We've already created the gltf mesh for the usd mesh so we can instance the gltf
// mesh
gnode.mesh = it->second;
}
} else {
// When there are multiple static meshes, we combine them into one mesh but this
// is not common so we don't support instancing
gnode.mesh = createGltfMesh(ctx, node);
}
}
if (offset) {
gnode.children.resize(node.children.size());
for (size_t i = 0; i < node.children.size(); i++) {
gnode.children[i] = node.children[i] + offset;
}
} else {
gnode.children = node.children;
}
if (hasAnimation) {
int animationTrackIndex = 0;
for (const NodeAnimation& nodeAnimation : node.animations) {
tinygltf::Animation& animationRef = ctx.gltf->animations[animationTrackIndex];
if (nodeAnimation.translations.times.size()) {
int timeAccessor = addAccessor(ctx.gltf,
"times",
0,
TINYGLTF_TYPE_SCALAR,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.translations.times.size(),
nodeAnimation.translations.times.data(),
true);
int translationAccessor = addAccessor(ctx.gltf,
"translations",
0,
TINYGLTF_TYPE_VEC3,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.translations.values.size(),
nodeAnimation.translations.values.data(),
false);
tinygltf::AnimationSampler sampler;
sampler.input = timeAccessor;
sampler.output = translationAccessor;
sampler.interpolation = "LINEAR";
int samplerIndex = animationRef.samplers.size();
animationRef.samplers.push_back(sampler);
tinygltf::AnimationChannel channel;
channel.sampler = samplerIndex;
channel.target_node = gltfNodeIndex;
channel.target_path = "translation";
animationRef.channels.push_back(channel);
}
if (nodeAnimation.rotations.times.size()) {
int timeAccessor = addAccessor(ctx.gltf,
"times",
0,
TINYGLTF_TYPE_SCALAR,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.rotations.times.size(),
nodeAnimation.rotations.times.data(),
true);
int rotationAccessor = addAccessor(ctx.gltf,
"rotations",
0,
TINYGLTF_TYPE_VEC4,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.rotations.values.size(),
nodeAnimation.rotations.values.data(),
false);
tinygltf::AnimationSampler sampler;
sampler.input = timeAccessor;
sampler.output = rotationAccessor;
sampler.interpolation = "LINEAR";
int samplerIndex = animationRef.samplers.size();
animationRef.samplers.push_back(sampler);
tinygltf::AnimationChannel channel;
channel.sampler = samplerIndex;
channel.target_node = gltfNodeIndex;
channel.target_path = "rotation";
animationRef.channels.push_back(channel);
}
if (nodeAnimation.scales.times.size()) {
int timeAccessor = addAccessor(ctx.gltf,
"times",
0,
TINYGLTF_TYPE_SCALAR,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.scales.times.size(),
nodeAnimation.scales.times.data(),
true);
int scaleAccessor = addAccessor(ctx.gltf,
"scales",
0,
TINYGLTF_TYPE_VEC3,
TINYGLTF_COMPONENT_TYPE_FLOAT,
nodeAnimation.scales.values.size(),
nodeAnimation.scales.values.data(),
false);
tinygltf::AnimationSampler sampler;
sampler.input = timeAccessor;
sampler.output = scaleAccessor;
sampler.interpolation = "LINEAR";
int samplerIndex = animationRef.samplers.size();
animationRef.samplers.push_back(sampler);
tinygltf::AnimationChannel channel;
channel.sampler = samplerIndex;
channel.target_node = gltfNodeIndex;
channel.target_path = "scale";
animationRef.channels.push_back(channel);
}
animationTrackIndex++;
}
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "Animation exported\n");
}
}
// exportNode should be called before exportSkeleton, since exportSkeleton needs the gltf node
// index map that is created in exportNode
void
exportSkeletons(ExportGltfContext& ctx, int gltfRootNodeIndex)
{
const UsdData* usd = ctx.usd;
for (size_t i = 0; i < usd->skeletons.size(); i++) {
const Skeleton& skeleton = usd->skeletons[i];
TF_DEBUG_MSG(FILE_FORMAT_GLTF, "gltf::export skeleton {%s}\n", skeleton.name.c_str());
// Create a root node to hold the skeleton root nodes as there can be more than one
int skelNodeIndex = ctx.gltf->nodes.size();
ctx.gltf->nodes.push_back(tinygltf::Node());
tinygltf::Node& skelNode = ctx.gltf->nodes[skelNodeIndex];
skelNode.name = "Skel" + std::to_string(i);
// If the skeleton had a parent, use that
int usdSkeletonParent = skeleton.parent;
// If not, use the rootNodeIndex as the parent
int gltfSkeletonParent = gltfRootNodeIndex;
if (usdSkeletonParent >= 0) {
// Valid usd skeleton parent, convert to gltf node index
gltfSkeletonParent = ctx.usdNodesToGltfNodes[usdSkeletonParent];
}
if (gltfSkeletonParent < 0) {
// No skeleton parent or root node
ctx.gltf->scenes.back().nodes.push_back(skelNodeIndex);
} else {
ctx.gltf->nodes[gltfSkeletonParent].children.push_back(skelNodeIndex);
}
// Export skeleton transforms
std::vector<float> values;
copyMatrices(skeleton.inverseBindTransforms, values);
int inverseBindMatricessAccessorIndex = addAccessor(ctx.gltf,
"inverseBindMatrices",
0,
TINYGLTF_TYPE_MAT4,
TINYGLTF_COMPONENT_TYPE_FLOAT,
values.size() / 16,
values.data(),
false);
// Export skeleton nodes
std::unordered_map<SdfPath, int, SdfPath::Hash> skeletonNodesMap;
std::vector<int> indices(skeleton.joints.size());
int skelRoot = -1;
int rootCount = 0;
for (size_t j = 0; j < skeleton.joints.size(); j++) {
SdfPath jointPath(skeleton.joints[j]);
int nodeIndex = ctx.gltf->nodes.size();
ctx.gltf->nodes.push_back(tinygltf::Node());
tinygltf::Node& node = ctx.gltf->nodes[nodeIndex];
node.name = jointPath.GetName();
decomposeMatrix(skeleton.restTransforms[j], node);
indices[j] = nodeIndex;
skeletonNodesMap[jointPath] = nodeIndex;
int parent = skeleton.jointParents[j];
if (parent < 0) {
skelRoot = nodeIndex;
++rootCount;
ctx.gltf->nodes[skelNodeIndex].children.push_back(nodeIndex);
}
TF_DEBUG_MSG(FILE_FORMAT_GLTF,
"Adding node path %s (%s) at %d\n",
jointPath.GetText(),
node.name.c_str(),
nodeIndex);
if (parent >= 0) {
SdfPath parentJointPath(skeleton.joints[parent]);
int parentNodeIndex = skeletonNodesMap[parentJointPath];
tinygltf::Node& parentNode = ctx.gltf->nodes[parentNodeIndex];
parentNode.children.push_back(nodeIndex);
TF_DEBUG_MSG(
FILE_FORMAT_GLTF, "Adding node to parent %s\n", parentJointPath.GetText());
}
}
// Export skeleton into a skin object
int skinIndex = ctx.gltf->skins.size();
ctx.gltf->skins.push_back(tinygltf::Skin());
tinygltf::Skin& skin = ctx.gltf->skins[skinIndex];
skin.joints = indices;
skin.inverseBindMatrices = inverseBindMatricessAccessorIndex;
// Only set the skeleton root on the skin if there is one root.
// Otherwise, this is generates a gltf validation warning.
if (rootCount == 1) {
skin.skeleton = skelRoot;
}
// Export target skinned meshes into root nodes (previously cached in ctx.primitiveMap)
// XXX should these form a hierarchy as well?
for (size_t j = 0; j < skeleton.meshSkinningTargets.size(); j++) {
int usdMeshIndex = skeleton.meshSkinningTargets[j];
const std::string& meshName = getNodeName(usd->meshes[usdMeshIndex]);
int nodeIndex = ctx.gltf->nodes.size();
ctx.gltf->nodes.push_back(tinygltf::Node());
tinygltf::Node& node = ctx.gltf->nodes[nodeIndex];
node.name = "skeleton_" + std::to_string(i) + "_" + std::to_string(j) + "_" + meshName;
node.skin = skinIndex;
if (gltfSkeletonParent == -1) {
ctx.gltf->scenes.back().nodes.push_back(nodeIndex);
} else {
ctx.gltf->nodes[gltfSkeletonParent].children.push_back(nodeIndex);
}
std::vector<tinygltf::Primitive>& primitives = ctx.primitiveMap[usdMeshIndex];
if (primitives.size()) {
size_t meshIndex = ctx.gltf->meshes.size();
ctx.gltf->meshes.push_back(tinygltf::Mesh());
tinygltf::Mesh& gmesh = ctx.gltf->meshes[meshIndex];
gmesh.name = meshName;
for (size_t j = 0; j < primitives.size(); j++) {
gmesh.primitives.push_back(primitives[j]);
}
node.mesh = meshIndex;
}
}
// Export skeleton animations
int animationTrackIndex = 0;
for (const SkeletonAnimation& skeletonAnimation : skeleton.skeletonAnimations) {
// We need to convert from timeCodesPerSecond to seconds so be compute the multiplier.
float secondsPerTimeCode =
ctx.usd->timeCodesPerSecond != 0.0 ? 1.0f / ctx.usd->timeCodesPerSecond : 1.0f;
size_t boneCount = skeleton.animatedJoints.size();
size_t animationTimesCount = skeletonAnimation.times.size();
std::vector<float> times(animationTimesCount);
std::vector<std::vector<float>> translations(
boneCount, std::vector<float>(animationTimesCount * 3));
std::vector<std::vector<float>> rotations(boneCount,
std::vector<float>(animationTimesCount * 4));
std::vector<std::vector<float>> scales(boneCount,
std::vector<float>(animationTimesCount * 3));
for (size_t i = 0; i < animationTimesCount; i++) {
times[i] = skeletonAnimation.times[i] * secondsPerTimeCode;
for (size_t j = 0; j < boneCount; j++) {
GfVec3f imaginary = skeletonAnimation.rotations[i][j].GetImaginary();
translations[j][i * 3] = skeletonAnimation.translations[i][j][0];
translations[j][i * 3 + 1] = skeletonAnimation.translations[i][j][1];
translations[j][i * 3 + 2] = skeletonAnimation.translations[i][j][2];
rotations[j][i * 4] = imaginary[0];
rotations[j][i * 4 + 1] = imaginary[1];
rotations[j][i * 4 + 2] = imaginary[2];
rotations[j][i * 4 + 3] = skeletonAnimation.rotations[i][j].GetReal();
scales[j][i * 3] = skeletonAnimation.scales[i][j][0];
scales[j][i * 3 + 1] = skeletonAnimation.scales[i][j][1];
scales[j][i * 3 + 2] = skeletonAnimation.scales[i][j][2];
}
}
int timeAccessor = addAccessor(ctx.gltf,
"times",
0,
TINYGLTF_TYPE_SCALAR,
TINYGLTF_COMPONENT_TYPE_FLOAT,
animationTimesCount,
times.data(),
true);
tinygltf::AnimationSampler translationSampler;
translationSampler.input = timeAccessor;
translationSampler.interpolation = "LINEAR";
tinygltf::AnimationSampler rotationSampler;
rotationSampler.input = timeAccessor;
rotationSampler.interpolation = "LINEAR";
tinygltf::AnimationSampler scaleSampler;
scaleSampler.input = timeAccessor;
scaleSampler.interpolation = "LINEAR";
tinygltf::AnimationChannel translationChannel;
translationChannel.target_path = "translation";
tinygltf::AnimationChannel rotationChannel;
rotationChannel.target_path = "rotation";
tinygltf::AnimationChannel scaleChannel;
scaleChannel.target_path = "scale";
tinygltf::Animation& anim = ctx.gltf->animations[animationTrackIndex];
for (size_t i = 0; i < boneCount; i++) {
int translationAccessor = addAccessor(ctx.gltf,
"translations",
0,
TINYGLTF_TYPE_VEC3,
TINYGLTF_COMPONENT_TYPE_FLOAT,
translations[i].size() / 3,
translations[i].data(),
false);
int rotationAccessor = addAccessor(ctx.gltf,
"rotations",
0,
TINYGLTF_TYPE_VEC4,
TINYGLTF_COMPONENT_TYPE_FLOAT,
rotations[i].size() / 4,
rotations[i].data(),
false);
int scaleAccessor = addAccessor(ctx.gltf,
"scales",
0,
TINYGLTF_TYPE_VEC3,
TINYGLTF_COMPONENT_TYPE_FLOAT,
scales[i].size() / 3,
scales[i].data(),
false);
SdfPath jointPath(skeleton.animatedJoints[i]);
int nodeIndex = skeletonNodesMap[jointPath];
translationSampler.output = translationAccessor;
rotationSampler.output = rotationAccessor;
scaleSampler.output = scaleAccessor;
int translationSamplerIndex = anim.samplers.size();
anim.samplers.push_back(translationSampler);
int rotationSamplerIndex = anim.samplers.size();
anim.samplers.push_back(rotationSampler);
int scaleSamplerIndex = anim.samplers.size();
anim.samplers.push_back(scaleSampler);
translationChannel.sampler = translationSamplerIndex;
translationChannel.target_node = nodeIndex;
rotationChannel.sampler = rotationSamplerIndex;
rotationChannel.target_node = nodeIndex;
scaleChannel.sampler = scaleSamplerIndex;
scaleChannel.target_node = nodeIndex;
anim.channels.push_back(translationChannel);
anim.channels.push_back(rotationChannel);
anim.channels.push_back(scaleChannel);
}
animationTrackIndex++;
}
}
}
int
getWrapCode(const TfToken& wrap)
{
if (wrap == AdobeTokens->repeat)
return TINYGLTF_TEXTURE_WRAP_REPEAT;
if (wrap == AdobeTokens->clamp)
return TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE;
if (wrap == AdobeTokens->mirror)
return TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT;
if (wrap == AdobeTokens->black || wrap == AdobeTokens->useMetadata) {
TF_WARN("Wrap mode %s is not supported in GLTF", wrap.GetText());
}
// Note, the default wrap mode in USD is "useMetadata", which is not supported in GLTF. So we
// default to the most common mode which is repeat.
return TINYGLTF_TEXTURE_WRAP_REPEAT;
}
int
getMipMapCode(const TfToken& mipMapMode)
{
if (mipMapMode == AdobeTokens->nearest)
return TINYGLTF_TEXTURE_FILTER_NEAREST;
if (mipMapMode == AdobeTokens->linear)
return TINYGLTF_TEXTURE_FILTER_LINEAR;
if (mipMapMode == AdobeTokens->nearestMipmapNearest)
return TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST;
if (mipMapMode == AdobeTokens->linearMipmapNearest)
return TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST;
if (mipMapMode == AdobeTokens->nearestMipmapLinear)
return TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR;
if (mipMapMode == AdobeTokens->linearMipmapLinear)
return TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR;
return TINYGLTF_TEXTURE_FILTER_LINEAR;
}
void
exportTexture(ExportGltfContext& ctx, const Input& input, int& textureIndex, int& texCoord)
{
if (input.image < 0)
return;
tinygltf::Sampler sampler;
sampler.magFilter = getMipMapCode(input.magFilter);
sampler.minFilter = getMipMapCode(input.minFilter);
sampler.wrapS = getWrapCode(input.wrapS);
sampler.wrapT = getWrapCode(input.wrapT);
int samplerIndex = ctx.gltf->samplers.size();
ctx.gltf->samplers.push_back(sampler);
tinygltf::Texture texture;
texture.sampler = samplerIndex;
texture.source = input.image;
textureIndex = ctx.gltf->textures.size();
ctx.gltf->textures.push_back(texture);
texCoord = input.uvIndex;
TF_DEBUG_MSG(FILE_FORMAT_GLTF,
"glTF::write texture[%d] { source: %d, coord: %d }\n",
textureIndex,
input.image,
texCoord);
}
void
addMaterialExt(ExportGltfContext& ctx,
tinygltf::Material& gltfMaterial,
const std::string& extensionName,
const ExtMap& ext)
{
addExtension(ctx, gltfMaterial.extensions, extensionName, ext);
}
void
addFloatValueToExt(ExtMap& ext, const std::string& name, float value)
{
ext[name] = tinygltf::Value((double)value);
}
bool
addFloatValueToExt(ExtMap& ext,
const std::string& name,
const VtValue& vtValue,
float defaultValue = 0.0f)
{
if (vtValue.IsHolding<float>()) {
float value = vtValue.UncheckedGet<float>();
if (value != defaultValue) {
addFloatValueToExt(ext, name, value);
return true;
}