All files / components/screens/training/components TrainingDummy3D.tsx

69.56% Statements 48/69
61.29% Branches 19/31
80% Functions 16/20
74.19% Lines 46/62

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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                                                                                                                                                      2x       5040x                             5040x     77760x   5040x                           2x 2x   2x         48x   48x 24x     48x 24x     48x   24x               48x 24x           48x 24x       48x 24x 24x 24x 24x       48x                                                                                                                   2x                           72x 72x   72x   24x             72x 24x       24x               72x   72x 72x 72x     72x 24x       24x           24x 24x     72x                   72x             72x                                                         5040x                                                                              
/**
 * TrainingDummy3D - 3D training dummy with vital points
 *
 * Provides anatomically accurate training dummy using SkeletalPlayer3D
 * for Korean martial arts practice. Supports anatomy overlays and difficulty modes.
 *
 * Refactored to extend SkeletalPlayer3D for visual consistency with player characters.
 *
 * @module components/screens/training/TrainingDummy3D
 * @category 3D Components
 * @korean 훈련인형3D컴포넌트
 */
 
import { useFrame } from "@react-three/fiber";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import * as THREE from "three";
import { KOREAN_VITAL_POINTS } from "../../../../systems/vitalpoint/KoreanVitalPoints";
import { PlayerArchetype, TrigramStance } from "../../../../types/common";
import { KOREAN_COLORS } from "../../../../types/constants";
import SkeletalPlayer3D from "../../../shared/three/models/SkeletalPlayer3D";
import VitalPointMarker3D from "./VitalPointMarker3D";
 
/**
 * Difficulty mode for training
 * @korean 난이도모드
 */
export type DifficultyMode = "easy" | "normal" | "hard";
 
/**
 * Props for TrainingDummy3D component
 * @korean 훈련인형3D속성
 */
export interface TrainingDummy3DProps {
  /** 3D world position of the dummy */
  readonly position: [number, number, number];
  /** Currently selected vital point for targeting */
  readonly selectedVitalPoint: string | null;
  /** Whether training is active */
  readonly isTraining: boolean;
  /** Current health of dummy (0-100) */
  readonly health?: number;
  /** Maximum health of dummy */
  readonly maxHealth?: number;
  /** Callback when vital point is hit */
  readonly onVitalPointHit?: (vitalPointId: string) => void;
  /** Callback when dummy is defeated */
  readonly onDefeated?: () => void;
  /** Difficulty mode (affects marker sizes) */
  readonly difficulty?: DifficultyMode;
  /** Number of vital points to display (3-70) */
  readonly vitalPointCount?: number;
  /** Whether on mobile device */
  readonly isMobile?: boolean;
  /** Archetype to display (affects body type and appearance) */
  readonly archetype?: PlayerArchetype;
  /** Current stance for the dummy */
  readonly stance?: TrigramStance;
}
 
/**
 * Map body region to 3D position on dummy
 *
 * Positions are calibrated for SkeletalPlayer3D bone structure.
 *
 * @param pointId - Unique identifier for the vital point
 * @param category - Anatomical category (head, neck, torso, etc.)
 * @returns 3D coordinates [x, y, z] relative to dummy center
 * @korean 급소위치계산
 */
const getVitalPointPosition = (
  pointId: string,
  category: string,
): [number, number, number] => {
  const positions: Record<string, [number, number, number]> = {
    head: [0, 1.75, 0.12], // Head bone + offset
    neck: [0, 1.5, 0.1], // Neck bone
    torso: [0, 1.15, 0.18], // Chest/spine area
    chest: [0, 1.2, 0.2], // Upper chest
    abdomen: [0, 0.85, 0.18], // Lower torso
    back: [0, 1.1, -0.15], // Spine back
    arm: [-0.45, 1.15, 0], // Upper arm area
    leg: [-0.18, 0.4, 0.05], // Thigh area
    neurological: [0, 1.7, 0.08], // Temple/head neural points
    vascular: [0, 1.45, 0.12], // Neck vascular points
    muscular: [0, 1.1, 0.2], // Muscle groups
    skeletal: [0, 0.9, 0.15], // Joints/bones
  };
 
  const basePos = positions[category.toLowerCase()] ?? [0, 1.1, 0.15];
 
  const hash =
    pointId.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0) *
    0.001;
  return [
    basePos[0] + Math.sin(hash * 7.3) * 0.08,
    basePos[1] + Math.cos(hash * 5.1) * 0.08,
    basePos[2] + Math.sin(hash * 3.7) * 0.03,
  ];
};
 
