All files / hooks useSkeletalAnimation.ts

82.75% Statements 72/87
62.06% Branches 54/87
100% Functions 5/5
82.35% Lines 70/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334                                                                                                                                                                        11x                                                                                       319x     319x                   319x     319x         319x   135x   135x 135x 135x   135x   4x       4x 131x     2x       2x 2x 129x     115x 108x 108x     115x 115x 14x   7x         7x 7x 7x                 7x       7x   1x 1x 6x   1x         1x 5x   4x 4x     4x 2x       1x       1x     1x 1x                     134x 132x       134x 132x     134x                       319x   102x 102x     102x 102x     102x 2x     2x 2x           102x           102x   102x       102x     102x 102x     102x 2x 2x             2x 2x               319x              
/**
 * useSkeletalAnimation - Shared hook for skeletal animation management
 *
 * Centralizes skeletal animation state and frame updates for player characters.
 * Reduces code duplication across SkeletalPlayer3D, Player3DWithTransitions,
 * and screen components.
 *
 * PHASE 2: Now uses cached interpolation and batch bone updates for 60fps performance
 *
 * @module hooks/useSkeletalAnimation
 * @category Hooks
 * @korean 골격애니메이션훅
 */
 
import { useCallback, useEffect, useRef, useState } from "react";
import {
  batchUpdateBones,
  getAnimation,
  getAnimationByName,
  getAttackAnimation,
  getDefensiveAnimation,
  getFootworkAnimation,
  getStepAnimation,
  interpolateKeyframeCached,
  performanceMonitor,
} from "../systems/animation";
import { applyLaterality } from "../systems/animation/core/LateralityTransform";
import type { TrigramStance } from "../types/common";
import type { PlayerAnimation } from "../types/player-visual";
import type {
  SkeletalAnimation,
  SkeletalAnimationState,
  SkeletalRig,
} from "../types/skeletal";
 
/**
 * Options for useSkeletalAnimation hook
 * @korean 골격애니메이션훅옵션
 */
export interface UseSkeletalAnimationOptions {
  /** Current animation name */
  readonly currentAnimation: PlayerAnimation;
  /** Specific attack animation name (for attack state) */
  readonly attackAnimation?: string;
  /** Whether player is blocking */
  readonly isBlocking?: boolean;
  /** Current player stance for trigram-specific idle animations */
  readonly stance?: TrigramStance;
  /**
   * Stance laterality (left or right foot forward)
   *
   * - "left": Left foot forward (왼발서기 - Oenbal Seogi)
   * - "right": Right foot forward (오른발서기 - Oreun Bal Seogi)
   *
   * This affects animation mirroring - techniques will be mirrored
   * appropriately based on the laterality, creating 16 distinct stance
   * configurations (8 trigrams × 2 laterality).
   *
   * **Korean**: 측면성 (Cheugmyeonseong - Laterality/Sidedness)
   */
  readonly laterality?: "left" | "right";
  /** Callback when animation completes */
  readonly onAnimationComplete?: () => void;
}
 
/**
 * Return type for useSkeletalAnimation hook
 * @korean 골격애니메이션훅반환타입
 */
export interface UseSkeletalAnimationReturn {
  /** Current animation state */
  readonly animState: SkeletalAnimationState;
  /** Animation time reference (seconds) */
  readonly animTimeRef: React.MutableRefObject<number>;
  /** Update animation and apply to rig (call in useFrame) */
  readonly updateRigAnimation: (rig: SkeletalRig, delta: number) => void;
  /** Diagonal rotation override for step animations */
  readonly diagonalRotationY: number | null;
}
 
/**
 * Set of diagonal step animations for O(1) lookup
 * @korean 대각선스텝애니메이션집합
 */
const DIAGONAL_STEP_ANIMATIONS = new Set([
  "step_forward_left",
  "step_forward_right",
  "step_back_left",
  "step_back_right",
]);
 
