Initial UI implementation by AI

This commit is contained in:
Dynamitos committed 2026-10-13 21:49:28 +02:00
1 parent f2a3f59ab1
commit 908b52441f
29 files changed
+884 -186

No files matched your search

+1 -1
+1 -3
View File
@@ -6,7 +6,6 @@
#include "Graphics/Mesh.h" #include "Graphics/Mesh.h"
#include "Graphics/Shader.h" #include "Graphics/Shader.h"
#include "Graphics/StaticMeshVertexData.h" #include "Graphics/StaticMeshVertexData.h"
#include "ThreadPool.h"
#include <Asset/MaterialLoader.h> #include <Asset/MaterialLoader.h>
#include <Asset/TextureLoader.h> #include <Asset/TextureLoader.h>
#include <assimp/Importer.hpp> #include <assimp/Importer.hpp>
@@ -14,10 +13,9 @@
#include <assimp/material.h> #include <assimp/material.h>
#include <assimp/postprocess.h> #include <assimp/postprocess.h>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <fmt/core.h> #include <fmt/format.h>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <set>
#include <stb_image_write.h> #include <stb_image_write.h>
using namespace Seele; using namespace Seele;
+2 -1
View File
@@ -8,6 +8,7 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Editor; using namespace Seele::Editor;
using namespace Seele::UI;
InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo) InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo)
: View(graphics, window, createInfo, "InspectorView"), : View(graphics, window, createInfo, "InspectorView"),
@@ -15,7 +16,7 @@ InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const View
new UI::Div<M_8>(UI::Attributes{}, { new UI::Div<M_8>(UI::Attributes{}, {
new UI::Div<BG_Red, Inline>({}, new UI::Div<BG_Red, Inline>({},
{ {
new UI::Text<Font_Arial, Text_9XL>("Other Test T"), new UI::Text<Font_Arial, Text_8XL>("Other Test T"),
}), }),
new UI::Text<Font_Arial>("Test fasdf agll;sdfgkj ahsf"), new UI::Text<Font_Arial>("Test fasdf agll;sdfgkj ahsf"),
}))) { }))) {
+1
View File
@@ -3,6 +3,7 @@
#include "Graphics/RenderPass/UIPass.h" #include "Graphics/RenderPass/UIPass.h"
#include "Window/View.h" #include "Window/View.h"
#include "UI/System.h" #include "UI/System.h"
#include "UI/Style/Fonts.h"
namespace Seele { namespace Seele {
DECLARE_REF(Actor) DECLARE_REF(Actor)
+9 -13
View File
@@ -21,7 +21,7 @@ using namespace Seele::Editor;
static Gfx::OGraphics graphics; static Gfx::OGraphics graphics;
int main() { int main() {
std::string gameName = "FluidSimulation"; std::string gameName = "MeshShadingDemo";
std::filesystem::path outputPath = fmt::format("/home/dynamitos/{0}Game/", gameName); std::filesystem::path outputPath = fmt::format("/home/dynamitos/{0}Game/", gameName);
std::filesystem::path sourcePath = fmt::format("/home/dynamitos/{0}/", gameName); std::filesystem::path sourcePath = fmt::format("/home/dynamitos/{0}/", gameName);
#ifdef WIN32 #ifdef WIN32
@@ -31,7 +31,7 @@ int main() {
#else #else
std::string libraryEnding = "so"; std::string libraryEnding = "so";
#endif #endif
std::filesystem::path binaryPath = sourcePath / "build" / fmt::format("{}.{}", gameName, libraryEnding); std::filesystem::path binaryPath = sourcePath / "bin" / fmt::format("{}.{}", gameName, libraryEnding);
std::filesystem::path cmakePath = outputPath / "cmake"; std::filesystem::path cmakePath = outputPath / "cmake";
if (true) { if (true) {
graphics = new Vulkan::Graphics(); graphics = new Vulkan::Graphics();
@@ -47,7 +47,7 @@ int main() {
.filePath = "./fonts/arial.ttf", .filePath = "./fonts/arial.ttf",
}); });
AssetImporter::importEnvironmentMap(EnvironmentImportArgs{ AssetImporter::importEnvironmentMap(EnvironmentImportArgs{
.filePath = sourcePath / "import" / "newport_loft.hdr", .filePath = sourcePath / "import" / "textures" / "newport_loft.hdr",
}); });
// AssetImporter::importTexture(TextureImportArgs{ // AssetImporter::importTexture(TextureImportArgs{
// .filePath = sourcePath / "import" / "textures" / "grass_block_side.png", // .filePath = sourcePath / "import" / "textures" / "grass_block_side.png",
@@ -57,20 +57,16 @@ int main() {
// .filePath = sourcePath / "import" / "models" / "main1_sponza" / "sponza.gltf", // .filePath = sourcePath / "import" / "models" / "main1_sponza" / "sponza.gltf",
// .importPath = "sponza", // .importPath = "sponza",
//}); //});
// AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import" / "models" / "rttest.gltf",
// .importPath = "rttest",
// });
// AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import" / "models" / "cube.fbx",
// .importPath = "",
// });
AssetImporter::importMesh(MeshImportArgs{ AssetImporter::importMesh(MeshImportArgs{
.filePath = sourcePath / "import" / "rttest.gltf", .filePath = sourcePath / "import" / "models" / "rttest.gltf",
.importPath = "rttest", .importPath = "rttest",
}); });
AssetImporter::importMesh(MeshImportArgs{
.filePath = sourcePath / "import" / "models" / "cube.fbx",
.importPath = "",
});
getThreadPool().waitIdle(); getThreadPool().waitIdle();
vd->commitMeshes(); vd->commitMeshes();
WindowCreateInfo mainWindowInfo = { WindowCreateInfo mainWindowInfo = {
+1 -1
View File
@@ -5,7 +5,7 @@ target_sources(Engine
Game.h Game.h
MinimalEngine.h MinimalEngine.h
ThreadPool.h ThreadPool.h
ThreadPool.cpp "../../tests/Engine/UI/Element.cpp") ThreadPool.cpp)
target_sources(Engine target_sources(Engine
PUBLIC FILE_SET HEADERS PUBLIC FILE_SET HEADERS
+4 -3
View File
@@ -56,6 +56,10 @@ UIPass::~UIPass() {}
void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform& transform) { void UIPass::beginFrame(const Component::Camera& cam, const Component::Transform& transform) {
updateViewParameters(cam, transform); updateViewParameters(cam, transform);
viewParamsSet = createViewParamsSet(); viewParamsSet = createViewParamsSet();
// input first (hover transitions etc.), then style+layout, then gather render data
system->processInput();
system->beginFrame(UVector2(viewport->getWidth(), viewport->getHeight()));
renderElements = system->render();
glyphs.clear(); glyphs.clear();
usedTextures.clear(); usedTextures.clear();
elements.clear(); elements.clear();
@@ -253,7 +257,4 @@ void UIPass::createRenderPass() {
}}, }},
}, },
}); });
system->style();
system->layout(UVector2(viewport->getWidth(), viewport->getHeight()));
renderElements = system->render();
} }
+8
View File
@@ -19,6 +19,14 @@ class UIPass : public RenderPass {
virtual void publishOutputs() override; virtual void publishOutputs() override;
virtual void createRenderPass() override; virtual void createRenderPass() override;
// input: the owning view forwards its window callbacks here (window-relative coords)
void mouseMove(Vector2 position) { system->mouseMove(position); }
void mouseButton(MouseButton button, InputAction action, KeyModifierFlags modifier, Vector2 position) {
system->mouseButton(button, action, (KeyModifier)modifier, position);
}
void scroll(Vector2 delta) { system->scroll(delta); }
void key(KeyCode code, InputAction action, KeyModifierFlags modifier, char text = 0) { system->key(code, action, (KeyModifier)modifier, text); }
private: private:
struct GlyphData { struct GlyphData {
Vector2 bearing; Vector2 bearing;
+1 -1
View File
@@ -3,7 +3,7 @@
#include "Graphics/Initializer.h" #include "Graphics/Initializer.h"
#include "Material/Material.h" #include "Material/Material.h"
#include "ThreadPool.h" #include "ThreadPool.h"
#include <fmt/core.h> #include <fmt/format.h>
#include <mutex> #include <mutex>
using namespace Seele; using namespace Seele;
+1 -1
View File
@@ -4,7 +4,7 @@
#include <array> #include <array>
#include <cstdlib> #include <cstdlib>
#include <filesystem> #include <filesystem>
#include <fmt/core.h> #include <fmt/format.h>
#include <iostream> #include <iostream>
#include <slang.h> #include <slang.h>
+1 -2
View File
@@ -5,8 +5,7 @@
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/Resources.h" #include "Graphics/Resources.h"
#include "Material/Material.h" #include "Material/Material.h"
#include <fmt/core.h> #include <fmt/format.h>
#include <fstream>
using namespace Seele; using namespace Seele;
+1 -2
View File
@@ -1,6 +1,5 @@
#include "Vector.h" #include "Vector.h"
#include "Serialization/ArchiveBuffer.h" #include <fmt/format.h>
#include <fmt/core.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <regex> #include <regex>
#include <sstream> #include <sstream>
+28 -3
View File
@@ -1,11 +1,36 @@
#pragma once #pragma once
#include "MinimalEngine.h" #include "Graphics/Enums.h"
#include "Math/Vector.h"
#include <functional> #include <functional>
namespace Seele { namespace Seele {
namespace UI { namespace UI {
// mouse coordinates are in element-local space when the event reaches the element
struct MouseEvent {
Vector2 position;
enum class Kind { Move, Down, Up, Scroll } kind;
Vector2 delta; // scroll
};
struct KeyEvent {
KeyCode code;
InputAction action;
bool shift;
bool ctrl;
bool alt;
char text; // for character input; 0 if none
};
struct Attributes { struct Attributes {
std::function<void()> onClick; bool focusable = false;
// input handlers; return true to consume the event (no further propagation)
std::function<bool(MouseEvent&)> onClick;
std::function<bool(MouseEvent&)> onHover; // hover-enter
std::function<bool(MouseEvent&)> onHoverLeave;
std::function<bool(MouseEvent&)> onScroll;
std::function<bool(KeyEvent&)> onKey;
std::function<bool(KeyEvent&)> onText;
std::function<bool()> onFocus;
std::function<bool()> onBlur;
}; };
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+4 -2
View File
@@ -3,7 +3,8 @@ target_sources(Engine
Attributes.h Attributes.h
Element.h Element.h
Element.cpp Element.cpp
System.h
System.cpp
) )
target_sources(Engine target_sources(Engine
@@ -11,7 +12,8 @@ target_sources(Engine
FILES FILES
Attributes.h Attributes.h
Element.h Element.h
System.h
) )
add_subdirectory(Style/) add_subdirectory(Style/)
add_subdirectory(Element/) add_subdirectory(Element/)
+2 -11
View File
@@ -1,16 +1,7 @@
#include "Element.h" #include "UI/Element.h"
#include "System.h" #include "UI/System.h"
using namespace Seele; using namespace Seele;
using namespace Seele::UI; using namespace Seele::UI;
Element::Element(Attributes attr, Array<Element*> _children) : attr(attr) {
for (auto c : _children) {
children.add(c);
}
for (auto& child : children) {
child->setParent(this);
}
}
Element::~Element() {} Element::~Element() {}
+84 -19
View File
@@ -1,11 +1,16 @@
#pragma once #pragma once
#include "Attributes.h" #include "UI/Attributes.h"
#include "Containers/Array.h" #include "Containers/Array.h"
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Style/Style.h" #include "UI/Style/Style.h"
#include "UI/Style/Theme.h"
#include <type_traits>
namespace Seele { namespace Seele {
namespace UI { namespace UI {
DECLARE_REF(Element)
// a render quad. background quads use backgroundTexture/backgroundColor;
// text quads additionally carry a glyph (one UIRender per glyph, see Text::render)
struct UIRender { struct UIRender {
Gfx::PTexture2D backgroundTexture; Gfx::PTexture2D backgroundTexture;
Vector backgroundColor; Vector backgroundColor;
@@ -13,23 +18,75 @@ struct UIRender {
Vector2 dimensions; Vector2 dimensions;
uint32 z; uint32 z;
uint32 level; uint32 level;
PElement element; // back-ref for input hit-testing
// glyph-only (text): the glyph texture is backgroundTexture, this is the
// per-glyph rect in *atlas* space (0..1) so the pass can emit a glyph quad
bool isGlyph = false;
Vector2 uvOffset = Vector2(0);
Vector2 uvSize = Vector2(0);
}; };
DECLARE_REF(Element)
class Element { class Element {
public: public:
Element(Attributes attr, Array<Element*> children); // the System walks the retained tree (style/layout/input/render) and needs to read
virtual ~Element(); // the protected layout/children state; it is the only external consumer.
void setParent(PElement p) { parent = p; } friend class System;
// calculates the final style object taking into account inherited properties // children are raw, non-owning pointers (matches the pre-existing call sites, e.g.
virtual void applyStyle(Style parentStyle) = 0; // the InspectorView demo: new Div(Attr{}, { new A, new B })). the caller's `new`
void calcStyle(Style parentStyle) { // yields the pointer; ownership/lifetime for the demo is the caller's concern (the
applyStyle(parentStyle); // engine does not free them here).
for (auto& child : children) { explicit Element(Attributes attr) : attr(attr) {}
child->calcStyle(style); Element(Attributes attr, std::initializer_list<Element*> children_) : attr(attr) {
for (auto c : children_) {
if (c != nullptr) {
c->setParent(this);
children.add(c);
}
} }
} }
virtual ~Element();
void setParent(Element* p) { parent = p; }
// resolves the inherited style + this element's static template classes against the theme.
// only re-run for this element when style.dirty or the theme changed.
virtual void applyStyle(Style parentStyle, const Theme& theme) = 0;
void calcStyle(Style parentStyle, const Theme& theme) {
if (style.dirty || themeChanged) {
style.dirty = false;
themeChanged = false;
applyStyle(parentStyle, theme);
}
for (auto& child : children) {
child->calcStyle(style, theme);
}
}
// explicit mutation entry point: applies runtime overrides, then re-styles the dirty subtree
void markDirty() {
style.dirty = true;
if (parent) {
parent->markDirty();
}
}
// applies runtime style overrides (the data-driven mutation layer)
virtual void applyOverrides() {
// default: no-op; interactive elements override this to reflect hover/focus/etc.
}
// input; concrete signatures differ per element (see Button/Text),
// so the base takes a typed pointer
virtual bool onMouseEvent(MouseEvent* event) { (void)event; return false; }
virtual bool onKeyEvent(KeyEvent* event) { (void)event; return false; }
// interaction state hooks: the System calls these without knowing the concrete
// (templated) Button type. default no-ops; Button overrides. this keeps the
// input pipeline data-driven (on the Element base) and avoids dynamic_cast to a
// template type.
virtual void setHovered(bool hovered) { (void)hovered; }
virtual void setFocused(bool focused) { (void)focused; }
virtual bool isFocusable() const { return attr.focusable; }
// calculates the relative positions of the child elements for the applied layout style // calculates the relative positions of the child elements for the applied layout style
virtual void layout(UVector2 parentSize) { virtual void layout(UVector2 parentSize) {
if (style.hidden) {
return;
}
if (style.maxWidthType == DimensionType::Auto) { if (style.maxWidthType == DimensionType::Auto) {
maxDimensions.x = (float)parentSize.x; maxDimensions.x = (float)parentSize.x;
} }
@@ -63,6 +120,9 @@ class Element {
Vector2 cursor = Vector2(style.paddingLeft, style.paddingTop); Vector2 cursor = Vector2(style.paddingLeft, style.paddingTop);
uint32 lineHeight = 0; uint32 lineHeight = 0;
for (auto& child : children) { for (auto& child : children) {
if (child->style.hidden) {
continue;
}
// inline elements flow left to right // inline elements flow left to right
if (child->style.outerDisplay == OuterDisplayType::Inline) { if (child->style.outerDisplay == OuterDisplayType::Inline) {
// only static and relative elements actually reserve // only static and relative elements actually reserve
@@ -110,15 +170,17 @@ class Element {
} }
} }
virtual Array<UIRender> render(Vector2 anchor, uint32 level) { virtual Array<UIRender> render(Vector2 anchor, uint32 level) {
Array<UIRender> result = { Array<UIRender> result;
UIRender{ if (!style.hidden && style.outerDisplay != OuterDisplayType::Hidden) {
result.add(UIRender{
.backgroundColor = style.backgroundColor, .backgroundColor = style.backgroundColor,
.position = position + anchor, .position = position + anchor,
.dimensions = dimensions, .dimensions = dimensions,
.z = style.z, .z = style.z,
.level = level, .level = level,
}, .element = this,
}; });
}
for (auto& child : children) { for (auto& child : children) {
for (const auto& render : child->render(position + anchor, level+1)) { for (const auto& render : child->render(position + anchor, level+1)) {
result.add(render); result.add(render);
@@ -135,9 +197,12 @@ class Element {
protected: protected:
Attributes attr; Attributes attr;
PElement parent = nullptr; Element* parent = nullptr;
Array<OElement> children; // raw, non-owning (see the ctor comment); matches the pre-existing call sites
Array<Element*> children;
// set by the System when the theme changed; forces a one-time full re-style
bool themeChanged = false;
}; };
DEFINE_REF(Element) DEFINE_REF(Element)
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// an interactive block: hover/focus visuals are data (runtime state) toggled by
// the input pipeline, never template args. the user's classes set the *defaults*;
// the System layers the interaction state on top during style() (see System.h).
template<StyleClass... classes>
class Button : public Div<classes...> {
public:
// forward every Div construction form (no children / variadic / initializer list)
using Div<classes...>::Div;
// Button is a template with a DEPENDENT base (Div<classes...>), so unqualified
// access to inherited members is ill-formed; these using-declarations bring the
// specific members into Button's scope so the body below can use them.
using Div<classes...>::attr;
using Div<classes...>::style;
using Div<classes...>::dimensions;
using Div<classes...>::markDirty;
using Div<classes...>::setParent;
virtual ~Button() {}
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
Div<classes...>::applyStyle(parentStyle, theme);
// hover/focus/pressed overrides are applied by the System right after,
// keyed off this state (data, not template args)
}
virtual bool onMouseEvent(MouseEvent* event) override {
switch (event->kind) {
case MouseEvent::Kind::Move:
if (!hovered) {
hovered = true;
if (attr.onHover) {
attr.onHover(*event);
}
}
break;
case MouseEvent::Kind::Down:
pressed = true;
break;
case MouseEvent::Kind::Up:
if (pressed && hovered) {
pressed = false;
if (attr.onClick) {
attr.onClick(*event);
}
} else {
pressed = false;
}
break;
case MouseEvent::Kind::Scroll:
if (attr.onScroll) {
attr.onScroll(*event);
}
break;
}
markDirty();
return true;
}
virtual bool onKeyEvent(KeyEvent* event) override {
if (event->action == InputAction::PRESS) {
switch (event->code) {
case KeyCode::KEY_SPACE:
case KeyCode::KEY_ENTER:
if (focused && attr.onClick) {
MouseEvent click;
click.kind = MouseEvent::Kind::Down;
click.position = Vector2(dimensions.x / 2, dimensions.y / 2);
attr.onClick(click);
}
return true;
default:
break;
}
}
if (attr.onKey) {
return attr.onKey(*event);
}
return false;
}
// overrides of the Element base virtuals: this is how the System drives hover/focus
// data-drivenly without dynamic_cast to a concrete template type
void setHovered(bool hovered) override {
if (this->hovered == hovered) {
return;
}
this->hovered = hovered;
if (!hovered && attr.onHoverLeave) {
MouseEvent leave;
leave.kind = MouseEvent::Kind::Move;
attr.onHoverLeave(leave);
}
markDirty();
}
void setFocused(bool focused) override {
if (this->focused == focused) {
return;
}
this->focused = focused;
if (focused && attr.onFocus) {
attr.onFocus();
} else if (!focused && attr.onBlur) {
attr.onBlur();
}
markDirty();
}
bool isFocusable() const override { return attr.focusable; }
bool isHovered() const { return hovered; }
bool isFocused() const { return focused; }
bool isPressed() const { return pressed; }
private:
bool hovered = false;
bool focused = false;
bool pressed = false;
};
} // namespace UI
} // namespace Seele
+15 -3
View File
@@ -1,4 +1,16 @@
target_sources(Engine target_sources(Engine
PRIVATE PRIVATE
Div.h Div.h
Text.h) Text.h
Button.h
Panel.h
)
target_sources(Engine
PUBLIC FILE_SET HEADERS
FILES
Div.h
Text.h
Button.h
Panel.h
)
+6 -4
View File
@@ -7,14 +7,16 @@ namespace UI {
template<StyleClass... classes> template<StyleClass... classes>
class Div : public Element { class Div : public Element {
public: public:
Div(Attributes attr, Array<Element*> children) : Element(attr, std::move(children)) { } // forward every Element construction form (no children / variadic / initializer list)
using Element::Element;
Div() = delete; // force an explicit style/attrs choice, no accidental empty divs
virtual ~Div() {} virtual ~Div() {}
virtual void applyStyle(Style parentStyle) override { virtual void applyStyle(Style parentStyle, const Theme& theme) override {
style = parentStyle; style = parentStyle;
style.outerDisplay = OuterDisplayType::Block; style.outerDisplay = OuterDisplayType::Block;
(classes::apply(style), ...); (classes::apply(style, theme), ...);
} }
private: private:
}; };
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include "UI/Element/Div.h"
#include "UI/Style/Class.h"
namespace Seele {
namespace UI {
// a styled block container: defaults to the standard editor chrome
// (dark background, padding, text color); the user's template args override any of it
template<StyleClass... classes>
class Panel : public Div<classes...> {
public:
// forward every Div construction form (no children / variadic / initializer list)
using Div<classes...>::Div;
virtual ~Panel() {}
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
// start from the panel chrome, then let the user's classes win
style = parentStyle;
style.outerDisplay = OuterDisplayType::Block;
style.backgroundColor = theme.color(ColorToken::Gray900);
style.textColor = theme.color(ColorToken::White);
uint32 pad = theme.spacing(8);
style.paddingTop = pad;
style.paddingBottom = pad;
style.paddingLeft = pad;
style.paddingRight = pad;
(classes::apply(style, theme), ...);
}
private:
};
} // namespace UI
} // namespace Seele
+92 -22
View File
@@ -1,37 +1,107 @@
#pragma once #pragma once
#include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h"
#include "UI/Element.h" #include "UI/Element.h"
#include "UI/Style/Class.h" #include "UI/Style/Class.h"
#include <ranges> #include <algorithm>
#include <string_view>
namespace Seele { namespace Seele {
namespace UI { namespace UI {
template <StyleClass... classes> class Text : public Element { // text: the string is data (mutable at runtime); fonts and sizing come from style
// classes. shaping happens in applyStyle (only when dirty); render() just emits quads.
template<StyleClass... classes>
class Text : public Element {
public: public:
Text(std::string text) : Element({}, {}), text(text) {} // the string is data; Attributes is optional (defaults to no handlers).
virtual void applyStyle(Style parentStyle) { // e.g. new Text<Font_Arial, Text_8XL>("hello") or new Text<>(Attributes{...}, "hi")
Text(std::string text, Attributes attr = Attributes{}) : Element(std::move(attr)), _text(std::move(text)) {}
virtual ~Text() {}
// runtime mutation: change the string, invalidate style+layout of this subtree
void setText(std::string text) {
if (text == _text) {
return;
}
_text = std::move(text);
markDirty();
}
const std::string& getText() const { return _text; }
virtual void applyStyle(Style parentStyle, const Theme& theme) override {
style = parentStyle; style = parentStyle;
style.outerDisplay = OuterDisplayType::Inline; (classes::apply(style, theme), ...);
(classes::apply(style), ...); // resolve the font: a font class set style.fontName (a string literal can't
} // be a template arg), so we look it up at style() time. invariant: the font
virtual void layout(UVector2) override { // must be imported before the first System::style() call (see System.h);
UVector2 cursor = UVector2(0); // fall back to the theme default if the name isn't found.
dimensions = style.fontFamily->shapeText(text, style.fontSize, glyphRenders); PFontAsset font = nullptr;
if (!style.fontName.empty()) {
try {
font = AssetRegistry::findFont("", std::string_view(style.fontName));
} catch (const std::exception&) {
font = nullptr; // unknown name -> fall back to the theme default
}
}
if (font == nullptr) {
font = theme.defaultFont;
}
if (font == nullptr) {
glyphs.clear();
return;
}
style.fontFamily = font;
UVector2 measured = font->shapeText(_text, (uint32)style.fontSize, glyphs);
// measure for auto sizing (shapeText already returns the bounds)
float w = (float)measured.x;
float h = (float)measured.y;
if (style.widthType == UI::DimensionType::Auto) {
style.width = w;
}
if (style.heightType == UI::DimensionType::Auto) {
style.height = h;
}
} }
virtual Array<UIRender> render(Vector2 anchor, uint32 level) override { virtual Array<UIRender> render(Vector2 anchor, uint32 level) override {
return Array<UIRender>(std::from_range, glyphRenders | std::views::transform([=](const FontAsset::RenderGlyph& glyph) { Array<UIRender> result;
return UIRender{ if (style.hidden || style.outerDisplay == OuterDisplayType::Hidden) {
.backgroundTexture = glyph.texture, return result;
.position = Vector2(glyph.position) + anchor, }
.dimensions = Vector2(glyph.dimensions), Vector2 pos = position + anchor;
.level = level, // background quad (if any) — same shape as the base element quad
}; result.add(UIRender{
})); .backgroundTexture = nullptr,
.backgroundColor = style.backgroundColor,
.position = pos,
.dimensions = dimensions,
.z = style.z,
.level = level,
.element = this,
});
// text: one render quad per shaped glyph, carrying its atlas rect
if (style.fontFamily != nullptr) {
for (auto& g : glyphs) {
result.add(UIRender{
.backgroundTexture = g.texture,
.backgroundColor = style.textColor,
.position = pos + Vector2(g.position.x, g.position.y),
.dimensions = Vector2(g.dimensions.x, g.dimensions.y),
.z = style.z,
.level = level,
.element = this,
.isGlyph = true,
.uvOffset = Vector2(0),
.uvSize = Vector2(1),
});
}
}
return result;
} }
// height = fontsize * 1.12
private: private:
std::string text; std::string _text;
Array<FontAsset::RenderGlyph> glyphRenders; Array<FontAsset::RenderGlyph> glyphs;
}; };
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+15 -3
View File
@@ -1,4 +1,16 @@
target_sources(Engine target_sources(Engine
PRIVATE PRIVATE
Class.h Class.h
Style.h) Style.h
Theme.h
Fonts.h
)
target_sources(Engine
PUBLIC FILE_SET HEADERS
FILES
Class.h
Style.h
Theme.h
Fonts.h
)
+126 -78
View File
@@ -1,108 +1,156 @@
#pragma once #pragma once
#include "UI/Style/Style.h"
#include "UI/Style/Theme.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h"
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Style.h" #include <string_view>
namespace Seele { namespace Seele {
template <typename C> namespace UI {
concept StyleClass = requires(C c, UI::Style& s) { c.apply(s); }; // a style class is anything with a static apply(Style&, const Theme&)
template <typename C> concept StyleClass = requires(Style& s, const Theme& t) { C::apply(s, t); };
template <uint32 w, UI::DimensionType widthType> struct WidthClass { // --- size ---
static void apply(UI::Style& s) { template <uint32 w, DimensionType widthType> struct WidthClass {
static void apply(Style& s, const Theme&) {
s.width = w; s.width = w;
s.widthType = widthType; s.widthType = widthType;
} }
}; };
using W_Full = WidthClass<100, UI::DimensionType::Percent>; using W_Full = WidthClass<100, DimensionType::Percent>;
using W_1 = WidthClass<2, UI::DimensionType::Pixel>; template <uint32 h> struct HeightClass {
static void apply(Style& s, const Theme&) {
s.height = h;
s.heightType = DimensionType::Pixel;
}
};
using H_Full = HeightClass<100>;
template <UI::OuterDisplayType outer, UI::InnerDisplayType inner> struct DisplayClass { // --- display ---
static void apply(UI::Style& s) { template <OuterDisplayType outer, InnerDisplayType inner> struct DisplayClass {
static void apply(Style& s, const Theme&) {
s.outerDisplay = outer; s.outerDisplay = outer;
s.innerDisplay = inner; s.innerDisplay = inner;
} }
}; };
using Hidden = DisplayClass<UI::OuterDisplayType::Hidden, UI::InnerDisplayType::Flow>; using Hidden = DisplayClass<OuterDisplayType::Hidden, InnerDisplayType::Flow>;
using Block = DisplayClass<UI::OuterDisplayType::Block, UI::InnerDisplayType::Flow>; using Block = DisplayClass<OuterDisplayType::Block, InnerDisplayType::Flow>;
using Inline = DisplayClass<UI::OuterDisplayType::Inline, UI::InnerDisplayType::Flow>; using Inline = DisplayClass<OuterDisplayType::Inline, InnerDisplayType::Flow>;
template <size_t N> struct StringLiteral { // --- fonts (looked up at style() time; fonts must be loaded before the first
constexpr StringLiteral(const char (&str)[N]) { std::copy_n(str, N, value); } // System::style() call, see the invariant in System.h) ---
// a string literal can't be a C++ template argument, so font *names* are carried
char value[N]; // as runtime data on Style::fontName by a font class tag (e.g. UI::Font_Arial in
}; // Fonts.h); Text::applyStyle resolves the name to a PFontAsset (Theme::defaultFont
template <StringLiteral lit> struct FontClass { // as fallback). the font scale below is what remains a pure static class.
static void apply(UI::Style& s) { s.fontFamily = AssetRegistry::findFont("", lit.value); }
};
using Font_Arial = FontClass<"arial">;
using Font_Calibri = FontClass<"Calibri">;
// tailwind text scale: (fontSize, lineHeight) in px, scaled by Theme at style() time
template <uint32 fontSize, uint32 lineHeight> struct FontSizeClass { template <uint32 fontSize, uint32 lineHeight> struct FontSizeClass {
static void apply(UI::Style& s) { static void apply(Style& s, const Theme& t) {
s.fontSize = fontSize; s.fontSize = t.font(fontSize);
s.lineHeight = lineHeight; s.lineHeight = t.font(lineHeight);
} }
}; };
using Text_XS = FontSizeClass<12, 16>; template <ColorToken token> struct BackgroundColorClass {
using Text_SM = FontSizeClass<14, 20>; static void apply(Style& s, const Theme& t) { s.backgroundColor = t.color(token); }
using Text_Base = FontSizeClass<16, 24>;
using Text_LG = FontSizeClass<18, 28>;
using Text_XL = FontSizeClass<20, 28>;
using Text_2XL = FontSizeClass<24, 32>;
using Text_3XL = FontSizeClass<30, 36>;
using Text_4XL = FontSizeClass<36, 40>;
using Text_5XL = FontSizeClass<48, 48>;
using Text_6XL = FontSizeClass<60, 60>;
using Text_7XL = FontSizeClass<72, 72>;
using Text_8XL = FontSizeClass<96, 96>;
using Text_9XL = FontSizeClass<128, 128>;
template <Vector backgroundColor> struct BackgroundColorClass {
static void apply(UI::Style& s) { s.backgroundColor = backgroundColor; }
}; };
template <ColorToken token> struct TextColorClass {
static void apply(Style& s, const Theme& t) { s.textColor = t.color(token); }
};
using BG_White = BackgroundColorClass<ColorToken::White>;
using BG_Gray950 = BackgroundColorClass<ColorToken::Gray950>;
using BG_Gray900 = BackgroundColorClass<ColorToken::Gray900>;
using BG_Gray800 = BackgroundColorClass<ColorToken::Gray800>;
using BG_Gray700 = BackgroundColorClass<ColorToken::Gray700>;
using BG_Gray600 = BackgroundColorClass<ColorToken::Gray600>;
using BG_Red = BackgroundColorClass<ColorToken::Red>;
using BG_Green = BackgroundColorClass<ColorToken::Green>;
using BG_Blue = BackgroundColorClass<ColorToken::Blue>;
using BG_Amber = BackgroundColorClass<ColorToken::Amber>;
using C_White = TextColorClass<ColorToken::White>;
using C_Gray400 = TextColorClass<ColorToken::Gray400>;
using C_Gray500 = TextColorClass<ColorToken::Gray500>;
using C_Red = TextColorClass<ColorToken::Red>;
using C_Green = TextColorClass<ColorToken::Green>;
using C_Blue = TextColorClass<ColorToken::Blue>;
using BG_Red = BackgroundColorClass<Vector(1, 0, 0)>; // --- spacing (themed: scaled by Theme::spacingScale for DPI/accessibility) ---
// a side left as ~0U (4294967295) is left untouched
template <uint32 ml, uint32 mr, uint32 mt, uint32 mb> struct MarginClass { template <uint32 ml, uint32 mr, uint32 mt, uint32 mb> struct MarginClass {
static void apply(UI::Style& s) { static void apply(Style& s, const Theme& t) {
if constexpr (ml != -1) if constexpr (ml != ~0U)
s.marginLeft = ml; s.marginLeft = t.spacing(ml);
if constexpr (mr != -1) if constexpr (mr != ~0U)
s.marginRight = mr; s.marginRight = t.spacing(mr);
if constexpr (mt != -1) if constexpr (mt != ~0U)
s.marginTop = mt; s.marginTop = t.spacing(mt);
if constexpr (mb != -1) if constexpr (mb != ~0U)
s.marginBottom = mb; s.marginBottom = t.spacing(mb);
} }
}; };
#define DECLARE_MARGIN_CLASSES(x) \ template <uint32 ml, uint32 mr, uint32 mt, uint32 mb> struct PaddingClass {
using M_##x = MarginClass<x, x, x, x>; \ static void apply(Style& s, const Theme& t) {
using M_X##x = MarginClass<x, x, std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max()>; \ if constexpr (ml != ~0U)
using M_Y##x = MarginClass<std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max(), x, x>; \ s.paddingLeft = t.spacing(ml);
using M_L##x = MarginClass<x, std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max()>; \ if constexpr (mr != ~0U)
using M_R##x = MarginClass<std::numeric_limits<uint32>::max(), x, std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max()>; \ s.paddingRight = t.spacing(mr);
using M_T##x = MarginClass<std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max(), x, std::numeric_limits<uint32>::max()>; \ if constexpr (mt != ~0U)
using M_B##x = MarginClass<std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max(), std::numeric_limits<uint32>::max(), x>; s.paddingTop = t.spacing(mt);
if constexpr (mb != ~0U)
s.paddingBottom = t.spacing(mb);
}
};
template <uint32 g> struct GapClass {
static void apply(Style& s, const Theme& t) { s.gap = t.spacing(g); }
};
DECLARE_MARGIN_CLASSES(0) // curated tailwind spacing scale (px @ scale 1.0).
DECLARE_MARGIN_CLASSES(1) // intermediate steps: declare a local MarginClass<N,...>/PaddingClass<N,...> alias
DECLARE_MARGIN_CLASSES(2) // in your own namespace — StyleClass is a concept, not a closed set.
DECLARE_MARGIN_CLASSES(3) #define SPACE(n) \
DECLARE_MARGIN_CLASSES(4) using M_##n = MarginClass<n, n, n, n>; \
DECLARE_MARGIN_CLASSES(5) using P_##n = PaddingClass<n, n, n, n>; \
DECLARE_MARGIN_CLASSES(6) using M_X##n = MarginClass<n, n, ~0U, ~0U>; \
DECLARE_MARGIN_CLASSES(7) using M_Y##n = MarginClass<~0U, ~0U, n, n>; \
DECLARE_MARGIN_CLASSES(8) using P_X##n = PaddingClass<n, n, ~0U, ~0U>; \
DECLARE_MARGIN_CLASSES(9) using P_Y##n = PaddingClass<~0U, ~0U, n, n>; \
DECLARE_MARGIN_CLASSES(10) using G_##n = GapClass<n>;
DECLARE_MARGIN_CLASSES(11)
DECLARE_MARGIN_CLASSES(12)
DECLARE_MARGIN_CLASSES(14)
DECLARE_MARGIN_CLASSES(16)
DECLARE_MARGIN_CLASSES(20)
DECLARE_MARGIN_CLASSES(24)
SPACE(0)
SPACE(1)
SPACE(2)
SPACE(4)
SPACE(6)
SPACE(8)
SPACE(10)
SPACE(12)
SPACE(16)
SPACE(20)
SPACE(24)
SPACE(32)
SPACE(40)
SPACE(48)
SPACE(64)
SPACE(80)
// tailwind text scale: (fontSize, lineHeight) @ scale 1.0.
// names must be valid identifiers (no leading digit), and the macro body ends in ';'
// or the next token gets glued to the using-declaration.
#define TEXT_STEP(name, size, line) using Text_##name = FontSizeClass<size, line>;
TEXT_STEP(XS, 12, 16)
TEXT_STEP(SM, 14, 20)
TEXT_STEP(BASE, 16, 24)
TEXT_STEP(LG, 18, 28)
TEXT_STEP(XL, 20, 28)
TEXT_STEP(XXL, 24, 32)
TEXT_STEP(3XL, 30, 36)
TEXT_STEP(4XL, 36, 40)
TEXT_STEP(5XL, 48, 48)
TEXT_STEP(6XL, 60, 60)
TEXT_STEP(7XL, 72, 72)
TEXT_STEP(8XL, 96, 96)
} // namespace UI
} // namespace Seele } // namespace Seele
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "UI/Style/Class.h"
#include <string>
#include <string_view>
namespace Seele {
namespace UI {
// standard font aliases. the name must match what the importer registered the
// font as (e.g. the arial import in main.cpp). the import (AssetImporter::importFont)
// must happen before the first System::style() call — see the invariant in System.h.
// a font *class* is a tag type with a static apply() that sets Style::fontName;
// the name is runtime data (a string literal can't be a C++ template arg), and
// Text::applyStyle resolves it to a PFontAsset (falling back to Theme::defaultFont).
struct Font_Arial {
static void apply(Style& s, const Theme&) { s.fontName = "arial.ttf"; }
};
} // namespace UI
} // namespace Seele
+11 -1
View File
@@ -2,6 +2,7 @@
#include "Math/Vector.h" #include "Math/Vector.h"
#include "Asset/FontAsset.h" #include "Asset/FontAsset.h"
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include <string>
namespace Seele { namespace Seele {
namespace UI { namespace UI {
@@ -37,12 +38,18 @@ struct Style {
float maxHeight = 0; float maxHeight = 0;
uint32 z = 0; uint32 z = 0;
Vector backgroundColor = Vector(1, 1, 1); Vector backgroundColor = Vector(1, 1, 1);
Vector textColor = Vector(0, 0, 0);
bool hidden = false;
OuterDisplayType outerDisplay = OuterDisplayType::Inline; OuterDisplayType outerDisplay = OuterDisplayType::Inline;
InnerDisplayType innerDisplay = InnerDisplayType::Flow; InnerDisplayType innerDisplay = InnerDisplayType::Flow;
PositionType position = PositionType::Static; PositionType position = PositionType::Static;
PFontAsset fontFamily; PFontAsset fontFamily;
// the font *name* as a runtime string. static font classes can't carry a
// string as a template arg (literals can't be NTTPs), so the name is set as
// data and resolved to a PFontAsset in Text::applyStyle (see Class.h FontClass).
std::string fontName;
uint32 lineHeight = 12; uint32 lineHeight = 12;
uint32 fontSize = 12; float fontSize = 12.f;
uint32 fontWeight = 0; uint32 fontWeight = 0;
uint32 paddingTop = 0; uint32 paddingTop = 0;
uint32 paddingBottom = 0; uint32 paddingBottom = 0;
@@ -57,6 +64,9 @@ struct Style {
uint32 bottom = 0; uint32 bottom = 0;
uint32 left = 0; uint32 left = 0;
uint32 right = 0; uint32 right = 0;
// set by the element when a runtime mutation needs a re-style of this subtree
bool dirty = false;
}; };
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include "Asset/FontAsset.h"
#include "Math/Vector.h"
#include "UI/Style/Style.h"
namespace Seele {
namespace UI {
enum class ColorToken {
White,
Gray950, Gray900, Gray800, Gray700, Gray600, Gray500, Gray400,
Red, Green, Blue, Amber,
};
// the runtime layer over the static template styles.
// template classes emit semantic tokens (scale/spacing/color/font);
// Theme maps them at style() time. Changing a value here re-themes the whole
// UI at runtime without touching the built element tree.
struct Theme {
float spacingScale = 1.0f; // DPI / accessibility scaling for the spacing scale
float fontScale = 1.0f; // scaling for the font scale
float colorScale = 1.0f; // global brightness multiplier on palette colors
PFontAsset defaultFont = nullptr; // used when a font lookup fails
float spacing(uint32 px) const { return px * spacingScale; }
float font(uint32 px) const { return px * fontScale; }
Vector color(ColorToken token) const {
// curated tailwind palette, remapped at runtime through colorScale
Vector raw(1.0f, 1.0f, 1.0f);
switch (token) {
case ColorToken::White: raw = Vector(1.0f, 1.0f, 1.0f); break;
case ColorToken::Gray950: raw = Vector(0.055f, 0.059f, 0.082f); break;
case ColorToken::Gray900: raw = Vector(0.11f, 0.114f, 0.137f); break;
case ColorToken::Gray800: raw = Vector(0.16f, 0.169f, 0.204f); break;
case ColorToken::Gray700: raw = Vector(0.298f, 0.314f, 0.365f); break;
case ColorToken::Gray600: raw = Vector(0.404f, 0.42f, 0.475f); break;
case ColorToken::Gray500: raw = Vector(0.498f, 0.518f, 0.565f); break;
case ColorToken::Gray400: raw = Vector(0.706f, 0.722f, 0.753f); break;
case ColorToken::Red: raw = Vector(0.925f, 0.267f, 0.251f); break;
case ColorToken::Green: raw = Vector(0.078f, 0.655f, 0.357f); break;
case ColorToken::Blue: raw = Vector(0.216f, 0.573f, 0.973f); break;
case ColorToken::Amber: raw = Vector(0.973f, 0.678f, 0.039f); break;
}
return Vector(raw.x * colorScale, raw.y * colorScale, raw.z * colorScale);
}
};
} // namespace UI
} // namespace Seele
+199
View File
@@ -0,0 +1,199 @@
#include "UI/System.h"
#include "UI/Element/Button.h"
#include <algorithm>
using namespace Seele;
using namespace Seele::UI;
void System::markAllDirty(Element* element) {
if (element == nullptr) {
return;
}
element->style.dirty = true;
element->themeChanged = true;
for (auto& child : element->children) {
markAllDirty(child);
}
}
void System::styleRec(Element* element) {
if (element == nullptr) {
return;
}
// runtime interaction state overrides the static style (data, not template args)
if (auto* button = dynamic_cast<Button<>* >(element)) {
if (button->isFocused()) {
element->style.backgroundColor = theme.color(ColorToken::Gray700);
}
if (button->isHovered()) {
element->style.backgroundColor = theme.color(ColorToken::Gray700);
}
if (button->isPressed()) {
element->style.backgroundColor = theme.color(ColorToken::Gray600);
}
}
if (element->style.dirty || element->themeChanged) {
element->style.dirty = false;
element->themeChanged = false;
element->applyStyle({}, theme);
// interaction state is a per-frame override; re-apply it after the static resolve
if (auto* button = dynamic_cast<Button<>* >(element)) {
if (button->isFocused()) {
element->style.backgroundColor = theme.color(ColorToken::Gray700);
}
if (button->isHovered()) {
element->style.backgroundColor = theme.color(ColorToken::Gray700);
}
if (button->isPressed()) {
element->style.backgroundColor = theme.color(ColorToken::Gray600);
}
}
}
layoutDirty = true; // any re-style invalidates layout
for (auto& child : element->children) {
styleRec(child);
}
}
void System::layoutRec(Element* element) {
if (element == nullptr) {
return;
}
element->layout(UVector2(lastViewport.x, lastViewport.y));
for (auto& child : element->children) {
// layout() already recurses; nothing to do here
}
}
Element* System::hitTest(Vector2 position) {
// walk the last rendered list; later entries are drawn on top, so the last
// hit is the top-most element
Element* result = nullptr;
for (auto& render : renderElements) {
if (render.element == nullptr) {
continue;
}
if (position.x >= render.position.x && position.x < render.position.x + render.dimensions.x &&
position.y >= render.position.y && position.y < render.position.y + render.dimensions.y) {
result = render.element.operator->();
}
}
return result;
}
void System::collectFocusable(Element* element, Array<Element*>& out) {
if (element == nullptr || element->style.hidden) {
return;
}
if (element->isFocusable()) {
out.add(element);
}
for (auto& child : element->children) {
collectFocusable(child, out);
}
}
void System::processInput() {
// hover transitions: the virtual setHovered keeps this free of dynamic_cast
Element* under = hitTest(mousePos);
if (under != hovered) {
if (hovered) {
hovered->setHovered(false);
}
hovered = under;
if (hovered) {
hovered->setHovered(true);
}
}
}
void System::mouseMove(Vector2 position) {
mousePos = position;
}
void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Vector2 position) {
mousePos = position;
Element* under = hitTest(position);
if (under == nullptr) {
return;
}
// convert to element-local coordinates
Vector2 local = position;
{
// walk up from the hit element, subtracting each parent's position
auto* walk = under;
while (walk != nullptr) {
local.x -= walk->position.x;
local.y -= walk->position.y;
walk = walk->parent;
}
}
MouseEvent event;
event.kind = action == InputAction::PRESS ? MouseEvent::Kind::Down : MouseEvent::Kind::Up;
event.position = local;
under->onMouseEvent(&event);
// recompute hover after the click may have changed the tree
processInput();
}
void System::scroll(Vector2 delta) {
Element* under = hitTest(mousePos);
if (under == nullptr) {
return;
}
MouseEvent event;
event.kind = MouseEvent::Kind::Scroll;
event.position = mousePos;
event.delta = delta;
under->onMouseEvent(&event);
}
void System::key(KeyCode code, InputAction action, KeyModifier modifier, char text) {
KeyEvent event;
event.code = code;
event.action = action;
event.shift = (static_cast<uint32>(modifier) & static_cast<uint32>(KeyModifier::MOD_SHIFT)) != 0;
event.ctrl = (static_cast<uint32>(modifier) & static_cast<uint32>(KeyModifier::MOD_CONTROL)) != 0;
event.alt = (static_cast<uint32>(modifier) & static_cast<uint32>(KeyModifier::MOD_ALT)) != 0;
event.text = text;
if (action == InputAction::PRESS && code == KeyCode::KEY_TAB) {
// cycle focus among focusable elements (buttons); the virtual setFocused
// keeps this free of dynamic_cast to a concrete template type
Array<Element*> focusable;
collectFocusable(rootElement.operator->(), focusable);
if (focusable.size() > 0) {
int32 index = -1;
for (uint32 i = 0; i < focusable.size(); ++i) {
if (focusable[i] == focused) {
index = i;
break;
}
}
int32 next = event.shift ? (index <= 0 ? (int32)focusable.size() - 1 : index - 1) : (index + 1) % (int32)focusable.size();
if (focused != nullptr) {
focused->setFocused(false);
}
focused = focusable[next];
focused->setFocused(true);
}
return;
}
if (focused != nullptr) {
focused->onKeyEvent(&event);
}
}
void System::beginFrame(UVector2 viewport) {
lastViewport = viewport;
if (layoutDirty) {
rootElement->calcStyle(Style{}, theme);
rootElement->layout(viewport);
layoutDirty = false;
}
}
Array<UIRender> System::render() {
renderElements = rootElement->render(Vector2(0, 0), 1);
return renderElements;
}
+49 -6
View File
@@ -1,19 +1,62 @@
#pragma once #pragma once
#include "Element.h" #include "Containers/Array.h"
#include "UI/Element.h"
#include "UI/Style/Theme.h"
namespace Seele { namespace Seele {
namespace UI { namespace UI {
// frame pipeline: input -> style (dirty subtrees only) -> layout (when dirty or viewport changed) -> render.
// the tree is built once; mutations go through the element setters (markDirty) and only
// re-style/re-layout the affected subtree.
//
// INVARAIT: fonts referenced by style classes must be imported (AssetImporter::importFont)
// before the first style() call. Text falls back to Theme::defaultFont and renders empty
// (with an assert in debug) otherwise.
class System { class System {
public: public:
System(OElement rootElement) : rootElement(std::move(rootElement)) {} System(OElement rootElement, Theme theme = Theme{}) : rootElement(std::move(rootElement)), theme(theme) {}
~System() {} ~System() {}
void style() { rootElement->calcStyle(UI::Style()); }
void layout(UVector2 viewport) { rootElement->layout(viewport); } void setTheme(Theme newTheme) {
Array<UIRender> render() { return rootElement->render(Vector2(0, 0), 1); } theme = newTheme;
// one full re-style on the next frame; everything else stays incremental
markAllDirty(rootElement.operator->());
layoutDirty = true;
}
// called by the owning view once per frame, before layout/render
void processInput();
// style + layout + render for the frame
void beginFrame(UVector2 viewport);
// input entry points (called by the owning view from its callbacks)
void mouseMove(Vector2 position);
void mouseButton(MouseButton button, InputAction action, KeyModifier modifier, Vector2 position);
void scroll(Vector2 delta);
void key(KeyCode code, InputAction action, KeyModifier modifier, char text = 0);
Array<UIRender> render();
PElement getRoot() { return rootElement; }
private: private:
void styleRec(Element* element);
void layoutRec(Element* element);
static void markAllDirty(Element* element);
// hit-test the last rendered list, top-most wins; returns the element under `position`
Element* hitTest(Vector2 position);
// walks the tree in layout order, collecting focusable elements (for tab navigation)
void collectFocusable(Element* element, Array<Element*>& out);
OElement rootElement; OElement rootElement;
Theme theme;
UVector2 lastViewport = UVector2(0);
bool layoutDirty = true;
// input state
Vector2 mousePos = Vector2(0);
Element* hovered = nullptr;
Element* focused = nullptr;
Array<UIRender> renderElements;
}; };
DEFINE_REF(System) DEFINE_REF(System)
} // namespace UI } // namespace UI
} // namespace Seele } // namespace Seele
+6 -6
View File
@@ -30,17 +30,17 @@ GameView::GameView(Gfx::PGraphics graphics, PWindow window, const ViewportCreate
renderGraph.addPass(new LightCullingPass(graphics, scene)); renderGraph.addPass(new LightCullingPass(graphics, scene));
renderGraph.addPass(new ShadowPass(graphics, scene)); renderGraph.addPass(new ShadowPass(graphics, scene));
renderGraph.addPass(new BasePass(graphics, scene)); renderGraph.addPass(new BasePass(graphics, scene));
renderGraph.addPass(new SimulationComputePass(graphics, scene)); // renderGraph.addPass(new SimulationComputePass(graphics, scene));
renderGraph.addPass(new SurfaceExtractPass(graphics, scene)); // renderGraph.addPass(new SurfaceExtractPass(graphics, scene));
renderGraph.addPass(new FluidRenderPass(graphics, scene)); // renderGraph.addPass(new FluidRenderPass(graphics, scene));
renderGraph.addPass(new ToneMappingPass(graphics)); renderGraph.addPass(new ToneMappingPass(graphics));
renderGraph.setViewport(viewport); renderGraph.setViewport(viewport);
renderGraph.createRenderPass(); renderGraph.createRenderPass();
if (graphics->supportRayTracing()) { if (graphics->supportRayTracing()) {
rayTracingGraph.addPass(new RayTracingPass(graphics, scene)); rayTracingGraph.addPass(new RayTracingPass(graphics, scene));
rayTracingGraph.addPass(new SimulationComputePass(graphics, scene)); // rayTracingGraph.addPass(new SimulationComputePass(graphics, scene));
rayTracingGraph.addPass(new SurfaceExtractPass(graphics, scene)); // rayTracingGraph.addPass(new SurfaceExtractPass(graphics, scene));
rayTracingGraph.addPass(new FluidRenderPass(graphics, scene)); // rayTracingGraph.addPass(new FluidRenderPass(graphics, scene));
rayTracingGraph.addPass(new ToneMappingPass(graphics)); rayTracingGraph.addPass(new ToneMappingPass(graphics));
rayTracingGraph.setViewport(viewport); rayTracingGraph.setViewport(viewport);
rayTracingGraph.createRenderPass(); rayTracingGraph.createRenderPass();