UIElement.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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 "Context.h"
  24. #include "HashSet.h"
  25. #include "Log.h"
  26. #include "ResourceCache.h"
  27. #include "Sort.h"
  28. #include "StringUtils.h"
  29. #include "UI.h"
  30. #include "UIElement.h"
  31. #include "UIEvents.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. static const char* horizontalAlignments[] =
  36. {
  37. "Left",
  38. "Center",
  39. "Right",
  40. 0
  41. };
  42. static const char* verticalAlignments[] =
  43. {
  44. "Top",
  45. "Center",
  46. "Bottom",
  47. 0
  48. };
  49. static const char* focusModes[] =
  50. {
  51. "NotFocusable",
  52. "ResetFocus",
  53. "Focusable",
  54. "FocusableDefocusable",
  55. 0
  56. };
  57. static const char* dragDropModes[] =
  58. {
  59. "Disabled",
  60. "Source",
  61. "Target",
  62. "SourceAndTarget",
  63. 0
  64. };
  65. static const char* layoutModes[] =
  66. {
  67. "Free",
  68. "Horizontal",
  69. "Vertical",
  70. 0
  71. };
  72. static bool CompareUIElements(const UIElement* lhs, const UIElement* rhs)
  73. {
  74. return lhs->GetPriority() < rhs->GetPriority();
  75. }
  76. template<> HorizontalAlignment Variant::Get<HorizontalAlignment>() const
  77. {
  78. return (HorizontalAlignment)GetInt();
  79. }
  80. template<> VerticalAlignment Variant::Get<VerticalAlignment>() const
  81. {
  82. return (VerticalAlignment)GetInt();
  83. }
  84. template<> FocusMode Variant::Get<FocusMode>() const
  85. {
  86. return (FocusMode)GetInt();
  87. }
  88. template<> LayoutMode Variant::Get<LayoutMode>() const
  89. {
  90. return (LayoutMode)GetInt();
  91. }
  92. OBJECTTYPESTATIC(UIElement);
  93. UIElement::UIElement(Context* context) :
  94. Serializable(context),
  95. parent_(0),
  96. clipBorder_(IntRect::ZERO),
  97. priority_(0),
  98. bringToFront_(false),
  99. bringToBack_(true),
  100. clipChildren_(false),
  101. sortChildren_(true),
  102. active_(false),
  103. selected_(false),
  104. visible_(true),
  105. hovering_(false),
  106. internal_(false),
  107. focusMode_(FM_NOTFOCUSABLE),
  108. dragDropMode_(DD_DISABLED),
  109. layoutMode_(LM_FREE),
  110. layoutSpacing_(0),
  111. layoutBorder_(IntRect::ZERO),
  112. resizeNestingLevel_(0),
  113. layoutNestingLevel_(0),
  114. layoutMinSize_(0),
  115. position_(IntVector2::ZERO),
  116. size_(IntVector2::ZERO),
  117. minSize_(IntVector2::ZERO),
  118. maxSize_(M_MAX_INT, M_MAX_INT),
  119. childOffset_(IntVector2::ZERO),
  120. horizontalAlignment_(HA_LEFT),
  121. verticalAlignment_(VA_TOP),
  122. opacity_(1.0f),
  123. positionDirty_(true),
  124. opacityDirty_(true),
  125. derivedColorDirty_(true),
  126. sortOrderDirty_(false),
  127. colorGradient_(false)
  128. {
  129. }
  130. UIElement::~UIElement()
  131. {
  132. // If child elements have outside references, detach them
  133. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); ++i)
  134. {
  135. if (i->Refs() > 1)
  136. (*i)->Detach();
  137. }
  138. }
  139. void UIElement::RegisterObject(Context* context)
  140. {
  141. context->RegisterFactory<UIElement>();
  142. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_STRING, "Name", GetName, SetName, String, String(), AM_FILE);
  143. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Position", GetPosition, SetPosition, IntVector2, IntVector2::ZERO, AM_FILE);
  144. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Size", GetSize, SetSize, IntVector2, IntVector2::ZERO, AM_FILE);
  145. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Min Size", GetMinSize, SetMinSize, IntVector2, IntVector2::ZERO, AM_FILE);
  146. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTVECTOR2, "Max Size", GetMaxSize, SetMaxSize, IntVector2, IntVector2::ZERO, AM_FILE);
  147. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_FILE);
  148. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_FILE);
  149. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Clip Border", GetClipBorder, SetClipBorder, IntRect, IntRect::ZERO, AM_FILE);
  150. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Priority", GetPriority, SetPriority, int, 0, AM_FILE);
  151. ACCESSOR_ATTRIBUTE(UIElement, VAR_FLOAT, "Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
  152. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_COLOR, "Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_FILE);
  153. ATTRIBUTE(UIElement, VAR_COLOR, "Top Left Color", color_[0], Color::WHITE, AM_FILE);
  154. ATTRIBUTE(UIElement, VAR_COLOR, "Top Right Color", color_[1], Color::WHITE, AM_FILE);
  155. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Left Color", color_[2], Color::WHITE, AM_FILE);
  156. ATTRIBUTE(UIElement, VAR_COLOR, "Bottom Right Color", color_[3], Color::WHITE, AM_FILE);
  157. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Active", IsActive, SetActive, bool, false, AM_FILE);
  158. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Selected", IsSelected, SetSelected, bool, false, AM_FILE);
  159. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Is Visible", IsVisible, SetVisible, bool, true, AM_FILE);
  160. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Front", GetBringToFront, SetBringToFront, bool, false, AM_FILE);
  161. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Bring To Back", GetBringToBack, SetBringToBack, bool, true, AM_FILE);
  162. ACCESSOR_ATTRIBUTE(UIElement, VAR_BOOL, "Clip Children", GetClipChildren, SetClipChildren, bool, false, AM_FILE);
  163. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Focus Mode", GetFocusMode, SetFocusMode, FocusMode, focusModes, FM_NOTFOCUSABLE, AM_FILE);
  164. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Drag And Drop Mode", GetDragDropMode, SetDragDropMode, unsigned, dragDropModes, DD_DISABLED, AM_FILE);
  165. ENUM_ACCESSOR_ATTRIBUTE(UIElement, "Layout Mode", GetLayoutMode, SetLayoutMode, LayoutMode, layoutModes, LM_FREE, AM_FILE);
  166. ACCESSOR_ATTRIBUTE(UIElement, VAR_INT, "Layout Spacing", GetLayoutSpacing, SetLayoutSpacing, int, 0, AM_FILE);
  167. REF_ACCESSOR_ATTRIBUTE(UIElement, VAR_INTRECT, "Layout Border", GetLayoutBorder, SetLayoutBorder, IntRect, IntRect::ZERO, AM_FILE);
  168. ATTRIBUTE(UIElement, VAR_VARIANTMAP, "Variables", vars_, VariantMap(), AM_FILE);
  169. }
  170. void UIElement::ApplyAttributes()
  171. {
  172. colorGradient_ = false;
  173. derivedColorDirty_ = true;
  174. for (unsigned i = 1; i < MAX_UIELEMENT_CORNERS; ++i)
  175. {
  176. if (color_[i] != color_[0])
  177. colorGradient_ = true;
  178. }
  179. }
  180. bool UIElement::LoadXML(const XMLElement& source)
  181. {
  182. return LoadXML(source, 0);
  183. }
  184. bool UIElement::LoadXML(const XMLElement& source, XMLFile* styleFile)
  185. {
  186. // Apply the style first, but only for non-internal elements
  187. if (!internal_ && styleFile)
  188. {
  189. // Use style override if defined, otherwise type name
  190. String styleName = source.GetAttribute("style");
  191. if (styleName.Empty())
  192. styleName = GetTypeName();
  193. SetStyle(styleFile, styleName);
  194. }
  195. // Then load rest of the attributes from the source
  196. if (!Serializable::LoadXML(source))
  197. return false;
  198. unsigned nextInternalChild = 0;
  199. // Load child elements. Internal elements are not to be created as they already exist
  200. XMLElement childElem = source.GetChild("element");
  201. while (childElem)
  202. {
  203. bool internalElem = childElem.GetBool("internal");
  204. String typeName = childElem.GetAttribute("type");
  205. if (typeName.Empty())
  206. typeName = "UIElement";
  207. UIElement* child = 0;
  208. if (!internalElem)
  209. child = CreateChild(ShortStringHash(typeName));
  210. else
  211. {
  212. for (unsigned i = nextInternalChild; i < children_.Size(); ++i)
  213. {
  214. if (children_[i]->IsInternal() && children_[i]->GetTypeName() == typeName)
  215. {
  216. child = children_[i];
  217. nextInternalChild = i + 1;
  218. break;
  219. }
  220. }
  221. if (!child)
  222. LOGWARNING("Could not find matching internal child element of type " + typeName + " in " + GetTypeName());
  223. }
  224. if (child)
  225. {
  226. if (!child->LoadXML(childElem, styleFile))
  227. return false;
  228. }
  229. childElem = childElem.GetNext("element");
  230. }
  231. ApplyAttributes();
  232. return true;
  233. }
  234. bool UIElement::SaveXML(XMLElement& dest)
  235. {
  236. // Write type and internal flag
  237. if (!dest.SetString("type", GetTypeName()))
  238. return false;
  239. if (internal_)
  240. {
  241. if (!dest.SetBool("internal", internal_))
  242. return false;
  243. }
  244. // Write attributes
  245. if (!Serializable::SaveXML(dest))
  246. return false;
  247. // Write child elements
  248. for (unsigned i = 0; i < children_.Size(); ++i)
  249. {
  250. UIElement* element = children_[i];
  251. XMLElement childElem = dest.CreateChild("element");
  252. if (!element->SaveXML(childElem))
  253. return false;
  254. }
  255. return true;
  256. }
  257. void UIElement::Update(float timeStep)
  258. {
  259. }
  260. void UIElement::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor)
  261. {
  262. // Reset hovering for next frame
  263. hovering_ = false;
  264. }
  265. void UIElement::OnHover(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  266. {
  267. hovering_ = true;
  268. }
  269. void UIElement::OnClick(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  270. {
  271. }
  272. void UIElement::OnDragBegin(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  273. {
  274. }
  275. void UIElement::OnDragMove(const IntVector2& position, const IntVector2& screenPosition, int buttons, int qualifiers, Cursor* cursor)
  276. {
  277. }
  278. void UIElement::OnDragEnd(const IntVector2& position, const IntVector2& screenPosition, Cursor* cursor)
  279. {
  280. }
  281. bool UIElement::OnDragDropTest(UIElement* source)
  282. {
  283. return true;
  284. }
  285. bool UIElement::OnDragDropFinish(UIElement* source)
  286. {
  287. return true;
  288. }
  289. void UIElement::OnWheel(int delta, int buttons, int qualifiers)
  290. {
  291. }
  292. void UIElement::OnKey(int key, int buttons, int qualifiers)
  293. {
  294. }
  295. void UIElement::OnChar(unsigned c, int buttons, int qualifiers)
  296. {
  297. }
  298. void UIElement::OnResize()
  299. {
  300. }
  301. bool UIElement::LoadXML(Deserializer& source)
  302. {
  303. SharedPtr<XMLFile> xml(new XMLFile(context_));
  304. if (!xml->Load(source))
  305. return false;
  306. return LoadXML(xml->GetRoot());
  307. }
  308. bool UIElement::SaveXML(Serializer& dest)
  309. {
  310. SharedPtr<XMLFile> xml(new XMLFile(context_));
  311. XMLElement rootElem = xml->CreateRoot("element");
  312. if (!SaveXML(rootElem))
  313. return false;
  314. return xml->Save(dest);
  315. }
  316. void UIElement::SetName(const String& name)
  317. {
  318. name_ = name;
  319. }
  320. void UIElement::SetPosition(const IntVector2& position)
  321. {
  322. if (position != position_)
  323. {
  324. position_ = position;
  325. MarkDirty();
  326. }
  327. }
  328. void UIElement::SetPosition(int x, int y)
  329. {
  330. SetPosition(IntVector2(x, y));
  331. }
  332. void UIElement::SetSize(const IntVector2& size)
  333. {
  334. ++resizeNestingLevel_;
  335. IntVector2 validatedSize;
  336. validatedSize.x_ = Clamp(size.x_, minSize_.x_, maxSize_.x_);
  337. validatedSize.y_ = Clamp(size.y_, minSize_.y_, maxSize_.y_);
  338. if (validatedSize != size_)
  339. {
  340. size_ = validatedSize;
  341. if (resizeNestingLevel_ == 1)
  342. {
  343. // Check if parent element's layout needs to be updated first
  344. if (parent_)
  345. parent_->UpdateLayout();
  346. MarkDirty();
  347. OnResize();
  348. UpdateLayout();
  349. using namespace Resized;
  350. VariantMap eventData;
  351. eventData[P_ELEMENT] = (void*)this;
  352. eventData[P_WIDTH] = size_.x_;
  353. eventData[P_HEIGHT] = size_.y_;
  354. SendEvent(E_RESIZED, eventData);
  355. }
  356. }
  357. --resizeNestingLevel_;
  358. }
  359. void UIElement::SetSize(int width, int height)
  360. {
  361. SetSize(IntVector2(width, height));
  362. }
  363. void UIElement::SetWidth(int width)
  364. {
  365. SetSize(IntVector2(width, size_.y_));
  366. }
  367. void UIElement::SetHeight(int height)
  368. {
  369. SetSize(IntVector2(size_.x_, height));
  370. }
  371. void UIElement::SetMinSize(const IntVector2& minSize)
  372. {
  373. minSize_.x_ = Max(minSize.x_, 0);
  374. minSize_.y_ = Max(minSize.y_, 0);
  375. SetSize(size_);
  376. }
  377. void UIElement::SetMinSize(int width, int height)
  378. {
  379. SetMinSize(IntVector2(width, height));
  380. }
  381. void UIElement::SetMinWidth(int width)
  382. {
  383. SetMinSize(IntVector2(width, minSize_.y_));
  384. }
  385. void UIElement::SetMinHeight(int height)
  386. {
  387. SetMinSize(IntVector2(minSize_.x_, height));
  388. }
  389. void UIElement::SetMaxSize(const IntVector2& maxSize)
  390. {
  391. maxSize_.x_ = Max(maxSize.x_, 0);
  392. maxSize_.y_ = Max(maxSize.y_, 0);
  393. SetSize(size_);
  394. }
  395. void UIElement::SetMaxSize(int width, int height)
  396. {
  397. SetMaxSize(IntVector2(width, height));
  398. }
  399. void UIElement::SetMaxWidth(int width)
  400. {
  401. SetMaxSize(IntVector2(width, maxSize_.y_));
  402. }
  403. void UIElement::SetMaxHeight(int height)
  404. {
  405. SetMaxSize(IntVector2(maxSize_.x_, height));
  406. }
  407. void UIElement::SetFixedSize(const IntVector2& size)
  408. {
  409. minSize_ = maxSize_ = IntVector2(Max(size.x_, 0), Max(size.y_, 0));
  410. SetSize(size);
  411. }
  412. void UIElement::SetFixedSize(int width, int height)
  413. {
  414. SetFixedSize(IntVector2(width, height));
  415. }
  416. void UIElement::SetFixedWidth(int width)
  417. {
  418. minSize_.x_ = maxSize_.x_ = Max(width, 0);
  419. SetWidth(width);
  420. }
  421. void UIElement::SetFixedHeight(int height)
  422. {
  423. minSize_.y_ = maxSize_.y_ = Max(height, 0);
  424. SetHeight(height);
  425. }
  426. void UIElement::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
  427. {
  428. horizontalAlignment_ = hAlign;
  429. verticalAlignment_ = vAlign;
  430. MarkDirty();
  431. }
  432. void UIElement::SetHorizontalAlignment(HorizontalAlignment align)
  433. {
  434. horizontalAlignment_ = align;
  435. MarkDirty();
  436. }
  437. void UIElement::SetVerticalAlignment(VerticalAlignment align)
  438. {
  439. verticalAlignment_ = align;
  440. MarkDirty();
  441. }
  442. void UIElement::SetClipBorder(const IntRect& rect)
  443. {
  444. clipBorder_.left_ = Max(rect.left_, 0);
  445. clipBorder_.top_ = Max(rect.top_, 0);
  446. clipBorder_.right_ = Max(rect.right_, 0);
  447. clipBorder_.bottom_ = Max(rect.bottom_, 0);
  448. }
  449. void UIElement::SetColor(const Color& color)
  450. {
  451. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  452. color_[i] = color;
  453. colorGradient_ = false;
  454. derivedColorDirty_ = true;
  455. }
  456. void UIElement::SetColor(Corner corner, const Color& color)
  457. {
  458. color_[corner] = color;
  459. colorGradient_ = false;
  460. derivedColorDirty_ = true;
  461. for (unsigned i = 0; i < MAX_UIELEMENT_CORNERS; ++i)
  462. {
  463. if (i != corner && color_[i] != color_[corner])
  464. colorGradient_ = true;
  465. }
  466. }
  467. void UIElement::SetPriority(int priority)
  468. {
  469. priority_ = priority;
  470. if (parent_)
  471. parent_->sortOrderDirty_ = true;
  472. }
  473. void UIElement::SetOpacity(float opacity)
  474. {
  475. opacity_ = Clamp(opacity, 0.0f, 1.0f);
  476. MarkDirty();
  477. }
  478. void UIElement::SetBringToFront(bool enable)
  479. {
  480. bringToFront_ = enable;
  481. }
  482. void UIElement::SetBringToBack(bool enable)
  483. {
  484. bringToBack_ = enable;
  485. }
  486. void UIElement::SetClipChildren(bool enable)
  487. {
  488. clipChildren_ = enable;
  489. }
  490. void UIElement::SetSortChildren(bool enable)
  491. {
  492. if (!sortChildren_ && enable)
  493. sortOrderDirty_ = true;
  494. sortChildren_ = enable;
  495. }
  496. void UIElement::SetActive(bool enable)
  497. {
  498. active_ = enable;
  499. }
  500. void UIElement::SetFocusMode(FocusMode mode)
  501. {
  502. focusMode_ = mode;
  503. }
  504. void UIElement::SetFocus(bool enable)
  505. {
  506. if (focusMode_ < FM_FOCUSABLE)
  507. enable = false;
  508. UI* ui = GetSubsystem<UI>();
  509. if (!ui)
  510. return;
  511. if (enable)
  512. {
  513. if (ui->GetFocusElement() != this)
  514. ui->SetFocusElement(this);
  515. }
  516. else
  517. {
  518. if (ui->GetFocusElement() == this)
  519. ui->SetFocusElement(0);
  520. }
  521. }
  522. void UIElement::SetSelected(bool enable)
  523. {
  524. selected_ = enable;
  525. }
  526. void UIElement::SetVisible(bool enable)
  527. {
  528. if (enable != visible_)
  529. {
  530. visible_ = enable;
  531. // Parent's layout may change as a result of visibility change
  532. if (parent_)
  533. parent_->UpdateLayout();
  534. using namespace VisibleChanged;
  535. VariantMap eventData;
  536. eventData[P_ELEMENT] = (void*)this;
  537. eventData[P_VISIBLE] = visible_;
  538. SendEvent(E_VISIBLECHANGED, eventData);
  539. }
  540. }
  541. void UIElement::SetDragDropMode(unsigned mode)
  542. {
  543. dragDropMode_ = mode;
  544. }
  545. void UIElement::SetStyle(XMLFile* file, const String& typeName)
  546. {
  547. if (!file)
  548. return;
  549. XMLElement rootElem = file->GetRoot();
  550. XMLElement childElem = rootElem.GetChild("element");
  551. while (childElem)
  552. {
  553. if (typeName == childElem.GetAttribute("type"))
  554. {
  555. SetStyle(childElem);
  556. return;
  557. }
  558. childElem = childElem.GetNext("element");
  559. }
  560. }
  561. void UIElement::SetStyle(const XMLElement& element)
  562. {
  563. LoadXML(element);
  564. }
  565. void UIElement::SetStyleAuto(XMLFile* file)
  566. {
  567. SetStyle(file, GetTypeName());
  568. }
  569. void UIElement::SetLayout(LayoutMode mode, int spacing, const IntRect& border)
  570. {
  571. layoutMode_ = mode;
  572. layoutSpacing_ = Max(spacing, 0);
  573. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  574. UpdateLayout();
  575. }
  576. void UIElement::SetLayoutMode(LayoutMode mode)
  577. {
  578. layoutMode_ = mode;
  579. UpdateLayout();
  580. }
  581. void UIElement::SetLayoutSpacing(int spacing)
  582. {
  583. layoutSpacing_ = Max(spacing, 0);
  584. UpdateLayout();
  585. }
  586. void UIElement::SetLayoutBorder(const IntRect& border)
  587. {
  588. layoutBorder_ = IntRect(Max(border.left_, 0), Max(border.top_, 0), Max(border.right_, 0), Max(border.bottom_, 0));
  589. UpdateLayout();
  590. }
  591. void UIElement::UpdateLayout()
  592. {
  593. if (layoutMode_ == LM_FREE || layoutNestingLevel_)
  594. return;
  595. // Prevent further updates while this update happens
  596. DisableLayoutUpdate();
  597. PODVector<int> positions;
  598. PODVector<int> sizes;
  599. PODVector<int> minSizes;
  600. PODVector<int> maxSizes;
  601. if (layoutMode_ == LM_HORIZONTAL)
  602. {
  603. int minChildHeight = 0;
  604. for (unsigned i = 0; i < children_.Size(); ++i)
  605. {
  606. if (!children_[i]->IsVisible())
  607. continue;
  608. positions.Push(0);
  609. sizes.Push(children_[i]->GetWidth());
  610. minSizes.Push(children_[i]->GetMinWidth());
  611. maxSizes.Push(children_[i]->GetMaxWidth());
  612. minChildHeight = Max(minChildHeight, children_[i]->GetMinHeight());
  613. }
  614. CalculateLayout(positions, sizes, minSizes, maxSizes, GetWidth(), layoutBorder_.left_, layoutBorder_.right_,
  615. layoutSpacing_);
  616. int width = CalculateLayoutParentSize(sizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_);
  617. int height = Max(GetHeight(), minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_);
  618. int minWidth = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.left_, layoutBorder_.right_, layoutSpacing_), maxSize_.x_);
  619. int minHeight = Min(minChildHeight + layoutBorder_.top_ + layoutBorder_.bottom_, maxSize_.y_);
  620. // Respect fixed size if already set
  621. if (minSize_.x_ != maxSize_.x_)
  622. minSize_.x_ = minWidth;
  623. if (minSize_.y_ != maxSize_.y_)
  624. minSize_.y_ = minHeight;
  625. SetSize(width, height);
  626. // Validate the size before resizing child elements, in case of min/max limits
  627. width = size_.x_;
  628. height = size_.y_;
  629. unsigned j = 0;
  630. for (unsigned i = 0; i < children_.Size(); ++i)
  631. {
  632. if (!children_[i]->IsVisible())
  633. continue;
  634. children_[i]->SetHorizontalAlignment(HA_LEFT);
  635. children_[i]->SetPosition(positions[j], GetLayoutChildPosition(children_[i]).y_);
  636. children_[i]->SetSize(sizes[j], height - layoutBorder_.top_ - layoutBorder_.bottom_);
  637. ++j;
  638. }
  639. }
  640. else if (layoutMode_ == LM_VERTICAL)
  641. {
  642. int minChildWidth = 0;
  643. for (unsigned i = 0; i < children_.Size(); ++i)
  644. {
  645. if (!children_[i]->IsVisible())
  646. continue;
  647. positions.Push(0);
  648. sizes.Push(children_[i]->GetHeight());
  649. minSizes.Push(children_[i]->GetMinHeight());
  650. maxSizes.Push(children_[i]->GetMaxHeight());
  651. minChildWidth = Max(minChildWidth, children_[i]->GetMinWidth());
  652. }
  653. CalculateLayout(positions, sizes, minSizes, maxSizes, GetHeight(), layoutBorder_.top_, layoutBorder_.bottom_,
  654. layoutSpacing_);
  655. int height = CalculateLayoutParentSize(sizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_);
  656. int width = Max(GetWidth(), minChildWidth + layoutBorder_.left_ + layoutBorder_.right_);
  657. int minHeight = Min(CalculateLayoutParentSize(minSizes, layoutBorder_.top_, layoutBorder_.bottom_, layoutSpacing_), maxSize_.y_);
  658. int minWidth = Min(minChildWidth + layoutBorder_.left_ + layoutBorder_.right_, maxSize_.x_);
  659. if (minSize_.x_ != maxSize_.x_)
  660. minSize_.x_ = minWidth;
  661. if (minSize_.y_ != maxSize_.y_)
  662. minSize_.y_ = minHeight;
  663. SetSize(width, height);
  664. width = size_.x_;
  665. height = size_.y_;
  666. unsigned j = 0;
  667. for (unsigned i = 0; i < children_.Size(); ++i)
  668. {
  669. if (!children_[i]->IsVisible())
  670. continue;
  671. children_[i]->SetVerticalAlignment(VA_TOP);
  672. children_[i]->SetPosition(GetLayoutChildPosition(children_[i]).x_, positions[j]);
  673. children_[i]->SetSize(width - layoutBorder_.left_ - layoutBorder_.right_, sizes[j]);
  674. ++j;
  675. }
  676. }
  677. EnableLayoutUpdate();
  678. }
  679. void UIElement::DisableLayoutUpdate()
  680. {
  681. ++layoutNestingLevel_;
  682. }
  683. void UIElement::EnableLayoutUpdate()
  684. {
  685. --layoutNestingLevel_;
  686. }
  687. void UIElement::BringToFront()
  688. {
  689. // Follow the parent chain to the top level window. If it has BringToFront mode, bring it to front now
  690. UIElement* root = GetRoot();
  691. UIElement* ptr = this;
  692. while (ptr && ptr->GetParent() != root)
  693. ptr = ptr->GetParent();
  694. if (!ptr || !ptr->GetBringToFront())
  695. return;
  696. // Get the highest priority used by all other top level elements, assign that to the new front element
  697. // and decrease others' priority where necessary. However, take into account only active (enabled)
  698. // elements and those which have the BringToBack flag set
  699. HashSet<int> usedPriorities;
  700. int maxPriority = M_MIN_INT;
  701. const Vector<SharedPtr<UIElement> >& rootChildren = root->GetChildren();
  702. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  703. {
  704. UIElement* other = *i;
  705. if (other->IsActive() && other->bringToBack_ && other != ptr)
  706. {
  707. int priority = other->GetPriority();
  708. usedPriorities.Insert(priority);
  709. maxPriority = Max(priority, maxPriority);
  710. }
  711. }
  712. if (maxPriority != M_MIN_INT && maxPriority >= ptr->GetPriority())
  713. {
  714. ptr->SetPriority(maxPriority);
  715. int minPriority = maxPriority;
  716. while (usedPriorities.Contains(minPriority))
  717. --minPriority;
  718. for (Vector<SharedPtr<UIElement> >::ConstIterator i = rootChildren.Begin(); i != rootChildren.End(); ++i)
  719. {
  720. UIElement* other = *i;
  721. int priority = other->GetPriority();
  722. if (other->IsActive() && other->bringToBack_ && other != ptr && priority >= minPriority && priority <= maxPriority)
  723. other->SetPriority(priority - 1);
  724. }
  725. }
  726. }
  727. UIElement* UIElement::CreateChild(ShortStringHash type, const String& name)
  728. {
  729. // Check that creation succeeds and that the object in fact is a UI element
  730. SharedPtr<UIElement> newElement = DynamicCast<UIElement>(context_->CreateObject(type));
  731. if (!newElement)
  732. {
  733. LOGERROR("Could not create unknown UI element type " + type.ToString());
  734. return 0;
  735. }
  736. newElement->SetName(name);
  737. AddChild(newElement);
  738. return newElement;
  739. }
  740. void UIElement::AddChild(UIElement* element)
  741. {
  742. InsertChild(children_.Size(), element);
  743. }
  744. void UIElement::InsertChild(unsigned index, UIElement* element)
  745. {
  746. // Check for illegal or redundant parent assignment
  747. if (!element || element == this || element->parent_ == this)
  748. return;
  749. // Check for possible cyclic parent assignment
  750. UIElement* parent = parent_;
  751. while (parent)
  752. {
  753. if (parent == element)
  754. return;
  755. parent = parent->parent_;
  756. }
  757. // Add first, then remove from old parent, to ensure the element does not get deleted
  758. if (index >= children_.Size())
  759. children_.Push(SharedPtr<UIElement>(element));
  760. else
  761. children_.Insert(children_.Begin() + index, SharedPtr<UIElement>(element));
  762. element->Remove();
  763. if (sortChildren_)
  764. sortOrderDirty_ = true;
  765. element->parent_ = this;
  766. element->MarkDirty();
  767. UpdateLayout();
  768. }
  769. void UIElement::RemoveChild(UIElement* element, unsigned index)
  770. {
  771. for (unsigned i = index; i < children_.Size(); ++i)
  772. {
  773. if (children_[i] == element)
  774. {
  775. element->Detach();
  776. children_.Erase(i);
  777. UpdateLayout();
  778. return;
  779. }
  780. }
  781. }
  782. void UIElement::RemoveAllChildren()
  783. {
  784. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i < children_.End(); )
  785. (*i++)->Detach();
  786. children_.Clear();
  787. }
  788. void UIElement::Remove()
  789. {
  790. if (parent_)
  791. parent_->RemoveChild(this);
  792. }
  793. void UIElement::SetParent(UIElement* parent)
  794. {
  795. if (parent)
  796. parent->AddChild(this);
  797. }
  798. void UIElement::SetVar(ShortStringHash key, const Variant& value)
  799. {
  800. vars_[key] = value;
  801. }
  802. void UIElement::SetInternal(bool enable)
  803. {
  804. internal_ = enable;
  805. }
  806. IntVector2 UIElement::GetScreenPosition() const
  807. {
  808. if (positionDirty_)
  809. {
  810. IntVector2 pos = position_;
  811. const UIElement* parent = parent_;
  812. const UIElement* current = this;
  813. while (parent)
  814. {
  815. switch (current->horizontalAlignment_)
  816. {
  817. case HA_LEFT:
  818. pos.x_ += parent->position_.x_;
  819. break;
  820. case HA_CENTER:
  821. pos.x_ += parent->position_.x_ + parent->size_.x_ / 2 - current->size_.x_ / 2;
  822. break;
  823. case HA_RIGHT:
  824. pos.x_ += parent->position_.x_ + parent->size_.x_ - current->size_.x_;
  825. break;
  826. }
  827. switch (current->verticalAlignment_)
  828. {
  829. case VA_TOP:
  830. pos.y_ += parent->position_.y_;
  831. break;
  832. case VA_CENTER:
  833. pos.y_ += parent->position_.y_ + parent->size_.y_ / 2 - current->size_.y_ / 2;
  834. break;
  835. case VA_BOTTOM:
  836. pos.y_ += parent->position_.y_ + parent->size_.y_ - current->size_.y_;
  837. break;
  838. }
  839. pos += parent->childOffset_;
  840. current = parent;
  841. parent = parent->parent_;
  842. }
  843. screenPosition_ = pos;
  844. positionDirty_ = false;
  845. }
  846. return screenPosition_;
  847. }
  848. float UIElement::GetDerivedOpacity() const
  849. {
  850. if (opacityDirty_)
  851. {
  852. float opacity = opacity_;
  853. const UIElement* parent = parent_;
  854. while (parent)
  855. {
  856. opacity *= parent->opacity_;
  857. parent = parent->parent_;
  858. }
  859. derivedOpacity_ = opacity;
  860. opacityDirty_ = false;
  861. }
  862. return derivedOpacity_;
  863. }
  864. bool UIElement::HasFocus() const
  865. {
  866. UI* ui = GetSubsystem<UI>();
  867. if (!ui)
  868. return false;
  869. else
  870. return ui->GetFocusElement() == this;
  871. }
  872. void UIElement::GetChildren(PODVector<UIElement*>& dest, bool recursive) const
  873. {
  874. dest.Clear();
  875. if (!recursive)
  876. {
  877. dest.Reserve(children_.Size());
  878. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  879. dest.Push(*i);
  880. }
  881. else
  882. GetChildrenRecursive(dest);
  883. }
  884. unsigned UIElement::GetNumChildren(bool recursive) const
  885. {
  886. if (!recursive)
  887. return children_.Size();
  888. else
  889. {
  890. unsigned allChildren = children_.Size();
  891. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  892. allChildren += (*i)->GetNumChildren(true);
  893. return allChildren;
  894. }
  895. }
  896. UIElement* UIElement::GetChild(unsigned index) const
  897. {
  898. return index < children_.Size() ? children_[index] : (UIElement*)0;
  899. }
  900. UIElement* UIElement::GetChild(const String& name, bool recursive) const
  901. {
  902. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  903. {
  904. if ((*i)->name_ == name)
  905. return *i;
  906. if (recursive)
  907. {
  908. UIElement* element = (*i)->GetChild(name, true);
  909. if (element)
  910. return element;
  911. }
  912. }
  913. return 0;
  914. }
  915. UIElement* UIElement::GetRoot() const
  916. {
  917. UIElement* root = parent_;
  918. if (!root)
  919. return 0;
  920. while (root->GetParent())
  921. root = root->GetParent();
  922. return root;
  923. }
  924. const Color& UIElement::GetDerivedColor() const
  925. {
  926. if (derivedColorDirty_)
  927. {
  928. derivedColor_ = color_[C_TOPLEFT];
  929. derivedColor_.a_ *= GetDerivedOpacity();
  930. derivedColorDirty_ = false;
  931. }
  932. return derivedColor_;
  933. }
  934. const Variant& UIElement::GetVar(ShortStringHash key) const
  935. {
  936. VariantMap::ConstIterator i = vars_.Find(key);
  937. if (i != vars_.End())
  938. return i->second_;
  939. else
  940. return Variant::EMPTY;
  941. }
  942. IntVector2 UIElement::ScreenToElement(const IntVector2& screenPosition)
  943. {
  944. return screenPosition - GetScreenPosition();
  945. }
  946. IntVector2 UIElement::ElementToScreen(const IntVector2& position)
  947. {
  948. return position + GetScreenPosition();
  949. }
  950. bool UIElement::IsInside(IntVector2 position, bool isScreen)
  951. {
  952. if (isScreen)
  953. position = ScreenToElement(position);
  954. return position.x_ >= 0 && position.y_ >= 0 && position.x_ < size_.x_ && position.y_ < size_.y_;
  955. }
  956. bool UIElement::IsInsideCombined(IntVector2 position, bool isScreen)
  957. {
  958. // If child elements are clipped, no need to expand the rect
  959. if (clipChildren_)
  960. return IsInside(position, isScreen);
  961. if (!isScreen)
  962. position = ElementToScreen(position);
  963. IntRect combined = GetCombinedScreenRect();
  964. return position.x_ >= combined.left_ && position.y_ >= combined.top_ && position.x_ < combined.right_ &&
  965. position.y_ < combined.bottom_;
  966. }
  967. IntRect UIElement::GetCombinedScreenRect()
  968. {
  969. IntVector2 screenPosition(GetScreenPosition());
  970. IntRect combined(screenPosition.x_, screenPosition.y_, screenPosition.x_ + size_.x_, screenPosition.y_ + size_.y_);
  971. if (!clipChildren_)
  972. {
  973. for (Vector<SharedPtr<UIElement> >::Iterator i = children_.Begin(); i != children_.End(); ++i)
  974. {
  975. IntVector2 childPos = (*i)->GetScreenPosition();
  976. const IntVector2& childSize = (*i)->GetSize();
  977. if (childPos.x_ < combined.left_)
  978. combined.left_ = childPos.x_;
  979. if (childPos.y_ < combined.top_)
  980. combined.top_ = childPos.y_;
  981. if (childPos.x_ + childSize.x_ > combined.right_)
  982. combined.right_ = childPos.x_ + childSize.x_;
  983. if (childPos.y_ + childSize.y_ > combined.bottom_)
  984. combined.bottom_ = childPos.y_ + childSize.y_;
  985. }
  986. }
  987. return combined;
  988. }
  989. void UIElement::SortChildren()
  990. {
  991. if (sortChildren_ && sortOrderDirty_)
  992. {
  993. Sort(children_.Begin(), children_.End(), CompareUIElements);
  994. sortOrderDirty_ = false;
  995. }
  996. }
  997. void UIElement::SetChildOffset(const IntVector2& offset)
  998. {
  999. if (offset != childOffset_)
  1000. {
  1001. childOffset_ = offset;
  1002. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1003. (*i)->MarkDirty();
  1004. }
  1005. }
  1006. void UIElement::SetHovering(bool enable)
  1007. {
  1008. hovering_ = enable;
  1009. }
  1010. void UIElement::SetTempVisible(bool enable)
  1011. {
  1012. visible_ = enable;
  1013. }
  1014. void UIElement::AdjustScissor(IntRect& currentScissor)
  1015. {
  1016. if (clipChildren_)
  1017. {
  1018. IntVector2 screenPos = GetScreenPosition();
  1019. currentScissor.left_ = Max(currentScissor.left_, screenPos.x_ + clipBorder_.left_);
  1020. currentScissor.top_ = Max(currentScissor.top_, screenPos.y_ + clipBorder_.top_);
  1021. currentScissor.right_ = Min(currentScissor.right_, screenPos.x_ + size_.x_ - clipBorder_.right_);
  1022. currentScissor.bottom_ = Min(currentScissor.bottom_, screenPos.y_ + size_.y_ - clipBorder_.bottom_);
  1023. if (currentScissor.right_ < currentScissor.left_)
  1024. currentScissor.right_ = currentScissor.left_;
  1025. if (currentScissor.bottom_ < currentScissor.top_)
  1026. currentScissor.bottom_ = currentScissor.top_;
  1027. }
  1028. }
  1029. void UIElement::GetBatchesWithOffset(IntVector2& offset, PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, IntRect
  1030. currentScissor)
  1031. {
  1032. unsigned initialSize = quads.Size();
  1033. GetBatches(batches, quads, currentScissor);
  1034. for (unsigned i = initialSize; i < quads.Size(); ++i)
  1035. {
  1036. quads[i].left_ += offset.x_;
  1037. quads[i].top_ += offset.y_;
  1038. quads[i].right_ += offset.x_;
  1039. quads[i].bottom_ += offset.y_;
  1040. }
  1041. AdjustScissor(currentScissor);
  1042. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1043. {
  1044. if ((*i)->IsVisible())
  1045. (*i)->GetBatchesWithOffset(offset, batches, quads, currentScissor);
  1046. }
  1047. }
  1048. void UIElement::MarkDirty()
  1049. {
  1050. positionDirty_ = true;
  1051. opacityDirty_ = true;
  1052. derivedColorDirty_ = true;
  1053. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1054. (*i)->MarkDirty();
  1055. }
  1056. void UIElement::GetChildrenRecursive(PODVector<UIElement*>& dest) const
  1057. {
  1058. for (Vector<SharedPtr<UIElement> >::ConstIterator i = children_.Begin(); i != children_.End(); ++i)
  1059. {
  1060. UIElement* element = *i;
  1061. dest.Push(element);
  1062. if (!element->children_.Empty())
  1063. element->GetChildrenRecursive(dest);
  1064. }
  1065. }
  1066. int UIElement::CalculateLayoutParentSize(const PODVector<int>& sizes, int begin, int end, int spacing)
  1067. {
  1068. int width = begin + end;
  1069. if (sizes.Empty())
  1070. return width;
  1071. for (unsigned i = 0; i < sizes.Size(); ++i)
  1072. {
  1073. // If calculating maximum size, and the default is specified, do not overflow it
  1074. if (sizes[i] == M_MAX_INT)
  1075. return M_MAX_INT;
  1076. width += sizes[i] + spacing;
  1077. }
  1078. // The last spacing is not needed
  1079. return width - spacing;
  1080. }
  1081. void UIElement::CalculateLayout(PODVector<int>& positions, PODVector<int>& sizes, const PODVector<int>& minSizes,
  1082. const PODVector<int>& maxSizes, int targetSize, int begin, int end, int spacing)
  1083. {
  1084. int numChildren = sizes.Size();
  1085. if (!numChildren)
  1086. return;
  1087. int targetTotalSize = targetSize - begin - end - (numChildren - 1) * spacing;
  1088. if (targetTotalSize < 0)
  1089. targetTotalSize = 0;
  1090. int targetChildSize = targetTotalSize / numChildren;
  1091. int remainder = targetTotalSize % numChildren;
  1092. float add = (float)remainder / numChildren;
  1093. float acc = 0.0f;
  1094. // Initial pass
  1095. for (int i = 0; i < numChildren; ++i)
  1096. {
  1097. int targetSize = targetChildSize;
  1098. if (remainder)
  1099. {
  1100. acc += add;
  1101. if (acc >= 0.5f)
  1102. {
  1103. acc -= 1.0f;
  1104. ++targetSize;
  1105. --remainder;
  1106. }
  1107. }
  1108. sizes[i] = Clamp(targetSize, minSizes[i], maxSizes[i]);
  1109. }
  1110. // Error correction passes
  1111. for (;;)
  1112. {
  1113. int actualTotalSize = 0;
  1114. for (int i = 0; i < numChildren; ++i)
  1115. actualTotalSize += sizes[i];
  1116. int error = targetTotalSize - actualTotalSize;
  1117. // Break if no error
  1118. if (!error)
  1119. break;
  1120. // Check which of the children can be resized to correct the error. If none, must break
  1121. PODVector<unsigned> resizable;
  1122. for (int i = 0; i < numChildren; ++i)
  1123. {
  1124. if (error < 0 && sizes[i] > minSizes[i])
  1125. resizable.Push(i);
  1126. else if (error > 0 && sizes[i] < maxSizes[i])
  1127. resizable.Push(i);
  1128. }
  1129. if (resizable.Empty())
  1130. break;
  1131. int numResizable = resizable.Size();
  1132. int errorPerChild = error / numResizable;
  1133. remainder = (abs(error)) % numResizable;
  1134. add = (float)remainder / numResizable;
  1135. acc = 0.0f;
  1136. for (int i = 0; i < numResizable; ++i)
  1137. {
  1138. unsigned index = resizable[i];
  1139. int targetSize = sizes[index] + errorPerChild;
  1140. if (remainder)
  1141. {
  1142. acc += add;
  1143. if (acc >= 0.5f)
  1144. {
  1145. acc -= 1.0f;
  1146. targetSize = error < 0 ? targetSize - 1 : targetSize + 1;
  1147. --remainder;
  1148. }
  1149. }
  1150. sizes[index] = Clamp(targetSize, minSizes[index], maxSizes[index]);
  1151. }
  1152. }
  1153. // Calculate final positions and store the minimum child element size
  1154. layoutMinSize_ = M_MAX_INT;
  1155. int position = begin;
  1156. for (int i = 0; i < numChildren; ++i)
  1157. {
  1158. positions[i] = position;
  1159. position += sizes[i] + spacing;
  1160. if (sizes[i] < layoutMinSize_)
  1161. layoutMinSize_ = sizes[i];
  1162. }
  1163. }
  1164. IntVector2 UIElement::GetLayoutChildPosition(UIElement* child)
  1165. {
  1166. IntVector2 ret(IntVector2::ZERO);
  1167. HorizontalAlignment ha = child->GetHorizontalAlignment();
  1168. switch (ha)
  1169. {
  1170. case HA_LEFT:
  1171. ret.x_ = layoutBorder_.left_;
  1172. break;
  1173. case HA_RIGHT:
  1174. ret.x_ = -layoutBorder_.right_;
  1175. break;
  1176. default:
  1177. break;
  1178. }
  1179. VerticalAlignment va = child->GetVerticalAlignment();
  1180. switch (va)
  1181. {
  1182. case VA_TOP:
  1183. ret.y_ = layoutBorder_.top_;
  1184. break;
  1185. case VA_BOTTOM:
  1186. ret.y_ = -layoutBorder_.bottom_;
  1187. break;
  1188. default:
  1189. break;
  1190. }
  1191. return ret;
  1192. }
  1193. void UIElement::Detach()
  1194. {
  1195. parent_ = 0;
  1196. MarkDirty();
  1197. }
  1198. }