UIComponent.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //
  2. // Copyright (c) 2008-2022 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 "../Core/Context.h"
  24. #include "../Graphics/BillboardSet.h"
  25. #include "../Graphics/Graphics.h"
  26. #include "../Graphics/Octree.h"
  27. #include "../Graphics/Technique.h"
  28. #include "../Graphics/Material.h"
  29. #include "../Graphics/Texture2D.h"
  30. #include "../Graphics/StaticModel.h"
  31. #include "../Graphics/Renderer.h"
  32. #include "../Graphics/Camera.h"
  33. #include "../Graphics/VertexBuffer.h"
  34. #include "../Scene/Scene.h"
  35. #include "../Scene/SceneEvents.h"
  36. #include "../Resource/ResourceCache.h"
  37. #include "../IO/Log.h"
  38. #include "../UI/UI.h"
  39. #include "../UI/UIComponent.h"
  40. #include "../UI/UIEvents.h"
  41. #include "../DebugNew.h"
  42. namespace Urho3D
  43. {
  44. static int const UICOMPONENT_DEFAULT_TEXTURE_SIZE = 512;
  45. static int const UICOMPONENT_MIN_TEXTURE_SIZE = 64;
  46. static int const UICOMPONENT_MAX_TEXTURE_SIZE = 4096;
  47. class UIElement3D : public UIElement
  48. {
  49. URHO3D_OBJECT(UIElement3D, UIElement);
  50. public:
  51. /// Construct.
  52. explicit UIElement3D(Context* context) : UIElement(context) { }
  53. /// Destruct.
  54. ~UIElement3D() override = default;
  55. /// Set UIComponent which is using this element as root element.
  56. void SetNode(Node* node) { node_ = node; }
  57. /// Set active viewport through which this element is rendered. If viewport is not set, it defaults to first viewport.
  58. void SetViewport(Viewport* viewport) { viewport_ = viewport; }
  59. /// Convert element coordinates to screen coordinates.
  60. IntVector2 ElementToScreen(const IntVector2& position) override
  61. {
  62. URHO3D_LOGERROR("UIElement3D::ElementToScreen is not implemented.");
  63. return {-1, -1};
  64. }
  65. /// Convert screen coordinates to element coordinates.
  66. IntVector2 ScreenToElement(const IntVector2& screenPos) override
  67. {
  68. IntVector2 result(-1, -1);
  69. if (node_.Expired())
  70. return result;
  71. Scene* scene = node_->GetScene();
  72. auto* model = node_->GetComponent<StaticModel>();
  73. if (scene == nullptr || model == nullptr)
  74. return result;
  75. auto* renderer = GetSubsystem<Renderer>();
  76. if (renderer == nullptr)
  77. return result;
  78. // \todo Always uses the first viewport, in case there are multiple
  79. auto* octree = scene->GetComponent<Octree>();
  80. if (viewport_ == nullptr)
  81. viewport_ = renderer->GetViewportForScene(scene, 0);
  82. if (viewport_.Expired() || octree == nullptr)
  83. return result;
  84. if (viewport_->GetScene() != scene)
  85. {
  86. URHO3D_LOGERROR("UIComponent and Viewport set to component's root element belong to different scenes.");
  87. return result;
  88. }
  89. Camera* camera = viewport_->GetCamera();
  90. if (camera == nullptr)
  91. return result;
  92. IntRect rect = viewport_->GetRect();
  93. if (rect == IntRect::ZERO)
  94. {
  95. auto* graphics = GetSubsystem<Graphics>();
  96. rect.right_ = graphics->GetWidth();
  97. rect.bottom_ = graphics->GetHeight();
  98. }
  99. auto* ui = GetSubsystem<UI>();
  100. // Convert to system mouse position
  101. IntVector2 pos;
  102. pos = ui->ConvertUIToSystem(screenPos);
  103. Ray ray(camera->GetScreenRay((float)pos.x_ / rect.Width(), (float)pos.y_ / rect.Height()));
  104. PODVector<RayQueryResult> queryResultVector;
  105. RayOctreeQuery query(queryResultVector, ray, RAY_TRIANGLE_UV, M_INFINITY, DRAWABLE_GEOMETRY, DEFAULT_VIEWMASK);
  106. octree->Raycast(query);
  107. if (queryResultVector.Empty())
  108. return result;
  109. for (unsigned i = 0; i < queryResultVector.Size(); i++)
  110. {
  111. RayQueryResult& queryResult = queryResultVector[i];
  112. if (queryResult.drawable_ != model)
  113. {
  114. // ignore billboard sets by default
  115. if (queryResult.drawable_->GetTypeInfo()->IsTypeOf(BillboardSet::GetTypeStatic()))
  116. continue;
  117. return result;
  118. }
  119. Vector2& uv = queryResult.textureUV_;
  120. result = IntVector2(static_cast<int>(uv.x_ * GetWidth()),
  121. static_cast<int>(uv.y_ * GetHeight()));
  122. // Convert back to scaled UI position
  123. result = ui->ConvertSystemToUI(result);
  124. return result;
  125. }
  126. return result;
  127. }
  128. protected:
  129. /// A UIComponent which owns this element.
  130. WeakPtr<Node> node_;
  131. /// Viewport which renders this element.
  132. WeakPtr<Viewport> viewport_;
  133. };
  134. UIComponent::UIComponent(Context* context)
  135. : Component(context),
  136. viewportIndex_(0)
  137. {
  138. texture_ = context_->CreateObject<Texture2D>();
  139. texture_->SetFilterMode(FILTER_BILINEAR);
  140. texture_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  141. texture_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  142. texture_->SetNumLevels(1); // No mipmaps
  143. rootElement_ = context_->CreateObject<UIElement3D>();
  144. rootElement_->SetTraversalMode(TM_BREADTH_FIRST);
  145. rootElement_->SetEnabled(true);
  146. material_ = context_->CreateObject<Material>();
  147. material_->SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/Diff.xml"));
  148. material_->SetTexture(TU_DIFFUSE, texture_);
  149. SubscribeToEvent(rootElement_, E_RESIZED, URHO3D_HANDLER(UIComponent, OnElementResized));
  150. // Triggers resizing of texture.
  151. rootElement_->SetRenderTexture(texture_);
  152. rootElement_->SetSize(UICOMPONENT_DEFAULT_TEXTURE_SIZE, UICOMPONENT_DEFAULT_TEXTURE_SIZE);
  153. }
  154. UIComponent::~UIComponent() = default;
  155. void UIComponent::RegisterObject(Context* context)
  156. {
  157. context->RegisterFactory<UIComponent>();
  158. context->RegisterFactory<UIElement3D>();
  159. }
  160. UIElement* UIComponent::GetRoot() const
  161. {
  162. return rootElement_;
  163. }
  164. Material* UIComponent::GetMaterial() const
  165. {
  166. return material_;
  167. }
  168. Texture2D* UIComponent::GetTexture() const
  169. {
  170. return texture_;
  171. }
  172. void UIComponent::OnNodeSet(Node* node)
  173. {
  174. rootElement_->SetNode(node);
  175. if (node)
  176. {
  177. auto* renderer = GetSubsystem<Renderer>();
  178. auto* model = node->GetComponent<StaticModel>();
  179. rootElement_->SetViewport(renderer->GetViewportForScene(GetScene(), viewportIndex_));
  180. if (model == nullptr)
  181. model_ = model = node->CreateComponent<StaticModel>();
  182. model->SetMaterial(material_);
  183. rootElement_->SetRenderTexture(texture_);
  184. }
  185. else
  186. {
  187. rootElement_->SetRenderTexture(nullptr);
  188. if (model_.NotNull())
  189. {
  190. model_->Remove();
  191. model_ = nullptr;
  192. }
  193. }
  194. }
  195. void UIComponent::OnElementResized(StringHash eventType, VariantMap& args)
  196. {
  197. int width = args[Resized::P_WIDTH].GetInt();
  198. int height = args[Resized::P_HEIGHT].GetInt();
  199. if (width < UICOMPONENT_MIN_TEXTURE_SIZE || width > UICOMPONENT_MAX_TEXTURE_SIZE ||
  200. height < UICOMPONENT_MIN_TEXTURE_SIZE || height > UICOMPONENT_MAX_TEXTURE_SIZE)
  201. {
  202. URHO3D_LOGERRORF("UIComponent: Texture size %dx%d is not valid. Width and height should be between %d and %d.",
  203. width, height, UICOMPONENT_MIN_TEXTURE_SIZE, UICOMPONENT_MAX_TEXTURE_SIZE);
  204. return;
  205. }
  206. if (texture_->SetSize(width, height, Graphics::GetRGBAFormat(), TEXTURE_RENDERTARGET))
  207. texture_->GetRenderSurface()->SetUpdateMode(SURFACE_MANUALUPDATE);
  208. else
  209. URHO3D_LOGERROR("UIComponent: resizing texture failed.");
  210. }
  211. void UIComponent::SetViewportIndex(unsigned int index)
  212. {
  213. viewportIndex_ = index;
  214. if (Scene* scene = GetScene())
  215. {
  216. auto* renderer = GetSubsystem<Renderer>();
  217. Viewport* viewport = renderer->GetViewportForScene(scene, index);
  218. rootElement_->SetViewport(viewport);
  219. }
  220. }
  221. }