dsh-quay-bot 1.0.2 → 1.0.6

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 (61) hide show
  1. package/README.md +28 -105
  2. package/botscreen/requirements.txt +1 -1
  3. package/client.js +123 -53
  4. package/cordis.patch.yml +1 -1
  5. package/host/api.js +4 -0
  6. package/host/remote.js +285 -8
  7. package/host/screen.js +22 -86
  8. package/package.json +34 -32
  9. package/remote/bin/dsh-remote.mjs +435 -0
  10. package/remote/package.json +27 -0
  11. package/remote/src/config.mjs +183 -0
  12. package/remote/src/crypto.mjs +220 -0
  13. package/remote/src/keys.mjs +226 -0
  14. package/remote/src/proxy.mjs +1028 -0
  15. package/remote/src/sessions.mjs +163 -0
  16. package/remote/src/shim.js +838 -0
  17. package/remote/src/supervisor.mjs +207 -0
  18. package/remote/src/tunnel.mjs +533 -0
  19. package/remote/src/upstream.mjs +403 -0
  20. package/remote/src/util.mjs +149 -0
  21. package/remote/src/ws.mjs +313 -0
  22. package/LICENSE +0 -21
  23. package/avatar/build.mjs +0 -81
  24. package/avatar/gallery/droid.json +0 -14
  25. package/avatar/gallery/ghost.json +0 -14
  26. package/avatar/gallery/grok-pod.json +0 -14
  27. package/avatar/gallery/guardian.json +0 -14
  28. package/avatar/gallery/mecha.json +0 -14
  29. package/avatar/gallery/mochi.json +0 -14
  30. package/avatar/gallery/neko.json +0 -14
  31. package/avatar/gallery/orbiter.json +0 -14
  32. package/avatar/gallery/relay.json +0 -14
  33. package/avatar/gallery/spark.json +0 -14
  34. package/avatar/src/bot/clay.ts +0 -135
  35. package/avatar/src/bot/effects.ts +0 -100
  36. package/avatar/src/bot/grok-bot.ts +0 -626
  37. package/avatar/src/bot/index.ts +0 -15
  38. package/avatar/src/bot/palettes.ts +0 -62
  39. package/avatar/src/bot/ring.ts +0 -219
  40. package/avatar/src/bot/scheduler.ts +0 -239
  41. package/avatar/src/bot/shapes.ts +0 -277
  42. package/avatar/src/bot/spring.ts +0 -196
  43. package/avatar/src/core/color.ts +0 -92
  44. package/avatar/src/core/eyes.ts +0 -297
  45. package/avatar/src/core/field.ts +0 -482
  46. package/avatar/src/core/frame.ts +0 -655
  47. package/avatar/src/core/fx.ts +0 -375
  48. package/avatar/src/core/index.ts +0 -49
  49. package/avatar/src/core/paint.ts +0 -331
  50. package/avatar/src/core/path.ts +0 -495
  51. package/avatar/src/core/pose.ts +0 -581
  52. package/avatar/src/core/svg.ts +0 -98
  53. package/avatar/src/core/types.ts +0 -153
  54. package/avatar/src/core/validate.ts +0 -296
  55. package/avatar/src/core/volume.ts +0 -681
  56. package/avatar/src/entry.ts +0 -260
  57. package/bin/doctor.mjs +0 -148
  58. package/botscreen/requirements-offline.txt +0 -11
  59. package/market/index.json +0 -41
  60. package/vendor/pip/pip-25.1.1-py3-none-any.whl +0 -0
  61. package/vendor/pip/setuptools-78.1.1-py3-none-any.whl +0 -0
