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 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | 1x 11x 11x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x | /**
* TrainingScreen3D - Three.js-based training screen
*
* Refactored to use consolidated hooks matching CombatScreen architecture.
* Provides 3D training dummy with vital point targeting and Html UI overlays.
*
* @korean 훈련화면3D - 훈련 상태 훅을 사용한 리팩토링된 3D 훈련 화면
*/
import { Html } from "@react-three/drei";
import { Canvas, useFrame } from "@react-three/fiber";
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import { useAudio } from "../../audio/AudioProvider";
import { usePlayerAnimation } from "../../hooks/usePlayerAnimation";
import { useTechniqueSelection } from "../../hooks/useTechniqueSelection";
import { GestureEvent } from "../../hooks/useTouchControls";
import { useWebGLContextLossHandler } from "../../hooks/useWebGLContextLossHandler";
import { PlayerState } from "../../systems";
import { AnimationEvents } from "../../systems/animation";
import { TRIGRAM_STANCES_ORDER } from "../../systems/trigram/types";
import { CombatState, PlayerArchetype, Position, Technique } from "../../types";
import { FONT_FAMILY, KOREAN_COLORS } from "../../types/constants";
import { hexToRgbaString } from "../../utils/colorUtils";
import { usePlayerMovement } from "../../utils/inputSystem";
import {
animationStateToPlayerAnimation,
convertPlayerStateToProps,
} from "../../utils/player3DHelpers";
import {
VitalPointMarkers3D,
VitalPointOverlayControls,
type BodyRegionFilter,
} from "../combat/components";
import { TechniqueBar } from "../combat/components/TechniqueBar";
import { useCombatLayout } from "../combat/hooks/useCombatLayout";
import {
ActionButtons,
GestureRecognizer,
StanceWheel,
VirtualDPad,
} from "../mobile";
import { ButtonEventType } from "../mobile/ActionButtons";
import { Direction, DPadEventType } from "../mobile/VirtualDPad";
import { SkeletalPlayer3D } from "../three/SkeletalPlayer3D";
import { VolumeControl } from "../ui/VolumeControl";
import AnatomyControlsHTML from "./components/AnatomyControlsHTML";
import AnatomyOverlay3D, {
type AnatomyLayer,
} from "./components/AnatomyOverlay3D";
import HitFeedbackEffect3D from "./components/HitFeedbackEffect3D";
import TrainingArena3D from "./components/TrainingArena3D";
import TrainingControlsHTML from "./components/TrainingControlsHTML";
import type { DifficultyMode } from "./components/TrainingDummy3D";
import TrainingDummy3D from "./components/TrainingDummy3D";
import TrainingFeedbackHTML from "./components/TrainingFeedbackHTML";
import TrainingModeSelectorHTML from "./components/TrainingModeSelectorHTML";
import TrainingStatsHTML from "./components/TrainingStatsHTML";
import VitalPointTrainingHTML from "./components/VitalPointTrainingHTML";
import useTrainingActions from "./hooks/useTrainingActions";
import useTrainingState from "./hooks/useTrainingState";
/**
* AnimationUpdater - Component that updates player animation at 60fps
*
* @korean 훈련애니메이션업데이터 - 60fps로 플레이어 애니메이션을 업데이트하는 컴포넌트
*/
interface TrainingAnimationUpdaterProps {
readonly playerAnimation: ReturnType<typeof usePlayerAnimation>;
}
const TrainingAnimationUpdater: React.FC<TrainingAnimationUpdaterProps> = ({
playerAnimation,
}) => {
useFrame((_state, delta) => {
playerAnimation.update(delta);
});
return null;
};
/**
* Props for the TrainingScreen3D component
*/
export interface TrainingScreen3DProps {
/** Callback to update player state */
readonly onPlayerUpdate: (updates: Partial<PlayerState>) => void;
/** Callback when returning to menu */
readonly onReturnToMenu: () => void;
/** Canvas width in pixels. Defaults to 1200 */
readonly width?: number;
/** Canvas height in pixels. Defaults to 800 */
readonly height?: number;
}
/**
* TrainingScreen3D Component
* Three.js-based training screen with 3D dummy and Html UI
*
* Uses consolidated hooks for state management matching CombatScreen architecture.
*/
export const TrainingScreen3D: React.FC<TrainingScreen3DProps> = ({
onPlayerUpdate,
onReturnToMenu,
width = 1200,
height = 800,
}) => {
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 1: Core State Management (Hooks)
// ═══════════════════════════════════════════════════════════════════════════
// Content is always mounted/visible (no loading gate)
const isMounted = true;
// Consolidated training state management (matches useCombatState pattern)
const { state: trainingState, actions: trainingActions } = useTrainingState();
// Audio context
const audio = useAudio();
// Responsive detection and layout (matching CombatScreen pattern)
const { arenaBounds, isMobile } = useCombatLayout(width, height);
// Training difficulty and vital point configuration
const difficulty: DifficultyMode = "normal";
const vitalPointCount = 70; // Show all 70 vital points
// Vital point overlay state
const [overlayVisible, setOverlayVisible] = React.useState(false);
const [severityFilters, setSeverityFilters] = React.useState<
import("../../types/common").VitalPointSeverity[]
>([]);
const [regionFilter, setRegionFilter] =
React.useState<BodyRegionFilter>("all");
const [searchQuery, setSearchQuery] = React.useState("");
const [showLabels, setShowLabels] = React.useState(true);
const [animated, setAnimated] = React.useState(true);
const [scale, setScale] = React.useState(1.0);
// Keyboard shortcut for toggling overlay (V key)
React.useEffect(() => {
const handleKeyPress = (e: KeyboardEvent) => {
if (e.key === "v" || e.key === "V") {
setOverlayVisible((prev) => !prev);
audio.playSFX("menu_select");
}
};
window.addEventListener("keydown", handleKeyPress);
return () => window.removeEventListener("keydown", handleKeyPress);
}, [audio]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 2: WebGL Context Management
// ═══════════════════════════════════════════════════════════════════════════
// Track context loss for recovery
const contextLossCountRef = useRef(0);
// Handle WebGL context loss and restoration (for 3D scene only)
useWebGLContextLossHandler({
onContextLost: () => {
console.warn("⚠️ WebGL context lost in TrainingScreen");
contextLossCountRef.current += 1;
},
onContextRestored: () => {
console.log("✓ WebGL context restored in TrainingScreen");
},
autoRestore: true,
});
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 3: Movement & Position Management
// ═══════════════════════════════════════════════════════════════════════════
// Initial player position in pixel space (left side of arena, centered vertically)
// Matches CombatScreen pattern: positions are pixel-based, converted to 3D for rendering
const initialPosition = useMemo<Position>(
() => ({
x: arenaBounds.x + arenaBounds.width * 0.25, // 25% from left
y: arenaBounds.y + arenaBounds.height * 0.5, // Centered vertically
}),
[arenaBounds]
);
// Player movement with input system (using pixel-based bounds like CombatScreen)
const { playerPosition, isMoving } = usePlayerMovement({
enabled: true, // Always allow movement in training screen
bounds: arenaBounds,
onPositionChange: (newPosition: Position) => {
onPlayerUpdate({ position: newPosition });
},
initialPosition,
moveSpeed: 300,
});
// Convert 2D pixel position to 3D world coordinates (matching CombatScreen pattern)
const player3DPosition = useMemo<[number, number, number]>(() => {
const relX = (playerPosition.x - arenaBounds.x) / arenaBounds.width;
const relZ = (playerPosition.y - arenaBounds.y) / arenaBounds.height;
const x = relX * 16 - 8; // Map 0-1 to -8 to 8
const z = relZ * 8 - 4; // Map 0-1 to -4 to 4
return [x, 0, z];
}, [playerPosition, arenaBounds]);
// Dummy position (fixed in 3D space, right side of arena)
const dummyPosition = useMemo<[number, number, number]>(() => [5, 0, 0], []);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 4: Player Animation State Machine
// ═══════════════════════════════════════════════════════════════════════════
// Reference for pending attack (executed at animation frame 6)
const pendingAttackRef = useRef<{
accuracy: number;
vitalPoint: string;
} | null>(null);
// Forward ref for handleDummyHit (defined in actions hook)
const handleDummyHitRef = useRef<(vitalPointId: string) => boolean>(
() => false
);
// Player animation events (matches CombatScreen pattern)
const playerAnimationEvents = useMemo<AnimationEvents>(
() => ({
onFrame: (frame, state) => {
// Execute attack at midpoint of animation (frame 6 of 12)
if (state === "attack" && frame === 6 && pendingAttackRef.current) {
const attackData = pendingAttackRef.current;
pendingAttackRef.current = null;
// Execute dummy hit with stored vital point
handleDummyHitRef.current(attackData.vitalPoint);
}
},
onAnimationComplete: (state) => {
if (state === "stance_change") {
audio.playSFX("menu_select");
}
},
}),
[audio]
);
const playerAnimation = usePlayerAnimation({
events: playerAnimationEvents,
});
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 5: Training Actions (Hook-based)
// ═══════════════════════════════════════════════════════════════════════════
// Training actions hook (matches useCombatActions pattern)
const {
handleStartTraining,
handleStopTraining,
handleDummyHit,
handleDummyDefeated,
handleStanceChange,
handleAttack,
} = useTrainingActions({
state: trainingState,
actions: trainingActions,
playerPosition,
player3DPosition,
dummyPosition,
audio,
onPlayerUpdate: (updates) => {
onPlayerUpdate(updates);
},
playerAnimation: {
transitionTo: playerAnimation.transitionTo,
currentState: playerAnimation.currentState,
},
pendingAttackRef, // Share the ref with animation events
});
// Update the ref so animation events can call handleDummyHit
useEffect(() => {
handleDummyHitRef.current = handleDummyHit;
}, [handleDummyHit]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 6: Movement-Animation Synchronization
// ═══════════════════════════════════════════════════════════════════════════
// Sync movement with animation (matches CombatScreen pattern)
const prevIsMovingRef = useRef<boolean>(isMoving);
useEffect(() => {
Iif (prevIsMovingRef.current !== isMoving) {
if (isMoving) {
playerAnimation.transitionTo("walk");
} else if (playerAnimation.currentState === "walk") {
playerAnimation.transitionTo("idle");
}
prevIsMovingRef.current = isMoving;
}
}, [isMoving, playerAnimation]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 7: Training Player State (Visual Display)
// ═══════════════════════════════════════════════════════════════════════════
// Training player state for visualization
const trainingPlayerState = useMemo<PlayerState>(() => {
return {
id: "training-player",
name: { korean: "훈련생", english: "Trainee" },
archetype: PlayerArchetype.MUSA,
health: 100,
maxHealth: 100,
ki: 100,
maxKi: 100,
stamina: 100,
maxStamina: 100,
energy: 100,
maxEnergy: 100,
attackPower: 10,
defense: 10,
speed: 10,
technique: 10,
pain: 0,
consciousness: 100,
balance: 100,
momentum: 0,
currentStance: TRIGRAM_STANCES_ORDER[trainingState.currentStanceIndex],
combatState: CombatState.IDLE,
position: playerPosition,
isBlocking: false,
isStunned: false,
isCountering: false,
lastActionTime: 0,
recoveryTime: 0,
lastStanceChangeTime: 0,
statusEffects: [],
activeEffects: [],
vitalPoints: [],
totalDamageReceived: 0,
totalDamageDealt: 0,
hitsTaken: 0,
hitsLanded: trainingState.stats.hits,
perfectStrikes: trainingState.perfectStrikes,
vitalPointHits: 0,
misses: trainingState.stats.misses,
accuracy: trainingState.stats.accuracy,
comboCount: trainingState.stats.combo,
};
}, [playerPosition, trainingState]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 7B: Technique Selection System
// ═══════════════════════════════════════════════════════════════════════════
// Technique selection and execution for training
const techniqueSelection = useTechniqueSelection({
player: trainingPlayerState,
enabled: trainingState.isTraining,
onTechniqueExecute: useCallback(
(technique: Technique) => {
// Show technique usage feedback
trainingActions.setFeedback(
`${technique.name.korean} 사용! | Used ${technique.name.english}!`
);
// In training mode, do not deduct resources to allow continuous practice
// Resources are displayed for educational purposes only
// Execute attack with technique (visual feedback)
handleAttack();
},
[handleAttack, trainingActions]
),
});
// Convert cooldowns to Map for TechniqueBar
const cooldownsMap = useMemo(() => {
const map = new Map<string, number>();
techniqueSelection.activeCooldowns.forEach((cd) => {
map.set(cd.techniqueId, cd.remaining);
});
return map;
}, [techniqueSelection.activeCooldowns]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 8: Mobile Touch Controls
// ═══════════════════════════════════════════════════════════════════════════
// Reference for tracking active mobile movement key (prevents stuck keys)
const activeMobileKeyRef = useRef<string | null>(null);
// Enable mobile controls always in training (allow movement even before starting training)
const mobileControlsEnabled = isMobile;
// Mobile D-pad movement handler (matches CombatScreen implementation)
const handleMobileMove = useCallback(
(direction: Direction | null, eventType: DPadEventType) => {
// Map D-pad directions to movement keys (WASD)
const directionMap: Record<Direction, string> = {
up: "w",
"up-right": "w",
right: "d",
"down-right": "s",
down: "s",
"down-left": "s",
left: "a",
"up-left": "w",
};
if (eventType === "start" && direction) {
// Release previous key if different (prevents stuck keys)
if (
activeMobileKeyRef.current &&
activeMobileKeyRef.current !== directionMap[direction]
) {
const prevKey = activeMobileKeyRef.current;
window.dispatchEvent(
new KeyboardEvent("keyup", {
key: prevKey,
code: `Key${prevKey.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
}
// Press new key with proper keyboard event properties
const key = directionMap[direction];
activeMobileKeyRef.current = key;
window.dispatchEvent(
new KeyboardEvent("keydown", {
key,
code: `Key${key.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
} else if (eventType === "end") {
// Release active key when D-pad released
if (activeMobileKeyRef.current) {
const key = activeMobileKeyRef.current;
window.dispatchEvent(
new KeyboardEvent("keyup", {
key,
code: `Key${key.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
activeMobileKeyRef.current = null;
}
}
},
[]
);
// Mobile attack handler - uses the same handleAttack from training actions
const handleMobileAttack = useCallback(() => {
handleAttack();
}, [handleAttack]);
// Mobile block handler
const handleMobileBlock = useCallback(
(eventType: ButtonEventType) => {
if (eventType === "start") {
audio.playSFX("block");
}
},
[audio]
);
// Mobile gesture handler
const handleMobileGesture = useCallback(
(gesture: GestureEvent) => {
switch (gesture.type) {
case "swipe-right":
window.dispatchEvent(new KeyboardEvent("keydown", { key: "d" }));
break;
case "swipe-left":
window.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
break;
case "swipe-up":
if (trainingState.isTraining) {
window.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
}
break;
case "swipe-down":
trainingActions.resetDummy();
break;
case "two-finger-tap":
trainingActions.setTrainingMode(
trainingState.trainingMode === "vital_point"
? "basics"
: "vital_point"
);
audio.playSFX("menu_select");
break;
}
},
[trainingState, trainingActions, audio]
);
// Mobile stance change handler
const handleMobileStanceChange = useCallback(
(stanceIndex: number) => {
handleStanceChange(stanceIndex);
},
[handleStanceChange]
);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 9: Keyboard Input Handling
// ═══════════════════════════════════════════════════════════════════════════
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const key = event.key.toLowerCase();
// ESC key - return to menu
if (key === "escape") {
onReturnToMenu();
return;
}
// Handle stance changes (1-8) - always available for exploration
if (key >= "1" && key <= "8") {
const stanceIndex = parseInt(key) - 1;
handleStanceChange(stanceIndex);
event.preventDefault();
return;
}
// Handle attacks (Space key) - always available for exploration
if (key === " ") {
handleAttack();
event.preventDefault();
return;
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [onReturnToMenu, handleStanceChange, handleAttack]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 10: Audio Lifecycle Management
// ═══════════════════════════════════════════════════════════════════════════
useEffect(() => {
let audioStarted = false;
const startMusic = async () => {
try {
await audio.fadeIn("cyberpunk_fusion", 2000);
audioStarted = true;
} catch (err) {
console.warn("Failed to start training music:", err);
trainingActions.setFeedback(
"오디오 초기화 실패 | Audio initialization failed"
);
}
};
void startMusic();
return () => {
Eif (audioStarted) {
void audio
.fadeOut(2000)
.then(() => audio.stopMusic())
.catch((err) => console.warn("Failed to stop training music:", err));
}
};
}, [audio, trainingActions]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 11: Feedback & Session Timer Effects
// ═══════════════════════════════════════════════════════════════════════════
// Hide feedback after delay
useEffect(() => {
Iif (trainingState.showFeedback) {
const timer = setTimeout(() => trainingActions.hideFeedback(), 2000);
return () => clearTimeout(timer);
}
}, [trainingState.showFeedback, trainingActions]);
// Update session duration
useEffect(() => {
Eif (!trainingState.isTraining || !trainingState.sessionStartTime) return;
const interval = setInterval(() => {
trainingActions.updateSessionDuration(
Math.floor((Date.now() - (trainingState.sessionStartTime ?? 0)) / 1000)
);
}, 1000);
return () => clearInterval(interval);
}, [
trainingState.isTraining,
trainingState.sessionStartTime,
trainingActions,
]);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 12: Hit Effect Management
// ═══════════════════════════════════════════════════════════════════════════
const handleEffectComplete = useCallback(
(effectId: number) => {
trainingActions.removeHitEffect(effectId);
},
[trainingActions]
);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 13: Anatomy Layer Toggle
// ═══════════════════════════════════════════════════════════════════════════
const handleAnatomyLayerToggle = useCallback(
(layer: AnatomyLayer) => {
trainingActions.toggleAnatomyLayer(layer);
audio.playSFX("menu_click");
},
[trainingActions, audio]
);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 14: Camera Configuration
// ═══════════════════════════════════════════════════════════════════════════
const cameraConfig = useMemo(
() => ({
position: [0, 8, 12] as [number, number, number],
fov: 60,
}),
[]
);
// ═══════════════════════════════════════════════════════════════════════════
// SECTION 15: RENDER
// ═══════════════════════════════════════════════════════════════════════════
return (
<div
style={{
width: `${width}px`,
height: `${height}px`,
position: "relative",
}}
data-testid="training-screen-3d"
>
<Canvas
style={{ width, height }}
gl={{
antialias: true,
alpha: false,
powerPreference: "high-performance",
}}
dpr={[1, 2]}
shadows
onCreated={({ gl }) => {
gl.setClearColor(KOREAN_COLORS.UI_BACKGROUND_DARK, 1);
}}
camera={cameraConfig}
>
{/* Korean-themed lighting (오방색 - Five Cardinal Colors) */}
<ambientLight intensity={0.4} color={KOREAN_COLORS.PRIMARY_CYAN} />
{/* Main directional light - Center (황색/Yellow) */}
<directionalLight
position={[0, 10, 5]}
intensity={1}
color={KOREAN_COLORS.SECONDARY_YELLOW}
castShadow
shadow-mapSize={[2048, 2048]}
/>
{/* East (청색/Blue-Green) */}
<pointLight
position={[10, 5, 0]}
intensity={0.6}
color={KOREAN_COLORS.ACCENT_GREEN}
distance={20}
/>
{/* West (백색/White) */}
<pointLight
position={[-10, 5, 0]}
intensity={0.6}
color={KOREAN_COLORS.WHITE_SOLID}
distance={20}
/>
{/* South (적색/Red) */}
<pointLight
position={[0, 5, 10]}
intensity={0.5}
color={KOREAN_COLORS.ACCENT_RED}
distance={20}
/>
{/* North (흑색/Black) - dim for depth */}
<pointLight
position={[0, 5, -10]}
intensity={0.3}
color={KOREAN_COLORS.UI_BACKGROUND_MEDIUM}
distance={20}
/>
{/* Animation updater - updates player animation at 60fps */}
<TrainingAnimationUpdater playerAnimation={playerAnimation} />
{/* Training arena ground */}
<TrainingArena3D />
{/* Training dummy at fixed position */}
<TrainingDummy3D
position={dummyPosition}
selectedVitalPoint={trainingState.selectedVitalPoint}
isTraining={trainingState.isTraining}
health={trainingState.dummyHealth}
onVitalPointHit={handleDummyHit}
onDefeated={handleDummyDefeated}
difficulty={difficulty}
vitalPointCount={vitalPointCount}
isMobile={isMobile}
/>
{/* Anatomy overlay for educational visualization */}
{trainingState.visibleAnatomyLayers.length > 0 && (
<AnatomyOverlay3D
position={dummyPosition}
visibleLayers={trainingState.visibleAnatomyLayers}
opacity={0.6}
isMobile={isMobile}
/>
)}
{/* Vital Point Overlay - Show all 70 points on dummy */}
{overlayVisible && (
<VitalPointMarkers3D
position={dummyPosition}
visible={overlayVisible}
severityFilter={severityFilters}
regionFilter={regionFilter}
searchQuery={searchQuery}
showLabels={showLabels}
scale={scale}
animated={animated}
selectedPoint={trainingState.selectedVitalPoint}
onPointClick={(pointId) => {
trainingActions.setSelectedVitalPoint(pointId);
audio.playSFX("menu_select");
}}
/>
)}
{/* VitalPointOverlayControls - fixed screen position */}
{overlayVisible && (
<VitalPointOverlayControls
visible={overlayVisible}
onVisibleChange={setOverlayVisible}
severityFilters={severityFilters}
onSeverityFiltersChange={setSeverityFilters}
regionFilter={regionFilter}
onRegionFilterChange={setRegionFilter}
searchQuery={searchQuery}
onSearchQueryChange={setSearchQuery}
showLabels={showLabels}
onShowLabelsChange={setShowLabels}
animated={animated}
onAnimatedChange={setAnimated}
scale={scale}
onScaleChange={setScale}
screenPosition={{ top: "180px", left: "20px" }}
isMobile={isMobile}
/>
)}
{/* Player model */}
<SkeletalPlayer3D
{...convertPlayerStateToProps(
trainingPlayerState,
player3DPosition,
0, // rotation - facing right towards dummy
{
isMobile,
facing: "right",
// Enable facial expressions and eye tracking - 얼굴 표정 및 눈 추적 활성화
enableFacialExpressions: true,
enableEyeTracking: true,
opponentPosition: dummyPosition,
}
)}
currentAnimation={animationStateToPlayerAnimation(
playerAnimation.currentState
)}
/>
{/* Hit effects */}
{trainingState.hitEffects.map((effect) => (
<HitFeedbackEffect3D
key={effect.id}
position={effect.position}
type={effect.type}
damage={effect.damage}
visible={effect.visible}
onComplete={() => handleEffectComplete(effect.id)}
isMobile={isMobile}
/>
))}
{/* Html UI Overlays - only render when content is ready */}
<Html fullscreen>
<div
style={{
width: "100%",
height: "100%",
pointerEvents: "none",
position: "relative",
opacity: isMounted ? 1 : 0,
transition: "opacity 0.2s ease-out",
}}
>
{/* Top Left - Training Controls */}
<div
style={{
position: "absolute",
top: 20,
left: 20,
pointerEvents: "all",
}}
>
<TrainingControlsHTML
isTraining={trainingState.isTraining}
onStartTraining={handleStartTraining}
onStopTraining={handleStopTraining}
isMobile={isMobile}
/>
</div>
{/* Top Right - Training Stats (below VolumeControl) */}
<div
style={{
position: "absolute",
top: isMobile ? 90 : 120,
right: 20,
pointerEvents: "all",
display: "flex",
flexDirection: "column",
gap: "10px",
alignItems: "flex-end",
}}
>
<TrainingStatsHTML
stats={{
...trainingState.stats,
sessionDuration: trainingState.sessionDuration,
bestCombo: trainingState.bestCombo,
perfectStrikes: trainingState.perfectStrikes,
}}
isMobile={isMobile}
/>
</div>
{/* Bottom Left - Mode Selector and Anatomy Controls */}
<div
style={{
position: "absolute",
bottom: isMobile ? 100 : 110,
left: isMobile ? 10 : 20,
pointerEvents: "all",
display: "flex",
flexDirection: "column",
gap: "15px",
}}
>
<TrainingModeSelectorHTML
currentMode={trainingState.trainingMode}
onModeChange={trainingActions.setTrainingMode}
isMobile={isMobile}
/>
<AnatomyControlsHTML
visibleLayers={trainingState.visibleAnatomyLayers}
onLayerToggle={handleAnatomyLayerToggle}
isMobile={isMobile}
/>
</div>
{/* Bottom Right - Vital Point Panel */}
<div
style={{
position: "absolute",
bottom: isMobile ? 100 : 110,
right: isMobile ? 10 : 20,
pointerEvents: "all",
}}
>
<VitalPointTrainingHTML
selectedVitalPoint={trainingState.selectedVitalPoint}
onVitalPointSelect={trainingActions.setSelectedVitalPoint}
isMobile={isMobile}
/>
</div>
{/* Vital Point Overlay Hint - Top Center */}
{!overlayVisible && (
<div
style={{
position: "absolute",
top: isMobile ? 20 : 30,
left: "50%",
transform: "translateX(-50%)",
pointerEvents: "none",
padding: isMobile ? "8px 12px" : "10px 16px",
background: hexToRgbaString(
KOREAN_COLORS.UI_BACKGROUND_DARK,
0.9
),
border: `2px solid ${hexToRgbaString(
KOREAN_COLORS.PRIMARY_CYAN,
0.6
)}`,
borderRadius: "8px",
fontSize: isMobile ? "12px" : "14px",
fontFamily: FONT_FAMILY.KOREAN,
color: hexToRgbaString(KOREAN_COLORS.PRIMARY_CYAN, 1),
fontWeight: "bold",
textAlign: "center",
}}
>
<div>
💡 급소 오버레이 | Vital Point Overlay: Press{" "}
<span
style={{
color: hexToRgbaString(KOREAN_COLORS.ACCENT_GOLD, 1),
}}
>
V
</span>
</div>
</div>
)}
{/* Center - Feedback Message */}
{trainingState.showFeedback && (
<div
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
pointerEvents: "none",
}}
>
<TrainingFeedbackHTML
message={trainingState.feedback}
isMobile={isMobile}
/>
</div>
)}
{/* Technique Bar - Bottom Center (above menu button) - Always visible for training */}
<TechniqueBar
techniques={techniqueSelection.availableTechniques}
player={trainingPlayerState}
selectedIndex={techniqueSelection.selectedIndex}
cooldowns={cooldownsMap}
onTechniqueSelect={techniqueSelection.selectTechnique}
onTechniqueHover={(_tech) => {
// Could add additional hover effects here
}}
isMobile={isMobile}
screenWidth={width}
screenHeight={height}
/>
{/* Bottom Center - Return to Menu Button */}
<div
style={{
position: "absolute",
bottom: isMobile ? 25 : 35,
left: "50%",
transform: "translateX(-50%)",
pointerEvents: "all",
minHeight: "50px",
zIndex: 100,
}}
>
<style>
{`
.training-return-menu-btn {
background: ${hexToRgbaString(
KOREAN_COLORS.ACCENT_GOLD,
1
)};
border: none;
border-radius: 8px;
padding: ${isMobile ? "10px 16px" : "12px 24px"};
font-size: ${isMobile ? "14px" : "16px"};
font-weight: bold;
font-family: ${FONT_FAMILY.KOREAN};
color: ${hexToRgbaString(KOREAN_COLORS.KOREAN_BLACK, 1)};
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 0 10px ${hexToRgbaString(
KOREAN_COLORS.ACCENT_GOLD,
0.5
)};
min-height: 40px;
}
.training-return-menu-btn:hover {
transform: scale(1.05);
box-shadow: 0 0 20px ${hexToRgbaString(
KOREAN_COLORS.ACCENT_GOLD,
0.8
)};
}
`}
</style>
<button
onClick={onReturnToMenu}
onMouseEnter={() => audio.playSFX("menu_hover")}
className="training-return-menu-btn"
data-testid="return-to-menu-button"
aria-label="Return to main menu"
>
메뉴로 | Return to Menu
</button>
</div>
</div>
</Html>
{/* Mobile Touch Controls - Only shown on mobile devices */}
{isMobile && (
<>
<VirtualDPad
onMove={handleMobileMove}
disabled={!mobileControlsEnabled}
size={120}
bottom={20}
left={20}
opacity={0.8}
/>
<ActionButtons
onAttack={handleMobileAttack}
onBlock={handleMobileBlock}
disabled={!mobileControlsEnabled}
bottom={20}
right={20}
opacity={0.8}
/>
<StanceWheel
currentStance={trainingState.currentStanceIndex}
onStanceChange={handleMobileStanceChange}
expanded={trainingState.stanceWheelExpanded}
onToggle={trainingActions.toggleStanceWheel}
disabled={!mobileControlsEnabled}
opacity={0.8}
/>
<GestureRecognizer
onGesture={handleMobileGesture}
enabled={mobileControlsEnabled}
showFeedback={true}
minSwipeDistance={50}
/>
</>
)}
</Canvas>
{/* Volume Control - positioned outside Canvas to maintain AudioProvider context */}
<VolumeControl position="top-right" compact={isMobile} />
</div>
);
};
export default TrainingScreen3D;
|