UI.cpp 74 KB

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