/**
 * Health bar component for training dummy
 *
 * Displays above the dummy with Korean cyberpunk styling.
 * @korean 훈련인형체력바
 */
 
const HEALTH_BAR_WIDTH = 1.2;
const HEALTH_BAR_HEIGHT = 0.1;
 
const DummyHealthBar: React.FC<{
  readonly health: number;
  readonly maxHealth: number;
  readonly position: [number, number, number];
}> = ({ health, maxHealth, position }) => {
  const healthPercent = Math.max(0, Math.min(100, (health / maxHealth) * 100));
 
  const bgGeometry = useMemo(
    () => new THREE.BoxGeometry(HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT, 0.02),
    [],
  );
  const healthGeometry = useMemo(
    () => new THREE.BoxGeometry(HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT, 0.02),
    [],
  );
  const borderGeometry = useMemo(
    () =>
      new THREE.BoxGeometry(
        HEALTH_BAR_WIDTH + 0.04,
        HEALTH_BAR_HEIGHT + 0.04,
        0.01,
      ),
    [],
  );
 
  const healthColor = useMemo(() => {
    Eif (healthPercent > 70) return KOREAN_COLORS.HEALTH_FULL;
    if (healthPercent > 40) return KOREAN_COLORS.HEALTH_MEDIUM;
    if (healthPercent > 20) return KOREAN_COLORS.HEALTH_LOW;
    return KOREAN_COLORS.HEALTH_CRITICAL;
  }, [healthPercent]);
 
  const healthScale: [number, number, number] = useMemo(
    () => [healthPercent / 100, 1, 1],
    [healthPercent],
  );
 
  useEffect(() => {
    return () => {
      bgGeometry.dispose();
      healthGeometry.dispose();
      borderGeometry.dispose();
    };
  }, [bgGeometry, healthGeometry, borderGeometry]);
 
  return (
    <group position={position} name="dummy-health-bar">
      {/* Background bar */}
      <mesh>
        <primitive object={bgGeometry} />
        <meshBasicMaterial
          color={KOREAN_COLORS.UI_BACKGROUND_DARK}
          transparent
          opacity={0.7}
        />
      </mesh>
 
      {/* Health bar (scaled based on health, anchored to left edge) */}
      <mesh
        position={[
          -(HEALTH_BAR_WIDTH * (1 - healthPercent / 100)) / 2,
          0,
          0.01,
        ]}
        scale={healthScale}
      >
        <primitive object={healthGeometry} />
        <meshBasicMaterial color={healthColor} transparent opacity={0.9} />
      </mesh>
 
      {/* Border frame - outline using EdgesGeometry for crisp border */}
      <lineSegments>
        <edgesGeometry args={[borderGeometry]} />
        <lineBasicMaterial
          color={KOREAN_COLORS.PRIMARY_CYAN}
          transparent
          opacity={0.8}
        />
      </lineSegments>
    </group>
  );
};
 
/**
 * TrainingDummy3D Component
 *
 * Main training dummy using SkeletalPlayer3D for consistent visual appearance.
 * Displays vital points for martial arts practice with difficulty-based sizing.
 *
 * @example
 * ```tsx
 * <TrainingDummy3D
 *   position={[0, 0, 5]}
 *   selectedVitalPoint="temple"
 *   isTraining={true}
 *   health={75}
 *   difficulty="normal"
 *   onVitalPointHit={(id) => console.log(`Hit ${id}`)}
 * />
 * ```
 *
 * @korean 훈련인형3D컴포넌트
 */
