ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
12_effects_canvas/main.cpp

Example from examples/12_effects_canvas/.

Example from examples/12_effects_canvas/.

#include "ExampleHost.hpp"
#include <cmath>
#include <memory>
#include <string>
using namespace ZenitUI;
namespace
{
class WaveformWidget : public TLayout<WaveformWidget>
{
public:
{
setInteractive(false);
setStyleTag("Waveform");
}
void setAnimating(bool a) { animating_ = a; }
bool isAnimating() const { return animating_; }
protected:
void onUpdate(float dt) override
{
if (animating_)
{
phase_ += dt * 3.2f;
invalidateLayerCache();
}
}
void renderContent(float op, const ComputedStyle &) override
{
auto *ctx = context();
auto *r = ctx ? ctx->renderer : nullptr;
if (!r || rect.width <= 4.0f || rect.height <= 4.0f)
return;
constexpr int kBars = 24;
const float pad = 14.0f;
const float innerW = std::max(1.0f, rect.width - pad * 2.0f);
const float innerH = std::max(1.0f, rect.height - pad * 2.0f);
const float gap = 4.0f;
const float barW = std::max(3.0f, (innerW - gap * (kBars - 1)) / kBars);
const float midY = rect.y + rect.height * 0.5f;
// Subtle baseline
r->fillRect({rect.x + pad, midY - 0.5f, innerW, 1.0f},
Color{71, 85, 105, 140}.withAlpha(op));
for (int i = 0; i < kBars; ++i)
{
const float norm = static_cast<float>(i) / static_cast<float>(kBars - 1);
const float wave = 0.25f + 0.70f * std::abs(std::sin(phase_ + norm * 5.2f) *
std::cos(phase_ * 0.45f + norm * 2.3f));
const float h = std::max(8.0f, innerH * wave);
const float x = rect.x + pad + i * (barW + gap);
const float y = midY - h * 0.5f;
// Blue gradient -> Hue-shift shader swaps R <-> B to bright orange.
const uint8_t g = static_cast<uint8_t>(110 + norm * 90.0f);
const Color barCol{0, g, 241, 255};
r->fillRoundedRect({x, y, barW, h}, barW * 0.4f, barCol.withAlpha(op));
}
// Moving marker dot
const float dotX = rect.x + pad + (0.5f + 0.45f * std::sin(phase_ * 0.7f)) * innerW;
r->fillCircle({dotX, rect.y + pad + 6.0f}, 5.0f, Color{56, 189, 248, 255}.withAlpha(op));
}
private:
float phase_{0.0f};
bool animating_{true};
};
} // namespace
static constexpr const char *kStyle = R"zs(
:root {
font: inter;
font-size: 14px;
letter-spacing: 0px;
color: #E5E7EB;
}
.page {
width: 100%;
height: 100%;
background: #0D1017;
padding: 24px;
overflow-x: hidden;
overflow-y: auto;
}
.shell {
width: 100%;
max-width: 920px;
margin: auto;
gap: 16px;
}
.title {
font: inter-bold;
font-size: 24px;
color: #F8FAFC;
}
.section-title {
font: inter-semibold;
font-size: 15px;
color: #F1F5F9;
}
.muted {
font-size: 13px;
color: #94A3B8;
}
.card {
width: 100%;
background: #151924;
border-width: 1px;
border-color: #262E42;
radius: 12px;
padding: 18px;
gap: 12px;
padding-bottom: 10px;
}
.stat-pill {
padding: 4px 10px;
radius: 999px;
background: #1B2233;
border-width: 1px;
border-color: #2E3852;
color: #7DD3FC;
font-size: 12px;
}
.row {
width: 100%;
gap: 14px;
wrap: true;
align-items: center;
padding-bottom: 10px;
}
Button.btn {
padding: 8px 14px;
radius: 8px;
background: #2563EB;
color: #FFFFFF;
cursor: pointer;
transition-time: 0.12;
}
Button.btn:hover {
background: #3B82F6;
}
Button.btn-ghost {
padding: 8px 14px;
radius: 8px;
background: #1F2638;
border-width: 1px;
border-color: #334155;
color: #E2E8F0;
cursor: pointer;
transition-time: 0.12;
}
Button.btn-ghost:hover {
border-color: #38BDF8;
color: #FFFFFF;
}
Button.btn-ghost.active {
background: #1E3A5F;
border-color: #38BDF8;
color: #7DD3FC;
}
/* Canvas off-screen surface */
Canvas.wave-canvas {
width: 100%;
height: 140px;
background: #0F1420;
border-width: 1px;
border-color: #283148;
radius: 10px;
}
Canvas.wave-canvas.hue-on {
effect: hue_shift;
}
/* Filter preview tiles */
.fx-tile {
flex: 1;
min-width: 210px;
padding: 18px;
radius: 12px;
background: #1D4ED8;
border-width: 1px;
border-color: #60A5FA;
gap: 6px;
}
.fx-tile.alt {
background: #0F766E;
border-color: #2DD4BF;
}
.fx-tile.warm {
background: #9333EA;
border-color: #C084FC;
}
.fx-blur {
filter: blur(4px);
}
.fx-shadow {
filter: drop-shadow(6px, 8px, #000000E6);
}
.fx-sepia {
filter: sepia(0.95), drop-shadow(6px, 8px, #000000E6);
}
/* Nine-slice textured box */
.nine-slice-box {
width: 100%;
min-height: 76px;
padding: 20px 24px;
background-texture: panel9 16 16 16 16;
justify: center;
gap: 4px;
}
)zs";
static constexpr const char *kMarkup = R"zm(
ScrollView.page {
VStack.shell {
HStack width="100%" justify="space-between" align-items="center" wrap="true" gap="10px" {
VStack gap="4px" {
Text.title wrap="true" "Effects, Filters, Custom Canvas & Nine-Slice"
Text.muted wrap="true" "Off-screen Canvas shaders, custom FilterDef (sepia), LayerCache caching, and TargetPool stats."
}
HStack gap="6px" wrap="true" align-items="center" {
Text.stat-pill@statTargets "Pool Targets: 0"
Text.stat-pill@statPasses "Filter Passes/f: 0"
Text.stat-pill@statPush "PushTarget/f: 0"
}
}
VStack.card {
HStack width="100%" justify="space-between" align-items="center" wrap="true" gap="8px" {
Text.section-title flex="1" min-width="220px" wrap="true" "1. Custom IRenderer Widget inside Canvas + Fragment Shader (hue_shift.fs)"
HStack gap="8px" wrap="true" {
Button.btn-ghost.active@toggleAnim "Pause Wave"
Button.btn@toggleHue "Enable Hue-Shift (R <-> B)"
}
}
Canvas.wave-canvas@waveCanvas {}
}
VStack.card {
HStack width="100%" justify="space-between" align-items="center" wrap="true" gap="8px" {
Text.section-title flex="1" min-width="200px" wrap="true" "2. CSS Post-Processing Filters & LayerCache"
Button.btn-ghost.active@toggleFilters "Disable Filters"
}
Text.muted wrap="true" "Static filtered tiles are baked into pooled targets by LayerCache — pause the wave and watch Filter Passes/f drop to 0."
HStack.row {
VStack.fx-tile.fx-blur@tileBlur {
Text.section-title "Separable Blur"
Text.muted "filter: blur(4px)"
}
VStack.fx-tile.alt.fx-shadow@tileShadow {
Text.section-title "Drop Shadow"
Text.muted "filter: drop-shadow(...)"
}
VStack.fx-tile.warm.fx-sepia@tileSepia {
Text.section-title "Custom Sepia Chain"
Text.muted "filter: sepia(0.95), drop-shadow"
}
}
}
VStack.card {
Text.section-title "3. Nine-Slice Texture (ctx.loadTexture + background-texture)"
VStack.nine-slice-box {
Text.section-title "Nine-Slice Panel (assets/images/npatches_y.png)"
Text.muted wrap="true" "Corners stay crisp at 16px insets while edges and center stretch cleanly across any window width."
}
}
}
}
)zm";
int main()
{
cfg.title = "ZenitUI 12 — Effects, Filters & Custom Canvas";
cfg.width = 980;
cfg.height = 740;
cfg.minWidth = 480;
cfg.minHeight = 480;
std::weak_ptr<UI::Text> statTargetsW;
std::weak_ptr<UI::Text> statPassesW;
std::weak_ptr<UI::Text> statPushW;
return ZenitExample::runApp(
cfg,
[&](UIContext &ctx, IBackend &) -> std::shared_ptr<Layout> {
ZenitExample::loadDefaultFonts(ctx);
// Unified asset loading: shaders & nine-slice texture through UIContext.
const std::string shaderDir = ZenitExample::assetPath("assets/shaders");
ctx.loadEffectAsset("blur", shaderDir, "blur");
ctx.loadEffectAsset("dropShadow", shaderDir, "drop_shadow");
ctx.loadEffectAsset("sepia", shaderDir, "sepia");
ctx.loadEffectAsset("hue_shift", shaderDir, "hue_shift");
ctx.loadTexture("panel9", ZenitExample::assetPath("assets/images/npatches_y.png"));
// Register custom "sepia" post-processing filter on ctx.filters.
FilterDef sepiaDef;
sepiaDef.name = "sepia";
sepiaDef.shader = "sepia";
sepiaDef.pattern = FilterPattern::SinglePass;
sepiaDef.params.emplace_back("amount", FilterParamType::Float, 0, 0.85f);
ctx.filters.add(std::move(sepiaDef));
auto ui = ZMarkup::build(kMarkup, ctx);
statTargetsW = ui.ref<UI::Text>("statTargets");
statPassesW = ui.ref<UI::Text>("statPasses");
statPushW = ui.ref<UI::Text>("statPush");
// Mount custom WaveformWidget inside the off-screen Canvas.
auto wave = WaveformWidget::create();
wave->setSize(Percent(100.0f), Percent(100.0f));
if (auto canvas = ui.ref("waveCanvas"))
canvas->addChild(wave);
ZMarkup::WeakUINode uiWeak = ui.weak();
std::weak_ptr<WaveformWidget> waveW = wave;
ui.onClickRef("toggleAnim", [waveW, uiWeak]() {
auto w = waveW.lock();
if (!w)
return;
const bool next = !w->isAnimating();
w->setAnimating(next);
if (auto locked = uiWeak.lock())
{
locked->toggleClassRef("toggleAnim", "active", next);
locked->setButtonTextRef("toggleAnim", next ? "Pause Wave" : "Resume Wave");
}
});
auto hueOn = std::make_shared<bool>(false);
ui.onClickRef("toggleHue", [hueOn, uiWeak]() {
*hueOn = !(*hueOn);
if (auto locked = uiWeak.lock())
{
locked->toggleClassRef("waveCanvas", "hue-on", *hueOn);
locked->setButtonTextRef("toggleHue",
*hueOn ? "Disable Hue-Shift" : "Enable Hue-Shift (R <-> B)");
}
});
auto fxOn = std::make_shared<bool>(true);
ui.onClickRef("toggleFilters", [fxOn, uiWeak]() {
*fxOn = !(*fxOn);
if (auto locked = uiWeak.lock())
{
locked->toggleClassRef("tileBlur", "fx-blur", *fxOn);
locked->toggleClassRef("tileShadow", "fx-shadow", *fxOn);
locked->toggleClassRef("tileSepia", "fx-sepia", *fxOn);
locked->toggleClassRef("toggleFilters", "active", *fxOn);
locked->setButtonTextRef("toggleFilters", *fxOn ? "Disable Filters" : "Enable Filters");
}
});
return ui.root();
},
[&](UIContext &ctx, float) {
// RenderStats reflect the previous frame's renderFrame() pass.
if (auto st = statTargetsW.lock())
st->setText("Pool Targets: " + std::to_string(ctx.targetPool.liveCount()));
if (auto sp = statPassesW.lock())
sp->setText("Filter Passes/f: " + std::to_string(ctx.renderStats.filterPasses));
if (auto su = statPushW.lock())
su->setText("PushTarget/f: " + std::to_string(ctx.renderStats.pushTargetCalls));
});
}
void add(FilterDef def)
Register or replace a filter definition.
Unified window, frame-loop, and subsystem host for interchangeable backends.
Definition Backend.hpp:49
void setSize(Value w, Value h)
Convenience: set explicit width and height.
Definition Layout.hpp:260
CRTP base for components that want fluent builders and a static create() factory.
Definition Layout.hpp:1397
A read-only text node.
Definition Text.hpp:32
Non-owning handle to a UINode, safe to capture inside child callbacks.
Definition ZMarkup.hpp:757
@ SinglePass
One shader, one draw.
Definition FilterRegistry.hpp:44
@ Stack
Children overlap each other; Z-order controls paint order.
Definition UIEnums.hpp:30
bool loadStyleString(std::string_view src, Theme &theme, const std::string &fileName="<string>", DiagnosticSink *sink=nullptr, bool strict=false, const Registry *registry=nullptr)
Parse src and apply it to theme.
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Color withAlpha(float k) const
Return a copy with the alpha channel scaled by k.
Definition CoreTypes.hpp:85
Dense style: every property has a concrete value.
Definition Style.hpp:1036
Complete description of one filter.
Definition FilterRegistry.hpp:113
Per-instance UI context: backends, theme, text engine, frame state, and routing.
Definition UIContext.hpp:725
FilterRegistry filters
Per-context post-processing filter definitions (preloaded with builtins).
Definition UIContext.hpp:910
TextureHandle loadTexture(std::string_view name, std::string_view path)
Load a 2D texture from disk under logical name.
Definition UIContext.hpp:824
Theme theme
Per-context stylesheet (rules, keyframes, and :root style).
Definition UIContext.hpp:911
EffectHandle loadEffectAsset(std::string_view name, std::string_view baseDir, std::string_view fileStem)
Load a shader effect by stem fileStem under baseDir, automatically resolving the file extension for t...
Definition UIContext.hpp:868
Backend-agnostic window and graphics-context creation parameters.
Definition Backend.hpp:31