# 2. FaceRig and the Layer Mixer
Part of [[Facial Animation and Lip Sync]]. Previous: [[1. Faces Blendshapes and the Performance Budget]]. Next: [[3. Expressions from Ink Mood Tags]].
## 2.1 Why a mixer
Three systems want the same blendshapes at once:
- The **expression** ("angry") wants `browDown` at 80 and a little `jawOpen`.
- The **mouth** (lip sync) wants `jawOpen` at 60 for an "aa".
- The **blink** wants `eyeBlinkLeft` at 100 for 90 ms, even while the expression is "surprised" (`eyeWide`).
If each one calls `SetBlendShapeWeight` directly, the last writer wins and the face flickers. Instead, each system writes into its own **layer**, and one mixer combines them in a fixed order, once per frame:
| Order | Layer | Mode | Why |
|---|---|---|---|
| 1 | expression | Additive | Moods can stack (a smile plus raised brows) |
| 2 | visemes | Override, weight fades 0↔1 | While talking, the mouth shape replaces the expression's mouth |
| 3 | blink | Override | A blink always closes the eye, whatever the mood |
**Override** means "lerp each channel *this layer touches* toward my value by my weight". Channels it doesn't touch pass through unchanged. That's how blinking leaves the smile alone.
This is the same idea as Animator layers with avatar masks ([[1.Layer Stacks and Avatar Masks Deep Dive]]), at blendshape scale. Writing it ourselves keeps it testable and lets dialogue code poke layers directly.
## 2.2 FaceMixer (pure C#)
Channels are interned names. Ask for `Channel("jawOpen")` once, keep the `int`, and never look a string up per frame.
```csharp
using System;
using System.Collections.Generic;
/// <summary>
/// Mixes named face channels (blendshapes) from several layers into one weight array (0..100).
/// Layers are evaluated in order: Additive layers add (scaled by layer weight), Override layers
/// lerp each channel they touch toward their value by the layer weight. Untouched channels pass through.
/// Typical stack: Expression (additive) -> Visemes (override mouth) -> Blink (override eyelids).
/// No UnityEngine types, so it is testable outside Unity.
/// </summary>
public sealed class FaceMixer
{
public enum Mode { Additive, Override }
public sealed class Layer
{
internal readonly Dictionary<int, float> Values = new Dictionary<int, float>();
internal Layer(string name, Mode mode)
{
Name = name;
LayerMode = mode;
}
public string Name { get; }
public Mode LayerMode { get; }
public float Weight { get; set; } = 1f;
public void Set(int channel, float value) => Values[channel] = value;
public void Clear() => Values.Clear();
public bool TryGet(int channel, out float value) => Values.TryGetValue(channel, out value);
}
readonly List<string> _channels = new List<string>();
readonly Dictionary<string, int> _index = new Dictionary<string, int>(StringComparer.Ordinal);
readonly List<Layer> _layers = new List<Layer>();
float[] _output = Array.Empty<float>();
public int ChannelCount => _channels.Count;
public IReadOnlyList<string> Channels => _channels;
public IReadOnlyList<float> Output => _output;
/// <summary>Returns the channel id for a name, adding it if new.</summary>
public int Channel(string name)
{
if (_index.TryGetValue(name, out var id))
return id;
id = _channels.Count;
_channels.Add(name);
_index[name] = id;
Array.Resize(ref _output, _channels.Count);
return id;
}
public bool TryChannel(string name, out int id) => _index.TryGetValue(name, out id);
public Layer AddLayer(string name, Mode mode)
{
var layer = new Layer(name, mode);
_layers.Add(layer);
return layer;
}
/// <summary>Computes Output. Call once per frame after all layers are written.</summary>
public IReadOnlyList<float> Evaluate()
{
Array.Clear(_output, 0, _output.Length);
for (var l = 0; l < _layers.Count; l++)
{
var layer = _layers[l];
var w = Clamp01(layer.Weight);
if (w <= 0f)
continue;
foreach (var kv in layer.Values)
{
var c = kv.Key;
if (c < 0 || c >= _output.Length)
continue;
if (layer.LayerMode == Mode.Additive)
_output[c] += kv.Value * w;
else
_output[c] += (kv.Value - _output[c]) * w;
}
}
for (var i = 0; i < _output.Length; i++)
_output[i] = Math.Max(0f, Math.Min(100f, _output[i]));
return _output;
}
static float Clamp01(float v) => v < 0f ? 0f : v > 1f ? 1f : v;
}
```
Worked example (it's a test in part 7): the expression sets `jawOpen` = 10, and the visemes layer sets 80 at weight 0.5. The jaw ends up at 10 + (80 − 10) × 0.5 = **45**. The blink layer at weight 1 sets `eyeBlinkLeft` to 100, overriding the expression's 20.
## 2.3 FaceRig (the Unity side)
`FaceRig` owns the mixer, creates the three layers in `Awake`, and in `LateUpdate`:
1. rebuilds the name→index maps if new channels were registered (each renderer may or may not have each shape)
2. evaluates the mixer
3. writes **only the weights that changed** by at least 0.01
It drives a list of renderers because faces are often split: head, teeth, tongue, eyebrows and beard are separate meshes, and all of them need the same `jawOpen`.
```csharp
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Owns a FaceMixer and writes its output to every SkinnedMeshRenderer that has a blendshape
/// of the same name (face, teeth, tongue, brows, beard). Runs in LateUpdate after the Animator,
/// so procedural face layers win over any blendshape curves in animation clips.
/// Layers: "expression" (additive), "visemes" (override), "blink" (override).
/// </summary>
[DefaultExecutionOrder(100)]
public sealed class FaceRig : MonoBehaviour
{
[SerializeField] SkinnedMeshRenderer[] renderers;
[Tooltip("Optional: rename rig-specific blendshapes to the names this system uses (e.g. 'Fcl_EYE_Close_L' -> 'eyeBlinkLeft').")]
[SerializeField] NameAlias[] aliases;
[SerializeField] bool logMissingChannels = true;
[System.Serializable]
public struct NameAlias
{
public string channel;
public string blendShape;
}
readonly FaceMixer _mixer = new FaceMixer();
// Per renderer: channel id -> blendshape index (-1 if that renderer doesn't have it).
readonly List<int[]> _maps = new List<int[]>();
readonly List<float[]> _lastWritten = new List<float[]>();
int _mappedChannelCount = -1;
public FaceMixer.Layer Expression { get; private set; }
public FaceMixer.Layer Visemes { get; private set; }
public FaceMixer.Layer Blink { get; private set; }
void Awake()
{
Expression = _mixer.AddLayer("expression", FaceMixer.Mode.Additive);
Visemes = _mixer.AddLayer("visemes", FaceMixer.Mode.Override);
Blink = _mixer.AddLayer("blink", FaceMixer.Mode.Override);
}
/// <summary>Channel id for a name. Cache it; ids never change.</summary>
public int Channel(string name) => _mixer.Channel(name);
void LateUpdate()
{
if (_mappedChannelCount != _mixer.ChannelCount)
RebuildMaps();
var output = _mixer.Evaluate();
for (var r = 0; r < renderers.Length; r++)
{
var smr = renderers[r];
if (smr == null)
continue;
var map = _maps[r];
var last = _lastWritten[r];
for (var c = 0; c < map.Length; c++)
{
var index = map[c];
if (index < 0)
continue;
var w = output[c];
// Only touch blendshapes whose value changed; SetBlendShapeWeight isn't free.
if (Mathf.Abs(last[c] - w) < 0.01f)
continue;
smr.SetBlendShapeWeight(index, w);
last[c] = w;
}
}
}
void RebuildMaps()
{
_maps.Clear();
_lastWritten.Clear();
var channels = _mixer.Channels;
for (var r = 0; r < renderers.Length; r++)
{
var map = new int[channels.Count];
var last = new float[channels.Count];
var mesh = renderers[r] != null ? renderers[r].sharedMesh : null;
for (var c = 0; c < channels.Count; c++)
{
last[c] = -1f;
map[c] = mesh != null ? mesh.GetBlendShapeIndex(Resolve(channels[c])) : -1;
}
_maps.Add(map);
_lastWritten.Add(last);
}
if (logMissingChannels)
{
for (var c = 0; c < channels.Count; c++)
{
var found = false;
for (var r = 0; r < _maps.Count; r++)
found |= _maps[r][c] >= 0;
if (!found)
Debug.LogWarning(
quot;FaceRig: no renderer has a blendshape for channel '{channels[c]}'.", this);
}
}
_mappedChannelCount = channels.Count;
}
string Resolve(string channel)
{
if (aliases != null)
{
foreach (var a in aliases)
{
if (a.channel == channel)
return a.blendShape;
}
}
return channel;
}
}
```
Setup:
1. Add `FaceRig` to the character root (or the head object).
2. Drag in every `SkinnedMeshRenderer` that has face shapes.
3. Add aliases where your rig's names differ, for example channel `eyeBlinkLeft` → blendshape `Fcl_EYE_Close_L` (VRoid-style), or `jawOpen` → `MTH_A`.
4. Press Play. Any channel no renderer has logs **one warning** at the first rebuild, which is your checklist of missing shapes.
> [!note] Why `[DefaultExecutionOrder(100)]`
> The Animator writes its pose during the animation update, which happens after `Update` and before `LateUpdate`. A `LateUpdate` with a high execution order runs after other `LateUpdate`s, including `EyeGaze` at 90, so the face is the last word. If you use Animation Rigging or another late system that also writes blendshapes, check its order. Blendshapes written by `FaceRig` are overwritten if the Animator has curves for the same shapes and something re-evaluates it later in the frame.
## 2.4 Design notes
- **Mixer as data, rig as adapter.** The mixer knows nothing about meshes, so the tests in part 7 run without Unity. `FaceRig` is a thin adapter, the same split as the *Component* chapter of [[Game Programming Patterns (Review)]].
- **No per-frame allocation.** Channel ids are ints, layers are dictionaries filled with `Set`, and output is one reused array. The `foreach` over a `Dictionary<int,float>` uses the struct enumerator, which doesn't allocate.
- **Additive clamping.** Two additive moods can push a channel past 100. The mixer clamps the *final* value, not each layer, so an override layer can still pull a 140 back down before the clamp.
## Exercises
1. Add a fourth layer, `"gesture"` (Override), for one-shot faces such as a wince on hit, and fade its weight 1→0 over 0.4 s from a `Wince()` method.
2. Extend `FaceRig` so `logMissingChannels` lists which *renderers* lack a shape that others have. A tongue mesh missing `jawOpen` is a classic bug.