Flecs – A fast entity component system for C and C++
flecs.dev
flecs.dev
Your game will get done if you work on it, not necessarily if you pick ECS!
Everything is MUCH more difficult to implement, I won't go into details but from my experience the time spent to achieve a similar result is about 5x-10x what it should be.
Weird APIs, poor documentation, limited collective experience, tons of restrictions and limits of the C# language are making the global experience quite nightmarish.
And I have had experience with ECS-like system in different engines in the past, and I am mostly experienced with low-level engine stuff, but the induced complexity there is something I did not expect.
It's a bit much of a over-simplication that just the GameObject architecture Unity uses is what made it popular. For example, if there wasn't a UI editor for Unity and only code, you still think it would be as popular? I'm 99% sure it wouldn't be.
I tried getting into DOTS as well, as ECS is an interesting architecture overall, but Unity kind of dropped the ball on it and made it way more complicated than it has to be, from every side of having to use it.
On the other hand, you have Bevy, which is built with ECS as a core part of the engine, and it makes using ECS a breeze. After getting to know Bevy and ECS outside of DOTS better, I'm not sure I could back to how I wrote my games before. ECS just makes it a lot easier to structure bigger projects than the basic introduction game like flappy bird. The modularity is on a different level and it gives you a much better view of the overall architecture than anything else I've tried before.
Simply put, I'm not sure I'd write the same amount of games if it wasn't ECS, because it makes it fun to make games again, for me.
This shocks me the most about how Unity operates. That they haven't figured out that dog-fooding their own main product is absolutely essential, especially since every single competitor of theirs does so very successfully as well.
How can you build something great for a specific group of people if you don't know what they are going through?
I've worked on AAA games that used it, and shipped games as a solo dev without it. If you don't know why you need it, then chances are you don't need it. Just keep it in mind as one possible architecture pattern for when your code base starts to experience growing pains is my advice.
Things like entity relationships (https://ajmmertens.medium.com/building-games-in-ecs-with-ent...) introduced features that were already common in existing entity management systems, such as entity hierarchies.
An ECS can also come with a bunch of tools for inspecting entities, monitoring performance or changing components in realtime (https://www.flecs.dev/explorer/). Definitely not something you need to complete a game, but very handy.
Existing game engines like Unity/Unreal already have builtin solutions for entity management, but if you're (for whatever reason) using something that's more custom you can avoid having to reinvent entity management by using an ECS library. Similar to how you'd use libraries like SDL/bgfx/sokol for graphics.
One of those things where discussing theoretical stuff doesn't help because "it depends". :D
I'm happy that a really cool option with a C API exists.
I guess it's one of those things that you don't know until you try (and hit the limits of using or not-using one).
I'm also reminded of Robert Nystrom's "Is There More to Game Architecture Than ECS": https://youtu.be/JxI3Eu5DPwE
(Yes, Robert Nystrom of Game Programming Patterns and Crafting Interpreters)
How games work is simple. It's a simulation run at some frequency and the simulation can be affected by player input. Sometimes there is a synchronization step with a server and that is more complicated.
ECS is a pattern that results in better performance and more maintainable code. There is no reason not to use it.
https://github.com/tmewett/BrogueCE
component systems are useful when you have no design doc, or a design doc written by new-hire monkeys. Or when management has no idea what the goals are.
Here's a bit of code from that project that generates a monster: https://github.com/tmewett/BrogueCE/blob/master/src/brogue/M...
It just allocates an object per monster, followed by initializing a long list of members that presumably just gets longer as more game systems get added.
The same code in ECS would look a lot simpler, and probably perform better/have better cache locality.
Does ECS not naturally arise from using OOP? Trying to think if you are creating instances of players/physics objects/items how that wouldn't turn into a kind of entity system.
In general, for large systems, this is a great way to achieve decoupling, where the naive OOP approach would get you stuck quickly.
There are hints (and needs) in ECS systems of post-hoc/runtime Prototypical inheritance rather than pre-hoc/design time Class based construction.
There are facets of ECS that resemble concepts like mixins and pattern matching and multi-dispatch and message passing rather than "pure" "C++ VTABLE" dispatch.
Some of these things arise more naturally in other branches of the OOP family tree: the Common Lisp Object System can do some of these things out of the box; Smalltalk and its descendants (even Objective-C) were easier to mold to ECS-like configurations; IO had interesting things to say about this style of OOP; even much-maligned JS' "strange" branch of Prototypical OOP has a bunch of low-level tools that make ECS "less of a need" in JS because there are ways to do them more "naturally".
Certainly, though, in C++ and closer-related derivatives (even Java and C#) ECS isn't as naturally a pattern, which is why it often has need for strong "frameworks" and why there are often multiple, competing ones to pick from.
In particular, keeping a single object’s state in several separate memory regions seems atypical (prototypes—or Self’s “traits objects”—are usually stateless even if the system doesn’t force them to be); and I can’t think of any way to map iteration over all objects that have parts of a specific kind, often mentioned in expositions of ECS, to a conventional OOP concept (looks relational if anything).
but actual ECS systems add a lot of stuff on top that's not very natural (in any programming paradigm, not just OOP).
it's about enabling you to add and remove components at runtime, manage complicated relationships between entities and their components in a generic sense. this has all the advantages and disadvantages that those kinds of abstractions bring. bad if you don't need it, good if you do.
I think the future of game dev may end up being immutable and event driven actually... but I’m yet to see anything beyond a prototype.
If you are using a low level rendering library, or immediate mode library, you can more easily define your state however you want, but still ECS incurs massive overhead compared to basic arrays of structs. If your language allows structural typing then ECS seems to me as having little benefit.
This is a weird take, an ECS can have its components listed as a basic array of structs as well. None of this is mutually exclusive.
The reason I say ESC incurs more overhead is because I find it involves a whole bunch of access patterns to add, remove, update, and query the data. Comparatively arrays of entities mostly just involves basic loops.
I'm sure there's examples where a non-ECS approach beats out an ECS approach. But to say that ECS incurs more overhead generally is just plain false.
ECS are obviously more efficient for traversing a subset of your entity data if that subset resides in one small component, simply because the total span of bytes accessed is lower and the cache hit rate is higher.
I would be more inclined to claim the opposite: that ECS systems are generally MORE performant than arrays of entities, but you can really only be wrong when making general claims like that.
I actually know of quite a few projects that use ECS as the foundation for a low level rendering library precisely because it lets you iterate over a bunch of plain arrays, but with more flexibility.
The overhead of an ECS depends on many things, but if you have lots of entities with similar components, the overhead per entity can be quite small.
Keeping indexes/keys for references, and loops over these collections can do a lot without any upfront complexity of an entity system.
But I _would_ recommend ECS to Haskell devs interested in making games because apecs is just that good.
But dynamically updating the set of components for an entity in order to "send it" to some other system, and relying on the ECS as a query database to coordinate all this, seems like questionable practice to me. I'm seeing more and more of that in our systems.
I think ECSes are becoming too dynamic, and will start to eat perf, and hide relations. Like some message bus.
Anyone else with the same gut feeling?
This might be bad design (no idea) but I’m working on an item system for a game right now. I have Item and ItemHolder components. If it’s a player, they’ll have an InputController component, which lets them use the Item in the ItemHolder, otherwise there is an AIController component that let’s an NPC use the item.
I have a system for handling every piece of functionality that can be defined in its smallest form, which makes it incredibly easy to add or remove functionality to any entity.
Also, performance is great. I have the mindset to not prematurely worry about performance until profiling now.
Inter-entity/system communication without a bunch of tooling to support it is always going to be a bit cludgy and hard to follow as it's by necessity dynamic at runtime. It is really useful though so writing tooling for it is a good idea.
Perf impact could be pretty big if your ECS uses archetypes and needs to do a lot of copying data around as components are added and removed. But in my experience these sort of events tend to be low frequency so probably not terrible. Always good to measure though!
Don't feel hide bound to stick within the confines of the ECS setup. It's a tool not a way of life! Straight forward message passing might be much cleaner and clearer or there might be a better data sharing strategy that can live outside the ECS itself. All frameworks provide fun puzzles of how to fit functionality into them when going round them is sometimes simpler and clearer!
IMO it would be interesting to consider all static components, i.e. you don't add/remove components at runtime.
If you do want "tags", have a TagsComponent (statically added to all entities that can have tags) and modify the values in it.
With the ECS implementation in Unity DOTS, this is absolutely not the case, the control flow is mostly managed behind the scene, and multi-threaded, the simplest things are transformed into a puzzle of cascading interactions.
Indeed it is. The idea of components is to decouple systems. Where systems generally operate on few components, and own a disjoint set of components. It is not a communication channel, just like any other database should not (primarily) be used as a communication channel.
You can combine an ECS with any number of different patterns to make your communication work: events, agents, messagebus, you name it.
So far, I've used an alternative ECS called entt:
- it has tools like https://github.com/flecs-hub/explorer that work with any Flecs project
- it has builtin support for hierarchies/prefabs and more (https://ajmmertens.medium.com/building-games-in-ecs-with-ent...)
- it has optional support for systems/scheduling
- it has an optional reflection framework
- it has an optional DSL for describing assets/scenes, with an online playground to try it out: https://www.flecs.dev/explorer/?local=true&wasm=https://www....
- and a lot more: https://www.flecs.dev/flecs/md_docs_Quickstart.html#autotoc_...
It seems that ECS helps compose "things" (an entity) out of groups of data (each a component), and then operates upon combinations of those components (using systems). My domain is organized around behavior (many musical instruments implementing a Rust trait or interface, such as MIDI), but the data constituting each instrument is totally different. So the behaviors are the same, but the data is different. It seems that ECS isn't a fit, which is a shame because the implementations I've seen offer cool features like easy parallel processing, querying, and so on.
Is there a design pattern like ECS but for common behaviors instead of common data? Or am I being dense and not seeing how ECS actually is a good fit for this situation?
For example:
- create custom components for different instruments
- create systems for specific instruments that match the necessary components
- write the result to a common component (e.g. "ChannelOutput")
You could then add components for EQ, effects, routing, ... and introduce systems that match those. The advantage of this approach would be that you end up with a bunch of loosely coupled systems (for instruments, effects, mixing, ...) and an in-memory representation that's cache & parallelization friendly.
One other datapoint would be that Unreal's animation sequencer uses an ECS design, which has a lot of things in common with a DAW.
Glossing over lots of details here, you can't of course design a DAW in one paragraph.
I had an epiphany a while ago that a modern interactive DAW is a video game, except parts of it run at 44,100 fps. And even the "except" part is misleading, because games have sound as well. That opened up my mind to game development as another domain to steal designs from.
Let's not argue "why". Most obvious would be saving battery.
I'm not sure how this translates to ECS architecture - probably depends on your library, but if you're in charge of the main loop it shouldn't be a problem.
This reminds me of:
https://thedailywtf.com/articles/Hidden-Tax-Moves
"Wait, let me try," Bruce said, grabbing the mouse.
"Whoa, what just happened?" a teammate exclaimed. "What did you do? A ton of traffic just came through!"
Prove that the story is real ;)
At one company we had a deployment script written in English. That support from India would execute. Except they would occasionally inject their undocumented codes to fix their own issues.
That and the component oriented distributed monolith that ran on single machine. It was monolith architecture but it was made to run on multiple machines. However it was never distributed and starting the components was an arcane science.
I feel like game programming in general is one big "we set a global variable" :)
Event queues are used to track things in long duration across multiple frames, like user input, animation sequences, sound sequences, pending state update, pending physics update, pending AI update, etc.
In each frame, check the event queues. If they are empty, sleep. Otherwise, process the events in the queues. For user input, do the state update corresponding to the input, like updating the camera position.
For ongoing animations, advance the steps in the sequences (the drawing is done in the rendering step). When an animation sequence completes, remove it from the queue. Same for sound.
For pending state update, run the update. E.g. the ship is moving, do the state update on its velocity and position. For ECS, you might end up calling or not calling the systems for the item type for batch update. E.g. when the bullet queue is not empty, you might just run the bullet related systems over all bullets for simplicity. When all the bullets end and the queue is empty, the bullet related systems can be skipped.
The physics queue has the items being simulated. Run those. Physics could run at a slower rate like 5fps, so the queued items would be skipped most of the times. Same with the AI items in the AI queue.
Whenever there's a state update, mark the screen as outdated. At the rendering step, run rendering if the screen is outdated. It's simpler to just run the whole rendering for any change. Ideally, when there's no event in the queues or the state updates are not triggered, there's no need for rendering.
This applies to using ECS or not. ECS is for tracking states of entities and do batch update with systems.
Here's an example using it, it's well suited for "desktop applications", the shorthand to use it is `desktop_app()` https://github.com/bevyengine/bevy/blob/1c5c94715cb17cda5ae2....
The OP only mentioned that he wanted to stop outputting frames. Animations, physics, input, etc should still happen normally.
game loops usually call into simulate() and render() entrypoints.
There's state potentially mutated by simulate().. render() looks at that state and potentially produces a new output to present on-screen.
Typically the render() entrypoint returns a status indicating whether a new output was produced or not to put on-screen. If no output was produced you don't flip pages. So in a quiescent situation with nothing changing, render() returns "don't flip" and you just leave the existing page displayed til the next iteration.
How you track the internal game state / dirty vs. clean state is implementation detail behind those simulate() and render() entrypoints and depends greatly on the type of game.
You would implement it almost the same as a standard Windows GUI -- using an event handler loop that marks the screen as "dirty" and needing a refresh if it has changed.
Where it would immediately break down is ongoing animations. If you stopped moving your mouse, then animations would stop. Of course, you can set up the event loop to continue triggering if there are animations going on, but then you basically have a standard game engine loop running most of the time.
Personally, I'd be happy if games simply paused rendering when minimised. Some games do this, some don't.
But yeah, games don't need to render any frames while minimized. I do feel like this should be the operating system's responsibility as well, but then, a lot of games still have the graphics rendering and other parts of the game linked tightly together.
Thanks for entertaining the idea!
Yes, please.
It drives me nuts to have GPU fans spinning when game is minimized, paused, in the loading screen, turn based and no inputs, etc.
That's probably oversimplifying it, I don't know anything about graphics programming.
fwiw: The downvotes are not from me.
Unless I'm mistaken, Unreal hasn't had an official blessed ECS system relying on other things: from just having regular objects to reading data from data tables.
They did introduce an ECS with (currently experimental) Mass Entity in Unreal 5: https://docs.unrealengine.com/5.0/en-US/mass-entity-in-unrea...