UI.cpp 14 KB

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