export const TrainingDummy3D: React.FC<TrainingDummy3DProps> = ({
  position,
  selectedVitalPoint,
  isTraining,
  health = 100,
  maxHealth = 100,
  onVitalPointHit,
  onDefeated,
  difficulty = "normal",
  vitalPointCount = 12,
  isMobile = false,
  archetype = PlayerArchetype.MUSA,
  stance = TrigramStance.GEON,
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const [isStunned, setIsStunned] = useState(false);
 
  const vitalPoints = useMemo(
    () =>
      KOREAN_VITAL_POINTS.slice(
        0,
        Math.min(vitalPointCount, KOREAN_VITAL_POINTS.length),
      ),
    [vitalPointCount],
  );
 
  const sizeMultiplier = useMemo(() => {
    switch (difficulty) {
      case "easy":
        return 1.5; // Larger targets
      case "normal":
        return 1.0; // Standard size
      case "hard":
        return 0.7; // Smaller targets
      default:
        return 1.0;
    }
  }, [difficulty]);
 
  const prevHealthRef = useRef(health);
 
  const onDefeatedRef = useRef(onDefeated);
  useEffect(() => {
    onDefeatedRef.current = onDefeated;
  }, [onDefeated]);
 
  useEffect(() => {
    Iif (prevHealthRef.current > 0 && health <= 0) {
      onDefeatedRef.current?.();
    }
 
    Iif (prevHealthRef.current - health > 20) {
      setIsStunned(true);
      const timer = setTimeout(() => setIsStunned(false), 500);
      return () => clearTimeout(timer);
    }
 
    prevHealthRef.current = health;
    return undefined;
  }, [health]);
 
  useFrame((state) => {
    if (!groupRef.current) return;
 
    const time = state.clock.elapsedTime;
    const breathScale = Math.sin(time * 1.5) * 0.01 + 1;
    groupRef.current.scale.y = breathScale;
 
    groupRef.current.rotation.y = Math.sin(time * 0.5) * 0.02;
  });
 
  const handlePointHit = useCallback(
    (pointId: string) => {
      onVitalPointHit?.(pointId);
    },
    [onVitalPointHit],
  );
 
  return (
    <group ref={groupRef} position={position} name="training-dummy-3d">
      {/* SkeletalPlayer3D as the base character model */}
      <SkeletalPlayer3D
        playerId="training-dummy"
        archetype={archetype}
        stance={stance}
        position={[0, 0, 0]}
        rotation={Math.PI} // Face the player
        facing="left"
        health={health}
        maxHealth={maxHealth}
        stamina={100}
        ki={50}
        balance="READY"
        pain={0}
        consciousness={100}
        isMobile={isMobile}
        currentAnimation="idle"
        isBlocking={false}
        isStunned={isStunned}
        showHealthBar={false} // We use custom health bar
        showStanceIndicator={false}
        enableFacialExpressions={true}
        enableEyeTracking={true}
      />
 
      {/* Vital point markers overlaid on the skeletal model */}
      {vitalPoints.map((point) => (
        <group
          key={point.id}
          position={getVitalPointPosition(point.id, point.category)}
        >
          <VitalPointMarker3D
            vitalPoint={point}
            isSelected={point.id === selectedVitalPoint}
            isTraining={isTraining}
            isMobile={isMobile}
            onHit={handlePointHit}
            sizeMultiplier={sizeMultiplier}
          />
        </group>
      ))}
 
      {/* Health bar above dummy */}
      {isTraining && (
        <DummyHealthBar
          health={health}
          maxHealth={maxHealth}
          position={[0, 2.3, 0]}
        />
      )}
 
      {/* Training mode indicator glow */}
      {isTraining && (
        <pointLight
          position={[0, 1.2, 0.5]}
          color={KOREAN_COLORS.PRIMARY_CYAN}
          intensity={0.3}
          distance={3}
          decay={2}
        />
      )}
    </group>
  );
};
 
export default TrainingDummy3D;