UI.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. mMouseButtons(0)
  53. {
  54. if (!mRenderer)
  55. EXCEPTION("Null renderer for UI");
  56. if (!mCache)
  57. EXCEPTION("Null resource cache for UI");
  58. LOGINFO("UI created");
  59. mRootElement = new UIElement();
  60. mRootElement->setSize(mRenderer->getWidth(), mRenderer->getHeight());
  61. subscribeToEvent(EVENT_WINDOWRESIZED, EVENT_HANDLER(UI, handleWindowResized));
  62. subscribeToEvent(EVENT_MOUSEMOVE, EVENT_HANDLER(UI, handleMouseMove));
  63. subscribeToEvent(EVENT_MOUSEBUTTONDOWN, EVENT_HANDLER(UI, handleMouseButtonDown));
  64. subscribeToEvent(EVENT_MOUSEBUTTONUP, EVENT_HANDLER(UI, handleMouseButtonUp));
  65. subscribeToEvent(EVENT_CHAR, EVENT_HANDLER(UI, handleChar));
  66. mNoTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_VCol.vs2");
  67. mDiffTextureVS = mCache->getResource<VertexShader>("Shaders/SM2/Basic_DiffVCol.vs2");
  68. mNoTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_VCol.ps2");
  69. mDiffTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_DiffVCol.ps2");
  70. mAlphaTexturePS = mCache->getResource<PixelShader>("Shaders/SM2/Basic_AlphaVCol.ps2");
  71. // Add the base element factory
  72. addElementFactory(new BaseUIElementFactory());
  73. }
  74. UI::~UI()
  75. {
  76. LOGINFO("UI shut down");
  77. }
  78. void UI::setCursor(Cursor* cursor)
  79. {
  80. // Remove old cursor (if any) and set new
  81. if (mCursor)
  82. {
  83. mRootElement->removeChild(mCursor);
  84. mCursor.reset();
  85. }
  86. if (cursor)
  87. {
  88. mRootElement->addChild(cursor);
  89. mCursor = cursor;
  90. IntVector2 pos = mCursor->getPosition();
  91. const IntVector2& rootSize = mRootElement->getSize();
  92. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  93. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  94. mCursor->setPosition(pos);
  95. }
  96. }
  97. void UI::setFocusElement(UIElement* element)
  98. {
  99. using namespace TryFocus;
  100. VariantMap eventData;
  101. eventData[P_ELEMENT] = (void*)element;
  102. sendEvent(EVENT_TRYFOCUS, eventData);
  103. if (element)
  104. {
  105. if ((element->hasFocus()) || (!element->isFocusable()))
  106. return;
  107. }
  108. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  109. // Go through all elements to clear the old focus
  110. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  111. {
  112. UIElement* other = *i;
  113. if ((other != element) && (other->hasFocus()))
  114. other->setFocus(false);
  115. }
  116. if (element)
  117. element->setFocus(true);
  118. }
  119. void UI::clear()
  120. {
  121. mRootElement->removeAllChildren();
  122. if (mCursor)
  123. mRootElement->addChild(mCursor);
  124. }
  125. void UI::update(float timeStep)
  126. {
  127. PROFILE(UI_Update);
  128. // If device lost, do not perform update
  129. if (mRenderer->isDeviceLost())
  130. return;
  131. if ((mCursor) && (mCursor->isVisible()))
  132. {
  133. IntVector2 pos = mCursor->getPosition();
  134. UIElement* element = getElementAt(pos);
  135. if (element)
  136. {
  137. // If a drag is going on, transmit hover only to the element being dragged
  138. if ((!mMouseDragElement) || (mMouseDragElement == element))
  139. element->onHover(element->screenToElement(pos), pos, mMouseButtons);
  140. }
  141. }
  142. {
  143. PROFILE(UI_UpdateElements);
  144. update(timeStep, mRootElement);
  145. }
  146. {
  147. PROFILE(UI_GetBatches);
  148. mBatches.clear();
  149. mQuads.clear();
  150. const IntVector2& rootSize = mRootElement->getSize();
  151. getBatches(mRootElement, IntRect(0, 0, rootSize.mX, rootSize.mY));
  152. }
  153. }
  154. void UI::render()
  155. {
  156. PROFILE(UI_Render);
  157. static const Vector2 scale(2.0f, -2.0f);
  158. static const Vector2 offset(-1.0f, 1.0f);
  159. Matrix4 projection;
  160. memset(&projection, 0, sizeof(projection));
  161. projection.m00 = scale.mX;
  162. projection.m03 = offset.mX;
  163. projection.m11 = scale.mY;
  164. projection.m13 = offset.mY;
  165. projection.m22 = 1.0f;
  166. projection.m23 = 0.0f;
  167. projection.m33 = 1.0f;
  168. mRenderer->resetRenderTargets();
  169. mRenderer->setCullMode(CULL_CCW);
  170. mRenderer->setDepthTest(CMP_ALWAYS);
  171. mRenderer->setDepthWrite(false);
  172. mRenderer->setFillMode(FILL_SOLID);
  173. mRenderer->setStencilTest(false);
  174. mRenderer->setVertexShaderConstant(getVSRegister(VSP_MODELVIEWPROJ), projection);
  175. mRenderer->setPixelShaderConstant(getPSRegister(PSP_MATDIFFCOLOR), Color(1.0f, 1.0f, 1.0f, 1.0f));
  176. PixelShader* ps = 0;
  177. VertexShader* vs = 0;
  178. for (unsigned i = 0; i < mBatches.size(); ++i)
  179. {
  180. // Choose shaders here so that UIBatch does not need to look up shaders each time
  181. if (!mBatches[i].mTexture)
  182. {
  183. ps = mNoTexturePS;
  184. vs = mNoTextureVS;
  185. }
  186. else
  187. {
  188. // If texture contains only an alpha channel, use the alpha pixel shader
  189. vs = mDiffTextureVS;
  190. if (mBatches[i].mTexture->getFormat() == D3DFMT_A8)
  191. ps = mAlphaTexturePS;
  192. else
  193. ps = mDiffTexturePS;
  194. }
  195. mBatches[i].draw(mRenderer, vs, ps);
  196. }
  197. }
  198. void UI::addElementFactory(UIElementFactory* factory)
  199. {
  200. if (!factory)
  201. return;
  202. mFactories.push_back(SharedPtr<UIElementFactory>(factory));
  203. }
  204. SharedPtr<UIElement> UI::createElement(ShortStringHash type, const std::string& name)
  205. {
  206. SharedPtr<UIElement> element;
  207. for (unsigned i = 0; i < mFactories.size(); ++i)
  208. {
  209. element = mFactories[i]->createElement(type, name);
  210. if (element)
  211. return element;
  212. }
  213. EXCEPTION("Could not create unknown UI element type " + toString(type));
  214. }
  215. SharedPtr<UIElement> UI::loadLayout(XMLFile* file, XMLFile* styleFile)
  216. {
  217. PROFILE(UI_LoadLayout);
  218. SharedPtr<UIElement> root;
  219. if (!file)
  220. {
  221. LOGERROR("Null UI layout XML file");
  222. return root;
  223. }
  224. LOGDEBUG("Loading UI layout " + file->getName());
  225. XMLElement rootElem = file->getRootElement();
  226. XMLElement childElem = rootElem.getChildElement("element");
  227. if (!childElem)
  228. {
  229. LOGERROR("No root UI element in " + file->getName());
  230. return root;
  231. }
  232. root = createElement(ShortStringHash(childElem.getString("type")), childElem.getString("name"));
  233. // First set the base style from the style file if exists, then apply UI layout overrides
  234. if (styleFile)
  235. root->setStyleAuto(styleFile, mCache);
  236. root->setStyle(childElem, mCache);
  237. // Load rest of the elements recursively
  238. loadLayout(root, childElem, styleFile);
  239. if (childElem.getNextElement("element"))
  240. LOGWARNING("Ignored additional root UI elements in " + file->getName());
  241. return root;
  242. }
  243. UIElement* UI::getElementAt(const IntVector2& position, bool enabledOnly)
  244. {
  245. UIElement* result = 0;
  246. getElementAt(result, mRootElement, position, enabledOnly);
  247. return result;
  248. }
  249. UIElement* UI::getElementAt(int x, int y, bool enabledOnly)
  250. {
  251. UIElement* result = 0;
  252. getElementAt(result, mRootElement, IntVector2(x, y), enabledOnly);
  253. return result;
  254. }
  255. UIElement* UI::getFocusElement()
  256. {
  257. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  258. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  259. {
  260. if ((*i)->hasFocus())
  261. return *i;
  262. }
  263. return 0;
  264. }
  265. IntVector2 UI::getCursorPosition()
  266. {
  267. if (!mCursor)
  268. return IntVector2::sZero;
  269. else
  270. return mCursor->getPosition();
  271. }
  272. void UI::update(float timeStep, UIElement* element)
  273. {
  274. element->update(timeStep);
  275. const std::vector<UIElement*> children = element->getChildren();
  276. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  277. update(timeStep, *i);
  278. }
  279. void UI::getBatches(UIElement* element, IntRect currentScissor)
  280. {
  281. // If hidden, do not draw this element or its children
  282. if (!element->isVisible())
  283. return;
  284. element->getBatches(mBatches, mQuads, currentScissor);
  285. // Set clipping scissor for child elements, then get child element batches in low-to-high priority order
  286. element->adjustScissor(currentScissor);
  287. std::vector<UIElement*> children = element->getChildren();
  288. std::sort(children.begin(), children.end(), compareUIElements);
  289. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  290. getBatches(*i, currentScissor);
  291. }
  292. void UI::getElementAt(UIElement*& result, UIElement* current, const IntVector2& position, bool enabledOnly)
  293. {
  294. if (!current)
  295. return;
  296. // Get children from lowest priority to highest
  297. std::vector<UIElement*> children = current->getChildren(false);
  298. std::sort(children.begin(), children.end(), compareUIElements);
  299. for (std::vector<UIElement*>::const_iterator i = children.begin(); i != children.end(); ++i)
  300. {
  301. UIElement* element = *i;
  302. if ((element != mCursor.getPtr()) && (element->isVisible()))
  303. {
  304. if (element->isInside(position, true))
  305. {
  306. // Store the current result, then recurse into its children. Because children
  307. // are sorted from lowest to highest priority, we should be left with the topmost match
  308. if ((element->isEnabled()) || (!enabledOnly))
  309. result = element;
  310. }
  311. if (element->isInsideCombined(position, true))
  312. getElementAt(result, element, position, enabledOnly);
  313. }
  314. }
  315. }
  316. UIElement* UI::verifyElement(UIElement* element)
  317. {
  318. std::vector<UIElement*> allChildren = mRootElement->getChildren(true);
  319. for (std::vector<UIElement*>::iterator i = allChildren.begin(); i != allChildren.end(); ++i)
  320. {
  321. if ((*i) == element)
  322. return *i;
  323. }
  324. return 0;
  325. }
  326. void UI::handleWindowResized(StringHash eventType, VariantMap& eventData)
  327. {
  328. using namespace WindowResized;
  329. mRootElement->setSize(eventData[P_WIDTH].getInt(), eventData[P_HEIGHT].getInt());
  330. }
  331. void UI::handleMouseMove(StringHash eventType, VariantMap& eventData)
  332. {
  333. using namespace MouseMove;
  334. mMouseButtons = eventData[P_BUTTONS].getInt();
  335. if ((mCursor) && (mCursor->isVisible()))
  336. {
  337. IntVector2 pos = mCursor->getPosition();
  338. pos.mX += eventData[P_X].getInt();
  339. pos.mY += eventData[P_Y].getInt();
  340. const IntVector2& rootSize = mRootElement->getSize();
  341. pos.mX = clamp(pos.mX, 0, rootSize.mX - 1);
  342. pos.mY = clamp(pos.mY, 0, rootSize.mY - 1);
  343. mCursor->setPosition(pos);
  344. if ((mMouseDrag) && (mMouseButtons))
  345. {
  346. UIElement* element = verifyElement(mMouseDragElement);
  347. if ((element) && (element->isEnabled()) && (element->isVisible()))
  348. element->onDragMove(element->screenToElement(pos), pos, mMouseButtons);
  349. else
  350. {
  351. mMouseDrag = false;
  352. mMouseDragElement = 0;
  353. }
  354. }
  355. }
  356. }
  357. void UI::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  358. {
  359. using namespace MouseButtonDown;
  360. mMouseButtons = eventData[P_BUTTONS].getInt();
  361. int button = eventData[P_BUTTON].getInt();
  362. if ((mCursor) && (mCursor->isVisible()))
  363. {
  364. IntVector2 pos = mCursor->getPosition();
  365. UIElement* element = getElementAt(pos);
  366. if (element)
  367. {
  368. // Handle focusing & bringing to front
  369. if (button == MOUSEB_LEFT)
  370. {
  371. setFocusElement(element);
  372. element->bringToFront();
  373. }
  374. // Handle click
  375. element->onClick(element->screenToElement(pos), pos, mMouseButtons);
  376. // Handle start of drag
  377. if (!mMouseDrag)
  378. {
  379. mMouseDrag = true;
  380. mMouseDragElement = element;
  381. element->onDragStart(element->screenToElement(pos), pos, mMouseButtons);
  382. }
  383. }
  384. else
  385. {
  386. // If clicked over no element, or a disabled element, lose focus
  387. setFocusElement(0);
  388. }
  389. }
  390. }
  391. void UI::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  392. {
  393. using namespace MouseButtonUp;
  394. mMouseButtons = eventData[P_BUTTONS].getInt();
  395. if ((mCursor) && (mCursor->isVisible()))
  396. {
  397. IntVector2 pos = mCursor->getPosition();
  398. if ((mMouseDrag) && (!mMouseButtons))
  399. {
  400. UIElement* element = verifyElement(mMouseDragElement);
  401. if ((element) && (element->isEnabled()) && (element->isVisible()))
  402. element->onDragEnd(element->screenToElement(pos), pos);
  403. mMouseDrag = false;
  404. mMouseDragElement = 0;
  405. }
  406. }
  407. }
  408. void UI::handleChar(StringHash eventType, VariantMap& eventData)
  409. {
  410. using namespace Char;
  411. UIElement* element = getFocusElement();
  412. if (element)
  413. element->onChar(eventData[P_CHAR].getInt());
  414. }
  415. void UI::loadLayout(UIElement* current, const XMLElement& elem, XMLFile* styleFile)
  416. {
  417. XMLElement childElem = elem.getChildElement("element");
  418. while (childElem)
  419. {
  420. // Create and add to the hierarchy
  421. SharedPtr<UIElement> child = createElement(ShortStringHash(childElem.getString("type")), childElem.getString("name"));
  422. current->addChild(child);
  423. // First set the base style from the style file if exists, then apply UI layout overrides
  424. if (styleFile)
  425. child->setStyleAuto(styleFile, mCache);
  426. child->setStyle(childElem, mCache);
  427. // Load the children recursively
  428. loadLayout(child, childElem, styleFile);
  429. childElem = childElem.getNextElement("element");
  430. }
  431. }