Animation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Container/Sort.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Graphics/Animation.h"
  27. #include "../IO/Deserializer.h"
  28. #include "../IO/FileSystem.h"
  29. #include "../IO/Log.h"
  30. #include "../IO/Serializer.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../Resource/XMLFile.h"
  33. #include "../Resource/JSONFile.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. inline bool CompareTriggers(AnimationTriggerPoint& lhs, AnimationTriggerPoint& rhs)
  38. {
  39. return lhs.time_ < rhs.time_;
  40. }
  41. inline bool CompareKeyFrames(AnimationKeyFrame& lhs, AnimationKeyFrame& rhs)
  42. {
  43. return lhs.time_ < rhs.time_;
  44. }
  45. void AnimationTrack::SetKeyFrame(unsigned index, const AnimationKeyFrame& keyFrame)
  46. {
  47. if (index < keyFrames_.Size())
  48. {
  49. keyFrames_[index] = keyFrame;
  50. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  51. }
  52. else if (index == keyFrames_.Size())
  53. AddKeyFrame(keyFrame);
  54. }
  55. void AnimationTrack::AddKeyFrame(const AnimationKeyFrame& keyFrame)
  56. {
  57. bool needSort = keyFrames_.Size() ? keyFrames_.Back().time_ > keyFrame.time_ : false;
  58. keyFrames_.Push(keyFrame);
  59. if (needSort)
  60. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  61. }
  62. void AnimationTrack::InsertKeyFrame(unsigned index, const AnimationKeyFrame& keyFrame)
  63. {
  64. keyFrames_.Insert(index, keyFrame);
  65. Urho3D::Sort(keyFrames_.Begin(), keyFrames_.End(), CompareKeyFrames);
  66. }
  67. void AnimationTrack::RemoveKeyFrame(unsigned index)
  68. {
  69. keyFrames_.Erase(index);
  70. }
  71. void AnimationTrack::RemoveAllKeyFrames()
  72. {
  73. keyFrames_.Clear();
  74. }
  75. AnimationKeyFrame* AnimationTrack::GetKeyFrame(unsigned index)
  76. {
  77. return index < keyFrames_.Size() ? &keyFrames_[index] : (AnimationKeyFrame*)0;
  78. }
  79. void AnimationTrack::GetKeyFrameIndex(float time, unsigned& index) const
  80. {
  81. if (time < 0.0f)
  82. time = 0.0f;
  83. if (index >= keyFrames_.Size())
  84. index = keyFrames_.Size() - 1;
  85. // Check for being too far ahead
  86. while (index && time < keyFrames_[index].time_)
  87. --index;
  88. // Check for being too far behind
  89. while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
  90. ++index;
  91. }
  92. Animation::Animation(Context* context) :
  93. Resource(context),
  94. length_(0.f)
  95. {
  96. }
  97. Animation::~Animation()
  98. {
  99. }
  100. void Animation::RegisterObject(Context* context)
  101. {
  102. context->RegisterFactory<Animation>();
  103. }
  104. bool Animation::BeginLoad(Deserializer& source)
  105. {
  106. unsigned memoryUse = sizeof(Animation);
  107. // Check ID
  108. if (source.ReadFileID() != "UANI")
  109. {
  110. URHO3D_LOGERROR(source.GetName() + " is not a valid animation file");
  111. return false;
  112. }
  113. // Read name and length
  114. animationName_ = source.ReadString();
  115. animationNameHash_ = animationName_;
  116. length_ = source.ReadFloat();
  117. tracks_.Clear();
  118. unsigned tracks = source.ReadUInt();
  119. memoryUse += tracks * sizeof(AnimationTrack);
  120. // Read tracks
  121. for (unsigned i = 0; i < tracks; ++i)
  122. {
  123. AnimationTrack* newTrack = CreateTrack(source.ReadString());
  124. newTrack->channelMask_ = source.ReadUByte();
  125. unsigned keyFrames = source.ReadUInt();
  126. newTrack->keyFrames_.Resize(keyFrames);
  127. memoryUse += keyFrames * sizeof(AnimationKeyFrame);
  128. // Read keyframes of the track
  129. for (unsigned j = 0; j < keyFrames; ++j)
  130. {
  131. AnimationKeyFrame& newKeyFrame = newTrack->keyFrames_[j];
  132. newKeyFrame.time_ = source.ReadFloat();
  133. if (newTrack->channelMask_ & CHANNEL_POSITION)
  134. newKeyFrame.position_ = source.ReadVector3();
  135. if (newTrack->channelMask_ & CHANNEL_ROTATION)
  136. newKeyFrame.rotation_ = source.ReadQuaternion();
  137. if (newTrack->channelMask_ & CHANNEL_SCALE)
  138. newKeyFrame.scale_ = source.ReadVector3();
  139. }
  140. }
  141. // Optionally read triggers from an XML file
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. String xmlName = ReplaceExtension(GetName(), ".xml");
  144. SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
  145. if (file)
  146. {
  147. XMLElement rootElem = file->GetRoot();
  148. XMLElement triggerElem = rootElem.GetChild("trigger");
  149. while (triggerElem)
  150. {
  151. if (triggerElem.HasAttribute("normalizedtime"))
  152. AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
  153. else if (triggerElem.HasAttribute("time"))
  154. AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
  155. triggerElem = triggerElem.GetNext("trigger");
  156. }
  157. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  158. SetMemoryUse(memoryUse);
  159. return true;
  160. }
  161. // Optionally read triggers from a JSON file
  162. String jsonName = ReplaceExtension(GetName(), ".json");
  163. SharedPtr<JSONFile> jsonFile(cache->GetTempResource<JSONFile>(jsonName, false));
  164. if (jsonFile)
  165. {
  166. const JSONValue& rootVal = jsonFile->GetRoot();
  167. JSONArray triggerArray = rootVal.Get("triggers").GetArray();
  168. for (unsigned i = 0; i < triggerArray.Size(); i++)
  169. {
  170. const JSONValue& triggerValue = triggerArray.At(i);
  171. JSONValue normalizedTimeValue = triggerValue.Get("normalizedTime");
  172. if (!normalizedTimeValue.IsNull())
  173. AddTrigger(normalizedTimeValue.GetFloat(), true, triggerValue.GetVariant());
  174. else
  175. {
  176. JSONValue timeVal = triggerValue.Get("time");
  177. if (!timeVal.IsNull())
  178. AddTrigger(timeVal.GetFloat(), false, triggerValue.GetVariant());
  179. }
  180. }
  181. memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
  182. SetMemoryUse(memoryUse);
  183. return true;
  184. }
  185. SetMemoryUse(memoryUse);
  186. return true;
  187. }
  188. bool Animation::Save(Serializer& dest) const
  189. {
  190. // Write ID, name and length
  191. dest.WriteFileID("UANI");
  192. dest.WriteString(animationName_);
  193. dest.WriteFloat(length_);
  194. // Write tracks
  195. dest.WriteUInt(tracks_.Size());
  196. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  197. {
  198. const AnimationTrack& track = i->second_;
  199. dest.WriteString(track.name_);
  200. dest.WriteUByte(track.channelMask_);
  201. dest.WriteUInt(track.keyFrames_.Size());
  202. // Write keyframes of the track
  203. for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
  204. {
  205. const AnimationKeyFrame& keyFrame = track.keyFrames_[j];
  206. dest.WriteFloat(keyFrame.time_);
  207. if (track.channelMask_ & CHANNEL_POSITION)
  208. dest.WriteVector3(keyFrame.position_);
  209. if (track.channelMask_ & CHANNEL_ROTATION)
  210. dest.WriteQuaternion(keyFrame.rotation_);
  211. if (track.channelMask_ & CHANNEL_SCALE)
  212. dest.WriteVector3(keyFrame.scale_);
  213. }
  214. }
  215. // If triggers have been defined, write an XML file for them
  216. if (triggers_.Size())
  217. {
  218. File* destFile = dynamic_cast<File*>(&dest);
  219. if (destFile)
  220. {
  221. String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
  222. SharedPtr<XMLFile> xml(new XMLFile(context_));
  223. XMLElement rootElem = xml->CreateRoot("animation");
  224. for (unsigned i = 0; i < triggers_.Size(); ++i)
  225. {
  226. XMLElement triggerElem = rootElem.CreateChild("trigger");
  227. triggerElem.SetFloat("time", triggers_[i].time_);
  228. triggerElem.SetVariant(triggers_[i].data_);
  229. }
  230. File xmlFile(context_, xmlName, FILE_WRITE);
  231. xml->Save(xmlFile);
  232. }
  233. else
  234. URHO3D_LOGWARNING("Can not save animation trigger data when not saving into a file");
  235. }
  236. return true;
  237. }
  238. void Animation::SetAnimationName(const String& name)
  239. {
  240. animationName_ = name;
  241. animationNameHash_ = StringHash(name);
  242. }
  243. void Animation::SetLength(float length)
  244. {
  245. length_ = Max(length, 0.0f);
  246. }
  247. AnimationTrack* Animation::CreateTrack(const String& name)
  248. {
  249. /// \todo When tracks / keyframes are created dynamically, memory use is not updated
  250. StringHash nameHash(name);
  251. AnimationTrack* oldTrack = GetTrack(nameHash);
  252. if (oldTrack)
  253. return oldTrack;
  254. AnimationTrack& newTrack = tracks_[nameHash];
  255. newTrack.name_ = name;
  256. newTrack.nameHash_ = nameHash;
  257. return &newTrack;
  258. }
  259. bool Animation::RemoveTrack(const String& name)
  260. {
  261. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  262. if (i != tracks_.End())
  263. {
  264. tracks_.Erase(i);
  265. return true;
  266. }
  267. else
  268. return false;
  269. }
  270. void Animation::RemoveAllTracks()
  271. {
  272. tracks_.Clear();
  273. }
  274. void Animation::SetTrigger(unsigned index, const AnimationTriggerPoint& trigger)
  275. {
  276. if (index == triggers_.Size())
  277. AddTrigger(trigger);
  278. else if (index < triggers_.Size())
  279. {
  280. triggers_[index] = trigger;
  281. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  282. }
  283. }
  284. void Animation::AddTrigger(const AnimationTriggerPoint& trigger)
  285. {
  286. triggers_.Push(trigger);
  287. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  288. }
  289. void Animation::AddTrigger(float time, bool timeIsNormalized, const Variant& data)
  290. {
  291. AnimationTriggerPoint newTrigger;
  292. newTrigger.time_ = timeIsNormalized ? time * length_ : time;
  293. newTrigger.data_ = data;
  294. triggers_.Push(newTrigger);
  295. Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
  296. }
  297. void Animation::RemoveTrigger(unsigned index)
  298. {
  299. if (index < triggers_.Size())
  300. triggers_.Erase(index);
  301. }
  302. void Animation::RemoveAllTriggers()
  303. {
  304. triggers_.Clear();
  305. }
  306. void Animation::SetNumTriggers(unsigned num)
  307. {
  308. triggers_.Resize(num);
  309. }
  310. SharedPtr<Animation> Animation::Clone(const String& cloneName) const
  311. {
  312. SharedPtr<Animation> ret(new Animation(context_));
  313. ret->SetName(cloneName);
  314. ret->SetAnimationName(animationName_);
  315. ret->length_ = length_;
  316. ret->tracks_ = tracks_;
  317. ret->triggers_ = triggers_;
  318. ret->SetMemoryUse(GetMemoryUse());
  319. return ret;
  320. }
  321. AnimationTrack* Animation::GetTrack(unsigned index)
  322. {
  323. if (index >= GetNumTracks())
  324. return (AnimationTrack*) 0;
  325. int j = 0;
  326. for(HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Begin(); i != tracks_.End(); ++i)
  327. {
  328. if (j == index)
  329. return &i->second_;
  330. ++j;
  331. }
  332. return (AnimationTrack*) 0;
  333. }
  334. AnimationTrack* Animation::GetTrack(const String& name)
  335. {
  336. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(StringHash(name));
  337. return i != tracks_.End() ? &i->second_ : (AnimationTrack*)0;
  338. }
  339. AnimationTrack* Animation::GetTrack(StringHash nameHash)
  340. {
  341. HashMap<StringHash, AnimationTrack>::Iterator i = tracks_.Find(nameHash);
  342. return i != tracks_.End() ? &i->second_ : (AnimationTrack*)0;
  343. }
  344. AnimationTriggerPoint* Animation::GetTrigger(unsigned index)
  345. {
  346. return index < triggers_.Size() ? &triggers_[index] : (AnimationTriggerPoint*)0;
  347. }
  348. }