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 | 1x 1x 1x | /**
* ImpactSparks3D - High-energy spark particle effects for critical hits
*
* Creates radial burst of golden/cyan spark particles that explode outward
* from impact points. Uses additive blending for glowing Korean cyberpunk aesthetic.
*
* PERFORMANCE OPTIMIZATION (Object Pooling):
* - Reduced allocations from ~50-100 per effect to 2 pooled objects
* - Pooling strategy:
* 1. Temporary Vector3 objects for calculation use pool
* 2. Owned objects (particle positions, velocities) are cloned from pooled objects
* 3. All pooled objects released after particle generation
* - Estimated reduction:
* - Normal hits: 50 Vector3 * 2 = 100 allocations → 2 pooled objects
* - Critical hits: 100 Vector3 * 2 = 200 allocations → 2 pooled objects
*
* Features:
* - Radial explosion pattern
* - Additive blending for glow effect
* - Korean gold/cyan color theming
* - Gravity-based physics
* - Critical hit intensity scaling
* - Mobile performance optimization
*
* @module components/combat/ImpactSparks3D
* @category Combat Effects
* @korean 충격불꽃3D
*/
import { Points, PointMaterial } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import React, { useRef, useMemo, useEffect } from "react";
import * as THREE from "three";
import { KOREAN_COLORS } from "../../../../../types/constants";
import { ThreeObjectPools } from "../../../../../utils/threeObjectPool";
/**
* Impact spark effect data
*/
export interface ImpactSparkEffect {
/** Unique identifier */
readonly id: string;
/** Impact position in 3D world space */
readonly position: [number, number, number];
/** Whether this is a critical hit (more particles, gold color) */
readonly isCritical: boolean;
/** Timestamp when effect was created */
readonly startTime: number;
/** Optional intensity multiplier (0.0 to 1.0) */
readonly intensity?: number;
}
/**
* Props for ImpactSparks3D component
*/
export interface ImpactSparks3DProps {
/** Active spark effects to render */
readonly effects: readonly ImpactSparkEffect[];
/** Whether to enable spark effects */
readonly enabled?: boolean;
/** Mobile device mode (reduced particle count) */
readonly isMobile?: boolean;
/** Callback when effect completes */
readonly onEffectComplete?: (effectId: string) => void;
}
/**
* Individual spark particle
*/
interface SparkParticle {
position: THREE.Vector3;
velocity: THREE.Vector3;
age: number;
lifetime: number;
/** Flag to track if vectors are pooled and need release */
isPooled: boolean;
}
/**
* Performance and physics constants
*/
const SPARK_CONSTANTS = {
/** Gravity acceleration for sparks (m/s²) */
GRAVITY: -9.8,
/** Base particle count for normal hits */
PARTICLES_NORMAL_DESKTOP: 50,
PARTICLES_NORMAL_MOBILE: 25,
/** Critical hit particle count */
PARTICLES_CRITICAL_DESKTOP: 100,
PARTICLES_CRITICAL_MOBILE: 50,
/** Particle lifetime in seconds */
LIFETIME: 1.5,
/** Initial velocity range (m/s) */
VELOCITY_MIN: 3.0,
VELOCITY_MAX: 6.0,
/** Particle size */
SIZE_NORMAL: 0.08,
SIZE_CRITICAL: 0.12,
/** Maximum delta time for physics stability */
MAX_DELTA: 1 / 30,
} as const;
/**
* Generate spark particles in radial explosion pattern
*
* PERFORMANCE: Uses ThreeObjectPools to eliminate ALL Vector3 allocations
* - 2 pooled Vector3 objects for temp calculations (released)
* - Particles acquire pooled Vector3 for position/velocity (released on expiration)
*
* Memory Impact:
* - Before: 50-100 particles × 2 Vector3 = 100-200 allocations per effect
* - After: 2 temp vectors (reused) + particles use pooled vectors (released)
* - Reduction: ~99% fewer allocations
*/
const generateSparkParticles = (
effect: ImpactSparkEffect,
particleCount: number
): SparkParticle[] => {
const particles: SparkParticle[] = [];
const intensity = effect.intensity ?? 1.0;
// Pooled objects for calculations - PERFORMANCE: Eliminates temp allocations
const tempOrigin = ThreeObjectPools.vector3.acquire();
const tempDirection = ThreeObjectPools.vector3.acquire();
try {
tempOrigin.set(...effect.position);
for (let i = 0; i < particleCount; i++) {
// Radial explosion pattern
const angle = (Math.PI * 2 * i) / particleCount;
const elevation = (Math.random() - 0.3) * Math.PI * 0.4; // Slightly upward bias
// Calculate direction
const horizontalSpeed = Math.cos(elevation);
tempDirection.set(
Math.cos(angle) * horizontalSpeed,
Math.sin(elevation),
Math.sin(angle) * horizontalSpeed
);
// Random speed with intensity scaling
const speed =
(SPARK_CONSTANTS.VELOCITY_MIN +
Math.random() *
(SPARK_CONSTANTS.VELOCITY_MAX - SPARK_CONSTANTS.VELOCITY_MIN)) *
intensity;
// CRITICAL: Acquire pooled vectors for particle ownership
const particlePosition = ThreeObjectPools.vector3.acquire();
const particleVelocity = ThreeObjectPools.vector3.acquire();
particlePosition.copy(tempOrigin);
particleVelocity.copy(tempDirection).multiplyScalar(speed);
particles.push({
position: particlePosition,
velocity: particleVelocity,
age: 0,
lifetime: SPARK_CONSTANTS.LIFETIME,
isPooled: true, // Mark for cleanup
});
}
return particles;
} finally {
// Release all pooled temp objects back to pool
ThreeObjectPools.vector3.release(tempOrigin);
ThreeObjectPools.vector3.release(tempDirection);
}
};
/**
* ImpactSparks3D Component
*
* Renders high-energy spark effects for combat impacts using radial particle bursts.
* Critical hits use Korean gold color with more particles for enhanced visual feedback.
*
* @example
* ```tsx
* const [sparkEffects, setSparkEffects] = useState<ImpactSparkEffect[]>([]);
*
* // On critical hit
* const handleCriticalHit = (position: [number, number, number]) => {
* setSparkEffects([...sparkEffects, {
* id: generateId(),
* position,
* isCritical: true,
* intensity: 1.0,
* startTime: Date.now(),
* }]);
* };
*
* <ImpactSparks3D
* effects={sparkEffects}
* enabled={true}
* isMobile={isMobile}
* onEffectComplete={(id) => {
* setSparkEffects(prev => prev.filter(e => e.id !== id));
* }}
* />
* ```
*/
export const ImpactSparks3D: React.FC<ImpactSparks3DProps> = ({
effects,
enabled = true,
isMobile = false,
onEffectComplete,
}) => {
// Particle system state
const particlesRef = useRef<Map<string, SparkParticle[]>>(new Map());
const pointsRef = useRef<THREE.Points>(null);
const completedEffectsRef = useRef<Set<string>>(new Set());
// Calculate max particles needed
const maxParticles = useMemo(() => {
return isMobile
? SPARK_CONSTANTS.PARTICLES_CRITICAL_MOBILE
: SPARK_CONSTANTS.PARTICLES_CRITICAL_DESKTOP;
}, [isMobile]);
// Spark color - gold for critical, cyan for normal
const sparkColor = useMemo(
() => ({
critical: KOREAN_COLORS.ACCENT_GOLD,
normal: KOREAN_COLORS.PRIMARY_CYAN,
}),
[]
);
// Initialize particles for new effects
useEffect(() => {
if (!enabled) return;
// Performance configuration - moved inside useEffect to avoid dependency issues
const getParticleCount = (effect: ImpactSparkEffect): number => {
if (effect.isCritical) {
return isMobile
? SPARK_CONSTANTS.PARTICLES_CRITICAL_MOBILE
: SPARK_CONSTANTS.PARTICLES_CRITICAL_DESKTOP;
}
return isMobile
? SPARK_CONSTANTS.PARTICLES_NORMAL_MOBILE
: SPARK_CONSTANTS.PARTICLES_NORMAL_DESKTOP;
};
effects.forEach((effect) => {
if (!particlesRef.current.has(effect.id)) {
const particleCount = getParticleCount(effect);
const particles = generateSparkParticles(effect, particleCount);
particlesRef.current.set(effect.id, particles);
}
});
// Clean up removed effects - Release pooled vectors!
const effectIds = new Set(effects.map((e) => e.id));
particlesRef.current.forEach((particles, id) => {
if (!effectIds.has(id)) {
// Release all pooled vectors for this effect
particles.forEach((p) => {
if (p.isPooled) {
ThreeObjectPools.vector3.release(p.position);
ThreeObjectPools.vector3.release(p.velocity);
p.isPooled = false;
}
});
particlesRef.current.delete(id);
completedEffectsRef.current.delete(id);
}
});
}, [effects, enabled, isMobile]);
// Cleanup on unmount - Release ALL pooled vectors
useEffect(() => {
// Capture refs at the start of effect to avoid stale closures
const currentParticles = particlesRef.current;
const currentCompletedEffects = completedEffectsRef.current;
return () => {
// Release all particle vectors
currentParticles.forEach((particles) => {
particles.forEach((p) => {
if (p.isPooled) {
ThreeObjectPools.vector3.release(p.position);
ThreeObjectPools.vector3.release(p.velocity);
p.isPooled = false;
}
});
});
// Clear refs
currentParticles.clear();
currentCompletedEffects.clear();
};
}, []);
// Initial positions for buffer (updated in useFrame)
const initialPositions = useMemo(() => {
const positions = new Float32Array(maxParticles * 3);
// Start with zeros - actual positions set in useFrame
return positions;
}, [maxParticles]);
// Physics update loop
useFrame((_, delta) => {
if (!enabled || !pointsRef.current) return;
const safeDelta = Math.min(delta, SPARK_CONSTANTS.MAX_DELTA);
let totalParticleIndex = 0;
const attr = pointsRef.current.geometry.attributes.position;
const posArray = attr.array as Float32Array;
// Update all active spark particles
particlesRef.current.forEach((particles, effectId) => {
let hasActiveParticles = false;
// Filter expired particles and release their pooled vectors
const aliveParticles: SparkParticle[] = [];
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
p.age += safeDelta;
if (p.age < p.lifetime) {
hasActiveParticles = true;
aliveParticles.push(p);
// Apply gravity
p.velocity.y += SPARK_CONSTANTS.GRAVITY * safeDelta;
// Update position
p.position.addScaledVector(p.velocity, safeDelta);
// Air resistance
p.velocity.multiplyScalar(0.98);
// Update render position
if (totalParticleIndex < posArray.length / 3) {
posArray[totalParticleIndex * 3] = p.position.x;
posArray[totalParticleIndex * 3 + 1] = p.position.y;
posArray[totalParticleIndex * 3 + 2] = p.position.z;
totalParticleIndex++;
}
} else {
// Release pooled vectors when particle expires
if (p.isPooled) {
ThreeObjectPools.vector3.release(p.position);
ThreeObjectPools.vector3.release(p.velocity);
p.isPooled = false;
}
}
}
// Update the particles array with only alive particles
particlesRef.current.set(effectId, aliveParticles);
// Check if effect is complete
if (!hasActiveParticles && !completedEffectsRef.current.has(effectId)) {
completedEffectsRef.current.add(effectId);
onEffectComplete?.(effectId);
}
});
attr.needsUpdate = true;
});
// Don't render if disabled or no effects
if (!enabled || effects.length === 0) {
return null;
}
// Determine color based on most recent effect
const latestEffect = effects[effects.length - 1];
const currentColor = latestEffect?.isCritical
? sparkColor.critical
: sparkColor.normal;
const currentSize = latestEffect?.isCritical
? SPARK_CONSTANTS.SIZE_CRITICAL
: SPARK_CONSTANTS.SIZE_NORMAL;
return (
<Points
ref={pointsRef}
positions={initialPositions}
data-testid="impact-sparks-3d"
>
<PointMaterial
color={currentColor}
size={currentSize}
sizeAttenuation
transparent
opacity={1.0}
depthWrite={false}
blending={THREE.AdditiveBlending} // Glowing effect for Korean cyberpunk aesthetic
/>
</Points>
);
};
export default ImpactSparks3D;
|