Skip to main content

Controls and Events

Controls let the user change values while the app runs; events let models, views and controllers react to changes. The two are connected: reacting to a control is subscribing to an event.

The control panel​

AniGraph has a control panel where you can add sliders, color pickers and other controls. Each control's current value is stored in the app state under the control's name, so any code can read it with GetAppState().getState(name).

The control panel

Adding controls​

Add controls in the scene model's initAppState(appState). If a node class comes with its own class-specific controls, it can be useful to define a static SetAppState(appState) function that groups them together, then call that from initAppState, as ParticlePlayground2D does.

// In a node model class that has specific controls associated with it
static ControlKeys = {
MySlider: "MySlider",
MyColor: "MyColor",
MyToggle: "MyToggle",
MyDropdown: "MyDropdown",
MyButton: "MyButton",
}

static SetAppState(appState: AppState){
const keys = MyModel.ControlKeys;
// Slider: name, initial value, min, max, step
appState.addSliderIfMissing(keys.MySlider, 0.5, 0, 1, 0.01);
// Color picker: name, initial color
appState.addColorControl(keys.MyColor, Color.FromString("#00abe0"));
// Checkbox: name, initial value
appState.addCheckboxControl(keys.MyToggle, false);
// Dropdown: name, initial choice, list of choices
appState.setSelectionControl(keys.MyDropdown, "OptionA", ["OptionA", "OptionB", "OptionC"]);
// Button: name, what to do when clicked
appState.addButton(keys.MyButton, ()=>{ console.log("Clicked!"); });
}
Add controls in initAppState

initAppState runs before the panel is first drawn, so controls added there are in place from the start. Controls can still be added later (e.g., in initScene, or in a node's constructor), but the control panel might not automatically resize appropriately, which can hide controls below the visible part of the panel.

That's also why SetAppState is static: no node instances exist yet when initAppState runs. If a button needs to call a method on a particular node, add that button from the scene model, and look the node up inside the callback, as the HierarchyAndAnimation example scene does: appState.addButton("Spin!", ()=>this.orbit?.spin()).

Call a node's controls function through its class: MyModel.SetAppState(appState). AniGraph also exports a global function named SetAppState, which sets up the app state when the app starts. Calling it by accident throws Already set the app state.

As in the snippet above, give each control's name one home, such as a static ControlKeys object on the class that owns it, and always refer to it through that object. A typo in a string key fails silently; a typo in MyModel.ControlKeys.Speeed is a compile error.

Reading controls​

There are two ways to use a control's value.

Read it when you need it. GetAppState().getState(name) returns the current value. This is the simplest option, and a good fit for values used every frame:

updateParticles(t: number, dt: number){
const appState = GetAppState();
const variable1: number = appState.getState(LabCatParticlePlaygroundModel.ControlKeys.Variable1);
// ...
}

Subscribe to changes. If changing a value means redoing some work (for example, rebuilding a shape's geometry when its number of spikes changes), subscribe from the node that cares:

// In a node model's constructor:
this.subscribeToAppState(MyShapeModel.ControlKeys.NSpikes, (n: number)=>{
this.rebuildGeometry(n);
});

subscribeToAppState(name, callback) is shorthand for this.subscribe(GetAppState().addStateValueListener(name, callback)). You can pass a third argument, a handle, if you want to unsubscribe later (see Events).

Read the node's own controls inside the node, where they're used, rather than having the scene model copy slider values into nodes.

Subscriptions only fire when a control changes, so apply the current value once yourself when the node is built. SpikyStarModel.ts (in HierarchyAndAnimation) shows both ways of using controls side by side: it builds its geometry once in the constructor, subscribes to its spikes, spikiness and color controls to rebuild it, and reads its scale and rotation sliders every frame in timeUpdate.

getState returns the control's own Color (or Vec2) object, so .clone() it if you plan to keep it or change it.

Setting a control from code. GetAppState().setControlPanelStateValue(name, value) changes a control's value and moves it in the panel (setState alone would not move the slider). HierarchyAndAnimation uses it so that dragging an arm link also moves that link's rotation slider.

Why so indirect?

At this point you may ask yourself, "Geez Abe, why do everything so indirectly? The control panel updates the app state, which signals an event that the model listens to, so that the model can signal ANOTHER event that the view listens to... Why???" Good question. The indirection makes everything modular, which is really useful in bigger applications. It also means a node can be moved to another scene and take its controls with it.

Events and subscriptions​

Callbacks are functions that sit around waiting for a particular event to happen. When it does, they do their thing, which is whatever you told them to do...

Models, views and controllers can all signal events and subscribe to them. The typical use: a model signals that something changed, and its view listens and redraws. When StarterScene's StarterShapeModel changes its geometry, it calls signalGeometryUpdate(), and StarterShapeView listens in its init():

// Rebuild the graphic whenever the model signals that its geometry changed.
// Passing the listener to subscribe means it is removed when this view is released.
this.subscribe(this.model.addGeometryListener(()=>{
this.element.setVerts2D(this.model.verts);
}));

Custom events. For changes specific to your node, signal an event of your own: this.signalEvent(name, ...args) sends it, and model.addEventListener(name, callback, handle?) listens for it. Keep event names in one place (for example a static Events = {...} on the class), and make them unique to the class. It's convenient to wrap the pair in methods, like signalGeometryUpdate()/addGeometryListener(...), so callers don't need to know the event's name.

addEventListener returns a callback switch. this.subscribe(switch, handle) stores it on the subscribing object, so that it is cleaned up when that object is released. With a handle, you can manage it later:

this.subscribe(this.model.addGeometryListener(()=>{ /* ... */ }), "GeometrySubscription");
this.deactivateSubscription("GeometrySubscription"); // pause
this.activateSubscription("GeometrySubscription"); // resume
this.unsubscribe("GeometrySubscription"); // remove

Use arrow functions (()=>{...}) for callbacks, as above, so that this inside the callback still refers to your object. Don't pass a method directly (addButton("Go", this.spin)); wrap it in an arrow function (()=>this.spin()). You may see const self = this; in AniGraph code, with self used inside the callback instead of this. This is optional. It makes it explicit which object the callback belongs to, since what this refers to depends on where the code runs.

Views listen for their model's transform changes by default. When the transform changes, the view re-applies it on its own. Geometry changes are different. signalGeometryUpdate() calls the view's update(), which in most views only re-applies the transform. To rebuild the graphics, either subscribe with this.subscribe(this.model.addGeometryListener(...)) in the view's init(), as StarterShapeView, PolygonView2D and WaveLineView all do, or rebuild them in update(). Beyond those two, you only need custom events for things specific to your node.