Implement update or insert operation on World and CommandBuffer#434
Implement update or insert operation on World and CommandBuffer#434K-Adam wants to merge 1 commit intoRalith:masterfrom
Conversation
47989ac to
469e69c
Compare
| Ok(()) | ||
| } | ||
|
|
||
| fn update_or_insert_one_inner<C: Component, F: FnOnce(&mut C), D: FnOnce() -> C>( |
There was a problem hiding this comment.
Why the additional _inner layer? It does not seem to be a cold path or have less generic arguments.
There was a problem hiding this comment.
Good point, _inner isn’t for performance, its mainly an organizational split (preconditions in the public method, mutation in a helper), consistent with insert/insert_inner. Since it has one call site, I can inline it for simplicity.
|
Thanks for the PR. While I appreciate that a use case exists, I don't think this feature makes a lot of sense to include, especially as implemented. If you're going to store a |
Thank you for the feedback! I think the main benefit would be command ordering. A mutator in CommandBuffer can be interleaved at an exact position between buffered spawn/insert/remove operations and executed with the same order. What do you think about adding something like a |
|
Hmm, ordering wrt. other operations is a fair point. Given how simple the added code for that variation would be, I don't think I could object. |
|
I created a new PR with CommandBuffer::queue |
We sometimes need an update-or-default pattern: if an entity already has a component, mutate it; otherwise insert a default value and then apply the update. This is especially useful for accumulator-style components or components that hold collections.
This can be implemented for World by trying entity_ref.get::<&mut C>() and falling back to insert_one. However, this does not work correctly with CommandBuffer, since querying the World while staging changes may yield incorrect results if an insert_one or remove_one has already been queued.
This PR adds an update_or_insert_one utility that handles this pattern safely by mutating the component if it exists, or lazily inserting it otherwise.