/**
 * useSkeletalAnimation hook
 *
 * Manages skeletal animation state and frame updates for player characters.
 * Handles animation selection based on player state (idle, walk, attack, etc.)
 * and applies keyframes to the skeletal rig.
 *
 * @param options - Animation options
 * @returns Animation state and update function
 *
 * @example
 * ```tsx
 * const { animState, animTimeRef, updateRigAnimation, diagonalRotationY } =
 *   useSkeletalAnimation({
 *     currentAnimation: "walk",
 *     isBlocking: false,
 *     onAnimationComplete: () => console.log("Animation completed"),
 *   });
 *
 * // In useFrame callback
 * useFrame((_, delta) => {
 *   updateRigAnimation(rig, delta);
 * });
 * ```
 *
 * @korean 골격애니메이션훅
 */
export function useSkeletalAnimation(
  options: UseSkeletalAnimationOptions,
): UseSkeletalAnimationReturn {
  const {
    currentAnimation,
    attackAnimation,
    isBlocking = false,
    stance,
    laterality = "right",
    onAnimationComplete,
  } = options;
 
  // Animation state
  const [animState, setAnimState] = useState<SkeletalAnimationState>({
    currentAnimation: null,
    currentTime: 0,
    isPlaying: false,
    playbackSpeed: 1.0,
    previousKeyframeIndex: 0,
    nextKeyframeIndex: 1,
  });
 
  // Animation time ref (updated at 60fps without triggering re-renders)
  const animTimeRef = useRef(0);
 
  // Diagonal step rotation override (Y-axis rotation in radians)
  const [diagonalRotationY, setDiagonalRotationY] = useState<number | null>(
    null,
  );
 
  // Load animation when currentAnimation, blocking state, or laterality changes
  useEffect(() => {
    // Reset animation time whenever animation changes
    animTimeRef.current = 0;
 
    let selectedAnim: SkeletalAnimation | null = null;
    let playbackSpeed = 1.0;
    let shouldClearDiagonalRotation = true;
 
    if (currentAnimation === "attack" && attackAnimation) {
      // Attack animation - first check stance-specific attacks, then generic
      selectedAnim =
        getAttackAnimation(attackAnimation) ??
        getAnimation(attackAnimation) ??
        null;
      playbackSpeed = 1.0;
    } else if (currentAnimation === "defend" || isBlocking) {
      // Block/defend animation - check stance-specific defensive animations first
      // If attackAnimation contains a defensive animation name, use it
      Iif (attackAnimation) {
        selectedAnim = getDefensiveAnimation(attackAnimation) ?? null;
      }
      // Fall back to generic block animation
      selectedAnim ??= getAnimation("block") ?? null;
      playbackSpeed = 1.0;
    } else if (currentAnimation === "idle") {
      // Idle animation - use trigram-specific stance idle if stance is provided
      // Otherwise fall back to generic idle breathing animation
      if (stance) {
        const stanceIdleAnim = `stance_${stance}` as PlayerAnimation;
        selectedAnim = getAnimationByName(stanceIdleAnim) ?? null;
      }
      // Fall back to generic idle if no stance or stance animation not found
      selectedAnim ??= getAnimation("idle") ?? null;
      playbackSpeed = 0.5; // Slow breathing animation
    } else if (currentAnimation === "walk") {
      // Walking animation - use trigram-specific walk if stance is provided
      Iif (stance) {
        const stanceWalkAnim = `walk_${stance}` as PlayerAnimation;
        selectedAnim = getAnimationByName(stanceWalkAnim) ?? null;
      }
      // Fall back to generic walk if no stance or stance animation not found
      selectedAnim ??= getAnimation("walk") ?? null;
      playbackSpeed = 1.0;
    I} else if (currentAnimation === "run") {
      // Running animation - use trigram-specific run if stance is provided
      if (stance) {
        const stanceRunAnim = `run_${stance}` as PlayerAnimation;
        selectedAnim = getAnimationByName(stanceRunAnim) ?? null;
      }
      // Fall back to generic run if no stance or stance animation not found
      selectedAnim ??= getAnimation("run") ?? null;
      playbackSpeed = 1.0;
    I} else if (currentAnimation?.startsWith("fall_")) {
      // Fall animations - directional falls from BasicAnimations
      selectedAnim = getAnimation(currentAnimation) ?? null;
      playbackSpeed = 1.0;
    } else if (currentAnimation === "stance_change") {
      // Stance change animation
      selectedAnim = getAnimation("idle_stance") ?? null;
      playbackSpeed = 1.2; // Slightly faster for responsiveness
    } else if (currentAnimation === "hit") {
      // Hit reaction - stop animation
      setAnimState((prev) => ({
        ...prev,
        isPlaying: false,
        currentTime: 0,
      }));
      return;
    } else if (currentAnimation?.startsWith("step_")) {
      // Tactical step animation
      selectedAnim = getStepAnimation(currentAnimation) ?? null;
      playbackSpeed = 1.0;
 
      // Handle diagonal step rotation
      if (DIAGONAL_STEP_ANIMATIONS.has(currentAnimation)) {
        shouldClearDiagonalRotation = false;
        // Diagonal rotation will be handled by parent component
        // This hook only manages the flag
      }
    I} else if (currentAnimation?.startsWith("footwork_")) {
      // Footwork pattern animation
      selectedAnim = getFootworkAnimation(currentAnimation) ?? null;
      playbackSpeed = 1.0;
    } else if (currentAnimation?.startsWith("stance_")) {
      // Stance-specific idle animation with proper biomechanics
      // Use getAnimationByName which searches ALL_ANIMATIONS (includes STANCE_ANIMATIONS)
      selectedAnim = getAnimationByName(currentAnimation) ?? null;
      playbackSpeed = 0.5; // Slow breathing animation for stance idle
    } else E{
      // Idle animation (fallback)
      selectedAnim = getAnimation("idle_stance") ?? null;
      playbackSpeed = 0.5; // Slow breathing animation
    }
 
    // Apply laterality transformation if selectedAnim exists
    // laterality directly affects animation mirroring:
    // "left" = left foot forward (왼발서기) → animations mirrored
    // "right" = right foot forward (오른발서기) → base animations (default)
    if (selectedAnim) {
      selectedAnim = applyLaterality(selectedAnim, laterality);
    }
 
    // Clear diagonal rotation for non-diagonal animations
    if (shouldClearDiagonalRotation) {
      setDiagonalRotationY(null);
    }
 
    setAnimState({
      currentAnimation: selectedAnim,
      currentTime: 0,
      isPlaying: true,
      playbackSpeed,
      previousKeyframeIndex: 0,
      nextKeyframeIndex: 1,
    });
  }, [currentAnimation, attackAnimation, isBlocking, stance, laterality]);
 
  // Update animation and apply to rig (called at 60fps in useFrame)
  // PHASE 2: Now uses cached interpolation and batch bone updates
  const updateRigAnimation = useCallback(
    (targetRig: SkeletalRig, delta: number) => {
      Eif (animState.isPlaying && animState.currentAnimation) {
        const frameStartTime = performance.now();
 
        // Advance animation time
        let newTime = animTimeRef.current + delta * animState.playbackSpeed;
        let completed = false;
 
        // Handle looping or completion
        if (newTime >= animState.currentAnimation.duration) {
          Iif (animState.currentAnimation.loop) {
            newTime = newTime % animState.currentAnimation.duration;
          } else {
            newTime = animState.currentAnimation.duration;
            completed = true;
          }
        }
 
        // Use cached interpolation for 90%+ cache hit rate
        // Use animation.name as the unique identifier
        const keyframe = interpolateKeyframeCached(
          animState.currentAnimation.name,
          animState.currentAnimation,
          newTime,
        );
 
        Eif (keyframe) {
          // Batch update bones (60% faster than individual updates)
          batchUpdateBones(targetRig, keyframe);
        }
 
        // Update time ref
        animTimeRef.current = newTime;
 
        // Record performance metrics
        const frameTime = performance.now() - frameStartTime;
        performanceMonitor.recordFrame(frameTime);
 
        // Handle animation completion
        if (completed) {
          animTimeRef.current = 0;
          setAnimState((prev) => ({
            ...prev,
            isPlaying: false,
            currentTime: 0,
          }));
 
          // Trigger callback
          Eif (onAnimationComplete) {
            onAnimationComplete();
          }
        }
      }
    },
    [animState, onAnimationComplete],
  );
 
  return {
    animState,
    animTimeRef,
    updateRigAnimation,
    diagonalRotationY,
  };
}