EntityModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. bool EntityModel::ScriptAttachModel(
  135. const char* model, const int bone, const float rx, const float ry, const float rz
  136. ){
  137. Ogre::SceneManager* scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
  138. if (attached_model_ != nullptr){
  139. model_->detachObjectFromBone(attached_model_);
  140. scene_manager->destroyEntity(attached_model_);
  141. attached_model_ = nullptr;
  142. }
  143. const Ogre::String file(model);
  144. if (file.empty()) return true;
  145. Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
  146. if (skeleton == nullptr){
  147. LOG_WARNING("The model '" + name_ + "' has no skeleton to attach '" + file + "' to.");
  148. return false;
  149. }
  150. // Bones are called bone0, bone1... and the skeleton also has a root bone.
  151. const int bone_number = (bone >= 0) ? bone : static_cast<int>(skeleton->getNumBones()) - 2;
  152. const Ogre::String bone_name = "bone" + std::to_string(bone_number);
  153. if (!skeleton->hasBone(bone_name)){
  154. LOG_WARNING("The model '" + name_ + "' has no bone '" + bone_name + "'.");
  155. return false;
  156. }
  157. if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group_, file)){
  158. LOG_WARNING("The model '" + file + "' to attach to '" + name_ + "' doesn't exist.");
  159. return false;
  160. }
  161. attached_model_ = scene_manager->createEntity(name_ + "/" + bone_name + "/" + file, file, resource_group_);
  162. // The vertices of an exported model already include the orientation of the root of its skeleton, the
  163. // same one the bone of this skeleton has. Undo it, or it would be applied twice.
  164. Ogre::Quaternion offset = Ogre::Quaternion::IDENTITY;
  165. Ogre::SkeletonInstance* attached_skeleton = attached_model_->getSkeleton();
  166. if (attached_skeleton != nullptr && attached_skeleton->hasBone("root")){
  167. offset = attached_skeleton->getBone("root")->getOrientation().Inverse();
  168. }
  169. // Extra rotation around the axes of the model itself (the ones of the original files).
  170. const Ogre::Quaternion extra
  171. = Ogre::Quaternion(Ogre::Degree(rx), Ogre::Vector3::UNIT_X)
  172. * Ogre::Quaternion(Ogre::Degree(ry), Ogre::Vector3::UNIT_Y)
  173. * Ogre::Quaternion(Ogre::Degree(rz), Ogre::Vector3::UNIT_Z);
  174. offset = extra * offset;
  175. model_->attachObjectToBone(bone_name, attached_model_, offset);
  176. attached_model_->setVisible(model_->isVisible());
  177. return true;
  178. }
  179. void EntityModel::ScriptSetBlend(const int blend){
  180. if (blend == blend_) return;
  181. blend_ = blend;
  182. // The model held in a bone (a weapon) is drawn like the body.
  183. std::vector<Ogre::Entity*> entities {model_};
  184. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  185. for (Ogre::Entity* entity : entities)
  186. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  187. Ogre::SubEntity* sub_entity = entity->getSubEntity(s);
  188. // Materials are shared among all the entities of a mesh, so use one of its own.
  189. Ogre::MaterialPtr material = OwnMaterial(sub_entity);
  190. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  191. Ogre::Technique* technique = material->getTechnique(t);
  192. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  193. Ogre::Pass* pass = technique->getPass(p);
  194. switch (blend){
  195. case BLEND_ADDITIVE:
  196. pass->setSceneBlending(Ogre::SBT_ADD);
  197. pass->setDepthWriteEnabled(false);
  198. pass->setLightingEnabled(false);
  199. break;
  200. case BLEND_ALPHA:
  201. pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
  202. pass->setDepthWriteEnabled(false);
  203. pass->setLightingEnabled(false);
  204. break;
  205. default:
  206. pass->setSceneBlending(Ogre::SBT_REPLACE);
  207. pass->setDepthWriteEnabled(true);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. /**
  214. * Gets a texture of one white pixel, for the parts that have no texture (they only have the colours of
  215. * the vertices), so a texture unit can give them an opacity.
  216. */
  217. static Ogre::TexturePtr GetWhiteTexture(){
  218. const Ogre::String name = "vgears_white_1x1";
  219. Ogre::TextureManager& manager = Ogre::TextureManager::getSingleton();
  220. Ogre::TexturePtr texture = manager.getByName(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  221. if (texture != nullptr) return texture;
  222. texture = manager.createManual(
  223. name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_BYTE_RGBA
  224. );
  225. unsigned char pixel[4] = {255, 255, 255, 255};
  226. Ogre::PixelBox box(Ogre::Box(0, 0, 1, 1), Ogre::PF_BYTE_RGBA, pixel);
  227. texture->getBuffer()->blitFromMemory(box);
  228. return texture;
  229. }
  230. void EntityModel::ScriptSetAlpha(const float alpha){
  231. if (blend_ == BLEND_NORMAL) return;
  232. const float a = std::max(0.0f, std::min(1.0f, alpha));
  233. std::vector<Ogre::Entity*> entities {model_};
  234. if (attached_model_ != nullptr) entities.push_back(attached_model_);
  235. for (Ogre::Entity* entity : entities)
  236. for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
  237. Ogre::MaterialPtr material = entity->getSubEntity(s)->getMaterial();
  238. for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
  239. Ogre::Technique* technique = material->getTechnique(t);
  240. for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
  241. Ogre::Pass* pass = technique->getPass(p);
  242. // Parts with only vertex colours have no texture unit to change, so give them a white one.
  243. if (pass->getNumTextureUnitStates() == 0) pass->createTextureUnitState()->setTexture(GetWhiteTexture());
  244. for (unsigned short u = 0; u < pass->getNumTextureUnitStates(); ++ u){
  245. Ogre::TextureUnitState* unit = pass->getTextureUnitState(u);
  246. if (blend_ == BLEND_ADDITIVE){
  247. // The colour is added, so less brightness is less opacity.
  248. unit->setColourOperationEx(
  249. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL,
  250. Ogre::ColourValue::White, Ogre::ColourValue(a, a, a)
  251. );
  252. }
  253. else{
  254. unit->setAlphaOperation(
  255. Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0f, a
  256. );
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. void EntityModel::ReleaseResources(){
  264. // The materials are used by the model, so make it use none before removing them.
  265. for (const Ogre::String& name : own_materials_){
  266. // The group is not known here (the material has the one of the original), so search all.
  267. Ogre::MaterialManager& manager = Ogre::MaterialManager::getSingleton();
  268. Ogre::MaterialPtr material = manager.getByName(
  269. name, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
  270. );
  271. if (material != nullptr) manager.remove(material);
  272. }
  273. own_materials_.clear();
  274. }
  275. void EntityModel::PlayAnimation(
  276. const Ogre::String& animation, Entity::AnimationState state,
  277. Entity::AnimationPlayType play_type, const float start, const float end
  278. ){
  279. if (animation_current_ != nullptr) animation_current_->setEnabled(false);
  280. if (
  281. model_->getAllAnimationStates() != nullptr
  282. && model_->getAllAnimationStates()->hasAnimationState(animation) == true
  283. ){
  284. animation_current_name_ = animation;
  285. animation_current_ = model_->getAnimationState(animation);
  286. animation_current_->setLoop((play_type == Entity::PLAY_LOOPED) ? true : false);
  287. // Single frame animations have no length. A looping animation without length wraps its
  288. // time position dividing by zero, ends up with a time that is not a number, and never
  289. // finishes, so any script waiting for it would wait forever.
  290. if (animation_current_->getLength() <= 0.0f) animation_current_->setLoop(false);
  291. animation_current_->setEnabled(true);
  292. animation_current_->setTimePosition(
  293. (start == -1) ? animation_current_->getLength() : start
  294. );
  295. animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
  296. animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
  297. animation_state_ = state;
  298. animation_play_type_ = play_type;
  299. }
  300. else{
  301. // Idle is hard coded to the default animation,
  302. // so don't spam crazy amounts of errors if its not found.
  303. if (animation != "Idle"){
  304. LOG_ERROR(
  305. "Animation '" + animation + "' doesn't exist in model '" + model_->getName() + "'."
  306. );
  307. }
  308. }
  309. }
  310. void EntityModel::PlayAnimationContinue(const Ogre::String& animation){
  311. if (
  312. // If animation isn't being played...
  313. animation_current_ == nullptr
  314. // ... the animatio to play exists (use this to avoid exception)...
  315. || (model_->getAllAnimationStates()->hasAnimationState(animation) == true
  316. && (
  317. // and (the requested animation is not currently playing...
  318. animation_current_ != model_->getAnimationState(animation)
  319. // or it's currently playing but it's not looped)
  320. || animation_play_type_ != Entity::PLAY_LOOPED))
  321. ){
  322. PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  323. }
  324. }
  325. void EntityModel::StopAnimation(){
  326. if (animation_current_ != nullptr){
  327. animation_current_->setEnabled(false);
  328. animation_current_ = nullptr;
  329. }
  330. animation_current_name_.clear();
  331. }
  332. void EntityModel::PlayAnimationPaused(const Ogre::String& animation){
  333. if (!HasAnimation(animation)) return;
  334. if (animation_frozen_ && animation_current_name_ == animation) return;
  335. PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
  336. animation_speed_ = 0.0f;
  337. animation_frozen_ = true;
  338. }
  339. void EntityModel::UnfreezeAnimation(){
  340. if (!animation_frozen_) return;
  341. animation_speed_ = 1.0f;
  342. animation_frozen_ = false;
  343. }
  344. bool EntityModel::HasAnimation(const Ogre::String& animation) const{
  345. return model_->getAllAnimationStates() != nullptr
  346. && model_->getAllAnimationStates()->hasAnimationState(animation);
  347. }
  348. void EntityModel::UpdateAnimation(const float delta){
  349. if (animation_current_ != nullptr){
  350. if (animation_hold_ > 0.0f){
  351. animation_hold_ -= delta;
  352. if (animation_hold_ > 0.0f) return;
  353. }
  354. float delta_mod = delta * animation_speed_;
  355. bool stop_check
  356. = (animation_current_->hasEnded() == true)
  357. || (animation_current_->getTimePosition() + delta_mod >= animation_end_time_);
  358. if (stop_check == true){
  359. //LOG_TRIVIAL("Animation finished for entity \"" + name_ + "\".");
  360. for (size_t i = 0; i < animation_sync_.size(); ++ i)
  361. ScriptManager::getSingleton().ContinueScriptExecution(animation_sync_[i]);
  362. animation_sync_.clear();
  363. if (animation_play_type_ == Entity::PLAY_DEFAULT){
  364. float time = (animation_current_->hasEnded() != true)
  365. ? animation_current_->getTimePosition() : 0;
  366. PlayAnimation(
  367. animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  368. );
  369. animation_current_->addTime(delta_mod);
  370. }
  371. else if (animation_play_type_ == Entity::PLAY_LOOPED){
  372. float time = (animation_current_->hasEnded() != true)
  373. ? animation_current_->getTimePosition()
  374. : animation_current_->getTimePosition() - animation_current_->getLength();
  375. PlayAnimation(
  376. animation_current_name_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, time, -1
  377. );
  378. animation_current_->addTime(delta_mod);
  379. }
  380. }
  381. else animation_current_->addTime(delta_mod);
  382. }
  383. }