UI.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "BaseUIElementFactory.h"
  25. #include "Cursor.h"
  26. #include "Font.h"
  27. #include "InputEvents.h"
  28. #include "Log.h"
  29. #include "Matrix4.h"
  30. #include "PixelShader.h"
  31. #include "Profiler.h"
  32. #include "Renderer.h"
  33. #include "RendererEvents.h"
  34. #include "RendererImpl.h"
  35. #include "ResourceCache.h"
  36. #include "StringUtils.h"
  37. #include "Texture2D.h"
  38. #include "UI.h"
  39. #include "UIEvents.h"
  40. #include "VertexShader.h"
  41. #include <algorithm>
  42. #include "DebugNew.h"
  43. static bool compareUIElements(const UIElement* lhs, const UIElement* rhs)
  44. {
  45. return lhs->getPriority() < rhs->getPriority();
  46. }
  47. UI::UI(Renderer* renderer, ResourceCache* cache) :
  48. mRenderer(renderer),
  49. mCache(cache),
  50. mMouseDrag(false),
  51. mMouseDragElement(0),
  52. mDefocusElement(0),
  53. mMouseButtons(0),
  54. mQualifiers(0)
  55. {
  56. if (!mRenderer)
  57. EXCEPTION("Null renderer for UI");
  58. if (!mCache)
  59. EXCEPTION("Null resource cache for UI");
  60. LOGINFO("UI created");
  61. mRootElement = new UIElement();
  62. mRootElement->setSize(mRenderer->getWidth(), mRenderer->getHeight());
  63. subscribeToEvent(EVENT_WINDOWRESIZED, EVENT_HANDLER(UI, handleWindowResized));
  64. subscribeToEvent(EVENT_MOUSEMOVE, EVENT_HANDLER(UI, handleMouseMove));
  65. subscribeToEvent(EVENT_MOUSEBUTTONDOWN, EVENT_HANDLER(UI, handleMouseButtonDown));
  66. subscribeToEvent(EVENT_MOUSEBUTTONUP, EVENT_HANDLER(UI, handleMouseButtonUp));
  67. subscribeToEvent(EVENT_KEYDOWN, EVENT_HANDLER(UI, handleKeyDown));
  68. subscribeToEvent(EVENT_CHAR, EVENT_HANDLER(UI, handleChar));
  69. mNoTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_VCol.vs2");
  70. mDiffTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_DiffVCol.vs2");
  71. mNoTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_VCol.ps2");
  72. mDiffTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_DiffVCol.ps2");
  73. mAlphaTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_AlphaVCol.ps2");
  74. // Add the base element factory
  75. addElementFactory(new BaseUIElementFactory());
  76. }
  77. UI::~UI()
  78. {
  79. LOGINFO("UI shut down");
  80. }
  81. void UI::setCursor(Cursor* cursor)
  82. {
  83. // Remove old cursor (if any) and set new
  84. if (mCursor)
  85. {
  86. mRootElement->removeChild(mCursor);
  87. mCursor.reset();
  88. }
  89. if (cursor)
  90. {
  91. mRootElement->addChild(cursor);
  92. mCursor = cursor;
  93. IntVector2 pos = mCursor->getPosition();
  94. const IntVector2& rootSize = mRootElement->getSize();
  95. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  96. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  97. mCursor->setPosition(pos);
  98. }
  99. }
  100. void UI::setFocusElement(UIElement* element)
  101. {
  102. using namespace TryFocus;
  103. VariantMap eventData;
  104. eventData[P_ELEMENT] = (void*)element;
  105. sendEvent(EVENT_TRYFOCUS, eventData);
  106. // The event receivers may divert the focus
  107. element = static_cast<UIElement*>(eventData[P_ELEMENT].getPtr());
  108. if (element)
  109. {
  110. // Return if already has focus
  111. if (element->hasFocus())
  112. return;
  113. // If element can not be focused, and does not reset the focus either, search toward the parent
  114. for (;;)
  115. {
  116. if (element->getFocusMode() != FM_NOTFOCUSABLE)
  117. break;
  118. element = element->getParent();
  119. // Return if did not find any parent element that changes the focus
  120. if (!element)
  121. return;
  122. }
  123. }
  124. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  125. // Go through all elements to clear the old focus
  126. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  127. {
  128. UIElement* other = *i;
  129. if ((other != element) && (other->hasFocus()))
  130. other->setFocus(false);
  131. }
  132. if (element)
  133. element->setFocus(true);
  134. }
  135. void UI::clear()
  136. {
  137. mRootElement->removeAllChildren();
  138. if (mCursor)
  139. mRootElement->addChild(mCursor);
  140. }
  141. void UI::update(float timeStep)
  142. {
  143. PROFILE(UI_Update);
  144. // If device lost, do not perform update
  145. if (mRenderer->isDeviceLost())
  146. return;
  147. if ((mCursor) && (mCursor->isVisible()))
  148. {
  149. IntVector2 pos = mCursor->getPosition();
  150. UIElement* element = getElementAt(pos);
  151. if (element)
  152. {
  153. // If a drag is going on, transmit hover only to the element being dragged
  154. if ((!mMouseDragElement) || (mMouseDragElement == element))
  155. element->onHover(element->screenToElement(pos), pos, mMouseButtons, mQualifiers);
  156. }
  157. }
  158. // Defocus element now if should
  159. if (mDefocusElement)
  160. {
  161. // Do nothing if the focus element changed in the meanwhile
  162. if (mDefocusElement == getFocusElement())
  163. setFocusElement(0);
  164. mDefocusElement = 0;
  165. }
  166. {
  167. PROFILE(UI_UpdateElements);
  168. update(timeStep, mRootElement);
  169. }
  170. {
  171. PROFILE(UI_GetBatches);
  172. mBatches.clear();
  173. mQuads.clear();
  174. const IntVector2& rootSize = mRootElement->getSize();
  175. getBatches(mRootElement, IntRect(0, 0, rootSize.mX, rootSize.mY));
  176. }
  177. }
  178. void UI::render()
  179. {
  180. PROFILE(UI_Render);
  181. static const Vector2 scale(2.0f, -2.0f);
  182. static const Vector2 offset(-1.0f, 1.0f);
  183. Matrix4 projection;
  184. memset(&projection, 0, sizeof(projection));
  185. projection.m00 = scale.mX;
  186. projection.m03 = offset.mX;
  187. projection.m11 = scale.mY;
  188. projection.m13 = offset.mY;
  189. projection.m22 = 1.0f;
  190. projection.m23 = 0.0f;
  191. projection.m33 = 1.0f;
  192. mRenderer->resetRenderTargets();
  193. mRenderer->setCullMode(CULL_CCW);
  194. mRenderer->setDepthTest(CMP_ALWAYS);
  195. mRenderer->setDepthWrite(false);
  196. mRenderer->setFillMode(FILL_SOLID);
  197. mRenderer->setStencilTest(false);
  198. mRenderer->setVertexShaderConstant(getVSRegister(VSP_MODELVIEWPROJ), projection);
  199. mRenderer->setPixelShaderConstant(getPSRegister(PSP_MATDIFFCOLOR), Color(1.0f, 1.0f, 1.0f, 1.0f));
  200. PixelShader* ps = 0;
  201. VertexShader* vs = 0;
  202. for (unsigned i = 0; i < mBatches.size(); ++i)
  203. {
  204. // Choose shaders here so that UIBatch does not need to look up shaders each time
  205. if (!mBatches[i].mTexture)
  206. {
  207. ps = mNoTexturePS;
  208. vs = mNoTextureVS;
  209. }
  210. else
  211. {
  212. // If texture contains only an alpha channel, use the alpha pixel shader
  213. vs = mDiffTextureVS;
  214. if (mBatches[i].mTexture->getFormat() == D3DFMT_A8)
  215. ps = mAlphaTexturePS;
  216. else
  217. ps = mDiffTexturePS;
  218. }
  219. mBatches[i].draw(mRenderer, vs, ps);
  220. }
  221. }
  222. void UI::addElementFactory(UIElementFactory* factory)
  223. {
  224. if (!factory)
  225. return;
  226. mFactories.push_back(SharedPtr<UIElementFactory>(factory));
  227. }
  228. SharedPtr<UIElement> UI::createElement(ShortStringHash type, const std::string& name)
  229. {
  230. SharedPtr<UIElement> element;
  231. for (unsigned i = 0; i < mFactories.size(); ++i)
  232. {
  233. element = mFactories[i]->createElement(type, name);
  234. if (element)
  235. return element;
  236. }
  237. EXCEPTION("Could not create unknown UI element type " + toString(type));
  238. }
  239. SharedPtr<UIElement> UI::loadLayout(XMLFile* file, XMLFile* styleFile)
  240. {
  241. PROFILE(UI_LoadLayout);
  242. SharedPtr<UIElement> root;
  243. if (!file)
  244. {
  245. LOGERROR("Null UI layout XML file");
  246. return root;
  247. }
  248. LOGDEBUG("Loading UI layout " + file->getName());
  249. XMLElement rootElem = file->getRootElement("element");
  250. if (!rootElem)
  251. {
  252. LOGERROR("No root UI element in " + file->getName());
  253. return root;
  254. }
  255. root = createElement(ShortStringHash(rootElem.getString("type")), rootElem.getString("name"));
  256. // First set the base style from the style file if exists, then apply UI layout overrides
  257. if (styleFile)
  258. root->setStyleAuto(styleFile, mCache);
  259. root->setStyle(rootElem, mCache);
  260. // Load rest of the elements recursively
  261. loadLayout(root, rootElem, styleFile);
  262. return root;
  263. }
  264. UIElement* UI::getElementAt(const IntVector2& position, bool enabledOnly)
  265. {
  266. UIElement* result = 0;
  267. getElementAt(result, mRootElement, position, enabledOnly);
  268. return result;
  269. }
  270. UIElement* UI::getElementAt(int x, int y, bool enabledOnly)
  271. {
  272. UIElement* result = 0;
  273. getElementAt(result, mRootElement, IntVector2(x, y), enabledOnly);
  274. return result;
  275. }
  276. UIElement* UI::getFocusElement()
  277. {
  278. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  279. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  280. {
  281. if ((*i)->hasFocus())
  282. return *i;
  283. }
  284. return 0;
  285. }
  286. IntVector2 UI::getCursorPosition()
  287. {
  288. if (!mCursor)
  289. return IntVector2::sZero;
  290. else
  291. return mCursor->getPosition();
  292. }
  293. void UI::update(float timeStep, UIElement* element)
  294. {
  295. element->update(timeStep);
  296. const std::vector<UIElement*> children = element->getChildren();
  297. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  298. update(timeStep, *i);
  299. }
  300. void UI::getBatches(UIElement* element, IntRect currentScissor)
  301. {
  302. // Set clipping scissor for child elements. No need to draw if zero size
  303. element->adjustScissor(currentScissor);
  304. if ((currentScissor.mLeft == currentScissor.mRight) || (currentScissor.mTop == currentScissor.mBottom))
  305. return;
  306. std::vector<UIElement*> children = element->getChildren();
  307. if (children.empty())
  308. return;
  309. std::sort(children.begin(), children.end(), compareUIElements);
  310. // For non-root elements draw all children of same priority before recursing into their children: assumption is that they have
  311. // same renderstate
  312. std::vector<UIElement*>::const_iterator i = children.begin();
  313. if (element != mRootElement)
  314. {
  315. std::vector<UIElement*>::const_iterator j = i;
  316. int currentPriority = children.front()->getPriority();
  317. while (i != children.end())
  318. {
  319. while ((j != children.end()) && ((*j)->getPriority() == currentPriority))
  320. {
  321. if ((*j)->isVisible())
  322. (*j)->getBatches(mBatches, mQuads, currentScissor);
  323. ++j;
  324. }
  325. // Now recurse into the children
  326. while (i != j)
  327. {
  328. if ((*i)->isVisible())
  329. getBatches(*i, currentScissor);
  330. ++i;
  331. }
  332. if (i != children.end())
  333. currentPriority = (*i)->getPriority();
  334. }
  335. }
  336. // On the root level draw each element and its children immediately after to avoid artifacts
  337. else
  338. {
  339. while (i != children.end())
  340. {
  341. if ((*i)->isVisible())
  342. {
  343. (*i)->getBatches(mBatches, mQuads, currentScissor);
  344. getBatches(*i, currentScissor);
  345. }
  346. ++i;
  347. }
  348. }
  349. }
  350. void UI::getElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  351. {
  352. if (!current)
  353. return;
  354. // Get children from lowest priority to highest
  355. std::vector<UIElement*> children = current->getChildren(false);
  356. std::sort(children.begin(), children.end(), compareUIElements);
  357. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  358. {
  359. UIElement* element = *i;
  360. if ((element != mCursor.getPtr()) && (element->isVisible()))
  361. {
  362. if (element->isInside(position, true))
  363. {
  364. // Store the current result, then recurse into its children. Because children
  365. // are sorted from lowest to highest priority, we should be left with the topmost match
  366. if ((element->isEnabled()) || (!enabledOnly))
  367. result = element;
  368. }
  369. if (element->isInsideCombined(position, true))
  370. getElementAt(result, element, position, enabledOnly);
  371. }
  372. }
  373. }
  374. UIElement* UI::verifyElement(UIElement* element)
  375. {
  376. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  377. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  378. {
  379. if ((*i) == element)
  380. return *i;
  381. }
  382. return 0;
  383. }
  384. void UI::handleWindowResized(StringHash eventType, VariantMap& eventData)
  385. {
  386. using namespace WindowResized;
  387. mRootElement->setSize(eventData[P_WIDTH].getInt(), eventData[P_HEIGHT].getInt());
  388. }
  389. void UI::handleMouseMove(StringHash eventType, VariantMap& eventData)
  390. {
  391. using namespace MouseMove;
  392. mMouseButtons = eventData[P_BUTTONS].getInt();
  393. mQualifiers = eventData[P_QUALIFIERS].getInt();
  394. if ((mCursor) && (mCursor->isVisible()))
  395. {
  396. IntVector2 pos = mCursor->getPosition();
  397. pos.mX += eventData[P_X].getInt();
  398. pos.mY += eventData[P_Y].getInt();
  399. const IntVector2& rootSize = mRootElement->getSize();
  400. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  401. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  402. mCursor->setPosition(pos);
  403. if ((mMouseDrag) && (mMouseButtons))
  404. {
  405. UIElement* element = verifyElement(mMouseDragElement);
  406. if ((element) && (element->isEnabled()) && (element->isVisible()))
  407. element->onDragMove(element->screenToElement(pos), pos, mMouseButtons, mQualifiers);
  408. else
  409. {
  410. mMouseDrag = false;
  411. mMouseDragElement = 0;
  412. }
  413. }
  414. }
  415. }
  416. void UI::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  417. {
  418. using namespace MouseButtonDown;
  419. mMouseButtons = eventData[P_BUTTONS].getInt();
  420. mQualifiers = eventData[P_QUALIFIERS].getInt();
  421. int button = eventData[P_BUTTON].getInt();
  422. if ((mCursor) && (mCursor->isVisible()))
  423. {
  424. IntVector2 pos = mCursor->getPosition();
  425. UIElement* element = getElementAt(pos);
  426. if (element)
  427. {
  428. // Handle focusing & bringing to front
  429. if (button == MOUSEB_LEFT)
  430. {
  431. setFocusElement(element);
  432. element->bringToFront();
  433. }
  434. // Handle click
  435. element->onClick(element->screenToElement(pos), pos, mMouseButtons, mQualifiers);
  436. // Handle start of drag
  437. if (!mMouseDrag)
  438. {
  439. mMouseDrag = true;
  440. mMouseDragElement = element;
  441. element->onDragStart(element->screenToElement(pos), pos, mMouseButtons, mQualifiers);
  442. }
  443. }
  444. else
  445. {
  446. // If clicked over no element, or a disabled element, lose focus
  447. setFocusElement(0);
  448. }
  449. }
  450. }
  451. void UI::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  452. {
  453. using namespace MouseButtonUp;
  454. mMouseButtons = eventData[P_BUTTONS].getInt();
  455. mQualifiers = eventData[P_QUALIFIERS].getInt();
  456. if ((mCursor) && (mCursor->isVisible()))
  457. {
  458. IntVector2 pos = mCursor->getPosition();
  459. if ((mMouseDrag) && (!mMouseButtons))
  460. {
  461. UIElement* element = verifyElement(mMouseDragElement);
  462. if ((element) && (element->isEnabled()) && (element->isVisible()))
  463. element->onDragEnd(element->screenToElement(pos), pos);
  464. mMouseDrag = false;
  465. mMouseDragElement = 0;
  466. }
  467. }
  468. }
  469. void UI::handleKeyDown(StringHash eventType, VariantMap& eventData)
  470. {
  471. using namespace KeyDown;
  472. mMouseButtons = eventData[P_BUTTONS].getInt();
  473. mQualifiers = eventData[P_QUALIFIERS].getInt();
  474. int key = eventData[P_KEY].getInt();
  475. UIElement* element = getFocusElement();
  476. if (element)
  477. {
  478. // Switch focus between focusable sibling elements
  479. if (key == KEY_TAB)
  480. {
  481. UIElement* parent = element->getParent();
  482. if (parent)
  483. {
  484. std::vector<UIElement*> children = parent->getChildren();
  485. for (std::vector<UIElement*>::iterator i = children.begin(); i != children.end();)
  486. {
  487. if ((*i)->getFocusMode() < FM_FOCUSABLE)
  488. i = children.erase(i);
  489. else
  490. ++i;
  491. }
  492. for (unsigned i = 0; i < children.size(); ++i)
  493. {
  494. if (children[i] == element)
  495. {
  496. UIElement* next = children[(i + 1) % children.size()];
  497. setFocusElement(next);
  498. return;
  499. }
  500. }
  501. }
  502. }
  503. // Defocus the element
  504. else if ((key == KEY_ESC) && (element->getFocusMode() == FM_FOCUSABLE_DEFOCUSABLE))
  505. mDefocusElement = element;
  506. // If none of the special keys, pass the key to the focused element
  507. else
  508. element->onKey(key, mMouseButtons, mQualifiers);
  509. }
  510. }
  511. void UI::handleChar(StringHash eventType, VariantMap& eventData)
  512. {
  513. using namespace Char;
  514. mMouseButtons = eventData[P_BUTTONS].getInt();
  515. mQualifiers = eventData[P_QUALIFIERS].getInt();
  516. UIElement* element = getFocusElement();
  517. if (element)
  518. element->onChar(eventData[P_CHAR].getInt(), mMouseButtons, mQualifiers);
  519. }
  520. void UI::loadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  521. {
  522. XMLElement childElem = elem.getChildElement("element");
  523. while (childElem)
  524. {
  525. // Create and add to the hierarchy
  526. SharedPtr<UIElement> child = createElement(ShortStringHash(childElem.getString("type")), childElem.getString("name"));
  527. current->addChild(child);
  528. // First set the base style from the style file if exists, then apply UI layout overrides
  529. if (styleFile)
  530. child->setStyleAuto(styleFile, mCache);
  531. child->setStyle(childElem, mCache);
  532. // Load the children recursively
  533. loadLayout(child, childElem, styleFile);
  534. childElem = childElem.getNextElement("element");
  535. }
  536. }