EntityModel.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <iostream>
  16. #include <algorithm>
  17. #include <vector>
  18. #include <OgreEntity.h>
  19. #include <OgreSubEntity.h>
  20. #include <OgreBone.h>
  21. #include <OgreSkeletonInstance.h>
  22. #include <OgreMaterialManager.h>
  23. #include <OgreResourceGroupManager.h>
  24. #include <OgreTechnique.h>
  25. #include <OgrePass.h>
  26. #include <OgreRoot.h>
  27. #include <OgreTextureManager.h>
  28. #include <OgreHardwarePixelBuffer.h>
  29. #include "core/EntityModel.h"
  30. #include "core/EntityManager.h"
  31. #include "core/Logger.h"
  32. #include "core/Timer.h"
  33. EntityModel::EntityModel(
  34. const Ogre::String& name, const Ogre::String file_name, Ogre::SceneNode* node,
  35. const Ogre::String& resource_group
  36. ): Entity(name, node), animation_current_(nullptr)
  37. {
  38. Ogre::SceneManager* scene_manager;
  39. Ogre::String res_group = resource_group;
  40. if (res_group.empty()){
  41. switch(EntityManager::getSingleton().GetModule()){
  42. case Manager::BATTLE:
  43. res_group = "BATTLE_MODELS";
  44. break;
  45. case Manager::WORLD:
  46. res_group = "WORLD_MODELS";
  47. break;
  48. case Manager::FIELD:
  49. default:
  50. res_group = "FIELD_MODELS";
  51. }
  52. }
  53. scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
  54. resource_group_ = res_group;
  55. model_ = scene_manager->createEntity(name_, file_name, res_group);
  56. model_->setVisible(false);
  57. PlayAnimation(animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  58. model_node_->attachObject(model_);
  59. }
  60. EntityModel::~EntityModel(){
  61. ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
  62. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(model_);
  63. }
  64. void EntityModel::Update(){
  65. if (animation_auto_play_ == true) UpdateAnimation(Timer::getSingleton().GetGameTimeDelta());
  66. Entity::Update();
  67. }
  68. void EntityModel::SetVisible(const bool visible){
  69. model_->setVisible(visible);
  70. if (attached_model_ != nullptr) attached_model_->setVisible(visible);
  71. }
  72. bool EntityModel::IsVisible() const{return model_->isVisible();}
  73. float EntityModel::GetAnimationLength(const Ogre::String& animation) const{
  74. Ogre::AnimationStateSet* states = model_->getAllAnimationStates();
  75. if (states == nullptr || states->hasAnimationState(animation) == false) return 0.0f;
  76. return states->getAnimationState(animation)->getLength();
  77. }
  78. unsigned int EntityModel::GetAnimationCount() const{
  79. Ogre::AnimationStateSet* states = model_->getAllAnimationStates();
  80. if (states == nullptr) return 0;
  81. return states->getAnimationStates().size();
  82. }
  83. Ogre::String EntityModel::GetAnimationName(const unsigned int index) const{
  84. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  85. if (skeleton == nullptr || index >= skeleton->getNumAnimations()) return "";
  86. return skeleton->getAnimation(index)->getName();
  87. }
  88. Ogre::Entity* EntityModel::GetModel(){return model_;}
  89. Ogre::MaterialPtr EntityModel::OwnMaterial(Ogre::SubEntity* sub_entity){
  90. Ogre::MaterialPtr material = sub_entity->getMaterial();
  91. if (std::find(own_materials_.begin(), own_materials_.end(), material->getName()) == own_materials_.end()){
  92. const Ogre::String own_name = material->getName() + "/" + name_;
  93. Ogre::MaterialPtr own = Ogre::MaterialManager::getSingleton().getByName(own_name, material->getGroup());
  94. if (own == nullptr) own = material->clone(own_name);
  95. own_materials_.push_back(own_name);
  96. sub_entity->setMaterial(own);
  97. material = own;
  98. }
  99. return material;
  100. }
  101. void EntityModel::ScriptSetTexture(const char* texture){
  102. const Ogre::String image(texture);
  103. Ogre::String group;
  104. if (Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", image)) group = "BATTLE_MODELS";
  105. else if (Ogre::ResourceGroupManager::getSingleton().resourceExists("IMAGES", image)) group = "IMAGES";
  106. else{
  107. LOG_WARNING("Image '" + image + "' for the model '" + name_ + "' doesn't exist.");
  108. return;
  109. }
  110. Ogre::TexturePtr loaded = Ogre::TextureManager::getSingleton().load(image, group);
  111. for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
  112. Ogre::MaterialPtr material = OwnMaterial(model_->getSubEntity(s));
  113. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  114. Ogre::Technique* technique = material->getTechnique(t);
  115. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  116. Ogre::Pass* pass = technique->getPass(p);
  117. pass->removeAllTextureUnitStates();
  118. pass->createTextureUnitState()->setTexture(loaded);
  119. pass->setLightingEnabled(false);
  120. }
  121. }
  122. }
  123. }
  124. std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bone){
  125. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  126. const Ogre::String name = "bone" + std::to_string(bone);
  127. if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
  128. // Bring the skeleton to the current frame of the animation.
  129. model_->_updateAnimation();
  130. const Ogre::Vector3 position
  131. = model_->_getParentNodeFullTransform() * skeleton->getBone(name)->_getDerivedPosition();
  132. return std::make_tuple(position.x, position.y, position.z);
  133. }
  134. std::tuple<float, float, float> EntityModel::ScriptGetBoneEnd(const int bone, const float length){
  135. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  136. const Ogre::String name = "bone" + std::to_string(bone);
  137. if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
  138. // Bring the skeleton to the current frame of the animation.
  139. model_->_updateAnimation();
  140. Ogre::Bone* node = skeleton->getBone(name);
  141. // The bones go along their Y axis, where their children are placed.
  142. const Ogre::Vector3 end = node->_getDerivedPosition()
  143. + node->_getDerivedOrientation() * (node->_getDerivedScale() * Ogre::Vector3(0, length, 0));
  144. const Ogre::Vector3 position = model_->_getParentNodeFullTransform() * end;
  145. return std::make_tuple(position.x, position.y, position.z);
  146. }
  147. bool EntityModel::ScriptAttachModel(
  148. const char* model, const int bone, const float rx, const float ry, const float rz
  149. ){
  150. Ogre::SceneManager* scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
  151. if (attached_model_ != nullptr){
  152. model_->detachObjectFromBone(attached_model_);
  153. scene_manager->destroyEntity(attached_model_);
  154. attached_model_ = nullptr;
  155. }
  156. const Ogre::String file(model);
  157. if (file.empty()) return true;
  158. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  159. if (skeleton == nullptr){
  160. LOG_WARNING("The model '" + name_ + "' has no skeleton to attach '" + file + "' to.");
  161. return false;
  162. }
  163. // Bones are called bone0, bone1... and the skeleton also has a root bone.
  164. const int bone_number = (bone >= 0) ? bone : static_cast<int>(skeleton->getNumBones()) - 2;
  165. const Ogre::String bone_name = "bone" + std::to_string(bone_number);
  166. if (!skeleton->hasBone(bone_name)){
  167. LOG_WARNING("The model '" + name_ + "' has no bone '" + bone_name + "'.");
  168. return false;
  169. }
  170. if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group_, file)){
  171. LOG_WARNING("The model '" + file + "' to attach to '" + name_ + "' doesn't exist.");
  172. return false;
  173. }
  174. attached_model_ = scene_manager->createEntity(name_ + "/" + bone_name + "/" + file, file, resource_group_);
  175. // The vertices of an exported model already include the orientation of the root of its skeleton, the
  176. // same one the bone of this skeleton has. Undo it, or it would be applied twice.
  177. Ogre::Quaternion offset = Ogre::Quaternion::IDENTITY;
  178. Ogre::SkeletonInstance* attached_skeleton = attached_model_->getSkeleton();
  179. if (attached_skeleton != nullptr && attached_skeleton->hasBone("root")){
  180. offset = attached_skeleton->getBone("root")->getOrientation().Inverse();
  181. }
  182. // Extra rotation around the axes of the model itself (the ones of the original files).
  183. const Ogre::Quaternion extra
  184. = Ogre::Quaternion(Ogre::Degree(rx), Ogre::Vector3::UNIT_X)
  185. * Ogre::Quaternion(Ogre::Degree(ry), Ogre::Vector3::UNIT_Y)
  186. * Ogre::Quaternion(Ogre::Degree(rz), Ogre::Vector3::UNIT_Z);
  187. offset = extra * offset;
  188. model_->attachObjectToBone(bone_name, attached_model_, offset);
  189. attached_model_->setVisible(model_->isVisible());
  190. return true;
  191. }
  192. void EntityModel::ScriptSetBlend(const int blend){
  193. if (blend == blend_) return;
  194. blend_ = blend;
  195. // The model held in a bone (a weapon) is drawn like the body.
  196. std::vector<Ogre::Entity*> entities {model_};
  197. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  198. for (Ogre::Entity* entity : entities)
  199. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  200. Ogre::SubEntity* sub_entity = entity->getSubEntity(s);
  201. // Materials are shared among all the entities of a mesh, so use one of its own.
  202. Ogre::MaterialPtr material = OwnMaterial(sub_entity);
  203. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  204. Ogre::Technique* technique = material->getTechnique(t);
  205. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  206. Ogre::Pass* pass = technique->getPass(p);
  207. switch (blend){
  208. case BLEND_ADDITIVE:
  209. pass->setSceneBlending(Ogre::SBT_ADD);
  210. pass->setDepthWriteEnabled(false);
  211. pass->setLightingEnabled(false);
  212. break;
  213. case BLEND_ALPHA:
  214. pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  215. pass->setDepthWriteEnabled(false);
  216. pass->setLightingEnabled(false);
  217. break;
  218. default:
  219. pass->setSceneBlending(Ogre::SBT_REPLACE);
  220. pass->setDepthWriteEnabled(true);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * Gets a texture of one white pixel, for the parts that have no texture (they only have the colours of
  228. * the vertices), so a texture unit can give them an opacity.
  229. */
  230. static Ogre::TexturePtr GetWhiteTexture(){
  231. const Ogre::String name = "vgears_white_1x1";
  232. Ogre::TextureManager& manager = Ogre::TextureManager::getSingleton();
  233. Ogre::TexturePtr texture = manager.getByName(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  234. if (texture != nullptr) return texture;
  235. texture = manager.createManual(
  236. name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_BYTE_RGBA
  237. );
  238. unsigned char pixel[4] = {255, 255, 255, 255};
  239. Ogre::PixelBox box(Ogre::Box(0, 0, 1, 1), Ogre::PF_BYTE_RGBA, pixel);
  240. texture->getBuffer()->blitFromMemory(box);
  241. return texture;
  242. }
  243. void EntityModel::ScriptSetAlpha(const float alpha){
  244. if (blend_ == BLEND_NORMAL) return;
  245. const float a = std::max(0.0f, std::min(1.0f, alpha));
  246. std::vector<Ogre::Entity*> entities {model_};
  247. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  248. for (Ogre::Entity* entity : entities)
  249. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  250. Ogre::MaterialPtr material = entity->getSubEntity(s)->getMaterial();
  251. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  252. Ogre::Technique* technique = material->getTechnique(t);
  253. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  254. Ogre::Pass* pass = technique->getPass(p);
  255. // Parts with only vertex colours have no texture unit to change, so give them a white one.
  256. if (pass->getNumTextureUnitStates() == 0) pass->createTextureUnitState()->setTexture(GetWhiteTexture());
  257. for (unsigned short u = 0; u < pass->getNumTextureUnitStates(); ++ u){
  258. Ogre::TextureUnitState* unit = pass->getTextureUnitState(u);
  259. if (blend_ == BLEND_ADDITIVE){
  260. // The colour is added, so less brightness is less opacity.
  261. unit->setColourOperationEx(
  262. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL,
  263. Ogre::ColourValue::White, Ogre::ColourValue(a, a, a)
  264. );
  265. }
  266. else{
  267. unit->setAlphaOperation(
  268. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0f, a
  269. );
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
  276. void EntityModel::ReleaseResources(){
  277. // The materials are used by the model, so make it use none before removing them.
  278. for (const Ogre::String& name : own_materials_){
  279. // The group is not known here (the material has the one of the original), so search all.
  280. Ogre::MaterialManager& manager = Ogre::MaterialManager::getSingleton();
  281. Ogre::MaterialPtr material = manager.getByName(
  282. name, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
  283. );
  284. if (material != nullptr) manager.remove(material);
  285. }
  286. own_materials_.clear();
  287. }
  288. void EntityModel::PlayAnimation(
  289. const Ogre::String& animation, Entity::AnimationState state,
  290. Entity::AnimationPlayType play_type, const float start, const float end
  291. ){
  292. if (animation_current_ != nullptr) animation_current_->setEnabled(false);
  293. if (
  294. model_->getAllAnimationStates() != nullptr
  295. && model_->getAllAnimationStates()->hasAnimationState(animation) == true
  296. ){
  297. animation_current_name_ = animation;
  298. animation_current_ = model_->getAnimationState(animation);
  299. animation_current_->setLoop((play_type == Entity::PLAY_LOOPED) ? true : false);
  300. // Single frame animations have no length. A looping animation without length wraps its
  301. // time position dividing by zero, ends up with a time that is not a number, and never
  302. // finishes, so any script waiting for it would wait forever.
  303. if (animation_current_->getLength() <= 0.0f) animation_current_->setLoop(false);
  304. animation_current_->setEnabled(true);
  305. // A pose at the very end of the animation (the dead soldiers of shpin_3, that hold the last
  306. // frame) is shown as the first frame: past the last key, the interpolation goes on to the
  307. // first one, as it does when it loops. The time stays a hair before the end.
  308. float time = (start == -1) ? animation_current_->getLength() : start;
  309. const float length = animation_current_->getLength();
  310. if (length > 0.0f && time >= length) time = std::max(0.0f, length - 0.0005f);
  311. animation_current_->setTimePosition(time);
  312. animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
  313. animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
  314. animation_state_ = state;
  315. animation_play_type_ = play_type;
  316. }
  317. else{
  318. // Idle is hard coded to the default animation,
  319. // so don't spam crazy amounts of errors if its not found.
  320. if (animation != "Idle"){
  321. LOG_ERROR(
  322. "Animation '" + animation + "' doesn't exist in model '" + model_->getName() + "'."
  323. );
  324. }
  325. }
  326. }
  327. void EntityModel::PlayAnimationContinue(const Ogre::String& animation){
  328. if (
  329. // If animation isn't being played...
  330. animation_current_ == nullptr
  331. // ... the animatio to play exists (use this to avoid exception)...
  332. || (model_->getAllAnimationStates()->hasAnimationState(animation) == true
  333. && (
  334. // and (the requested animation is not currently playing...
  335. animation_current_ != model_->getAnimationState(animation)
  336. // or it's currently playing but it's not looped)
  337. || animation_play_type_ != Entity::PLAY_LOOPED))
  338. ){
  339. PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  340. }
  341. }
  342. void EntityModel::StopAnimation(){
  343. if (animation_current_ != nullptr){
  344. animation_current_->setEnabled(false);
  345. animation_current_ = nullptr;
  346. }
  347. animation_current_name_.clear();
  348. }
  349. void EntityModel::PlayAnimationPaused(const Ogre::String& animation){
  350. if (!HasAnimation(animation)) return;
  351. if (animation_frozen_ && animation_current_name_ == animation) return;
  352. PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  353. animation_speed_ = 0.0f;
  354. animation_frozen_ = true;
  355. }
  356. void EntityModel::UnfreezeAnimation(){
  357. if (!animation_frozen_) return;
  358. animation_speed_ = 1.0f;
  359. animation_frozen_ = false;
  360. }
  361. bool EntityModel::HasAnimation(const Ogre::String& animation) const{
  362. return model_->getAllAnimationStates() != nullptr
  363. && model_->getAllAnimationStates()->hasAnimationState(animation);
  364. }
  365. void EntityModel::UpdateAnimation(const float delta){
  366. if (animation_current_ != nullptr){
  367. if (animation_hold_ > 0.0f){
  368. animation_hold_ -= delta;
  369. if (animation_hold_ > 0.0f) return;
  370. }
  371. float delta_mod = delta * animation_speed_;
  372. bool stop_check
  373. = (animation_current_->hasEnded() == true)
  374. || (animation_current_->getTimePosition() + delta_mod >= animation_end_time_);
  375. if (stop_check == true){
  376. //LOG_TRIVIAL("Animation finished for entity \"" + name_ + "\".");
  377. for (size_t i = 0; i < animation_sync_.size(); ++ i)
  378. ScriptManager::getSingleton().ContinueScriptExecution(animation_sync_[i]);
  379. animation_sync_.clear();
  380. if (animation_play_type_ == Entity::PLAY_DEFAULT){
  381. float time = (animation_current_->hasEnded() != true)
  382. ? animation_current_->getTimePosition() : 0;
  383. PlayAnimation(
  384. animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  385. );
  386. animation_current_->addTime(delta_mod);
  387. }
  388. else if (animation_play_type_ == Entity::PLAY_LOOPED){
  389. float time = (animation_current_->hasEnded() != true)
  390. ? animation_current_->getTimePosition()
  391. : animation_current_->getTimePosition() - animation_current_->getLength();
  392. PlayAnimation(
  393. animation_current_name_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  394. );
  395. animation_current_->addTime(delta_mod);
  396. }
  397. }
  398. else animation_current_->addTime(delta_mod);
  399. }
  400. }