| 39 | == Message passing == |
| 40 | |
| 41 | Direct method calls between components are sometimes necessary, but they force component implementations to know details of other components. For example, a `Position` component may want to notify many other components when the entity moves (e.g. any components that want to detect when an entity is within a certain range, or set it on fire if it's walking on lava), and it would be bad (complex, inflexible) if the `Position` component type's code had to know about every other component type it should notify. |
| 42 | |
| 43 | The '''message passing''' system helps with this case. Component types can '''subscribe''' to a particular message type, and components can '''post''' or '''broadcast''' a message with a type and associated data, which will be received by all subscribed components. (''Post'' sends the message to the components with a specific entity ID, ''broadcast'' sends to component of all entities). For example, the burn-on-lava component can subscribe to the `PositionChanged` message type, and the `Position` component can then post a `PositionChanged` message to its own entity ID, and the burn component's message handler function will be called. The `Position` component only has to know about this message type, not about any of the components that use it. |
| 44 | |
| 45 | Messages are one-to-many communication (any number of components can receive a single posted message), and they are one-way (it is not possible to return a value in response to a message). Components are notified in a consistent but arbitrary order. |
| 46 | |
| 47 | (TODO: the post vs broadcast semantics are not very well designed currently.) |
| 48 | |