UI.cpp 73 KB

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