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 | 6x 6x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 6x 6x 1x 1x 1x 1x 5x 6x 6x 6x 6x 6x 6x 6x 6x 18x 6x 6x 6x 18x 6x 6x | /**
* TrainingAICharacter3D - 3D character model for AI opponent in training
*
* Displays the AI opponent with stance-based materials and animations
*
* Performance optimizations:
* - Memoized geometries to prevent recreation on every render
* - Memoized materials for consistent shading
* - Minimal per-frame operations for 60fps target
* - Physics-based attack movement for realistic forward momentum
*/
import { useFrame } from "@react-three/fiber";
import React, { useEffect, useMemo, useRef } from "react";
import * as THREE from "three";
import { TrigramStance } from "../../../../types/common";
import { KOREAN_COLORS } from "../../../../types/constants";
import { AttackMovementPhysics } from "../../../../systems/physics";
import { AnimationType } from "../../../../systems/animation";
/**
* Props for TrainingAICharacter3D
*/
export interface TrainingAICharacter3DProps {
/** Position in 3D space */
readonly position: [number, number, number];
/** Current trigram stance */
readonly stance: TrigramStance;
/** Whether AI is currently attacking */
readonly isAttacking?: boolean;
/** Animation type for current attack (used for forward movement) */
readonly attackAnimationType?: AnimationType;
/** Health percentage (0-1) */
readonly healthPercent?: number;
}
/**
* Get color based on trigram stance
*/
function getStanceColor(stance: TrigramStance): number {
const stanceColors: Record<TrigramStance, number> = {
[TrigramStance.GEON]: KOREAN_COLORS.SECONDARY_YELLOW, // Heaven
[TrigramStance.TAE]: KOREAN_COLORS.ACCENT_BLUE, // Lake
[TrigramStance.LI]: KOREAN_COLORS.ACCENT_RED, // Fire
[TrigramStance.JIN]: KOREAN_COLORS.ACCENT_GOLD, // Thunder
[TrigramStance.SON]: KOREAN_COLORS.ACCENT_GREEN, // Wind
[TrigramStance.GAM]: KOREAN_COLORS.PRIMARY_CYAN, // Water
[TrigramStance.GAN]: KOREAN_COLORS.UI_BACKGROUND_LIGHT, // Mountain
[TrigramStance.GON]: KOREAN_COLORS.UI_BACKGROUND_MEDIUM, // Earth
};
return stanceColors[stance] ?? KOREAN_COLORS.PRIMARY_CYAN;
}
/**
* TrainingAICharacter3D Component
* Renders the AI opponent with stance-based visual effects and attack movement
*/
export const TrainingAICharacter3D: React.FC<TrainingAICharacter3DProps> = ({
position,
stance,
isAttacking = false,
attackAnimationType,
healthPercent = 1.0,
}) => {
const groupRef = useRef<THREE.Group>(null);
const stanceAuraRef = useRef<THREE.Mesh>(null);
// Attack movement physics
const attackPhysics = useMemo(() => new AttackMovementPhysics(), []);
const attackStartTimeRef = useRef<number | null>(null);
const originalPositionRef = useRef<THREE.Vector3 | null>(null);
const attackMovementResultRef = useRef<ReturnType<
typeof attackPhysics.calculateAttackMovement
> | null>(null);
// Track attack state changes
const wasAttackingRef = useRef(false);
// Initialize original position ref
useEffect(() => {
originalPositionRef.current ??= new THREE.Vector3(...position);
}, [position]);
// Keep original position synced with external position while not attacking
useEffect(() => {
if (!isAttacking && originalPositionRef.current) {
originalPositionRef.current.set(...position);
}
}, [position, isAttacking]);
// Reset attack movement when attack starts
useEffect(() => {
if (isAttacking && !wasAttackingRef.current) {
// Attack just started - initialize movement
attackStartTimeRef.current = performance.now() / 1000;
Eif (originalPositionRef.current) {
originalPositionRef.current.set(...position);
}
// Calculate attack movement if we have animation type
Iif (attackAnimationType) {
const direction = new THREE.Vector3(0, 0, -1); // Forward toward player
attackMovementResultRef.current = attackPhysics.calculateAttackMovement(
{
animationType: attackAnimationType,
currentStance: stance,
direction,
animationDuration: 0.4, // Default 400ms animation
}
);
}
} else if (I!isAttacking && wasAttackingRef.current) {
// Attack ended - clean up
attackStartTimeRef.current = null;
attackMovementResultRef.current = null;
}
wasAttackingRef.current = isAttacking;
}, [isAttacking, attackAnimationType, stance, position, attackPhysics]);
// Memoize stance color
const stanceColor = useMemo(() => getStanceColor(stance), [stance]);
// Memoize geometries to prevent recreation on every render
// Performance: Avoids WebGL context exhaustion and reduces memory allocations
// Note: Health ring geometry is not memoized as it requires dynamic args based on healthPercent
const geometries = useMemo(
() => ({
body: new THREE.CapsuleGeometry(0.4, 1.2, 16, 32),
head: new THREE.SphereGeometry(0.3, 16, 16),
aura: new THREE.RingGeometry(0.6, 0.8, 32),
}),
[]
);
// Memoize materials for consistent shading
// Materials are recreated when stance changes for proper color updates
const materials = useMemo(
() => ({
body: new THREE.MeshStandardMaterial({
color: stanceColor,
emissive: stanceColor,
emissiveIntensity: isAttacking ? 0.6 : 0.2,
metalness: 0.4,
roughness: 0.6,
}),
head: new THREE.MeshStandardMaterial({
color: KOREAN_COLORS.ACCENT_GOLD,
metalness: 0.5,
roughness: 0.5,
}),
aura: new THREE.MeshBasicMaterial({
color: stanceColor,
transparent: true,
opacity: 0.4,
side: THREE.DoubleSide,
}),
}),
[stanceColor, isAttacking]
);
// Cleanup geometries on unmount only (geometries are stable)
// Dependencies intentionally omitted to prevent premature disposal
useEffect(() => {
return () => {
Object.values(geometries).forEach((geom) => geom.dispose());
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Cleanup old materials when new ones are created
// This prevents memory leaks when stance or attacking state changes
useEffect(() => {
const currentMaterials = materials;
return () => {
Object.values(currentMaterials).forEach((mat) => mat.dispose());
};
}, [materials]);
// Animation loop
useFrame((state) => {
if (!groupRef.current || !stanceAuraRef.current) return;
const time = state.clock.elapsedTime;
// Breathing animation
// NOTE: This per-character animation is acceptable for training mode (single AI opponent).
// If planning to display multiple AI characters simultaneously (e.g., multiplayer),
// batch breathing animations using InstancedMesh or limit animation to active combat participants only.
// 한 명의 AI 상대만 표시되는 훈련 모드에서는 성능 문제가 없으나,
// 다수의 AI가 동시에 표시되는 경우에는 InstancedMesh 또는 배치 애니메이션으로 최적화 필요.
const breathScale = Math.sin(time * 2) * 0.02 + 1;
groupRef.current.scale.y = breathScale;
// Stance aura pulsing
const auraPulse = Math.sin(time * 3) * 0.1 + 0.9;
stanceAuraRef.current.scale.setScalar(auraPulse);
// Physics-based attack movement
if (
isAttacking &&
attackStartTimeRef.current !== null &&
attackMovementResultRef.current &&
originalPositionRef.current
) {
const currentTime = performance.now() / 1000;
const elapsedTime = currentTime - attackStartTimeRef.current;
const result = attackMovementResultRef.current;
// Determine if in lunge or recovery phase
const isRecoveryPhase =
elapsedTime >= result.lungeDuration &&
elapsedTime < result.totalDuration;
const isInAttackMovement = elapsedTime < result.totalDuration;
if (isInAttackMovement) {
// Apply attack movement physics
const newPosition = attackPhysics.applyAttackMovement(
originalPositionRef.current,
result,
elapsedTime,
isRecoveryPhase
);
// Update group position
groupRef.current.position.copy(newPosition);
} else {
// Attack movement complete - return to original position
groupRef.current.position.copy(originalPositionRef.current);
}
} else if (!isAttacking && originalPositionRef.current) {
// Not attacking - stay at base position
groupRef.current.position.copy(originalPositionRef.current);
}
});
return (
<group
ref={groupRef}
name="training-ai-character-3d"
>
{/* Main body - capsule representing the AI fighter */}
<mesh castShadow receiveShadow>
<primitive object={geometries.body} attach="geometry" />
<primitive object={materials.body} attach="material" />
</mesh>
{/* Head marker */}
<mesh position={[0, 1.2, 0]} castShadow>
<primitive object={geometries.head} attach="geometry" />
<primitive object={materials.head} attach="material" />
</mesh>
{/* Stance aura effect */}
<mesh ref={stanceAuraRef} position={[0, 0, 0]}>
<primitive object={geometries.aura} attach="geometry" />
<primitive object={materials.aura} attach="material" />
</mesh>
{/* Health indicator (rings around character) */}
{healthPercent < 1.0 && (
<mesh position={[0, 2, 0]} rotation={[Math.PI / 2, 0, 0]}>
<ringGeometry
args={[0.4, 0.5, 32, 1, 0, Math.PI * 2 * healthPercent]}
/>
<meshBasicMaterial
color={
healthPercent > 0.6
? KOREAN_COLORS.ACCENT_GREEN
: healthPercent > 0.3
? KOREAN_COLORS.SECONDARY_YELLOW
: KOREAN_COLORS.ACCENT_RED
}
transparent
opacity={0.8}
side={THREE.DoubleSide}
/>
</mesh>
)}
{/* Attack effect */}
{isAttacking && (
<pointLight
position={[0, 0.6, 0.5]}
intensity={1.5}
distance={3}
color={stanceColor}
decay={2}
/>
)}
</group>
);
};
export default TrainingAICharacter3D;
|