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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | 4x 4x 13x 13x 13x 13x 13x 13x 13x 13x 13x 85x 85x 85x 24x 24x 85x 85x 85x 85x 85x 13x 13x 4x 4x 13x 13x 13x 13x 13x 13x 13x 13x 9x 13x 12x 12x 12x 1x 85x | /**
* useTrainingActions Hook - Training Action Handlers
*
* Custom hook for managing training action handlers.
* Mirrors useCombatActions pattern for consistency.
*
* @korean 훈련액션훅 - 훈련 액션 핸들러 관리
*/
import { useCallback, useRef } from "react";
import {
AudioBodyRegion,
ImpactIntensity,
} from "../../../../audio/types";
import type { AttackIntensity } from "../../../screens/combat/hooks/useCombatAudio";
import { getArchetypePhysicalAttributes } from "../../../../data/archetypePhysicalAttributes";
import {
AnimationState,
AnimationType,
getAnimationForTechnique,
} from "../../../../systems/animation";
import { physicalReachCalculator } from "../../../../systems/physics";
import { getTechniquesByStance } from "../../../../systems/trigram/techniques";
import { KoreanTechniquesSystem } from "../../../../systems/trigram/KoreanTechniques";
import { TRIGRAM_STANCES_ORDER } from "../../../../systems/trigram/types";
import type { KoreanTechnique } from "../../../../systems/vitalpoint/types";
import {
CombatAttackType,
DamageType,
PlayerArchetype,
Position,
TrigramStance,
} from "../../../../types/common";
import {
DEFAULT_BODY_RADIUS_METERS,
METERS_TO_TRAINING_UNITS,
} from "../../../../types/physicsConstants";
import { calculateDistance3D } from "../../../../utils/math";
import { TrainingActions, TrainingScreenState } from "./useTrainingState";
export interface UseTrainingActionsConfig {
readonly state: TrainingScreenState;
readonly actions: TrainingActions;
readonly playerPosition: Position;
readonly player3DPosition: [number, number, number];
readonly dummyPosition: [number, number, number];
readonly playerArchetype: import("../../../../types/common").PlayerArchetype;
readonly playerStance: TrigramStance;
/** Ref to current selected technique's animation type for distance-based hit detection */
readonly currentTechniqueAnimationTypeRef: React.MutableRefObject<AnimationType>;
readonly audio: {
readonly playSFX: (sound: string, volume?: number) => Promise<void>;
};
/** Attack sound function from useCombatAudio for playing attack whoosh sounds */
readonly playAttackSound?: (intensity: AttackIntensity) => Promise<void>;
/** Bone impact audio function from useCombatAudio or similar hook */
readonly playBoneImpactSound?: (options: {
region?: AudioBodyRegion;
intensity?: ImpactIntensity;
damage?: number;
remainingHealth?: number;
vitalPoint?: boolean;
hitPosition?: { x: number; y: number; z?: number };
}) => Promise<void>;
readonly onPlayerUpdate: (updates: {
currentStance?: TrigramStance;
lastActionTime?: number;
position?: Position;
}) => void;
readonly playerAnimation: {
readonly transitionTo: (state: AnimationState) => boolean;
readonly transitionToStanceGuard: (stance: TrigramStance) => boolean;
readonly currentState: string;
};
/** External ref to store pending attack data - shared with animation events */
readonly pendingAttackRef: React.MutableRefObject<{
accuracy: number;
vitalPoint: string;
animationType?: AnimationType;
startTime?: number;
techniqueId?: string;
} | null>;
/** Currently selected technique ID (from technique bar) */
readonly selectedTechniqueId?: string;
/** Callback to set the visual attack animation */
readonly setAttackAnimation?: (animationName: string | undefined) => void;
}
export interface UseTrainingActionsReturn {
readonly handleStartTraining: () => void;
readonly handleStopTraining: () => void;
readonly handleDummyHit: (
vitalPointId: string,
attackContext?: {
animationType?: AnimationType;
techniqueId?: string;
},
) => boolean;
readonly handleDummyDefeated: () => void;
readonly handleStanceChange: (stanceIndex: number) => void;
readonly handleAttack: () => void;
}
/**
* Get the best default technique for an archetype based on current stance.
*
* Each archetype has preferred combat styles:
* - MUSA: Direct strikes, joint techniques (BLUNT/JOINT damage)
* - AMSALJA: Nerve strikes, pressure points (NERVE/PRESSURE damage)
* - HACKER: Precise calculated strikes (high accuracy)
* - JEONGBO_YOWON: Psychological pressure, submissions (PRESSURE/JOINT)
* - JOJIK_POKRYEOKBAE: High damage brutal strikes
*
* @korean 원형별 기본 기술 선택 - 8개 자세에 따른 최적 기술
*/
function getDefaultTechniqueForArchetype(
archetype: PlayerArchetype,
stance: TrigramStance,
): KoreanTechnique | undefined {
const techniques = getTechniquesByStance(stance);
Eif (techniques.length === 0) return undefined;
// Score each technique based on archetype preference
const scoredTechniques = techniques.map((tech) => {
let score = 0;
const damageType = tech.damageType;
const attackType = tech.type;
const isAdvanced =
(tech.kiCost || 0) >= 10 || (tech.staminaCost || 0) >= 15;
switch (archetype) {
case PlayerArchetype.MUSA:
// Musa prefers: strikes, blocks, counter-attacks (BLUNT/JOINT/CRUSHING)
if (damageType === DamageType.JOINT) score += 30;
if (damageType === DamageType.CRUSHING) score += 25;
if (damageType === DamageType.BLUNT) score += 20;
if (attackType === CombatAttackType.STRIKE) score += 15;
if (attackType === CombatAttackType.PUNCH) score += 10;
if (isAdvanced) score += 10;
break;
case PlayerArchetype.AMSALJA:
// Amsalja prefers: nerve strikes, pressure points, thrusts
if (damageType === DamageType.NERVE) score += 35;
if (damageType === DamageType.PRESSURE) score += 30;
if (attackType === CombatAttackType.NERVE_STRIKE) score += 25;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 25;
if (attackType === CombatAttackType.THRUST) score += 15;
if ((tech.accuracy || 0) >= 0.9) score += 10;
break;
case PlayerArchetype.HACKER:
// Hacker prefers: high accuracy, calculated strikes
if ((tech.accuracy || 0) >= 0.9) score += 30;
if ((tech.accuracy || 0) >= 0.8) score += 15;
if (damageType === DamageType.NERVE) score += 20;
if (damageType === DamageType.INTERNAL) score += 20;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 15;
break;
case PlayerArchetype.JEONGBO_YOWON:
// Jeongbo prefers: psychological pressure, submissions
if (damageType === DamageType.PRESSURE) score += 30;
if (damageType === DamageType.JOINT) score += 25;
if (attackType === CombatAttackType.GRAPPLE) score += 20;
if (attackType === CombatAttackType.PRESSURE_POINT) score += 15;
break;
case PlayerArchetype.JOJIK_POKRYEOKBAE:
// Jojik prefers: high damage, brutal techniques
if ((tech.damage || 0) >= 35) score += 35;
if ((tech.damage || 0) >= 30) score += 20;
if (damageType === DamageType.SLASHING) score += 20;
if (damageType === DamageType.PIERCING) score += 15;
if (damageType === DamageType.CRUSHING) score += 15;
if (attackType === CombatAttackType.KICK) score += 10;
break;
}
return { technique: tech, score };
});
// Sort by score descending, return highest scoring technique
scoredTechniques.sort((a, b) => b.score - a.score);
return scoredTechniques[0]?.technique;
}
/**
* Calculate hit accuracy based on distance and effective reach.
* Uses PhysicalReachCalculator for animation-aware reach calculation.
*
* Distance logic matches CombatSystem: if out of reach, guaranteed miss (accuracy 0).
* Training scene coordinates are in meters, using METERS_TO_TRAINING_UNITS = 1.0.
*
* **IMPORTANT**: Distance calculation accounts for body radius.
* Center-to-center distance is adjusted by subtracting target body radius
* because attacks hit the body surface, not the center point.
* The target body radius is calculated from physical attributes for archetypes,
* or uses DEFAULT_BODY_RADIUS_METERS for training dummies.
*
* Example: If player center is 1.5m from dummy center, but dummy body
* extends 0.23m from center, the effective distance to hit is 1.27m.
*
* @korean 거리 기반 명중률 계산 - 사정거리 밖이면 빗나감
*/
function calculateHitAccuracy(
playerPos: [number, number, number],
dummyPos: [number, number, number],
archetype: import("../../../../types/common").PlayerArchetype,
stance: TrigramStance,
animationType?: AnimationType,
reachConfig?: import("../../../../types/physics").PhysicalReachConfig,
): number {
// Calculate 3D distance between player and dummy centers (in meters)
const centerToCenterDistance = calculateDistance3D(playerPos, dummyPos);
// Get player's physical attributes for reach calculation
const playerPhysicalAttributes = getArchetypePhysicalAttributes(archetype);
// Training dummy uses default body radius since it has no archetype
// For combat between players, we would use calculateBodyRadius(targetPhysicalAttributes)
// 훈련 더미는 원형이 없으므로 기본 몸체 반경 사용
const targetBodyRadius = DEFAULT_BODY_RADIUS_METERS;
// Effective distance = center-to-center minus target body radius only
// Note: PhysicalReachCalculator already includes player body pivot/offset in reach calculation,
// so we only subtract the target radius to avoid double-counting.
// 유효 거리 = 중심간 거리 - 더미 몸체 반경 (플레이어 몸체 오프셋은 도달 거리에 포함됨)
const effectiveDistance = Math.max(
0,
centerToCenterDistance - targetBodyRadius,
);
// If animation type is available, use physics-based reach calculation
// We use calculateMaxReach (peak time reach) because:
// 1. Training hit detection happens at animation frame 6 (~100ms)
// 2. But technique hit timings expect longer animations (e.g., roundhouse 200-480ms)
// 3. Using max reach ensures the technique can hit if within peak reach range
// 4. This matches intuitive behavior - if you're close enough to be hit by the kick, it hits
// 훈련 타격 감지는 최대 도달 거리 사용 (애니메이션 타이밍과 기술 타이밍 불일치 보정)
Eif (animationType !== undefined) {
const maxReachMeters = physicalReachCalculator.calculateMaxReach(
playerPhysicalAttributes,
animationType,
stance,
reachConfig, // Use technique's designed reach if provided
);
// Convert reach from meters to training scene units.
// Training scenes are authored in real-world meters, so we intentionally
// use a 1:1 conversion here (METERS_TO_TRAINING_UNITS = 1.0).
// Combat AI uses METERS_TO_PIXELS_SCALE (100) for pixel coordinates.
const reachInUnits = maxReachMeters * METERS_TO_TRAINING_UNITS;
// STRICT DISTANCE CHECK (matches CombatSystem behavior):
// Out of reach = guaranteed miss with accuracy 0
Eif (effectiveDistance > reachInUnits) {
return 0;
}
// Within reach: accuracy based on how centered the hit is
// Closer = higher accuracy (0.7 to 1.0 range)
return Math.max(0.7, 1.0 - (effectiveDistance / reachInUnits) * 0.3);
}
// Fallback: use default punch reach (0.7 meters) for legacy behavior
const defaultReach = 0.7 * METERS_TO_TRAINING_UNITS;
if (effectiveDistance > defaultReach) {
return 0; // Out of reach = miss
}
// Within default reach: linear accuracy based on distance
return Math.max(0.5, 1.0 - (effectiveDistance / defaultReach) * 0.5);
}
/**
* useTrainingActions hook
* Provides training action handlers with proper memoization
*/
export function useTrainingActions(
config: UseTrainingActionsConfig,
): UseTrainingActionsReturn {
const {
state,
actions,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
currentTechniqueAnimationTypeRef,
audio,
playBoneImpactSound,
playAttackSound,
onPlayerUpdate,
playerAnimation,
pendingAttackRef,
selectedTechniqueId,
setAttackAnimation,
} = config;
// Ref to store timeout for dummy reset
const dummyResetTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const handleStartTraining = useCallback(() => {
actions.startTraining();
audio.playSFX("menu_select");
}, [actions, audio]);
const handleStopTraining = useCallback(() => {
// Clear any pending dummy reset timeout
if (dummyResetTimeoutRef.current) {
clearTimeout(dummyResetTimeoutRef.current);
dummyResetTimeoutRef.current = null;
}
actions.stopTraining();
audio.playSFX("menu_back");
}, [actions, audio]);
const handleDummyDefeated = useCallback(() => {
actions.setFeedback("훈련 더미 무력화! | Dummy Defeated!");
audio.playSFX("ki_release");
// Clear any existing timeout
if (dummyResetTimeoutRef.current) {
clearTimeout(dummyResetTimeoutRef.current);
}
// Reset dummy health after delay
dummyResetTimeoutRef.current = setTimeout(() => {
actions.resetDummy();
}, 2000);
}, [actions, audio]);
const handleDummyHit = useCallback(
(
_vitalPointId: string,
attackContext?: {
animationType?: AnimationType;
techniqueId?: string;
},
): boolean => {
// Get animation context from the passed attackContext parameter
// (TrainingScreen3D.tsx should pass the attackData before clearing the ref)
const animationType = attackContext?.animationType;
// Get technique's reachConfig for accurate reach calculation
// Priority: attackContext.techniqueId (resolved in handleAttack) > selectedTechniqueId
// This ensures default techniques (chosen when no explicit selection) also get their reachConfig
let reachConfig: import("../../../../types/physics").PhysicalReachConfig | undefined;
const resolvedTechniqueId =
attackContext?.techniqueId ?? selectedTechniqueId;
if (resolvedTechniqueId) {
const technique = KoreanTechniquesSystem.getTechniqueById(resolvedTechniqueId);
reachConfig = technique?.reachConfig;
}
const accuracy = calculateHitAccuracy(
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
animationType,
reachConfig,
);
// Determine hit position (dummy center)
const hitPosition: [number, number, number] = [
dummyPosition[0],
1.5,
dummyPosition[2],
];
if (accuracy > 0.5) {
const points = Math.round(accuracy * 100);
const damage = Math.round(accuracy * 15); // 0-15 damage based on accuracy
const isPerfect = accuracy > 0.9;
// Register hit with state (only counts if training)
if (state.isTraining) {
actions.registerHit(points, damage, isPerfect);
}
// Play bone impact audio with anatomical feedback using proper audio system
if (playBoneImpactSound) {
void playBoneImpactSound({
damage,
remainingHealth: 100, // Dummy has 100 health
vitalPoint: false,
hitPosition: { x: hitPosition[0], y: hitPosition[1], z: hitPosition[2] },
});
}
// Determine feedback and sound
let effectType: "success" | "perfect";
if (isPerfect) {
actions.setFeedback("완벽한 타격! | Perfect Strike!");
audio.playSFX("ki_release");
effectType = "perfect";
} else if (accuracy > 0.7) {
actions.setFeedback("좋은 타격! | Good Strike!");
audio.playSFX("ki_charge");
effectType = "success";
} else {
actions.setFeedback("타격 성공 | Strike Success");
audio.playSFX("menu_click");
effectType = "success";
}
// Add hit effect
actions.addHitEffect({
position: hitPosition,
type: effectType,
visible: true,
damage,
});
return true;
} else {
// Register miss (only counts if training)
if (state.isTraining) {
actions.registerMiss();
}
actions.setFeedback("빗나감 | Miss - Out of reach!");
audio.playSFX("menu_navigate");
// Add miss effect
actions.addHitEffect({
position: hitPosition,
type: "miss",
visible: true,
});
return false;
}
},
[
state.isTraining,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
actions,
audio,
playBoneImpactSound,
selectedTechniqueId,
],
);
const handleStanceChange = useCallback(
(stanceIndex: number) => {
actions.setStanceIndex(stanceIndex);
const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
if (stance) {
// Directly transition to stance guard animation (skips transitional animation)
// 자세 가드 애니메이션으로 직접 전환 (전환 애니메이션 생략)
playerAnimation.transitionToStanceGuard(stance);
onPlayerUpdate({ currentStance: stance });
audio.playSFX("stance_change");
}
},
[actions, onPlayerUpdate, audio, playerAnimation],
);
const handleAttack = useCallback(() => {
// Determine which technique to use:
// 1. If a technique is explicitly selected from the TechniqueBar, use that
// 2. Otherwise, use the best default technique for the archetype + stance
// 사용할 기술 결정: 명시적 선택 또는 원형+자세 기반 기본 기술
let techniqueToUse: KoreanTechnique | undefined;
let techniqueId = selectedTechniqueId;
if (!techniqueId) {
// No technique explicitly selected - get default for archetype + stance
// 명시적 선택 없음 - 원형과 자세에 맞는 기본 기술 사용
const defaultTechnique = getDefaultTechniqueForArchetype(
playerArchetype,
playerStance,
);
Iif (defaultTechnique) {
techniqueToUse = defaultTechnique;
techniqueId = defaultTechnique.id;
}
}
// Get the animation type from the technique
// 기술에서 애니메이션 타입 가져오기
let animationType = currentTechniqueAnimationTypeRef.current;
Iif (techniqueToUse?.animationType) {
animationType = techniqueToUse.animationType;
currentTechniqueAnimationTypeRef.current = animationType;
}
const startTime = performance.now() / 1000; // Current time in seconds
const accuracy = calculateHitAccuracy(
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
animationType,
techniqueToUse?.reachConfig, // Pass technique's reachConfig for accurate reach
);
pendingAttackRef.current = {
accuracy,
vitalPoint: state.selectedVitalPoint ?? "generic",
animationType,
startTime,
techniqueId, // Store resolved technique ID for handleDummyHit
};
// Set visual attack animation based on technique (AnimationRegistry lookup)
// This ensures the 3D model plays the correct technique animation (kick vs punch vs elbow)
// 기술에 따른 시각적 공격 애니메이션 설정 (발차기 vs 주먹 vs 팔꿈치)
Iif (setAttackAnimation && techniqueId) {
const animationName = getAnimationForTechnique(techniqueId);
setAttackAnimation(animationName);
}
// Trigger attack animation - this will fire onFrame event at frame 6
playerAnimation.transitionTo(AnimationState.ATTACK);
// Play attack sound based on technique damage/intensity
// Resolve technique data if we only have an ID (from TechniqueBar selection)
if (!techniqueToUse && selectedTechniqueId) {
// Technique selected from TechniqueBar but not yet resolved
techniqueToUse = KoreanTechniquesSystem.getTechniqueById(selectedTechniqueId);
}
if (playAttackSound) {
// Prefer explicit technique damage when available
const damage = techniqueToUse?.damage ?? 10;
const intensity: AttackIntensity =
damage >= 40
? "critical"
: damage >= 25
? "heavy"
: damage >= 10
? "medium"
: "light";
void playAttackSound(intensity);
} else {
// Fallback to generic whoosh if playAttackSound not available
audio.playSFX("whoosh");
}
}, [
state.selectedVitalPoint,
player3DPosition,
dummyPosition,
playerArchetype,
playerStance,
currentTechniqueAnimationTypeRef,
playerAnimation,
audio,
playAttackSound,
pendingAttackRef,
selectedTechniqueId,
setAttackAnimation,
]);
return {
handleStartTraining,
handleStopTraining,
handleDummyHit,
handleDummyDefeated,
handleStanceChange,
handleAttack,
};
}
export default useTrainingActions;
|