UI.cpp 14 KB

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