BVB Source Codes

CRYENGINE Show CharacterInstance.cpp Source code

Return Download CRYENGINE: download CharacterInstance.cpp Source code - Download CRYENGINE Source code - Type:.cpp
  1. // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
  2.  
  3. #include "stdafx.h"
  4. #include "CharacterInstance.h"
  5.  
  6. #include "ModelMesh.h"
  7. #include "CharacterManager.h"
  8. #include <CryRenderer/IRenderAuxGeom.h>
  9. #include "FacialAnimation/FacialInstance.h"
  10. #include <CryMath/GeomQuery.h>
  11. #include <CryThreading/IJobManager_JobDelegator.h>
  12. #include "Vertex/VertexCommandBuffer.h"
  13.  
  14. DECLARE_JOB("SkinningTransformationsComputation", TSkinningTransformationsComputation, CCharInstance::SkinningTransformationsComputation);
  15.  
  16. CCharInstance::CCharInstance(const string& strFileName, CDefaultSkeleton* pDefaultSkeleton) : m_skinningTransformationsCount(0), m_skinningTransformationsMovement(0)
  17. {
  18.         LOADING_TIME_PROFILE_SECTION(g_pISystem);
  19.         MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "Character Instance");
  20.  
  21.         g_pCharacterManager->RegisterInstanceSkel(pDefaultSkeleton, this);
  22.         m_pDefaultSkeleton = pDefaultSkeleton;
  23.         m_strFilePath = strFileName;
  24.  
  25.         m_CharEditMode = 0;
  26.         m_nRefCounter = 0;
  27.         m_nAnimationLOD = 0;
  28.         m_LastRenderedFrameID = 0;
  29.         m_Viewdir = Vec3(0, 1, 0);
  30.  
  31.         m_fDeltaTime = 0;
  32.         m_fOriginalDeltaTime = 0;
  33.  
  34.         m_location.SetIdentity();
  35.  
  36.         m_AttachmentManager.m_pSkelInstance = this;
  37.  
  38.         m_fPostProcessZoomAdjustedDistanceFromCamera = 0;
  39.  
  40.         m_bHideMaster = false;
  41.         m_bWasVisible = false;
  42.         m_bPlayedPhysAnim = false;
  43.         m_bEnableStartAnimation = 1;
  44.  
  45.         m_fPlaybackScale = 1;
  46.         m_LastUpdateFrameID_Pre = 0;
  47.         m_LastUpdateFrameID_Post = 0;
  48.  
  49.         m_rpFlags = CS_FLAG_DRAW_MODEL;
  50.         memset(arrSkinningRendererData, 0, sizeof(arrSkinningRendererData));
  51.         m_processingContext = -1;
  52.         m_SkeletonAnim.InitSkeletonAnim(this, &this->m_SkeletonPose);
  53.         RuntimeInit(0);
  54. }
  55.  
  56. //--------------------------------------------------------------------------------------------
  57. //--          re-initialize all members related to CDefaultSkeleton
  58. //--------------------------------------------------------------------------------------------
  59. void CCharInstance::RuntimeInit(CDefaultSkeleton* pExtDefaultSkeleton)
  60. {
  61.         for (uint32 i = 0; i < 3; i++)
  62.         {
  63.                 if (arrSkinningRendererData[i].pSkinningData)
  64.                 {
  65.                         if (arrSkinningRendererData[i].pSkinningData->pPreviousSkinningRenderData->pAsyncJobs)
  66.                                 gEnv->pJobManager->WaitForJob(*arrSkinningRendererData[i].pSkinningData->pPreviousSkinningRenderData->pAsyncJobs);
  67.                 }
  68.         }
  69.         memset(arrSkinningRendererData, 0, sizeof(arrSkinningRendererData));
  70.         m_SkeletonAnim.FinishAnimationComputations();
  71.  
  72.         //-----------------------------------------------
  73.         if (pExtDefaultSkeleton)
  74.         {
  75.                 g_pCharacterManager->UnregisterInstanceSkel(m_pDefaultSkeleton, this);
  76.                 g_pCharacterManager->RegisterInstanceSkel(pExtDefaultSkeleton, this);
  77.                 m_pDefaultSkeleton = pExtDefaultSkeleton;
  78.         }
  79.  
  80.         uint32 numJoints = m_pDefaultSkeleton->m_arrModelJoints.size();
  81.         m_skinningTransformationsCount = 0;
  82.         m_skinningTransformationsMovement = 0;
  83.         if (m_pDefaultSkeleton->m_ObjectType == CHR)
  84.                 m_skinningTransformationsCount = numJoints;
  85.  
  86.         m_SkeletonAnim.m_facialDisplaceInfo.Initialize(0);
  87.         m_bFacialAnimationEnabled = true;
  88.  
  89.         if (m_pDefaultSkeleton->GetFacialModel())
  90.         {
  91.                 m_pFacialInstance = new CFacialInstance(m_pDefaultSkeleton->GetFacialModel(), this);
  92.         }
  93.  
  94.         m_SkeletonPose.InitSkeletonPose(this, &this->m_SkeletonAnim);
  95.  
  96.         //
  97.         m_SkeletonPose.UpdateBBox(1);
  98.         m_SkeletonPose.m_physics.m_bHasPhysics = m_pDefaultSkeleton->m_bHasPhysics2;
  99.         m_SkeletonPose.m_physics.m_bHasPhysicsProxies = false;
  100.  
  101.         m_bHasVertexAnimation = false;
  102. }
  103.  
  104. //////////////////////////////////////////////////////////////////////////
  105. CCharInstance::~CCharInstance()
  106. {
  107.         // The command buffer needs to be flushed here, because if he is flushed
  108.         // later on, one of the commands might access the
  109.         // default skeleton which is no longer available
  110.         m_AttachmentManager.UpdateBindings();
  111.  
  112.         assert(m_nRefCounter == 0);
  113.         m_SkeletonPose.m_physics.DestroyPhysics();
  114.         KillAllSkeletonEffects();
  115.  
  116.         WaitForSkinningJob();
  117.  
  118.         const char* pFilePath = GetFilePath();
  119.         g_pCharacterManager->ReleaseCDF(pFilePath);
  120.  
  121.         if (m_pDefaultSkeleton)
  122.                 g_pCharacterManager->UnregisterInstanceSkel(m_pDefaultSkeleton, this);
  123. }
  124.  
  125. //-------------------------------------------------------------------------
  126. //-------------------------------------------------------------------------
  127. //-------------------------------------------------------------------------
  128.  
  129. void CCharInstance::StartAnimationProcessing(const SAnimationProcessParams& params)
  130. {
  131.         DEFINE_PROFILER_FUNCTION();
  132.         ANIMATION_LIGHT_PROFILER();
  133.  
  134.         // execute only if start animation processing has not been started for this character
  135.         if (GetProcessingContext())
  136.                 return;
  137.  
  138.         CharacterInstanceProcessing::CContextQueue& queue = g_pCharacterManager->GetContextSyncQueue();
  139.  
  140.         // generate contexts for me and all my attached instances
  141.         CharacterInstanceProcessing::SContext& ctx = queue.AppendContext();
  142.         m_processingContext = ctx.slot;
  143.         int numberOfChildren = m_AttachmentManager.GenerateAttachedInstanceContexts();
  144.         ctx.Initialize(this, nullptr, nullptr, numberOfChildren);
  145.         queue.ExecuteForContextAndAllChildrenRecursively(
  146.           m_processingContext, CharacterInstanceProcessing::SStartAnimationProcessing(params));
  147.  
  148.         bool bImmediate = (Console::GetInst().ca_thread == 0);
  149.  
  150.         WaitForSkinningJob();
  151.         ctx.job.Begin(bImmediate);
  152.  
  153.         if (bImmediate)
  154.         {
  155.                 m_SkeletonAnim.FinishAnimationComputations();
  156.         }
  157. }
  158.  
  159. //////////////////////////////////////////////////////////////////////////
  160. void CCharInstance::CopyPoseFrom(const ICharacterInstance& rICharInstance)
  161. {
  162.         const ISkeletonPose* srcIPose = rICharInstance.GetISkeletonPose();
  163.         const IDefaultSkeleton& rIDefaultSkeleton = rICharInstance.GetIDefaultSkeleton();
  164.  
  165.         CRY_ASSERT_TRACE(srcIPose, ("CopyPoseFrom: %s Copying from an invalid pose!", GetFilePath()));
  166.         if (srcIPose)
  167.         {
  168.                 CRY_ASSERT_TRACE(m_pDefaultSkeleton->GetJointCount() == rIDefaultSkeleton.GetJointCount(), ("CopyPoseFrom: %s Joint count mismatch %d vs %d", GetFilePath(), rIDefaultSkeleton.GetJointCount(), m_pDefaultSkeleton->GetJointCount()));
  169.  
  170.                 const CSkeletonPose* srcPose = (CSkeletonPose*)srcIPose;
  171.                 m_SkeletonPose.GetPoseDataForceWriteable().Initialize(srcPose->GetPoseData());
  172.         }
  173. }
  174.  
  175. //////////////////////////////////////////////////////////////////////////
  176. // TODO: Should be part of CSkeletonPhysics!
  177. void CCharInstance::UpdatePhysicsCGA(Skeleton::CPoseData& poseData, float fScale, const QuatTS& rAnimLocationNext)
  178. {
  179.         DEFINE_PROFILER_FUNCTION();
  180.         CAnimationSet* pAnimationSet = m_pDefaultSkeleton->m_pAnimationSet;
  181.  
  182.         if (!m_SkeletonPose.GetCharacterPhysics())
  183.                 return;
  184.  
  185.         if (m_fOriginalDeltaTime <= 0.0f)
  186.                 return;
  187.  
  188.         QuatT* const __restrict pAbsolutePose = poseData.GetJointsAbsolute();
  189.  
  190.         pe_params_part params;
  191.         pe_action_set_velocity asv;
  192.         pe_status_pos sp;
  193.         int numNodes = poseData.GetJointCount();
  194.         assert(numNodes);
  195.  
  196.         int i, iLayer, iLast = -1;
  197.         bool bSetVel = 0;
  198.         uint32 nType = m_SkeletonPose.GetCharacterPhysics()->GetType();
  199.         bool bBakeRotation = m_SkeletonPose.GetCharacterPhysics()->GetType() == PE_ARTICULATED;
  200.         if (bSetVel = bBakeRotation)
  201.         {
  202.                 for (iLayer = 0; iLayer < numVIRTUALLAYERS && m_SkeletonAnim.GetNumAnimsInFIFO(iLayer) == 0; iLayer++)
  203.                         ;
  204.                 bSetVel = iLayer < numVIRTUALLAYERS;
  205.         }
  206.         params.bRecalcBBox = false;
  207.  
  208.         for (i = 0; i < numNodes; i++)
  209.         {
  210. SetAgain:
  211.                 if (m_SkeletonPose.m_physics.m_ppBonePhysics && m_SkeletonPose.m_physics.m_ppBonePhysics[i])
  212.                 {
  213.                         sp.ipart = 0;
  214.                         MARK_UNUSED sp.partid;
  215.                         m_SkeletonPose.m_physics.m_ppBonePhysics[i]->GetStatus(&sp);
  216.                         pAbsolutePose[i].q = !rAnimLocationNext.q * sp.q;
  217.                         pAbsolutePose[i].t = !rAnimLocationNext.q * (sp.pos - rAnimLocationNext.t);
  218.                         continue;
  219.                 }
  220.                 if (m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID == ~0)
  221.                         continue;
  222.                 //      params.partid = joint->m_nodeid;
  223.                 params.partid = m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID;
  224.  
  225.                 assert(pAbsolutePose[i].IsValid());
  226.                 params.q = pAbsolutePose[i].q;
  227.  
  228.                 params.pos = pAbsolutePose[i].t * rAnimLocationNext.s;
  229.                 if (rAnimLocationNext.s != 1.0f)
  230.                         params.scale = rAnimLocationNext.s;
  231.  
  232.                 if (bBakeRotation)
  233.                 {
  234.                         params.pos = rAnimLocationNext.q * params.pos;
  235.                         params.q = rAnimLocationNext.q * params.q;
  236.                 }
  237.                 if (m_SkeletonPose.GetCharacterPhysics()->SetParams(&params))
  238.                         iLast = i;
  239.                 if (params.bRecalcBBox)
  240.                         break;
  241.         }
  242.  
  243.         // Recompute box after.
  244.         if (iLast >= 0 && !params.bRecalcBBox)
  245.         {
  246.                 params.bRecalcBBox = true;
  247.                 i = iLast;
  248.                 goto SetAgain;
  249.         }
  250.  
  251.         if (bSetVel)
  252.         {
  253.                 ApplyJointVelocitiesToPhysics(m_SkeletonPose.GetCharacterPhysics(), rAnimLocationNext.q);
  254.                 m_bPlayedPhysAnim = true;
  255.         }
  256.         else if (bBakeRotation && m_bPlayedPhysAnim)
  257.         {
  258.                 asv.v.zero();
  259.                 asv.w.zero();
  260.                 for (i = 0; i < numNodes; i++)
  261.                         if ((asv.partid = m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID) != ~0)
  262.                                 m_SkeletonPose.GetCharacterPhysics()->Action(&asv);
  263.                 m_bPlayedPhysAnim = false;
  264.         }
  265.  
  266.         if (m_SkeletonPose.m_physics.m_ppBonePhysics)
  267.                 m_SkeletonPose.UpdateBBox(1);
  268. }
  269.  
  270. void CCharInstance::ApplyJointVelocitiesToPhysics(IPhysicalEntity* pent, const Quat& qrot, const Vec3& velHost)
  271. {
  272.         int i, iParent, numNodes = m_SkeletonPose.GetPoseData().GetJointCount();
  273.         QuatT qParent;
  274.         IController* pController;
  275.         float t, dt;
  276.         pe_action_set_velocity asv;
  277.         CAnimationSet* pAnimationSet = m_pDefaultSkeleton->m_pAnimationSet;
  278.  
  279.         PREFAST_SUPPRESS_WARNING(6255)
  280.         QuatT * qAnimCur = (QuatT*)alloca(numNodes * sizeof(QuatT));
  281.         PREFAST_SUPPRESS_WARNING(6255)
  282.         QuatT * qAnimNext = (QuatT*)alloca(numNodes * sizeof(QuatT));
  283.         for (i = 0; i < numNodes; i++)
  284.                 qAnimCur[i] = qAnimNext[i] = m_SkeletonPose.GetPoseData().GetJointRelative(i);
  285.  
  286.         if (!m_SkeletonAnim.m_layers[0].m_transitionQueue.m_animations.size())
  287.         {
  288.                 for (i = 0; i < numNodes; i++)
  289.                         if (m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID != ~0)
  290.                         {
  291.                                 asv.partid = m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID;
  292.                                 asv.v = velHost;
  293.                                 pent->Action(&asv);
  294.                         }
  295.                 return;
  296.         }
  297.         const CAnimation& anim = m_SkeletonAnim.GetAnimFromFIFO(0, 0);
  298.  
  299.         int idGlobal = pAnimationSet->GetGlobalIDByAnimID_Fast(anim.GetAnimationId());
  300.         GlobalAnimationHeaderCAF& animHdr = g_AnimationManager.m_arrGlobalCAF[idGlobal];
  301.  
  302.         const float FRAME_TIME = 0.01f;
  303.         const float fAnimDuration = max(anim.GetExpectedTotalDurationSeconds(), 1e-5f);
  304.         dt = static_cast<float>(__fsel(fAnimDuration - FRAME_TIME, FRAME_TIME / fAnimDuration, 1.0f));
  305.         t = min(1.0f - dt, m_SkeletonAnim.GetAnimationNormalizedTime(&anim));
  306.  
  307.         for (i = 0; i < numNodes; i++)
  308.                 if (pController = animHdr.GetControllerByJointCRC32(m_pDefaultSkeleton->m_arrModelJoints[i].m_nJointCRC32))                        //m_pDefaultSkeleton->m_arrModelJoints[i].m_arrControllersMJoint[idAnim])
  309.                         pController->GetOP(animHdr.NTime2KTime(t), qAnimCur[i].q, qAnimCur[i].t),
  310.                         pController->GetOP(animHdr.NTime2KTime(t + dt), qAnimNext[i].q, qAnimNext[i].t);
  311.  
  312.         for (i = 0; i < numNodes; i++)
  313.                 if ((iParent = m_pDefaultSkeleton->m_arrModelJoints[i].m_idxParent) >= 0 && iParent != i)
  314.                 {
  315.                         PREFAST_ASSUME(iParent >= 0 && iParent < numNodes);
  316.                         qAnimCur[i] = qAnimCur[iParent] * qAnimCur[i], qAnimNext[i] = qAnimNext[iParent] * qAnimNext[i];
  317.                 }
  318.  
  319.         const float INV_FRAME_TIME = 1.0f / FRAME_TIME;
  320.         for (i = 0; i < numNodes; i++)
  321.                 if (m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID != ~0)
  322.                 {
  323.                         asv.partid = m_pDefaultSkeleton->m_arrModelJoints[i].m_NodeID;
  324.                         asv.v = qrot * ((qAnimNext[i].t - qAnimCur[i].t) * INV_FRAME_TIME) + velHost;
  325.                         Quat dq = qAnimNext[i].q * !qAnimCur[i].q;
  326.                         float sin2 = dq.v.len();
  327.                         asv.w = qrot * (sin2 > 0 ? dq.v * (atan2_tpl(sin2 * dq.w * 2, dq.w * dq.w - sin2 * sin2) * INV_FRAME_TIME / sin2) : Vec3(0));
  328.                         pent->Action(&asv);
  329.                 }
  330. }
  331.  
  332. //----------------------------------------------------------------------
  333. //----------------------------------------------------------------------
  334. //----------------------------------------------------------------------
  335.  
  336. SMeshLodInfo CCharInstance::ComputeGeometricMean() const
  337. {
  338.         SMeshLodInfo lodInfo;
  339.         lodInfo.Clear();
  340.  
  341.         const int attachmentCount = m_AttachmentManager.GetAttachmentCount();
  342.         for (int i = 0; i < attachmentCount; ++i)
  343.         {
  344.                 const IAttachment* const pIAttachment = m_AttachmentManager.GetInterfaceByIndex(i);
  345.  
  346.                 if (pIAttachment != NULL && pIAttachment->GetIAttachmentObject() != NULL)
  347.                 {
  348.                         const IAttachmentObject* const pIAttachmentObject = pIAttachment->GetIAttachmentObject();
  349.                         SMeshLodInfo attachmentLodInfo;
  350.  
  351.                         if (pIAttachmentObject->GetIAttachmentSkin())
  352.                         {
  353.                                 attachmentLodInfo = pIAttachmentObject->GetIAttachmentSkin()->ComputeGeometricMean();
  354.                         }
  355.                         else if (pIAttachmentObject->GetIStatObj())
  356.                         {
  357.                                 attachmentLodInfo = pIAttachmentObject->GetIStatObj()->ComputeGeometricMean();
  358.                         }
  359.                         else if (pIAttachmentObject->GetICharacterInstance())
  360.                         {
  361.                                 attachmentLodInfo = pIAttachmentObject->GetICharacterInstance()->ComputeGeometricMean();
  362.                         }
  363.  
  364.                         lodInfo.Merge(attachmentLodInfo);
  365.                 }
  366.         }
  367.  
  368.         if (GetObjectType() == CGA)
  369.         {
  370.                 // joints
  371.                 if (ISkeletonPose* pSkeletonPose = const_cast<CCharInstance*>(this)->GetISkeletonPose())
  372.                 {
  373.                         uint32 numJoints = GetIDefaultSkeleton().GetJointCount();
  374.  
  375.                         // check StatObj attachments
  376.                         for (uint32 i = 0; i < numJoints; i++)
  377.                         {
  378.                                 IStatObj* pStatObj = pSkeletonPose->GetStatObjOnJoint(i);
  379.                                 if (pStatObj)
  380.                                 {
  381.                                         SMeshLodInfo attachmentLodInfo = pStatObj->ComputeGeometricMean();
  382.  
  383.                                         lodInfo.Merge(attachmentLodInfo);
  384.                                 }
  385.                         }
  386.                 }
  387.         }
  388.  
  389.         return lodInfo;
  390. }
  391.  
  392. phys_geometry* CCharInstance::GetPhysGeom(int nType) const
  393. {
  394.         if (IPhysicalEntity* pPhysics = m_SkeletonPose.GetCharacterPhysics())
  395.         {
  396.                 pe_params_part part;
  397.                 part.ipart = 0;
  398.                 if (pPhysics->GetParams(&part))
  399.                         return part.pPhysGeom;
  400.         }
  401.         return NULL;
  402. }
  403.  
  404. IPhysicalEntity* CCharInstance::GetPhysEntity() const
  405. {
  406.         IPhysicalEntity* pPhysics = m_SkeletonPose.GetCharacterPhysics();
  407.         if (!pPhysics)
  408.                 pPhysics = m_SkeletonPose.GetCharacterPhysics(0);
  409.         return pPhysics;
  410. }
  411.  
  412. float CCharInstance::GetExtent(EGeomForm eForm)
  413. {
  414.         // Sum extents from base mesh, CGA joints, and attachments.
  415.         CGeomExtent& extent = m_Extents.Make(eForm);
  416.  
  417.         extent.Clear();
  418.         extent.ReserveParts(3);
  419.  
  420.         // Add base model as first part.
  421.         float fModelExt = 0.f;
  422.         if (m_pDefaultSkeleton)
  423.         {
  424.                 if (IRenderMesh* pMesh = m_pDefaultSkeleton->GetIRenderMesh())
  425.                         fModelExt = pMesh->GetExtent(eForm);
  426.         }
  427.         extent.AddPart(fModelExt);
  428.  
  429.         extent.AddPart(m_SkeletonPose.GetExtent(eForm));
  430.         extent.AddPart(m_AttachmentManager.GetExtent(eForm));
  431.  
  432.         return extent.TotalExtent();
  433. }
  434.  
  435. void CCharInstance::GetRandomPos(PosNorm& ran, CRndGen& seed, EGeomForm eForm) const
  436. {
  437.         CGeomExtent const& ext = m_Extents[eForm];
  438.         int iPart = ext.RandomPart(seed);
  439.  
  440.         if (iPart-- == 0)
  441.         {
  442.                 // Base model.
  443.                 IRenderMesh* pMesh = m_pDefaultSkeleton->GetIRenderMesh();
  444.  
  445.                 SSkinningData* pSkinningData = NULL;
  446.                 int nFrameID = gEnv->pRenderer->EF_GetSkinningPoolID();
  447.                 for (int n = 0; n < 3; n++)
  448.                 {
  449.                         int nList = (nFrameID - n) % 3;
  450.                         if (arrSkinningRendererData[nList].nFrameID == nFrameID - n)
  451.                         {
  452.                                 pSkinningData = arrSkinningRendererData[nList].pSkinningData;
  453.                                 break;
  454.                         }
  455.                 }
  456.  
  457.                 return pMesh->GetRandomPos(ran, seed, eForm, pSkinningData);
  458.         }
  459.  
  460.         if (iPart-- == 0)
  461.         {
  462.                 // Choose CGA joint.
  463.                 return m_SkeletonPose.GetRandomPos(ran, seed, eForm);
  464.         }
  465.  
  466.         if (iPart-- == 0)
  467.         {
  468.                 // Choose attachment.
  469.                 return m_AttachmentManager.GetRandomPos(ran, seed, eForm);
  470.         }
  471.  
  472.         ran.zero();
  473. }
  474.  
  475. void CCharInstance::OnDetach()
  476. {
  477.         pe_params_rope pr;
  478.         pr.pEntTiedTo[0] = pr.pEntTiedTo[1] = 0;
  479.         m_SkeletonPose.m_physics.SetAuxParams(&pr);
  480. }
  481.  
  482. // Skinning
  483.  
  484. void CCharInstance::BeginSkinningTransformationsComputation(SSkinningData* pSkinningData)
  485. {
  486.         if (m_pDefaultSkeleton->m_ObjectType == CHR)
  487.         {
  488.                 assert(pSkinningData->pMasterSkinningDataList);
  489.                 *pSkinningData->pMasterSkinningDataList = SKINNING_TRANSFORMATION_RUNNING_INDICATOR;
  490.  
  491.                 TSkinningTransformationsComputation job(pSkinningData, m_pDefaultSkeleton.get(), 0, &m_SkeletonPose.GetPoseData(), &m_skinningTransformationsMovement);
  492.                 job.SetClassInstance(this);
  493.                 job.RegisterJobState(pSkinningData->pAsyncJobs);
  494.                 job.SetPriorityLevel(JobManager::eHighPriority);
  495.                 job.Run();
  496.         }
  497. }
  498.  
  499. //////////////////////////////////////////////////////////////////////////
  500. void CCharInstance::Serialize(TSerialize ser)
  501. {
  502.         if (ser.GetSerializationTarget() != eST_Network)
  503.         {
  504.                 MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "Character instance serialization");
  505.  
  506.                 ser.BeginGroup("CCharInstance");
  507.                 ser.Value("fPlaybackScale", (float&)(m_fPlaybackScale));
  508.                 ser.EndGroup();
  509.  
  510.                 m_SkeletonAnim.Serialize(ser);
  511.                 m_AttachmentManager.Serialize(ser);
  512.  
  513.                 if (ser.IsReading())
  514.                 {
  515.                         // Make sure that serialized characters that are ragdoll are updated even if their physic entity is sleeping
  516.                         m_SkeletonPose.m_physics.m_bPhysicsWasAwake = true;
  517.                 }
  518.         }
  519. }
  520.  
  521. #ifdef EDITOR_PCDEBUGCODE
  522. void CCharInstance::DrawWireframeStatic(const Matrix34& m34, int nLOD, uint32 color)
  523. {
  524.         (void)nLOD; // TODO
  525.  
  526.         CModelMesh* pModelMesh = m_pDefaultSkeleton->GetModelMesh();
  527.         if (pModelMesh)
  528.         {
  529.                 pModelMesh->DrawWireframeStatic(m34, color);
  530.         }
  531. }
  532.  
  533. void CCharInstance::ReloadCHRPARAMS()
  534. {
  535.         g_pCharacterManager->StopAnimationsOnAllInstances(*GetIAnimationSet());
  536.         g_pCharacterManager->SyncAllAnimations();
  537.  
  538.         g_pCharacterManager->GetParamLoader().ClearLists();
  539.         m_pDefaultSkeleton->m_pAnimationSet->ReleaseAnimationData();
  540.         m_pDefaultSkeleton->SetModelAnimEventDatabase("");
  541.         string paramFileNameBase(m_pDefaultSkeleton->GetModelFilePath());
  542.         // Extended skeletons are identified with underscore prefix
  543.         if (!paramFileNameBase.empty() && paramFileNameBase[0] == '_')
  544.                 paramFileNameBase.erase(0, 1);
  545.         paramFileNameBase.replace(".chr", ".chrparams");
  546.         paramFileNameBase.replace(".cga", ".chrparams");
  547.         CryLog("Reloading %s", paramFileNameBase.c_str());
  548.         m_pDefaultSkeleton->m_pAnimationSet->NotifyListenersAboutReloadStarted();
  549.         m_pDefaultSkeleton->LoadCHRPARAMS(paramFileNameBase.c_str());
  550.         m_pDefaultSkeleton->m_pAnimationSet->NotifyListenersAboutReload();
  551.  
  552.         //--------------------------------------------------------------------------
  553.         //--- check if there is an attached SKEL and reload its list as well
  554.         //--------------------------------------------------------------------------
  555.         uint32 numAttachments = m_AttachmentManager.m_arrAttachments.size();
  556.         for (uint32 i = 0; i < numAttachments; i++)
  557.         {
  558.                 IAttachment* pIAttachment = m_AttachmentManager.m_arrAttachments[i];
  559.                 IAttachmentObject* pIAttachmentObject = pIAttachment->GetIAttachmentObject();
  560.                 if (pIAttachmentObject == 0)
  561.                         continue;
  562.  
  563.                 uint32 type = pIAttachment->GetType();
  564.                 CCharInstance* pCharInstance = (CCharInstance*)pIAttachmentObject->GetICharacterInstance();
  565.                 if (pCharInstance == 0)
  566.                         continue;  //its not a CHR at all
  567.  
  568.                 //reload Animation list for an attached character (attached SKELs are a rare case)
  569.                 g_pCharacterManager->GetParamLoader().ClearLists();
  570.                 m_pDefaultSkeleton->m_pAnimationSet->ReleaseAnimationData();
  571.                 string paramFileName(m_pDefaultSkeleton->GetModelFilePath());
  572.                 paramFileName.replace(".chr", ".chrparams");
  573.                 CryLog("Reloading %s", paramFileName.c_str());
  574.                 m_pDefaultSkeleton->m_pAnimationSet->NotifyListenersAboutReloadStarted();
  575.                 m_pDefaultSkeleton->LoadCHRPARAMS(paramFileName.c_str());
  576.                 m_pDefaultSkeleton->m_pAnimationSet->NotifyListenersAboutReload();
  577.         }
  578. }
  579. #endif
  580.  
  581. //////////////////////////////////////////////////////////////////////////
  582. IFacialInstance* CCharInstance::GetFacialInstance()
  583. {
  584.         return m_pFacialInstance;
  585. };
  586.  
  587. //////////////////////////////////////////////////////////////////////////
  588. const IFacialInstance* CCharInstance::GetFacialInstance() const
  589. {
  590.         return m_pFacialInstance;
  591. };
  592.  
  593. //////////////////////////////////////////////////////////////////////////
  594. void CCharInstance::EnableFacialAnimation(bool bEnable)
  595. {
  596.         m_bFacialAnimationEnabled = bEnable;
  597.  
  598.         for (int attachmentIndex = 0, end = int(m_AttachmentManager.m_arrAttachments.size()); attachmentIndex < end; ++attachmentIndex)
  599.         {
  600.                 IAttachment* pIAttachment = m_AttachmentManager.m_arrAttachments[attachmentIndex];
  601.                 IAttachmentObject* pIAttachmentObject = (pIAttachment ? pIAttachment->GetIAttachmentObject() : 0);
  602.                 ICharacterInstance* pIAttachmentCharacter = (pIAttachmentObject ? pIAttachmentObject->GetICharacterInstance() : 0);
  603.                 if (pIAttachmentCharacter)
  604.                         pIAttachmentCharacter->EnableFacialAnimation(bEnable);
  605.         }
  606. }
  607.  
  608. //////////////////////////////////////////////////////////////////////////
  609. void CCharInstance::EnableProceduralFacialAnimation(bool bEnable)
  610. {
  611.         IFacialInstance* pInst = GetFacialInstance();
  612.         if (pInst)
  613.                 pInst->EnableProceduralFacialAnimation(bEnable);
  614. }
  615.  
  616. void CCharInstance::SkeletonPostProcess()
  617. {
  618.         f32 fZoomAdjustedDistanceFromCamera = m_fPostProcessZoomAdjustedDistanceFromCamera;
  619.         QuatTS rPhysLocation = m_location;
  620.         m_SkeletonPose.SkeletonPostProcess(m_SkeletonPose.GetPoseDataExplicitWriteable());
  621.         m_skeletonEffectManager.Update(&m_SkeletonAnim, &m_SkeletonPose, rPhysLocation);
  622. };
  623.  
  624. void CCharInstance::SkinningTransformationsComputation(SSkinningData* pSkinningData, CDefaultSkeleton* pDefaultSkeleton, int nRenderLod, const Skeleton::CPoseData* pPoseData, f32* pSkinningTransformationsMovement)
  625. {
  626.         DEFINE_PROFILER_FUNCTION();
  627.         assert(pSkinningData->pBoneQuatsS);
  628.         assert(pSkinningData->pPreviousSkinningRenderData);
  629.         assert(pSkinningData->pPreviousSkinningRenderData->pBoneQuatsS);
  630.  
  631.         DualQuat* pSkinningTransformations = pSkinningData->pBoneQuatsS;
  632.         DualQuat* pSkinningTransformationsPrevious = pSkinningData->pPreviousSkinningRenderData->pBoneQuatsS;
  633.  
  634.         //      float fColor[4] = {1,0,0,1};
  635.         //      g_pAuxGeom->Draw2dLabel( 1,g_YLine, 1.3f, fColor, false,"SkinningTransformationsComputationTask" );
  636.         //      g_YLine+=16.0f;
  637.  
  638.         const QuatT* pJointsAbsolute = pPoseData->GetJointsAbsolute();
  639.         const QuatT* pJointsAbsoluteDefault = pDefaultSkeleton->m_poseDefaultData.GetJointsAbsolute();
  640.  
  641.         uint32 jointCount = pDefaultSkeleton->GetJointCount();
  642.         const CDefaultSkeleton::SJoint* pJoints = &pDefaultSkeleton->m_arrModelJoints[0];
  643.  
  644.         QuatT defaultInverse;
  645.         //--- Deliberate querying off the end of arrays for speed, prefetching off the end of an array is safe & avoids extra branches
  646.         const QuatT* absPose_PreFetchOnly = &pJointsAbsolute[0];
  647. #ifndef _DEBUG
  648.         CryPrefetch(&pJointsAbsoluteDefault[0]);
  649.         CryPrefetch(&absPose_PreFetchOnly[0]);
  650.         CryPrefetch(&pSkinningTransformations[0]);
  651.         CryPrefetch(&pJointsAbsoluteDefault[1]);
  652.         CryPrefetch(&absPose_PreFetchOnly[4]);
  653.         CryPrefetch(&pSkinningTransformations[4]);
  654. #endif
  655.         defaultInverse = pJointsAbsoluteDefault[0].GetInverted();
  656.         pSkinningTransformations[0] = pJointsAbsolute[0] * defaultInverse;
  657.         f32& movement = *pSkinningTransformationsMovement;
  658.         movement = 0.0f;
  659.         for (uint32 i = 1; i < jointCount; ++i)
  660.         {
  661. #ifndef _DEBUG
  662.                 CryPrefetch(&pJointsAbsoluteDefault[i + 1]);
  663.                 CryPrefetch(&absPose_PreFetchOnly[i + 4]);
  664.                 CryPrefetch(&pSkinningTransformations[i + 4]);
  665.                 CryPrefetch(&pJoints[i + 1].m_idxParent);
  666. #endif
  667.                 defaultInverse = pJointsAbsoluteDefault[i].GetInverted();
  668.  
  669.                 DualQuat& qd = pSkinningTransformations[i];
  670.                 qd = pJointsAbsolute[i] * defaultInverse;
  671.  
  672.                 int32 p = pJoints[i].m_idxParent;
  673.                 if (p > -1)
  674.                 {
  675.                         f32 cosine = qd.nq | pSkinningTransformations[p].nq;
  676.                         f32 mul = (f32)__fsel(cosine, 1.0f, -1.0f);
  677.                         qd.nq *= mul;
  678.                         qd.dq *= mul;
  679.                 }
  680.  
  681.                 const Quat& q0 = pSkinningTransformations[i].nq;
  682.                 const Quat& q1 = pSkinningTransformationsPrevious[i].nq;
  683.                 f32 fQdot = q0 | q1;
  684.                 f32 fQdotSign = (f32)__fsel(fQdot, 1.0f, -1.0f);
  685.                 movement += 1.0f - (fQdot * fQdotSign);
  686.         }
  687.  
  688.         CAttachmentManager* pAttachmentManager = static_cast<CAttachmentManager*>(GetIAttachmentManager());
  689.         const uint32 numJoints = pDefaultSkeleton->m_arrModelJoints.size();
  690.         const uint32 extraBonesCount = pAttachmentManager->GetExtraBonesCount();
  691.         for (uint32 i = 0; i < extraBonesCount; ++i)
  692.         {
  693.                 if (IAttachment* pAttachment = pAttachmentManager->m_extraBones[i])
  694.                 {
  695.                         if (pAttachment->IsMerged())
  696.                         {
  697.                                 if (pAttachment->GetType() == CA_FACE || (pAttachment->GetType() == CA_BONE && static_cast<CAttachmentBONE*>(pAttachment)->m_nJointID != -1))
  698.                                 {
  699.                                         DualQuat& dq = pSkinningTransformations[i + numJoints];
  700.                                         dq = pAttachment->GetAttModelRelative() * pAttachment->GetAdditionalTransformation();
  701.                                 }
  702.                         }
  703.                 }
  704.         }
  705.  
  706.         assert(pSkinningData->pMasterSkinningDataList);
  707.  
  708.         // set the list to NULL to indicate the mainthread that the skinning transformation job has finished
  709.         SSkinningData* pSkinningJobList = NULL;
  710.         do
  711.         {
  712.                 pSkinningJobList = *(const_cast<SSkinningData* volatile*>(pSkinningData->pMasterSkinningDataList));
  713.         }
  714.         while (CryInterlockedCompareExchangePointer(alias_cast<void* volatile*>(pSkinningData->pMasterSkinningDataList), NULL, pSkinningJobList) != pSkinningJobList);
  715.  
  716.         // start SW-Skinning Job till the list is empty
  717.         while (pSkinningJobList != SKINNING_TRANSFORMATION_RUNNING_INDICATOR)
  718.         {
  719.                 SVertexAnimationJob* pVertexAnimation = static_cast<SVertexAnimationJob*>(pSkinningJobList->pCustomData);
  720.                 pVertexAnimation->Begin(pSkinningJobList->pAsyncJobs);
  721.  
  722.                 pSkinningJobList = pSkinningJobList->pNextSkinningData;
  723.         }
  724. }
  725.  
  726. //////////////////////////////////////////////////////////////////////////
  727. size_t CCharInstance::SizeOfCharInstance() const
  728. {
  729.         if (ICrySizer* pSizer = gEnv->pSystem->CreateSizer())
  730.         {
  731.                 pSizer->AddObject(this);
  732.                 pSizer->End();
  733.  
  734.                 const auto totalSize = pSizer->GetTotalSize();
  735.  
  736.                 pSizer->Release();
  737.  
  738.                 return totalSize;
  739.         }
  740.         else
  741.         {
  742.                 return 0;
  743.         }
  744. }
  745.  
  746. void CCharInstance::GetMemoryUsage(ICrySizer* pSizer) const
  747. {
  748.         pSizer->AddObjectSize(this);
  749.  
  750.         pSizer->AddObjectSize(m_pFacialInstance.get());
  751.         pSizer->AddObject(m_strFilePath);
  752.  
  753.         {
  754.                 SIZER_COMPONENT_NAME(pSizer, "CAttachmentManager");
  755.                 pSizer->AddObject(m_AttachmentManager);
  756.         }
  757.  
  758.         {
  759.                 SIZER_COMPONENT_NAME(pSizer, "skeletonEffectManager");
  760.                 pSizer->AddObject(m_skeletonEffectManager);
  761.         }
  762.  
  763.         {
  764.                 SIZER_COMPONENT_NAME(pSizer, "FacialInstance");
  765.                 pSizer->AddObject(m_pFacialInstance);
  766.         }
  767.  
  768.         {
  769.                 SIZER_COMPONENT_NAME(pSizer, "SkeletonAnim");
  770.                 pSizer->AddObject(m_SkeletonAnim);
  771.         }
  772.  
  773.         {
  774.                 SIZER_COMPONENT_NAME(pSizer, "SkeletonPose");
  775.                 pSizer->AddObject(m_SkeletonPose);
  776.         }
  777.  
  778.         {
  779.                 // TODO: The m_Extents member allocates dynamic data and should also be included in the computation.
  780.         }
  781. }
  782.  
  783. CharacterInstanceProcessing::SContext* CCharInstance::GetProcessingContext()
  784. {
  785.         if (m_processingContext >= 0)
  786.         {
  787.                 return &g_pCharacterManager->GetContextSyncQueue().GetContext(m_processingContext);
  788.         }
  789.         return nullptr;
  790. }
  791.  
  792. void CCharInstance::WaitForSkinningJob() const
  793. {
  794.         // wait for the skinning transformation from the last frame to finish
  795.         // *note* the skinning pool id is increased in EF_Start, which is called during the frame
  796.         // after the CommandBuffer Job, thus we need the current id to get the skinning data from the last frame
  797.         int nFrameID = gEnv->pRenderer ? gEnv->pRenderer->EF_GetSkinningPoolID() : 0;
  798.         int nList = nFrameID % 3;
  799.         SSkinningData* pSkinningData = arrSkinningRendererData[nList].pSkinningData;
  800.         if (arrSkinningRendererData[nList].nFrameID == nFrameID && pSkinningData && pSkinningData->pAsyncJobs)
  801.                 gEnv->pJobManager->WaitForJob(*pSkinningData->pAsyncJobs);
  802. }
  803.  
  804. void CCharInstance::SetupThroughParent(const CCharInstance* pParent)
  805. {
  806.         CRY_ASSERT(pParent != nullptr);
  807.         m_fPostProcessZoomAdjustedDistanceFromCamera =
  808.           pParent->m_fPostProcessZoomAdjustedDistanceFromCamera;
  809.         m_fOriginalDeltaTime = pParent->m_fOriginalDeltaTime;
  810.         m_fDeltaTime = pParent->m_fDeltaTime;
  811.         m_nAnimationLOD = pParent->GetAnimationLOD();
  812.         m_SkeletonPose.m_bFullSkeletonUpdate = pParent->m_SkeletonPose.m_bFullSkeletonUpdate;
  813.         m_SkeletonPose.m_bInstanceVisible = pParent->m_SkeletonPose.m_bInstanceVisible;
  814. }
  815.  
  816. void CCharInstance::SetupThroughParams(const SAnimationProcessParams* pParams)
  817. {
  818.         CRY_ASSERT(pParams != nullptr);
  819.         static ICVar* pUseSinglePositionVar = gEnv->pConsole->GetCVar("g_useSinglePosition");
  820.         if (pUseSinglePositionVar && pUseSinglePositionVar->GetIVal() & 4)
  821.         {
  822.                 m_SkeletonPose.m_physics.SynchronizeWithPhysics(
  823.                   m_SkeletonPose.GetPoseDataExplicitWriteable());
  824.         }
  825.  
  826.         m_location = pParams->locationAnimation; // this the current location
  827.         m_fPostProcessZoomAdjustedDistanceFromCamera =
  828.           pParams->zoomAdjustedDistanceFromCamera;
  829.  
  830.         uint32 nErrorCode = 0;
  831.         uint32 minValid = m_SkeletonPose.m_AABB.min.IsValid();
  832.         if (minValid == 0)
  833.                 nErrorCode |= 0x8000;
  834.         uint32 maxValid = m_SkeletonPose.m_AABB.max.IsValid();
  835.         if (maxValid == 0)
  836.                 nErrorCode |= 0x8000;
  837.         if (Console::GetInst().ca_SaveAABB && nErrorCode)
  838.         {
  839.                 m_SkeletonPose.m_AABB.max = Vec3(2, 2, 2);
  840.                 m_SkeletonPose.m_AABB.min = Vec3(-2, -2, -2);
  841.         }
  842.  
  843.         float fNewDeltaTime = clamp_tpl(g_pITimer->GetFrameTime(), 0.0f, 0.5f);
  844.         fNewDeltaTime =
  845.           (float)__fsel(pParams->overrideDeltaTime, pParams->overrideDeltaTime, fNewDeltaTime);
  846.         m_fOriginalDeltaTime = fNewDeltaTime;
  847.         m_fDeltaTime = fNewDeltaTime * m_fPlaybackScale;
  848.  
  849.         //---------------------------------------------------------------------------------
  850.  
  851.         m_SkeletonPose.m_bFullSkeletonUpdate = false;
  852.         int nCurrentFrameID = g_pCharacterManager->m_nUpdateCounter; // g_pIRenderer->GetFrameID(false);
  853.         uint32 dif = nCurrentFrameID - m_LastRenderedFrameID;
  854.         m_SkeletonPose.m_bInstanceVisible =
  855.           (dif < 5) || m_SkeletonAnim.GetTrackViewStatus();
  856.  
  857.         if (m_SkeletonPose.m_bInstanceVisible)
  858.                 m_SkeletonPose.m_bFullSkeletonUpdate = true;
  859.         if (m_SkeletonAnim.m_TrackViewExclusive)
  860.                 m_SkeletonPose.m_bFullSkeletonUpdate = true;
  861.         if (m_SkeletonPose.m_nForceSkeletonUpdate)
  862.                 m_SkeletonPose.m_bFullSkeletonUpdate = true;
  863.         if (Console::GetInst().ca_ForceUpdateSkeletons != 0)
  864.                 m_SkeletonPose.m_bFullSkeletonUpdate = true;
  865. }
  866.  
  867. //////////////////////////////////////////////////////////////////////////
  868. void CCharInstance::PerFrameUpdate()
  869. {
  870.         if (m_rpFlags & CS_FLAG_UPDATE)
  871.         {
  872.                 if ((m_rpFlags & CS_FLAG_UPDATE_ALWAYS) ||
  873.                                 (m_rpFlags & CS_FLAG_RENDER_NODE_VISIBLE))
  874.                 {
  875.                         // If we need to be updated always, or our render node is potentially visible.
  876.                         // Animation should start
  877.  
  878.                         const CCamera& camera = GetISystem()->GetViewCamera();
  879.                         float fDistance = (camera.GetPosition() - m_location.t).GetLength();
  880.                         float fZoomFactor = 0.001f + 0.999f * (RAD2DEG(camera.GetFov()) / 60.f);
  881.  
  882.                         SAnimationProcessParams params;
  883.                         params.locationAnimation = m_location;
  884.                         params.bOnRender = 0;
  885.                         params.zoomAdjustedDistanceFromCamera = fDistance * fZoomFactor;
  886.                         StartAnimationProcessing(params);
  887.                 }
  888.         }
  889. }
  890.  
downloadCharacterInstance.cpp Source code - Download CRYENGINE Source code
Related Source Codes/Software:
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top