All files / components/three Player3DUnified.tsx

45.23% Statements 38/84
48.11% Branches 51/106
76.92% Functions 10/13
44.15% Lines 34/77

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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469                                                              5x 71x                   71x                   5x 71x                   71x                                                                           5x                                                   131x 131x 131x 131x 131x     131x 71x         131x 71x 71x 71x   71x                     131x 71x                 131x 71x 71x 69x                   131x 131x     131x 71x 71x       71x                   71x       131x                                                                                                                                                     131x                                                                                                                                                                                                                                                                                                                                                                                            
/**
 * Player3DUnified - Unified 3D player visual component
 * 
 * Provides a complete, reusable 3D player representation for use in both
 * CombatScreen3D and TrainingScreen3D. Includes body mesh, stance aura,
 * state indicators, and animations.
 * 
 * @module components/three/Player3DUnified
 * @category 3D Components
 * @korean 통합플레이어3D
 */
 
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useEffect, useMemo, useRef } from "react";
import * as THREE from "three";
import { TrigramStance } from "../../types/common";
import { FONT_FAMILY, KOREAN_COLORS } from "../../types/constants";
import type { Player3DUnifiedProps } from "../../types/player-visual";
import { toHexColor } from "../../utils/colorHelpers";
import { getArchetypeColors } from "../../utils/colorUtils";
import PlayerStateIndicators from "./PlayerStateIndicators";
import StanceAura from "./StanceAura";
 
/**
 * Get stance-specific color from Korean theming
 * 
 * @param stance - Current trigram stance
 * @returns Hex color number
 * @korean 자세색상가져오기
 */
const getStanceColor = (stance: TrigramStance): number => {
  const stanceColors = {
    [TrigramStance.GEON]: KOREAN_COLORS.TRIGRAM_GEON_PRIMARY,
    [TrigramStance.TAE]: KOREAN_COLORS.TRIGRAM_TAE_PRIMARY,
    [TrigramStance.LI]: KOREAN_COLORS.TRIGRAM_LI_PRIMARY,
    [TrigramStance.JIN]: KOREAN_COLORS.TRIGRAM_JIN_PRIMARY,
    [TrigramStance.SON]: KOREAN_COLORS.TRIGRAM_SON_PRIMARY,
    [TrigramStance.GAM]: KOREAN_COLORS.TRIGRAM_GAM_PRIMARY,
    [TrigramStance.GAN]: KOREAN_COLORS.TRIGRAM_GAN_PRIMARY,
    [TrigramStance.GON]: KOREAN_COLORS.TRIGRAM_GON_PRIMARY,
  };
  return stanceColors[stance] ?? KOREAN_COLORS.PRIMARY_CYAN;
};
 
/**
 * Get trigram symbol for stance
 * 
 * @param stance - Current trigram stance
 * @returns Unicode trigram symbol
 * @korean 팔괘기호가져오기
 */
const getTrigramSymbol = (stance: TrigramStance): string => {
  const symbols = {
    [TrigramStance.GEON]: "☰",
    [TrigramStance.TAE]: "☱",
    [TrigramStance.LI]: "☲",
    [TrigramStance.JIN]: "☳",
    [TrigramStance.SON]: "☴",
    [TrigramStance.GAM]: "☵",
    [TrigramStance.GAN]: "☶",
    [TrigramStance.GON]: "☷",
  };
  return symbols[stance] ?? "☰";
};
 
/**
 * Player3DUnified Component
 * 
 * Complete unified 3D player representation with:
 * - Body mesh with archetype-specific styling
 * - Stance aura effect (8 trigrams)
 * - State indicators (health, stamina, Ki, balance)
 * - Combat animations (attack, defend, hit, etc.)
 * - Pain/balance/consciousness visualization
 * 
 * @example
 * ```tsx
 * <Player3DUnified
 *   playerId="player1"
 *   archetype={PlayerArchetype.MUSA}
 *   stance={TrigramStance.GEON}
 *   position={[0, 0, 0]}
 *   rotation={0}
 *   health={85}
 *   maxHealth={100}
 *   stamina={60}
 *   ki={40}
 *   pain={20}
 *   balance="READY"
 *   consciousness={100}
 *   bloodLoss={0}
 *   isBlocking={false}
 *   isAttacking={false}
 *   currentAnimation="idle"
 *   isMobile={false}
 * />
 * ```
 * 
 * @korean 통합플레이어3D컴포넌트
 */
