Blender V5.3
usd_skel_convert.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 NVIDIA Corporation. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "usd_skel_convert.hh"
6
9
10#include <pxr/usd/usdGeom/primvarsAPI.h>
11#include <pxr/usd/usdSkel/animation.h>
12#include <pxr/usd/usdSkel/bindingAPI.h>
13#include <pxr/usd/usdSkel/blendShape.h>
14#include <pxr/usd/usdSkel/cache.h>
15#include <pxr/usd/usdSkel/skeletonQuery.h>
16#include <pxr/usd/usdSkel/utils.h>
17
18#include "DNA_anim_types.h"
19#include "DNA_armature_types.h"
20#include "DNA_key_types.h"
21#include "DNA_mesh_types.h"
22#include "DNA_meshdata_types.h"
23#include "DNA_object_types.h"
24
25#include "BKE_armature.hh"
26#include "BKE_deform.hh"
27#include "BKE_fcurve.hh"
28#include "BKE_key.hh"
29#include "BKE_lib_id.hh"
30#include "BKE_modifier.hh"
31#include "BKE_object_deform.h"
32#include "BKE_report.hh"
33
35#include "BLI_listbase.hh"
36#include "BLI_map.hh"
37#include "BLI_math_vector_c.hh"
38#include "BLI_set.hh"
39#include "BLI_span.hh"
40#include "BLI_string.hh"
41#include "BLI_vector.hh"
42
43#include "ED_armature.hh"
44#include "ED_object_vgroup.hh"
45
46#include "ANIM_action.hh"
47#include "ANIM_animdata.hh"
48
49#include <algorithm>
50#include <string>
51#include <vector>
52
53#include "CLG_log.h"
54
55namespace blender {
56
57static CLG_LogRef LOG = {"io.usd"};
58
59namespace {
60
61/* Utility: return the magnitude of the largest component
62 * of the given vector. */
63inline float max_mag_component(const pxr::GfVec3d &vec)
64{
65 return pxr::GfMax(pxr::GfAbs(vec[0]), pxr::GfAbs(vec[1]), pxr::GfAbs(vec[2]));
66}
67
68void resize_fcurve(FCurve &fcu, uint bezt_count)
69{
70 /* There is no need to resize if the counts match. */
71 if (bezt_count == fcu.totvert) {
72 return;
73 }
74
75 BKE_fcurve_bezt_resize(fcu, bezt_count);
76}
77
89void import_skeleton_curves(Main *bmain,
90 Object *arm_obj,
91 const pxr::UsdSkelSkeletonQuery &skel_query,
92 const Map<pxr::TfToken, std::string> &joint_to_bone_map,
93 ReportList *reports)
94{
95 using namespace blender::io::usd;
96
97 if (!(bmain && arm_obj && skel_query)) {
98 return;
99 }
100
101 if (joint_to_bone_map.is_empty()) {
102 return;
103 }
104
105 const pxr::UsdSkelAnimQuery &anim_query = skel_query.GetAnimQuery();
106
107 if (!anim_query) {
108 /* No animation is defined. */
109 return;
110 }
111
112 std::vector<double> samples;
113 anim_query.GetJointTransformTimeSamples(&samples);
114
115 if (samples.empty()) {
116 return;
117 }
118
119 const size_t num_samples = samples.size();
120
121 /* Create the action on the armature. */
122 bAction *act = animrig::id_action_ensure(bmain, &arm_obj->id);
123 BKE_id_rename(*bmain, act->id, anim_query.GetPrim().GetName().GetText());
124
125 animrig::Channelbag &channelbag = animrig::action_channelbag_ensure(*act, arm_obj->id);
126
127 /* Get the joint paths. */
128 const pxr::VtTokenArray joint_order = skel_query.GetJointOrder();
129
130 /* Create the curves. */
131 constexpr int curves_per_joint = 10; /* 3 loc, 4 rot, 3 scale */
132 LinearAllocator path_alloc;
134 curve_desc.reserve(joint_order.size() * curves_per_joint);
135
136 /* Iterate over the joints and create the corresponding curves for the bones. */
137 for (const pxr::TfToken &joint : joint_order) {
138 const std::string *name = joint_to_bone_map.lookup_ptr(joint);
139 if (name == nullptr) {
140 /* This joint doesn't correspond to any bone we created.
141 * Add null placeholders for the channel curves. */
142 curve_desc.append_n_times({}, curves_per_joint);
143 continue;
144 }
145
146 /* Translation curves. */
147 std::string rna_path = "pose.bones[\"" + *name + "\"].location";
148 StringRefNull path_desc = path_alloc.copy_string(rna_path);
149 curve_desc.append({path_desc, 0, {}, {}, *name});
150 curve_desc.append({path_desc, 1, {}, {}, *name});
151 curve_desc.append({path_desc, 2, {}, {}, *name});
152
153 /* Rotation curves. */
154 rna_path = "pose.bones[\"" + *name + "\"].rotation_quaternion";
155 path_desc = path_alloc.copy_string(rna_path);
156 curve_desc.append({path_desc, 0, {}, {}, *name});
157 curve_desc.append({path_desc, 1, {}, {}, *name});
158 curve_desc.append({path_desc, 2, {}, {}, *name});
159 curve_desc.append({path_desc, 3, {}, {}, *name});
160
161 /* Scale curves. */
162 rna_path = "pose.bones[\"" + *name + "\"].scale";
163 path_desc = path_alloc.copy_string(rna_path);
164 curve_desc.append({path_desc, 0, {}, {}, *name});
165 curve_desc.append({path_desc, 1, {}, {}, *name});
166 curve_desc.append({path_desc, 2, {}, {}, *name});
167 }
168
169 Vector<FCurve *> fcurves = channelbag.fcurve_create_many(nullptr, curve_desc.as_span());
170 BLI_assert_msg(fcurves.size() == curve_desc.size(), "USD: animation curve count mismatch");
171 for (FCurve *fcu : fcurves) {
172 if (fcu != nullptr) {
173 BKE_fcurve_bezt_resize(*fcu, num_samples);
174 }
175 }
176
177 /* The curve for each joint represents the transform relative
178 * to the bind transform in joint-local space. I.e.,
179 *
180 * `jointLocalTransform * inv(jointLocalBindTransform)`
181 *
182 * There doesn't appear to be a way to query the joint-local
183 * bind transform through the API, so we have to compute it
184 * ourselves from the world bind transforms and the skeleton
185 * topology.
186 */
187
188 /* Get the world space joint transforms at bind time. */
189 pxr::VtMatrix4dArray usd_bind_xforms;
190 if (!skel_query.GetJointWorldBindTransforms(&usd_bind_xforms)) {
191 BKE_reportf(reports,
193 "%s: Couldn't get world bind transforms for skeleton %s",
194 __func__,
195 skel_query.GetSkeleton().GetPrim().GetPath().GetAsString().c_str());
196 return;
197 }
198
199 if (usd_bind_xforms.size() != joint_order.size()) {
201 reports,
203 "%s: Number of bind transforms does not match the number of joints for skeleton %s",
204 __func__,
205 skel_query.GetSkeleton().GetPrim().GetPath().GetAsString().c_str());
206 return;
207 }
208
209 const pxr::UsdSkelTopology &skel_topology = skel_query.GetTopology();
210
211 const pxr::VtMatrix4dArray &bind_xforms = usd_bind_xforms.AsConst();
212 pxr::VtMatrix4dArray joint_local_bind_xforms(bind_xforms.size());
213 for (int i = 0; i < bind_xforms.size(); ++i) {
214 const int parent_id = skel_topology.GetParent(i);
215
216 if (parent_id >= 0) {
217 /* This is a non-root joint. Compute the bind transform of the joint
218 * relative to its parent. */
219 joint_local_bind_xforms[i] = bind_xforms[i] * bind_xforms[parent_id].GetInverse();
220 }
221 else {
222 /* This is the root joint. */
223 joint_local_bind_xforms[i] = bind_xforms[i];
224 }
225 }
226
227 /* Set the curve samples. */
228 Array<pxr::GfQuatf> prev_rot(joint_order.size());
229 uint bezt_index = 0;
230 for (const double frame : samples) {
231 pxr::VtMatrix4dArray joint_local_xforms;
232 if (!skel_query.ComputeJointLocalTransforms(&joint_local_xforms, frame)) {
233 CLOG_WARN(&LOG, "Couldn't compute joint local transforms on frame %f", frame);
234 continue;
235 }
236
237 if (joint_local_xforms.size() != joint_order.size()) {
238 CLOG_WARN(
239 &LOG,
240 "Number of joint local transform entries %zu does not match the number of joints %zu",
241 joint_local_xforms.size(),
242 joint_order.size());
243 continue;
244 }
245
246 for (int i = 0; i < joint_local_xforms.size(); ++i) {
247 const pxr::GfMatrix4d bone_xform = joint_local_xforms.AsConst()[i] *
248 joint_local_bind_xforms[i].GetInverse();
249
250 pxr::GfVec3f t;
251 pxr::GfQuatf qrot;
252 pxr::GfVec3h s;
253
254 if (!pxr::UsdSkelDecomposeTransform(bone_xform, &t, &qrot, &s)) {
255 CLOG_WARN(&LOG, "Error decomposing matrix on frame %f", frame);
256 continue;
257 }
258
259 if (bezt_index > 0) {
260 /* Quaternion "neighborhood" check to prevent most cases of discontinuous rotations.
261 * Note: An alternate method, comparing to the rotation of the rest position rather than
262 * to the previous rotation, was attempted but yielded much worse results for joints
263 * representing objects that are supposed to spin, like wheels and propellers. */
264 if (pxr::GfDot(prev_rot[i], qrot) < 0.0f) {
265 qrot = -qrot;
266 }
267 }
268 prev_rot[i] = qrot;
269
270 const float re = qrot.GetReal();
271 const pxr::GfVec3f &im = qrot.GetImaginary();
272
273 for (int j = 0; j < 3; ++j) {
274 const int k = curves_per_joint * i + j;
275 if (k >= fcurves.size()) {
276 CLOG_ERROR(&LOG, "Out of bounds translation curve index %d", k);
277 break;
278 }
279 if (FCurve *fcu = fcurves[k]) {
280 set_fcurve_sample(fcu, bezt_index, frame, t[j]);
281 }
282 }
283
284 for (int j = 0; j < 4; ++j) {
285 const int k = curves_per_joint * i + j + 3;
286 if (k >= fcurves.size()) {
287 CLOG_ERROR(&LOG, "Out of bounds rotation curve index %d", k);
288 break;
289 }
290 if (FCurve *fcu = fcurves[k]) {
291 if (j == 0) {
292 set_fcurve_sample(fcu, bezt_index, frame, re);
293 }
294 else {
295 set_fcurve_sample(fcu, bezt_index, frame, im[j - 1]);
296 }
297 }
298 }
299
300 for (int j = 0; j < 3; ++j) {
301 const int k = curves_per_joint * i + j + 7;
302 if (k >= fcurves.size()) {
303 CLOG_ERROR(&LOG, "Out of bounds scale curve index %d", k);
304 break;
305 }
306 if (FCurve *fcu = fcurves[k]) {
307 set_fcurve_sample(fcu, bezt_index, frame, s[j]);
308 }
309 }
310 }
311
312 bezt_index++;
313 }
314
315 /* Recalculate curve handles. */
316 for (FCurve *fcu : fcurves) {
317 if (fcu != nullptr) {
318 resize_fcurve(*fcu, bezt_index);
320 }
321 }
322}
323
324/* Set the skeleton path and bind transform on the given mesh. */
325void add_skinned_mesh_bindings(const pxr::UsdSkelSkeleton &skel,
326 const pxr::UsdPrim &mesh_prim,
327 pxr::UsdGeomXformCache &xf_cache)
328{
329 pxr::UsdSkelBindingAPI skel_api = pxr::UsdSkelBindingAPI::Apply(mesh_prim);
330
331 if (!skel_api) {
332 CLOG_WARN(&LOG,
333 "Couldn't apply UsdSkelBindingAPI to skinned mesh prim %s",
334 mesh_prim.GetPath().GetAsString().c_str());
335 return;
336 }
337
338 /* Specify the path to the skeleton. */
339 pxr::SdfPath skel_path = skel.GetPath();
340 skel_api.CreateSkeletonRel().SetTargets(pxr::SdfPathVector({skel_path}));
341
342 /* Set the mesh's bind transform. */
343 if (pxr::UsdAttribute geom_bind_attr = skel_api.CreateGeomBindTransformAttr()) {
344 /* The bind matrix is the mesh transform relative to the skeleton transform. */
345 pxr::GfMatrix4d mesh_xf = xf_cache.GetLocalToWorldTransform(mesh_prim);
346 pxr::GfMatrix4d skel_xf = xf_cache.GetLocalToWorldTransform(skel.GetPrim());
347 pxr::GfMatrix4d bind_xf = mesh_xf * skel_xf.GetInverse();
348 geom_bind_attr.Set(bind_xf);
349 }
350 else {
351 CLOG_WARN(&LOG,
352 "Couldn't create geom bind transform attribute for skinned mesh %s",
353 mesh_prim.GetPath().GetAsString().c_str());
354 }
355}
356
357} // namespace
358
359namespace io::usd {
360
362 Object *mesh_obj,
363 const pxr::UsdPrim &prim,
364 ReportList *reports,
365 const bool import_anim)
366{
367 if (!(mesh_obj && mesh_obj->data && mesh_obj->type == OB_MESH && prim)) {
368 return;
369 }
370
371 if (prim.IsInstanceProxy()) {
372 /* Attempting to create a UsdSkelBindingAPI for
373 * instance proxies generates USD errors. */
374 return;
375 }
376
377 pxr::UsdSkelBindingAPI skel_api(prim);
378
379 /* Get the blend shape targets, which are the USD paths to the
380 * blend shape primitives. */
381
382 if (!skel_api.GetBlendShapeTargetsRel().HasAuthoredTargets()) {
383 /* No targets. */
384 return;
385 }
386
387 pxr::SdfPathVector targets;
388 if (!skel_api.GetBlendShapeTargetsRel().GetTargets(&targets)) {
389 BKE_reportf(reports,
391 "%s: Couldn't get blendshape targets for prim %s",
392 __func__,
393 prim.GetPath().GetAsString().c_str());
394 return;
395 }
396
397 if (targets.empty()) {
398 return;
399 }
400
401 if (!skel_api.GetBlendShapesAttr().HasAuthoredValue()) {
402 return;
403 }
404
405 /* Get the blend shape name tokens. */
406 pxr::VtTokenArray usd_blendshapes;
407 if (!skel_api.GetBlendShapesAttr().Get(&usd_blendshapes)) {
408 return;
409 }
410
411 if (usd_blendshapes.empty()) {
412 return;
413 }
414
415 /* Sanity check. */
416 if (targets.size() != usd_blendshapes.size()) {
418 reports,
420 "%s: Number of blendshapes does not match number of blendshape targets for prim %s",
421 __func__,
422 prim.GetPath().GetAsString().c_str());
423 return;
424 }
425
426 pxr::UsdStageRefPtr stage = prim.GetStage();
427
428 if (!stage) {
429 BKE_reportf(reports,
431 "%s: Couldn't get stage for prim %s",
432 __func__,
433 prim.GetPath().GetAsString().c_str());
434 return;
435 }
436
437 Mesh *mesh = id_cast<Mesh *>(mesh_obj->data);
438
439 /* Insert key to source mesh. */
440 Key *key = BKE_key_add(bmain, id_cast<ID *>(mesh));
441 key->type = KEY_RELATIVE;
442
443 mesh->key = key;
444
445 /* Insert basis key. */
446 KeyBlock *kb = BKE_keyblock_add(key, "Basis");
448
449 /* Keep track of the shape-keys we're adding,
450 * for validation when creating curves later. */
451 Set<pxr::TfToken> shapekey_names;
452 Span<pxr::TfToken> blendshapes = Span(usd_blendshapes.cdata(), usd_blendshapes.size());
453
454 for (int i = 0; i < targets.size(); ++i) {
455 /* Get USD path to blend shape. */
456 const pxr::SdfPath &path = targets[i];
457 pxr::UsdSkelBlendShape blendshape(stage->GetPrimAtPath(path));
458
459 if (!blendshape) {
460 continue;
461 }
462
463 /* Get the blend shape offsets. */
464 if (!blendshape.GetOffsetsAttr().HasAuthoredValue()) {
465 /* Blend shape has no authored offsets. */
466 continue;
467 }
468
469 pxr::VtVec3fArray usd_offsets;
470 if (!blendshape.GetOffsetsAttr().Get(&usd_offsets)) {
471 BKE_reportf(reports,
473 "%s: Couldn't get offsets for blend shape %s",
474 __func__,
475 path.GetAsString().c_str());
476 continue;
477 }
478
479 if (usd_offsets.empty()) {
480 BKE_reportf(reports,
482 "%s: No offsets for blend shape %s",
483 __func__,
484 path.GetAsString().c_str());
485 continue;
486 }
487
488 shapekey_names.add(blendshapes[i]);
489
490 /* Add the key block. */
491 kb = BKE_keyblock_add(key, blendshapes[i].GetString().c_str());
493 if (!kb->data) {
494 /* Nothing to do. This can happen if the mesh has no vertices. */
495 continue;
496 }
497
498 /* if authored, point indices are indices into the original mesh
499 * that correspond to the values in the offsets array. */
500 pxr::VtArray<int> point_indices;
501 if (blendshape.GetPointIndicesAttr().HasAuthoredValue()) {
502 blendshape.GetPointIndicesAttr().Get(&point_indices);
503 }
504
505 float *fp = static_cast<float *>(kb->data);
506 Span<pxr::GfVec3f> offsets = Span(usd_offsets.cdata(), usd_offsets.size());
507
508 if (point_indices.empty()) {
509 /* Iterate over all key block elements and add the corresponding
510 * offset to the key block point. */
511 for (int a = 0; a < kb->totelem; ++a, fp += 3) {
512 if (a >= offsets.size()) {
514 reports,
516 "%s: Number of offsets greater than number of mesh vertices for blend shape %s",
517 __func__,
518 path.GetAsString().c_str());
519 break;
520 }
521 add_v3_v3(fp, offsets[a].data());
522 }
523 }
524 else {
525 /* Iterate over the point indices and add the offset to the corresponding
526 * key block point. */
527 int a = 0;
528 for (const int point : point_indices.AsConst()) {
529 if (point < 0 || point >= kb->totelem) {
530 CLOG_WARN(&LOG,
531 "Out of bounds point index %d for blendshape %s",
532 point,
533 path.GetAsString().c_str());
534 ++a;
535 continue;
536 }
537 if (a >= offsets.size()) {
539 reports,
541 "%s: Number of offsets greater than number of mesh vertices for blend shape %s",
542 __func__,
543 path.GetAsString().c_str());
544 break;
545 }
546 add_v3_v3(&fp[3 * point], offsets[a].data());
547 ++a;
548 }
549 }
550 }
551
552 if (!import_anim) {
553 /* We're not importing animation, so we are done. */
554 return;
555 }
556
557 /* Get the blend animation source from the skeleton. */
558
559 pxr::UsdSkelSkeleton skel_prim = skel_api.GetInheritedSkeleton();
560
561 if (!skel_prim) {
562 return;
563 }
564
565 skel_api = pxr::UsdSkelBindingAPI(skel_prim.GetPrim());
566
567 pxr::UsdPrim anim_prim = skel_api.GetInheritedAnimationSource();
568
569 if (!anim_prim) {
570 /* Querying the directly bound animation source may be necessary
571 * if the prim does not have an applied skel binding API schema. */
572 skel_api.GetAnimationSource(&anim_prim);
573 }
574
575 if (!anim_prim) {
576 return;
577 }
578
579 pxr::UsdSkelAnimation skel_anim(anim_prim);
580
581 if (!skel_anim) {
582 return;
583 }
584
585 /* Check if a blend shape weight animation was authored. */
586 if (!skel_anim.GetBlendShapesAttr().HasAuthoredValue()) {
587 return;
588 }
589
590 pxr::UsdAttribute weights_attr = skel_anim.GetBlendShapeWeightsAttr();
591
592 if (!(weights_attr && weights_attr.HasAuthoredValue())) {
593 return;
594 }
595
596 /* Get the animation time samples. */
597 std::vector<double> times;
598 if (!weights_attr.GetTimeSamples(&times)) {
599 return;
600 }
601
602 if (times.empty()) {
603 return;
604 }
605
606 /* Get the blend shape name tokens. */
607 if (!skel_anim.GetBlendShapesAttr().Get(&usd_blendshapes)) {
608 return;
609 }
610
611 if (usd_blendshapes.empty()) {
612 return;
613 }
614
615 /* Create the animation and curves. */
616 bAction *act = animrig::id_action_ensure(bmain, &key->id);
618
619 Set<pxr::TfToken> processed_shapes;
621 curves.reserve(usd_blendshapes.size());
622 processed_shapes.reserve(usd_blendshapes.size());
623
624 for (auto blendshape_name : usd_blendshapes.AsConst()) {
625 if (!shapekey_names.contains(blendshape_name)) {
626 /* We didn't create a shape-key for this blend-shape, so we don't
627 * create a curve and insert a null placeholder in the curve array. */
628 curves.append(nullptr);
629 continue;
630 }
631
632 if (!processed_shapes.add(blendshape_name)) {
633 CLOG_WARN(&LOG,
634 "Duplicate blendshape '%s' encountered for %s",
635 blendshape_name.GetText(),
636 skel_anim.GetPath().GetAsString().c_str());
637 curves.append(nullptr);
638 continue;
639 }
640
641 /* Create the curve for this shape key. */
642 const std::string rna_path = "key_blocks[\"" + BLI_str_escape(blendshape_name.GetString()) +
643 "\"].value";
644 FCurve *fcu = create_fcurve(channelbag, {rna_path, 0}, times.size());
645 curves.append(fcu);
646 }
647
648 /* Add the weight time samples to the curves. */
649 uint bezt_index = 0;
650 for (double frame : times) {
651 pxr::VtFloatArray usd_weights;
652 if (!weights_attr.Get(&usd_weights, frame)) {
653 CLOG_WARN(&LOG, "Couldn't get blendshape weights for time %f", frame);
654 continue;
655 }
656
657 if (usd_weights.size() != curves.size()) {
658 CLOG_WARN(
659 &LOG,
660 "Number of weight samples does not match number of shapekey curve entries for frame %f",
661 frame);
662 continue;
663 }
664
665 Span<float> weights = Span(usd_weights.cdata(), usd_weights.size());
666 for (int wi = 0; wi < weights.size(); ++wi) {
667 if (curves[wi] != nullptr) {
668 set_fcurve_sample(curves[wi], bezt_index, frame, weights[wi]);
669 }
670 }
671
672 bezt_index++;
673 }
674
675 /* Recalculate curve handles. */
676 auto recalc_handles = [bezt_index](FCurve *fcu) {
677 if (fcu) {
678 resize_fcurve(*fcu, bezt_index);
680 }
681 };
682 std::for_each(curves.begin(), curves.end(), recalc_handles);
683}
684
685static void set_rest_pose(Main *bmain,
686 Object *arm_obj,
687 bArmature *arm,
688 const pxr::VtArray<pxr::GfMatrix4d> &bind_xforms,
689 const pxr::VtTokenArray &joint_order,
690 const Map<pxr::TfToken, std::string> &joint_to_bone_map,
691 const pxr::UsdSkelTopology &skel_topology,
692 const pxr::UsdSkelSkeletonQuery &skel_query)
693{
694 if (!skel_query.HasRestPose()) {
695 return;
696 }
697
698 pxr::VtArray<pxr::GfMatrix4d> rest_xforms;
699 if (skel_query.ComputeJointLocalTransforms(&rest_xforms, pxr::UsdTimeCode::Default(), true)) {
700 BKE_pose_ensure(bmain, arm_obj, arm, false);
701
702 int64_t i = 0;
703 for (const pxr::TfToken &joint : joint_order) {
704 const std::string *name = joint_to_bone_map.lookup_ptr(joint);
705 if (name == nullptr) {
706 /* This joint doesn't correspond to any bone we created. Skip. */
707 continue;
708 }
709
710 bPoseChannel *pchan = BKE_pose_channel_find_name(arm_obj->pose, name->c_str());
711
712 pxr::GfMatrix4d xf = rest_xforms.AsConst()[i];
713 pxr::GfMatrix4d bind_xf = bind_xforms[i];
714
715 const int parent_id = skel_topology.GetParent(i);
716 if (parent_id >= 0) {
717 bind_xf = bind_xf * bind_xforms[parent_id].GetInverse();
718 }
719
720 xf = xf * bind_xf.GetInverse();
721
722 pxr::GfMatrix4f mat(xf);
723 BKE_pchan_apply_mat4(pchan, (float (*)[4])mat.data(), false);
724
725 i++;
726 }
727 }
728}
729
731 Object *arm_obj,
732 const pxr::UsdSkelSkeleton &skel,
733 ReportList *reports,
734 const bool import_anim)
735{
736 if (!(arm_obj && arm_obj->data && arm_obj->type == OB_ARMATURE)) {
737 return;
738 }
739
740 pxr::UsdSkelCache skel_cache;
741 pxr::UsdSkelSkeletonQuery skel_query = skel_cache.GetSkelQuery(skel);
742
743 if (!skel_query.IsValid()) {
744 BKE_reportf(reports,
746 "%s: Couldn't query skeleton %s",
747 __func__,
748 skel.GetPath().GetAsString().c_str());
749 return;
750 }
751
752 const pxr::UsdSkelTopology &skel_topology = skel_query.GetTopology();
753 const pxr::VtTokenArray joint_order = skel_query.GetJointOrder();
754
755 if (joint_order.size() != skel_topology.size()) {
756 BKE_reportf(reports,
758 "%s: Topology and joint order size mismatch for skeleton %s",
759 __func__,
760 skel.GetPath().GetAsString().c_str());
761 return;
762 }
763
764 /* Each joint path should be valid and unique. */
765 Set<pxr::TfToken> unique_joint_paths;
766 unique_joint_paths.reserve(joint_order.size());
767 const bool all_valid_paths = std::all_of(
768 joint_order.cbegin(), joint_order.cend(), [&unique_joint_paths](const pxr::TfToken &val) {
769 const bool is_valid = pxr::SdfPath::IsValidPathString(val);
770 return is_valid && unique_joint_paths.add(val);
771 });
772 if (!all_valid_paths) {
773 BKE_reportf(reports,
775 "%s: USD joint order array contains invalid or duplicated paths for skeleton %s",
776 __func__,
777 skel.GetPath().GetAsString().c_str());
778 return;
779 }
780
781 bArmature *arm = id_cast<bArmature *>(arm_obj->data);
782
783 /* Set the armature to edit mode when creating the bones. */
785
786 /* The bones we create, stored in the skeleton's joint order. */
787 Vector<EditBone *> edit_bones;
788
789 /* Keep track of the bones we create for each joint.
790 * We'll need this when creating animation curves
791 * later. */
792 Map<pxr::TfToken, std::string> joint_to_bone_map;
793
794 /* Create the bones. */
795 for (const pxr::TfToken &joint : joint_order) {
796 pxr::SdfPath bone_path(joint);
797 const std::string &bone_name = bone_path.GetName();
798 EditBone *bone = ED_armature_ebone_add(arm, bone_name.c_str());
799 if (!bone) {
800 BKE_reportf(reports,
802 "%s: Couldn't add bone for joint %s",
803 __func__,
804 joint.GetString().c_str());
805 edit_bones.append(nullptr);
806 continue;
807 }
808 joint_to_bone_map.add(joint, bone->name);
809 edit_bones.append(bone);
810 }
811
812 /* Sanity check: we should have created a bone for each joint. */
813 const size_t num_joints = skel_topology.GetNumJoints();
814 if (edit_bones.size() != num_joints) {
815 BKE_reportf(reports,
817 "%s: Mismatch in bone and joint counts for skeleton %s",
818 __func__,
819 skel.GetPath().GetAsString().c_str());
820 return;
821 }
822
823 /* Get the world space joint transforms at bind time. */
824 pxr::VtMatrix4dArray bind_xforms;
825 if (!skel_query.GetJointWorldBindTransforms(&bind_xforms)) {
826 BKE_reportf(reports,
828 "%s: Couldn't get world bind transforms for skeleton %s",
829 __func__,
830 skel.GetPath().GetAsString().c_str());
831 return;
832 }
833
834 if (bind_xforms.size() != num_joints) {
835 BKE_reportf(reports,
837 "%s: Mismatch in bind xforms and joint counts for skeleton %s",
838 __func__,
839 skel.GetPath().GetAsString().c_str());
840 return;
841 }
842
843 /* Check if any bone matrices have negative determinants,
844 * indicating negative scales, possibly due to mirroring
845 * operations. Such matrices can't be properly converted
846 * to Blender's axis/roll bone representation (see
847 * https://projects.blender.org/blender/blender/issues/82930).
848 * If we detect such matrices, we will flag an error and won't
849 * try to import the animation, since the rotations would
850 * be incorrect in such cases. Unfortunately, the Pixar
851 * `UsdSkel` examples of the "HumanFemale" suffer from
852 * this issue. */
853 bool negative_determinant = false;
854
855 /* Set bone rest transforms. */
856 for (size_t i = 0; i < num_joints; ++i) {
857 EditBone *ebone = edit_bones[i];
858
859 if (!ebone) {
860 continue;
861 }
862
863 pxr::GfMatrix4f mat(bind_xforms.AsConst()[i]);
864
865 float mat4[4][4];
866 mat.Get(mat4);
867
868 pxr::GfVec3f head(0.0f, 0.0f, 0.0f);
869 pxr::GfVec3f tail(0.0f, 1.0f, 0.0f);
870
871 copy_v3_v3(ebone->head, head.data());
872 copy_v3_v3(ebone->tail, tail.data());
873
874 ED_armature_ebone_from_mat4(ebone, mat4);
875
876 if (mat.GetDeterminant() < 0.0) {
877 negative_determinant = true;
878 }
879 }
880
881 bool valid_skeleton = true;
882 if (negative_determinant) {
883 valid_skeleton = false;
885 reports,
887 "USD Skeleton Import: bone matrices with negative determinants detected in prim %s. "
888 "Such matrices may indicate negative scales, possibly due to mirroring operations, "
889 "and cannot currently be converted to Blender's bone representation. "
890 "The skeletal animation won't be imported",
891 skel.GetPath().GetAsString().c_str());
892 }
893
894 /* Set bone parenting. In addition, scale bones to account
895 * for separation between parents and children, so that the
896 * bone size is in proportion with the overall skeleton hierarchy.
897 * USD skeletons are composed of joints which we imperfectly
898 * represent as bones. */
899
900 /* This will record the child bone indices per parent bone,
901 * to simplify accessing children when computing lengths. */
902 Vector<Vector<int>> child_bones(num_joints);
903
904 for (size_t i = 0; i < num_joints; ++i) {
905 const int parent_idx = skel_topology.GetParent(i);
906 if (parent_idx < 0) {
907 continue;
908 }
909 if (parent_idx >= edit_bones.size()) {
910 CLOG_WARN(&LOG,
911 "Out of bounds parent index for bone %s on skeleton %s",
912 pxr::SdfPath(joint_order[i]).GetAsString().c_str(),
913 skel.GetPath().GetAsString().c_str());
914 continue;
915 }
916
917 child_bones[parent_idx].append(i);
918 if (edit_bones[i] && edit_bones[parent_idx]) {
919 edit_bones[i]->parent = edit_bones[parent_idx];
920 }
921 }
922
923 /* Use our custom bone length data if possible, otherwise fall back to estimated lengths. */
924 const pxr::UsdGeomPrimvarsAPI pv_api = pxr::UsdGeomPrimvarsAPI(skel.GetPrim());
925 const pxr::UsdGeomPrimvar pv_lengths = pv_api.GetPrimvar(BlenderBoneLengths);
926 if (pv_lengths.HasValue()) {
927 pxr::VtArray<float> blender_bone_lengths;
928 pv_lengths.ComputeFlattened(&blender_bone_lengths);
929
930 Span<float> bone_lengths = Span(blender_bone_lengths.cdata(), blender_bone_lengths.size());
931 for (size_t i = 0; i < num_joints; ++i) {
932 EditBone *bone = edit_bones[i];
933 pxr::GfVec3f head(bone->head);
934 pxr::GfVec3f tail(bone->tail);
935
936 tail = head + (tail - head).GetNormalized() * bone_lengths[i];
937 copy_v3_v3(bone->tail, tail.data());
938 }
939 }
940 else {
941 float avg_len_scale = 0;
942 for (size_t i = 0; i < num_joints; ++i) {
943
944 /* If the bone has any children, scale its length
945 * by the distance between this bone's head
946 * and the average head location of its children. */
947
948 if (child_bones[i].is_empty()) {
949 continue;
950 }
951
952 EditBone *parent = edit_bones[i];
953 if (!parent) {
954 continue;
955 }
956
957 pxr::GfVec3f avg_child_head(0);
958 for (int j : child_bones[i]) {
959 EditBone *child = edit_bones[j];
960 if (!child) {
961 continue;
962 }
963 pxr::GfVec3f child_head(child->head);
964 avg_child_head += child_head;
965 }
966
967 avg_child_head /= child_bones[i].size();
968
969 pxr::GfVec3f parent_head(parent->head);
970 pxr::GfVec3f parent_tail(parent->tail);
971
972 const float new_len = (avg_child_head - parent_head).GetLength();
973
974 /* Check for epsilon relative to the parent head before scaling. */
975 if (new_len > .00001 * max_mag_component(parent_head)) {
976 parent_tail = parent_head + (parent_tail - parent_head).GetNormalized() * new_len;
977 copy_v3_v3(parent->tail, parent_tail.data());
978 avg_len_scale += new_len;
979 }
980 }
981
982 /* Scale terminal bones by the average length scale. */
983 avg_len_scale /= num_joints;
984
985 for (size_t i = 0; i < num_joints; ++i) {
986 if (!child_bones[i].is_empty()) {
987 /* Not a terminal bone. */
988 continue;
989 }
990 EditBone *bone = edit_bones[i];
991 if (!bone) {
992 continue;
993 }
994 pxr::GfVec3f head(bone->head);
995
996 /* Check for epsilon relative to the head before scaling. */
997 if (avg_len_scale > .00001 * max_mag_component(head)) {
998 pxr::GfVec3f tail(bone->tail);
999 tail = head + (tail - head).GetNormalized() * avg_len_scale;
1000 copy_v3_v3(bone->tail, tail.data());
1001 }
1002 }
1003 }
1004
1005 /* Get out of edit mode. */
1006 ED_armature_from_edit(bmain, arm);
1008
1010 bmain, arm_obj, arm, bind_xforms, joint_order, joint_to_bone_map, skel_topology, skel_query);
1011
1012 if (import_anim && valid_skeleton) {
1013 import_skeleton_curves(bmain, arm_obj, skel_query, joint_to_bone_map, reports);
1014 }
1015}
1016
1017void import_mesh_skel_bindings(Object *mesh_obj, const pxr::UsdPrim &prim, ReportList *reports)
1018{
1019 if (!(mesh_obj && mesh_obj->type == OB_MESH && prim)) {
1020 return;
1021 }
1022
1023 if (prim.IsInstanceProxy()) {
1024 /* Attempting to create a UsdSkelBindingAPI for
1025 * instance proxies generates USD errors. */
1026 return;
1027 }
1028
1029 pxr::UsdSkelBindingAPI skel_api(prim);
1030
1031 pxr::UsdSkelSkeleton skel = skel_api.GetInheritedSkeleton();
1032
1033 if (!skel) {
1034 return;
1035 }
1036
1037 /* Get the joint identifiers from the skeleton. We will
1038 * need these to construct deform groups. */
1039 pxr::VtArray<pxr::TfToken> joints;
1040
1041 if (skel_api.GetJointsAttr().HasAuthoredValue()) {
1042 skel_api.GetJointsAttr().Get(&joints);
1043 }
1044 else if (skel.GetJointsAttr().HasAuthoredValue()) {
1045 skel.GetJointsAttr().Get(&joints);
1046 }
1047
1048 if (joints.empty()) {
1049 return;
1050 }
1051
1052 /* Get the joint indices, which specify which joints influence a given point. */
1053 pxr::UsdGeomPrimvar joint_indices_primvar = skel_api.GetJointIndicesPrimvar();
1054 if (!(joint_indices_primvar && joint_indices_primvar.HasAuthoredValue())) {
1055 return;
1056 }
1057
1058 /* Get the weights, which specify the weight of a joint on a given point. */
1059 pxr::UsdGeomPrimvar joint_weights_primvar = skel_api.GetJointWeightsPrimvar();
1060 if (!(joint_weights_primvar && joint_weights_primvar.HasAuthoredValue())) {
1061 return;
1062 }
1063
1064 /* Element size specifies the number of joints that might influence a given point.
1065 * This is the stride we take when accessing the indices and weights for a given point. */
1066 int joint_indices_elem_size = joint_indices_primvar.GetElementSize();
1067 int joint_weights_elem_size = joint_weights_primvar.GetElementSize();
1068
1069 /* We expect the element counts to match. */
1070 if (joint_indices_elem_size != joint_weights_elem_size) {
1071 BKE_reportf(reports,
1073 "%s: Joint weights and joint indices element size mismatch for prim %s",
1074 __func__,
1075 prim.GetPath().GetAsString().c_str());
1076 return;
1077 }
1078
1079 /* Get the joint indices and weights. */
1080 pxr::VtIntArray joint_indices;
1081 joint_indices_primvar.ComputeFlattened(&joint_indices);
1082
1083 pxr::VtFloatArray joint_weights;
1084 joint_weights_primvar.ComputeFlattened(&joint_weights);
1085
1086 if (joint_indices.empty() || joint_weights.empty()) {
1087 return;
1088 }
1089
1090 if (joint_indices.size() != joint_weights.size()) {
1091 BKE_reportf(reports,
1093 "%s: Joint weights and joint indices size mismatch for prim %s",
1094 __func__,
1095 prim.GetPath().GetAsString().c_str());
1096 return;
1097 }
1098
1099 Mesh *mesh = id_cast<Mesh *>(mesh_obj->data);
1100
1101 const pxr::TfToken interp = joint_weights_primvar.GetInterpolation();
1102
1103 /* Sanity check: we expect only vertex or constant interpolation. */
1104 if (!ELEM(interp, pxr::UsdGeomTokens->vertex, pxr::UsdGeomTokens->constant)) {
1105 BKE_reportf(reports,
1107 "%s: Unexpected joint weights interpolation type %s for prim %s",
1108 __func__,
1109 interp.GetString().c_str(),
1110 prim.GetPath().GetAsString().c_str());
1111 return;
1112 }
1113
1114 /* Sanity check: make sure we have the expected number of values for the interpolation type. */
1115 if (interp == pxr::UsdGeomTokens->vertex &&
1116 joint_weights.size() != int64_t(mesh->verts_num) * joint_weights_elem_size)
1117 {
1118 BKE_reportf(reports,
1120 "%s: Joint weights of unexpected size for vertex interpolation for prim %s",
1121 __func__,
1122 prim.GetPath().GetAsString().c_str());
1123 return;
1124 }
1125
1126 if (interp == pxr::UsdGeomTokens->constant && joint_weights.size() != joint_weights_elem_size) {
1127 BKE_reportf(reports,
1129 "%s: Joint weights of unexpected size for constant interpolation for prim %s",
1130 __func__,
1131 prim.GetPath().GetAsString().c_str());
1132 return;
1133 }
1134
1135 /* Determine which joint indices are used for skinning this prim. */
1136 Vector<int> used_indices;
1137 for (int index : joint_indices.AsConst()) {
1138 if (std::find(used_indices.begin(), used_indices.end(), index) == used_indices.end()) {
1139 /* We haven't accounted for this index yet. */
1140 if (index < 0 || index >= joints.size()) {
1141 CLOG_ERROR(&LOG, "Out of bound joint index %d for mesh %s", index, mesh_obj->id.name + 2);
1142 return;
1143 }
1144 used_indices.append(index);
1145 }
1146 }
1147
1148 if (used_indices.is_empty()) {
1149 return;
1150 }
1151
1152 if (BKE_object_defgroup_data_create(mesh_obj->data) == nullptr) {
1153 BKE_reportf(reports,
1155 "%s: Error creating deform group data for mesh %s",
1156 __func__,
1157 mesh_obj->id.name + 2);
1158 return;
1159 }
1160
1161 /* Add the armature modifier, if one doesn't exist. */
1164 BLI_addtail(&mesh_obj->modifiers, md);
1165 BKE_modifiers_persistent_uid_init(*mesh_obj, *md);
1166 }
1167
1168 /* Create a deform group per joint. */
1169 Vector<bDeformGroup *> joint_def_grps(joints.size(), nullptr);
1170
1171 for (int idx : used_indices) {
1172 std::string joint_name = pxr::SdfPath(joints.AsConst()[idx]).GetName();
1173 if (!BKE_object_defgroup_find_name(mesh_obj, joint_name.c_str())) {
1174 bDeformGroup *def_grp = BKE_object_defgroup_add_name(mesh_obj, joint_name.c_str());
1175 joint_def_grps[idx] = def_grp;
1176 }
1177 }
1178
1179 /* Set the deform group verts and weights. */
1180 for (int64_t i = 0; i < mesh->verts_num; ++i) {
1181 /* Offset into the weights array, which is
1182 * always 0 for constant interpolation. */
1183 int64_t offset = 0;
1184 if (interp == pxr::UsdGeomTokens->vertex) {
1185 offset = i * joint_weights_elem_size;
1186 }
1187 for (int j = 0; j < joint_weights_elem_size; ++j) {
1188 const int64_t k = offset + j;
1189 const float w = joint_weights.AsConst()[k];
1190 if (w < .00001) {
1191 /* No deform group if zero weight. */
1192 continue;
1193 }
1194 const int joint_idx = joint_indices.AsConst()[k];
1195 if (bDeformGroup *def_grp = joint_def_grps[joint_idx]) {
1196 ed::object::vgroup_vert_add(mesh_obj, def_grp, i, w, WEIGHT_REPLACE);
1197 }
1198 }
1199 }
1200}
1201
1202void skel_export_chaser(pxr::UsdStageRefPtr stage,
1203 const ObjExportMap &armature_export_map,
1204 const ObjExportMap &skinned_mesh_export_map,
1205 const ObjExportMap &shape_key_mesh_export_map,
1206 const Depsgraph *depsgraph)
1207{
1208 /* We may need to compute the world transforms of certain primitives when
1209 * setting skinning data. Using a shared transform cache can make computing
1210 * the transforms more efficient. */
1211 pxr::UsdGeomXformCache xf_cache(1.0);
1213 stage, armature_export_map, skinned_mesh_export_map, xf_cache, depsgraph);
1214 shape_key_export_chaser(stage, shape_key_mesh_export_map);
1215}
1216
1217void skinned_mesh_export_chaser(pxr::UsdStageRefPtr stage,
1218 const ObjExportMap &armature_export_map,
1219 const ObjExportMap &skinned_mesh_export_map,
1220 pxr::UsdGeomXformCache &xf_cache,
1221 const Depsgraph *depsgraph)
1222{
1223 /* Finish creating skinned mesh bindings. */
1224 for (const auto &item : skinned_mesh_export_map.items()) {
1225 const Object *mesh_obj = item.key;
1226 const pxr::SdfPath &mesh_path = item.value;
1227
1228 /* Get the mesh prim from the stage. */
1229 pxr::UsdPrim mesh_prim = stage->GetPrimAtPath(mesh_path);
1230 if (!mesh_prim) {
1231 CLOG_WARN(&LOG,
1232 "Invalid export map prim path %s for mesh object %s",
1233 mesh_path.GetAsString().c_str(),
1234 mesh_obj->id.name + 2);
1235 continue;
1236 }
1237
1238 /* Get the armature bound to the mesh's armature modifier. */
1239 const Object *arm_obj = get_armature_modifier_obj(*mesh_obj, depsgraph);
1240 if (!arm_obj) {
1241 CLOG_WARN(&LOG, "Invalid armature modifier for skinned mesh %s", mesh_obj->id.name + 2);
1242 continue;
1243 }
1244 /* Look up the USD skeleton corresponding to the armature object. */
1245 const pxr::SdfPath *path = armature_export_map.lookup_ptr(arm_obj);
1246 if (!path) {
1247 CLOG_WARN(&LOG, "No export map entry for armature object %s", mesh_obj->id.name + 2);
1248 continue;
1249 }
1250 /* Get the skeleton prim. */
1251 pxr::UsdPrim skel_prim = stage->GetPrimAtPath(*path);
1252 pxr::UsdSkelSkeleton skel(skel_prim);
1253 if (!skel) {
1254 CLOG_WARN(&LOG, "Invalid USD skeleton for armature object %s", arm_obj->id.name + 2);
1255 continue;
1256 }
1257
1258 add_skinned_mesh_bindings(skel, mesh_prim, xf_cache);
1259 }
1260}
1261
1262void shape_key_export_chaser(pxr::UsdStageRefPtr stage,
1263 const ObjExportMap &shape_key_mesh_export_map)
1264{
1266
1267 /* We will keep track of the mesh primitives to clean up the temporary
1268 * weights attribute at the end. */
1269 Vector<pxr::UsdPrim> mesh_prims;
1270
1271 /* Finish creating blend shape bindings. */
1272 for (const auto &item : shape_key_mesh_export_map.items()) {
1273 const Object *mesh_obj = item.key;
1274 const pxr::SdfPath &mesh_path = item.value;
1275
1276 /* Get the mesh prim from the stage. */
1277 pxr::UsdPrim mesh_prim = stage->GetPrimAtPath(mesh_path);
1278 if (!mesh_prim) {
1279 CLOG_WARN(&LOG,
1280 "Invalid export map prim path %s for mesh object %s",
1281 mesh_path.GetAsString().c_str(),
1282 mesh_obj->id.name + 2);
1283 continue;
1284 }
1285
1286 /* Keep track of all the mesh primitives with blend shapes, for cleanup below. */
1287 mesh_prims.append(mesh_prim);
1288
1289 pxr::UsdSkelBindingAPI skel_api = pxr::UsdSkelBindingAPI::Apply(mesh_prim);
1290
1291 if (!skel_api) {
1292 CLOG_WARN(&LOG,
1293 "Couldn't apply UsdSkelBindingAPI to prim %s",
1294 mesh_prim.GetPath().GetAsString().c_str());
1295 return;
1296 }
1297
1298 pxr::UsdSkelSkeleton skel;
1299 if (skel_api.GetSkeleton(&skel)) {
1300 /* We have a bound skeleton, so we add it to the map. */
1301 pxr::SdfPathSet *mesh_paths = skel_to_mesh.lookup_ptr(skel.GetPath());
1302 if (!mesh_paths) {
1303 skel_to_mesh.add_new(skel.GetPath(), pxr::SdfPathSet());
1304 mesh_paths = skel_to_mesh.lookup_ptr(skel.GetPath());
1305 }
1306 if (mesh_paths) {
1307 mesh_paths->insert(mesh_prim.GetPath());
1308 }
1309 continue;
1310 }
1311
1312 /* The mesh is not bound to a skeleton, so we must create one for it. */
1313 ensure_blend_shape_skeleton(stage, mesh_prim);
1314 }
1315
1316 if (skel_to_mesh.is_empty()) {
1317 return;
1318 }
1319
1320 for (const auto &item : skel_to_mesh.items()) {
1321 remap_blend_shape_anim(stage, item.key, item.value);
1322 }
1323
1324 /* Finally, delete the temp blendshape weights attributes. */
1325 for (const pxr::UsdPrim &prim : mesh_prims) {
1326 pxr::UsdGeomPrimvarsAPI(prim).RemovePrimvar(TempBlendShapeWeightsPrimvarName);
1327 }
1328}
1329
1331 const pxr::UsdSkelBindingAPI &skel_api,
1332 const Span<StringRef> bone_names)
1333{
1335 BLI_assert(skel_api);
1336
1337 /* Map a deform vertex group index to the
1338 * index of the corresponding joint. I.e.,
1339 * joint_index[n] is the joint index of the
1340 * n-th vertex group. */
1341 Vector<int> joint_index;
1342
1343 /* Build the index mapping. */
1344 for (const bDeformGroup &def : mesh->vertex_group_names) {
1345 int bone_idx = -1;
1346 /* For now, n-squared search is acceptable. */
1347 for (int i = 0; i < bone_names.size(); ++i) {
1348 if (bone_names[i] == def.name) {
1349 bone_idx = i;
1350 break;
1351 }
1352 }
1353
1354 joint_index.append(bone_idx);
1355 }
1356
1357 if (joint_index.is_empty()) {
1358 return;
1359 }
1360
1361 const Span<MDeformVert> dverts = mesh->deform_verts();
1362
1363 int max_totweight = 1;
1364 for (const int i : dverts.index_range()) {
1365 const MDeformVert &vert = dverts[i];
1366 max_totweight = std::max(vert.totweight, max_totweight);
1367 }
1368
1369 /* elem_size will specify the number of
1370 * joints that can influence a given point. */
1371 const int element_size = max_totweight;
1372 int num_points = mesh->verts_num;
1373
1374 pxr::VtArray<int> joint_indices(num_points * element_size, 0);
1375 pxr::VtArray<float> joint_weights(num_points * element_size, 0.0f);
1376
1377 /* Current offset into the indices and weights arrays. */
1378 int offset = 0;
1379
1380 for (const int i : dverts.index_range()) {
1381 const MDeformVert &vert = dverts[i];
1382
1383 for (int j = 0; j < element_size; ++j, ++offset) {
1384
1385 if (offset >= joint_indices.size()) {
1387 return;
1388 }
1389
1390 if (j >= vert.totweight) {
1391 continue;
1392 }
1393
1394 int def_nr = int(vert.dw[j].def_nr);
1395
1396 if (def_nr >= joint_index.size()) {
1398 continue;
1399 }
1400
1401 if (joint_index[def_nr] == -1) {
1402 continue;
1403 }
1404
1405 joint_indices[offset] = joint_index[def_nr];
1406 joint_weights[offset] = vert.dw[j].weight;
1407 }
1408 }
1409
1410 pxr::UsdSkelNormalizeWeights(joint_weights, element_size);
1411
1412 skel_api.CreateJointIndicesPrimvar(false, element_size).GetAttr().Set(joint_indices);
1413 skel_api.CreateJointWeightsPrimvar(false, element_size).GetAttr().Set(joint_weights);
1414}
1415
1416} // namespace io::usd
1417} // namespace blender
Functions and classes to work with Actions.
Functions to work with AnimData.
support for deformation groups and hooks.
Functions for dealing with objects and deform verts, used by painting and tools.
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
Object is a sort of wrapper for general info.
#define WEIGHT_REPLACE
#define BLI_assert_unreachable()
#define ELEM(...)
#define BLI_assert_msg(a, msg)
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
StringRefNull copy_string(StringRef str)
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
bool is_empty() const
Definition BLI_map.hh:986
ItemIterator items() const &
Definition BLI_map.hh:902
void reserve(const int64_t n)
Definition BLI_set.hh:656
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr Span()=default
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
int64_t size() const
void append(const T &value)
bool is_empty() const
void reserve(const int64_t min_capacity)
Span< T > as_span() const
void append_n_times(const T &value, const int64_t n)
Vector< FCurve * > fcurve_create_many(Main *bmain, Span< FCurveDescriptor > fcurve_descriptors)
#define vertex
ccl_device_inline float interp(const float a, const float b, const float t)
Definition math_base.h:549
bAction * id_action_ensure(Main *bmain, ID *id)
Definition animdata.cc:195
Channelbag & action_channelbag_ensure(bAction &dna_action, ID &animated_id)
void vgroup_vert_add(Object *ob, bDeformGroup *dg, int vertnum, float weight, int assignmode)
void set_fcurve_sample(FCurve *fcu, int64_t sample_index, const float frame, const float value)
Map< const Object *, pxr::SdfPath > ObjExportMap
void shape_key_export_chaser(pxr::UsdStageRefPtr stage, const ObjExportMap &shape_key_mesh_export_map)
void import_mesh_skel_bindings(Object *mesh_obj, const pxr::UsdPrim &prim, ReportList *reports)
void set_fcurve_sample(FCurve *fcu, int64_t sample_index, const float frame, const float value)
void skel_export_chaser(pxr::UsdStageRefPtr stage, const ObjExportMap &armature_export_map, const ObjExportMap &skinned_mesh_export_map, const ObjExportMap &shape_key_mesh_export_map, const Depsgraph *depsgraph)
void export_deform_verts(const Mesh *mesh, const pxr::UsdSkelBindingAPI &skel_api, const Span< StringRef > bone_names)
void remap_blend_shape_anim(pxr::UsdStageRefPtr stage, const pxr::SdfPath &skel_path, const pxr::SdfPathSet &mesh_paths)
static void set_rest_pose(Main *bmain, Object *arm_obj, bArmature *arm, const pxr::VtArray< pxr::GfMatrix4d > &bind_xforms, const pxr::VtTokenArray &joint_order, const Map< pxr::TfToken, std::string > &joint_to_bone_map, const pxr::UsdSkelTopology &skel_topology, const pxr::UsdSkelSkeletonQuery &skel_query)
const pxr::TfToken BlenderBoneLengths("blender:bone_lengths", pxr::TfToken::Immortal)
void import_blendshapes(Main *bmain, Object *mesh_obj, const pxr::UsdPrim &prim, ReportList *reports, const bool import_anim)
void skinned_mesh_export_chaser(pxr::UsdStageRefPtr stage, const ObjExportMap &armature_export_map, const ObjExportMap &skinned_mesh_export_map, pxr::UsdGeomXformCache &xf_cache, const Depsgraph *depsgraph)
void ensure_blend_shape_skeleton(pxr::UsdStageRefPtr stage, pxr::UsdPrim &mesh_prim)
pxr::TfToken TempBlendShapeWeightsPrimvarName
void import_skeleton(Main *bmain, Object *arm_obj, const pxr::UsdSkelSkeleton &skel, ReportList *reports, const bool import_anim)
const Object * get_armature_modifier_obj(const Object &obj, const Depsgraph *depsgraph)
FCurve * create_fcurve(animrig::Channelbag &channelbag, const animrig::FCurveDescriptor &fcurve_descriptor, const int sample_count)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
struct MDeformVert * BKE_object_defgroup_data_create(struct ID *id)
__int64 int64_t
Definition BKE_text.h:90
@ RPT_WARNING
Definition BKE_report.hh:40
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void ED_armature_to_edit(bArmature *arm)
void ED_armature_from_edit(Main *bmain, bArmature *arm)
bDeformGroup * BKE_object_defgroup_find_name(const Object *ob, StringRef name)
Definition deform.cc:530
void BKE_pose_ensure(Main *bmain, Object *ob, bArmature *arm, bool do_id_user)
void BKE_modifiers_persistent_uid_init(const Object &object, ModifierData &md)
void ED_armature_ebone_from_mat4(EditBone *ebone, const float mat[4][4])
void BKE_fcurve_handles_recalc(FCurve &fcu)
Key * BKE_key_add(Main *bmain, ID *id)
Definition key.cc:228
BMesh const char void * data
ModifierData * BKE_modifier_new(int type)
char char size_t BLI_str_escape(char *__restrict dst, StringRef src, size_t dst_maxncpy) ATTR_NONNULL(1)
void BKE_pchan_apply_mat4(bPoseChannel *pchan, const float mat[4][4], bool use_compat)
struct bDeformGroup * BKE_object_defgroup_add_name(struct Object *ob, const char *name)
void ED_armature_edit_free(bArmature *arm)
ModifierData * BKE_modifiers_findby_type(const Object *ob, ModifierType type)
MINLINE void add_v3_v3(float r[3], const float a[3])
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
EditBone * ED_armature_ebone_add(bArmature *arm, const char *name)
KeyBlock * BKE_keyblock_add(Key *key, const char *name)
Definition key.cc:1322
static CLG_LogRef LOG
Definition logging.cpp:12
IDNewNameResult BKE_id_rename(Main &bmain, ID &id, StringRefNull name, const IDNewNameMode mode=IDNewNameMode::RenameExistingNever)
Definition lib_id.cc:2654
void BKE_fcurve_bezt_resize(FCurve &fcu, int new_totvert)
void BKE_keyblock_convert_from_mesh(const Mesh *mesh, const Key *key, KeyBlock *kb)
Definition key.cc:1681
bPoseChannel * BKE_pose_channel_find_name(const bPose *pose, const char *name)
char name[258]
Definition DNA_ID.h:433
ShapekeyContainerType type
ListBaseT< ModifierData > modifiers
struct bPose * pose