UI.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #include <TurboBadger/tb_core.h>
  2. #include <TurboBadger/tb_system.h>
  3. #include <TurboBadger/tb_debug.h>
  4. #include <TurboBadger/animation/tb_widget_animation.h>
  5. #include <TurboBadger/renderers/tb_renderer_batcher.h>
  6. #include <TurboBadger/tb_font_renderer.h>
  7. #include <TurboBadger/tb_node_tree.h>
  8. #include <TurboBadger/tb_widgets_reader.h>
  9. #include <TurboBadger/tb_window.h>
  10. #include <TurboBadger/tb_message_window.h>
  11. #include <TurboBadger/tb_editfield.h>
  12. #include <TurboBadger/tb_select.h>
  13. #include <TurboBadger/tb_inline_select.h>
  14. #include <TurboBadger/tb_tab_container.h>
  15. #include <TurboBadger/tb_toggle_container.h>
  16. #include <TurboBadger/image/tb_image_widget.h>
  17. void register_tbbf_font_renderer();
  18. void register_stb_font_renderer();
  19. void register_freetype_font_renderer();
  20. using namespace tb;
  21. #include "../Core/CoreEvents.h"
  22. #include "../IO/Log.h"
  23. #include "../Input/Input.h"
  24. #include "../Input/InputEvents.h"
  25. #include "../Resource/ResourceCache.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/GraphicsEvents.h"
  28. #include "../Graphics/Texture2D.h"
  29. #include "../Graphics/VertexBuffer.h"
  30. #include "UIRenderer.h"
  31. #include "UI.h"
  32. #include "UIButton.h"
  33. #include "UITextField.h"
  34. #include "UIEditField.h"
  35. #include "UILayout.h"
  36. #include "UIImageWidget.h"
  37. #include "UIClickLabel.h"
  38. #include "UICheckBox.h"
  39. #include "UISelectList.h"
  40. #include "UIMessageWindow.h"
  41. #include "UISkinImage.h"
  42. #include "UITabContainer.h"
  43. #include "UISceneView.h"
  44. #include "UIDragDrop.h"
  45. #include "UIContainer.h"
  46. #include "UISection.h"
  47. #include "UIInlineSelect.h"
  48. namespace tb
  49. {
  50. void TBSystem::RescheduleTimer(double fire_time)
  51. {
  52. }
  53. }
  54. namespace Atomic
  55. {
  56. WeakPtr<Context> UI::uiContext_;
  57. UI::UI(Context* context) :
  58. Object(context),
  59. rootWidget_(0),
  60. inputDisabled_(false),
  61. keyboardDisabled_(false),
  62. initialized_(false)
  63. {
  64. }
  65. UI::~UI()
  66. {
  67. if (initialized_)
  68. {
  69. TBFile::SetReaderFunction(0);
  70. TBID::tbidRegisterCallback = 0;
  71. tb::TBWidgetsAnimationManager::Shutdown();
  72. widgetWrap_.Clear();
  73. delete rootWidget_;
  74. // leak
  75. //delete TBUIRenderer::renderer_;
  76. tb_core_shutdown();
  77. }
  78. uiContext_ = 0;
  79. }
  80. void UI::Shutdown()
  81. {
  82. SetInputDisabled(true);
  83. }
  84. void UI::Initialize(const String& languageFile)
  85. {
  86. Graphics* graphics = GetSubsystem<Graphics>();
  87. assert(graphics);
  88. assert(graphics->IsInitialized());
  89. graphics_ = graphics;
  90. vertexBuffer_ = new VertexBuffer(context_);
  91. uiContext_ = context_;
  92. TBFile::SetReaderFunction(TBFileReader);
  93. TBID::tbidRegisterCallback = UI::TBIDRegisterStringCallback;
  94. TBWidgetsAnimationManager::Init();
  95. renderer_ = new UIRenderer(graphics_->GetContext());
  96. tb_core_init(renderer_, languageFile.CString());
  97. //register_tbbf_font_renderer();
  98. //register_stb_font_renderer();
  99. register_freetype_font_renderer();
  100. rootWidget_ = new TBWidget();
  101. int width = graphics_->GetWidth();
  102. int height = graphics_->GetHeight();
  103. rootWidget_->SetSize(width, height);
  104. rootWidget_->SetVisibilility(tb::WIDGET_VISIBILITY_VISIBLE);
  105. // register the UIDragDrop subsystem
  106. context_->RegisterSubsystem(new UIDragDrop(context_));
  107. SubscribeToEvent(E_MOUSEBUTTONDOWN, HANDLER(UI, HandleMouseButtonDown));
  108. SubscribeToEvent(E_MOUSEBUTTONUP, HANDLER(UI, HandleMouseButtonUp));
  109. SubscribeToEvent(E_MOUSEMOVE, HANDLER(UI, HandleMouseMove));
  110. SubscribeToEvent(E_MOUSEWHEEL, HANDLER(UI, HandleMouseWheel));
  111. SubscribeToEvent(E_KEYDOWN, HANDLER(UI, HandleKeyDown));
  112. SubscribeToEvent(E_KEYUP, HANDLER(UI, HandleKeyUp));
  113. SubscribeToEvent(E_TEXTINPUT, HANDLER(UI, HandleTextInput));
  114. SubscribeToEvent(E_UPDATE, HANDLER(UI, HandleUpdate));
  115. SubscribeToEvent(E_RENDERUPDATE, HANDLER(UI, HandleRenderUpdate));
  116. initialized_ = true;
  117. //TB_DEBUG_SETTING(LAYOUT_BOUNDS) = 1;
  118. }
  119. void UI::LoadSkin(const String& skin, const String& overrideSkin)
  120. {
  121. // Load the default skin, and override skin
  122. tb::g_tb_skin->Load(skin.CString(), overrideSkin.CString());
  123. }
  124. void UI::SetDefaultFont(const String& name, int size)
  125. {
  126. tb::TBFontDescription fd;
  127. fd.SetID(tb::TBIDC(name.CString()));
  128. fd.SetSize(tb::g_tb_skin->GetDimensionConverter()->DpToPx(12));
  129. tb::g_font_manager->SetDefaultFontDescription(fd);
  130. // Create the font now.
  131. tb::TBFontFace *font = tb::g_font_manager->CreateFontFace(tb::g_font_manager->GetDefaultFontDescription());
  132. // Render some glyphs in one go now since we know we are going to use them. It would work fine
  133. // without this since glyphs are rendered when needed, but with some extra updating of the glyph bitmap.
  134. if (font)
  135. font->RenderGlyphs(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~•·åäöÅÄÖ");
  136. }
  137. void UI::AddFont(const String& fontFile, const String& name)
  138. {
  139. tb::g_font_manager->AddFontInfo(fontFile.CString(), name.CString());
  140. }
  141. void UI::Render(VertexBuffer* buffer, const PODVector<UIBatch>& batches, unsigned batchStart, unsigned batchEnd)
  142. {
  143. if (batches.Empty())
  144. return;
  145. Vector2 invScreenSize(1.0f / (float)graphics_->GetWidth(), 1.0f / (float)graphics_->GetHeight());
  146. Vector2 scale(2.0f * invScreenSize.x_, -2.0f * invScreenSize.y_);
  147. Vector2 offset(-1.0f, 1.0f);
  148. Matrix4 projection(Matrix4::IDENTITY);
  149. projection.m00_ = scale.x_;
  150. projection.m03_ = offset.x_;
  151. projection.m11_ = scale.y_;
  152. projection.m13_ = offset.y_;
  153. projection.m22_ = 1.0f;
  154. projection.m23_ = 0.0f;
  155. projection.m33_ = 1.0f;
  156. graphics_->ClearParameterSources();
  157. graphics_->SetColorWrite(true);
  158. graphics_->SetCullMode(CULL_NONE);
  159. graphics_->SetDepthTest(CMP_ALWAYS);
  160. graphics_->SetDepthWrite(false);
  161. graphics_->SetFillMode(FILL_SOLID);
  162. graphics_->SetStencilTest(false);
  163. graphics_->ResetRenderTargets();
  164. graphics_->SetVertexBuffer(buffer);
  165. ShaderVariation* noTextureVS = graphics_->GetShader(VS, "Basic", "VERTEXCOLOR");
  166. ShaderVariation* diffTextureVS = graphics_->GetShader(VS, "Basic", "DIFFMAP VERTEXCOLOR");
  167. ShaderVariation* noTexturePS = graphics_->GetShader(PS, "Basic", "VERTEXCOLOR");
  168. ShaderVariation* diffTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP VERTEXCOLOR");
  169. ShaderVariation* diffMaskTexturePS = graphics_->GetShader(PS, "Basic", "DIFFMAP ALPHAMASK VERTEXCOLOR");
  170. ShaderVariation* alphaTexturePS = graphics_->GetShader(PS, "Basic", "ALPHAMAP VERTEXCOLOR");
  171. unsigned alphaFormat = Graphics::GetAlphaFormat();
  172. for (unsigned i = batchStart; i < batchEnd; ++i)
  173. {
  174. const UIBatch& batch = batches[i];
  175. if (batch.vertexStart_ == batch.vertexEnd_)
  176. continue;
  177. ShaderVariation* ps;
  178. ShaderVariation* vs;
  179. if (!batch.texture_)
  180. {
  181. ps = noTexturePS;
  182. vs = noTextureVS;
  183. }
  184. else
  185. {
  186. // If texture contains only an alpha channel, use alpha shader (for fonts)
  187. vs = diffTextureVS;
  188. if (batch.texture_->GetFormat() == alphaFormat)
  189. ps = alphaTexturePS;
  190. else if (batch.blendMode_ != BLEND_ALPHA && batch.blendMode_ != BLEND_ADDALPHA && batch.blendMode_ != BLEND_PREMULALPHA)
  191. ps = diffMaskTexturePS;
  192. else
  193. ps = diffTexturePS;
  194. }
  195. graphics_->SetShaders(vs, ps);
  196. if (graphics_->NeedParameterUpdate(SP_OBJECT, this))
  197. graphics_->SetShaderParameter(VSP_MODEL, Matrix3x4::IDENTITY);
  198. if (graphics_->NeedParameterUpdate(SP_CAMERA, this))
  199. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  200. if (graphics_->NeedParameterUpdate(SP_MATERIAL, this))
  201. graphics_->SetShaderParameter(PSP_MATDIFFCOLOR, Color(1.0f, 1.0f, 1.0f, 1.0f));
  202. graphics_->SetBlendMode(batch.blendMode_);
  203. graphics_->SetScissorTest(true, batch.scissor_);
  204. graphics_->SetTexture(0, batch.texture_);
  205. graphics_->Draw(TRIANGLE_LIST, batch.vertexStart_ / UI_VERTEX_SIZE, (batch.vertexEnd_ - batch.vertexStart_) /
  206. UI_VERTEX_SIZE);
  207. }
  208. }
  209. void UI::SetVertexData(VertexBuffer* dest, const PODVector<float>& vertexData)
  210. {
  211. if (vertexData.Empty())
  212. return;
  213. // Update quad geometry into the vertex buffer
  214. // Resize the vertex buffer first if too small or much too large
  215. unsigned numVertices = vertexData.Size() / UI_VERTEX_SIZE;
  216. if (dest->GetVertexCount() < numVertices || dest->GetVertexCount() > numVertices * 2)
  217. dest->SetSize(numVertices, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true);
  218. dest->SetData(&vertexData[0]);
  219. }
  220. void UI::Render(bool resetRenderTargets)
  221. {
  222. SetVertexData(vertexBuffer_, vertexData_);
  223. Render(vertexBuffer_, batches_, 0, batches_.Size());
  224. }
  225. void UI::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  226. {
  227. // Get rendering batches from the non-modal UI elements
  228. batches_.Clear();
  229. vertexData_.Clear();
  230. tb::TBRect rect = rootWidget_->GetRect();
  231. IntRect currentScissor = IntRect(0, 0, rect.w, rect.h);
  232. GetBatches(batches_, vertexData_, currentScissor);
  233. }
  234. void UI::GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor)
  235. {
  236. //if (!initialized_)
  237. // return;
  238. TBAnimationManager::Update();
  239. rootWidget_->InvokeProcessStates();
  240. rootWidget_->InvokeProcess();
  241. tb::g_renderer->BeginPaint(rootWidget_->GetRect().w, rootWidget_->GetRect().h);
  242. renderer_->currentScissor_ = currentScissor;
  243. renderer_->batches_ = &batches;
  244. renderer_->vertexData_ = &vertexData;
  245. rootWidget_->InvokePaint(tb::TBWidget::PaintProps());
  246. tb::g_renderer->EndPaint();
  247. }
  248. void UI::SubmitBatchVertexData(Texture* texture, const PODVector<float>& vertexData)
  249. {
  250. UIBatch b(BLEND_ALPHA , renderer_->currentScissor_, texture, &vertexData_);
  251. unsigned begin = b.vertexData_->Size();
  252. b.vertexData_->Resize(begin + vertexData.Size());
  253. float* dest = &(b.vertexData_->At(begin));
  254. b.vertexEnd_ = b.vertexData_->Size();
  255. for (unsigned i = 0; i < vertexData.Size(); i++, dest++)
  256. {
  257. *dest = vertexData[i];
  258. }
  259. UIBatch::AddOrMerge(b, batches_);
  260. }
  261. void UI::TBFileReader(const char* filename, void** data, unsigned* length)
  262. {
  263. *data = 0;
  264. *length = 0;
  265. ResourceCache* cache = uiContext_->GetSubsystem<ResourceCache>();
  266. SharedPtr<File> file = cache->GetFile(filename);
  267. if (!file || !file->IsOpen())
  268. {
  269. LOGERRORF("UI::TBFileReader: Unable to load file: %s", filename);
  270. return;
  271. }
  272. unsigned size = file->GetSize();
  273. if (!size)
  274. return;
  275. void* _data = malloc(size);
  276. if (!_data)
  277. return;
  278. if (file->Read(_data, size) != size)
  279. {
  280. free(_data);
  281. return;
  282. }
  283. *length = size;
  284. *data = _data;
  285. }
  286. void UI::GetTBIDString(unsigned id, String& value)
  287. {
  288. if (!id)
  289. {
  290. value = "";
  291. }
  292. else
  293. {
  294. value = tbidToString_[id];
  295. }
  296. }
  297. void UI::TBIDRegisterStringCallback(unsigned id, const char* value)
  298. {
  299. uiContext_->GetSubsystem<UI>()->tbidToString_[id] = String(value);
  300. }
  301. bool UI::LoadResourceFile(TBWidget* widget, const String& filename)
  302. {
  303. tb::TBNode node;
  304. if (!node.ReadFile(filename.CString()))
  305. return false;
  306. tb::g_widgets_reader->LoadNodeTree(widget, &node);
  307. return true;
  308. }
  309. void UI::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  310. {
  311. using namespace ScreenMode;
  312. rootWidget_->SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  313. //SetSize(eventData[P_WIDTH].GetInt(), eventData[P_HEIGHT].GetInt());
  314. }
  315. void UI::HandleUpdate(StringHash eventType, VariantMap& eventData)
  316. {
  317. TBMessageHandler::ProcessMessages();
  318. }
  319. bool UI::IsWidgetWrapped(tb::TBWidget* widget)
  320. {
  321. return widgetWrap_.Contains(widget);
  322. }
  323. bool UI::UnwrapWidget(tb::TBWidget* widget)
  324. {
  325. if (widgetWrap_.Contains(widget))
  326. {
  327. widgetWrap_.Erase(widget);
  328. return true;
  329. }
  330. return false;
  331. }
  332. void UI::PruneUnreachableWidgets()
  333. {
  334. HashMap<tb::TBWidget*, SharedPtr<UIWidget>>::Iterator itr;
  335. for (itr = widgetWrap_.Begin(); itr != widgetWrap_.End(); )
  336. {
  337. if ((*itr).first_->GetParent() || (*itr).second_->JSGetHeapPtr())
  338. {
  339. itr++;
  340. continue;
  341. }
  342. tb::TBWidget* toDelete = (*itr).first_;
  343. itr.GotoNext();
  344. delete toDelete;
  345. // this will likely be flagged by valgrind as accessing invalid memory
  346. assert(!widgetWrap_.Contains(toDelete));
  347. }
  348. }
  349. void UI::WrapWidget(UIWidget* widget, tb::TBWidget* tbwidget)
  350. {
  351. assert (!widgetWrap_.Contains(tbwidget));
  352. widgetWrap_[tbwidget] = widget;
  353. }
  354. UIWidget* UI::WrapWidget(tb::TBWidget* widget)
  355. {
  356. if (!widget)
  357. return NULL;
  358. if (widgetWrap_.Contains(widget))
  359. return widgetWrap_[widget];
  360. // switch this to use a factory?
  361. // this is order dependent as we're using IsOfType which also works if a base class
  362. if (widget->IsOfType<TBInlineSelect>())
  363. {
  364. UIInlineSelect* select = new UIInlineSelect(context_, false);
  365. select->SetWidget(widget);
  366. widgetWrap_[widget] = select;
  367. return select;
  368. }
  369. if (widget->IsOfType<TBSection>())
  370. {
  371. UISection* section = new UISection(context_, false);
  372. section->SetWidget(widget);
  373. widgetWrap_[widget] = section;
  374. return section;
  375. }
  376. if (widget->IsOfType<TBContainer>())
  377. {
  378. UIContainer* container = new UIContainer(context_, false);
  379. container->SetWidget(widget);
  380. widgetWrap_[widget] = container;
  381. return container;
  382. }
  383. if (widget->IsOfType<TBButton>())
  384. {
  385. // don't wrap the close button of a TBWindow.close
  386. if (widget->GetID() == TBIDC("TBWindow.close"))
  387. return 0;
  388. UIButton* button = new UIButton(context_, false);
  389. button->SetWidget(widget);
  390. widgetWrap_[widget] = button;
  391. return button;
  392. }
  393. if (widget->IsOfType<TBTextField>())
  394. {
  395. UITextField* textfield = new UITextField(context_, false);
  396. textfield->SetWidget(widget);
  397. widgetWrap_[widget] = textfield;
  398. return textfield;
  399. }
  400. if (widget->IsOfType<TBEditField>())
  401. {
  402. UIEditField* editfield = new UIEditField(context_, false);
  403. editfield->SetWidget(widget);
  404. widgetWrap_[widget] = editfield;
  405. return editfield;
  406. }
  407. if (widget->IsOfType<TBSkinImage>())
  408. {
  409. UISkinImage* skinimage = new UISkinImage(context_, "", false);
  410. skinimage->SetWidget(widget);
  411. widgetWrap_[widget] = skinimage;
  412. return skinimage;
  413. }
  414. if (widget->IsOfType<TBImageWidget>())
  415. {
  416. UIImageWidget* imagewidget = new UIImageWidget(context_, false);
  417. imagewidget->SetWidget(widget);
  418. widgetWrap_[widget] = imagewidget;
  419. return imagewidget;
  420. }
  421. if (widget->IsOfType<TBClickLabel>())
  422. {
  423. UIClickLabel* nwidget = new UIClickLabel(context_, false);
  424. nwidget->SetWidget(widget);
  425. widgetWrap_[widget] = nwidget;
  426. return nwidget;
  427. }
  428. if (widget->IsOfType<TBCheckBox>())
  429. {
  430. UICheckBox* nwidget = new UICheckBox(context_, false);
  431. nwidget->SetWidget(widget);
  432. widgetWrap_[widget] = nwidget;
  433. return nwidget;
  434. }
  435. if (widget->IsOfType<TBSelectList>())
  436. {
  437. UISelectList* nwidget = new UISelectList(context_, false);
  438. nwidget->SetWidget(widget);
  439. widgetWrap_[widget] = nwidget;
  440. return nwidget;
  441. }
  442. if (widget->IsOfType<TBMessageWindow>())
  443. {
  444. UIMessageWindow* nwidget = new UIMessageWindow(context_, NULL, "", false);
  445. nwidget->SetWidget(widget);
  446. widgetWrap_[widget] = nwidget;
  447. return nwidget;
  448. }
  449. if (widget->IsOfType<TBTabContainer>())
  450. {
  451. UITabContainer* nwidget = new UITabContainer(context_, false);
  452. nwidget->SetWidget(widget);
  453. widgetWrap_[widget] = nwidget;
  454. return nwidget;
  455. }
  456. if (widget->IsOfType<SceneViewWidget>())
  457. {
  458. UISceneView* nwidget = new UISceneView(context_, false);
  459. nwidget->SetWidget(widget);
  460. widgetWrap_[widget] = nwidget;
  461. return nwidget;
  462. }
  463. if (widget->IsOfType<TBLayout>())
  464. {
  465. UILayout* layout = new UILayout(context_, (UI_AXIS) widget->GetAxis(), false);
  466. layout->SetWidget(widget);
  467. widgetWrap_[widget] = layout;
  468. return layout;
  469. }
  470. if (widget->IsOfType<TBWidget>())
  471. {
  472. UIWidget* nwidget = new UIWidget(context_, false);
  473. nwidget->SetWidget(widget);
  474. widgetWrap_[widget] = nwidget;
  475. return nwidget;
  476. }
  477. return 0;
  478. }
  479. }