UI.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. //
  2. // Copyright (c) 2008-2013 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 "CheckBox.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "Cursor.h"
  27. #include "DropDownList.h"
  28. #include "FileSelector.h"
  29. #include "Font.h"
  30. #include "Graphics.h"
  31. #include "GraphicsEvents.h"
  32. #include "Input.h"
  33. #include "InputEvents.h"
  34. #include "LineEdit.h"
  35. #include "ListView.h"
  36. #include "Log.h"
  37. #include "Matrix3x4.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ScrollBar.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Slider.h"
  44. #include "Sort.h"
  45. #include "Sprite.h"
  46. #include "Text.h"
  47. #include "Texture2D.h"
  48. #include "UI.h"
  49. #include "UIEvents.h"
  50. #include "VertexBuffer.h"
  51. #include "Window.h"
  52. #include "DebugNew.h"
  53. namespace Urho3D
  54. {
  55. ShortStringHash VAR_ORIGIN("Origin");
  56. const ShortStringHash VAR_ORIGINAL_PARENT("OriginalParent");
  57. const ShortStringHash VAR_PARENT_CHANGED("ParentChanged");
  58. OBJECTTYPESTATIC(UI);
  59. UI::UI(Context* context) :
  60. Object(context),
  61. rootElement_(new UIElement(context)),
  62. rootModalElement_(new UIElement(context)),
  63. mouseButtons_(0),
  64. qualifiers_(0),
  65. initialized_(false),
  66. #ifdef WIN32
  67. nonFocusedMouseWheel_(false), // Default MS Windows behaviour
  68. #else
  69. nonFocusedMouseWheel_(true), // Default Mac OS X and Linux behaviour
  70. #endif
  71. nonModalBatchSize_(0)
  72. {
  73. rootElement_->SetTraversalMode(TM_DEPTH_FIRST);
  74. rootModalElement_->SetTraversalMode(TM_DEPTH_FIRST);
  75. SubscribeToEvent(E_SCREENMODE, HANDLER(UI, HandleScreenMode));
  76. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  77. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  78. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  79. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  80. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(UI, HandleTouchBegin));
  81. SubscribeToEvent(E_TOUCHEND, HANDLER(UI, HandleTouchEnd));
  82. SubscribeToEvent(E_TOUCHMOVE, HANDLER(UI, HandleTouchMove));
  83. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  84. SubscribeToEvent(E_CHAR, HANDLER(UI, HandleChar));
  85. // Delay SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate)) and
  86. // SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate)) until UI is initialized
  87. // Try to initialize right now, but skip if screen mode is not yet set
  88. Initialize();
  89. }
  90. UI::~UI()
  91. {
  92. }
  93. void UI::SetCursor(Cursor* cursor)
  94. {
  95. // Remove old cursor (if any) and set new
  96. if (cursor_)
  97. {
  98. rootElement_->RemoveChild(cursor_);
  99. cursor_.Reset();
  100. }
  101. if (cursor)
  102. {
  103. rootElement_->AddChild(cursor);
  104. cursor_ = cursor;
  105. IntVector2 pos = cursor_->GetPosition();
  106. const IntVector2& rootSize = rootElement_->GetSize();
  107. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  108. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  109. cursor_->SetPosition(pos);
  110. }
  111. }
  112. void UI::SetFocusElement(UIElement* element)
  113. {
  114. using namespace FocusChanged;
  115. VariantMap eventData;
  116. eventData[P_CLICKEDELEMENT] = (void*)element;
  117. if (element)
  118. {
  119. // Return if already has focus
  120. if (focusElement_ == element)
  121. return;
  122. // Only allow child elements of the modal element to receive focus
  123. if (HasModalElement())
  124. {
  125. UIElement* topLevel = element->GetParent();
  126. while (topLevel && topLevel->GetParent() != rootElement_)
  127. topLevel = topLevel->GetParent();
  128. if (topLevel) // If parented to non-modal root then ignore
  129. return;
  130. }
  131. // Search for an element in the hierarchy that can alter focus. If none found, exit
  132. element = GetFocusableElement(element);
  133. if (!element)
  134. return;
  135. }
  136. // Remove focus from the old element
  137. if (focusElement_)
  138. {
  139. UIElement* oldFocusElement = focusElement_;
  140. focusElement_.Reset();
  141. VariantMap focusEventData;
  142. focusEventData[Defocused::P_ELEMENT] = oldFocusElement;
  143. oldFocusElement->SendEvent(E_DEFOCUSED, focusEventData);
  144. }
  145. // Then set focus to the new
  146. if (element && element->GetFocusMode() >= FM_FOCUSABLE)
  147. {
  148. focusElement_ = element;
  149. VariantMap focusEventData;
  150. focusEventData[Focused::P_ELEMENT] = element;
  151. element->SendEvent(E_FOCUSED, focusEventData);
  152. }
  153. eventData[P_ELEMENT] = (void*)element;
  154. SendEvent(E_FOCUSCHANGED, eventData);
  155. }
  156. bool UI::SetModalElement(UIElement* modalElement, bool enable)
  157. {
  158. if (!modalElement)
  159. return false;
  160. // Currently only allow modal window
  161. if (modalElement->GetType() != Window::GetTypeStatic())
  162. return false;
  163. assert(rootModalElement_);
  164. const Vector<SharedPtr<UIElement> >& children = rootModalElement_->GetChildren();
  165. if (enable)
  166. {
  167. // Make sure it is not already the child of the root modal element
  168. for (unsigned i = 0; i < children.Size(); ++i)
  169. {
  170. if (children[i] == modalElement)
  171. return false;
  172. }
  173. // Adopt modal root as parent
  174. modalElement->SetVar(VAR_ORIGINAL_PARENT, modalElement->GetParent());
  175. modalElement->SetParent(rootModalElement_);
  176. // If it is a popup element, bring along its top-level parent
  177. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  178. if (originElement)
  179. {
  180. UIElement* element = originElement;
  181. while (element && element->GetParent() != rootElement_)
  182. element = element->GetParent();
  183. if (element)
  184. {
  185. originElement->SetVar(VAR_PARENT_CHANGED, element);
  186. element->SetVar(VAR_ORIGINAL_PARENT, element->GetParent());
  187. element->SetParent(rootModalElement_);
  188. }
  189. }
  190. return true;
  191. }
  192. else
  193. {
  194. // Only the modal element can disable itself
  195. for (unsigned i = 0; i < children.Size(); ++i)
  196. {
  197. if (children[i] == modalElement)
  198. {
  199. // Revert back to original parent
  200. modalElement->SetParent(static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGINAL_PARENT).GetPtr()));
  201. const_cast<VariantMap&>(modalElement->GetVars()).Erase(VAR_ORIGINAL_PARENT);
  202. // If it is a popup element, revert back its top-level parent to its original parent
  203. UIElement* originElement = static_cast<UIElement*>(modalElement->GetVar(VAR_ORIGIN).GetPtr());
  204. if (originElement)
  205. {
  206. UIElement* element = static_cast<UIElement*>(originElement->GetVar(VAR_PARENT_CHANGED).GetPtr());
  207. if (element)
  208. {
  209. const_cast<VariantMap&>(originElement->GetVars()).Erase(VAR_PARENT_CHANGED);
  210. element->SetParent(static_cast<UIElement*>(element->GetVar(VAR_ORIGINAL_PARENT).GetPtr()));
  211. const_cast<VariantMap&>(element->GetVars()).Erase(VAR_ORIGINAL_PARENT);
  212. }
  213. }
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. }
  220. void UI::Clear()
  221. {
  222. rootElement_->RemoveAllChildren();
  223. rootModalElement_->RemoveAllChildren();
  224. if (cursor_)
  225. rootElement_->AddChild(cursor_);
  226. }
  227. void UI::Update(float timeStep)
  228. {
  229. assert(rootElement_ && rootModalElement_);
  230. PROFILE(UpdateUI);
  231. if (cursor_ && cursor_->IsVisible())
  232. {
  233. IntVector2 pos = cursor_->GetPosition();
  234. WeakPtr<UIElement> element(GetElementAt(pos));
  235. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  236. bool dragTarget = element && (element->GetDragDropMode() & DD_TARGET) != 0;
  237. bool dragDropTest = dragSource && dragTarget && element != dragElement_;
  238. // Hover effect
  239. // If a drag is going on, transmit hover only to the element being dragged, unless it's a drop target
  240. if (element && element->IsEnabled())
  241. {
  242. if (!dragElement_ || dragElement_ == element || dragDropTest)
  243. element->OnHover(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  244. }
  245. else
  246. cursor_->SetShape(CS_NORMAL);
  247. // Drag and drop test
  248. if (dragDropTest)
  249. {
  250. bool accept = element->OnDragDropTest(dragElement_);
  251. if (accept)
  252. {
  253. using namespace DragDropTest;
  254. VariantMap eventData;
  255. eventData[P_SOURCE] = (void*)dragElement_.Get();
  256. eventData[P_TARGET] = (void*)element.Get();
  257. eventData[P_ACCEPT] = accept;
  258. SendEvent(E_DRAGDROPTEST, eventData);
  259. accept = eventData[P_ACCEPT].GetBool();
  260. }
  261. cursor_->SetShape(accept ? CS_ACCEPTDROP : CS_REJECTDROP);
  262. }
  263. else if (dragSource)
  264. cursor_->SetShape(dragElement_ == element ? CS_ACCEPTDROP : CS_REJECTDROP);
  265. }
  266. // Touch hover
  267. Input* input = GetSubsystem<Input>();
  268. if (input)
  269. {
  270. unsigned numTouches = input->GetNumTouches();
  271. for (unsigned i = 0; i < numTouches; ++i)
  272. {
  273. TouchState* touch = input->GetTouch(i);
  274. UIElement* element = GetElementAt(touch->position_);
  275. if (element && element->IsEnabled())
  276. element->OnHover(element->ScreenToElement(touch->position_), touch->position_, MOUSEB_LEFT, 0, 0);
  277. }
  278. }
  279. Update(timeStep, rootElement_);
  280. Update(timeStep, rootModalElement_);
  281. }
  282. void UI::RenderUpdate()
  283. {
  284. assert(rootElement_ && rootModalElement_ && graphics_);
  285. PROFILE(GetUIBatches);
  286. // If the OS cursor is visible, do not render the UI's own cursor
  287. bool osCursorVisible = GetSubsystem<Input>()->IsMouseVisible();
  288. bool uiCursorVisible = false;
  289. if (osCursorVisible && cursor_)
  290. {
  291. uiCursorVisible = cursor_->IsVisible();
  292. cursor_->SetTempVisible(false);
  293. }
  294. // Get rendering batches from the non-modal UI elements
  295. batches_.Clear();
  296. vertexData_.Clear();
  297. const IntVector2& rootSize = rootElement_->GetSize();
  298. IntRect currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  299. GetBatches(rootElement_, currentScissor);
  300. // Save the batch size of the non-modal batches for later use
  301. nonModalBatchSize_ = batches_.Size();
  302. // Get rendering batches from the modal UI elements
  303. GetBatches(rootModalElement_, currentScissor);
  304. // Restore UI cursor visibility state
  305. if (osCursorVisible && cursor_)
  306. cursor_->SetTempVisible(uiCursorVisible);
  307. }
  308. void UI::Render()
  309. {
  310. PROFILE(RenderUI);
  311. // Render non-modal batches
  312. Render(batches_, vertexData_, 0, nonModalBatchSize_);
  313. // Render debug draw
  314. Render(debugDrawBatches_, debugDrawVertexData_, 0, debugDrawBatches_.Size());
  315. // Render modal batches
  316. Render(batches_, vertexData_, nonModalBatchSize_, batches_.Size());
  317. // Clear the debug draw batches and data
  318. debugDrawBatches_.Clear();
  319. debugDrawVertexData_.Clear();
  320. }
  321. void UI::DebugDraw(UIElement* element)
  322. {
  323. if (element)
  324. {
  325. const IntVector2& rootSize = rootElement_->GetSize();
  326. IntRect currentScissor = IntRect(0, 0, rootSize.x_, rootSize.y_);
  327. // Set clipping scissor for child elements. No need to draw if zero size
  328. element->AdjustScissor(currentScissor);
  329. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  330. return;
  331. element->GetDebugDrawBatches(debugDrawBatches_, debugDrawVertexData_, currentScissor);
  332. }
  333. }
  334. SharedPtr<UIElement> UI::LoadLayout(Deserializer& source, XMLFile* styleFile)
  335. {
  336. SharedPtr<XMLFile> xml(new XMLFile(context_));
  337. if (!xml->Load(source))
  338. return SharedPtr<UIElement>();
  339. else
  340. return LoadLayout(xml, styleFile);
  341. }
  342. SharedPtr<UIElement> UI::LoadLayout(XMLFile* file, XMLFile* styleFile)
  343. {
  344. PROFILE(LoadUILayout);
  345. SharedPtr<UIElement> root;
  346. if (!file)
  347. {
  348. LOGERROR("Null UI layout XML file");
  349. return root;
  350. }
  351. LOGDEBUG("Loading UI layout " + file->GetName());
  352. XMLElement rootElem = file->GetRoot("element");
  353. if (!rootElem)
  354. {
  355. LOGERROR("No root UI element in " + file->GetName());
  356. return root;
  357. }
  358. String typeName = rootElem.GetAttribute("type");
  359. if (typeName.Empty())
  360. typeName = "UIElement";
  361. root = DynamicCast<UIElement>(context_->CreateObject(typeName));
  362. if (!root)
  363. {
  364. LOGERROR("Could not create unknown UI element " + typeName);
  365. return root;
  366. }
  367. if (styleFile)
  368. // Set it as default for later use by children elements
  369. root->SetDefaultStyle(styleFile);
  370. else
  371. // Use default style file of the root element if it has one
  372. styleFile = rootElement_->GetDefaultStyle(false);
  373. root->LoadXML(rootElem, styleFile);
  374. return root;
  375. }
  376. bool UI::SaveLayout(Serializer& dest, UIElement* element)
  377. {
  378. PROFILE(SaveUILayout);
  379. if (element)
  380. return element->SaveXML(dest);
  381. else
  382. return false;
  383. }
  384. void UI::SetClipBoardText(const String& text)
  385. {
  386. clipBoard_ = text;
  387. }
  388. void UI::SetNonFocusedMouseWheel(bool nonFocusedMouseWheel)
  389. {
  390. nonFocusedMouseWheel_ = nonFocusedMouseWheel;
  391. }
  392. UIElement* UI::GetElementAt(const IntVector2& position, bool enabledOnly)
  393. {
  394. UIElement* result = 0;
  395. GetElementAt(result, HasModalElement() ? rootModalElement_ : rootElement_, position, enabledOnly);
  396. return result;
  397. }
  398. UIElement* UI::GetElementAt(int x, int y, bool enabledOnly)
  399. {
  400. return GetElementAt(IntVector2(x, y), enabledOnly);
  401. }
  402. UIElement* UI::GetFrontElement() const
  403. {
  404. const Vector<SharedPtr<UIElement> >& rootChildren = rootElement_->GetChildren();
  405. int maxPriority = M_MIN_INT;
  406. UIElement* front = 0;
  407. for (unsigned i = 0; i < rootChildren.Size(); ++i)
  408. {
  409. // Do not take into account input-disabled elements, hidden elements or those that are always in the front
  410. if (!rootChildren[i]->IsEnabled() || !rootChildren[i]->IsVisible() || !rootChildren[i]->GetBringToBack())
  411. continue;
  412. int priority = rootChildren[i]->GetPriority();
  413. if (priority > maxPriority)
  414. {
  415. maxPriority = priority;
  416. front = rootChildren[i];
  417. }
  418. }
  419. return front;
  420. }
  421. IntVector2 UI::GetCursorPosition() const
  422. {
  423. return cursor_ ? cursor_->GetPosition() : IntVector2::ZERO;
  424. }
  425. bool UI::HasModalElement() const
  426. {
  427. return rootModalElement_->GetNumChildren() > 0;
  428. }
  429. void UI::Initialize()
  430. {
  431. Graphics* graphics = GetSubsystem<Graphics>();
  432. Renderer* renderer = GetSubsystem<Renderer>();
  433. if (!graphics || !graphics->IsInitialized() || !renderer)
  434. return;
  435. PROFILE(InitUI);
  436. graphics_ = graphics;
  437. rootElement_->SetSize(graphics->GetWidth(), graphics->GetHeight());
  438. rootModalElement_->SetSize(rootElement_->GetSize());
  439. noTextureVS_ = renderer->GetVertexShader("Basic_VCol");
  440. diffTextureVS_ = renderer->GetVertexShader("Basic_DiffVCol");
  441. noTexturePS_ = renderer->GetPixelShader("Basic_VCol");
  442. diffTexturePS_ = renderer->GetPixelShader("Basic_DiffVCol");
  443. diffMaskTexturePS_ = renderer->GetPixelShader("Basic_DiffAlphaMaskVCol");
  444. alphaTexturePS_ = renderer->GetPixelShader("Basic_AlphaVCol");
  445. vertexBuffer_ = new VertexBuffer(context_);
  446. initialized_ = true;
  447. SubscribeToEvent(E_POSTUPDATE, HANDLER(UI, HandlePostUpdate));
  448. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  449. LOGINFO("Initialized user interface");
  450. }
  451. void UI::Update(float timeStep, UIElement* element)
  452. {
  453. element->Update(timeStep);
  454. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  455. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin(); i != children.End(); ++i)
  456. Update(timeStep, *i);
  457. }
  458. void UI::Render(const PODVector<UIBatch>& batches, const PODVector<float>& vertexData, unsigned batchStart, unsigned batchSize)
  459. {
  460. // Engine does not render when window is closed or device is lost
  461. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  462. if (vertexData.Empty())
  463. return;
  464. // Update quad geometry into the vertex buffer
  465. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  466. // Resize the vertex buffer if too small or much too large
  467. if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
  468. vertexBuffer_->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  469. vertexBuffer_->SetData(&vertexData[0]);
  470. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  471. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  472. Vector2 offset(-1.0f, 1.0f);
  473. Matrix4 projection(Matrix4::IDENTITY);
  474. projection.m00_ = scale.x_;
  475. projection.m03_ = offset.x_;
  476. projection.m11_ = scale.y_;
  477. projection.m13_ = offset.y_;
  478. projection.m22_ = 1.0f;
  479. projection.m23_ = 0.0f;
  480. projection.m33_ = 1.0f;
  481. graphics_->ClearParameterSources();
  482. graphics_->SetCullMode(CULL_CCW);
  483. graphics_->SetDepthTest(CMP_ALWAYS);
  484. graphics_->SetDepthWrite(false);
  485. graphics_->SetStencilTest(false);
  486. graphics_->ResetRenderTargets();
  487. ShaderVariation* ps = 0;
  488. ShaderVariation* vs = 0;
  489. unsigned alphaFormat = Graphics::GetAlphaFormat();
  490. for (unsigned i = batchStart; i < batchSize; ++i)
  491. {
  492. const UIBatch& batch = batches[i];
  493. if (batch.vertexStart_ == batch.vertexEnd_)
  494. continue;
  495. if (!batch.texture_)
  496. {
  497. ps = noTexturePS_;
  498. vs = noTextureVS_;
  499. }
  500. else
  501. {
  502. // If texture contains only an alpha channel, use alpha shader (for fonts)
  503. vs = diffTextureVS_;
  504. if (batch.texture_->GetFormat() == alphaFormat)
  505. ps = alphaTexturePS_;
  506. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  507. ps = diffMaskTexturePS_;
  508. else
  509. ps = diffTexturePS_;
  510. }
  511. graphics_->SetShaders(vs, ps);
  512. if (graphics_->NeedParameterUpdate(SP_OBJECTTRANSFORM, this))
  513. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  514. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  515. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  516. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  517. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  518. graphics_->SetBlendMode(batch.blendMode_);
  519. graphics_->SetScissorTest(true, batch.scissor_);
  520. graphics_->SetTexture(0, batch.texture_);
  521. graphics_->SetVertexBuffer(vertexBuffer_);
  522. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  523. UI_VERTEX_SIZE);
  524. }
  525. }
  526. void UI::GetBatches(UIElement* element, IntRect currentScissor)
  527. {
  528. // Set clipping scissor for child elements. No need to draw if zero size
  529. element->AdjustScissor(currentScissor);
  530. if (currentScissor.left_ == currentScissor.right_ || currentScissor.top_ == currentScissor.bottom_)
  531. return;
  532. element->SortChildren();
  533. const Vector<SharedPtr<UIElement> >& children = element->GetChildren();
  534. if (children.Empty())
  535. return;
  536. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  537. // same renderstate
  538. Vector<SharedPtr<UIElement> >::ConstIterator i = children.Begin();
  539. if (element->GetTraversalMode() == TM_BREADTH_FIRST)
  540. {
  541. Vector<SharedPtr<UIElement> >::ConstIterator j = i;
  542. while (i != children.End())
  543. {
  544. int currentPriority = (*i)->GetPriority();
  545. while (j != children.End() && (*j)->GetPriority() == currentPriority)
  546. {
  547. if ((*j)->IsWithinScissor(currentScissor))
  548. (*j)->GetBatches(batches_, vertexData_, currentScissor);
  549. ++j;
  550. }
  551. // Now recurse into the children
  552. while (i != j)
  553. {
  554. if ((*i)->IsVisible())
  555. GetBatches(*i, currentScissor);
  556. ++i;
  557. }
  558. }
  559. }
  560. // On the root level draw each element and its children immediately after to avoid artifacts
  561. else
  562. {
  563. while (i != children.End())
  564. {
  565. if ((*i)->IsWithinScissor(currentScissor))
  566. (*i)->GetBatches(batches_, vertexData_, currentScissor);
  567. if ((*i)->IsVisible())
  568. GetBatches(*i, currentScissor);
  569. ++i;
  570. }
  571. }
  572. }
  573. void UI::GetElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  574. {
  575. if (!current)
  576. return;
  577. current->SortChildren();
  578. const Vector<SharedPtr<UIElement> >& children = current->GetChildren();
  579. LayoutMode parentLayoutMode = current->GetLayoutMode();
  580. for (unsigned i = 0; i < children.Size(); ++i)
  581. {
  582. UIElement* element = children[i];
  583. bool hasChildren = element->GetNumChildren() > 0;
  584. if (element != cursor_.Get() && element->IsVisible())
  585. {
  586. if (element->IsInside(position, true))
  587. {
  588. // Store the current result, then recurse into its children. Because children
  589. // are sorted from lowest to highest priority, the topmost match should remain
  590. if (element->IsEnabled() || !enabledOnly)
  591. result = element;
  592. if (hasChildren)
  593. GetElementAt(result, element, position, enabledOnly);
  594. // Layout optimization: if the element has no children, can break out after the first match
  595. else if (parentLayoutMode != LM_FREE)
  596. break;
  597. }
  598. else
  599. {
  600. if (hasChildren)
  601. {
  602. if (element->IsInsideCombined(position, true))
  603. GetElementAt(result, element, position, enabledOnly);
  604. }
  605. // Layout optimization: if position is much beyond the visible screen, check how many elements we can skip,
  606. // or if we already passed all visible elements
  607. else if (parentLayoutMode != LM_FREE)
  608. {
  609. if (!i)
  610. {
  611. int screenPos = (parentLayoutMode == LM_HORIZONTAL) ? element->GetScreenPosition().x_ :
  612. element->GetScreenPosition().y_;
  613. int layoutMinSize = current->GetLayoutMinSize();
  614. if (screenPos < 0 && layoutMinSize > 0)
  615. {
  616. unsigned toSkip = -screenPos / layoutMinSize;
  617. if (toSkip > 0)
  618. i += (toSkip - 1);
  619. }
  620. }
  621. else if (parentLayoutMode == LM_HORIZONTAL)
  622. {
  623. if (element->GetScreenPosition().x_ >= rootElement_->GetSize().x_)
  624. break;
  625. }
  626. else if (parentLayoutMode == LM_VERTICAL)
  627. {
  628. if (element->GetScreenPosition().y_ >= rootElement_->GetSize().y_)
  629. break;
  630. }
  631. }
  632. }
  633. }
  634. }
  635. }
  636. UIElement* UI::GetFocusableElement(UIElement* element)
  637. {
  638. while (element)
  639. {
  640. if (element->GetFocusMode() != FM_NOTFOCUSABLE)
  641. break;
  642. element = element->GetParent();
  643. }
  644. return element;
  645. }
  646. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  647. {
  648. using namespace ScreenMode;
  649. if (!initialized_)
  650. Initialize();
  651. else
  652. {
  653. rootElement_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  654. rootModalElement_->SetSize(rootElement_->GetSize());
  655. }
  656. }
  657. void UI::HandleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  658. {
  659. mouseButtons_ = eventData[MouseButtonDown::P_BUTTONS].GetInt();
  660. qualifiers_ = eventData[MouseButtonDown::P_QUALIFIERS].GetInt();
  661. if (cursor_ && cursor_->IsVisible())
  662. {
  663. int button = eventData[MouseButtonDown::P_BUTTON].GetInt();
  664. IntVector2 pos = cursor_->GetPosition();
  665. WeakPtr<UIElement> element(GetElementAt(pos));
  666. if (element)
  667. {
  668. // Handle focusing & bringing to front
  669. if (button == MOUSEB_LEFT)
  670. {
  671. SetFocusElement(element);
  672. element->BringToFront();
  673. }
  674. // Handle click
  675. element->OnClick(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  676. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  677. if (element && !dragElement_ && mouseButtons_ == MOUSEB_LEFT)
  678. {
  679. dragElement_ = element;
  680. element->OnDragBegin(element->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  681. }
  682. }
  683. else
  684. {
  685. // If clicked over no element, or a disabled element, lose focus
  686. SetFocusElement(0);
  687. }
  688. using namespace UIMouseClick;
  689. VariantMap eventData;
  690. eventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  691. eventData[UIMouseClick::P_X] = pos.x_;
  692. eventData[UIMouseClick::P_Y] = pos.y_;
  693. eventData[UIMouseClick::P_BUTTON] = button;
  694. eventData[UIMouseClick::P_BUTTONS] = mouseButtons_;
  695. eventData[UIMouseClick::P_QUALIFIERS] = qualifiers_;
  696. SendEvent(E_UIMOUSECLICK, eventData);
  697. }
  698. }
  699. void UI::HandleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  700. {
  701. using namespace MouseButtonUp;
  702. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  703. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  704. if (cursor_ && (cursor_->IsVisible() || dragElement_))
  705. {
  706. IntVector2 pos = cursor_->GetPosition();
  707. if (dragElement_ && !mouseButtons_)
  708. {
  709. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  710. {
  711. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  712. // Drag and drop finish
  713. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  714. if (dragSource)
  715. {
  716. WeakPtr<UIElement> target(GetElementAt(pos));
  717. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  718. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  719. if (dragDropFinish)
  720. {
  721. bool accept = target->OnDragDropFinish(dragElement_);
  722. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  723. if (accept && dragElement_ && target)
  724. {
  725. using namespace DragDropFinish;
  726. VariantMap eventData;
  727. eventData[P_SOURCE] = (void*)dragElement_.Get();
  728. eventData[P_TARGET] = (void*)target.Get();
  729. eventData[P_ACCEPT] = accept;
  730. SendEvent(E_DRAGDROPFINISH, eventData);
  731. }
  732. }
  733. }
  734. }
  735. dragElement_.Reset();
  736. }
  737. }
  738. }
  739. void UI::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  740. {
  741. using namespace MouseMove;
  742. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  743. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  744. if (cursor_)
  745. {
  746. Input* input = GetSubsystem<Input>();
  747. const IntVector2& rootSize = rootElement_->GetSize();
  748. if (!input->IsMouseVisible())
  749. {
  750. // Relative mouse motion: move cursor only when visible
  751. if (cursor_->IsVisible())
  752. {
  753. IntVector2 pos = cursor_->GetPosition();
  754. pos.x_ += eventData[P_DX].GetInt();
  755. pos.y_ += eventData[P_DY].GetInt();
  756. pos.x_ = Clamp(pos.x_, 0, rootSize.x_ - 1);
  757. pos.y_ = Clamp(pos.y_, 0, rootSize.y_ - 1);
  758. cursor_->SetPosition(pos);
  759. }
  760. }
  761. else
  762. {
  763. // Absolute mouse motion: move always
  764. cursor_->SetPosition(IntVector2(eventData[P_X].GetInt(), eventData[P_Y].GetInt()));
  765. }
  766. if (dragElement_ && mouseButtons_)
  767. {
  768. IntVector2 pos = cursor_->GetPosition();
  769. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  770. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, mouseButtons_, qualifiers_, cursor_);
  771. else
  772. {
  773. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  774. dragElement_.Reset();
  775. }
  776. }
  777. }
  778. }
  779. void UI::HandleMouseWheel(StringHash eventType, VariantMap& eventData)
  780. {
  781. using namespace MouseWheel;
  782. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  783. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  784. int delta = eventData[P_WHEEL].GetInt();
  785. UIElement* element;
  786. if (!nonFocusedMouseWheel_&& (element = focusElement_))
  787. element->OnWheel(delta, mouseButtons_, qualifiers_);
  788. else
  789. {
  790. // If no element has actual focus or in non-focused mode, get the element at cursor
  791. if (cursor_)
  792. {
  793. IntVector2 pos = cursor_->GetPosition();
  794. element = GetElementAt(pos);
  795. if (nonFocusedMouseWheel_)
  796. {
  797. // Going up the hierarchy chain to find element that could handle mouse wheel
  798. while (element)
  799. {
  800. if (element->GetType() == ListView::GetTypeStatic() ||
  801. element->GetType() == ScrollView::GetTypeStatic())
  802. break;
  803. element = element->GetParent();
  804. }
  805. }
  806. else
  807. // If the element itself is not focusable, search for a focusable parent,
  808. // although the focusable element may not actually handle mouse wheel
  809. element = GetFocusableElement(element);
  810. if (element && (nonFocusedMouseWheel_ || element->GetFocusMode() >= FM_FOCUSABLE))
  811. element->OnWheel(delta, mouseButtons_, qualifiers_);
  812. }
  813. }
  814. }
  815. void UI::HandleTouchBegin(StringHash eventType, VariantMap& eventData)
  816. {
  817. using namespace TouchBegin;
  818. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  819. WeakPtr<UIElement> element(GetElementAt(pos));
  820. if (element)
  821. {
  822. // Handle focusing & bringing to front
  823. SetFocusElement(element);
  824. element->BringToFront();
  825. // Handle click
  826. element->OnClick(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  827. // Handle start of drag. OnClick() may have caused destruction of the element, so check the pointer again
  828. if (element && !dragElement_ )
  829. {
  830. dragElement_ = element;
  831. element->OnDragBegin(element->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  832. }
  833. }
  834. else
  835. {
  836. // If clicked over no element, or a disabled element, lose focus
  837. SetFocusElement(0);
  838. }
  839. using namespace UIMouseClick;
  840. VariantMap clickEventData;
  841. clickEventData[UIMouseClick::P_ELEMENT] = (void*)element.Get();
  842. clickEventData[UIMouseClick::P_X] = pos.x_;
  843. clickEventData[UIMouseClick::P_Y] = pos.y_;
  844. clickEventData[UIMouseClick::P_BUTTON] = MOUSEB_LEFT;
  845. clickEventData[UIMouseClick::P_BUTTONS] = MOUSEB_LEFT;
  846. clickEventData[UIMouseClick::P_QUALIFIERS] = 0;
  847. SendEvent(E_UIMOUSECLICK, clickEventData);
  848. }
  849. void UI::HandleTouchEnd(StringHash eventType, VariantMap& eventData)
  850. {
  851. using namespace TouchEnd;
  852. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  853. // Transmit hover end to the position where the finger was lifted
  854. UIElement* element = GetElementAt(pos);
  855. if (element && element->IsEnabled())
  856. element->OnHover(element->ScreenToElement(pos), pos, 0, 0, 0);
  857. if (dragElement_)
  858. {
  859. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  860. {
  861. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, cursor_);
  862. // Drag and drop finish
  863. bool dragSource = dragElement_ && (dragElement_->GetDragDropMode() & DD_SOURCE) != 0;
  864. if (dragSource)
  865. {
  866. WeakPtr<UIElement> target(GetElementAt(pos));
  867. bool dragTarget = target && (target->GetDragDropMode() & DD_TARGET) != 0;
  868. bool dragDropFinish = dragSource && dragTarget && target != dragElement_;
  869. if (dragDropFinish)
  870. {
  871. bool accept = target->OnDragDropFinish(dragElement_);
  872. // OnDragDropFinish() may have caused destruction of the elements, so check the pointers again
  873. if (accept && dragElement_ && target)
  874. {
  875. using namespace DragDropFinish;
  876. VariantMap eventData;
  877. eventData[P_SOURCE] = (void*)dragElement_.Get();
  878. eventData[P_TARGET] = (void*)target.Get();
  879. eventData[P_ACCEPT] = accept;
  880. SendEvent(E_DRAGDROPFINISH, eventData);
  881. }
  882. }
  883. }
  884. }
  885. dragElement_.Reset();
  886. }
  887. }
  888. void UI::HandleTouchMove(StringHash eventType, VariantMap& eventData)
  889. {
  890. using namespace TouchMove;
  891. IntVector2 pos(eventData[P_X].GetInt(), eventData[P_Y].GetInt());
  892. if (dragElement_)
  893. {
  894. if (dragElement_->IsEnabled() && dragElement_->IsVisible())
  895. dragElement_->OnDragMove(dragElement_->ScreenToElement(pos), pos, MOUSEB_LEFT, 0, 0);
  896. else
  897. {
  898. dragElement_->OnDragEnd(dragElement_->ScreenToElement(pos), pos, 0);
  899. dragElement_.Reset();
  900. }
  901. }
  902. }
  903. void UI::HandleKeyDown(StringHash eventType, VariantMap& eventData)
  904. {
  905. using namespace KeyDown;
  906. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  907. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  908. int key = eventData[P_KEY].GetInt();
  909. // Dismiss modal element if any when ESC key is pressed
  910. if (key == KEY_ESC && HasModalElement())
  911. {
  912. UIElement* element = rootModalElement_->GetChild(rootModalElement_->GetNumChildren() - 1);
  913. if (element->GetVars().Contains(VAR_ORIGIN))
  914. // If it is a popup, dismiss by defocusing it
  915. SetFocusElement(0);
  916. else
  917. {
  918. // If it is a modal window, by resetting its modal flag and auto-remove it
  919. Window* window = dynamic_cast<Window*>(element);
  920. if (window)
  921. {
  922. window->SetModal(false);
  923. window->Remove();
  924. }
  925. }
  926. return;
  927. }
  928. UIElement* element = focusElement_;
  929. if (element)
  930. {
  931. // Switch focus between focusable elements in the same top level window
  932. if (key == KEY_TAB)
  933. {
  934. UIElement* topLevel = element->GetParent();
  935. while (topLevel && topLevel->GetParent() != rootElement_ && topLevel->GetParent() != rootModalElement_)
  936. topLevel = topLevel->GetParent();
  937. if (topLevel)
  938. {
  939. topLevel->GetChildren(tempElements_, true);
  940. for (PODVector<UIElement*>::Iterator i = tempElements_.Begin(); i != tempElements_.End();)
  941. {
  942. if ((*i)->GetFocusMode() < FM_FOCUSABLE)
  943. i = tempElements_.Erase(i);
  944. else
  945. ++i;
  946. }
  947. for (unsigned i = 0; i < tempElements_.Size(); ++i)
  948. {
  949. if (tempElements_[i] == element)
  950. {
  951. UIElement* next = tempElements_[(i + 1) % tempElements_.Size()];
  952. SetFocusElement(next);
  953. return;
  954. }
  955. }
  956. }
  957. }
  958. // Defocus the element
  959. else if (key == KEY_ESC && element->GetFocusMode() == FM_FOCUSABLE_DEFOCUSABLE)
  960. element->SetFocus(false);
  961. // If none of the special keys, pass the key to the focused element
  962. else
  963. element->OnKey(key, mouseButtons_, qualifiers_);
  964. }
  965. }
  966. void UI::HandleChar(StringHash eventType, VariantMap& eventData)
  967. {
  968. using namespace Char;
  969. mouseButtons_ = eventData[P_BUTTONS].GetInt();
  970. qualifiers_ = eventData[P_QUALIFIERS].GetInt();
  971. UIElement* element = focusElement_;
  972. if (element)
  973. element->OnChar(eventData[P_CHAR].GetInt(), mouseButtons_, qualifiers_);
  974. }
  975. void UI::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
  976. {
  977. using namespace PostUpdate;
  978. Update(eventData[P_TIMESTEP].GetFloat());
  979. }
  980. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  981. {
  982. RenderUpdate();
  983. }
  984. void RegisterUILibrary(Context* context)
  985. {
  986. Font::RegisterObject(context);
  987. UIElement::RegisterObject(context);
  988. BorderImage::RegisterObject(context);
  989. Sprite::RegisterObject(context);
  990. Button::RegisterObject(context);
  991. CheckBox::RegisterObject(context);
  992. Cursor::RegisterObject(context);
  993. Text::RegisterObject(context);
  994. Window::RegisterObject(context);
  995. LineEdit::RegisterObject(context);
  996. Slider::RegisterObject(context);
  997. ScrollBar::RegisterObject(context);
  998. ScrollView::RegisterObject(context);
  999. ListView::RegisterObject(context);
  1000. Menu::RegisterObject(context);
  1001. DropDownList::RegisterObject(context);
  1002. FileSelector::RegisterObject(context);
  1003. }
  1004. }