So you want to build an ECS-backed GUI framework
Challenges and opportunities in the future of `bevy_ui`
So you want to build a UI in Rust. What better tool than an Enity-Component-System (ECS) framework to do so? It's a type-safe, trendy solution for state management and most importantly: it'll be blazing fast (no need for benchmarks obviously).
While an ECS-based GUI may be unconventional, there's prior art showing it's not impossible.
flecs implements many of the key ideas in this post and existing experiments like
kayak_ui show a ton of promise using Bevy's ECS.
It turns out, most of the problems that plague
bevy_ui aren't driven by the decision to use an ECS, or even to use Rust.
They're the boring, tedious and frustrating ones: writing GUI frameworks is a lot of work with many moving parts.
Bugs, boilerplate, and missing features crush the will of both users and devs to actually make things better incrementally.
But before we get too deep in the weeds, an important disclaimer. Alice is a maintainer of Bevy, but not the project lead or even a UI subject-matter-expert. Rose is an employee at the Foresight Spatial Labs, and uses both Bevy and traditional web frameworks (React) to build GUI-heavy applications for her day job. These opinions are purely our own, and are not the final or official word!
This post aims to record how you might make a GUI framework, why we're using an ECS at all, and what we need to fix to make
bevy_ui genuinely good.
There's been a lot of rehashed discussion, in far too many places, but very little tangible movement (except ickshonpe, you rock).
It's easy to say "
bevy_ui should work just like my favorite UI framework", but actually turning that into a workable design, getting consensus, and building it is much harder.
By writing an up-to-date, comprehensive, low-buzzword document on the requirements, vision and progress, we hope that the Bevy community will be able to come together to fix the problems
bevy_ui has today, conclusively rule out possibilities and propose solid designs for the critical missing pieces.
And who knows? Maybe it's a decade later and you're reading this post, dreaming of writing your own ECS-powered GUI framework.
In my very weary experience, there are three common ways that conversations about
bevy_ui get derailed:
- Bevy should just use an existing GUI framework.
- A single GUI framework that works for both games and applications is impossible.
- You can't build a GUI framework in the ECS.
There are a lot of Rust UI frameworks already. Some of them are even actively maintained, documented and basically functional!
Bevy trying to write our own must be a critical case of Not Invented Here syndrome. Why should scarce energy (and decision-making) go towards this, when we could instead write the upcoming Bevy Editor using an existing solution? After all, we could just officially partner with Dioxus and skip years of work.
Here's why we think Bevy shouldn't do that, for both technical and social reasons:
- Consistency with the rest of the engine is valuable in its own right.
- It makes for an easier and more consistent learning experience for new users.
- It makes the system easier to maintain.
- It keeps all the changes in the same repository, eliminating the need for carefully coordinated releases down the dependency tree.
- Improvements made to other areas of the engine benefit UI, and vice versa. Cart believes that many of the challenges are not unique to UI, and we agree!
- Bevy already has a good solution to many of the core tasks that a GUI library needs to do.
- Rendering, state management, assets, inputs, windowing, async...
- Why should we pull in duplicate, subtly incompatible ways to do these tasks?
- Sending data to and from an external UI framework is inherently error-prone, complex, hard to maintain and heavy on boilerplate.
- There's an inescapable floor due to the need for an integration layer and mismatched data models.
- This isn't unique to UI:
bevy_rapierruns into similar problems with physics (although it is still an excellent library).
- Breaking out of the standard "boxes on a screen" design for UI becomes much harder.
- World-space UI is a key feature for games: unit overlays, VR menus, diagetic computer screens...
- Game UI often wants to closely integrate with game world state and have unusual artistic effects.
- Writing custom shaders to overwrite the behavior of some nodes is dramatically harder with a third-party solution.
- None of the existing Rust GUI projects have a great answer to the fact that the borrow checker really hates graphs and really hates split mutability.
- With the addition of relations, Bevy promises a uniquely powerful approach to dealing with graphs in Rust.
- Bevy's systems are a flexible, panic-free, fast, and sound solution for sharing mutable access to world state. There's a lot of black magic under the hood powering this, and dear god do we not want to write it twice.
- Other projects are not run by the Bevy project.
- Our goals may diverge:
eguifor example is deliberately focused on simple, quick-to-build UIs, and trades off performance and customizability to get that.
- Changes become harder to coordinate: migration PRs are needed, and we can't quickly add features needed by the editor.
- The upstream crate may become abandoned (again). If Bevy is planning to stay around for decades, will the UI solutions be there too?
- We can't ensure the quality of one of our critical dependencies.
- It puts a lot of maintainership pressure on smaller third-party dependencies to have such a large client making requests of them.
- Our goals may diverge:
- Not to be too harsh, but a lot of the existing Rust GUI solutions... just aren't very good.
- There's a lot of passable options, but they all have non-trivial drawbacks. No one has really risen to the top as a clear winner.
- There's a reason that areweguiyet.rs says "the roots aren't deep but the seeds are planted".
- Deep down, we all know that we can do better, and we should.
- Users who prefer third-party GUI solutions can and will use them anyways.
Will we learn from other GUI frameworks? Absolutely. Will we adopt them officially wholesale? Absolutely not.
Another common good-faith question in discussion of
bevy_ui is "can we really meet the needs of all of our users with a single UI framework"?
Some potential splits that I've seen:
- Application UI vs simple game UI vs complex game UI
- People who love CSS and the web vs those that hate it
- Procedural programmer-friendly GUIs vs asset-driven artist-friendly GUIs
- Immediate UI vs retained mode UI
- It's very confusing for users.
- It splits developer attention.
- Tradeoffs are not always clear to users choosing which solution to use.
- Migrating between two competing solutions is very painful.
- Using multiple solutions within the same project is fundamentally untenable.
- Takes twice as long (if you're lucky).
Fortunately, "navigating the requirements of multiple user groups with distinct needs" is not a problem unique to UI. We have good tools to manage this at an architectural level:
- This problem is hypothetical and has literally already been solved on the web.
- We're not going to argue that web UI is the greatest UI solution ever created (it has many flaws, both obvious and not).
- And in case it needs saying, the web UI stack was not designed for most of these use cases. Arguably, it wasn't designed for any of them!
- Modularity: ensure that users can take or leave parts of the solution that they don't like.
- Components, systems, plugins and feature flags are great for this!
- Third-party UI libraries currently exist, and will continue to exist.
- Extensibility: ensure that internals are accessible and can be built on.
- Public components and resources are really helpful here.
- Imagine a rich ecosystem of
bevy_uiinteroperable extension libraries, all of which build on our core rendering, interaction and layout paradigms.
- Progressive disclosure in abstraction design.
- Widgets are built out of nodes.
- Nodes are just entities.
- Throughout the process, there's nothing stopping you from hooking in at a lower level.
If users can use the same ECS and rendering tools for everything from pixel art platformers to cell-shaded visual novels to PBR arena shooters, we can make a UI solution that is flexible and pleasant enough to work for everyone.
With those common objections addressed, we can hopefully talk about how to actually build our UI framework.
Let's think about our actual product requirements, so we can see where
bevy_ui falls short.
Unfortunately for us, GUI frameworks are wildly complex beasts. There are several parts that are so essential that their removal cripples the entire system:
- Storing a tree of nodes
- Virtually every non-trivial UI paradigm has one or more nested trees of elements
- A "node" is one of these elements: the smallest indivisible atom of UI
- You need to store this data somewhere!
bevy_ui, this is stored in the
World: each node is an entity with the
- UI entities are joined together with using the
- Once you have a collection of nodes, you want to be able to describe where they go on the screen.
- Simply specifying absolute size and position is not very robust: it breaks when nodes are added / removed, or when screen size changes.
bevy_ui, this is specified via the
Stylecomponent (blame CSS for the name, sorry).
taffy(which Alice helps maintain!): it supports
morphormis (in our opinion) simply a better choice if you're not tied to Web layout algorithms
- Collecting user input in the form of keyboard presses, mouse clicks, mouse movement, touchscreen taps, gamepad inputs and so on
- Generally paired with "picking": figure out the elements that a pointer event is associated with based on position
- Ideally build some nice abstractions for this, to cover things like hovering and pressing, releasing, and long-pressing buttons
bevy_input, which in turn gets data from
- Converts strings into pixels that we can draw on the screen
- Lays out text within the bounds of the node it is contained within
- The exact pixels matter for rendering, but the size is important as an input for node layout
cosmic-texthas much better shaping support for non-Latin scripts
- Window management
- Actually creating a window (or three) to draw your UI in
winit, and you should too!
- State management
- Keeping track of the state of persistent features of your UI
- Filled text, radio buttons, animation progress, whether menus are open or closed, dark/light mode, etc.
bevy_ui, state is stored as components on entities (or rarely, as global resources). This works extremely well!
- Data transfer
- Transferring data from the UI to other data stores and vice versa
- In the context of Bevy, the "other data store" is the ECS
Worldthat stores all of your game / app state
- Data binding is an abstraction used to automate this process: automatically and granularly transmitting changes
bevy_uiuses systems to send data back and forth from the rest of the
On top of this base, you likely want to add:
- Moving through GUI menus in a prinicipled discretized way: "tab" is the common keybinding for this
- Very useful for both keyboards and gamepads
- Vital accessibility feature for traditional applications
bevy_uihas no first-party solution to this
- Widgets and nodes have a ton of mostly-cosmetic properties.
- We want to ensure a consistent look and feel across our app, and be able to quickly swap it out.
- For applications, (espcially mobile applications) a native look and feel is very desirable
- This might take the form of:
- Cascading inheritance (like in CSS)
- Selectors (like in CSS, or like you might write in
- Global themes like light and dark mode
- Widget-specific styles
- Styles often need to have predictable rules for composition: what happens when more than one style is affecting an element at once?
bevy_uidoes not currently have any first-party abstractions for this.
- An abstraction for composable, reusable widgets
- Even simple widget types (radio buttons, text entry box, ) are quite complex!
- Users should be able to write these once, then reuse them across their project(s), improving both development speed and UI consistency
- Widgets may be composed of one or more nodes/elements
- The number of nodes per widget can change dynamically: think about a growing to-do list
- Widgets need to be able to take arguments to change their contents or behavior. For example, creating a reusable button with customizable text.
bevy_uicurrently uses the
Bundletype for this, but it fails badly because it can't handle multiple nodes
- Action abstractions
- Rebindable hotkeys
- Command palettes
bevy_uihas no first-party solution to this, and even third-party solutions are immature (sorry!)
- Create and expose a machine-friendly API for your UI: reading state, altering rendering/display, sending inputs and detecting what happens when these inputs change
- Generally hooks into keyboard navigation
- This API is used by tools like screen readers, which present an alternative user interface that meets the needs of disabled users
accesskit, and your GUI framework should too
- There's a lot to potentially talk about with accessability that we unfortunately don't have the word count to do here
- There is more than one language: you need a way to swap out elements of your UI (especially text) to meet the needs of users who prefer a different language
- Some languages are read right-to-left instead of left-to-right, and often certain UI designs will end up backwards if this isn't taken into account
- Icons and emoji have different cultural meanings in different places as well
- Seriously, just use
- Asset management
- UIs often use prerendered images or icons for visuals, especially in games
- You'll want custom decorations and icons, or to show images and videos in their own right
- Small animations, especially when UI elements change, can dramatically improve the polish and juiciness of a UI
- Folding/unfolding context menus, sliding drawers, spinning loading icons, fade-in/fade-out, etc.
bevy_uitheoretically integrates with
bevy_animationfor this, but the integration is unpolished
- Debug tools
- Quickly inspect and modify the UI tree after it has been rendered
- This is extremely useful for catching bugs and twiddling styles
bevy_uihas no solution for this, but
- UI serialization (in-memory object to file) and deserialization (file to in-memory object)
- If we can build our UIs based on a definition stored in a file, we can:
- Make it way easier for external tools (like a game editor) to build UIs
- Make the UIs easier for end users to customize (think Greasemonkey and game mods)
- Makes it easier to build debug tools
- Reduce time spent compiling: just hot-reload the asset
- Allows full control over the format and syntax used to define objects
- Offers the potential for better, modular tooling to create higher level abstractions and automated migrations without modifying source code
- In games, this is called a "data-driven" approach
bevy_uicurrently uses scenes (from
bevy_scene) for this
- If we can build our UIs based on a definition stored in a file, we can:
- Asynchronous tasks
- Sometimes, work is triggered by the UI that will take quite a while to complete
- You don't want your program to freeze while this happens!
bevy_ui, this uses
By hooking into Bevy, a fully-featured (but not yet complete) game engine,
bevy_ui actually has preliminary solutions in most of these domains!
So why is it overwhelmingly viewed as more Bavy than Bevy?
Having used, worked on, and listened to users using
bevy_ui, here are the key problems, as of Bevy 0.12.
These are loosely ranked in order of subjective impact on user experience.
- Spawning entities with tons of custom properties requires a lot of boilerplate.
- Endless nesting and
- This gets so, so much worse when working with multiple entities arranged in a tree. As mentioned, you can't use bundles for this.
- A data-driven workflow isn't widely used, because Bevy's scenes are verbose and inadequately documented.
- Endless nesting and
- Bevy needs a real abstraction for widgets.
- Not all widgets can be meaningfully represented as a single entity.
- Bevy provides precious few prebuilt widgets: we only have buttons and images.
- Because we lack a standardized abstraction, even adding the simplest, most useful widgets is controversial and gets bogged down. (To be clear, this isn't the fault of the reviewers or the author.)
- Using systems in a schedule is not a great fit for data binding.
- UI behavior is almost always one-off or very sparse.
- Tasks launched from the UI are usually either quite small, or are throwing work into an async pool.
- We really want to be able to reference a single, specific entity plus its parent and children.
- Getting around this requires the creation of dozens and dozens of marker components: virtually one for every button, text box, image, container, etc.
- 99% of the time, these systems will be doing no work. This wastes time, as the schedule must constantly poll to see if anything needs to be done.
- Managing and traversing hierarchies (both up and down) in
- Relations can't come soon enough.
- Bevy's input handling for UI is very primitive.
Interactioncomponent for dealing with pointer input is too limited.
- Multi-touch support for mobile is quite limited.
- Keyboard and gamepad navigation is currently missing.
- There is no first party support for an action abstraction for configurable keybindings.
- Bevy's picking support is very simplistic, and isn't easily extended to non-rectangular elements or those in world-space. (
- Flexbox (and to a much lesser extent CSS Grid) are hard to learn, have frustrating edge cases, and a terrible API. Can you explain what
- Font rendering in
bevy_uiis sometimes remarkably ugly, due to a just fixed bug.
- Bevy is missing a styling abstraction.
- Implementation could be done today: just modify components!
- Adding non-trivial visuals to
bevy_uiis too hard.
- We're missing rounded corners: essential for good-looking code-defined UI. (They're currently very fashionable for UI. We could just wait a few years for them to go out of fashion, but they'll be back in a few years after that anyway.)
- We don't have drop shadows either, but no one cares.
- We're missing nine-patch support: essential for good-looking but flexible asset-defined UI.
- Until Bevy 0.12's UI materials, there was no escape hatch that let you add your own rendering abstractions within
- Building UIs in pure code or by typing out a scene file can be painful and error-prone: a visual editor would be great.
- World-space UI is very poorly supported, and uses an entirely different set of tools.
- This is essential for games (healthbars, unit frames), but is also really useful for things like markers and labels in GIS or CAD applications.
bevy_uihas no first-class animation support.
bevy_uinodes all have
GlobalTransformcomponents, but you're not allowed to touch them.
- The ergonomics of working with async tasks in Bevy is frustrating: too much manual tracking and polling of tasks.
Of these problems, only 1 (entity spawning boilerplate), 2 (widget abstraction), 3 (systems are not a good fit for callbacks) and 4 (hierarchy pain) are caused by our choice to use an ECS architecture. The rest of these are bog-standard GUI problems: they need to be solved no matter what paradigm you're using. And critically, every single one of those ECS-linked problems is something that Bevy should fix for other use cases:
- Spawning custom entities (and especially entity assemblages) sucks for ordinary gameplay code, and scenes aren't good enough. For example, spawning a player and all their weapons.
- Bevy is missing a code-defined level of abstraction that covers multi-entity hierarchies: bundles aren't good enough.
- One-shot systems are useful for all sorts of bespoke, complex logic, and we need to develop patterns to use them effectively.
- Bevy's approach to hierarchy is fundamentally slow, brittle and painful to work with. Relations need to be a first-class primitive.
There's no fundamental impedance mismatch or architectural incompatibility beween ECS and GUIs.
bevy_ui isn't a fundamentally flawed concept, its ECS foundation just isn't good enough yet.
There is a long path to making
bevy_ui genuinely great, but we can walk it one step at a time.
There are some big open questions still, and upcoming rewrites to core components, but that doesn't mean that all of
bevy_ui is going to be burned to the ground.
GUI frameworks involve a large number of complex, mostly independent subcomponents: improvements in one area will not be invalidated by a rewrite in others!
We can split the work to be done into three categories: straightforward, controversial and research.
Straightforward tasks just need to be done. They may or may not be easy, but there shouldn't be a lot of disagreement on how or if they should be done. Currently these include:
- Review and merge support for rounded corners.
- Review and merge nine-patch support.
- Review and merge Animatable trait for interpolation and blending.
- Review and merge the winit update, which is likely to fix various small bugs and limitations.
- Finish, review and merge the migration to cosmic-text, which unlocks the use of system fonts and sophisticated font shaping.
- Add support for world-space UI, beginning by reviewing and merging the Camera-driven UI PR.
- Add support for varying UI opacity.
- Add more documentation, examples and tests to
bevy_sceneto make it easier to extend and learn.
- Add better examples and functionality for working with multitouch input in Bevy.
- Improve the ergonomics of working with async tasks in Bevy.
- Add a Morphorm and/or
cuicui_layoutlayout strategy to
taffy, and expose it in Bevy.
- Add dozens of widgets (blocked on consensus around a good widget abstraction).
Controversial tasks are ones that we have a clear understanding of and broad agreement on, but have significant architectural implications and tradeoffs:
- Create a styling abstraction, which works by modifying component values.
- Upstream bevy_fluent, taking it under the wings of the Bevy project for long term maintenance.
- Add support for keyboard and gamepad navigation, and integrate it into
- Add a proper abstraction for how to handle pointer events and states.
- Refine and implement Cart's
bsnproposal to improve the usability of scenes.
- Add an abstraction like bundles, but for multi-enitity hierachical assemblages.
- Add ways to interpolate colors to facilitate UI animation.
- Create a UI-specific transform type for faster layout and a clearer, more type-safe API.
- Add support for blending layout strategies in a single tree to
- Add support for easing/tweening for animations, following
leafwing-input-managerto create a keybinding abstraction.
bevy_mod_pickingto unlock high performance, flexible element selection.
- Implement relations, and use them inside of
Research tasks will require significant design expertise, careful consideration of wildly different proposals and may not have clear requirements:
- Define and implement a standard widget abstraction. This should be:
- Composable: widgets can be combined with other widgets to create a new widget type
- Flexible: we should be able to support everything from a button to a list to a tab view using this abstraction
- Configurable: users can change important properties of how a widget works without having to make their own type
- May map to one Bevy entity or many, in a way that is dynamically updated using ordinary systems
- Serializable to and from Bevy scenes
- Figure out how we want to handle UI behavior (and data binding) to avoid the problems involved with just using systems
- This was Alice's original motivation behind creating one shot systems
- Event bubbling and various sundry andassorted reactive UI experiments seem like interesting potential tools.
- Raph Levien's post on Xilem is an interesting read, although not always directly applicable
- Data model is the key challenge here: it's very easy to get into trouble with ownership
- Figure out how to integrate data binding logic into Bevy scenes
- Build the Bevy Editor, and add support for building GUI scenes using it
- There's something of a circular dependency here: the better
bevy_uiis, the easier this is to build
- There's something of a circular dependency here: the better
Obviously, there's a ton of work to be done!
But critically, none of it is impossible.
If we (the Bevy developer community) can come together and steadily fix these problems, one at a time, we (Alice and Rose) genuinely think
bevy_ui will one day live up to the standard for quality, flexibility and ergonomics that we expect out of the rest of the engine.
Thanks for reading: hopefully it was educational, thought-provoking, and/or fun. If you'd like to read more like this in the future, consider signing up for our email list or subscribing to our RSS feed.