@convai/embody 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +191 -0
  3. package/README.md +165 -0
  4. package/dist/character/createCharacter.d.ts +101 -0
  5. package/dist/character/createCharacter.js +163 -0
  6. package/dist/character/lifecycle.d.ts +55 -0
  7. package/dist/character/lifecycle.js +28 -0
  8. package/dist/character/pipeline.d.ts +46 -0
  9. package/dist/character/pipeline.js +29 -0
  10. package/dist/clips/animations.d.ts +39 -0
  11. package/dist/clips/animations.js +77 -0
  12. package/dist/decorate/types.d.ts +29 -0
  13. package/dist/decorate/types.js +13 -0
  14. package/dist/index.d.ts +30 -0
  15. package/dist/index.js +14 -0
  16. package/dist/motion/blink.d.ts +56 -0
  17. package/dist/motion/blink.js +127 -0
  18. package/dist/motion/breathe.d.ts +72 -0
  19. package/dist/motion/breathe.js +93 -0
  20. package/dist/motion/eyeGaze.d.ts +65 -0
  21. package/dist/motion/eyeGaze.js +66 -0
  22. package/dist/motion/gaze.d.ts +212 -0
  23. package/dist/motion/gaze.js +467 -0
  24. package/dist/motion/reducedMotion.d.ts +13 -0
  25. package/dist/motion/reducedMotion.js +13 -0
  26. package/dist/motion/types.d.ts +16 -0
  27. package/dist/motion/types.js +1 -0
  28. package/dist/react/ConvaiCharacter.d.ts +7 -0
  29. package/dist/react/ConvaiCharacter.js +25 -0
  30. package/dist/react/index.d.ts +4 -0
  31. package/dist/react/index.js +2 -0
  32. package/dist/react/useCharacter.d.ts +11 -0
  33. package/dist/react/useCharacter.js +45 -0
  34. package/dist/resolve/resolver.d.ts +56 -0
  35. package/dist/resolve/resolver.js +45 -0
  36. package/dist/rig/profile.d.ts +64 -0
  37. package/dist/rig/profile.js +110 -0
  38. package/dist/rig/resolve.d.ts +33 -0
  39. package/dist/rig/resolve.js +76 -0
  40. package/dist/rig/units.d.ts +27 -0
  41. package/dist/rig/units.js +61 -0
  42. package/dist/speech/lipsync.d.ts +56 -0
  43. package/dist/speech/lipsync.js +139 -0
  44. package/package.json +109 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @convai/embody
