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

3.26% Statements 3/92
0% Branches 0/41
0% Functions 0/17
3.57% Lines 3/84

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                                                                                  1x                               1x                                 1x                                                                                                                                                                                                                                                                                                                                                                      
/**
 * TrainingHitEffects3D - Optimized particle effects using InstancedMesh
 *
 * Provides visual feedback for successful and missed strikes
 * Uses InstancedMesh for better performance with many particles
 */
 
import { useFrame } from "@react-three/fiber";
import React, { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { KOREAN_COLORS } from "../../../../types/constants";
import { ThreeObjectPools } from "../../../../utils/threeObjectPool";
 
/**
 * Props for TrainingHitEffects3D component
 */
export interface TrainingHitEffects3DProps {
  /** Position where the hit occurred */
  readonly position: [number, number, number];
  /** Type of hit effect */
  readonly type: "success" | "perfect" | "miss";
  /** Whether to show the effect */
  readonly visible: boolean;
  /** Callback when effect completes */
  readonly onComplete?: () => void;
}
 
/**
 * Single particle in the effect
 */
interface Particle {
  position: THREE.Vector3;
  velocity: THREE.Vector3;
  life: number;
  maxLife: number;
  size: number;
}
 
/**
 * Get color based on hit type
 */
const getEffectColor = (type: "success" | "perfect" | "miss"): number => {
  switch (type) {
    case "perfect":
      return KOREAN_COLORS.ACCENT_GOLD;
    case "success":
      return KOREAN_COLORS.PRIMARY_CYAN;
    case "miss":
      return KOREAN_COLORS.UI_GRAY;
    default:
      return KOREAN_COLORS.PRIMARY_CYAN;
  }
};
 
/**
 * Get particle count based on hit type
 */
const getParticleCount = (type: "success" | "perfect" | "miss"): number => {
  switch (type) {
    case "perfect":
      return 30;
    case "success":
      return 20;
    case "miss":
      return 10;
    default:
      return 15;
  }
};
 
/**
 * TrainingHitEffects3D Component
 * Optimized particle burst effect using InstancedMesh for better performance
 */
export const TrainingHitEffects3D: React.FC<TrainingHitEffects3DProps> = ({
  position,
  type,
  visible,
  onComplete,
}) => {
  const groupRef = useRef<THREE.Group>(null);
  const instancedMeshRef = useRef<THREE.InstancedMesh>(null);
  const particlesRef = useRef<Particle[]>([]);
  const [isActive, setIsActive] = useState(false);
  // Track particle count in state for render access
  const [hasParticles, setHasParticles] = useState(false);
  // Track if we've initialized for this visibility cycle
  const initializedRef = useRef(false);
 
  // Reusable objects to avoid allocations in animation loop
  const tempMatrix = useMemo(() => new THREE.Matrix4(), []);
  const tempVelocity = useMemo(() => new THREE.Vector3(), []);
  const tempColor = useMemo(() => new THREE.Color(), []);
  const tempScaleVector = useMemo(() => new THREE.Vector3(), []);
 
  const particleCount = useMemo(() => getParticleCount(type), [type]);
  const color = useMemo(() => new THREE.Color(getEffectColor(type)), [type]);
 
  // Initialize particles when effect becomes visible - use ref to track initialization
  // and avoid setState during effect
  useEffect(() => {
    if (visible && !initializedRef.current) {
      initializedRef.current = true;
 
      // Use pooled vector for velocity calculations to reduce allocations
      // Pool strategy: Acquire once, reuse for all particles, release
      const tempVel = ThreeObjectPools.vector3.acquire();
      
      try {
        particlesRef.current = Array.from({ length: particleCount }, () => {
          // Random direction in sphere
          const theta = Math.random() * Math.PI * 2;
          const phi = Math.acos(2 * Math.random() - 1);
          const speed = type === "perfect" ? 5 : type === "success" ? 3 : 2;
 
          // Calculate velocity using pooled vector
          tempVel.set(
            Math.sin(phi) * Math.cos(theta),
            Math.sin(phi) * Math.sin(theta),
            Math.cos(phi)
          );
          tempVel.normalize().multiplyScalar(speed);
 
          return {
            position: new THREE.Vector3(0, 0, 0),
            velocity: tempVel.clone(), // Clone for storage - particle owns this vector
            life: 1.0,
            maxLife: 1.0,
            size: type === "perfect" ? 0.15 : 0.1,
          };
        });
        setHasParticles(particlesRef.current.length > 0);
      } finally {
        // Always release pooled vector
        ThreeObjectPools.vector3.release(tempVel);
      }
    }
    // Reset initialization tracking when visibility changes to false
    if (!visible) {
      initializedRef.current = false;
    }
  }, [visible, type, particleCount]);
 
  // Animate particles
  useFrame((_, delta) => {
    const mesh = instancedMeshRef.current;
    if (!isActive || !mesh || particlesRef.current.length === 0) return;
 
    let allDead = true;
 
    particlesRef.current.forEach((particle, index) => {
      if (particle.life > 0) {
        allDead = false;
 
        // Update position using temp vector to avoid allocation
        tempVelocity.copy(particle.velocity).multiplyScalar(delta);
        particle.position.add(tempVelocity);
 
        // Apply gravity
        particle.velocity.y -= 9.8 * delta;
 
        // Decay life
        particle.life -= delta * 1.5;
 
        // Update instance matrix
        const opacity = Math.max(0, particle.life / particle.maxLife);
        const scale = particle.size * (0.5 + opacity * 0.5);
 
        tempMatrix.identity();
        tempMatrix.setPosition(particle.position);
        tempScaleVector.set(scale, scale, scale);
        tempMatrix.scale(tempScaleVector);
        mesh.setMatrixAt(index, tempMatrix);
 
        // Update color with opacity
        tempColor.copy(color);
        mesh.setColorAt(index, tempColor);
      } else {
        // Hide dead particles by scaling to 0
        tempMatrix.identity();
        tempScaleVector.set(0, 0, 0);
        tempMatrix.scale(tempScaleVector);
        mesh.setMatrixAt(index, tempMatrix);
      }
    });
 
    // Mark instances as needing update
    if (mesh.instanceMatrix) {
      mesh.instanceMatrix.needsUpdate = true;
    }
    if (mesh.instanceColor) {
      mesh.instanceColor.needsUpdate = true;
    }
 
    if (allDead) {
      setIsActive(false);
      particlesRef.current = [];
      setHasParticles(false);
      onComplete?.();
    }
  });
 
  // Shared geometry and material
  const geometry = useMemo(() => new THREE.SphereGeometry(1, 8, 8), []);
  const material = useMemo(
    () =>
      new THREE.MeshBasicMaterial({
        transparent: true,
        opacity: 0.9,
        depthWrite: false,
      }),
    []
  );
 
  // Cleanup
  useEffect(() => {
    return () => {
      geometry.dispose();
      material.dispose();
    };
  }, [geometry, material]);
 
  if (!isActive || !hasParticles) {
    return null;
  }
 
  return (
    <group ref={groupRef} position={position}>
      {/* InstancedMesh for all particles - single draw call */}
      <instancedMesh
        ref={instancedMeshRef}
        args={[geometry, material, particleCount]}
        frustumCulled={false}
      />
 
      {/* Central flash for perfect hits */}
      {type === "perfect" && (
        <mesh scale={2}>
          <sphereGeometry args={[0.3, 16, 16]} />
          <meshStandardMaterial
            color={KOREAN_COLORS.ACCENT_GOLD}
            transparent
            opacity={isActive ? 0.6 : 0}
            emissive={KOREAN_COLORS.ACCENT_GOLD}
            emissiveIntensity={2}
          />
        </mesh>
      )}
    </group>
  );
};
 
export default TrainingHitEffects3D;