UI.cpp 12 KB

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