BsGUIManager.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. #include "BsGUIManager.h"
  2. #include "BsGUIWidget.h"
  3. #include "BsGUIElement.h"
  4. #include "BsImageSprite.h"
  5. #include "BsSpriteTexture.h"
  6. #include "CmTime.h"
  7. #include "CmSceneObject.h"
  8. #include "CmMaterial.h"
  9. #include "CmMeshData.h"
  10. #include "CmVertexDataDesc.h"
  11. #include "CmMesh.h"
  12. #include "CmUtil.h"
  13. #include "CmRenderWindowManager.h"
  14. #include "CmPlatform.h"
  15. #include "CmRectI.h"
  16. #include "CmApplication.h"
  17. #include "CmException.h"
  18. #include "CmInput.h"
  19. #include "CmPass.h"
  20. #include "CmDebug.h"
  21. #include "CmRenderQueue.h"
  22. #include "BsGUIInputCaret.h"
  23. #include "BsGUIInputSelection.h"
  24. #include "BsGUIListBox.h"
  25. #include "BsGUIButton.h"
  26. #include "BsGUIDropDownBox.h"
  27. #include "BsGUIContextMenu.h"
  28. #include "BsDragAndDropManager.h"
  29. #include "BsGUIDropDownBoxManager.h"
  30. #include "BsGUIContextMenu.h"
  31. #include "CmProfiler.h"
  32. #include "CmMeshHeap.h"
  33. #include "CmTransientMesh.h"
  34. #include "BsVirtualInput.h"
  35. #include "BsCursor.h"
  36. using namespace CamelotFramework;
  37. using namespace std::placeholders;
  38. namespace BansheeEngine
  39. {
  40. struct GUIGroupElement
  41. {
  42. GUIGroupElement()
  43. { }
  44. GUIGroupElement(GUIElement* _element, UINT32 _renderElement)
  45. :element(_element), renderElement(_renderElement)
  46. { }
  47. GUIElement* element;
  48. UINT32 renderElement;
  49. };
  50. struct GUIMaterialGroup
  51. {
  52. GUIMaterialInfo matInfo;
  53. UINT32 numQuads;
  54. UINT32 depth;
  55. RectI bounds;
  56. Vector<GUIGroupElement>::type elements;
  57. };
  58. const UINT32 GUIManager::DRAG_DISTANCE = 3;
  59. const UINT32 GUIManager::MESH_HEAP_INITIAL_NUM_VERTS = 16384;
  60. const UINT32 GUIManager::MESH_HEAP_INITIAL_NUM_INDICES = 49152;
  61. GUIManager::GUIManager()
  62. :mSeparateMeshesByWidget(true), mActiveMouseButton(GUIMouseButton::Left),
  63. mCaretBlinkInterval(0.5f), mCaretLastBlinkTime(0.0f), mCaretColor(1.0f, 0.6588f, 0.0f), mIsCaretOn(false),
  64. mTextSelectionColor(1.0f, 0.6588f, 0.0f), mInputCaret(nullptr), mInputSelection(nullptr), mDragState(DragState::NoDrag),
  65. mActiveCursor(CursorType::Arrow)
  66. {
  67. mOnCursorMovedConn = gInput().onCursorMoved.connect(std::bind(&GUIManager::onCursorMoved, this, _1));
  68. mOnCursorPressedConn = gInput().onCursorPressed.connect(std::bind(&GUIManager::onCursorPressed, this, _1));
  69. mOnCursorReleasedConn = gInput().onCursorReleased.connect(std::bind(&GUIManager::onCursorReleased, this, _1));
  70. mOnCursorDoubleClick = gInput().onDoubleClick.connect(std::bind(&GUIManager::onCursorDoubleClick, this, _1));
  71. mOnTextInputConn = gInput().onCharInput.connect(std::bind(&GUIManager::onTextInput, this, _1));
  72. mOnInputCommandConn = gInput().onInputCommand.connect(std::bind(&GUIManager::onInputCommandEntered, this, _1));
  73. mOnVirtualButtonDown = VirtualInput::instance().onButtonDown.connect(std::bind(&GUIManager::onVirtualButtonDown, this, _1));
  74. mWindowGainedFocusConn = RenderWindowManager::instance().onFocusGained.connect(std::bind(&GUIManager::onWindowFocusGained, this, _1));
  75. mWindowLostFocusConn = RenderWindowManager::instance().onFocusLost.connect(std::bind(&GUIManager::onWindowFocusLost, this, _1));
  76. mMouseLeftWindowConn = Platform::onMouseLeftWindow.connect(std::bind(&GUIManager::onMouseLeftWindow, this, _1));
  77. mInputCaret = cm_new<GUIInputCaret, PoolAlloc>();
  78. mInputSelection = cm_new<GUIInputSelection, PoolAlloc>();
  79. DragAndDropManager::startUp(cm_new<DragAndDropManager>());
  80. mDragEndedConn = DragAndDropManager::instance().onDragEnded.connect(std::bind(&GUIManager::onMouseDragEnded, this, _1));
  81. GUIDropDownBoxManager::startUp(cm_new<GUIDropDownBoxManager>());
  82. mVertexDesc = cm_shared_ptr<VertexDataDesc>();
  83. mVertexDesc->addVertElem(VET_FLOAT2, VES_POSITION);
  84. mVertexDesc->addVertElem(VET_FLOAT2, VES_TEXCOORD);
  85. mMeshHeap = MeshHeap::create(MESH_HEAP_INITIAL_NUM_VERTS, MESH_HEAP_INITIAL_NUM_INDICES, mVertexDesc);
  86. // Need to defer this call because I want to make sure all managers are initialized first
  87. deferredCall(std::bind(&GUIManager::updateCaretTexture, this));
  88. deferredCall(std::bind(&GUIManager::updateTextSelectionTexture, this));
  89. }
  90. GUIManager::~GUIManager()
  91. {
  92. GUIDropDownBoxManager::shutDown();
  93. DragAndDropManager::shutDown();
  94. // Make a copy of widgets, since destroying them will remove them from mWidgets and
  95. // we can't iterate over an array thats getting modified
  96. Vector<WidgetInfo>::type widgetCopy = mWidgets;
  97. for(auto& widget : widgetCopy)
  98. widget.widget->destroy();
  99. mOnCursorPressedConn.disconnect();
  100. mOnCursorReleasedConn.disconnect();
  101. mOnCursorMovedConn.disconnect();
  102. mOnCursorDoubleClick.disconnect();
  103. mOnTextInputConn.disconnect();
  104. mOnInputCommandConn.disconnect();
  105. mOnVirtualButtonDown.disconnect();
  106. mDragEndedConn.disconnect();
  107. mWindowGainedFocusConn.disconnect();
  108. mWindowLostFocusConn.disconnect();
  109. mMouseLeftWindowConn.disconnect();
  110. cm_delete<PoolAlloc>(mInputCaret);
  111. cm_delete<PoolAlloc>(mInputSelection);
  112. }
  113. void GUIManager::registerWidget(GUIWidget* widget)
  114. {
  115. mWidgets.push_back(WidgetInfo(widget));
  116. const Viewport* renderTarget = widget->getTarget();
  117. auto findIter = mCachedGUIData.find(renderTarget);
  118. if(findIter == end(mCachedGUIData))
  119. mCachedGUIData[renderTarget] = GUIRenderData();
  120. GUIRenderData& windowData = mCachedGUIData[renderTarget];
  121. windowData.widgets.push_back(widget);
  122. windowData.isDirty = true;
  123. }
  124. void GUIManager::unregisterWidget(GUIWidget* widget)
  125. {
  126. {
  127. auto findIter = std::find_if(begin(mWidgets), end(mWidgets), [=] (const WidgetInfo& x) { return x.widget == widget; } );
  128. if(findIter != mWidgets.end())
  129. mWidgets.erase(findIter);
  130. }
  131. const Viewport* renderTarget = widget->getTarget();
  132. GUIRenderData& renderData = mCachedGUIData[renderTarget];
  133. {
  134. auto findIter = std::find(begin(renderData.widgets), end(renderData.widgets), widget);
  135. if(findIter != end(renderData.widgets))
  136. renderData.widgets.erase(findIter);
  137. }
  138. if(renderData.widgets.size() == 0)
  139. {
  140. mCachedGUIData.erase(renderTarget);
  141. }
  142. else
  143. renderData.isDirty = true;
  144. }
  145. void GUIManager::update()
  146. {
  147. DragAndDropManager::instance().update();
  148. // Update layouts
  149. gProfiler().beginSample("UpdateLayout");
  150. for(auto& widgetInfo : mWidgets)
  151. {
  152. widgetInfo.widget->_updateLayout();
  153. }
  154. gProfiler().endSample("UpdateLayout");
  155. // Blink caret
  156. float curTime = gTime().getTime();
  157. if((curTime - mCaretLastBlinkTime) >= mCaretBlinkInterval)
  158. {
  159. mCaretLastBlinkTime = curTime;
  160. mIsCaretOn = !mIsCaretOn;
  161. mCommandEvent = GUICommandEvent();
  162. mCommandEvent.setType(GUICommandEventType::Redraw);
  163. for(auto& elementInfo : mElementsInFocus)
  164. {
  165. sendCommandEvent(elementInfo.widget, elementInfo.element, mCommandEvent);
  166. }
  167. }
  168. PROFILE_CALL(updateMeshes(), "UpdateMeshes");
  169. mNewElementsUnderCursor.clear();
  170. for(auto& elementInfo : mElementsUnderCursor)
  171. {
  172. if(!elementInfo.element->_isDestroyed())
  173. mNewElementsUnderCursor.push_back(elementInfo);
  174. }
  175. mElementsUnderCursor.swap(mNewElementsUnderCursor);
  176. mNewActiveElements.clear();
  177. for(auto& elementInfo : mActiveElements)
  178. {
  179. if(!elementInfo.element->_isDestroyed())
  180. mNewActiveElements.push_back(elementInfo);
  181. }
  182. mActiveElements.swap(mNewActiveElements);
  183. mNewElementsInFocus.clear();
  184. for(auto& elementInfo : mElementsInFocus)
  185. {
  186. if(!elementInfo.element->_isDestroyed())
  187. mNewElementsInFocus.push_back(elementInfo);
  188. }
  189. mElementsInFocus.swap(mNewElementsInFocus);
  190. for(auto& focusElementInfo : mForcedFocusElements)
  191. {
  192. if(focusElementInfo.element->_isDestroyed())
  193. continue;
  194. if(focusElementInfo.focus)
  195. {
  196. auto iterFind = std::find_if(mElementsInFocus.begin(), mElementsInFocus.end(),
  197. [&](const ElementInfo& x) { return x.element == focusElementInfo.element; });
  198. if(iterFind == mElementsInFocus.end())
  199. {
  200. mElementsInFocus.push_back(ElementInfo(focusElementInfo.element, focusElementInfo.element->_getParentWidget()));
  201. mCommandEvent = GUICommandEvent();
  202. mCommandEvent.setType(GUICommandEventType::FocusGained);
  203. sendCommandEvent(focusElementInfo.element->_getParentWidget(), focusElementInfo.element, mCommandEvent);
  204. }
  205. }
  206. else
  207. {
  208. mNewElementsInFocus.clear();
  209. for(auto& elementInfo : mElementsInFocus)
  210. {
  211. if(elementInfo.element == focusElementInfo.element)
  212. {
  213. mCommandEvent = GUICommandEvent();
  214. mCommandEvent.setType(GUICommandEventType::FocusLost);
  215. sendCommandEvent(elementInfo.widget, elementInfo.element, mCommandEvent);
  216. }
  217. else
  218. mNewElementsInFocus.push_back(elementInfo);
  219. }
  220. mElementsInFocus.swap(mNewElementsInFocus);
  221. }
  222. }
  223. mForcedFocusElements.clear();
  224. processDestroyQueue();
  225. }
  226. void GUIManager::render(ViewportPtr& target, CM::RenderQueue& renderQueue) const
  227. {
  228. auto findIter = mCachedGUIData.find(target.get());
  229. if(findIter == mCachedGUIData.end())
  230. return;
  231. const GUIRenderData& renderData = findIter->second;
  232. // Render the meshes
  233. if(mSeparateMeshesByWidget)
  234. {
  235. // TODO - Possible optimization. I currently divide by width/height inside the shader, while it
  236. // might be more optimal to just scale the mesh as the resolution changes?
  237. float invViewportWidth = 1.0f / (target->getWidth() * 0.5f);
  238. float invViewportHeight = 1.0f / (target->getHeight() * 0.5f);
  239. UINT32 meshIdx = 0;
  240. for(auto& mesh : renderData.cachedMeshes)
  241. {
  242. GUIMaterialInfo materialInfo = renderData.cachedMaterials[meshIdx];
  243. GUIWidget* widget = renderData.cachedWidgetsPerMesh[meshIdx];
  244. if(materialInfo.material == nullptr || !materialInfo.material.isLoaded())
  245. {
  246. meshIdx++;
  247. continue;
  248. }
  249. if(mesh == nullptr)
  250. {
  251. meshIdx++;
  252. continue;
  253. }
  254. materialInfo.invViewportWidth.set(invViewportWidth);
  255. materialInfo.invViewportHeight.set(invViewportHeight);
  256. materialInfo.worldTransform.set(widget->SO()->getWorldTfrm());
  257. renderQueue.add(materialInfo.material.getInternalPtr(), mesh, 0, Vector3::ZERO);
  258. meshIdx++;
  259. }
  260. }
  261. else
  262. {
  263. // TODO: I want to avoid separating meshes by widget in the future. On DX11 and GL I can set up a shader
  264. // that accepts multiple world transforms (one for each widget). Then I can add some instance information to vertices
  265. // and render elements using multiple different transforms with a single call.
  266. // Separating meshes can then be used as a compatibility mode for DX9
  267. CM_EXCEPT(NotImplementedException, "Not implemented");
  268. }
  269. }
  270. void GUIManager::updateMeshes()
  271. {
  272. for(auto& cachedMeshData : mCachedGUIData)
  273. {
  274. GUIRenderData& renderData = cachedMeshData.second;
  275. gProfiler().beginSample("UM_A");
  276. // Check if anything is dirty. If nothing is we can skip the update
  277. bool isDirty = renderData.isDirty;
  278. renderData.isDirty = false;
  279. for(auto& widget : renderData.widgets)
  280. {
  281. if(widget->isDirty(true))
  282. {
  283. isDirty = true;
  284. }
  285. }
  286. gProfiler().endSample("UM_A");
  287. if(!isDirty)
  288. continue;
  289. // Make a list of all GUI elements, sorted from farthest to nearest (highest depth to lowest)
  290. auto elemComp = [](const GUIGroupElement& a, const GUIGroupElement& b)
  291. {
  292. UINT32 aDepth = a.element->_getRenderElementDepth(a.renderElement);
  293. UINT32 bDepth = b.element->_getRenderElementDepth(b.renderElement);
  294. // Compare pointers just to differentiate between two elements with the same depth, their order doesn't really matter, but std::set
  295. // requires all elements to be unique
  296. return (aDepth > bDepth) ||
  297. (aDepth == bDepth && a.element > b.element) ||
  298. (aDepth == bDepth && a.element == b.element && a.renderElement > b.renderElement);
  299. };
  300. Set<GUIGroupElement, std::function<bool(const GUIGroupElement&, const GUIGroupElement&)>>::type allElements(elemComp);
  301. for(auto& widget : renderData.widgets)
  302. {
  303. const Vector<GUIElement*>::type& elements = widget->getElements();
  304. for(auto& element : elements)
  305. {
  306. if(element->_isDisabled())
  307. continue;
  308. UINT32 numRenderElems = element->getNumRenderElements();
  309. for(UINT32 i = 0; i < numRenderElems; i++)
  310. {
  311. allElements.insert(GUIGroupElement(element, i));
  312. }
  313. }
  314. }
  315. // Group the elements in such a way so that we end up with a smallest amount of
  316. // meshes, without breaking back to front rendering order
  317. UnorderedMap<UINT64, Vector<GUIMaterialGroup>::type>::type materialGroups;
  318. for(auto& elem : allElements)
  319. {
  320. GUIElement* guiElem = elem.element;
  321. UINT32 renderElemIdx = elem.renderElement;
  322. UINT32 elemDepth = guiElem->_getRenderElementDepth(renderElemIdx);
  323. RectI tfrmedBounds = guiElem->_getClippedBounds();
  324. tfrmedBounds.transform(guiElem->_getParentWidget()->SO()->getWorldTfrm());
  325. const GUIMaterialInfo& matInfo = guiElem->getMaterial(renderElemIdx);
  326. UINT64 materialId = matInfo.material->getInternalID(); // TODO - I group based on material ID. So if two widgets used exact copies of the same material
  327. // this system won't detect it. Find a better way of determining material similarity?
  328. // If this is a new material, add a new list of groups
  329. auto findIterMaterial = materialGroups.find(materialId);
  330. if(findIterMaterial == end(materialGroups))
  331. materialGroups[materialId] = Vector<GUIMaterialGroup>::type();
  332. // Try to find a group this material will fit in:
  333. // - Group that has a depth value same or one below elements depth will always be a match
  334. // - Otherwise, we search higher depth values as well, but we only use them if no elements in between those depth values
  335. // overlap the current elements bounds.
  336. Vector<GUIMaterialGroup>::type& allGroups = materialGroups[materialId];
  337. GUIMaterialGroup* foundGroup = nullptr;
  338. for(auto groupIter = allGroups.rbegin(); groupIter != allGroups.rend(); ++groupIter)
  339. {
  340. // If we separate meshes by widget, ignore any groups with widget parents other than mine
  341. if(mSeparateMeshesByWidget)
  342. {
  343. if(groupIter->elements.size() > 0)
  344. {
  345. GUIElement* otherElem = groupIter->elements.begin()->element; // We only need to check the first element
  346. if(otherElem->_getParentWidget() != guiElem->_getParentWidget())
  347. continue;
  348. }
  349. }
  350. GUIMaterialGroup& group = *groupIter;
  351. if(group.depth == elemDepth || group.depth == (elemDepth - 1))
  352. {
  353. foundGroup = &group;
  354. break;
  355. }
  356. else
  357. {
  358. UINT32 startDepth = elemDepth;
  359. UINT32 endDepth = group.depth;
  360. RectI potentialGroupBounds = group.bounds;
  361. potentialGroupBounds.encapsulate(tfrmedBounds);
  362. bool foundOverlap = false;
  363. for(auto& material : materialGroups)
  364. {
  365. for(auto& matGroup : material.second)
  366. {
  367. if(&matGroup == &group)
  368. continue;
  369. if(matGroup.depth > startDepth && matGroup.depth < endDepth)
  370. {
  371. if(matGroup.bounds.overlaps(potentialGroupBounds))
  372. {
  373. foundOverlap = true;
  374. break;
  375. }
  376. }
  377. }
  378. }
  379. if(!foundOverlap)
  380. {
  381. foundGroup = &group;
  382. break;
  383. }
  384. }
  385. }
  386. if(foundGroup == nullptr)
  387. {
  388. allGroups.push_back(GUIMaterialGroup());
  389. foundGroup = &allGroups[allGroups.size() - 1];
  390. foundGroup->depth = elemDepth;
  391. foundGroup->bounds = tfrmedBounds;
  392. foundGroup->elements.push_back(GUIGroupElement(guiElem, renderElemIdx));
  393. foundGroup->matInfo = matInfo;
  394. foundGroup->numQuads = guiElem->getNumQuads(renderElemIdx);
  395. }
  396. else
  397. {
  398. foundGroup->bounds.encapsulate(tfrmedBounds);
  399. foundGroup->elements.push_back(GUIGroupElement(guiElem, renderElemIdx));
  400. foundGroup->depth = std::min(foundGroup->depth, elemDepth);
  401. foundGroup->numQuads += guiElem->getNumQuads(renderElemIdx);
  402. }
  403. }
  404. // Make a list of all GUI elements, sorted from farthest to nearest (highest depth to lowest)
  405. auto groupComp = [](GUIMaterialGroup* a, GUIMaterialGroup* b)
  406. {
  407. return (a->depth > b->depth) || (a->depth == b->depth && a > b);
  408. // Compare pointers just to differentiate between two elements with the same depth, their order doesn't really matter, but std::set
  409. // requires all elements to be unique
  410. };
  411. Set<GUIMaterialGroup*, std::function<bool(GUIMaterialGroup*, GUIMaterialGroup*)>>::type sortedGroups(groupComp);
  412. for(auto& material : materialGroups)
  413. {
  414. for(auto& group : material.second)
  415. {
  416. sortedGroups.insert(&group);
  417. }
  418. }
  419. UINT32 numMeshes = (UINT32)sortedGroups.size();
  420. UINT32 oldNumMeshes = (UINT32)renderData.cachedMeshes.size();
  421. if(numMeshes < oldNumMeshes)
  422. {
  423. renderData.cachedMeshes.resize(numMeshes);
  424. }
  425. renderData.cachedMaterials.resize(numMeshes);
  426. if(mSeparateMeshesByWidget)
  427. renderData.cachedWidgetsPerMesh.resize(numMeshes);
  428. // Fill buffers for each group and update their meshes
  429. UINT32 groupIdx = 0;
  430. for(auto& group : sortedGroups)
  431. {
  432. renderData.cachedMaterials[groupIdx] = group->matInfo;
  433. if(mSeparateMeshesByWidget)
  434. {
  435. if(group->elements.size() == 0)
  436. renderData.cachedWidgetsPerMesh[groupIdx] = nullptr;
  437. else
  438. {
  439. GUIElement* elem = group->elements.begin()->element;
  440. renderData.cachedWidgetsPerMesh[groupIdx] = elem->_getParentWidget();
  441. }
  442. }
  443. MeshDataPtr meshData = cm_shared_ptr<MeshData, PoolAlloc>(group->numQuads * 4, group->numQuads * 6, mVertexDesc);
  444. UINT8* vertices = meshData->getElementData(VES_POSITION);
  445. UINT8* uvs = meshData->getElementData(VES_TEXCOORD);
  446. UINT32* indices = meshData->getIndices32();
  447. UINT32 vertexStride = meshData->getVertexDesc()->getVertexStride();
  448. UINT32 indexStride = meshData->getIndexElementSize();
  449. UINT32 quadOffset = 0;
  450. for(auto& matElement : group->elements)
  451. {
  452. matElement.element->fillBuffer(vertices, uvs, indices, quadOffset, group->numQuads, vertexStride, indexStride, matElement.renderElement);
  453. UINT32 numQuads = matElement.element->getNumQuads(matElement.renderElement);
  454. UINT32 indexStart = quadOffset * 6;
  455. UINT32 indexEnd = indexStart + numQuads * 6;
  456. UINT32 vertOffset = quadOffset * 4;
  457. for(UINT32 i = indexStart; i < indexEnd; i++)
  458. indices[i] += vertOffset;
  459. quadOffset += numQuads;
  460. }
  461. if(groupIdx < (UINT32)renderData.cachedMeshes.size())
  462. {
  463. mMeshHeap->dealloc(renderData.cachedMeshes[groupIdx]);
  464. renderData.cachedMeshes[groupIdx] = mMeshHeap->alloc(meshData);
  465. }
  466. else
  467. {
  468. renderData.cachedMeshes.push_back(mMeshHeap->alloc(meshData));
  469. }
  470. groupIdx++;
  471. }
  472. }
  473. }
  474. void GUIManager::updateCaretTexture()
  475. {
  476. if(mCaretTexture == nullptr)
  477. {
  478. HTexture newTex = Texture::create(TEX_TYPE_2D, 1, 1, 0, PF_R8G8B8A8);
  479. newTex->synchronize(); // TODO - Required due to a bug in allocateSubresourceBuffer
  480. mCaretTexture = SpriteTexture::create(newTex);
  481. }
  482. const HTexture& tex = mCaretTexture->getTexture();
  483. UINT32 subresourceIdx = tex->mapToSubresourceIdx(0, 0);
  484. PixelDataPtr data = tex->allocateSubresourceBuffer(subresourceIdx);
  485. data->setColorAt(mCaretColor, 0, 0);
  486. gCoreAccessor().writeSubresource(tex.getInternalPtr(), tex->mapToSubresourceIdx(0, 0), data);
  487. }
  488. void GUIManager::updateTextSelectionTexture()
  489. {
  490. if(mTextSelectionTexture == nullptr)
  491. {
  492. HTexture newTex = Texture::create(TEX_TYPE_2D, 1, 1, 0, PF_R8G8B8A8);
  493. newTex->synchronize(); // TODO - Required due to a bug in allocateSubresourceBuffer
  494. mTextSelectionTexture = SpriteTexture::create(newTex);
  495. }
  496. const HTexture& tex = mTextSelectionTexture->getTexture();
  497. UINT32 subresourceIdx = tex->mapToSubresourceIdx(0, 0);
  498. PixelDataPtr data = tex->allocateSubresourceBuffer(subresourceIdx);
  499. data->setColorAt(mTextSelectionColor, 0, 0);
  500. gCoreAccessor().writeSubresource(tex.getInternalPtr(), tex->mapToSubresourceIdx(0, 0), data);
  501. }
  502. bool GUIManager::onMouseDragEnded(const CM::PositionalInputEvent& event)
  503. {
  504. GUIMouseButton guiButton = buttonToGUIButton(event.button);
  505. if(DragAndDropManager::instance().isDragInProgress() && guiButton == GUIMouseButton::Left)
  506. {
  507. for(auto& elementInfo : mElementsUnderCursor)
  508. {
  509. Vector2I localPos;
  510. if(elementInfo.widget != nullptr)
  511. localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  512. bool acceptDrop = true;
  513. if(DragAndDropManager::instance().needsValidDropTarget())
  514. {
  515. acceptDrop = elementInfo.element->_acceptDragAndDrop(localPos, DragAndDropManager::instance().getDragTypeId());
  516. }
  517. if(acceptDrop)
  518. {
  519. mMouseEvent.setDragAndDropDroppedData(localPos, DragAndDropManager::instance().getDragTypeId(), DragAndDropManager::instance().getDragData());
  520. bool processed = sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent);
  521. if(processed)
  522. return true;
  523. }
  524. }
  525. }
  526. return false;
  527. }
  528. void GUIManager::onCursorMoved(const PositionalInputEvent& event)
  529. {
  530. if(event.isUsed())
  531. return;
  532. bool buttonStates[(int)GUIMouseButton::Count];
  533. buttonStates[0] = event.buttonStates[0];
  534. buttonStates[1] = event.buttonStates[1];
  535. buttonStates[2] = event.buttonStates[2];
  536. if(findElementUnderCursor(event.screenPos, buttonStates, event.shift, event.control, event.alt))
  537. event.markAsUsed();
  538. if(mDragState == DragState::HeldWithoutDrag)
  539. {
  540. UINT32 dist = mLastCursorClickPos.manhattanDist(event.screenPos);
  541. if(dist > DRAG_DISTANCE)
  542. {
  543. for(auto& activeElement : mActiveElements)
  544. {
  545. Vector2I localPos = getWidgetRelativePos(*activeElement.widget, event.screenPos);
  546. mMouseEvent.setMouseDragStartData(localPos);
  547. if(sendMouseEvent(activeElement.widget, activeElement.element, mMouseEvent))
  548. event.markAsUsed();
  549. }
  550. mDragState = DragState::Dragging;
  551. }
  552. }
  553. // If mouse is being held down send MouseDrag events
  554. if(mDragState == DragState::Dragging)
  555. {
  556. for(auto& activeElement : mActiveElements)
  557. {
  558. if(mLastCursorScreenPos != event.screenPos)
  559. {
  560. Vector2I localPos = getWidgetRelativePos(*activeElement.widget, event.screenPos);
  561. mMouseEvent.setMouseDragData(localPos, localPos - mLastCursorScreenPos);
  562. if(sendMouseEvent(activeElement.widget, activeElement.element, mMouseEvent))
  563. event.markAsUsed();
  564. }
  565. }
  566. mLastCursorScreenPos = event.screenPos;
  567. // Also if drag is in progress send DragAndDrop events
  568. if(DragAndDropManager::instance().isDragInProgress())
  569. {
  570. bool acceptDrop = true;
  571. for(auto& elementInfo : mElementsUnderCursor)
  572. {
  573. Vector2I localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  574. acceptDrop = true;
  575. if(DragAndDropManager::instance().needsValidDropTarget())
  576. {
  577. acceptDrop = elementInfo.element->_acceptDragAndDrop(localPos, DragAndDropManager::instance().getDragTypeId());
  578. }
  579. if(acceptDrop)
  580. {
  581. mMouseEvent.setDragAndDropDraggedData(localPos, DragAndDropManager::instance().getDragTypeId(), DragAndDropManager::instance().getDragData());
  582. if(sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent))
  583. {
  584. event.markAsUsed();
  585. break;
  586. }
  587. }
  588. }
  589. if(acceptDrop)
  590. {
  591. if(mActiveCursor != CursorType::ArrowDrag)
  592. {
  593. Cursor::instance().setCursor(CursorType::ArrowDrag);
  594. mActiveCursor = CursorType::ArrowDrag;
  595. }
  596. }
  597. else
  598. {
  599. if(mActiveCursor != CursorType::Deny)
  600. {
  601. Cursor::instance().setCursor(CursorType::Deny);
  602. mActiveCursor = CursorType::Deny;
  603. }
  604. }
  605. }
  606. }
  607. else // Otherwise, send MouseMove events if we are hovering over any element
  608. {
  609. if(mLastCursorScreenPos != event.screenPos)
  610. {
  611. bool moveProcessed = false;
  612. bool hasCustomCursor = false;
  613. for(auto& elementInfo : mElementsUnderCursor)
  614. {
  615. Vector2I localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  616. if(!moveProcessed)
  617. {
  618. // Send MouseMove event
  619. mMouseEvent.setMouseMoveData(localPos);
  620. moveProcessed = sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent);
  621. if(moveProcessed)
  622. {
  623. event.markAsUsed();
  624. break;
  625. }
  626. }
  627. if(!hasCustomCursor)
  628. {
  629. CursorType newCursor = CursorType::Arrow;
  630. if(elementInfo.element->_hasCustomCursor(localPos, newCursor))
  631. {
  632. if(newCursor != mActiveCursor)
  633. {
  634. Cursor::instance().setCursor(newCursor);
  635. mActiveCursor = newCursor;
  636. }
  637. hasCustomCursor = true;
  638. }
  639. }
  640. if(moveProcessed && hasCustomCursor)
  641. break;
  642. }
  643. if(!hasCustomCursor)
  644. {
  645. if(mActiveCursor != CursorType::Arrow)
  646. {
  647. Cursor::instance().setCursor(CursorType::Arrow);
  648. mActiveCursor = CursorType::Arrow;
  649. }
  650. }
  651. }
  652. mLastCursorScreenPos = event.screenPos;
  653. if(Math::abs(event.mouseWheelScrollAmount) > 0.00001f)
  654. {
  655. for(auto& elementInfo : mElementsUnderCursor)
  656. {
  657. mMouseEvent.setMouseWheelScrollData(event.mouseWheelScrollAmount);
  658. if(sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent))
  659. {
  660. event.markAsUsed();
  661. break;
  662. }
  663. }
  664. }
  665. }
  666. }
  667. void GUIManager::onCursorReleased(const CM::PositionalInputEvent& event)
  668. {
  669. if(event.isUsed())
  670. return;
  671. bool buttonStates[(int)GUIMouseButton::Count];
  672. buttonStates[0] = event.buttonStates[0];
  673. buttonStates[1] = event.buttonStates[1];
  674. buttonStates[2] = event.buttonStates[2];
  675. if(findElementUnderCursor(event.screenPos, buttonStates, event.shift, event.control, event.alt))
  676. event.markAsUsed();
  677. mMouseEvent = GUIMouseEvent(buttonStates, event.shift, event.control, event.alt);
  678. GUIMouseButton guiButton = buttonToGUIButton(event.button);
  679. // Send MouseUp event only if we are over the active element (we don't want to accidentally trigger other elements).
  680. // And only activate when a button that originally caused the active state is released, otherwise ignore it.
  681. if(mActiveMouseButton == guiButton)
  682. {
  683. for(auto& elementInfo : mElementsUnderCursor)
  684. {
  685. auto iterFind2 = std::find_if(mActiveElements.begin(), mActiveElements.end(),
  686. [&](const ElementInfo& x) { return x.element == elementInfo.element; });
  687. if(iterFind2 != mActiveElements.end())
  688. {
  689. Vector2I localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  690. mMouseEvent.setMouseUpData(localPos, guiButton);
  691. if(sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent))
  692. {
  693. event.markAsUsed();
  694. break;
  695. }
  696. }
  697. }
  698. }
  699. // Send DragEnd event to whichever element is active
  700. bool acceptEndDrag = (mDragState == DragState::Dragging || mDragState == DragState::HeldWithoutDrag) && mActiveMouseButton == guiButton &&
  701. (guiButton == GUIMouseButton::Left);
  702. if(acceptEndDrag)
  703. {
  704. if(mDragState == DragState::Dragging)
  705. {
  706. for(auto& activeElement : mActiveElements)
  707. {
  708. Vector2I localPos = getWidgetRelativePos(*activeElement.widget, event.screenPos);
  709. mMouseEvent.setMouseDragEndData(localPos);
  710. if(sendMouseEvent(activeElement.widget, activeElement.element, mMouseEvent))
  711. event.markAsUsed();
  712. }
  713. }
  714. mDragState = DragState::NoDrag;
  715. }
  716. if(mActiveMouseButton == guiButton)
  717. {
  718. mActiveElements.clear();
  719. mActiveMouseButton = GUIMouseButton::Left;
  720. }
  721. if(mActiveCursor != CursorType::Arrow)
  722. {
  723. Cursor::instance().setCursor(CursorType::Arrow);
  724. mActiveCursor = CursorType::Arrow;
  725. }
  726. }
  727. void GUIManager::onCursorPressed(const CM::PositionalInputEvent& event)
  728. {
  729. if(event.isUsed())
  730. return;
  731. bool buttonStates[(int)GUIMouseButton::Count];
  732. buttonStates[0] = event.buttonStates[0];
  733. buttonStates[1] = event.buttonStates[1];
  734. buttonStates[2] = event.buttonStates[2];
  735. if(findElementUnderCursor(event.screenPos, buttonStates, event.shift, event.control, event.alt))
  736. event.markAsUsed();
  737. mMouseEvent = GUIMouseEvent(buttonStates, event.shift, event.control, event.alt);
  738. GUIMouseButton guiButton = buttonToGUIButton(event.button);
  739. // We only check for mouse down if mouse isn't already being held down, and we are hovering over an element
  740. if(mActiveElements.size() == 0)
  741. {
  742. mNewActiveElements.clear();
  743. for(auto& elementInfo : mElementsUnderCursor)
  744. {
  745. Vector2I localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  746. mMouseEvent.setMouseDownData(localPos, guiButton);
  747. bool processed = sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent);
  748. if(guiButton == GUIMouseButton::Left)
  749. {
  750. mDragState = DragState::HeldWithoutDrag;
  751. mLastCursorClickPos = event.screenPos;
  752. }
  753. mNewActiveElements.push_back(ElementInfo(elementInfo.element, elementInfo.widget));
  754. mActiveMouseButton = guiButton;
  755. if(processed)
  756. {
  757. event.markAsUsed();
  758. break;
  759. }
  760. }
  761. mActiveElements.swap(mNewActiveElements);
  762. }
  763. mNewElementsInFocus.clear();
  764. mCommandEvent = GUICommandEvent();
  765. // Determine elements that gained focus
  766. mCommandEvent.setType(GUICommandEventType::FocusGained);
  767. for(auto& elementInfo : mElementsUnderCursor)
  768. {
  769. mNewElementsInFocus.push_back(elementInfo);
  770. auto iterFind = std::find_if(begin(mElementsInFocus), end(mElementsInFocus),
  771. [=] (const ElementInfo& x) { return x.element == elementInfo.element; });
  772. if(iterFind == mElementsInFocus.end())
  773. {
  774. sendCommandEvent(elementInfo.widget, elementInfo.element, mCommandEvent);
  775. }
  776. }
  777. // Determine elements that lost focus
  778. mCommandEvent.setType(GUICommandEventType::FocusLost);
  779. for(auto& elementInfo : mElementsInFocus)
  780. {
  781. auto iterFind = std::find_if(begin(mNewElementsInFocus), end(mNewElementsInFocus),
  782. [=] (const ElementInfo& x) { return x.element == elementInfo.element; });
  783. if(iterFind == mNewElementsInFocus.end())
  784. {
  785. sendCommandEvent(elementInfo.widget, elementInfo.element, mCommandEvent);
  786. }
  787. }
  788. if(mElementsUnderCursor.size() > 0)
  789. event.markAsUsed();
  790. mElementsInFocus.swap(mNewElementsInFocus);
  791. // If right click try to open context menu
  792. if(buttonStates[2] == true)
  793. {
  794. for(auto& elementInfo : mElementsUnderCursor)
  795. {
  796. GUIContextMenu* menu = elementInfo.element->getContextMenu();
  797. if(menu != nullptr)
  798. {
  799. const RenderWindow* window = getWidgetWindow(*elementInfo.widget);
  800. Vector2I windowPos = window->screenToWindowPos(event.screenPos);
  801. menu->open(windowPos, *elementInfo.widget);
  802. event.markAsUsed();
  803. break;
  804. }
  805. }
  806. }
  807. }
  808. void GUIManager::onCursorDoubleClick(const CM::PositionalInputEvent& event)
  809. {
  810. if(event.isUsed())
  811. return;
  812. bool buttonStates[(int)GUIMouseButton::Count];
  813. buttonStates[0] = event.buttonStates[0];
  814. buttonStates[1] = event.buttonStates[1];
  815. buttonStates[2] = event.buttonStates[2];
  816. if(findElementUnderCursor(event.screenPos, buttonStates, event.shift, event.control, event.alt))
  817. event.markAsUsed();
  818. mMouseEvent = GUIMouseEvent(buttonStates, event.shift, event.control, event.alt);
  819. GUIMouseButton guiButton = buttonToGUIButton(event.button);
  820. // We only check for mouse down if we are hovering over an element
  821. for(auto& elementInfo : mElementsUnderCursor)
  822. {
  823. Vector2I localPos = getWidgetRelativePos(*elementInfo.widget, event.screenPos);
  824. mMouseEvent.setMouseDoubleClickData(localPos, guiButton);
  825. if(sendMouseEvent(elementInfo.widget, elementInfo.element, mMouseEvent))
  826. {
  827. event.markAsUsed();
  828. break;
  829. }
  830. }
  831. }
  832. void GUIManager::onInputCommandEntered(CM::InputCommandType commandType)
  833. {
  834. if(mElementsInFocus.size() == 0)
  835. return;
  836. mCommandEvent = GUICommandEvent();
  837. switch(commandType)
  838. {
  839. case InputCommandType::Backspace:
  840. mCommandEvent.setType(GUICommandEventType::Backspace);
  841. break;
  842. case InputCommandType::Delete:
  843. mCommandEvent.setType(GUICommandEventType::Delete);
  844. break;
  845. case InputCommandType::Return:
  846. mCommandEvent.setType(GUICommandEventType::Return);
  847. break;
  848. case InputCommandType::Escape:
  849. mCommandEvent.setType(GUICommandEventType::Escape);
  850. break;
  851. case InputCommandType::CursorMoveLeft:
  852. mCommandEvent.setType(GUICommandEventType::MoveLeft);
  853. break;
  854. case InputCommandType::CursorMoveRight:
  855. mCommandEvent.setType(GUICommandEventType::MoveRight);
  856. break;
  857. case InputCommandType::CursorMoveUp:
  858. mCommandEvent.setType(GUICommandEventType::MoveUp);
  859. break;
  860. case InputCommandType::CursorMoveDown:
  861. mCommandEvent.setType(GUICommandEventType::MoveDown);
  862. break;
  863. case InputCommandType::SelectLeft:
  864. mCommandEvent.setType(GUICommandEventType::SelectLeft);
  865. break;
  866. case InputCommandType::SelectRight:
  867. mCommandEvent.setType(GUICommandEventType::SelectRight);
  868. break;
  869. case InputCommandType::SelectUp:
  870. mCommandEvent.setType(GUICommandEventType::SelectUp);
  871. break;
  872. case InputCommandType::SelectDown:
  873. mCommandEvent.setType(GUICommandEventType::SelectDown);
  874. break;
  875. }
  876. for(auto& elementInfo : mElementsInFocus)
  877. {
  878. sendCommandEvent(elementInfo.widget, elementInfo.element, mCommandEvent);
  879. }
  880. }
  881. void GUIManager::onVirtualButtonDown(const VirtualButton& button)
  882. {
  883. mVirtualButtonEvent.setButton(button);
  884. for(auto& elementInFocus : mElementsInFocus)
  885. {
  886. bool processed = sendVirtualButtonEvent(elementInFocus.widget, elementInFocus.element, mVirtualButtonEvent);
  887. if(processed)
  888. break;
  889. }
  890. }
  891. bool GUIManager::findElementUnderCursor(const CM::Vector2I& cursorScreenPos, bool buttonStates[3], bool shift, bool control, bool alt)
  892. {
  893. Vector<const RenderWindow*>::type widgetWindows;
  894. for(auto& widgetInfo : mWidgets)
  895. widgetWindows.push_back(getWidgetWindow(*widgetInfo.widget));
  896. #if CM_DEBUG_MODE
  897. // Checks if all referenced windows actually exist
  898. Vector<RenderWindow*>::type activeWindows = RenderWindowManager::instance().getRenderWindows();
  899. for(auto& window : widgetWindows)
  900. {
  901. if(window == nullptr)
  902. continue;
  903. auto iterFind = std::find(begin(activeWindows), end(activeWindows), window);
  904. if(iterFind == activeWindows.end())
  905. {
  906. CM_EXCEPT(InternalErrorException, "GUI manager has a reference to a window that doesn't exist. \
  907. Please detach all GUIWidgets from windows before destroying a window.");
  908. }
  909. }
  910. #endif
  911. mNewElementsUnderCursor.clear();
  912. const RenderWindow* windowUnderCursor = nullptr;
  913. UnorderedSet<const RenderWindow*>::type uniqueWindows;
  914. for(auto& window : widgetWindows)
  915. {
  916. if(window == nullptr)
  917. continue;
  918. uniqueWindows.insert(window);
  919. }
  920. for(auto& window : uniqueWindows)
  921. {
  922. if(Platform::isPointOverWindow(*window, cursorScreenPos))
  923. {
  924. windowUnderCursor = window;
  925. break;
  926. }
  927. }
  928. if(windowUnderCursor != nullptr)
  929. {
  930. Vector2I windowPos = windowUnderCursor->screenToWindowPos(cursorScreenPos);
  931. Vector4 vecWindowPos((float)windowPos.x, (float)windowPos.y, 0.0f, 1.0f);
  932. UINT32 widgetIdx = 0;
  933. for(auto& widgetInfo : mWidgets)
  934. {
  935. if(widgetWindows[widgetIdx] == nullptr)
  936. {
  937. widgetIdx++;
  938. continue;
  939. }
  940. GUIWidget* widget = widgetInfo.widget;
  941. if(widgetWindows[widgetIdx] == windowUnderCursor && widget->inBounds(windowToBridgedCoords(*widget, windowPos)))
  942. {
  943. const Vector<GUIElement*>::type& elements = widget->getElements();
  944. Vector2I localPos = getWidgetRelativePos(*widget, cursorScreenPos);
  945. // Elements with lowest depth (most to the front) get handled first
  946. for(auto iter = elements.begin(); iter != elements.end(); ++iter)
  947. {
  948. GUIElement* element = *iter;
  949. if(!element->_isDisabled() && element->_isInBounds(localPos))
  950. {
  951. mNewElementsUnderCursor.push_back(ElementInfo(element, widget));
  952. }
  953. }
  954. }
  955. widgetIdx++;
  956. }
  957. }
  958. std::sort(mNewElementsUnderCursor.begin(), mNewElementsUnderCursor.end(),
  959. [](const ElementInfo& a, const ElementInfo& b)
  960. {
  961. return a.element->_getDepth() < b.element->_getDepth();
  962. });
  963. // Send MouseOut and MouseOver events
  964. bool eventProcessed = false;
  965. for(auto& elementInfo : mElementsUnderCursor)
  966. {
  967. GUIElement* element = elementInfo.element;
  968. GUIWidget* widget = elementInfo.widget;
  969. auto iterFind = std::find_if(mNewElementsUnderCursor.begin(), mNewElementsUnderCursor.end(),
  970. [=] (const ElementInfo& x) { return x.element == element; });
  971. if(iterFind == mNewElementsUnderCursor.end())
  972. {
  973. auto iterFind2 = std::find_if(mActiveElements.begin(), mActiveElements.end(),
  974. [=](const ElementInfo& x) { return x.element == element; });
  975. // Send MouseOut event
  976. if(mActiveElements.size() == 0 || iterFind2 != mActiveElements.end())
  977. {
  978. Vector2I curLocalPos = getWidgetRelativePos(*widget, cursorScreenPos);
  979. mMouseEvent.setMouseOutData(curLocalPos);
  980. if(sendMouseEvent(widget, element, mMouseEvent))
  981. eventProcessed = true;
  982. }
  983. }
  984. }
  985. for(auto& elementInfo : mNewElementsUnderCursor)
  986. {
  987. GUIElement* element = elementInfo.element;
  988. GUIWidget* widget = elementInfo.widget;
  989. auto iterFind = std::find_if(begin(mElementsUnderCursor), end(mElementsUnderCursor),
  990. [=] (const ElementInfo& x) { return x.element == element; });
  991. if(iterFind == mElementsUnderCursor.end())
  992. {
  993. auto iterFind2 = std::find_if(mActiveElements.begin(), mActiveElements.end(),
  994. [&](const ElementInfo& x) { return x.element == element; });
  995. // Send MouseOver event
  996. if(mActiveElements.size() == 0 || iterFind2 != mActiveElements.end())
  997. {
  998. Vector2I localPos;
  999. if(widget != nullptr)
  1000. localPos = getWidgetRelativePos(*widget, cursorScreenPos);
  1001. mMouseEvent = GUIMouseEvent(buttonStates, shift, control, alt);
  1002. mMouseEvent.setMouseOverData(localPos);
  1003. if(sendMouseEvent(widget, element, mMouseEvent))
  1004. eventProcessed = true;
  1005. }
  1006. }
  1007. }
  1008. mElementsUnderCursor.swap(mNewElementsUnderCursor);
  1009. return eventProcessed;
  1010. }
  1011. void GUIManager::onTextInput(const CM::TextInputEvent& event)
  1012. {
  1013. mTextInputEvent = GUITextInputEvent();
  1014. mTextInputEvent.setData(event.textChar);
  1015. for(auto& elementInFocus : mElementsInFocus)
  1016. {
  1017. if(sendTextInputEvent(elementInFocus.widget, elementInFocus.element, mTextInputEvent))
  1018. event.markAsUsed();
  1019. }
  1020. }
  1021. void GUIManager::onWindowFocusGained(RenderWindow& win)
  1022. {
  1023. for(auto& widgetInfo : mWidgets)
  1024. {
  1025. GUIWidget* widget = widgetInfo.widget;
  1026. if(getWidgetWindow(*widget) == &win)
  1027. widget->ownerWindowFocusChanged();
  1028. }
  1029. }
  1030. void GUIManager::onWindowFocusLost(RenderWindow& win)
  1031. {
  1032. for(auto& widgetInfo : mWidgets)
  1033. {
  1034. GUIWidget* widget = widgetInfo.widget;
  1035. if(getWidgetWindow(*widget) == &win)
  1036. widget->ownerWindowFocusChanged();
  1037. }
  1038. mNewElementsInFocus.clear();
  1039. for(auto& focusedElement : mElementsInFocus)
  1040. {
  1041. if(getWidgetWindow(*focusedElement.widget) == &win)
  1042. {
  1043. mCommandEvent = GUICommandEvent();
  1044. mCommandEvent.setType(GUICommandEventType::FocusLost);
  1045. sendCommandEvent(focusedElement.widget, focusedElement.element, mCommandEvent);
  1046. }
  1047. else
  1048. mNewElementsInFocus.push_back(focusedElement);
  1049. }
  1050. mElementsInFocus.swap(mNewElementsInFocus);
  1051. }
  1052. // We stop getting mouse move events once it leaves the window, so make sure
  1053. // nothing stays in hover state
  1054. void GUIManager::onMouseLeftWindow(CM::RenderWindow* win)
  1055. {
  1056. bool buttonStates[3];
  1057. buttonStates[0] = false;
  1058. buttonStates[1] = false;
  1059. buttonStates[2] = false;
  1060. mNewElementsUnderCursor.clear();
  1061. for(auto& elementInfo : mElementsUnderCursor)
  1062. {
  1063. GUIElement* element = elementInfo.element;
  1064. GUIWidget* widget = elementInfo.widget;
  1065. if(widget->getTarget()->getTarget().get() != win)
  1066. {
  1067. mNewElementsUnderCursor.push_back(elementInfo);
  1068. continue;
  1069. }
  1070. auto iterFind = std::find_if(mActiveElements.begin(), mActiveElements.end(),
  1071. [&](const ElementInfo& x) { return x.element == element; });
  1072. // Send MouseOut event
  1073. if(mActiveElements.size() == 0 || iterFind != mActiveElements.end())
  1074. {
  1075. Vector2I curLocalPos = getWidgetRelativePos(*widget, Vector2I());
  1076. mMouseEvent.setMouseOutData(curLocalPos);
  1077. sendMouseEvent(widget, element, mMouseEvent);
  1078. }
  1079. }
  1080. mElementsUnderCursor.swap(mNewElementsUnderCursor);
  1081. }
  1082. void GUIManager::queueForDestroy(GUIElement* element)
  1083. {
  1084. mScheduledForDestruction.push(element);
  1085. }
  1086. void GUIManager::setFocus(GUIElement* element, bool focus)
  1087. {
  1088. ElementFocusInfo efi;
  1089. efi.element = element;
  1090. efi.focus = focus;
  1091. mForcedFocusElements.push_back(efi);
  1092. }
  1093. void GUIManager::processDestroyQueue()
  1094. {
  1095. // Need two loops and a temporary since element destructors may themselves
  1096. // queue other elements for destruction
  1097. while(!mScheduledForDestruction.empty())
  1098. {
  1099. CM::Stack<GUIElement*>::type toDestroy = mScheduledForDestruction;
  1100. mScheduledForDestruction = CM::Stack<GUIElement*>::type();
  1101. while(!toDestroy.empty())
  1102. {
  1103. cm_delete<PoolAlloc>(toDestroy.top());
  1104. toDestroy.pop();
  1105. }
  1106. }
  1107. }
  1108. void GUIManager::setInputBridge(const CM::RenderTexture* renderTex, const GUIElement* element)
  1109. {
  1110. if(element == nullptr)
  1111. mInputBridge.erase(renderTex);
  1112. else
  1113. mInputBridge[renderTex] = element;
  1114. }
  1115. GUIMouseButton GUIManager::buttonToGUIButton(PositionalInputEventButton cursorButton) const
  1116. {
  1117. if(cursorButton == PositionalInputEventButton::Left)
  1118. return GUIMouseButton::Left;
  1119. else if(cursorButton == PositionalInputEventButton::Middle)
  1120. return GUIMouseButton::Middle;
  1121. else if(cursorButton == PositionalInputEventButton::Right)
  1122. return GUIMouseButton::Right;
  1123. CM_EXCEPT(InvalidParametersException, "Provided button is not a GUI supported mouse button.");
  1124. }
  1125. Vector2I GUIManager::getWidgetRelativePos(const GUIWidget& widget, const Vector2I& screenPos) const
  1126. {
  1127. const RenderWindow* window = getWidgetWindow(widget);
  1128. if(window == nullptr)
  1129. return Vector2I();
  1130. Vector2I windowPos = window->screenToWindowPos(screenPos);
  1131. windowPos = windowToBridgedCoords(widget, windowPos);
  1132. const Matrix4& worldTfrm = widget.SO()->getWorldTfrm();
  1133. Vector4 vecLocalPos = worldTfrm.inverse().multiply3x4(Vector4((float)windowPos.x, (float)windowPos.y, 0.0f, 1.0f));
  1134. Vector2I curLocalPos(Math::roundToInt(vecLocalPos.x), Math::roundToInt(vecLocalPos.y));
  1135. return curLocalPos;
  1136. }
  1137. Vector2I GUIManager::windowToBridgedCoords(const GUIWidget& widget, const Vector2I& windowPos) const
  1138. {
  1139. // This cast might not be valid (the render target could be a window), but we only really need to cast
  1140. // so that mInputBridge map allows us to search through it - we don't access anything unless the target is bridged
  1141. // (in which case we know it is a RenderTexture)
  1142. const RenderTexture* renderTexture = static_cast<const RenderTexture*>(widget.getTarget()->getTarget().get());
  1143. auto iterFind = mInputBridge.find(renderTexture);
  1144. if(iterFind != mInputBridge.end()) // Widget input is bridged, which means we need to transform the coordinates
  1145. {
  1146. const GUIElement* bridgeElement = iterFind->second;
  1147. const Matrix4& worldTfrm = bridgeElement->_getParentWidget()->SO()->getWorldTfrm();
  1148. Vector4 vecLocalPos = worldTfrm.inverse().multiply3x4(Vector4((float)windowPos.x, (float)windowPos.y, 0.0f, 1.0f));
  1149. RectI bridgeBounds = bridgeElement->getBounds();
  1150. // Find coordinates relative to the bridge element
  1151. float x = vecLocalPos.x - (float)bridgeBounds.x;
  1152. float y = vecLocalPos.y - (float)bridgeBounds.y;
  1153. float scaleX = renderTexture->getWidth() / (float)bridgeBounds.width;
  1154. float scaleY = renderTexture->getHeight() / (float)bridgeBounds.height;
  1155. return Vector2I(Math::roundToInt(x * scaleX), Math::roundToInt(y * scaleY));
  1156. }
  1157. return windowPos;
  1158. }
  1159. const CM::RenderWindow* GUIManager::getWidgetWindow(const GUIWidget& widget) const
  1160. {
  1161. // This cast might not be valid (the render target could be a window), but we only really need to cast
  1162. // so that mInputBridge map allows us to search through it - we don't access anything unless the target is bridged
  1163. // (in which case we know it is a RenderTexture)
  1164. const RenderTexture* renderTexture = static_cast<const RenderTexture*>(widget.getTarget()->getTarget().get());
  1165. auto iterFind = mInputBridge.find(renderTexture);
  1166. if(iterFind != mInputBridge.end())
  1167. {
  1168. GUIWidget* parentWidget = iterFind->second->_getParentWidget();
  1169. if(parentWidget != &widget)
  1170. {
  1171. return getWidgetWindow(*parentWidget);
  1172. }
  1173. }
  1174. RenderTargetPtr renderTarget = widget.getTarget()->getTarget();
  1175. Vector<RenderWindow*>::type renderWindows = RenderWindowManager::instance().getRenderWindows();
  1176. auto iterFindWin = std::find(renderWindows.begin(), renderWindows.end(), renderTarget.get());
  1177. if(iterFindWin != renderWindows.end())
  1178. return static_cast<RenderWindow*>(renderTarget.get());
  1179. return nullptr;
  1180. }
  1181. bool GUIManager::sendMouseEvent(GUIWidget* widget, GUIElement* element, const GUIMouseEvent& event)
  1182. {
  1183. return widget->_mouseEvent(element, event);
  1184. }
  1185. bool GUIManager::sendTextInputEvent(GUIWidget* widget, GUIElement* element, const GUITextInputEvent& event)
  1186. {
  1187. return widget->_textInputEvent(element, event);
  1188. }
  1189. bool GUIManager::sendCommandEvent(GUIWidget* widget, GUIElement* element, const GUICommandEvent& event)
  1190. {
  1191. return widget->_commandEvent(element, event);
  1192. }
  1193. bool GUIManager::sendVirtualButtonEvent(GUIWidget* widget, GUIElement* element, const GUIVirtualButtonEvent& event)
  1194. {
  1195. return widget->_virtualButtonEvent(element, event);
  1196. }
  1197. GUIManager& gGUIManager()
  1198. {
  1199. return GUIManager::instance();
  1200. }
  1201. }