UI.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Container/Sort.h"
  5. #include "../Core/Context.h"
  6. #include "../Core/CoreEvents.h"
  7. #include "../Core/Profiler.h"
  8. #include "../Graphics/Camera.h"
  9. #include "../Graphics/Graphics.h"
  10. #include "../Graphics/GraphicsEvents.h"
  11. #include "../Graphics/Octree.h"
  12. #include "../Graphics/Technique.h"
  13. #include "../Graphics/Viewport.h"
  14. #include "../GraphicsAPI/Shader.h"
  15. #include "../GraphicsAPI/ShaderVariation.h"
  16. #include "../GraphicsAPI/Texture2D.h"
  17. #include "../GraphicsAPI/VertexBuffer.h"
  18. #include "../Input/Input.h"
  19. #include "../Input/InputEvents.h"
  20. #include "../IO/Log.h"
  21. #include "../Math/Matrix3x4.h"
  22. #include "../Resource/ResourceCache.h"
  23. #include "../Scene/Scene.h"
  24. #include "../UI/CheckBox.h"
  25. #include "../UI/Cursor.h"
  26. #include "../UI/DropDownList.h"
  27. #include "../UI/FileSelector.h"
  28. #include "../UI/Font.h"
  29. #include "../UI/LineEdit.h"
  30. #include "../UI/ListView.h"
  31. #include "../UI/MessageBox.h"
  32. #include "../UI/ProgressBar.h"
  33. #include "../UI/ScrollBar.h"
  34. #include "../UI/Slider.h"
  35. #include "../UI/Sprite.h"
  36. #include "../UI/Text.h"
  37. #include "../UI/Text3D.h"
  38. #include "../UI/ToolTip.h"
  39. #include "../UI/UI.h"
  40. #include "../UI/UIComponent.h"
  41. #include "../UI/UIEvents.h"
  42. #include "../UI/View3D.h"
  43. #include "../UI/Window.h"
  44. #include <cassert>
  45. #include <SDL/SDL.h>
  46. #include "../DebugNew.h"
  47. namespace Urho3D
  48. {
  49. static MouseButton MakeTouchIDMask(int id)
  50. {
  51. return static_cast<MouseButton>(1u << static_cast<MouseButtonFlags::Integer>(id)); // NOLINT(misc-misplaced-widening-cast)
  52. }
  53. StringHash VAR_ORIGIN("Origin");
  54. const StringHash VAR_ORIGINAL_PARENT("OriginalParent");
  55. const StringHash VAR_ORIGINAL_CHILD_INDEX("OriginalChildIndex");
  56. const StringHash VAR_PARENT_CHANGED("ParentChanged");
  57. const float DEFAULT_DOUBLECLICK_INTERVAL = 0.5f;
  58. const float DEFAULT_DRAGBEGIN_INTERVAL = 0.5f;
  59. const float DEFAULT_TOOLTIP_DELAY = 0.5f;
  60. const int DEFAULT_DRAGBEGIN_DISTANCE = 5;
  61. const int DEFAULT_FONT_TEXTURE_MAX_SIZE = 2048;
  62. const char* UI_CATEGORY = "UI";
  63. UI::UI(Context* context) :
  64. Object(context),
  65. rootElement_(new UIElement(context)),
  66. rootModalElement_(new UIElement(context)),
  67. doubleClickInterval_(DEFAULT_DOUBLECLICK_INTERVAL),
  68. dragBeginInterval_(DEFAULT_DRAGBEGIN_INTERVAL),
  69. defaultToolTipDelay_(DEFAULT_TOOLTIP_DELAY),
  70. dragBeginDistance_(DEFAULT_DRAGBEGIN_DISTANCE),
  71. mouseButtons_(0),
  72. lastMouseButtons_(0),
  73. maxDoubleClickDist_(M_LARGE_VALUE),
  74. qualifiers_(0),
  75. maxFontTextureSize_(DEFAULT_FONT_TEXTURE_MAX_SIZE),
  76. initialized_(false),
  77. usingTouchInput_(false),
  78. #ifdef _WIN32
  79. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  80. #else
  81. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  82. #endif
  83. useSystemClipboard_(false),
  84. #if defined(__ANDROID__) || defined(IOS) || defined(TVOS)
  85. useScreenKeyboard_(true),
  86. #else
  87. useScreenKeyboard_(false),
  88. #endif
  89. useMutableGlyphs_(false),
  90. forceAutoHint_(false),
  91. fontHintLevel_(FONT_HINT_LEVEL_NORMAL),
  92. fontSubpixelThreshold_(12),
  93. fontOversampling_(2),
  94. uiRendered_(false),
  95. nonModalBatchSize_(0),
  96. dragElementsCount_(0),
  97. dragConfirmedCount_(0),
  98. uiScale_(1.0f),
  99. customSize_(IntVector2::ZERO)
  100. {
  101. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  102. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  103. // Register UI library object factories
  104. RegisterUILibrary(context_);
  105. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(UI, HandleScreenMode));
  106. SubscribeToEvent(E_MOUSEBUTTONDOWN, URHO3D_HANDLER(UI, HandleMouseButtonDown));
  107. SubscribeToEvent(E_MOUSEBUTTONUP, URHO3D_HANDLER(UI, HandleMouseButtonUp));
  108. SubscribeToEvent(E_MOUSEMOVE, URHO3D_HANDLER(UI, HandleMouseMove));
  109. SubscribeToEvent(E_MOUSEWHEEL, URHO3D_HANDLER(UI, HandleMouseWheel));
  110. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(UI, HandleTouchBegin));
  111. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(UI, HandleTouchEnd));
  112. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(UI, HandleTouchMove));
  113. SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(UI, HandleKeyDown));
  114. SubscribeToEvent(E_TEXTINPUT, URHO3D_HANDLER(UI, HandleTextInput));
  115. SubscribeToEvent(E_DROPFILE, URHO3D_HANDLER(UI, HandleDropFile));
  116. // Try to initialize right now, but skip if screen mode is not yet set
  117. Initialize();
  118. }
  119. UI::~UI() = default;
  120. void UI::SetCursor(Cursor* cursor)
  121. {
  122. if (cursor_ == cursor)
  123. return;
  124. // Remove old cursor (if any) and set new
  125. if (cursor_)
  126. {
  127. rootElement_->RemoveChild(cursor_);
  128. cursor_.Reset();
  129. }
  130. if (cursor)
  131. {
  132. rootElement_->AddChild(cursor);
  133. cursor_ = cursor;
  134. IntVector2 pos = cursor_->GetPosition();
  135. const IntVector2& rootSize = rootElement_->GetSize();
  136. const IntVector2& rootPos = rootElement_->GetPosition();
  137. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  138. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  139. cursor_->SetPosition(pos);
  140. }
  141. }
  142. void UI::SetFocusElement(UIElement* element, bool byKey)
  143. {
  144. using namespace FocusChanged;
  145. UIElement* originalElement = element;
  146. if (element)
  147. {
  148. // Return if already has focus
  149. if (focusElement_ == element)
  150. return;
  151. // Only allow child elements of the modal element to receive focus
  152. if (HasModalElement())
  153. {
  154. UIElement* topLevel = element->GetParent();
  155. while (topLevel && topLevel->GetParent() != rootElement_)
  156. topLevel = topLevel->GetParent();
  157. if (topLevel) // If parented to non-modal root then ignore
  158. return;
  159. }
  160. // Search for an element in the hierarchy that can alter focus. If none found, exit
  161. element = GetFocusableElement(element);
  162. if (!element)
  163. return;
  164. }
  165. // Remove focus from the old element
  166. if (focusElement_)
  167. {
  168. UIElement* oldFocusElement = focusElement_;
  169. focusElement_.Reset();
  170. VariantMap& focusEventData = GetEventDataMap();
  171. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  172. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  173. }
  174. // Then set focus to the new
  175. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  176. {
  177. focusElement_ = element;
  178. VariantMap& focusEventData = GetEventDataMap();
  179. focusEventData[Focused::P_ELEMENT] = element;
  180. focusEventData[Focused::P_BYKEY] = byKey;
  181. element->SendEvent(E_FOCUSED, focusEventData);
  182. }
  183. VariantMap& eventData = GetEventDataMap();
  184. eventData[P_CLICKEDELEMENT] = originalElement;
  185. eventData[P_ELEMENT] = element;
  186. SendEvent(E_FOCUSCHANGED, eventData);
  187. }
  188. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  189. {
  190. if (!modalElement)
  191. return false;
  192. // Currently only allow modal window
  193. if (modalElement->GetType() != Window::GetTypeStatic())
  194. return false;
  195. assert(rootModalElement_);
  196. UIElement* currParent = modalElement->GetParent();
  197. if (enable)
  198. {
  199. // Make sure it is not already the child of the root modal element
  200. if (currParent == rootModalElement_)
  201. return false;
  202. // Adopt modal root as parent
  203. modalElement->SetVar(VAR_ORIGINAL_PARENT, currParent);
  204. modalElement->SetVar(VAR_ORIGINAL_CHILD_INDEX, currParent ? currParent->FindChild(modalElement) : M_MAX_UNSIGNED);
  205. modalElement->SetParent(rootModalElement_);
  206. // If it is a popup element, bring along its top-level parent
  207. auto* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  208. if (originElement)
  209. {
  210. UIElement* element = originElement;
  211. while (element && element->GetParent() != rootElement_)
  212. element = element->GetParent();
  213. if (element)
  214. {
  215. originElement->SetVar(VAR_PARENT_CHANGED, element);
  216. UIElement* oriParent = element->GetParent();
  217. element->SetVar(VAR_ORIGINAL_PARENT, oriParent);
  218. element->SetVar(VAR_ORIGINAL_CHILD_INDEX, oriParent ? oriParent->FindChild(element) : M_MAX_UNSIGNED);
  219. element->SetParent(rootModalElement_);
  220. }
  221. }
  222. return true;
  223. }
  224. else
  225. {
  226. // Only the modal element can disable itself
  227. if (currParent != rootModalElement_)
  228. return false;
  229. // Revert back to original parent
  230. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  231. modalElement->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  232. auto& vars = const_cast<VariantMap&>(modalElement->GetVars());
  233. vars.Erase(VAR_ORIGINAL_PARENT);
  234. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  235. // If it is a popup element, revert back its top-level parent
  236. auto* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  237. if (originElement)
  238. {
  239. auto* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  240. if (element)
  241. {
  242. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  243. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()),
  244. element->GetVar(VAR_ORIGINAL_CHILD_INDEX).GetUInt());
  245. vars = const_cast<VariantMap&>(element->GetVars());
  246. vars.Erase(VAR_ORIGINAL_PARENT);
  247. vars.Erase(VAR_ORIGINAL_CHILD_INDEX);
  248. }
  249. }
  250. return true;
  251. }
  252. }
  253. void UI::Clear()
  254. {
  255. rootElement_->RemoveAllChildren();
  256. rootModalElement_->RemoveAllChildren();
  257. if (cursor_)
  258. rootElement_->AddChild(cursor_);
  259. }
  260. void UI::Update(float timeStep)
  261. {
  262. assert(rootElement_ && rootModalElement_);
  263. URHO3D_PROFILE(UpdateUI);
  264. // Expire hovers
  265. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End(); ++i)
  266. i->second_ = false;
  267. auto* input = GetSubsystem<Input>();
  268. bool mouseGrabbed = input->IsMouseGrabbed();
  269. IntVector2 cursorPos;
  270. bool cursorVisible;
  271. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  272. // Drag begin based on time
  273. if (dragElementsCount_ > 0 && !mouseGrabbed)
  274. {
  275. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  276. {
  277. WeakPtr<UIElement> dragElement = i->first_;
  278. UI::DragData* dragData = i->second_;
  279. if (!dragElement)
  280. {
  281. i = DragElementErase(i);
  282. continue;
  283. }
  284. if (!dragData->dragBeginPending)
  285. {
  286. ++i;
  287. continue;
  288. }
  289. if (dragData->dragBeginTimer.GetMSec(false) >= (unsigned)(dragBeginInterval_ * 1000))
  290. {
  291. dragData->dragBeginPending = false;
  292. IntVector2 beginSendPos = dragData->dragBeginSumPos / dragData->numDragButtons;
  293. dragConfirmedCount_++;
  294. if (!usingTouchInput_)
  295. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons,
  296. qualifiers_, cursor_);
  297. else
  298. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, dragData->dragButtons, QUAL_NONE, nullptr);
  299. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  300. }
  301. ++i;
  302. }
  303. }
  304. // Mouse hover
  305. if (!mouseGrabbed && !input->GetTouchEmulation())
  306. {
  307. if (!usingTouchInput_ && cursorVisible)
  308. ProcessHover(cursorPos, mouseButtons_, qualifiers_, cursor_);
  309. }
  310. // Touch hover
  311. unsigned numTouches = input->GetNumTouches();
  312. for (unsigned i = 0; i < numTouches; ++i)
  313. {
  314. TouchState* touch = input->GetTouch(i);
  315. IntVector2 touchPos = touch->position_;
  316. touchPos = ConvertSystemToUI(touchPos);
  317. ProcessHover(touchPos, MakeTouchIDMask(touch->touchID_), QUAL_NONE, nullptr);
  318. }
  319. // End hovers that expired without refreshing
  320. for (HashMap<WeakPtr<UIElement>, bool>::Iterator i = hoveredElements_.Begin(); i != hoveredElements_.End();)
  321. {
  322. if (i->first_.Expired() || !i->second_)
  323. {
  324. UIElement* element = i->first_;
  325. if (element)
  326. {
  327. using namespace HoverEnd;
  328. VariantMap& eventData = GetEventDataMap();
  329. eventData[P_ELEMENT] = element;
  330. element->SendEvent(E_HOVEREND, eventData);
  331. }
  332. i = hoveredElements_.Erase(i);
  333. }
  334. else
  335. ++i;
  336. }
  337. Update(timeStep, rootElement_);
  338. Update(timeStep, rootModalElement_);
  339. }
  340. void UI::RenderUpdate()
  341. {
  342. assert(rootElement_ && rootModalElement_ && graphics_);
  343. URHO3D_PROFILE(GetUIBatches);
  344. uiRendered_ = false;
  345. // If the OS cursor is visible, do not render the UI's own cursor
  346. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  347. // Get rendering batches from the non-modal UI elements
  348. batches_.Clear();
  349. vertexData_.Clear();
  350. const IntVector2& rootSize = rootElement_->GetSize();
  351. const IntVector2& rootPos = rootElement_->GetPosition();
  352. // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
  353. IntRect currentScissor = IntRect(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
  354. if (rootElement_->IsVisible())
  355. GetBatches(batches_, vertexData_, rootElement_, currentScissor);
  356. // Save the batch size of the non-modal batches for later use
  357. nonModalBatchSize_ = batches_.Size();
  358. // Get rendering batches from the modal UI elements
  359. GetBatches(batches_, vertexData_, rootModalElement_, currentScissor);
  360. // Get batches from the cursor (and its possible children) last to draw it on top of everything
  361. if (cursor_ && cursor_->IsVisible() && !osCursorVisible)
  362. {
  363. currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  364. cursor_->GetBatches(batches_, vertexData_, currentScissor);
  365. GetBatches(batches_, vertexData_, cursor_, currentScissor);
  366. }
  367. // Get batches for UI elements rendered into textures. Each element rendered into texture is treated as root element.
  368. for (auto it = renderToTexture_.Begin(); it != renderToTexture_.End();)
  369. {
  370. RenderToTextureData& data = it->second_;
  371. if (data.rootElement_.Expired())
  372. {
  373. it = renderToTexture_.Erase(it);
  374. continue;
  375. }
  376. if (data.rootElement_->IsEnabled())
  377. {
  378. data.batches_.Clear();
  379. data.vertexData_.Clear();
  380. UIElement* element = data.rootElement_;
  381. const IntVector2& size = element->GetSize();
  382. const IntVector2& pos = element->GetPosition();
  383. // Note: the scissors operate on unscaled coordinates. Scissor scaling is only performed during render
  384. IntRect scissor = IntRect(pos.x_, pos.y_, pos.x_ + size.x_, pos.y_ + size.y_);
  385. GetBatches(data.batches_, data.vertexData_, element, scissor);
  386. // UIElement does not have anything to show. Insert dummy batch that will clear the texture.
  387. if (data.batches_.Empty())
  388. {
  389. UIBatch batch(element, BLEND_REPLACE, scissor, nullptr, &data.vertexData_);
  390. batch.SetColor(Color::BLACK);
  391. batch.AddQuad(scissor.left_, scissor.top_, scissor.right_, scissor.bottom_, 0, 0);
  392. data.batches_.Push(batch);
  393. }
  394. }
  395. ++it;
  396. }
  397. }
  398. void UI::Render(bool renderUICommand)
  399. {
  400. URHO3D_PROFILE(RenderUI);
  401. // If the OS cursor is visible, apply its shape now if changed
  402. if (!renderUICommand)
  403. {
  404. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  405. if (cursor_ && osCursorVisible)
  406. cursor_->ApplyOSCursorShape();
  407. }
  408. // Perform the default backbuffer render only if not rendered yet, or additional renders through RenderUI command
  409. if (renderUICommand || !uiRendered_)
  410. {
  411. SetVertexData(vertexBuffer_, vertexData_);
  412. SetVertexData(debugVertexBuffer_, debugVertexData_);
  413. if (!renderUICommand)
  414. graphics_->ResetRenderTargets();
  415. // Render non-modal batches
  416. Render(vertexBuffer_, batches_, 0, nonModalBatchSize_);
  417. // Render debug draw
  418. Render(debugVertexBuffer_, debugDrawBatches_, 0, debugDrawBatches_.Size());
  419. // Render modal batches
  420. Render(vertexBuffer_, batches_, nonModalBatchSize_, batches_.Size());
  421. }
  422. // Render to UIComponent textures. This is skipped when called from the RENDERUI command
  423. if (!renderUICommand)
  424. {
  425. for (auto& item : renderToTexture_)
  426. {
  427. RenderToTextureData& data = item.second_;
  428. if (data.rootElement_->IsEnabled())
  429. {
  430. SetVertexData(data.vertexBuffer_, data.vertexData_);
  431. SetVertexData(data.debugVertexBuffer_, data.debugVertexData_);
  432. RenderSurface* surface = data.texture_->GetRenderSurface();
  433. graphics_->SetDepthStencil(surface->GetLinkedDepthStencil());
  434. graphics_->SetRenderTarget(0, surface);
  435. graphics_->SetViewport(IntRect(0, 0, surface->GetWidth(), surface->GetHeight()));
  436. graphics_->Clear(Urho3D::CLEAR_COLOR);
  437. Render(data.vertexBuffer_, data.batches_, 0, data.batches_.Size());
  438. Render(data.debugVertexBuffer_, data.debugDrawBatches_, 0, data.debugDrawBatches_.Size());
  439. data.debugDrawBatches_.Clear();
  440. data.debugVertexData_.Clear();
  441. }
  442. }
  443. if (renderToTexture_.Size())
  444. graphics_->ResetRenderTargets();
  445. }
  446. // Clear the debug draw batches and data
  447. debugDrawBatches_.Clear();
  448. debugVertexData_.Clear();
  449. uiRendered_ = true;
  450. }
  451. void UI::DebugDraw(UIElement* element)
  452. {
  453. if (element)
  454. {
  455. UIElement* root = element->GetRoot();
  456. if (!root)
  457. root = element;
  458. const IntVector2& rootSize = root->GetSize();
  459. const IntVector2& rootPos = root->GetPosition();
  460. IntRect scissor(rootPos.x_, rootPos.y_, rootPos.x_ + rootSize.x_, rootPos.y_ + rootSize.y_);
  461. if (root == rootElement_ || root == rootModalElement_)
  462. element->GetDebugDrawBatches(debugDrawBatches_, debugVertexData_, scissor);
  463. else
  464. {
  465. for (auto& item : renderToTexture_)
  466. {
  467. RenderToTextureData& data = item.second_;
  468. if (!data.rootElement_.Expired() && data.rootElement_ == root && data.rootElement_->IsEnabled())
  469. {
  470. element->GetDebugDrawBatches(data.debugDrawBatches_, data.debugVertexData_, scissor);
  471. break;
  472. }
  473. }
  474. }
  475. }
  476. }
  477. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  478. {
  479. SharedPtr<XMLFile> xml(new XMLFile(context_));
  480. if (!xml->Load(source))
  481. return SharedPtr<UIElement>();
  482. else
  483. return LoadLayout(xml, styleFile);
  484. }
  485. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  486. {
  487. URHO3D_PROFILE(LoadUILayout);
  488. SharedPtr<UIElement> root;
  489. if (!file)
  490. {
  491. URHO3D_LOGERROR("Null UI layout XML file");
  492. return root;
  493. }
  494. URHO3D_LOGDEBUG("Loading UI layout " + file->GetName());
  495. XMLElement rootElem = file->GetRoot("element");
  496. if (!rootElem)
  497. {
  498. URHO3D_LOGERROR("No root UI element in " + file->GetName());
  499. return root;
  500. }
  501. String typeName = rootElem.GetAttribute("type");
  502. if (typeName.Empty())
  503. typeName = "UIElement";
  504. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  505. if (!root)
  506. {
  507. URHO3D_LOGERROR("Could not create unknown UI element " + typeName);
  508. return root;
  509. }
  510. // Use default style file of the root element if it has one
  511. if (!styleFile)
  512. styleFile = rootElement_->GetDefaultStyle(false);
  513. // Set it as default for later use by children elements
  514. if (styleFile)
  515. root->SetDefaultStyle(styleFile);
  516. root->LoadXML(rootElem, styleFile);
  517. return root;
  518. }
  519. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  520. {
  521. URHO3D_PROFILE(SaveUILayout);
  522. return element && element->SaveXML(dest);
  523. }
  524. void UI::SetClipboardText(const String& text)
  525. {
  526. clipBoard_ = text;
  527. if (useSystemClipboard_)
  528. SDL_SetClipboardText(text.CString());
  529. }
  530. void UI::SetDoubleClickInterval(float interval)
  531. {
  532. doubleClickInterval_ = Max(interval, 0.0f);
  533. }
  534. void UI::SetMaxDoubleClickDistance(float distPixels)
  535. {
  536. maxDoubleClickDist_ = distPixels;
  537. }
  538. void UI::SetDragBeginInterval(float interval)
  539. {
  540. dragBeginInterval_ = Max(interval, 0.0f);
  541. }
  542. void UI::SetDragBeginDistance(int pixels)
  543. {
  544. dragBeginDistance_ = Max(pixels, 0);
  545. }
  546. void UI::SetDefaultToolTipDelay(float delay)
  547. {
  548. defaultToolTipDelay_ = Max(delay, 0.0f);
  549. }
  550. void UI::SetMaxFontTextureSize(int size)
  551. {
  552. if (IsPowerOfTwo((unsigned)size) && size >= FONT_TEXTURE_MIN_SIZE)
  553. {
  554. if (size != maxFontTextureSize_)
  555. {
  556. maxFontTextureSize_ = size;
  557. ReleaseFontFaces();
  558. }
  559. }
  560. }
  561. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  562. {
  563. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  564. }
  565. void UI::SetUseSystemClipboard(bool enable)
  566. {
  567. useSystemClipboard_ = enable;
  568. }
  569. void UI::SetUseScreenKeyboard(bool enable)
  570. {
  571. useScreenKeyboard_ = enable;
  572. }
  573. void UI::SetUseMutableGlyphs(bool enable)
  574. {
  575. if (enable != useMutableGlyphs_)
  576. {
  577. useMutableGlyphs_ = enable;
  578. ReleaseFontFaces();
  579. }
  580. }
  581. void UI::SetForceAutoHint(bool enable)
  582. {
  583. if (enable != forceAutoHint_)
  584. {
  585. forceAutoHint_ = enable;
  586. ReleaseFontFaces();
  587. }
  588. }
  589. void UI::SetFontHintLevel(FontHintLevel level)
  590. {
  591. if (level != fontHintLevel_)
  592. {
  593. fontHintLevel_ = level;
  594. ReleaseFontFaces();
  595. }
  596. }
  597. void UI::SetFontSubpixelThreshold(float threshold)
  598. {
  599. assert(threshold >= 0);
  600. if (threshold != fontSubpixelThreshold_)
  601. {
  602. fontSubpixelThreshold_ = threshold;
  603. ReleaseFontFaces();
  604. }
  605. }
  606. void UI::SetFontOversampling(int oversampling)
  607. {
  608. assert(oversampling >= 1);
  609. oversampling = Clamp(oversampling, 1, 8);
  610. if (oversampling != fontOversampling_)
  611. {
  612. fontOversampling_ = oversampling;
  613. ReleaseFontFaces();
  614. }
  615. }
  616. void UI::SetScale(float scale)
  617. {
  618. uiScale_ = Max(scale, M_EPSILON);
  619. ResizeRootElement();
  620. }
  621. void UI::SetWidth(float width)
  622. {
  623. IntVector2 size = GetEffectiveRootElementSize(false);
  624. SetScale((float)size.x_ / width);
  625. }
  626. void UI::SetHeight(float height)
  627. {
  628. IntVector2 size = GetEffectiveRootElementSize(false);
  629. SetScale((float)size.y_ / height);
  630. }
  631. void UI::SetCustomSize(const IntVector2& size)
  632. {
  633. customSize_ = IntVector2(Max(0, size.x_), Max(0, size.y_));
  634. ResizeRootElement();
  635. }
  636. void UI::SetCustomSize(int width, int height)
  637. {
  638. customSize_ = IntVector2(Max(0, width), Max(0, height));
  639. ResizeRootElement();
  640. }
  641. IntVector2 UI::GetCursorPosition() const
  642. {
  643. if (cursor_)
  644. return cursor_->GetPosition();
  645. return ConvertSystemToUI(GetSubsystem<Input>()->GetMousePosition());
  646. }
  647. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly, IntVector2* elementScreenPosition)
  648. {
  649. UIElement* result = nullptr;
  650. if (HasModalElement())
  651. result = GetElementAt(rootModalElement_, position, enabledOnly);
  652. if (!result)
  653. result = GetElementAt(rootElement_, position, enabledOnly);
  654. // Mouse was not hovering UI element. Check elements rendered on 3D objects.
  655. if (!result && renderToTexture_.Size())
  656. {
  657. for (auto& item : renderToTexture_)
  658. {
  659. RenderToTextureData& data = item.second_;
  660. if (data.rootElement_.Expired() || !data.rootElement_->IsEnabled())
  661. continue;
  662. IntVector2 screenPosition = data.rootElement_->ScreenToElement(position);
  663. if (data.rootElement_->GetCombinedScreenRect().IsInside(screenPosition) == INSIDE)
  664. {
  665. result = GetElementAt(data.rootElement_, screenPosition, enabledOnly);
  666. if (result)
  667. {
  668. if (elementScreenPosition)
  669. *elementScreenPosition = screenPosition;
  670. break;
  671. }
  672. }
  673. }
  674. }
  675. else if (elementScreenPosition)
  676. *elementScreenPosition = position;
  677. return result;
  678. }
  679. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  680. {
  681. return GetElementAt(position, enabledOnly, nullptr);
  682. }
  683. UIElement* UI::GetElementAt(UIElement* root, const IntVector2& position, bool enabledOnly)
  684. {
  685. IntVector2 positionCopy(position);
  686. const IntVector2& rootSize = root->GetSize();
  687. const IntVector2& rootPos = root->GetPosition();
  688. // If position is out of bounds of root element return null.
  689. if (position.x_ < rootPos.x_ || position.x_ > rootPos.x_ + rootSize.x_)
  690. return nullptr;
  691. if (position.y_ < rootPos.y_ || position.y_ > rootPos.y_ + rootSize.y_)
  692. return nullptr;
  693. // If UI is smaller than the screen, wrap if necessary
  694. if (rootSize.x_ > 0 && rootSize.y_ > 0)
  695. {
  696. if (positionCopy.x_ >= rootPos.x_ + rootSize.x_)
  697. positionCopy.x_ = rootPos.x_ + ((positionCopy.x_ - rootPos.x_) % rootSize.x_);
  698. if (positionCopy.y_ >= rootPos.y_ + rootSize.y_)
  699. positionCopy.y_ = rootPos.y_ + ((positionCopy.y_ - rootPos.y_) % rootSize.y_);
  700. }
  701. UIElement* result = nullptr;
  702. GetElementAt(result, root, positionCopy, enabledOnly);
  703. return result;
  704. }
  705. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  706. {
  707. return GetElementAt(IntVector2(x, y), enabledOnly);
  708. }
  709. IntVector2 UI::ConvertSystemToUI(const IntVector2& systemPos) const
  710. {
  711. return VectorFloorToInt(static_cast<Vector2>(systemPos) / GetScale());
  712. }
  713. IntVector2 UI::ConvertUIToSystem(const IntVector2& uiPos) const
  714. {
  715. return VectorFloorToInt(static_cast<Vector2>(uiPos) * GetScale());
  716. }
  717. UIElement* UI::GetFrontElement() const
  718. {
  719. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  720. int maxPriority = M_MIN_INT;
  721. UIElement* front = nullptr;
  722. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  723. {
  724. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  725. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  726. continue;
  727. int priority = rootChildren[i]->GetPriority();
  728. if (priority > maxPriority)
  729. {
  730. maxPriority = priority;
  731. front = rootChildren[i];
  732. }
  733. }
  734. return front;
  735. }
  736. const Vector<UIElement*> UI::GetDragElements()
  737. {
  738. // Do not return the element until drag begin event has actually been posted
  739. if (!dragElementsConfirmed_.Empty())
  740. return dragElementsConfirmed_;
  741. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  742. {
  743. WeakPtr<UIElement> dragElement = i->first_;
  744. UI::DragData* dragData = i->second_;
  745. if (!dragElement)
  746. {
  747. i = DragElementErase(i);
  748. continue;
  749. }
  750. if (!dragData->dragBeginPending)
  751. dragElementsConfirmed_.Push(dragElement);
  752. ++i;
  753. }
  754. return dragElementsConfirmed_;
  755. }
  756. UIElement* UI::GetDragElement(unsigned index)
  757. {
  758. GetDragElements();
  759. if (index >= dragElementsConfirmed_.Size())
  760. return nullptr;
  761. return dragElementsConfirmed_[index];
  762. }
  763. const String& UI::GetClipboardText() const
  764. {
  765. if (useSystemClipboard_)
  766. {
  767. char* text = SDL_GetClipboardText();
  768. clipBoard_ = String(text);
  769. if (text)
  770. SDL_free(text);
  771. }
  772. return clipBoard_;
  773. }
  774. bool UI::HasModalElement() const
  775. {
  776. return rootModalElement_->GetNumChildren() > 0;
  777. }
  778. void UI::Initialize()
  779. {
  780. auto* graphics = GetSubsystem<Graphics>();
  781. if (!graphics || !graphics->IsInitialized())
  782. return;
  783. URHO3D_PROFILE(InitUI);
  784. graphics_ = graphics;
  785. UIBatch::posAdjust = Vector3(Graphics::GetPixelUVOffset(), 0.0f);
  786. // Set initial root element size
  787. ResizeRootElement();
  788. vertexBuffer_ = new VertexBuffer(context_);
  789. debugVertexBuffer_ = new VertexBuffer(context_);
  790. initialized_ = true;
  791. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame));
  792. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate));
  793. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate));
  794. URHO3D_LOGINFO("Initialized user interface");
  795. }
  796. void UI::Update(float timeStep, UIElement* element)
  797. {
  798. // Keep a weak pointer to the element in case it destroys itself on update
  799. WeakPtr<UIElement> elementWeak(element);
  800. element->Update(timeStep);
  801. if (elementWeak.Expired())
  802. return;
  803. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  804. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  805. for (unsigned i = 0; i < children.Size(); ++i)
  806. Update(timeStep, children[i]);
  807. }
  808. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  809. {
  810. if (vertexData.Empty())
  811. return;
  812. // Update quad geometry into the vertex buffer
  813. // Resize the vertex buffer first if too small or much too large
  814. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  815. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  816. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  817. dest->SetData(&vertexData[0]);
  818. }
  819. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  820. {
  821. // Engine does not render when window is closed or device is lost
  822. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  823. if (batches.Empty())
  824. return;
  825. unsigned alphaFormat = Graphics::GetAlphaFormat();
  826. RenderSurface* surface = graphics_->GetRenderTarget(0);
  827. IntVector2 viewSize = graphics_->GetViewport().Size();
  828. Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_);
  829. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  830. Vector2 offset(-1.0f, 1.0f);
  831. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  832. {
  833. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the
  834. // same way as a render texture produced on Direct3D.
  835. offset.y_ = -offset.y_;
  836. scale.y_ = -scale.y_;
  837. }
  838. Matrix4 projection(Matrix4::IDENTITY);
  839. projection.m00_ = scale.x_ * uiScale_;
  840. projection.m03_ = offset.x_;
  841. projection.m11_ = scale.y_ * uiScale_;
  842. projection.m13_ = offset.y_;
  843. projection.m22_ = 1.0f;
  844. projection.m23_ = 0.0f;
  845. projection.m33_ = 1.0f;
  846. graphics_->ClearParameterSources();
  847. graphics_->SetColorWrite(true);
  848. // Reverse winding if rendering to texture on OpenGL
  849. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  850. graphics_->SetCullMode(CULL_CW);
  851. else
  852. graphics_->SetCullMode(CULL_CCW);
  853. graphics_->SetDepthTest(CMP_ALWAYS);
  854. graphics_->SetDepthWrite(false);
  855. graphics_->SetFillMode(FILL_SOLID);
  856. graphics_->SetStencilTest(false);
  857. graphics_->SetVertexBuffer(buffer);
  858. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  859. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  860. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  861. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  862. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  863. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  864. for (unsigned i = batchStart; i < batchEnd; ++i)
  865. {
  866. const UIBatch& batch = batches[i];
  867. if (batch.vertexStart_ == batch.vertexEnd_)
  868. continue;
  869. ShaderVariation* ps;
  870. ShaderVariation* vs;
  871. if (!batch.customMaterial_)
  872. {
  873. if (!batch.texture_)
  874. {
  875. ps = noTexturePS;
  876. vs = noTextureVS;
  877. } else
  878. {
  879. // If texture contains only an alpha channel, use alpha shader (for fonts)
  880. vs = diffTextureVS;
  881. if (batch.texture_->GetFormat() == alphaFormat)
  882. ps = alphaTexturePS;
  883. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  884. ps = diffMaskTexturePS;
  885. else
  886. ps = diffTexturePS;
  887. }
  888. } else
  889. {
  890. vs = diffTextureVS;
  891. ps = diffTexturePS;
  892. Technique* technique = batch.customMaterial_->GetTechnique(0);
  893. if (technique)
  894. {
  895. Pass* pass = nullptr;
  896. for (int i = 0; i < technique->GetNumPasses(); ++i)
  897. {
  898. pass = technique->GetPass(i);
  899. if (pass)
  900. {
  901. vs = graphics_->GetShader(VS, pass->GetVertexShader(), batch.customMaterial_->GetVertexShaderDefines());
  902. ps = graphics_->GetShader(PS, pass->GetPixelShader(), batch.customMaterial_->GetPixelShaderDefines());
  903. break;
  904. }
  905. }
  906. }
  907. }
  908. graphics_->SetShaders(vs, ps);
  909. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  910. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  911. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  912. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  913. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  914. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  915. float elapsedTime = GetSubsystem<Time>()->GetElapsedTime();
  916. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  917. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  918. IntRect scissor = batch.scissor_;
  919. scissor.left_ = (int)(scissor.left_ * uiScale_);
  920. scissor.top_ = (int)(scissor.top_ * uiScale_);
  921. scissor.right_ = (int)(scissor.right_ * uiScale_);
  922. scissor.bottom_ = (int)(scissor.bottom_ * uiScale_);
  923. // Flip scissor vertically if using OpenGL texture rendering
  924. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  925. {
  926. int top = scissor.top_;
  927. int bottom = scissor.bottom_;
  928. scissor.top_ = viewSize.y_ - bottom;
  929. scissor.bottom_ = viewSize.y_ - top;
  930. }
  931. graphics_->SetBlendMode(batch.blendMode_);
  932. graphics_->SetScissorTest(true, scissor);
  933. if (!batch.customMaterial_)
  934. {
  935. graphics_->SetTexture(0, batch.texture_);
  936. } else
  937. {
  938. // Update custom shader parameters if needed
  939. if (graphics_->NeedParameterUpdate(SP_MATERIAL, reinterpret_cast<const void*>(batch.customMaterial_->GetShaderParameterHash())))
  940. {
  941. auto shader_parameters = batch.customMaterial_->GetShaderParameters();
  942. for (auto it = shader_parameters.Begin(); it != shader_parameters.End(); ++it)
  943. {
  944. graphics_->SetShaderParameter(it->second_.name_, it->second_.value_);
  945. }
  946. }
  947. // Apply custom shader textures
  948. auto textures = batch.customMaterial_->GetTextures();
  949. for (auto it = textures.Begin(); it != textures.End(); ++it)
  950. {
  951. graphics_->SetTexture(it->first_, it->second_);
  952. }
  953. }
  954. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE,
  955. (batch.vertexEnd_ - batch.vertexStart_) / UI_VERTEX_SIZE);
  956. if (batch.customMaterial_)
  957. {
  958. // Reset textures used by the batch custom material
  959. auto textures = batch.customMaterial_->GetTextures();
  960. for (auto it = textures.Begin(); it != textures.End(); ++it)
  961. {
  962. graphics_->SetTexture(it->first_, 0);
  963. }
  964. }
  965. }
  966. }
  967. void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, UIElement* element, IntRect currentScissor)
  968. {
  969. // Set clipping scissor for child elements. No need to draw if zero size
  970. element->AdjustScissor(currentScissor);
  971. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  972. return;
  973. element->SortChildren();
  974. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  975. if (children.Empty())
  976. return;
  977. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  978. // same renderstate
  979. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  980. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  981. {
  982. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  983. while (i != children.End())
  984. {
  985. int currentPriority = (*i)->GetPriority();
  986. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  987. {
  988. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  989. (*j)->GetBatches(batches, vertexData, currentScissor);
  990. ++j;
  991. }
  992. // Now recurse into the children
  993. while (i != j)
  994. {
  995. if ((*i)->IsVisible() && (*i) != cursor_)
  996. GetBatches(batches, vertexData, *i, currentScissor);
  997. ++i;
  998. }
  999. }
  1000. }
  1001. // On the root level draw each element and its children immediately after to avoid artifacts
  1002. else
  1003. {
  1004. while (i != children.End())
  1005. {
  1006. if ((*i) != cursor_)
  1007. {
  1008. if ((*i)->IsWithinScissor(currentScissor))
  1009. (*i)->GetBatches(batches, vertexData, currentScissor);
  1010. if ((*i)->IsVisible())
  1011. GetBatches(batches, vertexData, *i, currentScissor);
  1012. }
  1013. ++i;
  1014. }
  1015. }
  1016. }
  1017. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  1018. {
  1019. if (!current)
  1020. return;
  1021. current->SortChildren();
  1022. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  1023. LayoutMode parentLayoutMode = current->GetLayoutMode();
  1024. for (unsigned i = 0; i < children.Size(); ++i)
  1025. {
  1026. UIElement* element = children[i];
  1027. bool hasChildren = element->GetNumChildren() > 0;
  1028. if (element != cursor_.Get() && element->IsVisible())
  1029. {
  1030. if (element->IsInside(position, true))
  1031. {
  1032. // Store the current result, then recurse into its children. Because children
  1033. // are sorted from lowest to highest priority, the topmost match should remain
  1034. if (element->IsEnabled() || !enabledOnly)
  1035. result = element;
  1036. if (hasChildren)
  1037. GetElementAt(result, element, position, enabledOnly);
  1038. // Layout optimization: if the element has no children, can break out after the first match
  1039. else if (parentLayoutMode != LM_FREE)
  1040. break;
  1041. }
  1042. else
  1043. {
  1044. if (hasChildren)
  1045. {
  1046. if (element->IsInsideCombined(position, true))
  1047. GetElementAt(result, element, position, enabledOnly);
  1048. }
  1049. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  1050. // or if we already passed all visible elements
  1051. else if (parentLayoutMode != LM_FREE)
  1052. {
  1053. if (!i)
  1054. {
  1055. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  1056. element->GetScreenPosition().y_;
  1057. int layoutMaxSize = current->GetLayoutElementMaxSize();
  1058. int spacing = current->GetLayoutSpacing();
  1059. if (screenPos < 0 && layoutMaxSize > 0)
  1060. {
  1061. auto toSkip = (unsigned)(-screenPos / (layoutMaxSize + spacing));
  1062. if (toSkip > 0)
  1063. i += (toSkip - 1);
  1064. }
  1065. }
  1066. // Note: we cannot check for the up / left limits of positioning, since the element may be off the visible
  1067. // screen but some of its layouted children will yet be visible. In down & right directions we can terminate
  1068. // the loop, since all further children will be further down or right.
  1069. else if (parentLayoutMode == LM_HORIZONTAL)
  1070. {
  1071. if (element->GetScreenPosition().x_ >= rootElement_->GetPosition().x_ + rootElement_->GetSize().x_)
  1072. break;
  1073. }
  1074. else if (parentLayoutMode == LM_VERTICAL)
  1075. {
  1076. if (element->GetScreenPosition().y_ >= rootElement_->GetPosition().y_ + rootElement_->GetSize().y_)
  1077. break;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. UIElement* UI::GetFocusableElement(UIElement* element)
  1085. {
  1086. while (element)
  1087. {
  1088. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  1089. break;
  1090. element = element->GetParent();
  1091. }
  1092. return element;
  1093. }
  1094. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  1095. {
  1096. // Prefer software cursor then OS-specific cursor
  1097. if (cursor_ && cursor_->IsVisible())
  1098. {
  1099. pos = cursor_->GetPosition();
  1100. visible = true;
  1101. }
  1102. else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
  1103. visible = true;
  1104. else
  1105. {
  1106. auto* input = GetSubsystem<Input>();
  1107. visible = input->IsMouseVisible();
  1108. if (!visible && cursor_)
  1109. {
  1110. pos = cursor_->GetPosition();
  1111. }
  1112. else
  1113. {
  1114. pos = input->GetMousePosition();
  1115. pos = ConvertSystemToUI(pos);
  1116. }
  1117. }
  1118. }
  1119. void UI::SetCursorShape(CursorShape shape)
  1120. {
  1121. if (cursor_)
  1122. cursor_->SetShape(shape);
  1123. }
  1124. void UI::ReleaseFontFaces()
  1125. {
  1126. URHO3D_LOGDEBUG("Reloading font faces");
  1127. PODVector<Font*> fonts;
  1128. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  1129. for (unsigned i = 0; i < fonts.Size(); ++i)
  1130. fonts[i]->ReleaseFaces();
  1131. }
  1132. void UI::ProcessHover(const IntVector2& windowCursorPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
  1133. {
  1134. IntVector2 cursorPos;
  1135. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1136. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1137. {
  1138. WeakPtr<UIElement> dragElement = i->first_;
  1139. UI::DragData* dragData = i->second_;
  1140. if (!dragElement)
  1141. {
  1142. i = DragElementErase(i);
  1143. continue;
  1144. }
  1145. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1146. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1147. bool dragDropTest = dragSource && dragTarget && element != dragElement;
  1148. // If drag start event has not been posted yet, do not do drag handling here
  1149. if (dragData->dragBeginPending)
  1150. dragSource = dragTarget = dragDropTest = false;
  1151. // Hover effect
  1152. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  1153. if (element && element->IsEnabled())
  1154. {
  1155. if (dragElement == element || dragDropTest)
  1156. {
  1157. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1158. // Begin hover event
  1159. if (!hoveredElements_.Contains(element))
  1160. {
  1161. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1162. // Exit if element is destroyed by the event handling
  1163. if (!element)
  1164. return;
  1165. }
  1166. hoveredElements_[element] = true;
  1167. }
  1168. }
  1169. // Drag and drop test
  1170. if (dragDropTest)
  1171. {
  1172. bool accept = element->OnDragDropTest(dragElement);
  1173. if (accept)
  1174. {
  1175. using namespace DragDropTest;
  1176. VariantMap& eventData = GetEventDataMap();
  1177. eventData[P_SOURCE] = dragElement.Get();
  1178. eventData[P_TARGET] = element.Get();
  1179. eventData[P_ACCEPT] = accept;
  1180. SendEvent(E_DRAGDROPTEST, eventData);
  1181. accept = eventData[P_ACCEPT].GetBool();
  1182. }
  1183. if (cursor)
  1184. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  1185. }
  1186. else if (dragSource && cursor)
  1187. cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  1188. ++i;
  1189. }
  1190. // Hover effect
  1191. // If no drag is going on, transmit hover event.
  1192. if (element && element->IsEnabled())
  1193. {
  1194. if (dragElementsCount_ == 0)
  1195. {
  1196. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1197. // Begin hover event
  1198. if (!hoveredElements_.Contains(element))
  1199. {
  1200. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1201. // Exit if element is destroyed by the event handling
  1202. if (!element)
  1203. return;
  1204. }
  1205. hoveredElements_[element] = true;
  1206. }
  1207. }
  1208. }
  1209. void UI::ProcessClickBegin(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1210. {
  1211. if (cursorVisible)
  1212. {
  1213. IntVector2 cursorPos;
  1214. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1215. bool newButton;
  1216. if (usingTouchInput_)
  1217. newButton = (buttons & button) == MOUSEB_NONE;
  1218. else
  1219. newButton = true;
  1220. buttons |= button;
  1221. if (element)
  1222. SetFocusElement(element);
  1223. // Focus change events may destroy the element, check again.
  1224. if (element)
  1225. {
  1226. // Handle focusing & bringing to front
  1227. element->BringToFront();
  1228. // Handle click
  1229. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1230. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1231. // Fire double click event if element matches and is in time and is within max distance from the original click
  1232. if (doubleClickElement_ && element == doubleClickElement_ &&
  1233. (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000)) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1234. {
  1235. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1236. doubleClickElement_.Reset();
  1237. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1238. }
  1239. else
  1240. {
  1241. doubleClickElement_ = element;
  1242. doubleClickFirstPos_ = windowCursorPos;
  1243. clickTimer_.Reset();
  1244. }
  1245. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  1246. bool dragElementsContain = dragElements_.Contains(element);
  1247. if (element && !dragElementsContain)
  1248. {
  1249. auto* dragData = new DragData();
  1250. dragElements_[element] = dragData;
  1251. dragData->dragBeginPending = true;
  1252. dragData->sumPos = cursorPos;
  1253. dragData->dragBeginSumPos = cursorPos;
  1254. dragData->dragBeginTimer.Reset();
  1255. dragData->dragButtons = button;
  1256. dragData->numDragButtons = CountSetBits((u32)dragData->dragButtons);
  1257. dragElementsCount_++;
  1258. dragElementsContain = dragElements_.Contains(element);
  1259. }
  1260. else if (element && dragElementsContain && newButton)
  1261. {
  1262. DragData* dragData = dragElements_[element];
  1263. dragData->sumPos += cursorPos;
  1264. dragData->dragBeginSumPos += cursorPos;
  1265. dragData->dragButtons |= button;
  1266. dragData->numDragButtons = CountSetBits((u32)dragData->dragButtons);
  1267. }
  1268. }
  1269. else
  1270. {
  1271. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  1272. if (!HasModalElement())
  1273. SetFocusElement(nullptr);
  1274. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1275. if (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1276. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1277. }
  1278. lastMouseButtons_ = buttons;
  1279. }
  1280. }
  1281. void UI::ProcessClickEnd(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1282. {
  1283. WeakPtr<UIElement> element;
  1284. IntVector2 cursorPos = windowCursorPos;
  1285. if (cursorVisible)
  1286. element = GetElementAt(cursorPos, true, &cursorPos);
  1287. // Handle end of drag
  1288. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1289. {
  1290. WeakPtr<UIElement> dragElement = i->first_;
  1291. UI::DragData* dragData = i->second_;
  1292. if (!dragElement || !cursorVisible)
  1293. {
  1294. i = DragElementErase(i);
  1295. continue;
  1296. }
  1297. if (dragData->dragButtons & button)
  1298. {
  1299. // Handle end of click
  1300. if (element)
  1301. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor,
  1302. dragElement);
  1303. SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
  1304. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1305. {
  1306. dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons,
  1307. cursor);
  1308. SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1309. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1310. if (dragSource)
  1311. {
  1312. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1313. bool dragDropFinish = dragSource && dragTarget && element != dragElement;
  1314. if (dragDropFinish)
  1315. {
  1316. bool accept = element->OnDragDropFinish(dragElement);
  1317. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  1318. if (accept && dragElement && element)
  1319. {
  1320. using namespace DragDropFinish;
  1321. VariantMap& eventData = GetEventDataMap();
  1322. eventData[P_SOURCE] = dragElement.Get();
  1323. eventData[P_TARGET] = element.Get();
  1324. eventData[P_ACCEPT] = accept;
  1325. SendEvent(E_DRAGDROPFINISH, eventData);
  1326. }
  1327. }
  1328. }
  1329. }
  1330. i = DragElementErase(i);
  1331. }
  1332. else
  1333. ++i;
  1334. }
  1335. }
  1336. void UI::ProcessMove(const IntVector2& windowCursorPos, const IntVector2& cursorDeltaPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor,
  1337. bool cursorVisible)
  1338. {
  1339. if (cursorVisible && dragElementsCount_ > 0 && buttons)
  1340. {
  1341. IntVector2 cursorPos;
  1342. GetElementAt(windowCursorPos, true, &cursorPos);
  1343. auto* input = GetSubsystem<Input>();
  1344. bool mouseGrabbed = input->IsMouseGrabbed();
  1345. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1346. {
  1347. WeakPtr<UIElement> dragElement = i->first_;
  1348. UI::DragData* dragData = i->second_;
  1349. if (!dragElement)
  1350. {
  1351. i = DragElementErase(i);
  1352. continue;
  1353. }
  1354. if (!(dragData->dragButtons & buttons))
  1355. {
  1356. ++i;
  1357. continue;
  1358. }
  1359. // Calculate the position that we should send for this drag event.
  1360. IntVector2 sendPos;
  1361. if (usingTouchInput_)
  1362. {
  1363. dragData->sumPos += cursorDeltaPos;
  1364. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1365. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1366. }
  1367. else
  1368. {
  1369. dragData->sumPos = cursorPos;
  1370. sendPos = cursorPos;
  1371. }
  1372. if (dragElement->IsEnabled() && dragElement->IsVisible())
  1373. {
  1374. // Signal drag begin if distance threshold was exceeded
  1375. if (dragData->dragBeginPending && !mouseGrabbed)
  1376. {
  1377. IntVector2 beginSendPos;
  1378. beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
  1379. beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
  1380. IntVector2 offset = cursorPos - beginSendPos;
  1381. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  1382. {
  1383. dragData->dragBeginPending = false;
  1384. dragConfirmedCount_++;
  1385. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers,
  1386. cursor);
  1387. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  1388. }
  1389. }
  1390. if (!dragData->dragBeginPending)
  1391. {
  1392. dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers,
  1393. cursor);
  1394. SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
  1395. }
  1396. }
  1397. else
  1398. {
  1399. dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
  1400. SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
  1401. dragElement.Reset();
  1402. }
  1403. ++i;
  1404. }
  1405. }
  1406. }
  1407. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos,
  1408. UI::DragData* dragData)
  1409. {
  1410. if (!element)
  1411. return;
  1412. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1413. using namespace DragMove;
  1414. VariantMap& eventData = GetEventDataMap();
  1415. eventData[P_ELEMENT] = element;
  1416. eventData[P_X] = screenPos.x_;
  1417. eventData[P_Y] = screenPos.y_;
  1418. eventData[P_ELEMENTX] = relativePos.x_;
  1419. eventData[P_ELEMENTY] = relativePos.y_;
  1420. if (eventType == E_DRAGMOVE)
  1421. {
  1422. eventData[P_DX] = deltaPos.x_;
  1423. eventData[P_DY] = deltaPos.y_;
  1424. }
  1425. if (dragData)
  1426. {
  1427. eventData[P_BUTTONS] = (unsigned)dragData->dragButtons;
  1428. eventData[P_NUMBUTTONS] = dragData->numDragButtons;
  1429. }
  1430. element->SendEvent(eventType, eventData);
  1431. }
  1432. void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, MouseButton button,
  1433. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1434. {
  1435. VariantMap& eventData = GetEventDataMap();
  1436. eventData[UIMouseClick::P_ELEMENT] = endElement;
  1437. eventData[UIMouseClick::P_X] = pos.x_;
  1438. eventData[UIMouseClick::P_Y] = pos.y_;
  1439. eventData[UIMouseClick::P_BUTTON] = button;
  1440. eventData[UIMouseClick::P_BUTTONS] = (unsigned)buttons;
  1441. eventData[UIMouseClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1442. // For click end events, send also the element the click began on
  1443. if (eventType == E_UIMOUSECLICKEND)
  1444. eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
  1445. if (endElement)
  1446. {
  1447. // Send also element version of the event
  1448. if (eventType == E_UIMOUSECLICK)
  1449. endElement->SendEvent(E_CLICK, eventData);
  1450. else if (eventType == E_UIMOUSECLICKEND)
  1451. endElement->SendEvent(E_CLICKEND, eventData);
  1452. }
  1453. // Send the global event from the UI subsystem last
  1454. SendEvent(eventType, eventData);
  1455. }
  1456. void UI::SendDoubleClickEvent(UIElement* beginElement, UIElement* endElement, const IntVector2& firstPos, const IntVector2& secondPos, MouseButton button,
  1457. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1458. {
  1459. VariantMap& eventData = GetEventDataMap();
  1460. eventData[UIMouseDoubleClick::P_ELEMENT] = endElement;
  1461. eventData[UIMouseDoubleClick::P_X] = secondPos.x_;
  1462. eventData[UIMouseDoubleClick::P_Y] = secondPos.y_;
  1463. eventData[UIMouseDoubleClick::P_XBEGIN] = firstPos.x_;
  1464. eventData[UIMouseDoubleClick::P_YBEGIN] = firstPos.y_;
  1465. eventData[UIMouseDoubleClick::P_BUTTON] = button;
  1466. eventData[UIMouseDoubleClick::P_BUTTONS] = (unsigned)buttons;
  1467. eventData[UIMouseDoubleClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1468. if (endElement)
  1469. {
  1470. // Send also element version of the event
  1471. endElement->SendEvent(E_DOUBLECLICK, eventData);
  1472. }
  1473. // Send the global event from the UI subsystem last
  1474. SendEvent(E_UIMOUSEDOUBLECLICK, eventData);
  1475. }
  1476. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1477. {
  1478. using namespace ScreenMode;
  1479. if (!initialized_)
  1480. Initialize();
  1481. else
  1482. ResizeRootElement();
  1483. }
  1484. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1485. {
  1486. using namespace MouseButtonDown;
  1487. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1488. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1489. usingTouchInput_ = false;
  1490. IntVector2 cursorPos;
  1491. bool cursorVisible;
  1492. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1493. // Handle drag cancelling
  1494. ProcessDragCancel();
  1495. auto* input = GetSubsystem<Input>();
  1496. if (!input->IsMouseGrabbed())
  1497. ProcessClickBegin(cursorPos, MouseButton(eventData[P_BUTTON].GetUInt()), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1498. }
  1499. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1500. {
  1501. using namespace MouseButtonUp;
  1502. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1503. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1504. IntVector2 cursorPos;
  1505. bool cursorVisible;
  1506. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1507. ProcessClickEnd(cursorPos, (MouseButton)eventData[P_BUTTON].GetUInt(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1508. }
  1509. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1510. {
  1511. using namespace MouseMove;
  1512. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1513. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1514. usingTouchInput_ = false;
  1515. auto* input = GetSubsystem<Input>();
  1516. const IntVector2& rootSize = rootElement_->GetSize();
  1517. const IntVector2& rootPos = rootElement_->GetPosition();
  1518. const IntVector2 mouseDeltaPos{ eventData[P_DX].GetInt(), eventData[P_DY].GetInt() };
  1519. const IntVector2 mousePos{ eventData[P_X].GetInt(), eventData[P_Y].GetInt() };
  1520. if (cursor_)
  1521. {
  1522. if (!input->IsMouseVisible())
  1523. {
  1524. if (!input->IsMouseLocked())
  1525. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1526. else if (cursor_->IsVisible())
  1527. {
  1528. // Relative mouse motion: move cursor only when visible
  1529. IntVector2 pos = cursor_->GetPosition();
  1530. pos += ConvertSystemToUI(mouseDeltaPos);
  1531. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  1532. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  1533. cursor_->SetPosition(pos);
  1534. }
  1535. }
  1536. else
  1537. {
  1538. // Absolute mouse motion: move always
  1539. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1540. }
  1541. }
  1542. IntVector2 cursorPos;
  1543. bool cursorVisible;
  1544. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1545. ProcessMove(cursorPos, mouseDeltaPos, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1546. }
  1547. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1548. {
  1549. auto* input = GetSubsystem<Input>();
  1550. if (input->IsMouseGrabbed())
  1551. return;
  1552. using namespace MouseWheel;
  1553. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetInt());
  1554. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetInt());
  1555. int delta = eventData[P_WHEEL].GetInt();
  1556. usingTouchInput_ = false;
  1557. IntVector2 cursorPos;
  1558. bool cursorVisible;
  1559. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1560. if (!nonFocusedMouseWheel_ && focusElement_)
  1561. focusElement_->OnWheel(delta, mouseButtons_, qualifiers_);
  1562. else
  1563. {
  1564. // If no element has actual focus or in non-focused mode, get the element at cursor
  1565. if (cursorVisible)
  1566. {
  1567. UIElement* element = GetElementAt(cursorPos);
  1568. if (nonFocusedMouseWheel_)
  1569. {
  1570. // Going up the hierarchy chain to find element that could handle mouse wheel
  1571. while (element && !element->IsWheelHandler())
  1572. {
  1573. element = element->GetParent();
  1574. }
  1575. }
  1576. else
  1577. // If the element itself is not focusable, search for a focusable parent,
  1578. // although the focusable element may not actually handle mouse wheel
  1579. element = GetFocusableElement(element);
  1580. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1581. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1582. }
  1583. }
  1584. }
  1585. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1586. {
  1587. auto* input = GetSubsystem<Input>();
  1588. if (input->IsMouseGrabbed())
  1589. return;
  1590. using namespace TouchBegin;
  1591. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1592. pos = ConvertSystemToUI(pos);
  1593. usingTouchInput_ = true;
  1594. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1595. WeakPtr<UIElement> element(GetElementAt(pos));
  1596. if (element)
  1597. {
  1598. ProcessClickBegin(pos, touchId, touchDragElements_[element], QUAL_NONE, nullptr, true);
  1599. touchDragElements_[element] |= touchId;
  1600. }
  1601. else
  1602. ProcessClickBegin(pos, touchId, touchId, QUAL_NONE, nullptr, true);
  1603. }
  1604. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1605. {
  1606. using namespace TouchEnd;
  1607. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1608. pos = ConvertSystemToUI(pos);
  1609. // Get the touch index
  1610. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1611. // Transmit hover end to the position where the finger was lifted
  1612. WeakPtr<UIElement> element(GetElementAt(pos));
  1613. // Clear any drag events that were using the touch id
  1614. for (auto i = touchDragElements_.Begin(); i != touchDragElements_.End();)
  1615. {
  1616. const MouseButtonFlags touches = i->second_;
  1617. if (touches & touchId)
  1618. i = touchDragElements_.Erase(i);
  1619. else
  1620. ++i;
  1621. }
  1622. if (element && element->IsEnabled())
  1623. element->OnHover(element->ScreenToElement(pos), pos, MOUSEB_NONE, QUAL_NONE, nullptr);
  1624. ProcessClickEnd(pos, touchId, MOUSEB_NONE, QUAL_NONE, nullptr, true);
  1625. }
  1626. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1627. {
  1628. using namespace TouchMove;
  1629. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  1630. IntVector2 deltaPos(eventData[P_DX].GetInt(), eventData[P_DY].GetInt());
  1631. pos = ConvertSystemToUI(pos);
  1632. deltaPos = ConvertSystemToUI(deltaPos);
  1633. usingTouchInput_ = true;
  1634. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetInt());
  1635. ProcessMove(pos, deltaPos, touchId, QUAL_NONE, nullptr, true);
  1636. }
  1637. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1638. {
  1639. using namespace KeyDown;
  1640. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetUInt());
  1641. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetUInt());
  1642. auto key = (Key)eventData[P_KEY].GetUInt();
  1643. // Cancel UI dragging
  1644. if (key == KEY_ESCAPE && dragElementsCount_ > 0)
  1645. {
  1646. ProcessDragCancel();
  1647. return;
  1648. }
  1649. // Dismiss modal element if any when ESC key is pressed
  1650. if (key == KEY_ESCAPE && HasModalElement())
  1651. {
  1652. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1653. if (element->GetVars().Contains(VAR_ORIGIN))
  1654. // If it is a popup, dismiss by defocusing it
  1655. SetFocusElement(nullptr);
  1656. else
  1657. {
  1658. // If it is a modal window, by resetting its modal flag
  1659. auto* window = dynamic_cast<Window*>(element);
  1660. if (window && window->GetModalAutoDismiss())
  1661. window->SetModal(false);
  1662. }
  1663. return;
  1664. }
  1665. UIElement* element = focusElement_;
  1666. if (element)
  1667. {
  1668. // Switch focus between focusable elements in the same top level window
  1669. if (key == KEY_TAB)
  1670. {
  1671. UIElement* topLevel = element->GetParent();
  1672. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1673. topLevel = topLevel->GetParent();
  1674. if (topLevel)
  1675. {
  1676. topLevel->GetChildren(tempElements_, true);
  1677. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1678. {
  1679. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1680. i = tempElements_.Erase(i);
  1681. else
  1682. ++i;
  1683. }
  1684. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1685. {
  1686. if (tempElements_[i] == element)
  1687. {
  1688. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1689. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1690. UIElement* next = tempElements_[nextIndex];
  1691. SetFocusElement(next, true);
  1692. return;
  1693. }
  1694. }
  1695. }
  1696. }
  1697. // Defocus the element
  1698. else if (key == KEY_ESCAPE && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1699. element->SetFocus(false);
  1700. // If none of the special keys, pass the key to the focused element
  1701. else
  1702. element->OnKey(key, mouseButtons_, qualifiers_);
  1703. }
  1704. }
  1705. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1706. {
  1707. using namespace TextInput;
  1708. UIElement* element = focusElement_;
  1709. if (element)
  1710. element->OnTextInput(eventData[P_TEXT].GetString());
  1711. }
  1712. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1713. {
  1714. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1715. // custom shapes can do it after this, but needs to do it each frame
  1716. if (cursor_ && dragElementsCount_ == 0)
  1717. cursor_->SetShape(CS_NORMAL);
  1718. }
  1719. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1720. {
  1721. using namespace PostUpdate;
  1722. Update(eventData[P_TIMESTEP].GetFloat());
  1723. }
  1724. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1725. {
  1726. RenderUpdate();
  1727. }
  1728. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1729. {
  1730. auto* input = GetSubsystem<Input>();
  1731. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1732. if (input->IsMouseVisible())
  1733. {
  1734. IntVector2 screenPos = input->GetMousePosition();
  1735. screenPos = ConvertSystemToUI(screenPos);
  1736. UIElement* element = GetElementAt(screenPos);
  1737. using namespace UIDropFile;
  1738. VariantMap uiEventData;
  1739. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1740. uiEventData[P_X] = screenPos.x_;
  1741. uiEventData[P_Y] = screenPos.y_;
  1742. uiEventData[P_ELEMENT] = element;
  1743. if (element)
  1744. {
  1745. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1746. uiEventData[P_ELEMENTX] = relativePos.x_;
  1747. uiEventData[P_ELEMENTY] = relativePos.y_;
  1748. }
  1749. SendEvent(E_UIDROPFILE, uiEventData);
  1750. }
  1751. }
  1752. HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::DragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
  1753. {
  1754. // If running the engine frame in response to an event (re-entering UI frame logic) the dragElements_ may already be empty
  1755. if (dragElements_.Empty())
  1756. return dragElements_.End();
  1757. dragElementsConfirmed_.Clear();
  1758. DragData* dragData = i->second_;
  1759. if (!dragData->dragBeginPending)
  1760. --dragConfirmedCount_;
  1761. i = dragElements_.Erase(i);
  1762. --dragElementsCount_;
  1763. delete dragData;
  1764. return i;
  1765. }
  1766. void UI::ProcessDragCancel()
  1767. {
  1768. // How to tell difference between drag cancel and new selection on multi-touch?
  1769. if (usingTouchInput_)
  1770. return;
  1771. IntVector2 cursorPos;
  1772. bool cursorVisible;
  1773. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1774. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1775. {
  1776. WeakPtr<UIElement> dragElement = i->first_;
  1777. UI::DragData* dragData = i->second_;
  1778. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1779. {
  1780. dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_,
  1781. cursor_);
  1782. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1783. i = DragElementErase(i);
  1784. }
  1785. else
  1786. ++i;
  1787. }
  1788. }
  1789. IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
  1790. {
  1791. IntVector2 sendPos = oldSendPos;
  1792. if (usingTouchInput_)
  1793. {
  1794. MouseButtonFlags buttons = dragData->dragButtons;
  1795. dragData->sumPos = IntVector2::ZERO;
  1796. auto* input = GetSubsystem<Input>();
  1797. for (unsigned i = 0; (1u << i) <= (unsigned)buttons; i++)
  1798. {
  1799. auto mouseButton = static_cast<MouseButton>(1u << i); // NOLINT(misc-misplaced-widening-cast)
  1800. if (buttons & mouseButton)
  1801. {
  1802. TouchState* ts = input->GetTouch((unsigned)i);
  1803. if (!ts)
  1804. break;
  1805. IntVector2 pos = ts->position_;
  1806. pos = ConvertSystemToUI(pos);
  1807. dragData->sumPos += pos;
  1808. }
  1809. }
  1810. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1811. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1812. }
  1813. return sendPos;
  1814. }
  1815. void UI::ResizeRootElement()
  1816. {
  1817. IntVector2 effectiveSize = GetEffectiveRootElementSize();
  1818. rootElement_->SetSize(effectiveSize);
  1819. rootModalElement_->SetSize(effectiveSize);
  1820. }
  1821. IntVector2 UI::GetEffectiveRootElementSize(bool applyScale) const
  1822. {
  1823. // Use a fake size in headless mode
  1824. IntVector2 size = graphics_ ? IntVector2(graphics_->GetWidth(), graphics_->GetHeight()) : IntVector2(1024, 768);
  1825. if (customSize_.x_ > 0 && customSize_.y_ > 0)
  1826. size = customSize_;
  1827. if (applyScale)
  1828. {
  1829. size.x_ = RoundToInt((float)size.x_ / uiScale_);
  1830. size.y_ = RoundToInt((float)size.y_ / uiScale_);
  1831. }
  1832. return size;
  1833. }
  1834. void UI::SetElementRenderTexture(UIElement* element, Texture2D* texture)
  1835. {
  1836. if (element == nullptr)
  1837. {
  1838. URHO3D_LOGERROR("UI::SetElementRenderTexture called with null element.");
  1839. return;
  1840. }
  1841. auto it = renderToTexture_.Find(element);
  1842. if (texture && it == renderToTexture_.End())
  1843. {
  1844. RenderToTextureData data;
  1845. data.texture_ = texture;
  1846. data.rootElement_ = element;
  1847. data.vertexBuffer_ = new VertexBuffer(context_);
  1848. data.debugVertexBuffer_ = new VertexBuffer(context_);
  1849. renderToTexture_[element] = data;
  1850. }
  1851. else if (it != renderToTexture_.End())
  1852. {
  1853. if (texture == nullptr)
  1854. renderToTexture_.Erase(it);
  1855. else
  1856. it->second_.texture_ = texture;
  1857. }
  1858. }
  1859. void RegisterUILibrary(Context* context)
  1860. {
  1861. Font::RegisterObject(context);
  1862. UIElement::RegisterObject(context);
  1863. UISelectable::RegisterObject(context);
  1864. BorderImage::RegisterObject(context);
  1865. Sprite::RegisterObject(context);
  1866. Button::RegisterObject(context);
  1867. CheckBox::RegisterObject(context);
  1868. Cursor::RegisterObject(context);
  1869. Text::RegisterObject(context);
  1870. Text3D::RegisterObject(context);
  1871. Window::RegisterObject(context);
  1872. View3D::RegisterObject(context);
  1873. LineEdit::RegisterObject(context);
  1874. Slider::RegisterObject(context);
  1875. ScrollBar::RegisterObject(context);
  1876. ScrollView::RegisterObject(context);
  1877. ListView::RegisterObject(context);
  1878. Menu::RegisterObject(context);
  1879. DropDownList::RegisterObject(context);
  1880. FileSelector::RegisterObject(context);
  1881. MessageBox::RegisterObject(context);
  1882. ProgressBar::RegisterObject(context);
  1883. ToolTip::RegisterObject(context);
  1884. UIComponent::RegisterObject(context);
  1885. }
  1886. }