2
0

UI.cpp 77 KB

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