UI.cpp 15 KB

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