void UPoseableMeshComponent::FillSpaceBases() { SCOPE_CYCLE_COUNTER(STAT_SkelComposeTime); if( !SkeletalMesh ) { return; } // right now all this does is to convert to SpaceBases check( SkeletalMesh->RefSkeleton.GetNum() == LocalAtoms.Num() ); check( SkeletalMesh->RefSkeleton.GetNum() == GetNumSpaceBases()); check( SkeletalMesh->RefSkeleton.GetNum() == BoneVisibilityStates.Num() ); const int32 NumBones = LocalAtoms.Num(); #if (UE_BUILD_DEBUG || UE_BUILD_DEVELOPMENT) /** Keep track of which bones have been processed for fast look up */ TArray<uint8> BoneProcessed; BoneProcessed.AddZeroed(NumBones); #endif // Build in 3 passes. FTransform* LocalTransformsData = LocalAtoms.GetData(); FTransform* SpaceBasesData = GetEditableSpaceBases().GetData(); GetEditableSpaceBases()[0] = LocalAtoms[0]; #if (UE_BUILD_DEBUG || UE_BUILD_DEVELOPMENT) BoneProcessed[0] = 1; #endif for(int32 BoneIndex=1; BoneIndex<LocalAtoms.Num(); BoneIndex++) { FPlatformMisc::Prefetch(SpaceBasesData + BoneIndex); #if (UE_BUILD_DEBUG || UE_BUILD_DEVELOPMENT) // Mark bone as processed BoneProcessed[BoneIndex] = 1; #endif // For all bones below the root, final component-space transform is relative transform * component-space transform of parent. const int32 ParentIndex = SkeletalMesh->RefSkeleton.GetParentIndex(BoneIndex); FPlatformMisc::Prefetch(SpaceBasesData + ParentIndex); #if (UE_BUILD_DEBUG || UE_BUILD_DEVELOPMENT) // Check the precondition that Parents occur before Children in the RequiredBones array. checkSlow(BoneProcessed[ParentIndex] == 1); #endif FTransform::Multiply(SpaceBasesData + BoneIndex, LocalTransformsData + BoneIndex, SpaceBasesData + ParentIndex); checkSlow(GetEditableSpaceBases()[BoneIndex].IsRotationNormalized()); checkSlow(!GetEditableSpaceBases()[BoneIndex].ContainsNaN()); } bNeedToFlipSpaceBaseBuffers = true; }
FBoxSphereBounds UDebugSkelMeshComponent::CalcBounds(const FTransform& LocalToWorld) const { FBoxSphereBounds Result = Super::CalcBounds(LocalToWorld); if (! IsUsingInGameBounds()) { // extend bounds by bones but without root bone FBox BoundingBox(0); const int32 NumBones = GetNumSpaceBases(); for (int32 BoneIndex = 1; BoneIndex < NumBones; ++BoneIndex) { BoundingBox += GetBoneMatrix(BoneIndex).GetOrigin(); } Result = Result + FBoxSphereBounds(BoundingBox); } return Result; }
void UPoseableMeshComponent::RefreshBoneTransforms(FActorComponentTickFunction* TickFunction) { SCOPE_CYCLE_COUNTER(STAT_RefreshBoneTransforms); // Can't do anything without a SkeletalMesh if( !SkeletalMesh ) { return; } // Do nothing more if no bones in skeleton. if( GetNumSpaceBases() == 0 ) { return; } // We need the mesh space bone transforms now for renderer to get delta from ref pose: FillSpaceBases(); FlipEditableSpaceBases(); MarkRenderDynamicDataDirty(); }
void UPhATEdSkeletalMeshComponent::DrawHierarchy(FPrimitiveDrawInterface* PDI, bool bAnimSkel) { for (int32 i=1; i<GetNumSpaceBases(); ++i) { int32 ParentIndex = SkeletalMesh->RefSkeleton.GetParentIndex(i); FVector ParentPos, ChildPos; if (bAnimSkel) { ParentPos = ComponentToWorld.TransformPosition(AnimationSpaceBases[ParentIndex].GetLocation()); ChildPos = ComponentToWorld.TransformPosition(AnimationSpaceBases[i].GetLocation()); } else { ParentPos = ComponentToWorld.TransformPosition(GetSpaceBases()[ParentIndex].GetLocation()); ChildPos = ComponentToWorld.TransformPosition(GetSpaceBases()[i].GetLocation()); } FColor DrawColor = bAnimSkel ? AnimSkelDrawColor : HierarchyDrawColor; PDI->DrawLine(ParentPos, ChildPos, DrawColor, SDPG_Foreground); } }
void USkeletalMeshComponent::UpdateKinematicBonesToAnim(const TArray<FTransform>& InSpaceBases, ETeleportType Teleport, bool bNeedsSkinning) { SCOPE_CYCLE_COUNTER(STAT_UpdateRBBones); // This below code produces some interesting result here // - below codes update physics data, so if you don't update pose, the physics won't have the right result // - but if we just update physics bone without update current pose, it will have stale data // If desired, pass the animation data to the physics joints so they can be used by motors. // See if we are going to need to update kinematics const bool bUpdateKinematics = (KinematicBonesUpdateType != EKinematicBonesUpdateToPhysics::SkipAllBones); const bool bTeleport = Teleport == ETeleportType::TeleportPhysics; // If desired, update physics bodies associated with skeletal mesh component to match. if(!bUpdateKinematics && !(bTeleport && IsAnySimulatingPhysics())) { // nothing to do return; } // Get the scene, and do nothing if we can't get one. FPhysScene* PhysScene = nullptr; if (GetWorld() != nullptr) { PhysScene = GetWorld()->GetPhysicsScene(); } if(PhysScene == nullptr) { return; } const FTransform& CurrentLocalToWorld = ComponentToWorld; // Gracefully handle NaN if(CurrentLocalToWorld.ContainsNaN()) { return; } // If desired, draw the skeleton at the point where we pass it to the physics. if (bShowPrePhysBones && SkeletalMesh && InSpaceBases.Num() == SkeletalMesh->RefSkeleton.GetNum()) { for (int32 i = 1; i<InSpaceBases.Num(); i++) { FVector ThisPos = CurrentLocalToWorld.TransformPosition(InSpaceBases[i].GetLocation()); int32 ParentIndex = SkeletalMesh->RefSkeleton.GetParentIndex(i); FVector ParentPos = CurrentLocalToWorld.TransformPosition(InSpaceBases[ParentIndex].GetLocation()); GetWorld()->LineBatcher->DrawLine(ThisPos, ParentPos, AnimSkelDrawColor, SDPG_Foreground); } } // warn if it has non-uniform scale const FVector& MeshScale3D = CurrentLocalToWorld.GetScale3D(); #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) if( !MeshScale3D.IsUniform() ) { UE_LOG(LogPhysics, Log, TEXT("USkeletalMeshComponent::UpdateKinematicBonesToAnim : Non-uniform scale factor (%s) can cause physics to mismatch for %s SkelMesh: %s"), *MeshScale3D.ToString(), *GetFullName(), SkeletalMesh ? *SkeletalMesh->GetFullName() : TEXT("NULL")); } #endif if (bEnablePerPolyCollision == false) { const UPhysicsAsset* const PhysicsAsset = GetPhysicsAsset(); if (PhysicsAsset && SkeletalMesh && Bodies.Num() > 0) { #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) if (!ensure(PhysicsAsset->BodySetup.Num() == Bodies.Num())) { // related to TTP 280315 UE_LOG(LogPhysics, Warning, TEXT("Mesh (%s) has PhysicsAsset(%s), and BodySetup(%d) and Bodies(%d) don't match"), *SkeletalMesh->GetName(), *PhysicsAsset->GetName(), PhysicsAsset->BodySetup.Num(), Bodies.Num()); return; } #endif #if WITH_PHYSX // Lock the scenes we need (flags set in InitArticulated) if(bHasBodiesInSyncScene) { SCENE_LOCK_WRITE(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_LOCK_WRITE(PhysScene->GetPhysXScene(PST_Async)) } #endif // Iterate over each body for (int32 i = 0; i < Bodies.Num(); i++) { // If we have a physics body, and its kinematic... FBodyInstance* BodyInst = Bodies[i]; check(BodyInst); if (bTeleport || (BodyInst->IsValidBodyInstance() && !BodyInst->IsInstanceSimulatingPhysics())) { const int32 BoneIndex = BodyInst->InstanceBoneIndex; // If we could not find it - warn. if (BoneIndex == INDEX_NONE || BoneIndex >= GetNumSpaceBases()) { const FName BodyName = PhysicsAsset->BodySetup[i]->BoneName; UE_LOG(LogPhysics, Log, TEXT("UpdateRBBones: WARNING: Failed to find bone '%s' need by PhysicsAsset '%s' in SkeletalMesh '%s'."), *BodyName.ToString(), *PhysicsAsset->GetName(), *SkeletalMesh->GetName()); } else { #if WITH_PHYSX // update bone transform to world const FTransform BoneTransform = InSpaceBases[BoneIndex] * CurrentLocalToWorld; if(BoneTransform.ContainsNaN()) { const FName BodyName = PhysicsAsset->BodySetup[i]->BoneName; UE_LOG(LogPhysics, Warning, TEXT("UpdateKinematicBonesToAnim: Trying to set transform with bad data %s on PhysicsAsset '%s' in SkeletalMesh '%s' for bone '%s'"), *BoneTransform.ToHumanReadableString(), *PhysicsAsset->GetName(), *SkeletalMesh->GetName(), *BodyName.ToString()); continue; } // If kinematic and not teleporting, set kinematic target PxRigidDynamic* PRigidDynamic = BodyInst->GetPxRigidDynamic_AssumesLocked(); if (!IsRigidBodyNonKinematic_AssumesLocked(PRigidDynamic) && !bTeleport) { PhysScene->SetKinematicTarget_AssumesLocked(BodyInst, BoneTransform, true); } // Otherwise, set global pose else { const PxTransform PNewPose = U2PTransform(BoneTransform); ensure(PNewPose.isValid()); PRigidDynamic->setGlobalPose(PNewPose); } #endif // now update scale // if uniform, we'll use BoneTranform if (MeshScale3D.IsUniform()) { // @todo UE4 should we update scale when it's simulated? BodyInst->UpdateBodyScale(BoneTransform.GetScale3D()); } else { // @note When you have non-uniform scale on mesh base, // hierarchical bone transform can update scale too often causing performance issue // So we just use mesh scale for all bodies when non-uniform // This means physics representation won't be accurate, but // it is performance friendly by preventing too frequent physics update BodyInst->UpdateBodyScale(MeshScale3D); } } } else { //make sure you have physics weight or blendphysics on, otherwise, you'll have inconsistent representation of bodies // @todo make this to be kismet log? But can be too intrusive if (!bBlendPhysics && BodyInst->PhysicsBlendWeight <= 0.f && BodyInst->BodySetup.IsValid()) { UE_LOG(LogPhysics, Warning, TEXT("%s(Mesh %s, PhysicsAsset %s, Bone %s) is simulating, but no blending. "), *GetName(), *GetNameSafe(SkeletalMesh), *GetNameSafe(PhysicsAsset), *BodyInst->BodySetup.Get()->BoneName.ToString()); } } } #if WITH_PHYSX // Unlock the scenes if (bHasBodiesInSyncScene) { SCENE_UNLOCK_WRITE(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_UNLOCK_WRITE(PhysScene->GetPhysXScene(PST_Async)) } #endif } } else { //per poly update requires us to update all vertex positions if (MeshObject)
void USkeletalMeshComponent::PerformBlendPhysicsBones(const TArray<FBoneIndexType>& InRequiredBones, TArray<FTransform>& InLocalAtoms) { // Get drawscale from Owner (if there is one) FVector TotalScale3D = ComponentToWorld.GetScale3D(); FVector RecipScale3D = TotalScale3D.Reciprocal(); UPhysicsAsset * const PhysicsAsset = GetPhysicsAsset(); check( PhysicsAsset ); if (GetNumSpaceBases() == 0) { return; } // Get the scene, and do nothing if we can't get one. FPhysScene* PhysScene = nullptr; if (GetWorld() != nullptr) { PhysScene = GetWorld()->GetPhysicsScene(); } if (PhysScene == nullptr) { return; } // Make sure scratch space is big enough. TArray<FAssetWorldBoneTM> WorldBoneTMs; WorldBoneTMs.Reset(); WorldBoneTMs.AddZeroed(GetNumSpaceBases()); FTransform LocalToWorldTM = ComponentToWorld; LocalToWorldTM.RemoveScaling(); TArray<FTransform>& EditableSpaceBases = GetEditableSpaceBases(); struct FBodyTMPair { FBodyInstance* BI; FTransform TM; }; TArray<FBodyTMPair> PendingBodyTMs; #if WITH_PHYSX // Lock the scenes we need (flags set in InitArticulated) if (bHasBodiesInSyncScene) { SCENE_LOCK_READ(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_LOCK_READ(PhysScene->GetPhysXScene(PST_Async)) } #endif // For each bone - see if we need to provide some data for it. for(int32 i=0; i<InRequiredBones.Num(); i++) { int32 BoneIndex = InRequiredBones[i]; // See if this is a physics bone.. int32 BodyIndex = PhysicsAsset ? PhysicsAsset->FindBodyIndex(SkeletalMesh->RefSkeleton.GetBoneName(BoneIndex)) : INDEX_NONE; // need to update back to physX so that physX knows where it was after blending bool bUpdatePhysics = false; FBodyInstance* BodyInstance = NULL; // If so - get its world space matrix and its parents world space matrix and calc relative atom. if(BodyIndex != INDEX_NONE ) { #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) // tracking down TTP 280421. Remove this if this doesn't happen. if ( !ensure(Bodies.IsValidIndex(BodyIndex)) ) { UE_LOG(LogPhysics, Warning, TEXT("%s(Mesh %s, PhysicsAsset %s)"), *GetName(), *GetNameSafe(SkeletalMesh), *GetNameSafe(PhysicsAsset)); if ( PhysicsAsset ) { UE_LOG(LogPhysics, Warning, TEXT(" - # of BodySetup (%d), # of Bodies (%d), Invalid BodyIndex(%d)"), PhysicsAsset->BodySetup.Num(), Bodies.Num(), BodyIndex); } continue; } #endif BodyInstance = Bodies[BodyIndex]; //if simulated body copy back and blend with animation if(BodyInstance->IsInstanceSimulatingPhysics()) { FTransform PhysTM = BodyInstance->GetUnrealWorldTransform_AssumesLocked(); // Store this world-space transform in cache. WorldBoneTMs[BoneIndex].TM = PhysTM; WorldBoneTMs[BoneIndex].bUpToDate = true; float UsePhysWeight = (bBlendPhysics)? 1.f : BodyInstance->PhysicsBlendWeight; // Find this bones parent matrix. FTransform ParentWorldTM; // if we wan't 'full weight' we just find if(UsePhysWeight > 0.f) { if(BoneIndex == 0) { ParentWorldTM = LocalToWorldTM; } else { // If not root, get parent TM from cache (making sure its up-to-date). int32 ParentIndex = SkeletalMesh->RefSkeleton.GetParentIndex(BoneIndex); UpdateWorldBoneTM(WorldBoneTMs, ParentIndex, this, LocalToWorldTM, TotalScale3D); ParentWorldTM = WorldBoneTMs[ParentIndex].TM; } // Then calc rel TM and convert to atom. FTransform RelTM = PhysTM.GetRelativeTransform(ParentWorldTM); RelTM.RemoveScaling(); FQuat RelRot(RelTM.GetRotation()); FVector RelPos = RecipScale3D * RelTM.GetLocation(); FTransform PhysAtom = FTransform(RelRot, RelPos, InLocalAtoms[BoneIndex].GetScale3D()); // Now blend in this atom. See if we are forcing this bone to always be blended in InLocalAtoms[BoneIndex].Blend( InLocalAtoms[BoneIndex], PhysAtom, UsePhysWeight ); if(BoneIndex == 0) { //We must update RecipScale3D based on the atom scale of the root TotalScale3D *= InLocalAtoms[0].GetScale3D(); RecipScale3D = TotalScale3D.Reciprocal(); } if (UsePhysWeight < 1.f) { bUpdatePhysics = true; } } } } // Update SpaceBases entry for this bone now if( BoneIndex == 0 ) { EditableSpaceBases[0] = InLocalAtoms[0]; } else { const int32 ParentIndex = SkeletalMesh->RefSkeleton.GetParentIndex(BoneIndex); EditableSpaceBases[BoneIndex] = InLocalAtoms[BoneIndex] * EditableSpaceBases[ParentIndex]; /** * Normalize rotations. * We want to remove any loss of precision due to accumulation of error. * i.e. A componentSpace transform is the accumulation of all of its local space parents. The further down the chain, the greater the error. * SpaceBases are used by external systems, we feed this to PhysX, send this to gameplay through bone and socket queries, etc. * So this is a good place to make sure all transforms are normalized. */ EditableSpaceBases[BoneIndex].NormalizeRotation(); } if (bUpdatePhysics && BodyInstance) { //This is extremely inefficient. We need to obtain a write lock which will block other threads from blending //For now I'm juts deferring it to the end of this loop, but in general we need to move it all out of here and do it when the blend task is done FBodyTMPair* BodyTMPair = new (PendingBodyTMs) FBodyTMPair; BodyTMPair->BI = BodyInstance; BodyTMPair->TM = EditableSpaceBases[BoneIndex] * ComponentToWorld; } } #if WITH_PHYSX //See above for read lock instead of write lock // Unlock the scenes if (bHasBodiesInSyncScene) { SCENE_UNLOCK_READ(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_UNLOCK_READ(PhysScene->GetPhysXScene(PST_Async)) } if(PendingBodyTMs.Num()) { //This is extremely inefficient. We need to obtain a write lock which will block other threads from blending //For now I'm juts deferring it to the end of this loop, but in general we need to move it all out of here and do it when the blend task is done if (bHasBodiesInSyncScene) { SCENE_LOCK_WRITE(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_LOCK_WRITE(PhysScene->GetPhysXScene(PST_Async)) } for (const FBodyTMPair& BodyTMPair : PendingBodyTMs) { BodyTMPair.BI->SetBodyTransform(BodyTMPair.TM, ETeleportType::TeleportPhysics); } if (bHasBodiesInSyncScene) { SCENE_UNLOCK_WRITE(PhysScene->GetPhysXScene(PST_Sync)) } if (bHasBodiesInAsyncScene) { SCENE_UNLOCK_WRITE(PhysScene->GetPhysXScene(PST_Async)) } } #endif // Transforms updated, cached local bounds are now out of date. InvalidateCachedBounds(); }