UI.cpp 11 KB

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