@@ -1,655 +0,0 @@
1
- /**
2
- * 把“定义 + 体积 + 姿态”压成一帧扁平数据:每个截面及其投影矩阵、两只眼睛、
3
- * 身前的彩带与标记。任何矢量渲染器(canvas、SVG、Skia)都能照着画。
4
- *
5
- * 投影是正交投影:先绕竖直轴 yaw,再绕水平轴 pitch。截面按到观察者的深度
6
- * 从后往前排序,于是叠起来就是实体的剪影,看不到平面的“侧面”。
7
- */
8
- import { oklch, parseHex, toHex, toOklch, type Rgb } from './color.ts';
9
- import { bloomPieces, bodyScale, markParts, ribbonPieces, rimOf, type Box, type Rim } from './fx.ts';
10
- import { eyePath, plainLook, type EyeSpot } from './eyes.ts';
11
- import { blendPoses, hashString, computePose, type Pose } from './pose.ts';
12
- import type { PoseLike } from './types.ts';
13
- import type { Bounds, Point } from './path.ts';
14
- import { EYE_H, EYE_W, GAZE_X, GAZE_Y, HAPPY_ARC, analyzeBody, eyeCenters, gazeRange, validateAvatar, type BodyAnalysis, type GazeRange } from './validate.ts';
15
- import { buildVolume, type EyePlane, type Volume, type VolumeSlice } from './volume.ts';
16
- import type { AvatarDefinition, RenderOptions } from './types.ts';
17
- import { derivePalette } from '../bot/palettes.ts';
18
- import { RING_ENVELOPE, ringPath } from '../bot/ring.ts';
19
- import { badgePiece, orbitPieces } from '../bot/effects.ts';
20
-
21
- export const DEFAULT_COLOR = '#ff6a1a';
22
- export const DEFAULT_EYE_COLOR = '#151515';
23
- /** `depth` 选项里对应“自然体积”的值。 */
24
- export const DEFAULT_DEPTH = 6;
25
- const MAX_DEPTH = 14;
26
-
27
- export type Matrix = [number, number, number, number, number, number];
28
-
29
- export type EyeMark =
30
- | { shape: 'pill'; x: number; y: number; width: number; height: number; radius: number }
31
- | { shape: 'arc'; d: string; strokeWidth: number }
32
- | { shape: 'path'; d: string };
33
-
34
- export interface FramePath {
35
- id: string;
36
- d: string;
37
- evenOdd: boolean;
38
- box: Box;
39
- }
40
-
41
- export type FrameShape =
42
- | { kind: 'slice'; key: string; path: string; matrix: Matrix }
43
- | { kind: 'eye'; key: 'eye-0' | 'eye-1'; matrix: Matrix; mark: EyeMark }
44
- | {
45
- kind: 'ribbon';
46
- key: string;
47
- d: string;
48
- box: Box;
49
- matrix: Matrix;
50
- front: boolean;
51
- gradient: { x1: number; y1: number; x2: number; y2: number; stops: string[] };
52
- }
53
- | { kind: 'mark'; key: string; id: string; d: string; box: Box; matrix: Matrix }
54
- | { kind: 'particle'; key: string; d: string; box: Box; matrix: Matrix; fill: string; front: boolean };
55
-
56
- export interface Frame {
57
- name: string;
58
- color: string;
59
- highlight: string;
60
- shadow: string;
61
- clay: boolean;
62
- bodyBox: Bounds;
63
- ink: string;
64
- paths: FramePath[];
65
- /** 身体整体的 2D 动作(跳、摇、压扁),作用在所有形状上。 */
66
- root: Matrix;
67
- /** 从后往前。 */
68
- shapes: FrameShape[];
69
- /** 这一帧的姿态(已含缓动),可以直接作为下一帧的 `poseBlend.from`。 */
70
- pose: PoseLike;
71
- }
72
-
73
- // ---------------------------------------------------------------------------
74
- // 视图数学
75
-
76
- export interface ViewBasis {
77
- cY: number;
78
- sY: number;
79
- cP: number;
80
- sP: number;
81
- /** cos(yaw)·cos(pitch):> 0 表示正面朝向观察者。 */
82
- facing: number;
83
- }
84
-
85
- export function viewBasis(yaw: number, pitch: number): ViewBasis {
86
- const cY = Math.cos(yaw);
87
- const cP = Math.cos(pitch);
88
- return { cY, sY: Math.sin(yaw), cP, sP: Math.sin(pitch), facing: cY * cP };
89
- }
90
-
91
- /** 该视角下,模型空间方向朝向观察者的分量(1 = 正对)。 */
92
- export function facingOf(v: ViewBasis, [x, y, z]: [number, number, number]): number {
93
- return v.sP * y + v.cP * (-v.sY * x + v.cY * z);
94
- }
95
-
96
- export const mul = (m: Matrix, n: Matrix): Matrix => [
97
- m[0] * n[0] + m[2] * n[1],
98
- m[1] * n[0] + m[3] * n[1],
99
- m[0] * n[2] + m[2] * n[3],
100
- m[1] * n[2] + m[3] * n[3],
101
- m[0] * n[4] + m[2] * n[5] + m[4],
102
- m[1] * n[4] + m[3] * n[5] + m[5],
103
- ];
104
- const translate = (x: number, y: number): Matrix => [1, 0, 0, 1, x, y];
105
- const about = (x: number, y: number, m: Matrix): Matrix => mul(translate(x, y), mul(m, translate(-x, -y)));
106
- const invert = ([a, b, c, d, e, g]: Matrix): Matrix => {
107
- const det = a * d - b * c;
108
- return [d / det, -b / det, -c / det, a / det, (c * g - d * e) / det, (b * e - a * g) / det];
109
- };
110
-
111
- export const pivotOf = (b: Bounds): Point => [(b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2];
112
-
113
- /** 深度 z 的平面在 `pivot` 处的正交投影矩阵(yaw 后 pitch)。 */
114
- export function planeMatrix(v: ViewBasis, z: number, pivot: Point): Matrix {
115
- const [cx, cy] = pivot;
116
- return [
117
- v.cY,
118
- v.sY * v.sP,
119
- 0,
120
- v.cP,
121
- cx - v.cY * cx + v.sY * z,
122
- cy - v.cP * cy - v.sY * v.sP * cx - v.cY * v.sP * z,
123
- ];
124
- }
125
-
126
- /** 侧平面 x = x0 的投影,其局部坐标是 (u = −z, y)。 */
127
- export function sidePlaneMatrix(v: ViewBasis, x0: number, pivot: Point): Matrix {
128
- const [cx, cy] = pivot;
129
- return [-v.sY, v.cY * v.sP, 0, v.cP, cx + v.cY * (x0 - cx), cy - v.cP * cy + v.sY * v.sP * (x0 - cx)];
130
- }
131
-
132
- export function projectPoint(v: ViewBasis, [x, y, z]: [number, number, number], pivot: Point): [number, number, number] {
133
- const m = planeMatrix(v, z, pivot);
134
- const X = x - pivot[0];
135
- const Y = y - pivot[1];
136
- return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5], v.sP * Y + v.cP * (-v.sY * X + v.cY * z)];
137
- }
138
-
139
- /** 哪一叠截面更朝向观察者:朝前的 z 平面,还是朝侧的 x 平面。 */
140
- export function activeStack(v: ViewBasis): 'z' | 'x' {
141
- return Math.abs(v.cY) >= Math.abs(v.sY) ? 'z' : 'x';
142
- }
143
-
144
- /** 眼睛的切平面矩阵:先在平面上放一个矩形,再按表面斜率倾斜。 */
145
- function eyeMatrix(v: ViewBasis, { x, y, z, dzdx, dzdy }: EyePlane, pivot: Point): Matrix {
146
- const m = planeMatrix(v, z - x * dzdx - y * dzdy, pivot);
147
- m[0] += v.sY * dzdx;
148
- m[1] -= v.cY * v.sP * dzdx;
149
- m[2] += v.sY * dzdy;
150
- m[3] -= v.cY * v.sP * dzdy;
151
- return m;
152
- }
153
-
154
- /** 单位平面法线在该视角下是否朝向观察者(侧到极限时面积趋于 0)。 */
155
- function eyeVisible(v: ViewBasis, plane: EyePlane): boolean {
156
- return facingOf(v, [-plane.dzdx, -plane.dzdy, 1]) > 1e-6;
157
- }
158
-
159
- /** 跳、摇、压扁都以身体底部为支点。 */
160
- function rootMatrix(pose: Pose, b: Bounds): Matrix {
161
- const bx = (b.minX + b.maxX) / 2;
162
- const by = b.maxY;
163
- const r = (pose.roll * Math.PI) / 180;
164
- const rot: Matrix = [Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0];
165
- return mul(translate(0, pose.lift), about(bx, by, mul(rot, [pose.sx, 0, 0, pose.sy, 0, 0])));
166
- }
167
-
168
- /** 圆润的身体弹得更狠:越接近圆,压扁/拉伸与弹跳的幅度越大(弹性球体的手感)。 */
169
- export function elasticityOf(b: Bounds): number {
170
- const w = b.maxX - b.minX;
171
- const h = b.maxY - b.minY;
172
- const ratio = Math.min(w, h) / Math.max(w, h || 1);
173
- return Math.min(1.5, Math.max(0.55, 0.55 + 0.9 * ratio));
174
- }
175
-
176
- /** 按弹性系数放大姿态里的形变(压扁、拉伸、弹跳、摇摆),让圆身子的头像更有橡皮感。 */
177
- export function applyElasticity(pose: Pose, k: number): Pose {
178
- if (!Number.isFinite(k) || k <= 0) return pose;
179
- return {
180
- ...pose,
181
- sy: 1 + (pose.sy - 1) * k,
182
- sx: 1 + (pose.sx - 1) * k,
183
- lift: pose.lift * k,
184
- roll: pose.roll * Math.min(1.2, k),
185
- };
186
- }
187
-
188
- /** 缓动:两端平缓、中间快(smoothstep)。 */
189
- const smoothstep = (t: number): number => {
190
- const x = Math.min(1, Math.max(0, t));
191
- return x * x * (3 - 2 * x);
192
- };
193
-
194
- const clampedDepth = (depth: number | undefined): number => {
195
- const d = Math.min(MAX_DEPTH, Math.max(0, Number.isFinite(depth) ? (depth as number) : DEFAULT_DEPTH));
196
- return Math.round(d * 2) / 2;
197
- };
198
-
199
- // ---------------------------------------------------------------------------
200
- // 预计算与缓存
201
-
202
- export interface Prepared {
203
- def: AvatarDefinition;
204
- body: BodyAnalysis;
205
- vol: Volume;
206
- range: GazeRange;
207
- seed: number;
208
- id: string;
209
- ids: Map<string, string>;
210
- rim: () => Rim;
211
- }
212
-
213
- const cache = new Map<string, Prepared>();
214
-
215
- /** 校验后的定义与其缓存体积,与渲染器实际使用的完全一致。 */
216
- export function prepare(definition: AvatarDefinition, depth?: number): Prepared {
217
- const key = JSON.stringify([definition?.id, definition?.name, definition?.body?.path, definition?.eyes, clampedDepth(depth)]);
218
- const hit = cache.get(key);
219
- if (hit) return hit;
220
- const res = validateAvatar(definition);
221
- if (!res.ok) throw new Error(`Invalid avatar definition: ${res.errors.join('; ')}`);
222
- const def = res.value;
223
- const body = analyzeBody(def.body.path);
224
- const vol = buildVolume(def, clampedDepth(depth) / DEFAULT_DEPTH, body);
225
- const id = `obr-${hashString(`${def.id}|${def.body.path}|${clampedDepth(depth)}`).toString(36)}`;
226
- const ids = new Map<string, string>();
227
- for (const part of vol.parts) {
228
- for (const s of [...part.zSlices, ...part.xSlices]) if (!ids.has(s.d)) ids.set(s.d, `${id}-${ids.size}`);
229
- }
230
- let rim: Rim | undefined;
231
- const prepared: Prepared = {
232
- def,
233
- body,
234
- vol,
235
- range: gazeRange(body.polys, { ...def.eyes, scale: vol.eyeScale }),
236
- seed: hashString(def.id),
237
- id,
238
- ids,
239
- rim: () => (rim ??= rimOf(body.polys, (vol.bounds.minX + vol.bounds.maxX) / 2, (vol.bounds.minY + vol.bounds.maxY) / 2)),
240
- };
241
- if (cache.size >= 48) cache.delete(cache.keys().next().value as string);
242
- cache.set(key, prepared);
243
- return prepared;
244
- }
245
-
246
- // ---------------------------------------------------------------------------
247
- // 眼睛
248
-
249
- interface EyeState {
250
- x: number;
251
- y: number;
252
- w: number;
253
- h: number;
254
- dx: number;
255
- dy: number;
256
- open: number;
257
- shift: number;
258
- /** 这只眼睛完全闭着(眨眼到顶)。 */
259
- closed: boolean;
260
- plain: 'pill' | 'arc' | null;
261
- look: Pose['eyes'];
262
- /** 高光强度(0 = 不画)。 */
263
- glint: number;
264
- }
265
-
266
- function eyeStates(p: Prepared, pose: Pose): [EyeState, EyeState] {
267
- const s = p.vol.eyeScale;
268
- const w = EYE_W * s;
269
- const h = EYE_H * s;
270
- const r = p.range;
271
- const dx = pose.gazeX * (pose.gazeX >= 0 ? r.right : r.left) * GAZE_X * s;
272
- const dy = pose.gazeY * (pose.gazeY >= 0 ? r.down : r.up) * GAZE_Y * s;
273
- const centers = eyeCenters(p.def.eyes);
274
- return ([0, 1] as const).map((i) => {
275
- const squint = i === 0 ? pose.squintL : pose.squintR;
276
- // 上眼皮下垂(困)与眯眼一起压高度;闭眼另走闭眼线,不靠“压成一条”硬凑。
277
- const lid = Math.max(0, Math.min(1, pose.eyes.lid * 0.82 + squint * 0.4));
278
- const openness = (1 - pose.blink) * (1 - lid);
279
- const closed = pose.blink > 0.92;
280
- const open = Math.max(h * Math.max(0.09, openness), w * 0.55);
281
- return {
282
- x: centers[i][0],
283
- y: centers[i][1],
284
- w,
285
- h,
286
- dx,
287
- dy,
288
- open,
289
- shift: (h - open) * 0.18,
290
- closed,
291
- plain: plainLook(pose.eyes),
292
- look: pose.eyes,
293
- glint: pose.eyes.glint,
294
- };
295
- }) as [EyeState, EyeState];
296
- }
297
-
298
- function spotOf(e: EyeState, withGaze: boolean): EyeSpot {
299
- return {
300
- x: e.x + (withGaze ? e.dx : 0),
301
- y: e.y + (withGaze ? e.dy : 0),
302
- w: e.w,
303
- h: e.h,
304
- open: e.open,
305
- shift: e.shift,
306
- closed: e.closed,
307
- };
308
- }
309
-
310
- function happyArc(e: EyeState): string {
311
- const ex = e.x + e.dx;
312
- const ey = e.y + e.dy;
313
- const hw = e.w * HAPPY_ARC.halfWidth;
314
- const base = ey + e.h * HAPPY_ARC.base;
315
- return `M${ex - hw} ${base}Q${ex} ${ey - e.h * HAPPY_ARC.peak} ${ex + hw} ${base}`;
316
- }
317
-
318
- function eyeMark(e: EyeState): EyeMark {
319
- if (e.closed) return { shape: 'path', d: eyePath(e.look, spotOf(e, true)) };
320
- if (e.plain === 'arc') return { shape: 'arc', d: happyArc(e), strokeWidth: e.w * HAPPY_ARC.stroke };
321
- if (e.plain === null) return { shape: 'path', d: eyePath(e.look, spotOf(e, true)) };
322
- const cx = e.x + e.dx;
323
- const cy = e.y + e.dy + e.shift;
324
- return { shape: 'pill', x: cx - e.w / 2, y: cy - e.open / 2, width: e.w, height: e.open, radius: Math.min(e.w, e.open) / 2 };
325
- }
326
-
327
- function colors(options: RenderOptions): { color: string; highlight: string; shadow: string; accent: string; ink: string } {
328
- const palette = derivePalette(options.color ?? DEFAULT_COLOR);
329
- const highlight = options.highlightColor ? toHex(parseHex(options.highlightColor) ?? (parseHex(palette.highlight) as Rgb)) : palette.highlight;
330
- const shadow = options.shadowColor ? toHex(parseHex(options.shadowColor) ?? (parseHex(palette.shadow) as Rgb)) : palette.shadow;
331
- return {
332
- color: palette.base,
333
- highlight,
334
- shadow,
335
- accent: palette.accent,
336
- ink: toHex(parseHex(options.eyeColor) ?? (parseHex(DEFAULT_EYE_COLOR) as Rgb)),
337
- };
338
- }
339
-
340
- // ---------------------------------------------------------------------------
341
- // 彩带配色
342
-
343
- const RAMP_LIGHT = 0.09;
344
- const RAMP_HUE = 14;
345
- const RAMP_RANGE: [number, number] = [0.36, 0.9];
346
- const WARM = 100;
347
- const GRADIENT_LIGHT = 0.13;
348
- const GRADIENT_HUE = 25;
349
- const GRADIENT_STOPS = 5;
350
- const NEUTRAL = 0.04;
351
- const NEUTRAL_TINT = 0.025;
352
- const BAND_SHADES = [
353
- [0, 1, 2],
354
- [2, 0, 3],
355
- [1, 2, 0],
356
- ] as const;
357
-
358
- function turnToward(h: number, to: number, by: number): number {
359
- const d = ((to - h + 540) % 360) - 180;
360
- return (h + Math.sign(d) * Math.min(Math.abs(d), by) + 360) % 360;
361
- }
362
-
363
- const palettes = new Map<string, string[][]>();
364
-
365
- /** 每条彩带的渐变(尾 → 头),取自身体颜色的那条色阶:越亮越暖,越暗越冷。 */
366
- function ribbonPalette(color: string, seed: number): string[][] {
367
- const key = `${color}|${seed}`;
368
- const hit = palettes.get(key);
369
- if (hit) return hit;
370
- const [light, chroma, hue] = toOklch(parseHex(color) ?? (parseHex(DEFAULT_COLOR) as Rgb));
371
- const neutral = chroma < NEUTRAL;
372
- const base = neutral ? (130 + ((seed % 997) / 997) * 310) % 360 : hue;
373
- const c = neutral ? NEUTRAL_TINT : Math.max(chroma, 0.17);
374
- const from = Math.min(RAMP_RANGE[1], Math.max(RAMP_RANGE[0], light));
375
- const steps: number[] = [];
376
- for (let k = 1; steps.length < 5 && k < 10; k++) {
377
- for (const step of [k, -k]) {
378
- const l = from + step * RAMP_LIGHT;
379
- if (steps.length < 5 && l >= RAMP_RANGE[0] - 1e-9 && l <= RAMP_RANGE[1] + 1e-9) steps.push(step);
380
- }
381
- }
382
- while (steps.length < 5) steps.push(steps[steps.length - 1] ?? 1);
383
- const shades = steps.map((step) => {
384
- const l = from + step * RAMP_LIGHT;
385
- const h = turnToward(base, step > 0 ? WARM : WARM + 180, RAMP_HUE * Math.abs(step));
386
- const away = step > 0 ? 1 : -1;
387
- return Array.from({ length: GRADIENT_STOPS }, (_, n) => {
388
- const t = n / (GRADIENT_STOPS - 1);
389
- const hh = turnToward(h, away > 0 ? WARM : WARM + 180, GRADIENT_HUE * t);
390
- return toHex(oklch(Math.min(0.9, Math.max(0.26, l + away * GRADIENT_LIGHT * t)), c, hh));
391
- });
392
- });
393
- const palette = BAND_SHADES.flatMap((pick) => pick.map((n) => shades[n]));
394
- if (palettes.size >= 64) palettes.clear();
395
- palettes.set(key, palette);
396
- return palette;
397
- }
398
-
399
- // ---------------------------------------------------------------------------
400
- // 一帧
401
-
402
- function sliceCull(v: ViewBasis): (s: VolumeSlice) => boolean {
403
- const sweep = Math.hypot(v.sY, v.cY * v.sP);
404
- const inset = Math.min(Math.abs(v.cY), Math.abs(v.cP));
405
- return (s) => s.axis !== 'z' || s.inset <= 0 || Math.abs(s.at) * sweep > s.inset * inset;
406
- }
407
-
408
- /** 按渲染尺寸丢掉挤在一起的截面(小于约 0.75 px 的间隔看不出差别)。 */
409
- function keptSlices(p: Prepared, stack: 'z' | 'x', size: number | undefined): boolean[] {
410
- const px = Number.isFinite(size) && (size as number) > 0 ? Math.round(size as number) : 0;
411
- const gap = px ? (0.75 * 100) / px : 0;
412
- const out: boolean[] = [];
413
- for (const part of p.vol.parts) {
414
- const slices = stack === 'z' ? part.zSlices : part.xSlices;
415
- let last = -Infinity;
416
- slices.forEach((s, j) => {
417
- const core = s.axis === 'z' && s.at === 0 && s.inset === 0;
418
- const keep = core || j === 0 || j === slices.length - 1 || s.at - last >= gap;
419
- if (keep) last = s.at;
420
- out.push(keep);
421
- });
422
- }
423
- return out;
424
- }
425
-
426
- /** 计算一帧。定义非法时抛错。 */
427
- export function computeFrame(definition: AvatarDefinition, options: RenderOptions = {}, size?: number): Frame {
428
- const p = prepare(definition, options.depth);
429
- const { vol, body } = p;
430
- const b = vol.bounds;
431
- const pivot = pivotOf(b);
432
- const { color, highlight, shadow, accent, ink } = colors(options);
433
- const clay = options.clay !== false;
434
- const time = Number.isFinite(options.time) ? (options.time as number) : 0;
435
- const pose = applyElasticity(computePose({
436
- seed: p.seed,
437
- time,
438
- state: options.state,
439
- mood: options.mood,
440
- expression: options.expression,
441
- stateAge: options.stateAge,
442
- gaze: options.gaze,
443
- reducedMotion: options.reducedMotion === true,
444
- view: options.view,
445
- }), elasticityOf(b));
446
- // 从“屏幕上正在显示的样子”缓动过来:状态与表情的切换都经过这里。
447
- const blended: Pose = options.poseBlend && Number.isFinite(options.poseBlend.t) && options.poseBlend.t < 1
448
- ? blendPoses(options.poseBlend.from as Pose, pose, smoothstep(options.poseBlend.t))
449
- : pose;
450
- const v = viewBasis(blended.yaw, blended.pitch);
451
- const stack = activeStack(v);
452
- const shrink = bodyScale(blended.bang, blended.dots);
453
- const root = rootMatrix(blended, b);
454
- const scaleAbout = (m: Matrix): Matrix => (shrink < 1 ? mul(about(pivot[0], pivot[1], [shrink, 0, 0, shrink, 0, 0]), m) : m);
455
-
456
- const paths = new Map<string, FramePath>();
457
- const items: { depth: number; shape: FrameShape }[] = [];
458
- const pathFor = (d: string, evenOdd: boolean, box: Box, id?: string): FramePath => {
459
- let path = paths.get(d);
460
- if (!path) {
461
- path = { id: id ?? (p.ids.get(d) as string), d, evenOdd, box };
462
- paths.set(d, path);
463
- }
464
- return path;
465
- };
466
-
467
- if (shrink > 0) {
468
- const drawn = sliceCull(v);
469
- const kept = keptSlices(p, stack, size);
470
- let k = 0;
471
- vol.parts.forEach((part, i) => {
472
- (stack === 'z' ? part.zSlices : part.xSlices).forEach((s, j) => {
473
- if (!kept[k++] || !drawn(s)) return;
474
- const path = pathFor(s.d, s.evenOdd, s.box);
475
- // 平行的截面在每条视射线上顺序相同。
476
- const depth = stack === 'z' ? v.facing * s.at : -v.sY * v.cP * s.at;
477
- items.push({ depth, shape: { kind: 'slice', key: `${i}${stack}${j}`, path: path.id, matrix: scaleAbout(stack === 'z' ? planeMatrix(v, s.at, pivot) : sidePlaneMatrix(v, s.at, pivot)) } });
478
- });
479
- });
480
-
481
- if (options.eyeRings && options.eyeRings.length === 2) {
482
- const s = p.vol.eyeScale;
483
- const r = p.range;
484
- const dx = blended.gazeX * (blended.gazeX >= 0 ? r.right : r.left) * GAZE_X * s;
485
- const dy = blended.gazeY * (blended.gazeY >= 0 ? r.down : r.up) * GAZE_Y * s;
486
- const blinkScale = Number.isFinite(options.blinkScale) ? Math.max(0.06, Math.min(1, options.blinkScale as number)) : 1;
487
- const centers = eyeCenters(p.def.eyes);
488
- const halfW = RING_ENVELOPE.hw * s;
489
- const halfH = RING_ENVELOPE.hh * s;
490
- const xDepth = -v.sY * v.cP;
491
-
492
- centers.forEach(([cx, cy], idx) => {
493
- const plane = vol.eyePlanes[idx];
494
- if (!eyeVisible(v, plane)) return;
495
- const z = plane.z + dx * plane.dzdx + dy * plane.dzdy;
496
- const depth =
497
- stack === 'z'
498
- ? v.facing * z + Math.abs(v.facing) * (Math.abs(plane.dzdx) * halfW + Math.abs(plane.dzdy) * halfH)
499
- : xDepth * (cx + dx) + Math.abs(xDepth) * halfW;
500
- const eyeMatrixNow = scaleAbout(eyeMatrix(v, plane, pivot));
501
- const d = ringPath(options.eyeRings![idx], cx, cy, s, blinkScale, dx, dy);
502
- items.push({
503
- depth: depth + 1e-6,
504
- shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: eyeMatrixNow, mark: { shape: 'path', d } },
505
- });
506
- });
507
- } else {
508
- eyeStates(p, blended).forEach((e, idx) => {
509
- const plane = vol.eyePlanes[idx];
510
- if (!eyeVisible(v, plane)) return;
511
- const halfW = e.w * (e.plain === 'pill' ? 0.5 : HAPPY_ARC.halfWidth + 0.5 * HAPPY_ARC.stroke);
512
- const xDepth = -v.sY * v.cP;
513
- const z = plane.z + e.dx * plane.dzdx + e.dy * plane.dzdy;
514
- const depth =
515
- stack === 'z'
516
- ? v.facing * z + Math.abs(v.facing) * (Math.abs(plane.dzdx) * halfW + (Math.abs(plane.dzdy) * e.h) / 2)
517
- : xDepth * (e.x + e.dx) + Math.abs(xDepth) * halfW;
518
- const eyeMatrixNow = scaleAbout(eyeMatrix(v, plane, pivot));
519
- const mark = eyeMark(e);
520
- items.push({
521
- depth: depth + 1e-6,
522
- shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: eyeMatrixNow, mark },
523
- });
524
- });
525
- }
526
- items.sort((m, n) => m.depth - n.depth);
527
- }
528
-
529
- // 彩带与标记停在原地,不随身体的 2D 动作移动:用 root 的逆矩阵抵消。
530
- const fixed = shrink < 1 || blended.ribbons > 0.01 || options.orbit ? invert(root) : null;
531
- const ribbons: FrameShape[] = [];
532
- if (blended.ribbons > 0.01 && !options.reducedMotion) {
533
- const inside = (x: number, y: number) => {
534
- let w = 0;
535
- for (const poly of body.polys) {
536
- for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
537
- const [xi, yi] = poly[i];
538
- const [xj, yj] = poly[j];
539
- if (yj <= y) {
540
- if (yi > y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) > 0) w++;
541
- } else if (yi <= y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) < 0) w--;
542
- }
543
- }
544
- return w !== 0;
545
- };
546
- const palette = ribbonPalette(color, p.seed);
547
- for (const piece of ribbonPieces(p.rim(), blended.ribbons, p.seed, time, blended.sweep, blended.cage, inside, (i) => palette[i % palette.length])) {
548
- ribbons.push({
549
- kind: 'ribbon',
550
- key: '',
551
- d: piece.d,
552
- box: piece.box,
553
- matrix: fixed ?? [1, 0, 0, 1, 0, 0],
554
- front: piece.front,
555
- gradient: piece.gradient,
556
- });
557
- }
558
- }
559
- const particles: FrameShape[] = [];
560
- if (blended.bloom > 0.01) {
561
- const palette = ribbonPalette(color, p.seed).map((run) => run[Math.floor(run.length / 2)]);
562
- for (const [i, piece] of bloomPieces(b, p.seed, blended.bloomAge, blended.bloom, palette).entries()) {
563
- particles.push({
564
- kind: 'particle',
565
- key: `particle-${i}`,
566
- d: piece.d,
567
- box: piece.box,
568
- matrix: mul(fixed ?? [1, 0, 0, 1, 0, 0], piece.matrix),
569
- fill: piece.fill,
570
- front: piece.front,
571
- });
572
- }
573
- }
574
- if (options.orbit) {
575
- const orbitColors = [accent, highlight, color];
576
- for (const [i, piece] of orbitPieces(p.rim(), p.seed, time, options.state ?? 'idle', orbitColors, options.reducedMotion === true).entries()) {
577
- particles.push({
578
- kind: 'particle',
579
- key: `orbit-${i}`,
580
- d: piece.d,
581
- box: piece.box,
582
- matrix: mul(fixed ?? [1, 0, 0, 1, 0, 0], piece.matrix),
583
- fill: piece.fill,
584
- front: piece.front,
585
- });
586
- }
587
- }
588
- const badge = badgePiece(b, options.badge, time, options.reducedMotion === true);
589
- if (badge) {
590
- const outerR = badge.radius;
591
- const innerR = badge.radius * 0.72;
592
- const circle = (r: number) => `M${-r} 0A${r} ${r} 0 1 1 ${r} 0A${r} ${r} 0 1 1 ${-r} 0Z`;
593
- const m: Matrix = [badge.pulse, 0, 0, badge.pulse, badge.x, badge.y];
594
- particles.push(
595
- {
596
- kind: 'particle',
597
- key: 'badge-ring',
598
- d: circle(outerR),
599
- box: { x: -outerR, y: -outerR, w: 2 * outerR, h: 2 * outerR },
600
- matrix: m,
601
- fill: badge.ringFill,
602
- front: true,
603
- },
604
- {
605
- kind: 'particle',
606
- key: 'badge-dot',
607
- d: circle(innerR),
608
- box: { x: -innerR, y: -innerR, w: 2 * innerR, h: 2 * innerR },
609
- matrix: m,
610
- fill: badge.fill,
611
- front: true,
612
- },
613
- );
614
- }
615
-
616
- const marks: FrameShape[] = [];
617
- if (shrink < 1) {
618
- for (const part of markParts(b, blended.bang, blended.dots, p.seed, time, options.reducedMotion === true)) {
619
- const turn: Matrix = [Math.cos(part.turn), Math.sin(part.turn), -Math.sin(part.turn), Math.cos(part.turn), 0, 0];
620
- const id = `${p.id}-${part.shape}`;
621
- pathFor(part.d, false, part.box, id);
622
- marks.push({
623
- kind: 'mark',
624
- key: `mark-${part.shape}-${marks.length}`,
625
- id,
626
- d: part.d,
627
- box: part.box,
628
- matrix: mul(fixed ?? [1, 0, 0, 1, 0, 0], mul(about(pivot[0], pivot[1], turn), mul(translate(part.x, part.y), [part.scale, 0, 0, part.scale, 0, 0]))),
629
- });
630
- }
631
- }
632
-
633
- const ordered: FrameShape[] = [
634
- ...particles.filter((r) => r.kind === 'particle' && !r.front),
635
- ...ribbons.filter((r) => r.kind === 'ribbon' && !r.front),
636
- ...items.map((it) => it.shape),
637
- ...ribbons.filter((r) => r.kind === 'ribbon' && r.front),
638
- ...particles.filter((r) => r.kind === 'particle' && r.front),
639
- ...marks,
640
- ].map((s, i) => (s.kind === 'ribbon' ? { ...s, key: `ribbon-${i}` } : s));
641
-
642
- return { name: p.def.name, color, highlight, shadow, clay, bodyBox: b, ink, paths: [...paths.values()], root, shapes: ordered, pose: blended };
643
- }
644
-
645
- /** 一帧可用的方形范围(viewBox 单位),canvas 用它做位图上限。 */
646
- export function avatarExtent(definition: AvatarDefinition, depth?: number): { x: number; y: number; size: number } {
647
- const p = prepare(definition, depth);
648
- const b = p.vol.bounds;
649
- const [cx, cy] = pivotOf(b);
650
- const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...p.vol.parts.map((part) => part.depth)) + 3) / 2;
651
- const rim = p.rim();
652
- const reach = Math.hypot(rim.cx - cx, rim.cy - cy) + rim.max * 1.1 + 8;
653
- const half = Math.max(radius + 5, reach);
654
- return { x: cx - half, y: cy - half, size: 2 * half };
655
- }