UI.cpp 15 KB

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