UI.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  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).GetU32());
  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).GetU32());
  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 (const SharedPtr<UIElement>& rootChild : rootChildren)
  723. {
  724. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  725. if (!rootChild->IsEnabled() || !rootChild->IsVisible() || !rootChild->GetBringToBack())
  726. continue;
  727. int priority = rootChild->GetPriority();
  728. if (priority > maxPriority)
  729. {
  730. maxPriority = priority;
  731. front = rootChild;
  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. // Set initial root element size
  786. ResizeRootElement();
  787. vertexBuffer_ = new VertexBuffer(context_);
  788. debugVertexBuffer_ = new VertexBuffer(context_);
  789. initialized_ = true;
  790. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(UI, HandleBeginFrame));
  791. SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(UI, HandlePostUpdate));
  792. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(UI, HandleRenderUpdate));
  793. URHO3D_LOGINFO("Initialized user interface");
  794. }
  795. void UI::Update(float timeStep, UIElement* element)
  796. {
  797. // Keep a weak pointer to the element in case it destroys itself on update
  798. WeakPtr<UIElement> elementWeak(element);
  799. element->Update(timeStep);
  800. if (elementWeak.Expired())
  801. return;
  802. const Vector<SharedPtr<UIElement>>& children = element->GetChildren();
  803. // Update of an element may modify its child vector. Use just index-based iteration to be safe
  804. for (i32 i = 0; i < children.Size(); ++i)
  805. Update(timeStep, children[i]);
  806. }
  807. void UI::SetVertexData(VertexBuffer* dest, const Vector<float>& vertexData)
  808. {
  809. if (vertexData.Empty())
  810. return;
  811. // Update quad geometry into the vertex buffer
  812. // Resize the vertex buffer first if too small or much too large
  813. i32 numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  814. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  815. dest->SetSize(numVertices, VertexElements::Position | VertexElements::Color | VertexElements::TexCoord1, true);
  816. dest->SetData(&vertexData[0]);
  817. }
  818. void UI::Render(VertexBuffer* buffer, const Vector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  819. {
  820. // Engine does not render when window is closed or device is lost
  821. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  822. if (batches.Empty())
  823. return;
  824. unsigned alphaFormat = Graphics::GetAlphaFormat();
  825. RenderSurface* surface = graphics_->GetRenderTarget(0);
  826. IntVector2 viewSize = graphics_->GetViewport().Size();
  827. Vector2 invScreenSize(1.0f / (float)viewSize.x_, 1.0f / (float)viewSize.y_);
  828. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  829. Vector2 offset(-1.0f, 1.0f);
  830. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  831. {
  832. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the
  833. // same way as a render texture produced on Direct3D.
  834. offset.y_ = -offset.y_;
  835. scale.y_ = -scale.y_;
  836. }
  837. Matrix4 projection(Matrix4::IDENTITY);
  838. projection.m00_ = scale.x_ * uiScale_;
  839. projection.m03_ = offset.x_;
  840. projection.m11_ = scale.y_ * uiScale_;
  841. projection.m13_ = offset.y_;
  842. projection.m22_ = 1.0f;
  843. projection.m23_ = 0.0f;
  844. projection.m33_ = 1.0f;
  845. graphics_->ClearParameterSources();
  846. graphics_->SetColorWrite(true);
  847. // Reverse winding if rendering to texture on OpenGL
  848. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  849. graphics_->SetCullMode(CULL_CW);
  850. else
  851. graphics_->SetCullMode(CULL_CCW);
  852. graphics_->SetDepthTest(CMP_ALWAYS);
  853. graphics_->SetDepthWrite(false);
  854. graphics_->SetFillMode(FILL_SOLID);
  855. graphics_->SetStencilTest(false);
  856. graphics_->SetVertexBuffer(buffer);
  857. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  858. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  859. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  860. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  861. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  862. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  863. for (unsigned i = batchStart; i < batchEnd; ++i)
  864. {
  865. const UIBatch& batch = batches[i];
  866. if (batch.vertexStart_ == batch.vertexEnd_)
  867. continue;
  868. ShaderVariation* ps;
  869. ShaderVariation* vs;
  870. if (!batch.customMaterial_)
  871. {
  872. if (!batch.texture_)
  873. {
  874. ps = noTexturePS;
  875. vs = noTextureVS;
  876. } else
  877. {
  878. // If texture contains only an alpha channel, use alpha shader (for fonts)
  879. vs = diffTextureVS;
  880. if (batch.texture_->GetFormat() == alphaFormat)
  881. ps = alphaTexturePS;
  882. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  883. ps = diffMaskTexturePS;
  884. else
  885. ps = diffTexturePS;
  886. }
  887. } else
  888. {
  889. vs = diffTextureVS;
  890. ps = diffTexturePS;
  891. Technique* technique = batch.customMaterial_->GetTechnique(0);
  892. if (technique)
  893. {
  894. Pass* pass = nullptr;
  895. for (int i = 0; i < technique->GetNumPasses(); ++i)
  896. {
  897. pass = technique->GetPass(i);
  898. if (pass)
  899. {
  900. vs = graphics_->GetShader(VS, pass->GetVertexShader(), batch.customMaterial_->GetVertexShaderDefines());
  901. ps = graphics_->GetShader(PS, pass->GetPixelShader(), batch.customMaterial_->GetPixelShaderDefines());
  902. break;
  903. }
  904. }
  905. }
  906. }
  907. graphics_->SetShaders(vs, ps);
  908. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  909. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  910. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  911. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  912. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  913. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  914. float elapsedTime = GetSubsystem<Time>()->GetElapsedTime();
  915. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  916. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  917. IntRect scissor = batch.scissor_;
  918. scissor.left_ = (int)(scissor.left_ * uiScale_);
  919. scissor.top_ = (int)(scissor.top_ * uiScale_);
  920. scissor.right_ = (int)(scissor.right_ * uiScale_);
  921. scissor.bottom_ = (int)(scissor.bottom_ * uiScale_);
  922. // Flip scissor vertically if using OpenGL texture rendering
  923. if (Graphics::GetGAPI() == GAPI_OPENGL && surface)
  924. {
  925. int top = scissor.top_;
  926. int bottom = scissor.bottom_;
  927. scissor.top_ = viewSize.y_ - bottom;
  928. scissor.bottom_ = viewSize.y_ - top;
  929. }
  930. graphics_->SetBlendMode(batch.blendMode_);
  931. graphics_->SetScissorTest(true, scissor);
  932. if (!batch.customMaterial_)
  933. {
  934. graphics_->SetTexture(0, batch.texture_);
  935. } else
  936. {
  937. // Update custom shader parameters if needed
  938. if (graphics_->NeedParameterUpdate(SP_MATERIAL, reinterpret_cast<const void*>(batch.customMaterial_->GetShaderParameterHash())))
  939. {
  940. auto shader_parameters = batch.customMaterial_->GetShaderParameters();
  941. for (auto it = shader_parameters.Begin(); it != shader_parameters.End(); ++it)
  942. {
  943. graphics_->SetShaderParameter(it->second_.name_, it->second_.value_);
  944. }
  945. }
  946. // Apply custom shader textures
  947. auto textures = batch.customMaterial_->GetTextures();
  948. for (auto it = textures.Begin(); it != textures.End(); ++it)
  949. {
  950. graphics_->SetTexture(it->first_, it->second_);
  951. }
  952. }
  953. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE,
  954. (batch.vertexEnd_ - batch.vertexStart_) / UI_VERTEX_SIZE);
  955. if (batch.customMaterial_)
  956. {
  957. // Reset textures used by the batch custom material
  958. auto textures = batch.customMaterial_->GetTextures();
  959. for (auto it = textures.Begin(); it != textures.End(); ++it)
  960. {
  961. graphics_->SetTexture(it->first_, 0);
  962. }
  963. }
  964. }
  965. }
  966. void UI::GetBatches(Vector<UIBatch>& batches, Vector<float>& vertexData, UIElement* element, IntRect currentScissor)
  967. {
  968. // Set clipping scissor for child elements. No need to draw if zero size
  969. element->AdjustScissor(currentScissor);
  970. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  971. return;
  972. element->SortChildren();
  973. const Vector<SharedPtr<UIElement>>& children = element->GetChildren();
  974. if (children.Empty())
  975. return;
  976. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  977. // same renderstate
  978. Vector<SharedPtr<UIElement>>::ConstIterator i = children.Begin();
  979. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  980. {
  981. Vector<SharedPtr<UIElement>>::ConstIterator j = i;
  982. while (i != children.End())
  983. {
  984. int currentPriority = (*i)->GetPriority();
  985. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  986. {
  987. if ((*j)->IsWithinScissor(currentScissor) && (*j) != cursor_)
  988. (*j)->GetBatches(batches, vertexData, currentScissor);
  989. ++j;
  990. }
  991. // Now recurse into the children
  992. while (i != j)
  993. {
  994. if ((*i)->IsVisible() && (*i) != cursor_)
  995. GetBatches(batches, vertexData, *i, currentScissor);
  996. ++i;
  997. }
  998. }
  999. }
  1000. // On the root level draw each element and its children immediately after to avoid artifacts
  1001. else
  1002. {
  1003. while (i != children.End())
  1004. {
  1005. if ((*i) != cursor_)
  1006. {
  1007. if ((*i)->IsWithinScissor(currentScissor))
  1008. (*i)->GetBatches(batches, vertexData, currentScissor);
  1009. if ((*i)->IsVisible())
  1010. GetBatches(batches, vertexData, *i, currentScissor);
  1011. }
  1012. ++i;
  1013. }
  1014. }
  1015. }
  1016. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  1017. {
  1018. if (!current)
  1019. return;
  1020. current->SortChildren();
  1021. const Vector<SharedPtr<UIElement>>& children = current->GetChildren();
  1022. LayoutMode parentLayoutMode = current->GetLayoutMode();
  1023. for (unsigned i = 0; i < children.Size(); ++i)
  1024. {
  1025. UIElement* element = children[i];
  1026. bool hasChildren = element->GetNumChildren() > 0;
  1027. if (element != cursor_.Get() && element->IsVisible())
  1028. {
  1029. if (element->IsInside(position, true))
  1030. {
  1031. // Store the current result, then recurse into its children. Because children
  1032. // are sorted from lowest to highest priority, the topmost match should remain
  1033. if (element->IsEnabled() || !enabledOnly)
  1034. result = element;
  1035. if (hasChildren)
  1036. GetElementAt(result, element, position, enabledOnly);
  1037. // Layout optimization: if the element has no children, can break out after the first match
  1038. else if (parentLayoutMode != LM_FREE)
  1039. break;
  1040. }
  1041. else
  1042. {
  1043. if (hasChildren)
  1044. {
  1045. if (element->IsInsideCombined(position, true))
  1046. GetElementAt(result, element, position, enabledOnly);
  1047. }
  1048. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  1049. // or if we already passed all visible elements
  1050. else if (parentLayoutMode != LM_FREE)
  1051. {
  1052. if (!i)
  1053. {
  1054. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  1055. element->GetScreenPosition().y_;
  1056. int layoutMaxSize = current->GetLayoutElementMaxSize();
  1057. int spacing = current->GetLayoutSpacing();
  1058. if (screenPos < 0 && layoutMaxSize > 0)
  1059. {
  1060. auto toSkip = (unsigned)(-screenPos / (layoutMaxSize + spacing));
  1061. if (toSkip > 0)
  1062. i += (toSkip - 1);
  1063. }
  1064. }
  1065. // Note: we cannot check for the up / left limits of positioning, since the element may be off the visible
  1066. // screen but some of its layouted children will yet be visible. In down & right directions we can terminate
  1067. // the loop, since all further children will be further down or right.
  1068. else if (parentLayoutMode == LM_HORIZONTAL)
  1069. {
  1070. if (element->GetScreenPosition().x_ >= rootElement_->GetPosition().x_ + rootElement_->GetSize().x_)
  1071. break;
  1072. }
  1073. else if (parentLayoutMode == LM_VERTICAL)
  1074. {
  1075. if (element->GetScreenPosition().y_ >= rootElement_->GetPosition().y_ + rootElement_->GetSize().y_)
  1076. break;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. UIElement* UI::GetFocusableElement(UIElement* element)
  1084. {
  1085. while (element)
  1086. {
  1087. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  1088. break;
  1089. element = element->GetParent();
  1090. }
  1091. return element;
  1092. }
  1093. void UI::GetCursorPositionAndVisible(IntVector2& pos, bool& visible)
  1094. {
  1095. // Prefer software cursor then OS-specific cursor
  1096. if (cursor_ && cursor_->IsVisible())
  1097. {
  1098. pos = cursor_->GetPosition();
  1099. visible = true;
  1100. }
  1101. else if (GetSubsystem<Input>()->GetMouseMode() == MM_RELATIVE)
  1102. visible = true;
  1103. else
  1104. {
  1105. auto* input = GetSubsystem<Input>();
  1106. visible = input->IsMouseVisible();
  1107. if (!visible && cursor_)
  1108. {
  1109. pos = cursor_->GetPosition();
  1110. }
  1111. else
  1112. {
  1113. pos = input->GetMousePosition();
  1114. pos = ConvertSystemToUI(pos);
  1115. }
  1116. }
  1117. }
  1118. void UI::SetCursorShape(CursorShape shape)
  1119. {
  1120. if (cursor_)
  1121. cursor_->SetShape(shape);
  1122. }
  1123. void UI::ReleaseFontFaces()
  1124. {
  1125. URHO3D_LOGDEBUG("Reloading font faces");
  1126. Vector<Font*> fonts;
  1127. GetSubsystem<ResourceCache>()->GetResources<Font>(fonts);
  1128. for (Font* font : fonts)
  1129. font->ReleaseFaces();
  1130. }
  1131. void UI::ProcessHover(const IntVector2& windowCursorPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor)
  1132. {
  1133. IntVector2 cursorPos;
  1134. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1135. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1136. {
  1137. WeakPtr<UIElement> dragElement = i->first_;
  1138. UI::DragData* dragData = i->second_;
  1139. if (!dragElement)
  1140. {
  1141. i = DragElementErase(i);
  1142. continue;
  1143. }
  1144. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1145. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1146. bool dragDropTest = dragSource && dragTarget && element != dragElement;
  1147. // If drag start event has not been posted yet, do not do drag handling here
  1148. if (dragData->dragBeginPending)
  1149. dragSource = dragTarget = dragDropTest = false;
  1150. // Hover effect
  1151. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  1152. if (element && element->IsEnabled())
  1153. {
  1154. if (dragElement == element || dragDropTest)
  1155. {
  1156. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1157. // Begin hover event
  1158. if (!hoveredElements_.Contains(element))
  1159. {
  1160. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1161. // Exit if element is destroyed by the event handling
  1162. if (!element)
  1163. return;
  1164. }
  1165. hoveredElements_[element] = true;
  1166. }
  1167. }
  1168. // Drag and drop test
  1169. if (dragDropTest)
  1170. {
  1171. bool accept = element->OnDragDropTest(dragElement);
  1172. if (accept)
  1173. {
  1174. using namespace DragDropTest;
  1175. VariantMap& eventData = GetEventDataMap();
  1176. eventData[P_SOURCE] = dragElement.Get();
  1177. eventData[P_TARGET] = element.Get();
  1178. eventData[P_ACCEPT] = accept;
  1179. SendEvent(E_DRAGDROPTEST, eventData);
  1180. accept = eventData[P_ACCEPT].GetBool();
  1181. }
  1182. if (cursor)
  1183. cursor->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  1184. }
  1185. else if (dragSource && cursor)
  1186. cursor->SetShape(dragElement == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  1187. ++i;
  1188. }
  1189. // Hover effect
  1190. // If no drag is going on, transmit hover event.
  1191. if (element && element->IsEnabled())
  1192. {
  1193. if (dragElementsCount_ == 0)
  1194. {
  1195. element->OnHover(element->ScreenToElement(cursorPos), cursorPos, buttons, qualifiers, cursor);
  1196. // Begin hover event
  1197. if (!hoveredElements_.Contains(element))
  1198. {
  1199. SendDragOrHoverEvent(E_HOVERBEGIN, element, cursorPos, IntVector2::ZERO, nullptr);
  1200. // Exit if element is destroyed by the event handling
  1201. if (!element)
  1202. return;
  1203. }
  1204. hoveredElements_[element] = true;
  1205. }
  1206. }
  1207. }
  1208. void UI::ProcessClickBegin(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1209. {
  1210. if (cursorVisible)
  1211. {
  1212. IntVector2 cursorPos;
  1213. WeakPtr<UIElement> element(GetElementAt(windowCursorPos, true, &cursorPos));
  1214. bool newButton;
  1215. if (usingTouchInput_)
  1216. newButton = (buttons & button) == MOUSEB_NONE;
  1217. else
  1218. newButton = true;
  1219. buttons |= button;
  1220. if (element)
  1221. SetFocusElement(element);
  1222. // Focus change events may destroy the element, check again.
  1223. if (element)
  1224. {
  1225. // Handle focusing & bringing to front
  1226. element->BringToFront();
  1227. // Handle click
  1228. element->OnClickBegin(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1229. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1230. // Fire double click event if element matches and is in time and is within max distance from the original click
  1231. if (doubleClickElement_ && element == doubleClickElement_ &&
  1232. (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000)) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1233. {
  1234. element->OnDoubleClick(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor);
  1235. doubleClickElement_.Reset();
  1236. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1237. }
  1238. else
  1239. {
  1240. doubleClickElement_ = element;
  1241. doubleClickFirstPos_ = windowCursorPos;
  1242. clickTimer_.Reset();
  1243. }
  1244. // Handle start of drag. Click handling may have caused destruction of the element, so check the pointer again
  1245. bool dragElementsContain = dragElements_.Contains(element);
  1246. if (element && !dragElementsContain)
  1247. {
  1248. auto* dragData = new DragData();
  1249. dragElements_[element] = dragData;
  1250. dragData->dragBeginPending = true;
  1251. dragData->sumPos = cursorPos;
  1252. dragData->dragBeginSumPos = cursorPos;
  1253. dragData->dragBeginTimer.Reset();
  1254. dragData->dragButtons = button;
  1255. dragData->numDragButtons = CountSetBits((u32)dragData->dragButtons);
  1256. dragElementsCount_++;
  1257. dragElementsContain = dragElements_.Contains(element);
  1258. }
  1259. else if (element && dragElementsContain && newButton)
  1260. {
  1261. DragData* dragData = dragElements_[element];
  1262. dragData->sumPos += cursorPos;
  1263. dragData->dragBeginSumPos += cursorPos;
  1264. dragData->dragButtons |= button;
  1265. dragData->numDragButtons = CountSetBits((u32)dragData->dragButtons);
  1266. }
  1267. }
  1268. else
  1269. {
  1270. // If clicked over no element, or a disabled element, lose focus (but not if there is a modal element)
  1271. if (!HasModalElement())
  1272. SetFocusElement(nullptr);
  1273. SendClickEvent(E_UIMOUSECLICK, nullptr, element, cursorPos, button, buttons, qualifiers);
  1274. if (clickTimer_.GetMSec(true) < (unsigned)(doubleClickInterval_ * 1000) && lastMouseButtons_ == buttons && (windowCursorPos - doubleClickFirstPos_).Length() < maxDoubleClickDist_)
  1275. SendDoubleClickEvent(nullptr, element, doubleClickFirstPos_, cursorPos, button, buttons, qualifiers);
  1276. }
  1277. lastMouseButtons_ = buttons;
  1278. }
  1279. }
  1280. void UI::ProcessClickEnd(const IntVector2& windowCursorPos, MouseButton button, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor, bool cursorVisible)
  1281. {
  1282. WeakPtr<UIElement> element;
  1283. IntVector2 cursorPos = windowCursorPos;
  1284. if (cursorVisible)
  1285. element = GetElementAt(cursorPos, true, &cursorPos);
  1286. // Handle end of drag
  1287. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1288. {
  1289. WeakPtr<UIElement> dragElement = i->first_;
  1290. UI::DragData* dragData = i->second_;
  1291. if (!dragElement || !cursorVisible)
  1292. {
  1293. i = DragElementErase(i);
  1294. continue;
  1295. }
  1296. if (dragData->dragButtons & button)
  1297. {
  1298. // Handle end of click
  1299. if (element)
  1300. element->OnClickEnd(element->ScreenToElement(cursorPos), cursorPos, button, buttons, qualifiers, cursor,
  1301. dragElement);
  1302. SendClickEvent(E_UIMOUSECLICKEND, dragElement, element, cursorPos, button, buttons, qualifiers);
  1303. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1304. {
  1305. dragElement->OnDragEnd(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, buttons,
  1306. cursor);
  1307. SendDragOrHoverEvent(E_DRAGEND, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1308. bool dragSource = dragElement && (dragElement->GetDragDropMode() & DD_SOURCE);
  1309. if (dragSource)
  1310. {
  1311. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET);
  1312. bool dragDropFinish = dragSource && dragTarget && element != dragElement;
  1313. if (dragDropFinish)
  1314. {
  1315. bool accept = element->OnDragDropFinish(dragElement);
  1316. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  1317. if (accept && dragElement && element)
  1318. {
  1319. using namespace DragDropFinish;
  1320. VariantMap& eventData = GetEventDataMap();
  1321. eventData[P_SOURCE] = dragElement.Get();
  1322. eventData[P_TARGET] = element.Get();
  1323. eventData[P_ACCEPT] = accept;
  1324. SendEvent(E_DRAGDROPFINISH, eventData);
  1325. }
  1326. }
  1327. }
  1328. }
  1329. i = DragElementErase(i);
  1330. }
  1331. else
  1332. ++i;
  1333. }
  1334. }
  1335. void UI::ProcessMove(const IntVector2& windowCursorPos, const IntVector2& cursorDeltaPos, MouseButtonFlags buttons, QualifierFlags qualifiers, Cursor* cursor,
  1336. bool cursorVisible)
  1337. {
  1338. if (cursorVisible && dragElementsCount_ > 0 && buttons)
  1339. {
  1340. IntVector2 cursorPos;
  1341. GetElementAt(windowCursorPos, true, &cursorPos);
  1342. auto* input = GetSubsystem<Input>();
  1343. bool mouseGrabbed = input->IsMouseGrabbed();
  1344. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1345. {
  1346. WeakPtr<UIElement> dragElement = i->first_;
  1347. UI::DragData* dragData = i->second_;
  1348. if (!dragElement)
  1349. {
  1350. i = DragElementErase(i);
  1351. continue;
  1352. }
  1353. if (!(dragData->dragButtons & buttons))
  1354. {
  1355. ++i;
  1356. continue;
  1357. }
  1358. // Calculate the position that we should send for this drag event.
  1359. IntVector2 sendPos;
  1360. if (usingTouchInput_)
  1361. {
  1362. dragData->sumPos += cursorDeltaPos;
  1363. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1364. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1365. }
  1366. else
  1367. {
  1368. dragData->sumPos = cursorPos;
  1369. sendPos = cursorPos;
  1370. }
  1371. if (dragElement->IsEnabled() && dragElement->IsVisible())
  1372. {
  1373. // Signal drag begin if distance threshold was exceeded
  1374. if (dragData->dragBeginPending && !mouseGrabbed)
  1375. {
  1376. IntVector2 beginSendPos;
  1377. beginSendPos.x_ = dragData->dragBeginSumPos.x_ / dragData->numDragButtons;
  1378. beginSendPos.y_ = dragData->dragBeginSumPos.y_ / dragData->numDragButtons;
  1379. IntVector2 offset = cursorPos - beginSendPos;
  1380. if (Abs(offset.x_) >= dragBeginDistance_ || Abs(offset.y_) >= dragBeginDistance_)
  1381. {
  1382. dragData->dragBeginPending = false;
  1383. dragConfirmedCount_++;
  1384. dragElement->OnDragBegin(dragElement->ScreenToElement(beginSendPos), beginSendPos, buttons, qualifiers,
  1385. cursor);
  1386. SendDragOrHoverEvent(E_DRAGBEGIN, dragElement, beginSendPos, IntVector2::ZERO, dragData);
  1387. }
  1388. }
  1389. if (!dragData->dragBeginPending)
  1390. {
  1391. dragElement->OnDragMove(dragElement->ScreenToElement(sendPos), sendPos, cursorDeltaPos, buttons, qualifiers,
  1392. cursor);
  1393. SendDragOrHoverEvent(E_DRAGMOVE, dragElement, sendPos, cursorDeltaPos, dragData);
  1394. }
  1395. }
  1396. else
  1397. {
  1398. dragElement->OnDragEnd(dragElement->ScreenToElement(sendPos), sendPos, dragData->dragButtons, buttons, cursor);
  1399. SendDragOrHoverEvent(E_DRAGEND, dragElement, sendPos, IntVector2::ZERO, dragData);
  1400. dragElement.Reset();
  1401. }
  1402. ++i;
  1403. }
  1404. }
  1405. }
  1406. void UI::SendDragOrHoverEvent(StringHash eventType, UIElement* element, const IntVector2& screenPos, const IntVector2& deltaPos,
  1407. UI::DragData* dragData)
  1408. {
  1409. if (!element)
  1410. return;
  1411. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1412. using namespace DragMove;
  1413. VariantMap& eventData = GetEventDataMap();
  1414. eventData[P_ELEMENT] = element;
  1415. eventData[P_X] = screenPos.x_;
  1416. eventData[P_Y] = screenPos.y_;
  1417. eventData[P_ELEMENTX] = relativePos.x_;
  1418. eventData[P_ELEMENTY] = relativePos.y_;
  1419. if (eventType == E_DRAGMOVE)
  1420. {
  1421. eventData[P_DX] = deltaPos.x_;
  1422. eventData[P_DY] = deltaPos.y_;
  1423. }
  1424. if (dragData)
  1425. {
  1426. eventData[P_BUTTONS] = (unsigned)dragData->dragButtons;
  1427. eventData[P_NUMBUTTONS] = dragData->numDragButtons;
  1428. }
  1429. element->SendEvent(eventType, eventData);
  1430. }
  1431. void UI::SendClickEvent(StringHash eventType, UIElement* beginElement, UIElement* endElement, const IntVector2& pos, MouseButton button,
  1432. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1433. {
  1434. VariantMap& eventData = GetEventDataMap();
  1435. eventData[UIMouseClick::P_ELEMENT] = endElement;
  1436. eventData[UIMouseClick::P_X] = pos.x_;
  1437. eventData[UIMouseClick::P_Y] = pos.y_;
  1438. eventData[UIMouseClick::P_BUTTON] = button;
  1439. eventData[UIMouseClick::P_BUTTONS] = (unsigned)buttons;
  1440. eventData[UIMouseClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1441. // For click end events, send also the element the click began on
  1442. if (eventType == E_UIMOUSECLICKEND)
  1443. eventData[UIMouseClickEnd::P_BEGINELEMENT] = beginElement;
  1444. if (endElement)
  1445. {
  1446. // Send also element version of the event
  1447. if (eventType == E_UIMOUSECLICK)
  1448. endElement->SendEvent(E_CLICK, eventData);
  1449. else if (eventType == E_UIMOUSECLICKEND)
  1450. endElement->SendEvent(E_CLICKEND, eventData);
  1451. }
  1452. // Send the global event from the UI subsystem last
  1453. SendEvent(eventType, eventData);
  1454. }
  1455. void UI::SendDoubleClickEvent(UIElement* beginElement, UIElement* endElement, const IntVector2& firstPos, const IntVector2& secondPos, MouseButton button,
  1456. MouseButtonFlags buttons, QualifierFlags qualifiers)
  1457. {
  1458. VariantMap& eventData = GetEventDataMap();
  1459. eventData[UIMouseDoubleClick::P_ELEMENT] = endElement;
  1460. eventData[UIMouseDoubleClick::P_X] = secondPos.x_;
  1461. eventData[UIMouseDoubleClick::P_Y] = secondPos.y_;
  1462. eventData[UIMouseDoubleClick::P_XBEGIN] = firstPos.x_;
  1463. eventData[UIMouseDoubleClick::P_YBEGIN] = firstPos.y_;
  1464. eventData[UIMouseDoubleClick::P_BUTTON] = button;
  1465. eventData[UIMouseDoubleClick::P_BUTTONS] = (unsigned)buttons;
  1466. eventData[UIMouseDoubleClick::P_QUALIFIERS] = (unsigned)qualifiers;
  1467. if (endElement)
  1468. {
  1469. // Send also element version of the event
  1470. endElement->SendEvent(E_DOUBLECLICK, eventData);
  1471. }
  1472. // Send the global event from the UI subsystem last
  1473. SendEvent(E_UIMOUSEDOUBLECLICK, eventData);
  1474. }
  1475. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1476. {
  1477. using namespace ScreenMode;
  1478. if (!initialized_)
  1479. Initialize();
  1480. else
  1481. ResizeRootElement();
  1482. }
  1483. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  1484. {
  1485. using namespace MouseButtonDown;
  1486. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetU32());
  1487. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetU32());
  1488. usingTouchInput_ = false;
  1489. IntVector2 cursorPos;
  1490. bool cursorVisible;
  1491. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1492. // Handle drag cancelling
  1493. ProcessDragCancel();
  1494. auto* input = GetSubsystem<Input>();
  1495. if (!input->IsMouseGrabbed())
  1496. ProcessClickBegin(cursorPos, MouseButton(eventData[P_BUTTON].GetU32()), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1497. }
  1498. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  1499. {
  1500. using namespace MouseButtonUp;
  1501. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetU32());
  1502. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetU32());
  1503. IntVector2 cursorPos;
  1504. bool cursorVisible;
  1505. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1506. ProcessClickEnd(cursorPos, (MouseButton)eventData[P_BUTTON].GetU32(), mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1507. }
  1508. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  1509. {
  1510. using namespace MouseMove;
  1511. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetU32());
  1512. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetU32());
  1513. usingTouchInput_ = false;
  1514. auto* input = GetSubsystem<Input>();
  1515. const IntVector2& rootSize = rootElement_->GetSize();
  1516. const IntVector2& rootPos = rootElement_->GetPosition();
  1517. const IntVector2 mouseDeltaPos{ eventData[P_DX].GetI32(), eventData[P_DY].GetI32() };
  1518. const IntVector2 mousePos{ eventData[P_X].GetI32(), eventData[P_Y].GetI32() };
  1519. if (cursor_)
  1520. {
  1521. if (!input->IsMouseVisible())
  1522. {
  1523. if (!input->IsMouseLocked())
  1524. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1525. else if (cursor_->IsVisible())
  1526. {
  1527. // Relative mouse motion: move cursor only when visible
  1528. IntVector2 pos = cursor_->GetPosition();
  1529. pos += ConvertSystemToUI(mouseDeltaPos);
  1530. pos.x_ = Clamp(pos.x_, rootPos.x_, rootPos.x_ + rootSize.x_ - 1);
  1531. pos.y_ = Clamp(pos.y_, rootPos.y_, rootPos.y_ + rootSize.y_ - 1);
  1532. cursor_->SetPosition(pos);
  1533. }
  1534. }
  1535. else
  1536. {
  1537. // Absolute mouse motion: move always
  1538. cursor_->SetPosition(ConvertSystemToUI(mousePos));
  1539. }
  1540. }
  1541. IntVector2 cursorPos;
  1542. bool cursorVisible;
  1543. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1544. ProcessMove(cursorPos, mouseDeltaPos, mouseButtons_, qualifiers_, cursor_, cursorVisible);
  1545. }
  1546. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  1547. {
  1548. auto* input = GetSubsystem<Input>();
  1549. if (input->IsMouseGrabbed())
  1550. return;
  1551. using namespace MouseWheel;
  1552. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetI32());
  1553. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetI32());
  1554. int delta = eventData[P_WHEEL].GetI32();
  1555. usingTouchInput_ = false;
  1556. IntVector2 cursorPos;
  1557. bool cursorVisible;
  1558. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1559. if (!nonFocusedMouseWheel_ && focusElement_)
  1560. focusElement_->OnWheel(delta, mouseButtons_, qualifiers_);
  1561. else
  1562. {
  1563. // If no element has actual focus or in non-focused mode, get the element at cursor
  1564. if (cursorVisible)
  1565. {
  1566. UIElement* element = GetElementAt(cursorPos);
  1567. if (nonFocusedMouseWheel_)
  1568. {
  1569. // Going up the hierarchy chain to find element that could handle mouse wheel
  1570. while (element && !element->IsWheelHandler())
  1571. {
  1572. element = element->GetParent();
  1573. }
  1574. }
  1575. else
  1576. // If the element itself is not focusable, search for a focusable parent,
  1577. // although the focusable element may not actually handle mouse wheel
  1578. element = GetFocusableElement(element);
  1579. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  1580. element->OnWheel(delta, mouseButtons_, qualifiers_);
  1581. }
  1582. }
  1583. }
  1584. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  1585. {
  1586. auto* input = GetSubsystem<Input>();
  1587. if (input->IsMouseGrabbed())
  1588. return;
  1589. using namespace TouchBegin;
  1590. IntVector2 pos(eventData[P_X].GetI32(), eventData[P_Y].GetI32());
  1591. pos = ConvertSystemToUI(pos);
  1592. usingTouchInput_ = true;
  1593. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetI32());
  1594. WeakPtr<UIElement> element(GetElementAt(pos));
  1595. if (element)
  1596. {
  1597. ProcessClickBegin(pos, touchId, touchDragElements_[element], QUAL_NONE, nullptr, true);
  1598. touchDragElements_[element] |= touchId;
  1599. }
  1600. else
  1601. ProcessClickBegin(pos, touchId, touchId, QUAL_NONE, nullptr, true);
  1602. }
  1603. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  1604. {
  1605. using namespace TouchEnd;
  1606. IntVector2 pos(eventData[P_X].GetI32(), eventData[P_Y].GetI32());
  1607. pos = ConvertSystemToUI(pos);
  1608. // Get the touch index
  1609. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetI32());
  1610. // Transmit hover end to the position where the finger was lifted
  1611. WeakPtr<UIElement> element(GetElementAt(pos));
  1612. // Clear any drag events that were using the touch id
  1613. for (auto i = touchDragElements_.Begin(); i != touchDragElements_.End();)
  1614. {
  1615. const MouseButtonFlags touches = i->second_;
  1616. if (touches & touchId)
  1617. i = touchDragElements_.Erase(i);
  1618. else
  1619. ++i;
  1620. }
  1621. if (element && element->IsEnabled())
  1622. element->OnHover(element->ScreenToElement(pos), pos, MOUSEB_NONE, QUAL_NONE, nullptr);
  1623. ProcessClickEnd(pos, touchId, MOUSEB_NONE, QUAL_NONE, nullptr, true);
  1624. }
  1625. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  1626. {
  1627. using namespace TouchMove;
  1628. IntVector2 pos(eventData[P_X].GetI32(), eventData[P_Y].GetI32());
  1629. IntVector2 deltaPos(eventData[P_DX].GetI32(), eventData[P_DY].GetI32());
  1630. pos = ConvertSystemToUI(pos);
  1631. deltaPos = ConvertSystemToUI(deltaPos);
  1632. usingTouchInput_ = true;
  1633. const MouseButton touchId = MakeTouchIDMask(eventData[P_TOUCHID].GetI32());
  1634. ProcessMove(pos, deltaPos, touchId, QUAL_NONE, nullptr, true);
  1635. }
  1636. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  1637. {
  1638. using namespace KeyDown;
  1639. mouseButtons_ = MouseButtonFlags(eventData[P_BUTTONS].GetU32());
  1640. qualifiers_ = QualifierFlags(eventData[P_QUALIFIERS].GetU32());
  1641. auto key = (Key)eventData[P_KEY].GetU32();
  1642. // Cancel UI dragging
  1643. if (key == KEY_ESCAPE && dragElementsCount_ > 0)
  1644. {
  1645. ProcessDragCancel();
  1646. return;
  1647. }
  1648. // Dismiss modal element if any when ESC key is pressed
  1649. if (key == KEY_ESCAPE && HasModalElement())
  1650. {
  1651. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  1652. if (element->GetVars().Contains(VAR_ORIGIN))
  1653. // If it is a popup, dismiss by defocusing it
  1654. SetFocusElement(nullptr);
  1655. else
  1656. {
  1657. // If it is a modal window, by resetting its modal flag
  1658. auto* window = dynamic_cast<Window*>(element);
  1659. if (window && window->GetModalAutoDismiss())
  1660. window->SetModal(false);
  1661. }
  1662. return;
  1663. }
  1664. UIElement* element = focusElement_;
  1665. if (element)
  1666. {
  1667. // Switch focus between focusable elements in the same top level window
  1668. if (key == KEY_TAB)
  1669. {
  1670. UIElement* topLevel = element->GetParent();
  1671. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  1672. topLevel = topLevel->GetParent();
  1673. if (topLevel)
  1674. {
  1675. topLevel->GetChildren(tempElements_, true);
  1676. for (Vector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  1677. {
  1678. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  1679. i = tempElements_.Erase(i);
  1680. else
  1681. ++i;
  1682. }
  1683. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  1684. {
  1685. if (tempElements_[i] == element)
  1686. {
  1687. int dir = (qualifiers_ & QUAL_SHIFT) ? -1 : 1;
  1688. unsigned nextIndex = (tempElements_.Size() + i + dir) % tempElements_.Size();
  1689. UIElement* next = tempElements_[nextIndex];
  1690. SetFocusElement(next, true);
  1691. return;
  1692. }
  1693. }
  1694. }
  1695. }
  1696. // Defocus the element
  1697. else if (key == KEY_ESCAPE && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  1698. element->SetFocus(false);
  1699. // If none of the special keys, pass the key to the focused element
  1700. else
  1701. element->OnKey(key, mouseButtons_, qualifiers_);
  1702. }
  1703. }
  1704. void UI::HandleTextInput(StringHash eventType, VariantMap& eventData)
  1705. {
  1706. using namespace TextInput;
  1707. UIElement* element = focusElement_;
  1708. if (element)
  1709. element->OnTextInput(eventData[P_TEXT].GetString());
  1710. }
  1711. void UI::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1712. {
  1713. // If have a cursor, and a drag is not going on, reset the cursor shape. Application logic that wants to apply
  1714. // custom shapes can do it after this, but needs to do it each frame
  1715. if (cursor_ && dragElementsCount_ == 0)
  1716. cursor_->SetShape(CS_NORMAL);
  1717. }
  1718. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  1719. {
  1720. using namespace PostUpdate;
  1721. Update(eventData[P_TIMESTEP].GetFloat());
  1722. }
  1723. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1724. {
  1725. RenderUpdate();
  1726. }
  1727. void UI::HandleDropFile(StringHash eventType, VariantMap& eventData)
  1728. {
  1729. auto* input = GetSubsystem<Input>();
  1730. // Sending the UI variant of the event only makes sense if the OS cursor is visible (not locked to window center)
  1731. if (input->IsMouseVisible())
  1732. {
  1733. IntVector2 screenPos = input->GetMousePosition();
  1734. screenPos = ConvertSystemToUI(screenPos);
  1735. UIElement* element = GetElementAt(screenPos);
  1736. using namespace UIDropFile;
  1737. VariantMap uiEventData;
  1738. uiEventData[P_FILENAME] = eventData[P_FILENAME];
  1739. uiEventData[P_X] = screenPos.x_;
  1740. uiEventData[P_Y] = screenPos.y_;
  1741. uiEventData[P_ELEMENT] = element;
  1742. if (element)
  1743. {
  1744. IntVector2 relativePos = element->ScreenToElement(screenPos);
  1745. uiEventData[P_ELEMENTX] = relativePos.x_;
  1746. uiEventData[P_ELEMENTY] = relativePos.y_;
  1747. }
  1748. SendEvent(E_UIDROPFILE, uiEventData);
  1749. }
  1750. }
  1751. HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator UI::DragElementErase(HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i)
  1752. {
  1753. // If running the engine frame in response to an event (re-entering UI frame logic) the dragElements_ may already be empty
  1754. if (dragElements_.Empty())
  1755. return dragElements_.End();
  1756. dragElementsConfirmed_.Clear();
  1757. DragData* dragData = i->second_;
  1758. if (!dragData->dragBeginPending)
  1759. --dragConfirmedCount_;
  1760. i = dragElements_.Erase(i);
  1761. --dragElementsCount_;
  1762. delete dragData;
  1763. return i;
  1764. }
  1765. void UI::ProcessDragCancel()
  1766. {
  1767. // How to tell difference between drag cancel and new selection on multi-touch?
  1768. if (usingTouchInput_)
  1769. return;
  1770. IntVector2 cursorPos;
  1771. bool cursorVisible;
  1772. GetCursorPositionAndVisible(cursorPos, cursorVisible);
  1773. for (HashMap<WeakPtr<UIElement>, UI::DragData*>::Iterator i = dragElements_.Begin(); i != dragElements_.End();)
  1774. {
  1775. WeakPtr<UIElement> dragElement = i->first_;
  1776. UI::DragData* dragData = i->second_;
  1777. if (dragElement && dragElement->IsEnabled() && dragElement->IsVisible() && !dragData->dragBeginPending)
  1778. {
  1779. dragElement->OnDragCancel(dragElement->ScreenToElement(cursorPos), cursorPos, dragData->dragButtons, mouseButtons_,
  1780. cursor_);
  1781. SendDragOrHoverEvent(E_DRAGCANCEL, dragElement, cursorPos, IntVector2::ZERO, dragData);
  1782. i = DragElementErase(i);
  1783. }
  1784. else
  1785. ++i;
  1786. }
  1787. }
  1788. IntVector2 UI::SumTouchPositions(UI::DragData* dragData, const IntVector2& oldSendPos)
  1789. {
  1790. IntVector2 sendPos = oldSendPos;
  1791. if (usingTouchInput_)
  1792. {
  1793. MouseButtonFlags buttons = dragData->dragButtons;
  1794. dragData->sumPos = IntVector2::ZERO;
  1795. auto* input = GetSubsystem<Input>();
  1796. for (unsigned i = 0; (1u << i) <= (unsigned)buttons; i++)
  1797. {
  1798. auto mouseButton = static_cast<MouseButton>(1u << i); // NOLINT(misc-misplaced-widening-cast)
  1799. if (buttons & mouseButton)
  1800. {
  1801. TouchState* ts = input->GetTouch((unsigned)i);
  1802. if (!ts)
  1803. break;
  1804. IntVector2 pos = ts->position_;
  1805. pos = ConvertSystemToUI(pos);
  1806. dragData->sumPos += pos;
  1807. }
  1808. }
  1809. sendPos.x_ = dragData->sumPos.x_ / dragData->numDragButtons;
  1810. sendPos.y_ = dragData->sumPos.y_ / dragData->numDragButtons;
  1811. }
  1812. return sendPos;
  1813. }
  1814. void UI::ResizeRootElement()
  1815. {
  1816. IntVector2 effectiveSize = GetEffectiveRootElementSize();
  1817. rootElement_->SetSize(effectiveSize);
  1818. rootModalElement_->SetSize(effectiveSize);
  1819. }
  1820. IntVector2 UI::GetEffectiveRootElementSize(bool applyScale) const
  1821. {
  1822. // Use a fake size in headless mode
  1823. IntVector2 size = graphics_ ? IntVector2(graphics_->GetWidth(), graphics_->GetHeight()) : IntVector2(1024, 768);
  1824. if (customSize_.x_ > 0 && customSize_.y_ > 0)
  1825. size = customSize_;
  1826. if (applyScale)
  1827. {
  1828. size.x_ = RoundToInt((float)size.x_ / uiScale_);
  1829. size.y_ = RoundToInt((float)size.y_ / uiScale_);
  1830. }
  1831. return size;
  1832. }
  1833. void UI::SetElementRenderTexture(UIElement* element, Texture2D* texture)
  1834. {
  1835. if (element == nullptr)
  1836. {
  1837. URHO3D_LOGERROR("UI::SetElementRenderTexture called with null element.");
  1838. return;
  1839. }
  1840. auto it = renderToTexture_.Find(element);
  1841. if (texture && it == renderToTexture_.End())
  1842. {
  1843. RenderToTextureData data;
  1844. data.texture_ = texture;
  1845. data.rootElement_ = element;
  1846. data.vertexBuffer_ = new VertexBuffer(context_);
  1847. data.debugVertexBuffer_ = new VertexBuffer(context_);
  1848. renderToTexture_[element] = data;
  1849. }
  1850. else if (it != renderToTexture_.End())
  1851. {
  1852. if (texture == nullptr)
  1853. renderToTexture_.Erase(it);
  1854. else
  1855. it->second_.texture_ = texture;
  1856. }
  1857. }
  1858. void RegisterUILibrary(Context* context)
  1859. {
  1860. Font::RegisterObject(context);
  1861. UIElement::RegisterObject(context);
  1862. UISelectable::RegisterObject(context);
  1863. BorderImage::RegisterObject(context);
  1864. Sprite::RegisterObject(context);
  1865. Button::RegisterObject(context);
  1866. CheckBox::RegisterObject(context);
  1867. Cursor::RegisterObject(context);
  1868. Text::RegisterObject(context);
  1869. Text3D::RegisterObject(context);
  1870. Window::RegisterObject(context);
  1871. View3D::RegisterObject(context);
  1872. LineEdit::RegisterObject(context);
  1873. Slider::RegisterObject(context);
  1874. ScrollBar::RegisterObject(context);
  1875. ScrollView::RegisterObject(context);
  1876. ListView::RegisterObject(context);
  1877. Menu::RegisterObject(context);
  1878. DropDownList::RegisterObject(context);
  1879. FileSelector::RegisterObject(context);
  1880. MessageBox::RegisterObject(context);
  1881. ProgressBar::RegisterObject(context);
  1882. ToolTip::RegisterObject(context);
  1883. UIComponent::RegisterObject(context);
  1884. }
  1885. }