아바타 v3 세션 연결 — P1 서연 리노컷 아바타와 음성 립싱크
Some checks failed
API contract / OpenAPI type drift (push) Has been cancelled

- ClientAvatar가 리그 레지스트리(v3/rigs)로 P1을 판정해 그림 영역을 ClientAvatarV3로 그린다(로드 중·실패 시 기존 SVG, VITE_AVATAR_V3=0이면 끔)
- 발화 구동 공용 모듈 speechDriver: Lab과 세션이 함께 쓰고, TTS AudioBuffer를 오디오 시계로 표본해 립싱크·발화 동반층·지문 cue를 돌린다
- Session: TTS 재생 시작 시 발화(원문·버퍼·시작 시각) 전달, 음성 실패 시 텍스트 타이밍 발화, 정지 경로에서 해제, 개방도·겉표정 강도 전달
- 정지 화면(시작 전·썸네일)도 한 프레임을 그리고, 박스 실측 폭으로 상반신/얼굴 크롭을 고른다
- 세션 발화 E2E(오디오·실패 경로), P1 레이아웃 게이트, P1 표정 시험을 v3 기대로 갱신
This commit is contained in:
Yun Chan 2026-10-01 16:12:24 +09:00
parent ecb36d123f
commit 613bcb603e
14 changed files with 1000 additions and 182 deletions

View file

