LCOV - code coverage report
Current view: top level - source/collada - PSAConvert.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 128 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 7 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2025 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "PSAConvert.h"
      21             : 
      22             : #include "CommonConvert.h"
      23             : #include "Decompose.h"
      24             : #include "Maths.h"
      25             : #include "StdSkeletons.h"
      26             : #include "DLL.h"
      27             : 
      28             : #include <FCDocument/FCDAnimated.h>
      29             : #include <FCDocument/FCDAnimationCurve.h>
      30             : #include <FCDocument/FCDAnimationKey.h>
      31             : #include <FCDocument/FCDController.h>
      32             : #include <FCDocument/FCDControllerInstance.h>
      33             : #include <FCDocument/FCDEntityInstance.h>
      34             : #include <FCDocument/FCDExtra.h>
      35             : #include <FCDocument/FCDSceneNode.h>
      36             : #include <FCDocument/FCDSkinController.h>
      37             : #include <FCDocument/FCDTransform.h>
      38             : #include <FCDocument/FCDocument.h>
      39             : #include <FMath/FMMatrix44.h>
      40             : #include <FUtils/FUString.h>
      41             : #include <FUtils/FUStringConversion.h>
      42             : #include <FUtils/Platforms.h>
      43             : #include <algorithm>
      44             : #include <cassert>
      45             : #include <cfloat>
      46             : #include <cstring>
      47             : #include <iterator>
      48             : #include <limits>
      49             : #include <vector>
      50             : 
      51             : class PSAConvert
      52             : {
      53             : public:
      54             :     /**
      55             :      * Converts a COLLADA XML document into the PSA animation format.
      56             :      *
      57             :      * @param input XML document to parse
      58             :      * @param output callback for writing the PSA data; called lots of times
      59             :      *               with small strings
      60             :      * @param xmlErrors output - errors reported by the XML parser
      61             :      * @throws ColladaException on failure
      62             :      */
      63           0 :     static void ColladaToPSA(const char* input, OutputCB& output, std::string& xmlErrors)
      64             :     {
      65           0 :         CommonConvert converter(input, xmlErrors);
      66             : 
      67           0 :         if (converter.GetInstance().GetType() == FCDEntityInstance::CONTROLLER)
      68             :         {
      69           0 :             FCDControllerInstance& controllerInstance = static_cast<FCDControllerInstance&>(converter.GetInstance());
      70             : 
      71           0 :             FixSkeletonRoots(controllerInstance);
      72             : 
      73           0 :             assert(converter.GetInstance().GetEntity()->GetType() == FCDEntity::CONTROLLER); // assume this is always true?
      74           0 :             FCDController* controller = static_cast<FCDController*>(converter.GetInstance().GetEntity());
      75             : 
      76           0 :             FCDSkinController* skin = controller->GetSkinController();
      77           0 :             REQUIRE(skin != NULL, "is skin controller");
      78             : 
      79           0 :             const Skeleton& skeleton = FindSkeleton(controllerInstance);
      80             : 
      81           0 :             float frameLength = 1.f / 30.f; // currently we always want to create PMDs at fixed 30fps
      82             : 
      83             :             // Find the extents of the animation:
      84             : 
      85           0 :             float timeStart = 0, timeEnd = 0;
      86           0 :             GetAnimationRange(converter.GetDocument(), skeleton, controllerInstance, timeStart, timeEnd);
      87             :             // To catch broken animations / skeletons.xml:
      88           0 :             REQUIRE(timeEnd > timeStart, "animation end frame must come after start frame");
      89             : 
      90             :             // Count frames; don't include the last keyframe
      91           0 :             size_t frameCount = (size_t)((timeEnd - timeStart) / frameLength - 0.5f);
      92           0 :             REQUIRE(frameCount > 0, "animation must have frames");
      93             :             // (TODO: sort out the timing/looping problems)
      94             : 
      95           0 :             const size_t boneCount = skeleton.GetBoneCount();
      96           0 :             if (boneCount > 192)
      97           0 :                 Log(LOG_ERROR, "Skeleton has too many bones %zu/192", boneCount);
      98             : 
      99           0 :             std::vector<BoneTransform> boneTransforms;
     100             : 
     101           0 :             for (size_t frame = 0; frame < frameCount; ++frame)
     102             :             {
     103           0 :                 float time = timeStart + frameLength * frame;
     104             : 
     105           0 :                 BoneTransform boneDefault  = { { 0, 0, 0 }, { 0, 0, 0, 1 } };
     106           0 :                 std::vector<BoneTransform> frameBoneTransforms(boneCount, boneDefault);
     107             : 
     108             :                 // Move the model into the new animated pose
     109             :                 // (We can't tell exactly which nodes should be animated, so
     110             :                 // just update the entire world recursively)
     111           0 :                 EvaluateAnimations(converter.GetRoot(), time);
     112             : 
     113             :                 // Convert the pose into the form require by the game
     114           0 :                 for (size_t i = 0; i < controllerInstance.GetJointCount(); ++i)
     115             :                 {
     116           0 :                     FCDSceneNode* joint = controllerInstance.GetJoint(i);
     117             : 
     118           0 :                     int boneId = skeleton.GetRealBoneID(joint->GetName().c_str());
     119           0 :                     if (boneId < 0)
     120           0 :                         continue; // not a recognised bone - ignore it, same as before
     121             : 
     122           0 :                     FMMatrix44 worldTransform = joint->CalculateWorldTransform();
     123             : 
     124           0 :                     HMatrix matrix;
     125           0 :                     memcpy(matrix, worldTransform.Transposed().m, sizeof(matrix));
     126             : 
     127           0 :                     AffineParts parts;
     128           0 :                     decomp_affine(matrix, &parts);
     129             : 
     130           0 :                     BoneTransform b = {
     131           0 :                         { parts.t.x, parts.t.y, parts.t.z },
     132           0 :                         { parts.q.x, parts.q.y, parts.q.z, parts.q.w }
     133           0 :                     };
     134             : 
     135           0 :                     frameBoneTransforms[boneId] = b;
     136             :                 }
     137             : 
     138             :                 // Push frameBoneTransforms onto the back of boneTransforms
     139           0 :                 copy(frameBoneTransforms.begin(), frameBoneTransforms.end(),
     140             :                     std::inserter(boneTransforms, boneTransforms.end()));
     141           0 :             }
     142             : 
     143             :             // Convert into game's coordinate space
     144           0 :             TransformVertices(boneTransforms, skin->GetBindShapeTransform(), converter.IsYUp(), converter.IsXSI());
     145             : 
     146             :             // Write out the file
     147           0 :             WritePSA(output, frameCount, boneCount, boneTransforms);
     148           0 :         }
     149             :         else
     150             :         {
     151           0 :             throw ColladaException("Unrecognized object type");
     152             :         }
     153           0 :     }
     154             : 
     155             :     /**
     156             :      * Writes the animation data in the PSA format.
     157             :      */
     158           0 :     static void WritePSA(OutputCB& output, size_t frameCount, size_t boneCount, const std::vector<BoneTransform>& boneTransforms)
     159             :     {
     160           0 :         output("PSSA", 4);  // magic number
     161           0 :         write(output, (uint32)1); // version number
     162           0 :         write(output, (uint32)(
     163             :             4 + 0 + // name
     164             :             4 + // frameLength
     165           0 :             4 + 4 + // numBones, numFrames
     166             :             7*4*boneCount*frameCount // boneStates
     167             :             )); // data size
     168             : 
     169             :         // Name
     170           0 :         write(output, (uint32)0);
     171             : 
     172             :         // Frame length
     173           0 :         write(output, 1000.f/30.f);
     174             : 
     175           0 :         write(output, (uint32)boneCount);
     176           0 :         write(output, (uint32)frameCount);
     177             : 
     178           0 :         for (size_t i = 0; i < boneCount*frameCount; ++i)
     179             :         {
     180           0 :             output((char*)&boneTransforms[i], 7*4);
     181             :         }
     182           0 :     }
     183             : 
     184           0 :     static void TransformVertices(std::vector<BoneTransform>& bones,
     185             :         const FMMatrix44& transform, bool yUp, bool isXSI)
     186             :     {
     187             :         // HACK: we want to handle scaling in XSI because that makes it easy
     188             :         // for artists to adjust the models to the right size. But this way
     189             :         // doesn't work in Max, and I can't see how to make it do so, so this
     190             :         // is only applied to models from XSI.
     191           0 :         if (isXSI)
     192             :         {
     193           0 :             TransformBones(bones, DecomposeToScaleMatrix(transform), yUp);
     194             :         }
     195             :         else
     196             :         {
     197           0 :             TransformBones(bones, FMMatrix44_Identity, yUp);
     198             :         }
     199           0 :     }
     200             : 
     201           0 :     static void GetAnimationRange(const FColladaDocument& doc, const Skeleton& skeleton,
     202             :         const FCDControllerInstance& controllerInstance,
     203             :         float& timeStart, float& timeEnd)
     204             :     {
     205             :         // FCollada tools export <extra> info in the scene to specify the start
     206             :         // and end times.
     207             :         // If that isn't available, we have to search for the earliest and latest
     208             :         // keyframes on any of the bones.
     209           0 :         if (doc.GetDocument()->HasStartTime() && doc.GetDocument()->HasEndTime())
     210             :         {
     211           0 :             timeStart = doc.GetDocument()->GetStartTime();
     212           0 :             timeEnd = doc.GetDocument()->GetEndTime();
     213           0 :             return;
     214             :         }
     215             : 
     216             :         // XSI exports relevant information in
     217             :         // <extra><technique profile="XSI"><SI_Scene><xsi_param sid="start">
     218             :         // (and 'end' and 'frameRate') so use those
     219           0 :         if (GetAnimationRange_XSI(doc, timeStart, timeEnd))
     220             :             return;
     221             : 
     222           0 :         timeStart = std::numeric_limits<float>::max();
     223           0 :         timeEnd = -std::numeric_limits<float>::max();
     224           0 :         for (size_t i = 0; i < controllerInstance.GetJointCount(); ++i)
     225             :         {
     226           0 :             const FCDSceneNode* joint = controllerInstance.GetJoint(i);
     227           0 :             REQUIRE(joint != NULL, "joint exists");
     228             : 
     229           0 :             int boneId = skeleton.GetBoneID(joint->GetName().c_str());
     230           0 :             if (boneId < 0)
     231             :             {
     232             :                 // unrecognised joint - it's probably just a prop point
     233             :                 // or something, so ignore it
     234           0 :                 continue;
     235             :             }
     236             : 
     237             :             // Skip unanimated joints
     238           0 :             if (joint->GetTransformCount() == 0)
     239           0 :                 continue;
     240             : 
     241           0 :             for (size_t j = 0; j < joint->GetTransformCount(); ++j)
     242             :             {
     243           0 :                 const FCDTransform* transform = joint->GetTransform(j);
     244             : 
     245           0 :                 if (! transform->IsAnimated())
     246           0 :                     continue;
     247             : 
     248             :                 // Iterate over all curves to find the earliest and latest keys
     249           0 :                 const FCDAnimated* anim = transform->GetAnimated();
     250           0 :                 const FCDAnimationCurveListList& curvesList = anim->GetCurves();
     251           0 :                 for (size_t k = 0; k < curvesList.size(); ++k)
     252             :                 {
     253           0 :                     const FCDAnimationCurveTrackList& curves = curvesList[k];
     254           0 :                     for (size_t l = 0; l < curves.size(); ++l)
     255             :                     {
     256           0 :                         const FCDAnimationCurve* curve = curves[l];
     257           0 :                         timeStart = std::min(timeStart, curve->GetKeys()[0]->input);
     258           0 :                         timeEnd = std::max(timeEnd, curve->GetKeys()[curve->GetKeyCount()-1]->input);
     259             :                     }
     260             :                 }
     261             :             }
     262             :         }
     263             :     }
     264             : 
     265           0 :     static bool GetAnimationRange_XSI(const FColladaDocument& doc, float& timeStart, float& timeEnd)
     266             :     {
     267           0 :         FCDExtra* extra = doc.GetExtra();
     268           0 :         if (! extra) return false;
     269             : 
     270           0 :         FCDEType* type = extra->GetDefaultType();
     271           0 :         if (! type) return false;
     272             : 
     273           0 :         FCDETechnique* technique = type->FindTechnique("XSI");
     274           0 :         if (! technique) return false;
     275             : 
     276           0 :         FCDENode* scene = technique->FindChildNode("SI_Scene");
     277           0 :         if (! scene) return false;
     278             : 
     279           0 :         float start = FLT_MAX, end = -FLT_MAX, framerate = 0.f;
     280             : 
     281           0 :         FCDENodeList paramNodes;
     282           0 :         scene->FindChildrenNodes("xsi_param", paramNodes);
     283           0 :         for (FCDENodeList::iterator it = paramNodes.begin(); it != paramNodes.end(); ++it)
     284             :         {
     285           0 :             if ((*it)->ReadAttribute("sid") == "start")
     286           0 :                 start = FUStringConversion::ToFloat((*it)->GetContent());
     287           0 :             else if ((*it)->ReadAttribute("sid") == "end")
     288           0 :                 end = FUStringConversion::ToFloat((*it)->GetContent());
     289           0 :             else if ((*it)->ReadAttribute("sid") == "frameRate")
     290           0 :                 framerate = FUStringConversion::ToFloat((*it)->GetContent());
     291             :         }
     292             : 
     293           0 :         if (framerate != 0.f && start != FLT_MAX && end != -FLT_MAX)
     294             :         {
     295           0 :             timeStart = start / framerate;
     296           0 :             timeEnd = end / framerate;
     297           0 :             return true;
     298             :         }
     299             : 
     300             :         return false;
     301           0 :     }
     302             : 
     303           0 :     static void EvaluateAnimations(FCDSceneNode& node, float time)
     304             :     {
     305           0 :         for (size_t i = 0; i < node.GetTransformCount(); ++i)
     306             :         {
     307           0 :             FCDTransform* transform = node.GetTransform(i);
     308           0 :             FCDAnimated* anim = transform->GetAnimated();
     309           0 :             if (anim)
     310           0 :                 anim->Evaluate(time);
     311             :         }
     312             : 
     313           0 :         for (size_t i = 0; i < node.GetChildrenCount(); ++i)
     314           0 :             EvaluateAnimations(*node.GetChild(i), time);
     315           0 :     }
     316             : 
     317             : };
     318             : 
     319             : 
     320             : // The above stuff is just in a class since I don't like having to bother
     321             : // with forward declarations of functions - but provide the plain function
     322             : // interface here:
     323             : 
     324           0 : void ColladaToPSA(const char* input, OutputCB& output, std::string& xmlErrors)
     325             : {
     326           0 :     PSAConvert::ColladaToPSA(input, output, xmlErrors);
     327           0 : }

Generated by: LCOV version 1.16