export const Player3DUnified: React.FC<Player3DUnifiedProps> = ({
  playerId,
  archetype,
  stance,
  position,
  rotation,
  health,
  maxHealth,
  stamina,
  ki,
  pain,
  balance,
  consciousness,
  bloodLoss,
  isBlocking,
  isStunned = false,
  isCountering = false,
  currentAnimation,
  isMobile,
  name,
  scale = 1,
  showDetails = true,
  facing = "right",
  showStanceIndicator = true,
  onAnimationComplete,
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const bodyRef = useRef<THREE.Mesh>(null);
  const bodyMaterialRef = useRef<THREE.MeshStandardMaterial | null>(null);
  const attackTimeRef = useRef(0);
  const lastAnimationRef = useRef(currentAnimation);
 
  // Get archetype colors
  const archetypeColors = useMemo(
    () => getArchetypeColors(archetype),
    [archetype]
  );
 
  // Calculate visual states
  const visualStates = useMemo(() => {
    const healthPercent = health / maxHealth;
    const kiPercent = ki / 100;
    const consciousnessPercent = consciousness / 100;
 
    return {
      healthPercent,
      kiPercent,
      consciousnessPercent,
      isLowHealth: healthPercent < 0.3,
      isHighKi: kiPercent > 0.8,
      shouldGlow: isBlocking || isCountering || kiPercent > 0.7,
    };
  }, [health, maxHealth, ki, consciousness, isBlocking, isCountering]);
 
  // Cache material reference on mount
  useEffect(() => {
    Iif (bodyRef.current?.material) {
      if ("emissiveIntensity" in bodyRef.current.material) {
        bodyMaterialRef.current = bodyRef.current
          .material as THREE.MeshStandardMaterial;
      }
    }
  }, []);
 
  // Body color based on state
  const bodyColor = useMemo(() => {
    Iif (isStunned) return KOREAN_COLORS.WARNING_YELLOW;
    if (visualStates.isLowHealth) return KOREAN_COLORS.ACCENT_RED;
    Eif (visualStates.isHighKi) return KOREAN_COLORS.PRIMARY_CYAN;
    return archetypeColors.primary;
  }, [
    isStunned,
    visualStates.isLowHealth,
    visualStates.isHighKi,
    archetypeColors.primary,
  ]);
 
  // Stance color
  const stanceColor = useMemo(() => getStanceColor(stance), [stance]);
  const trigramSymbol = useMemo(() => getTrigramSymbol(stance), [stance]);
 
  // Reset attack animation timer when animation state changes
  useEffect(() => {
    Eif (currentAnimation !== "attack") {
      attackTimeRef.current = 0;
    }
 
    // Trigger animation complete callback if animation changed
    Iif (
      lastAnimationRef.current !== currentAnimation &&
      onAnimationComplete
    ) {
      const timer = setTimeout(() => {
        onAnimationComplete();
      }, 500); // Animation duration
      return () => clearTimeout(timer);
    }
 
    lastAnimationRef.current = currentAnimation;
  }, [currentAnimation, onAnimationComplete]);
 
  // Animation loop using useFrame (60fps)
  useFrame((state, delta) => {
    if (!groupRef.current || !bodyRef.current) return;
 
    // --- Consolidated scale accumulator pattern ---
    // Start with base scale
    let accumulatedScaleX = (facing === "left" ? -1 : 1) * scale;
    let accumulatedScaleY = scale;
    let accumulatedScaleZ = scale;
 
    // Breathing animation
    const breath = 1 + Math.sin(state.clock.elapsedTime * 2) * 0.02;
    accumulatedScaleY *= breath;
 
    // Stance change animation - pulse multiplied with breathing
    if (currentAnimation === "stance_change") {
      const pulseScale = 1 + Math.sin(state.clock.elapsedTime * 10) * 0.1;
      accumulatedScaleX *= pulseScale;
      accumulatedScaleY *= pulseScale; // Multiplies with breathing animation
      accumulatedScaleZ *= pulseScale;
    }
 
    // Set the final scale once
    groupRef.current.scale.set(accumulatedScaleX, accumulatedScaleY, accumulatedScaleZ);
 
    // Attack animation
    if (currentAnimation === "attack") {
      attackTimeRef.current += delta;
      const attackProgress = attackTimeRef.current / 0.5; // 500ms attack
 
      if (attackProgress < 1) {
        // Lunge forward
        bodyRef.current.position.z = Math.sin(attackProgress * Math.PI) * 0.5;
      } else {
        // Reset
        bodyRef.current.position.z = 0;
        attackTimeRef.current = 0;
      }
    } else {
      bodyRef.current.position.z = 0;
    }
 
    // Hit animation - flash and recoil (using cached material)
    if (currentAnimation === "hit") {
      const hitFlash = Math.sin(state.clock.elapsedTime * 20);
      if (bodyMaterialRef.current) {
        bodyMaterialRef.current.emissiveIntensity = Math.abs(hitFlash) * 0.5;
      }
      // Recoil backward
      bodyRef.current.position.z = Math.sin(state.clock.elapsedTime * 20) * -0.1;
    } else if (bodyMaterialRef.current) {
      bodyMaterialRef.current.emissiveIntensity = visualStates.shouldGlow ? 0.3 : 0.1;
    }
 
    // --- Consolidated rotation (Ki aura + balance wobble) ---
    let rotationY = 0;
    let rotationZ = 0;
 
    // Ki aura rotation
    if (visualStates.shouldGlow) {
      rotationY = Math.sin(state.clock.elapsedTime * 0.5) * 0.2;
    }
 
    // Balance state wobble
    if (balance === "SHAKEN" || balance === "VULNERABLE") {
      rotationZ = Math.sin(state.clock.elapsedTime * 5) * 0.05;
    } else if (balance === "HELPLESS") {
      // Extreme wobble when helpless
      rotationZ = Math.sin(state.clock.elapsedTime * 8) * 0.15;
    }
 
    // Apply combined rotations
    groupRef.current.rotation.y = rotationY;
    groupRef.current.rotation.z = rotationZ;
  });
 
  return (
    <group
      ref={groupRef}
      position={position}
      rotation={[0, rotation, 0]}
      data-testid={`player3d-${playerId}`}
    >
      {/* Stance aura effect */}
      <StanceAura stance={stance} intensity={ki / 100} animated />
 
      {/* Main body (torso) */}
      <mesh
        ref={bodyRef}
        position={[0, 1, 0]}
        castShadow
        receiveShadow
        data-testid="player-body"
      >
        <capsuleGeometry args={[0.3, 0.8, 8, 16]} />
        <meshStandardMaterial
          color={bodyColor}
          emissive={bodyColor}
          emissiveIntensity={0.1}
          metalness={0.3}
          roughness={0.7}
        />
      </mesh>
 
      {/* Head */}
      <mesh position={[0, 1.9, 0]} castShadow receiveShadow>
        <sphereGeometry args={[0.2, 16, 16]} />
        <meshStandardMaterial
          color={
            visualStates.isLowHealth
              ? KOREAN_COLORS.ACCENT_RED
              : archetypeColors.secondary
          }
          metalness={0.2}
          roughness={0.8}
        />
      </mesh>
 
      {/* Arms */}
      <mesh
        position={
          currentAnimation === "attack"
            ? [-0.4, 1.2, 0.3]
            : currentAnimation === "defend" || isBlocking
            ? [-0.3, 1.4, 0.2]
            : [-0.4, 1.2, 0]
        }
        rotation={[0, 0, currentAnimation === "attack" ? -0.5 : 0]}
        castShadow
      >
        <capsuleGeometry args={[0.08, 0.6, 4, 8]} />
        <meshStandardMaterial color={bodyColor} />
      </mesh>
      <mesh
        position={
          currentAnimation === "attack"
            ? [0.4, 1.2, 0.3]
            : currentAnimation === "defend" || isBlocking
            ? [0.3, 1.4, 0.2]
            : [0.4, 1.2, 0]
        }
        rotation={[0, 0, currentAnimation === "attack" ? 0.5 : 0]}
        castShadow
      >
        <capsuleGeometry args={[0.08, 0.6, 4, 8]} />
        <meshStandardMaterial color={bodyColor} />
      </mesh>
 
      {/* Legs */}
      <mesh
        position={[-0.15, 0.4, 0]}
        rotation={[currentAnimation === "walk" ? 0.2 : 0, 0, 0]}
        castShadow
      >
        <capsuleGeometry args={[0.1, 0.7, 4, 8]} />
        <meshStandardMaterial color={bodyColor} />
      </mesh>
      <mesh
        position={[0.15, 0.4, 0]}
        rotation={[currentAnimation === "walk" ? -0.2 : 0, 0, 0]}
        castShadow
      >
        <capsuleGeometry args={[0.1, 0.7, 4, 8]} />
        <meshStandardMaterial color={bodyColor} />
      </mesh>
 
      {/* Blocking shield effect */}
      {isBlocking && (
        <mesh position={[0, 1.2, 0.3]}>
          <circleGeometry args={[0.5, 32]} />
          <meshBasicMaterial
            color={KOREAN_COLORS.PRIMARY_BLUE}
            transparent
            opacity={0.5}
            side={THREE.DoubleSide}
          />
        </mesh>
      )}
 
      {/* Counter indicator */}
      {isCountering && (
        <mesh position={[0, 1.5, 0]}>
          <torusGeometry args={[0.4, 0.05, 8, 32]} />
          <meshBasicMaterial color={KOREAN_COLORS.ACCENT_PURPLE} />
        </mesh>
      )}
 
      {/* Player name overlay */}
      {showDetails && name && (
        <Html
          position={[0, 2.8, 0]}
          center
          distanceFactor={isMobile ? 15 : 10}
          occlude={false}
          style={{ pointerEvents: "none", userSelect: "none" }}
        >
          <div
            style={{
              fontFamily: FONT_FAMILY.KOREAN,
              textAlign: "center",
              color: "white",
              textShadow: "0 0 4px rgba(0,0,0,0.8)",
            }}
          >
            {/* Player name */}
            <div
              style={{
                fontSize: isMobile ? "12px" : "14px",
                fontWeight: "bold",
                marginBottom: "4px",
              }}
              data-testid="player-name"
            >
              {name.korean}
            </div>
 
            {/* Trigram symbol */}
            {showStanceIndicator && (
              <div
                style={{
                  fontSize: isMobile ? "14px" : "16px",
                  color: toHexColor(stanceColor),
                }}
                data-testid="trigram-symbol"
              >
                {trigramSymbol}
              </div>
            )}
 
            {/* Combat state text */}
            {(isBlocking || isStunned || isCountering) && (
              <div
                style={{
                  fontSize: isMobile ? "10px" : "12px",
                  fontWeight: "bold",
                  color: "#ffff00",
                  marginTop: "4px",
                }}
                data-testid="combat-state"
              >
                {isBlocking ? "방어" : isStunned ? "기절" : "반격"}
              </div>
            )}
          </div>
        </Html>
      )}
 
      {/* State indicators (health, stamina, Ki, balance) */}
      {showDetails && (
        <PlayerStateIndicators
          health={health}
          maxHealth={maxHealth}
          stamina={stamina}
          ki={ki}
          balance={balance}
          consciousness={consciousness}
          pain={pain}
          bloodLoss={bloodLoss}
          isMobile={isMobile}
        />
      )}
    </group>
  );
};
 
export default Player3DUnified;