@ -35,6 +35,8 @@ import { Brows } from "./Brows";
import { Mouth } from "./Mouth";
import { live2dModel3Path, live2dModelForPersonaCode, live2dMotionForExpression } from "./live2dModel";
import { useExpressionTransition } from "./useExpressionTransition";
import ClientAvatarV3, { type AvatarSpeech } from "./v3/ClientAvatarV3";
import { linocutRigFor } from "./v3/rigs";
import "./client-avatar.css";
/* ── 공개 타입 재노출 (기존 import 경로 호환) ──────────────────────────
@ -48,6 +50,7 @@ export {
type AvatarPersona,
} from "./persona";
export type { Live2DExpressionMotion, Live2DPersonaModel } from "./live2dModel";
export type { AvatarSpeech } from "./v3/ClientAvatarV3";
export interface ClientAvatarProps {
persona: AvatarPersona;
@ -65,6 +68,15 @@ export interface ClientAvatarProps {
* null/미지정이면 speaking 동안 차분한 의사 발화 모션.
*/
speakingProgress?: number | null;
/**
* 개방도 0~1(세션 effective_openness). v3(리노컷) 리그가 있는 페르소나에서만 쓴다.
* 미지정이면 rapport로 대신한다(결정문 §8.5).
*/
openness?: number;
/** 겉표정 강도 0~1(performance.ts surfaceIntensityFor). 미지정이면 0.5. v3 전용. */
surfaceIntensity?: number;
/** TTS 발화 구동(결정문 §8.5). v3 리그가 있는 페르소나에서만 립싱크·발화 동반층을 돈다. */
speech?: AvatarSpeech | null;
/** px 지름 (기본 220 — §5.2 아바타 220px) */
size?: number;
className?: string;
@ -215,6 +227,9 @@ export function ClientAvatar({
analyser = null,
rapport = 0,
speakingProgress = null,
openness,
surfaceIntensity,
speech = null,
size = 220,
className,
animated = true,
@ -222,7 +237,29 @@ export function ClientAvatar({
showMeta = true,
}: ClientAvatarProps) {
const reduced = useReducedMotion();
const motionEnabled = animated && !reduced;
/* v3(리노컷) 분기(결정문 §8.5) — persona.code로 판정(지금은 P1만). 리그가 있으면
그림 영역을 ClientAvatarV3로 그린다. 로드가 끝날 때까지 기존 SVG를 그대로 보이고,
ready가 되면 300ms 불투명도 전환으로 v3를 위에 올린 뒤 기존 SVG를 언마운트해
rAF를 멈춘다. error면 v3를 언마운트하고 기존 SVG로 남는다(§8.4 로드 실패 규칙). */
const rig = useMemo(() => linocutRigFor(persona.code), [persona.code]);
const [v3LoadState, setV3LoadState] = useState<"loading" | "ready" | "error">("loading");
const [legacyMounted, setLegacyMounted] = useState(true);
useEffect(() => {
setV3LoadState("loading");
setLegacyMounted(true);
}, [rig]);
useEffect(() => {
if (v3LoadState !== "ready") return;
const transitionMs = reduced ? 0 : 300;
const timer = window.setTimeout(() => setLegacyMounted(false), transitionMs);
return () => window.clearTimeout(timer);
}, [v3LoadState, reduced]);
const v3Active = rig !== null && v3LoadState !== "error";
const motionEnabled = animated && !reduced && legacyMounted;
// 외형 안전값
const skin = persona.skinTone;
@ -275,6 +312,10 @@ export function ClientAvatar({
const shoulderRotate = params.shoulderTurn * 0.4;
const mouthOpen = Math.max(mouth, params.mouthOpen);
// v3 전용 보정값(결정문 §8.5): 없으면 openness는 rapport로, 강도는 0.5로 둔다.
const v3Openness = openness ?? rapport ?? 0.5;
const v3SurfaceIntensity = surfaceIntensity ?? 0.5;
return (
<figure
className={"vg-avatar" + (className ? " " + className : "")}
@ -307,66 +348,84 @@ export function ClientAvatar({
) : null}
<div className="vg-avatar__stage" style={{ height: size }}>
{/* 호흡하는 광배 */}
<AuraLayer
hue={params.auraHue}
opacity={params.auraOpacity}
saturation={age.auraSaturation}
state={state}
mouth={mouth}
reduced={reduced}
/>
{legacyMounted ? (
<>
{/* 호흡하는 광배 */}
<AuraLayer
hue={params.auraHue}
opacity={params.auraOpacity}
saturation={age.auraSaturation}
state={state}
mouth={mouth}
reduced={reduced}
/>
<svg
className="vg-avatar__svg"
viewBox="0 0 200 200"
width={size}
height={size}
role="img"
aria-hidden="true"
>
{/* 흉상 그룹: 어깨 호흡(translateY) + 저항 시 미세 회전 */}
<g transform={`translate(0 ${-breath}) rotate(${shoulderRotate} 100 150)`}>
{/* 어깨/상반신 실루엣 */}
<BodySilhouette color={outfitColor} shoulderTurn={params.shoulderTurn} />
<svg
className="vg-avatar__svg"
viewBox="0 0 200 200"
width={size}
height={size}
role="img"
aria-hidden="true"
>
{/* 흉상 그룹: 어깨 호흡(translateY) + 저항 시 미세 회전 */}
<g transform={`translate(0 ${-breath}) rotate(${shoulderRotate} 100 150)`}>
{/* 어깨/상반신 실루엣 */}
<BodySilhouette color={outfitColor} shoulderTurn={params.shoulderTurn} />
<g transform={`rotate(${params.headTilt} 100 101)`}>
<HairBack style={hairStyle} color={hairColor} jawWidth={age.jawWidth} />
<NeckBridge skin={skin} />
<g transform={`rotate(${params.headTilt} 100 101)`}>
<HairBack style={hairStyle} color={hairColor} jawWidth={age.jawWidth} />
<NeckBridge skin={skin} />
{/* 머리 (양식화 — 코·주름·모공 없음) */}
<ellipse cx="100" cy="92" rx={42 * age.jawWidth} ry="46" fill={skin} />
{/* 머리 (양식화 — 코·주름·모공 없음) */}
<ellipse cx="100" cy="92" rx={42 * age.jawWidth} ry="46" fill={skin} />
<HairFront style={hairStyle} color={hairColor} />
<HairFront style={hairStyle} color={hairColor} />
{/* 얼굴 그룹: 시선 회피/saccade (translate) */}
<g transform={`translate(${gazeX} ${gazeY})`}>
<Brows
browTilt={params.browTilt}
browLift={params.browLift}
browPinch={params.browPinch}
color={hairColor}
/>
<Eyes
eyeSize={age.eyeSize}
blink={blink}
eyeOpen={params.eyeOpen}
eyelidDrop={params.eyelidDrop}
pupilScale={params.pupilScale}
irisColor={irisColor}
/>
<Mouth
open={mouthOpen}
curve={params.mouthCurve}
width={params.mouthWidth}
tension={params.mouthTension}
color="#9B5B52"
/>
{/* 얼굴 그룹: 시선 회피/saccade (translate) */}
<g transform={`translate(${gazeX} ${gazeY})`}>
<Brows
browTilt={params.browTilt}
browLift={params.browLift}
browPinch={params.browPinch}
color={hairColor}
/>
<Eyes
eyeSize={age.eyeSize}
blink={blink}
eyeOpen={params.eyeOpen}
eyelidDrop={params.eyelidDrop}
pupilScale={params.pupilScale}
irisColor={irisColor}
/>
<Mouth
open={mouthOpen}
curve={params.mouthCurve}
width={params.mouthWidth}
tension={params.mouthTension}
color="#9B5B52"
/>
</g>
</g>
</g>
</g>
</g>
</svg>
</svg>
</>
) : null}
{rig && v3Active ? (
<ClientAvatarV3
rig={rig}
code={persona.code}
state={state}
affect={affect}
openness={v3Openness}
surfaceIntensity={v3SurfaceIntensity}
speech={speech}
running={animated}
reducedMotion={reduced}
onLoadStateChange={setV3LoadState}
/>
) : null}
</div>
{/* 페르소나 메타 + 상태 텍스트 */}

View file

@ -0,0 +1,153 @@
/* =====================================================================
아바타 v3 발화 구동 공용 모듈 — 결정문 §8.5 "세션 연결". AvatarLab의
runSpeechTimeline / playSpeech / playSpeechWithAudioFile / endSpeech가
하던 엔진 구동 부분(buildPerformance → buildSpeechTimeline[+포락선]
→ buildCoSpeechPlan → playPerformance → 매 프레임 표본)을 여기로 옮겨
Lab과 v3 래퍼(ClientAvatarV3)가 함께 쓴다. 화면 표시(ref 갱신)는 onFrame
콜백으로 호출자에 남긴다. 발화 종료 시 상태 복귀(Lab은 listening, 래퍼는
prop state)도 호출자가 onEnd에서 정한다 — 이 모듈은 setSpeechShape(null)·
setSpeechMotion(null)과 rAF 해제까지만 한다.
===================================================================== */
import type { AvatarExpression } from "../persona";
import type { AvatarEngine } from "./engine";
import type { SpeechStyle } from "./demeanorDefaults";
import { buildPerformance, type PerformanceCue } from "./performance";
import {
buildSpeechTimeline,
currentViseme,
sampleSpeech,
type PhraseKind,
type SpeechShape,
type SpeechTimeline,
type VisemeId,
} from "./lipsync";
import { buildCoSpeechPlan, isStressPulseActive, sampleCoSpeech } from "./coSpeech";
import { computeEnvelope, type SpeechEnvelope } from "./speechEnvelope";
export interface SpeechDriverAudio {
buffer: AudioBuffer;
context: BaseAudioContext;
/** source.start(when)의 when(초, context 시계). */
startAt: number;
}
export interface SpeechFrameSample {
viseme: VisemeId;
shape: SpeechShape;
phraseKind: PhraseKind | null;
stressed: boolean;
}
export interface StartSpeechParams {
engine: AvatarEngine;
/** 괄호 지문을 포함한 발화 원문. */
text: string;
expression: AvatarExpression;
intensity: number;
openness: number;
seed: number;
speech: SpeechStyle;
/** 엔진 시계(engine.evaluate에 넘기는 시계와 같은 시계). */
now: () => number;
/** 있으면 오디오 선분석 정렬 경로. 없으면 텍스트 타이밍(speech.syllablesPerSec). */
audio?: SpeechDriverAudio;
/** 매 프레임 표본 결과(화면 표시용). React state 갱신은 호출자 책임(ref로 받는다). */
onFrame?: (sample: SpeechFrameSample) => void;
/** 타임라인이 끝까지 재생됐을 때(stop() 호출로 끝난 경우에는 부르지 않는다). */
onEnd?: () => void;
}
export interface SpeechHandle {
stop(): void;
/** 표시·디버그용 — buildPerformance가 파싱한 cue와 미대응 지문. */
cues: PerformanceCue[];
unmatched: string[];
}
/** tMs 시점까지 시작한 가장 최근 구의 종류. 구 사이 휴지 중에는 그 직전 구를 보인다. */
function currentPhraseKind(timeline: SpeechTimeline, localMs: number): PhraseKind | null {
let kind: PhraseKind | null = null;
for (const ph of timeline.phrases) {
if (ph.startMs > localMs) break;
kind = ph.kind;
}
return kind;
}
/**
* 발화 하나를 시작한다. 오디오가 있으면 포락선을 선분석해 오디오 시계로 표본하고,
* 없으면 텍스트 타이밍으로 엔진 시계에서 300ms 뒤 시작한다(결정문 §5.4·§8.5).
* 지문은 playPerformance로 함께 재생한다. 반환된 stop()은 호출자가 발화를 바꾸거나
* 끝낼 때 부른다(speechShape·speechMotion을 null로 되돌리고 rAF를 해제, 상태 복귀는 않는다).
*/
export function startSpeech(params: StartSpeechParams): SpeechHandle {
const { engine, text, expression, intensity, openness, seed, speech, now, audio, onFrame, onEnd } = params;
const nowMs = now();
const { performance: perf, unmatched } = buildPerformance({ text, expression, intensity, openness, seed });
let envelope: SpeechEnvelope | undefined;
let timeline: SpeechTimeline;
let speechStartMs: number;
let sampleClock: () => number;
if (audio) {
const channels: Float32Array[] = [];
for (let c = 0; c < audio.buffer.numberOfChannels; c++) channels.push(audio.buffer.getChannelData(c));
envelope = computeEnvelope(channels, audio.buffer.sampleRate);
timeline = buildSpeechTimeline({ text, syllablesPerSec: speech.syllablesPerSec, envelope });
speechStartMs = nowMs + (audio.startAt - audio.context.currentTime) * 1000;
/* 오디오 시계 기준(초 → ms, §8.5 "매 프레임 표본 시각은 (context.currentTime − startAt)·1000"). */
sampleClock = () => (audio.context.currentTime - audio.startAt) * 1000 + speechStartMs;
} else {
timeline = buildSpeechTimeline({ text, syllablesPerSec: speech.syllablesPerSec });
speechStartMs = nowMs + 300;
sampleClock = now;
}
const coSpeechPlan = buildCoSpeechPlan(timeline, speech, seed);
engine.playPerformance(perf, { speechStartMs, speechDurationMs: timeline.totalDurationMs }, nowMs);
let rafId = 0;
let prevLocalMs = -Infinity;
const endMs = speechStartMs + timeline.totalDurationMs;
function stop(): void {
cancelAnimationFrame(rafId);
engine.setSpeechShape(null);
engine.setSpeechMotion(null);
}
const step = () => {
const t = sampleClock();
if (t < speechStartMs) {
rafId = requestAnimationFrame(step);
return;
}
if (t >= endMs) {
stop();
onEnd?.();
return;
}
const localMs = t - speechStartMs;
const shape = sampleSpeech(timeline, localMs, speech.articulation);
engine.setSpeechShape(shape);
const sample = sampleCoSpeech(coSpeechPlan, localMs, prevLocalMs, envelope);
engine.setSpeechMotion(sample.delta);
if (sample.blinkNow) engine.requestSpeechBlink(now());
onFrame?.({
viseme: currentViseme(timeline, localMs),
shape,
phraseKind: currentPhraseKind(timeline, localMs),
stressed: isStressPulseActive(coSpeechPlan, localMs),
});
prevLocalMs = localMs;
rafId = requestAnimationFrame(step);
};
rafId = requestAnimationFrame(step);
return { stop, cues: perf.cues, unmatched };
}

View file

@ -0,0 +1,210 @@
/* =====================================================================
ClientAvatarV3 — 리노컷 리그가 있는 페르소나를 위한 v3 그림 영역 래퍼.
결정문 §8.5 "세션 연결". ClientAvatar가 그림 영역만 이 컴포넌트로 바꿔
그린다(루트 data-*·캡션·메타는 ClientAvatar가 그대로 유지한다).
엔진은 이 컴포넌트가 소유한다(persona.code로 demeanor·시드를 만든다).
시계는 모듈 수준 상수 함수(engineNowMs)를 LinocutAvatar에 안정 참조로
넘긴다 — 인라인 화살표를 넘기면 리렌더마다 rAF가 다시 시작된다.
크롭(bust/face)은 이 래퍼의 실측 폭(ResizeObserver)으로 정한다 —
session.css의 !important 규칙이 실제 렌더 크기를 덮어쓰기 때문에 size
prop은 쓰지 않는다(§8.5).
===================================================================== */
import { useEffect, useMemo, useRef, useState } from "react";
import type { AvatarExpression, AvatarState } from "../persona";
import { createAvatarEngine } from "../engine/engine";
import { demeanorFor } from "../engine/demeanorDefaults";
import { hashString } from "../engine/rng";
import { startSpeech, type SpeechDriverAudio } from "../engine/speechDriver";
import type { VisemeId } from "../engine/lipsync";
import LinocutAvatar from "./LinocutAvatar";
import { observeWidth } from "./observeWidth";
import type { LinocutRig, RigCrop } from "./linocutRig";
import "./client-avatar-v3.css";
/** ClientAvatar의 speech? prop 타입 — ClientAvatar 모듈에서 재노출한다. */
export interface AvatarSpeech {
id: string;
/** 괄호 지문을 포함한 답변 원문. */
text: string;
/** 있으면 오디오 선분석 경로. startAt은 source.start(when)의 when(초, context 시계). */
audio?: SpeechDriverAudio;
}
export interface ClientAvatarV3Props {
rig: LinocutRig;
code: string | null | undefined;
state: AvatarState;
affect: AvatarExpression;
/** 호출부가 openness ?? rapport ?? 0.5 로 보정해 넘긴다. */
openness: number;
/** 호출부가 surfaceIntensity ?? 0.5 로 보정해 넘긴다. */
surfaceIntensity: number;
speech?: AvatarSpeech | null;
/** false면 rAF를 멈추고 정지한 한 프레임만 그린다(시작 전 화면·썸네일). */
running: boolean;
reducedMotion: boolean;
className?: string;
onLoadStateChange?: (state: "loading" | "ready" | "error") => void;
}
const CROP_BUST_MIN_WIDTH = 120;
/** 엔진 시계는 performance.now()다. 안정 참조로 LinocutAvatar의 nowMs에 넘긴다
(인라인 화살표를 넘기면 리렌더마다 rAF가 다시 시작된다, §8.5). */
function engineNowMs(): number {
return performance.now();
}
export default function ClientAvatarV3({
rig,
code,
state,
affect,
openness,
surfaceIntensity,
speech = null,
running,
reducedMotion,
className,
onLoadStateChange,
}: ClientAvatarV3Props) {
const demeanor = useMemo(() => demeanorFor(code), [code]);
const seed = useMemo(() => hashString(code ?? ""), [code]);
const engine = useMemo(
() => createAvatarEngine({ demeanor, seed, reducedMotion }),
[demeanor, seed, reducedMotion],
);
const stateRef = useRef(state);
const speakingRef = useRef(false);
/* 엔진이 바뀌면(페르소나·reduced motion 전환) 지금 값으로 한 번에 다시 맞춘다
(AvatarLab.tsx의 같은 패턴). */
useEffect(() => {
engine.setState(speakingRef.current ? "speaking" : state, engineNowMs());
engine.setOpenness(openness);
engine.setSurface(affect, surfaceIntensity);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [engine]);
useEffect(() => {
stateRef.current = state;
if (!speakingRef.current) engine.setState(state, engineNowMs());
}, [engine, state]);
useEffect(() => {
engine.setOpenness(openness);
}, [engine, openness]);
useEffect(() => {
engine.setSurface(affect, surfaceIntensity);
}, [engine, affect, surfaceIntensity]);
/* 래퍼 박스 루트 — 크롭 판정(ResizeObserver)과 발화 data-* 속성 쓰기가 함께 쓴다. */
const rootRef = useRef<HTMLDivElement | null>(null);
/* 크롭(§8.5): 래퍼 박스의 실측 폭. 120px 이상이면 bust, 미만이면 face다. */
const [crop, setCrop] = useState<RigCrop>("face");
useEffect(() => {
const el = rootRef.current;
if (!el) return;
return observeWidth(el, (widthPx) => setCrop(widthPx >= CROP_BUST_MIN_WIDTH ? "bust" : "face"));
}, []);
const [loadState, setLoadState] = useState<"loading" | "ready" | "error">("loading");
function handleLoadStateChange(next: "loading" | "ready" | "error"): void {
setLoadState(next);
onLoadStateChange?.(next);
}
/* 발화(§8.5·§5.4·§5.5): id가 바뀌면 이전 발화를 멈추고 새 발화를 시작한다. 발화가
진행 중이면 엔진 상태를 "speaking"으로 유지하고, 끝나면 그때의 prop state로
되돌린다. 프레임마다 바뀌는 data-viseme은 React state가 아니라 ref로 쓴다. */
const speechHandleRef = useRef<ReturnType<typeof startSpeech> | null>(null);
const activeSpeechIdRef = useRef<string | null>(null);
function writeSpeechAttrs(source: "audio" | "text" | null, viseme: VisemeId): void {
const el = rootRef.current;
if (!el) return;
if (source) {
el.setAttribute("data-speech-source", source);
el.setAttribute("data-viseme", viseme);
} else {
el.removeAttribute("data-speech-source");
el.setAttribute("data-viseme", "X");
}
}
useEffect(() => {
if (!speech) {
if (activeSpeechIdRef.current !== null) {
speechHandleRef.current?.stop();
speechHandleRef.current = null;
activeSpeechIdRef.current = null;
speakingRef.current = false;
engine.setState(stateRef.current, engineNowMs());
writeSpeechAttrs(null, "X");
}
return;
}
if (speech.id === activeSpeechIdRef.current) return;
speechHandleRef.current?.stop();
activeSpeechIdRef.current = speech.id;
speakingRef.current = true;
engine.setState("speaking", engineNowMs());
const source: "audio" | "text" = speech.audio ? "audio" : "text";
writeSpeechAttrs(source, "X");
speechHandleRef.current = startSpeech({
engine,
text: speech.text,
expression: affect,
intensity: surfaceIntensity,
openness,
seed,
speech: demeanor.speech,
now: engineNowMs,
audio: speech.audio,
onFrame: ({ viseme }) => writeSpeechAttrs(source, viseme),
onEnd: () => {
speakingRef.current = false;
speechHandleRef.current = null;
activeSpeechIdRef.current = null;
engine.setState(stateRef.current, engineNowMs());
writeSpeechAttrs(null, "X");
},
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [speech]);
/* 언마운트 시 발화 rAF를 해제한다(페르소나 전환 등으로 이 래퍼 자체가 사라질 때). */
useEffect(() => {
return () => speechHandleRef.current?.stop();
}, []);
const transitionMs = reducedMotion ? 0 : 300;
return (
<div
ref={rootRef}
className={"vg-avatar-v3" + (className ? " " + className : "")}
data-avatar-renderer="linocut"
data-load-state={loadState}
data-viseme="X"
style={{ opacity: loadState === "ready" ? 1 : 0, transitionDuration: `${transitionMs}ms` }}
>
<LinocutAvatar
rig={rig}
engine={engine}
running={running}
nowMs={engineNowMs}
crop={crop}
backdropExpression={affect}
onLoadStateChange={handleLoadStateChange}
/>
</div>
);
}

View file

@ -23,6 +23,7 @@ import {
type LinocutFrame,
type JawWarpLayer,
} from "./linocutGeometry";
import { observeWidth } from "./observeWidth";
import "./linocut-avatar.css";
export interface LinocutAvatarProps {
@ -442,25 +443,23 @@ export default function LinocutAvatar({
const el = svgRef.current;
if (!el) return;
const viewBoxWidth = rig.crops[crop][2];
const update = (widthPx: number) => {
if (widthPx <= 0) return;
return observeWidth(el, (widthPx) => {
const k = widthPx / viewBoxWidth;
sizeScaleRef.current = Math.min(2, Math.max(1, 0.3 / k));
};
update(el.getBoundingClientRect().width);
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
const w = entry.contentBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;
update(w);
}
});
observer.observe(el);
return () => observer.disconnect();
}, [rig, crop]);
/* running=false(§8.5 세션 연결 — 시작 전 화면·썸네일)여도 정지한 한 프레임은 계산해
그린다. 그렇지 않으면 벡터 부위(눈·눈썹·입)가 비어 보인다. 마운트할 때, loadState가
ready가 될 때, engine·rig·crop이 바뀔 때 다시 계산한다(crop·loadState를 deps에
넣는다). running=true면 그대로 rAF 루프를 돈다. */
useEffect(() => {
if (!running) return;
const clock = nowMs ?? (() => performance.now());
if (!running) {
const v = engine.evaluate(clock());
applyFrame(refs.current, computeLinocutFrame(rig, v, sizeScaleRef.current));
return;
}
const loop = () => {
const v = engine.evaluate(clock());
const frame = computeLinocutFrame(rig, v, sizeScaleRef.current);
@ -469,7 +468,7 @@ export default function LinocutAvatar({
};
rafRef.current = requestAnimationFrame(loop);
return () => cancelAnimationFrame(rafRef.current);
}, [engine, running, nowMs, rig]);
}, [engine, running, nowMs, rig, crop, loadState]);
const viewBox = rig.crops[crop].join(" ");
const faceClipId = `${uid}-face-clip`;

View file

@ -0,0 +1,20 @@
/* =====================================================================
client-avatar-v3.css — ClientAvatarV3 래퍼 스타일. 결정문 §8.5 "화면".
원형 오브 안(.vg-avatar__stage, position:relative)에 꽉 차게 올라가
기존 SVG와 정확히 같은 자리를 차지한다(inset:0) — session.css의
!important 크기 규칙이 스테이지 쪽에 이미 걸려 있어 이 규칙만으로
모든 브레이크포인트에서 기존 SVG와 같은 크기가 된다. 원형이 아닌 곳에
이 컴포넌트를 쓰면 border-radius는 그대로 두되 바깥에서 inset을
덮어써야 한다(지금은 호출부가 모두 원형 오브다).
===================================================================== */
.vg-avatar-v3 {
position: absolute;
inset: 0;
z-index: 1;
border-radius: 50%;
overflow: hidden;
transition-property: opacity;
transition-timing-function: ease;
}

View file

@ -0,0 +1,15 @@
/** 요소의 렌더 폭(px)을 지금 한 번, 이후 크기가 바뀔 때마다 onWidth로 알린다(프레임마다 아님).
폭이 0 이하인 측정(아직 배치 전)은 건너뛴다. 반환 함수로 관찰을 끝낸다. */
export function observeWidth(el: Element, onWidth: (widthPx: number) => void): () => void {
const report = (widthPx: number) => {
if (widthPx > 0) onWidth(widthPx);
};
report(el.getBoundingClientRect().width);
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
report(entry.contentBoxSize?.[0]?.inlineSize ?? entry.contentRect.width);
}
});
observer.observe(el);
return () => observer.disconnect();
}

View file

@ -0,0 +1,16 @@
/* =====================================================================
아바타 v3 리그 레지스트리 — 결정문 §8.5 "분기". 페르소나 코드 → 리노컷
리그. 지금은 P1만 있고 나머지는 null(기존 SVG로 남는다). 빌드 플래그
VITE_AVATAR_V3=0 이면 항상 null(기본은 켜짐).
===================================================================== */
import type { LinocutRig } from "../linocutRig";
import { P1_LINOCUT_RIG } from "./p1Rig";
const LINOCUT_RIGS: Partial<Record<string, LinocutRig>> = { P1: P1_LINOCUT_RIG };
export function linocutRigFor(code: string | null | undefined): LinocutRig | null {
if (import.meta.env.VITE_AVATAR_V3 === "0") return null;
if (!code) return null;
return LINOCUT_RIGS[code.toUpperCase()] ?? null;
}