3
0

CsvSerializers.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AzCore/std/string/conversions.h>
  9. #include <AzCore/IO/GenericStreams.h>
  10. #include <EMotionFX/Source/ActorInstance.h>
  11. #include <EMotionFX/Source/Node.h>
  12. #include <EMotionFX/Source/PoseDataFactory.h>
  13. #include <EMotionFX/Source/TransformData.h>
  14. #include <CsvSerializers.h>
  15. #include <FeatureSchema.h>
  16. namespace EMotionFX::MotionMatching
  17. {
  18. CsvWriterBase::~CsvWriterBase()
  19. {
  20. End();
  21. }
  22. bool CsvWriterBase::OpenFile(const char* filename, int openMode)
  23. {
  24. m_file.Close();
  25. if (!m_file.Open(filename, openMode))
  26. {
  27. End();
  28. return false;
  29. }
  30. return true;
  31. }
  32. void CsvWriterBase::End()
  33. {
  34. m_file.Close();
  35. m_tempBuffer.clear();
  36. }
  37. void CsvWriterBase::WriteLine(AZStd::string& line)
  38. {
  39. line = AZ::StringFunc::RStrip(line, ",");
  40. line += "\n";
  41. m_file.Write(line.data(), line.size());
  42. }
  43. void CsvWriterBase::WriteVector3ToString(const AZ::Vector3& vec, AZStd::string& text)
  44. {
  45. text += AZStd::string::format("%.8f,%.8f,%.8f,", vec.GetX(), vec.GetY(), vec.GetZ());
  46. };
  47. void CsvWriterBase::WriteFloatArrayToString(const AZStd::vector<float>& values, AZStd::string& text)
  48. {
  49. text.reserve(text.size() + values.size() * 10);
  50. for (float value : values)
  51. {
  52. text += AZStd::string::format("%.8f,", value);
  53. }
  54. }
  55. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  56. bool PoseWriterCsv::Begin(const char* filename, ActorInstance* actorInstance, const WriteSettings& writeSettings)
  57. {
  58. m_settings = writeSettings;
  59. if (!actorInstance)
  60. {
  61. return false;
  62. }
  63. if (!CsvWriterBase::OpenFile(filename, AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  64. {
  65. return false;
  66. }
  67. m_actorInstance = actorInstance;
  68. SaveColumnNamesToString(m_tempBuffer);
  69. return true;
  70. }
  71. void PoseWriterCsv::SaveColumnNamesToString(AZStd::string& outText)
  72. {
  73. const Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton();
  74. const size_t numEnabledJoints = m_actorInstance->GetNumEnabledNodes();
  75. outText.clear();
  76. outText.reserve(50 * numEnabledJoints);
  77. auto SaveVector3ColumnNames = [](AZStd::string& text, const char* jointName, const char* vecName)
  78. {
  79. text += AZStd::string::format("%s.%s.X,%s.%s.Y,%s.%s.Z,", jointName, vecName, jointName, vecName, jointName, vecName);
  80. };
  81. for (size_t i = 0; i < numEnabledJoints; ++i)
  82. {
  83. const size_t jointIndex = m_actorInstance->GetEnabledNode(i);
  84. const Node* joint = skeleton->GetNode(jointIndex);
  85. // Position
  86. if (m_settings.m_writePositions)
  87. {
  88. SaveVector3ColumnNames(outText, joint->GetName(), "Pos");
  89. }
  90. // Rotation
  91. if (m_settings.m_writeRotations)
  92. {
  93. SaveVector3ColumnNames(outText, joint->GetName(), "RotBasisX");
  94. SaveVector3ColumnNames(outText, joint->GetName(), "RotBasisY");
  95. }
  96. }
  97. WriteLine(m_tempBuffer);
  98. }
  99. void PoseWriterCsv::WritePose(Pose& pose, const ETransformSpace transformSpace)
  100. {
  101. if (!IsReady() || !m_actorInstance)
  102. {
  103. return;
  104. }
  105. SavePoseToString(pose, transformSpace, m_tempBuffer);
  106. WriteLine(m_tempBuffer);
  107. }
  108. void PoseWriterCsv::SavePoseToString(Pose& pose, const ETransformSpace transformSpace, AZStd::string& outText)
  109. {
  110. const size_t numEnabledJoints = m_actorInstance->GetNumEnabledNodes();
  111. outText.clear();
  112. outText.reserve(10 * 3 * 3 * numEnabledJoints);
  113. for (size_t i = 0; i < numEnabledJoints; ++i)
  114. {
  115. const size_t jointIndex = m_actorInstance->GetEnabledNode(i);
  116. Transform transform = Transform::CreateIdentity();
  117. switch (transformSpace)
  118. {
  119. case TRANSFORM_SPACE_LOCAL:
  120. {
  121. transform = pose.GetLocalSpaceTransform(jointIndex);
  122. break;
  123. }
  124. case TRANSFORM_SPACE_MODEL:
  125. {
  126. transform = pose.GetModelSpaceTransform(jointIndex);
  127. break;
  128. }
  129. default:
  130. {
  131. AZ_Error("Motion Matching", false, "Unsupported transform space");
  132. break;
  133. }
  134. }
  135. // Position
  136. if (m_settings.m_writePositions)
  137. {
  138. const AZ::Vector3 position = transform.m_position;
  139. WriteVector3ToString(position, outText);
  140. }
  141. // Rotation
  142. // Store rotation as the X and Y axes The Z axis can be reconstructed by the cross product of the X and Y axes.
  143. if (m_settings.m_writeRotations)
  144. {
  145. const AZ::Quaternion rotation = transform.m_rotation;
  146. AZ::Matrix3x3 rotationMatrix = AZ::Matrix3x3::CreateFromQuaternion(rotation);
  147. WriteVector3ToString(rotationMatrix.GetBasisX().GetNormalizedSafe(), outText);
  148. WriteVector3ToString(rotationMatrix.GetBasisY().GetNormalizedSafe(), outText);
  149. }
  150. }
  151. }
  152. void PoseWriterCsv::End()
  153. {
  154. m_actorInstance = nullptr;
  155. CsvWriterBase::End();
  156. }
  157. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  158. bool QueryVectorWriterCsv::Begin(const char* filename, const FeatureSchema* featureSchema)
  159. {
  160. if (!featureSchema)
  161. {
  162. return false;
  163. }
  164. if (!CsvWriterBase::OpenFile(filename, AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  165. {
  166. return false;
  167. }
  168. // Save column names in the first row
  169. const AZStd::vector<AZStd::string> columnNames = featureSchema->CollectColumnNames();
  170. m_tempBuffer.clear();
  171. if (!columnNames.empty())
  172. {
  173. for (size_t i = 0; i < columnNames.size(); ++i)
  174. {
  175. if (i != 0)
  176. {
  177. m_tempBuffer += ",";
  178. }
  179. m_tempBuffer += columnNames[i];
  180. }
  181. }
  182. WriteLine(m_tempBuffer);
  183. return true;
  184. }
  185. void QueryVectorWriterCsv::Write(const QueryVector* queryVector)
  186. {
  187. if (!IsReady() || !queryVector)
  188. {
  189. return;
  190. }
  191. m_tempBuffer.clear();
  192. WriteFloatArrayToString(queryVector->GetData(), m_tempBuffer);
  193. WriteLine(m_tempBuffer);
  194. }
  195. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  196. bool BestMatchingFrameWriterCsv::Begin(const char* filename)
  197. {
  198. if (!CsvWriterBase::OpenFile(filename, AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  199. {
  200. return false;
  201. }
  202. m_tempBuffer = "Best Matching Frames";
  203. WriteLine(m_tempBuffer);
  204. return true;
  205. }
  206. void BestMatchingFrameWriterCsv::Write(size_t frame)
  207. {
  208. m_tempBuffer = AZStd::to_string(frame);
  209. WriteLine(m_tempBuffer);
  210. }
  211. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  212. PoseReaderCsv::~PoseReaderCsv()
  213. {
  214. End();
  215. }
  216. bool PoseReaderCsv::Begin(const char* filename, const ReadSettings& readSettings)
  217. {
  218. m_settings = readSettings;
  219. AZ::IO::SystemFile file;
  220. if (!file.Open(filename, AZ::IO::SystemFile::SF_OPEN_READ_ONLY))
  221. {
  222. return false;
  223. }
  224. AZ::IO::SystemFile::SizeType fileSize = file.Length();
  225. AZStd::string textBuffer;
  226. textBuffer.resize(fileSize);
  227. file.Read(fileSize, textBuffer.data());
  228. file.Close();
  229. AZStd::vector<AZStd::string> lines;
  230. AZ::StringFunc::Tokenize(textBuffer, lines, '\n');
  231. if (lines.empty())
  232. {
  233. return false;
  234. }
  235. m_columnNamesLine = lines[0];
  236. lines.erase(lines.begin());
  237. m_poseValueLines = lines;
  238. return true;
  239. }
  240. void PoseReaderCsv::ApplyPose(ActorInstance* actorInstance, Pose& pose, const ETransformSpace transformSpace, size_t index)
  241. {
  242. AZStd::vector<AZStd::string> valueTokens;
  243. AZ::StringFunc::Tokenize(m_poseValueLines[index], valueTokens, ',');
  244. Pose* bindPose = actorInstance->GetTransformData()->GetBindPose();
  245. size_t valueIndex = 0;
  246. const size_t numEnabledJoints = actorInstance->GetNumEnabledNodes();
  247. for (size_t i = 0; i < numEnabledJoints; ++i)
  248. {
  249. const size_t jointIndex = actorInstance->GetEnabledNode(i);
  250. Transform transform = bindPose->GetLocalSpaceTransform(jointIndex);
  251. switch (transformSpace)
  252. {
  253. case TRANSFORM_SPACE_LOCAL:
  254. {
  255. transform = pose.GetLocalSpaceTransform(jointIndex);
  256. break;
  257. }
  258. case TRANSFORM_SPACE_MODEL:
  259. {
  260. transform = pose.GetModelSpaceTransform(jointIndex);
  261. break;
  262. }
  263. default:
  264. {
  265. AZ_Error("Motion Matching", false, "Unsupported transform space");
  266. break;
  267. }
  268. }
  269. auto LoadVector3FromString = [&valueTokens](size_t& valueIndex, AZ::Vector3& outVec)
  270. {
  271. outVec.SetX(AZStd::stof(valueTokens[valueIndex + 0]));
  272. outVec.SetY(AZStd::stof(valueTokens[valueIndex + 1]));
  273. outVec.SetZ(AZStd::stof(valueTokens[valueIndex + 2]));
  274. valueIndex += 3;
  275. };
  276. // Position
  277. if (m_settings.m_readPositions)
  278. {
  279. LoadVector3FromString(valueIndex, transform.m_position);
  280. }
  281. // Rotation
  282. if (m_settings.m_readRotations)
  283. {
  284. // Load the X and Y axes.
  285. AZ::Vector3 basisX = AZ::Vector3::CreateZero();
  286. AZ::Vector3 basisY = AZ::Vector3::CreateZero();
  287. LoadVector3FromString(valueIndex, basisX);
  288. LoadVector3FromString(valueIndex, basisY);
  289. basisX.NormalizeSafe();
  290. basisY.NormalizeSafe();
  291. // Create a 3x3 rotation matrix by the X and Y axes and construct the Z-axis as the
  292. // cross-product of the X and Y axes.
  293. AZ::Matrix3x3 rotationMatrix = AZ::Matrix3x3::CreateIdentity();
  294. rotationMatrix.SetBasisX(basisX);
  295. rotationMatrix.SetBasisY(basisY);
  296. rotationMatrix.SetBasisZ(basisX.Cross(basisY));
  297. // Convert the rotation matrix to a quaternion.
  298. transform.m_rotation = AZ::Quaternion::CreateFromMatrix3x3(rotationMatrix);
  299. }
  300. switch (transformSpace)
  301. {
  302. case TRANSFORM_SPACE_LOCAL:
  303. {
  304. pose.SetLocalSpaceTransform(jointIndex, transform);
  305. break;
  306. }
  307. case TRANSFORM_SPACE_MODEL:
  308. {
  309. pose.SetModelSpaceTransform(jointIndex, transform);
  310. break;
  311. }
  312. default:
  313. {
  314. AZ_Error("Motion Matching", false, "Unsupported transform space");
  315. break;
  316. }
  317. }
  318. }
  319. }
  320. void PoseReaderCsv::End()
  321. {
  322. m_columnNamesLine.clear();
  323. m_poseValueLines.clear();
  324. }
  325. } // namespace EMotionFX::MotionMatching