2
+
3
+ All notable changes are recorded here. Versions are managed with
4
+ [changesets](https://github.com/changesets/changesets); add one with
5
+ `pnpm changeset` and the release flow writes this file.
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 Convai
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ # @convai/embody
2
+
3
+ **Give a Convai character a body.**
4
+
5
+ [![npm](https://img.shields.io/badge/npm-0.1.0-blue)](https://www.npmjs.com/package/@convai/embody)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-first-3178C6)](https://www.typescriptlang.org/)
7
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green)](./LICENSE)
8
+
9
+ Resolves ready-to-use 3D characters by `characterId` and drives them with
10
+ lipsync, gaze, breathing and blink. Layered on
11
+ [`@convai/web-sdk`](https://www.npmjs.com/package/@convai/web-sdk).
12
+
13
+ ---
14
+
15
+ > **Branch: `stg`** — this branch defaults to the staging backend, which has
16
+ > its own character database. Use `main` or `prod` for production.
17
+ >
18
+ > **Status: early release (`0.1.0`).** The front-door API is still moving —
19
+ > see [Roadmap](#roadmap).
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pnpm add @convai/embody three
25
+ # React consumers also need:
26
+ pnpm add @react-three/fiber react
27
+ ```
28
+
29
+ `three` and `@convai/web-sdk` are peer dependencies. `react` and
30
+ `@react-three/fiber` are optional peers — the `/core` path needs neither.
31
+
32
+ ## Quick start — React
33
+
34
+ ```tsx
35
+ import { ConvaiCharacter } from '@convai/embody/react'
36
+ import { httpResolver } from '@convai/embody'
37
+
38
+ <ConvaiCharacter
39
+ resolver={httpResolver({ apiKey })} // host defaults per release channel
40
+ characterId={characterId}
41
+ queue={client.blendshapeQueue} // only while this character owns the turn
42
+ />
43
+ ```
44
+
45
+ ## Quick start — core (plain three.js)
46
+
47
+ ```ts
48
+ import { createCharacter, httpResolver } from '@convai/embody'
49
+
50
+ const character = await createCharacter({
51
+ resolver: httpResolver({ apiKey }), // host defaults per release channel
52
+ characterId,
53
+ })
54
+
55
+ scene.add(character.root)
56
+ character.camera = camera
57
+
58
+ renderer.setAnimationLoop(() => {
59
+ character.update(clock.getDelta(), client?.blendshapeQueue)
60
+ renderer.render(scene, camera)
61
+ })
62
+ ```
63
+
64
+ `character.dispose()` releases the model, its materials and textures, the
65
+ mixer, and the reduced-motion listener.
66
+
67
+ ## What it does
68
+
69
+ Eight systems run in an explicit, ordered frame pipeline. The order is
70
+ load-bearing, not incidental:
71
+
72
+ | Stage | System | Why here |
73
+ |---|---|---|
74
+ | 0 normalize | unit normalizer | root scale must settle before anything reads world space |
75
+ | 1 mixer | animation clips | drives the skeleton |
76
+ | 2 gaze | `GazeSystem` | **overrides** the mixer's head rotation rather than blending with it |
77
+ | 3 additive | `BreathingSystem` | added *after* the mixer so nothing accumulates |
78
+ | 4 ik / 5 attach | *(reserved)* | foot lock and hair land here later |
79
+ | 6 morph | lipsync → `EyeGazeSystem` → `BlinkSystem` | blink must run after lipsync to win the eyelid channels |
80
+
81
+ - **Gaze** — head/neck solve about the rig's own axis basis, idle micro-drift,
82
+ occasional look-away shifts with dwell timing, turn banking, camera lock, and
83
+ a deviation pull-back that lets the clip's own head motion flow until it strays.
84
+ - **Breathing** — asymmetric waveform, chest leading the waist, composed onto
85
+ whatever the mixer wrote.
86
+ - **Blink** — asymmetric close/hold/reopen envelope, resting droop that wanders
87
+ rather than loops, partial and double blinks, lids following downward gaze.
88
+ - **Eye gaze** — morph-only on `convai-mha-1`, which has no eye bones.
89
+ - **`prefers-reduced-motion`** damps every additive layer and suppresses
90
+ look-away shifts, while leaving lipsync and clip playback untouched.
91
+
92
+ ## Rigs
93
+
94
+ `convai-mha-1` (the UE MetaHuman rig) is the registered profile. `CC4_LEGACY`
95
+ ships but is deliberately not registered. Bone and morph names are data on the
96
+ profile, so a new rig is a value rather than a code change.
97
+
98
+ ## The resolver seam
99
+
100
+ `CharacterResolver` is the plug point between this package and the asset
101
+ backend. `httpResolver` talks to `GET /character/{id}/embodiment`, but anything
102
+ returning a `CharacterBundle` works — the demo ships an offline fixture
103
+ resolver for backend-free development.
104
+
105
+ ## Docs
106
+
107
+ Design, plan and decision history live in [`docs/`](./docs):
108
+
109
+ | | |
110
+ |---|---|
111
+ | [motion-design.md](./docs/motion-design.md) | the approved design — the binding authority |
112
+ | [motion-implementation-plan.md](./docs/motion-implementation-plan.md) | the 12-task TDD plan |
113
+ | [motion-decisions.md](./docs/motion-decisions.md) | 73 rulings, each with its cost if wrong |
114
+ | [motion-execution-ledger.md](./docs/motion-execution-ledger.md) | the full execution record |
115
+
116
+ ## Release channels
117
+
118
+ The backend host is a source constant, `DEFAULT_BASE_URL` in
119
+ `src/resolve/resolver.ts`, pinned per release branch — the same shape
120
+ `@convai/web-sdk` uses for its connect host.
121
+
122
+ | Branch | Host | npm tag |
123
+ |---|---|---|
124
+ | `stable-release` | `https://api.convai.com` | `latest` |
125
+ | `beta-release` | `https://api.convai.com` | `beta` |
126
+ | `stg-release` | `https://api-stg.convai.com` | `stg` |
127
+
128
+ Beta points at **production** — it is the first line of testing against real
129
+ infrastructure, not a staging channel. Only `stg-release` targets staging,
130
+ which has its own character database.
131
+
132
+ `scripts/check-hosts.mjs` enforces this. Each channel build asserts the policy
133
+ for the release it claims to be, so a staging artifact cannot be cut from
134
+ prod-host source:
135
+
136
+ ```bash
137
+ pnpm build:stg # refuses unless DEFAULT_BASE_URL is the staging host
138
+ pnpm build:beta # refuses unless it is production
139
+ pnpm build:prod # refuses unless it is production
140
+ pnpm check:hosts # auto-detects the current branch
141
+ ```
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ pnpm install
147
+ pnpm test # 86 tests
148
+ pnpm typecheck
149
+ pnpm build # emits dist/ with .d.ts
150
+ pnpm verify # hosts + typecheck + test + build
151
+ pnpm dev # the demo (see demo/verify.md)
152
+ ```
153
+
154
+ ## Roadmap
155
+
156
+ - **Credential-first API.** `apiKey` / `authToken` + `characterId` should be
157
+ enough; the resolver should become optional and be constructed internally.
158
+ The default host now exists, so this is the remaining half.
159
+ - **Retry on expired asset URLs** — re-resolve and retry once on a 403.
160
+ - Foot lock, locomotion, hair physics, idle gestures.
161
+ - Eye saccades and the speech lock.
162
+
163
+ ## License
164
+
165
+ Apache-2.0. See [LICENSE](./LICENSE).
@@ -0,0 +1,101 @@
1
+ /**
2
+ * createCharacter — the orchestrator. Resolve → load → wire → hand back a
3
+ * framework-free handle the app ticks once per frame.
4
+ */
5
+ import * as THREE from 'three';
6
+ import { type CharacterResolver, type CharacterBundle, type Representation } from '../resolve/resolver.js';
7
+ import { type UnitNormalizer } from '../rig/units.js';
8
+ import { AnimationController } from '../clips/animations.js';
9
+ import { LipsyncSystem, type MouthTuning } from '../speech/lipsync.js';
10
+ import { type CharacterDecorator } from '../decorate/types.js';
11
+ import type { BlendshapeQueue } from '@convai/web-sdk/core';
12
+ import { Pipeline } from './pipeline.js';
13
+ import { type ResolvedRig } from '../rig/resolve.js';
14
+ import { GazeSystem, type GazeConfig } from '../motion/gaze.js';
15
+ import { type BreathingConfig } from '../motion/breathe.js';
16
+ import { type EyeGazeConfig } from '../motion/eyeGaze.js';
17
+ import { type BlinkConfig } from '../motion/blink.js';
18
+ import { type ReducedMotion } from '../motion/reducedMotion.js';
19
+ export interface CreateCharacterOptions {
20
+ resolver: CharacterResolver;
21
+ characterId: string;
22
+ /** Rig profiles this build understands, in preference order. */
23
+ supportedRigs?: string[];
24
+ targetHeight?: number;
25
+ groundY?: number;
26
+ mouth?: MouthTuning;
27
+ /** Tier-2 customization: run once after load, before first frame. */
28
+ decorators?: CharacterDecorator[];
29
+ /** Extra local clips (name → url), merged OVER manifest clips by name. */
30
+ animations?: Record<string, string>;
31
+ /** Stage 2 head/neck gaze tracking config. */
32
+ gaze?: GazeConfig;
33
+ /** Stage 6 eyelid/blink config. */
34
+ blink?: BlinkConfig;
35
+ /** Stage 3 additive chest/spine breathing config. */
36
+ breathing?: BreathingConfig;
37
+ /** Stage 6 morph-only eye-look config. */
38
+ eyeGaze?: EyeGazeConfig;
39
+ /**
40
+ * When `false`, register only the units (0), mixer (1) and lipsync (6)
41
+ * systems — no gaze, breathing, eye-look or blink. Default `true`.
42
+ */
43
+ motion?: boolean;
44
+ }
45
+ export interface CharacterHandle {
46
+ root: THREE.Object3D;
47
+ bundle: CharacterBundle;
48
+ representation: Representation;
49
+ animations: AnimationController;
50
+ lipsync: LipsyncSystem;
51
+ rig: ResolvedRig;
52
+ pipeline: Pipeline;
53
+ gaze: GazeSystem;
54
+ /** Set by the app once its camera exists; gaze tracking no-ops without one. */
55
+ camera?: THREE.Camera;
56
+ /** Tick every frame; pass the queue only when this character owns the turn. */
57
+ update(delta: number, queue?: BlendshapeQueue): void;
58
+ /** Stop the reduced-motion media-query watcher. Call on teardown. */
59
+ dispose(): void;
60
+ }
61
+ /**
62
+ * The registration block, factored out as its own seam so it can be tested
63
+ * without a GLB or a network resolver — it only needs objects of the right
64
+ * shape (the `Pick<...>` deps below are satisfied by trivial `{ update() {} }`
65
+ * stubs). `createCharacter` is the only production caller.
66
+ *
67
+ * Registration order in stage 6 is the contract: lipsync, then eye gaze,
68
+ * then blink — see the stage-6 comment below and `pipeline.ts`'s header.
69
+ */
70
+ export declare function buildPipeline(deps: {
71
+ units: Pick<UnitNormalizer, 'update'>;
72
+ animations: Pick<AnimationController, 'update'>;
73
+ lipsync: Pick<LipsyncSystem, 'update'>;
74
+ rig: ResolvedRig;
75
+ }, opts: Pick<CreateCharacterOptions, 'motion' | 'gaze' | 'breathing' | 'eyeGaze' | 'blink'>): {
76
+ pipeline: Pipeline;
77
+ gaze: GazeSystem;
78
+ };
79
+ /**
80
+ * The teardown block, factored out as its own seam (same rationale as
81
+ * `buildPipeline` above) so it can be tested without a GLB — real,
82
+ * lightweight `THREE.BufferGeometry`/`THREE.Material` instances are enough
83
+ * to prove every disposable is actually visited.
84
+ *
85
+ * RULING (2026-09-07 fix wave, "dispose() leaks the entire GLB"):
86
+ * `CharacterHandle.dispose()` used to release only the reduced-motion
87
+ * listener. `<primitive>` does not dispose on unmount, so every geometry,
88
+ * material and texture in the loaded GLB (31MB in the fixture used to
89
+ * measure this), plus the mixer's cached bindings, leaked on every
90
+ * `characterId` change. This traverses the whole scene graph exactly once,
91
+ * disposing every mesh's geometry and material(s) (array-aware) and every
92
+ * texture a material holds (deduped via a `Set`, since decorators or a
93
+ * shared-material GLB can point multiple meshes at the same texture),
94
+ * uncaches the root from the mixer, and detaches the root from its parent.
95
+ */
96
+ export declare function disposeCharacter(deps: {
97
+ root: THREE.Object3D;
98
+ mixer: Pick<THREE.AnimationMixer, 'uncacheRoot'>;
99
+ reducedMotion: Pick<ReducedMotion, 'dispose'>;
100
+ }): void;
101
+ export declare function createCharacter(opts: CreateCharacterOptions): Promise<CharacterHandle>;
@@ -0,0 +1,163 @@
1
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
2
+ import { pickRepresentation } from '../resolve/resolver.js';
3
+ import { createUnitNormalizer } from '../rig/units.js';
4
+ import { AnimationController } from '../clips/animations.js';
5
+ import { LipsyncSystem } from '../speech/lipsync.js';
6
+ import { collectMaterials } from '../decorate/types.js';
7
+ import { Pipeline } from './pipeline.js';
8
+ import { CONVAI_MHA_1 } from '../rig/profile.js';
9
+ import { resolveRig } from '../rig/resolve.js';
10
+ import { GazeSystem } from '../motion/gaze.js';
11
+ import { BreathingSystem } from '../motion/breathe.js';
12
+ import { EyeGazeSystem } from '../motion/eyeGaze.js';
13
+ import { BlinkSystem } from '../motion/blink.js';
14
+ import { createReducedMotion } from '../motion/reducedMotion.js';
15
+ /**
16
+ * The registration block, factored out as its own seam so it can be tested
17
+ * without a GLB or a network resolver — it only needs objects of the right
18
+ * shape (the `Pick<...>` deps below are satisfied by trivial `{ update() {} }`
19
+ * stubs). `createCharacter` is the only production caller.
20
+ *
21
+ * Registration order in stage 6 is the contract: lipsync, then eye gaze,
22
+ * then blink — see the stage-6 comment below and `pipeline.ts`'s header.
23
+ */
24
+ export function buildPipeline(deps, opts) {
25
+ const { units, animations, lipsync } = deps;
26
+ const pipeline = new Pipeline();
27
+ // Stage 0 — root scale must settle before anything reads world space.
28
+ pipeline.add({ stage: 0, update: () => void units.update() });
29
+ // Stage 1 — clips drive the skeleton.
30
+ pipeline.add({ stage: 1, update: (dt) => animations.update(dt) });
31
+ const gaze = new GazeSystem(opts.gaze);
32
+ if (opts.motion !== false) {
33
+ pipeline.add(gaze); // 2 — overrides mixer
34
+ pipeline.add(new BreathingSystem(opts.breathing)); // 3 — additive
35
+ }
36
+ // Stage 6 — ORDER IS THE CONTRACT: lipsync, then eye gaze, then blink.
37
+ pipeline.add({ stage: 6, update: (dt, ctx) => lipsync.update(dt, ctx.queue) });
38
+ if (opts.motion !== false) {
39
+ pipeline.add(new EyeGazeSystem(gaze, opts.eyeGaze));
40
+ pipeline.add(new BlinkSystem(opts.blink, gaze));
41
+ }
42
+ return { pipeline, gaze };
43
+ }
44
+ /** Every material property that can hold a disposable `THREE.Texture`. */
45
+ const TEXTURE_PROPS = [
46
+ 'map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap',
47
+ 'aoMap', 'bumpMap', 'displacementMap', 'alphaMap', 'envMap', 'lightMap',
48
+ 'clearcoatMap', 'clearcoatNormalMap', 'clearcoatRoughnessMap',
49
+ 'sheenColorMap', 'sheenRoughnessMap', 'specularMap', 'specularColorMap',
50
+ 'specularIntensityMap', 'transmissionMap', 'thicknessMap',
51
+ 'iridescenceMap', 'iridescenceThicknessMap', 'gradientMap',
52
+ ];
53
+ /**
54
+ * The teardown block, factored out as its own seam (same rationale as
55
+ * `buildPipeline` above) so it can be tested without a GLB — real,
56
+ * lightweight `THREE.BufferGeometry`/`THREE.Material` instances are enough
57
+ * to prove every disposable is actually visited.
58
+ *
59
+ * RULING (2026-09-07 fix wave, "dispose() leaks the entire GLB"):
60
+ * `CharacterHandle.dispose()` used to release only the reduced-motion
61
+ * listener. `<primitive>` does not dispose on unmount, so every geometry,
62
+ * material and texture in the loaded GLB (31MB in the fixture used to
63
+ * measure this), plus the mixer's cached bindings, leaked on every
64
+ * `characterId` change. This traverses the whole scene graph exactly once,
65
+ * disposing every mesh's geometry and material(s) (array-aware) and every
66
+ * texture a material holds (deduped via a `Set`, since decorators or a
67
+ * shared-material GLB can point multiple meshes at the same texture),
68
+ * uncaches the root from the mixer, and detaches the root from its parent.
69
+ */
70
+ export function disposeCharacter(deps) {
71
+ const { root, mixer, reducedMotion } = deps;
72
+ const disposedTextures = new Set();
73
+ root.traverse((o) => {
74
+ const mesh = o;
75
+ if (!mesh.isMesh)
76
+ return;
77
+ mesh.geometry?.dispose();
78
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
79
+ for (const mat of materials) {
80
+ if (!mat)
81
+ continue;
82
+ const m = mat;
83
+ for (const prop of TEXTURE_PROPS) {
84
+ const tex = m[prop];
85
+ if (tex && !disposedTextures.has(tex)) {
86
+ disposedTextures.add(tex);
87
+ tex.dispose();
88
+ }
89
+ }
90
+ mat.dispose();
91
+ }
92
+ });
93
+ mixer.uncacheRoot(root);
94
+ root.parent?.remove(root);
95
+ reducedMotion.dispose();
96
+ }
97
+ export async function createCharacter(opts) {
98
+ const bundle = await opts.resolver.resolve(opts.characterId);
99
+ const rep = pickRepresentation(bundle, opts.supportedRigs ?? ['convai-mha-1']);
100
+ const loader = new GLTFLoader();
101
+ const modelUrl = rep.model[0].url;
102
+ // clip sources: manifest clips, with local overrides winning by name
103
+ const clipUrls = new Map();
104
+ for (const [name, c] of Object.entries(rep.clips ?? {}))
105
+ clipUrls.set(name, c.url);
106
+ for (const [name, url] of Object.entries(opts.animations ?? {}))
107
+ clipUrls.set(name, url);
108
+ const uniqueUrls = [...new Set(clipUrls.values())];
109
+ const [modelGltf, ...clipGltfs] = await Promise.all([
110
+ loader.loadAsync(modelUrl),
111
+ ...uniqueUrls.map((u) => loader.loadAsync(u)),
112
+ ]);
113
+ const root = modelGltf.scene;
114
+ // gather every clip whose name the manifest/overrides declared
115
+ const wanted = new Set(clipUrls.keys());
116
+ const clips = [];
117
+ for (const g of clipGltfs)
118
+ for (const a of g.animations)
119
+ if (wanted.has(a.name))
120
+ clips.push(a);
121
+ const animations = new AnimationController(root);
122
+ animations.register(clips);
123
+ const lipsync = new LipsyncSystem(opts.mouth);
124
+ lipsync.bind(root);
125
+ for (const d of opts.decorators ?? []) {
126
+ d({ root, bundle, representation: rep, materials: collectMaterials(root) });
127
+ }
128
+ const units = createUnitNormalizer(root, {
129
+ targetHeight: opts.targetHeight,
130
+ groundY: opts.groundY,
131
+ });
132
+ const rig = resolveRig(root, CONVAI_MHA_1);
133
+ const reduced = createReducedMotion();
134
+ const { pipeline, gaze } = buildPipeline({ units, animations, lipsync, rig }, { motion: opts.motion, gaze: opts.gaze, breathing: opts.breathing, eyeGaze: opts.eyeGaze, blink: opts.blink });
135
+ // Reused every frame — mutated in place rather than reallocated, so the
136
+ // per-frame path makes zero steady-state allocations for the frame context.
137
+ const frameCtx = {
138
+ root, rig,
139
+ camera: undefined,
140
+ queue: undefined,
141
+ speaking: false,
142
+ energy: 0,
143
+ reducedMotion: false,
144
+ };
145
+ const handle = {
146
+ root, bundle, representation: rep, animations, lipsync, rig, pipeline, gaze,
147
+ camera: undefined,
148
+ update(delta, queue) {
149
+ frameCtx.camera = handle.camera;
150
+ frameCtx.queue = queue;
151
+ // Produced in stage 6 last frame — deliberately one frame stale (see
152
+ // FrameContext's doc comment on `speaking`/`energy`).
153
+ frameCtx.speaking = lipsync.speaking;
154
+ frameCtx.energy = lipsync.energy;
155
+ frameCtx.reducedMotion = reduced.value;
156
+ pipeline.update(delta, frameCtx);
157
+ },
158
+ dispose() {
159
+ disposeCharacter({ root, mixer: animations.mixer, reducedMotion: reduced });
160
+ },
161
+ };
162
+ return handle;
163
+ }