# How do I go about creating the “Watcher” component?

Last weekend, I spent several hours writing a basic entity component model, in JavaScript. I was largely referencing the Ash Actionscript game engine. I successfully worked out how the systems, components, nodes, and entities all link up, but one thing that eludes me is how to implement the "watcher" that checks the entities for their components, creates nodes for them, adds those nodes to the various systems automatically, and watches for any changes in the components on an entity. I was a bit confused by the way it works, in Ash, and all of the posts and tutorials on the subject that I have read seem to forgo the details of that part of the implementation.

Right now, I currently have the following:

• Entity, which is assigned components.
• Engine, which keeps a track of the systems and entities.
• Node, which contains references to the components in an entity that we want the system to modify (I am currently creating these, manually, and adding it to the system).
• Component, which contains the data to be modified by the system.
• System, which operates on the nodes, which in turn change the data in the entity.
• I also have various other classes, dedicated to holding lists of the various objects.

How do I go about creating the "Watcher" component?

I think simplicity is key when designing these systems. What I do is associate a bitmask with each entity where each component type corresponds to a bit; the bit is switched on if the entity contains a component of that type. I give the entity/component manager a couple of helper functions to change the bitmask when adding and removing components.

If you associate each system with a component bitmask as well, it is trivial to build the set of entities to be processed by a given system. You can then do one of two things:

1. Make each system loop through all entities each frame, skipping those that do not satisfy the system's component requirements.

2. Each frame, check the entities which have been modified and loop through all the systems, registering the entity with each system that is able to use it.

To store the components, I use a struct-of-arrays approach where each component type is an array (possibly with another layer of indirection) and each entity is an index into all the component pools. All the systems have access to this data, and accessing components is as easy as world.type[entity].

It's difficult to figure out exactly what you need, but it seems like you want to use something similar to the Observer Pattern or the Publish-Subscribe Pattern.

Basically your entities would become observers/subscribers and your "watcher" would be the subject/publisher.

• Thanks, I will take a look. Going to wait a bit though before accepting an answer. – Zerocaliber Apr 29 '13 at 5:07