๐ŸŽฎ Black Trigram (ํ‘๊ด˜)

May 24, 2026 ยท View on GitHub

Last Updated: 2026-04-21
Architecture Version: 2.1 (Production-Ready)
Product Version: 0.7.32
Status: Production-Ready (9.4/10) - Combat Realism 100% Complete (13/13 Systems)


๐Ÿ“š Architecture Documentation Map

DocumentFocusDescription
๐ŸŒ System ContextC4 ModelHigh-level view showing actors (Player, CDNs) and the entirely front-end application
๐Ÿข Container ViewC4 ModelFrontend-only architecture: UI Layer, Game Logic, Three.js Renderer, Animation System, State Management
๐Ÿงฉ Component ViewC4 ModelDetailed breakdown: Combat System, Trigram System (8 stances), Vital Point System (70 points), Skeletal Animation (28 bones)
๐Ÿ”ง File StructureOrganizationQ2 2026 project structure with systems/, components/, data/, types/ layout
๐Ÿ”„ Combat Flow SequenceSequence DiagramInput โ†’ Trigram โ†’ Vital Point โ†’ Damage โ†’ Three.js rendering with skeletal animation
๐ŸŽฌ Skeletal AnimationAnimation System28-bone hierarchy, 7 hand poses, muscle tension visualization
โšก Performance ArchitecturePerformanceThree.js optimization, 60fps targets, instancing, LOD, benchmarks
๐Ÿ“Š SWOT AnalysisStrategyQ2 2026 status: Strengths (70/70 vital points, 100% combat realism), Weaknesses (niche market), Opportunities, Threats
๐Ÿ“ˆ Game Status ReportCurrent ProgressComprehensive status (72.34% line coverage per docs/coverage/coverage-summary.json, 13/13 combat realism systems, 8/8 trigram stances)
๐Ÿ”ฎ Future ArchitectureRoadmapQ2 2026+ evolution: Combat realism completion, VR/AR integration, advanced features
๐ŸŽฏ Core Game ConceptsGame DesignPlayer archetypes (5), trigram system (8), resources & mechanics
๐Ÿ—๏ธ Architecture ConceptsTechnical DesignMindmap of system architecture layers and components
๐Ÿ”„ UX FlowUser ExperienceUser journey through screens and interactions
๐Ÿ”„ Combat MechanicsGame MechanicsDetailed combat system data flow and relationships

๐ŸŒ System Context

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','personBkg':'#1565C0','containerBkg':'#2979FF','componentBkg':'#4CAF50','person_bg':'#1565C0','container_bg':'#2979FF','component_bg':'#4CAF50'}}}%%
C4Context
    title System Context - Black Trigram (ํ‘๊ด˜) Web Application (v0.7.32)

    Person(player, "๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Martial Arts Student", "Learns Korean vital point targeting with 70 anatomical points and 28-bone skeletal animation")
    Person(instructor, "๐Ÿฅ‹ Martial Arts Instructor", "Uses for teaching traditional Korean techniques and I Ching philosophy")
    
    System(blackTrigram, "๐ŸŒ Black Trigram (ํ‘๊ด˜)", "Korean martial arts combat simulator with 70 vital points, 8 trigram stances, 28-bone skeletal animation, 60fps performance")
    
    System_Ext(cloudfront, "โš–๏ธ AWS CloudFront CDN", "Global content delivery with 400+ edge locations, DDoS protection")
    System_Ext(s3Storage, "๐Ÿ’พ AWS S3 Multi-Region", "Primary (us-east-1) + backup region storage with versioning")
    System_Ext(route53, "๐Ÿ“ก AWS Route53", "DNS with DNSSEC, health checks, automatic DR failover")
    System_Ext(ghPages, "๐Ÿ“„ GitHub Pages DR", "Disaster recovery hosting with independent infrastructure")
    System_Ext(culturalDB, "๐Ÿ›๏ธ Korean Cultural Database", "Authentic martial arts terminology, I Ching philosophy, TCM meridians")

    Rel(player, route53, "Resolves DNS", "DNS/DNSSEC")
    Rel(route53, cloudfront, "Primary route", "DNS")
    Rel(route53, ghPages, "DR failover", "DNS")
    Rel(player, blackTrigram, "Practices combat techniques", "HTTPS/TLS 1.3 via CloudFront CDN")
    Rel(instructor, blackTrigram, "Demonstrates vital points", "HTTPS/TLS 1.3 via CloudFront CDN")
    Rel(blackTrigram, culturalDB, "References authentic terminology", "HTTPS/JSON")

    UpdateLayoutConfig($c4ShapeInRow="2", $c4BoundaryInRow="1")

Legend (Q1 2026)

  • ๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Player: End-user interacting with Black Trigram through desktop (60fps) or mobile (30-45fps) browser.
  • ๐ŸŒ Black Trigram Web App: Entirely front-end, built with React 19 + Three.js (TypeScript). All game logic, state, skeletal animation, & 3D rendering occur in-browserโ€”no backend.
  • โš–๏ธ CloudFront CDN: AWS global CDN with 400+ edge locations, DDoS protection (AWS Shield Standard), TLS 1.3 encryption, and aggressive caching.
  • ๐Ÿ’พ S3 Multi-Region: Primary storage in us-east-1 with server-side encryption (SSE-S3), versioning, and multi-region replication for redundancy.
  • ๐Ÿ“ก Route53: AWS DNS service with DNSSEC, active health checks monitoring CloudFront, automatic failover to GitHub Pages DR.
  • ๐Ÿ“„ GitHub Pages DR: Independent disaster recovery infrastructure, activated automatically via Route53 health checks when AWS unavailable.
  • ๐Ÿฅ‹ Key Capabilities: 70 vital points with Korean names (100% complete), 8 trigram stances, 28-bone skeletal animation system, 7 hand poses, muscle tension visualization, 8 body part health tracking, 60fps desktop performance.

๐Ÿข Container View

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','personBkg':'#1565C0','containerBkg':'#2979FF','componentBkg':'#4CAF50','person_bg':'#1565C0','container_bg':'#2979FF','component_bg':'#4CAF50'}}}%%
C4Container
    title Container View - Black Trigram Performance Architecture (Q1 2026)

    Person(user, "๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ User", "Practices Korean martial arts")

    System_Boundary(browserApp, "๐ŸŒ Black Trigram Browser Application") {
        Container(ui, "๐Ÿ–ฅ๏ธ React UI Layer", "React 19 + TypeScript", "Korean-themed components, responsive design, Html overlays")
        Container(gameEngine, "โš™๏ธ Game Logic Engine", "TypeScript Modules", "Combat calculations, trigram system (8 stances), vital points (70)")
        Container(renderer, "๐ŸŽจ Three.js Renderer", "@react-three/fiber + drei", "60fps 3D graphics, skeletal animation (28 bones), particle systems")
        Container(audioEngine, "๐ŸŽต Audio Engine", "Web Audio API", "Damage-based sound feedback, Korean traditional + cyberpunk audio")
        Container(stateManager, "๐Ÿ—„๏ธ State Manager", "Zustand + React Context", "Combat state, player archetypes (5), trigram stances")
        Container(animationSystem, "๐ŸŽฌ Animation System", "Skeletal Animation + Hand Poses", "28-bone system, muscle tension, 70 vital point mapping")
        Container(perfMonitor, "๐Ÿ“ˆ Performance Monitor", "PerformanceOverlay3D", "60fps tracking, memory usage, optimization")
    }

    Rel(user, ui, "Interacts via input", "Touch/Mouse/Keyboard")
    Rel(ui, gameEngine, "Dispatches actions", "Function calls")
    Rel(gameEngine, renderer, "Updates visuals", "Three.js API")
    Rel(gameEngine, audioEngine, "Triggers sounds", "Web Audio API")
    Rel(gameEngine, stateManager, "Updates state", "Zustand actions")
    Rel(gameEngine, animationSystem, "Execute techniques", "Animation API")
    Rel(animationSystem, renderer, "Bone transforms", "Three.js Skeleton")
    Rel(perfMonitor, stateManager, "Reports metrics", "Performance data")

    UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")

Containers Overview

  • ๐Ÿ–ฅ๏ธ UI Layer:

    • React 19 + TypeScript functional components.
    • Screens: CombatScreen3D, TrainingScreen3D, IntroScreen3D, ControlsScreen3D, PhilosophyScreen3D.
    • Common UI: Html overlays from @react-three/drei for HUD elements, health bars, stance indicators.
    • Base modules: Korean-themed UI components with bilingual support (Korean | English).
    • CSS: App.css, component-specific styling for overlays.
  • โš™๏ธ Game Logic Layer:

    • Under src/systems/*, src/types/*, src/data/*.

    • CombatSystem (src/systems/CombatSystem.ts): Orchestrates input โ†’ trigram โ†’ vital-point โ†’ damage โ†’ audio/visual.

    • TrigramSystem (src/systems/trigram/*):

      • StanceManager.ts: Tracks current stance, validates Ki/Stamina, handles transition cost.
      • TransitionCalculator.ts: Computes validity of stance switches.
      • TrigramCalculator.ts: Provides technique data & advantage multipliers.
      • KoreanCulture.ts: Supplies I Ching lore, Korean labels/descriptions.
    • VitalPointSystem (src/systems/vitalpoint/*):

      • 70 vital points database with Korean names (๋ฐฑํšŒํ˜ˆ, ์ธ์˜, ๋ช…๋ฌธ, etc.)
      • Enhanced anatomical zones with polygon-based hit detection.
      • 5 severity levels (Lethal, Critical, Major, Moderate, Minor).
      • 7 anatomical categories (Neurological, Skeletal, Joint, Organ, Muscular, Vascular, Respiratory).
    • AudioManager (src/audio/*):

      • AudioAssetRegistry.ts, AudioManager.ts, AudioUtils.ts: Load & play SFX/music via Web Audio API.
      • Damage-based audio scaling (combat impact sounds scaled by effectiveness).
    • Animation System (src/systems/animation/*):

      • 28-bone skeletal system (PELVIS โ†’ SPINE (3) โ†’ NECK/HEAD (2) โ†’ ARMS (6 each) โ†’ LEGS (5 each)).
      • Hand pose system (fist_vertical, fist_horizontal, open_hand_knife, etc.).
      • Muscle tension visualization (0.0-1.0 mapped to bone visual intensity).
    • AI System (src/systems/ai/*): Tactical combat behaviors, archetype-specific AI.

  • ๐ŸŽจ Rendering Engine:

    • Three.js via @react-three/fiber (React renderer for Three.js).
    • Manages 3D scene with WebGL rendering via Canvas component.
    • Renders: Character 3D models with skeletal animation, environment, particles, and visual effects.
    • UI overlays via Html component from @react-three/drei for HUD, health bars, Ki meters, stance indicators.
    • Korean cyberpunk aesthetic with traditional ์˜ค๋ฐฉ์ƒ‰ (Five Directional Colors).
  • ๐ŸŽฌ Animation System:

    • 28-bone skeletal hierarchy (src/types/skeletal.ts).
    • Hand pose management (src/types/hand-animation.ts) for martial arts techniques.
    • Muscle activation visualization (src/types/muscle.ts) with tension mapping.
    • Technique animation (src/types/technique.ts) with keyframe interpolation.
  • ๐Ÿ—„๏ธ State Management:

    • In-browser only (no backend). Uses Zustand (or React Context fallback) under hooks.
    • Combat state: Health, stamina, Ki, current stance (8 trigrams), body part health (8 parts), consciousness levels.
    • Player archetypes: 5 distinct fighter types (๋ฌด์‚ฌ, ์•”์‚ด์ž, ํ•ด์ปค, ์ •๋ณด์š”์›, ์กฐ์งํญ๋ ฅ๋ฐฐ).
    • No Persistence: Refresh resets all state / progress.

๐Ÿงฉ Component View

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','personBkg':'#1565C0','containerBkg':'#2979FF','componentBkg':'#4CAF50','person_bg':'#1565C0','container_bg':'#2979FF','component_bg':'#4CAF50'}}}%%
C4Component
    title Combat System Components - Korean Martial Arts Engine (Q1 2026)

    Container_Boundary(combatSystem, "โš™๏ธ Combat System") {
        Component(combatController, "๐ŸฅŠ CombatController", "TypeScript", "Orchestrates combat interactions (CombatSystem.ts - 36KB)")
        Component(inputHandler, "๐ŸŽฎ InputHandler", "TypeScript", "Processes keyboard/mouse/touch input")
        Component(trigramEngine, "โ˜ฏ๏ธ TrigramEngine", "TypeScript", "Manages 8 trigram stances and transitions")
        Component(vitalPointEngine, "๐ŸŽฏ VitalPointEngine", "TypeScript", "70 vital points with polygon hit detection (<0.01ms)")
        Component(damageCalculator, "๐Ÿ’ฅ DamageCalculator", "TypeScript", "Base ร— trigram ร— vital point multipliers")
        Component(effectsProcessor, "โœจ EffectsProcessor", "TypeScript", "Visual and audio effect coordination")
        Component(animationSystem, "๐ŸŽฌ AnimationSystem", "TypeScript", "28-bone skeletal animation + hand poses")
        Component(bodyPartHealth, "๐Ÿฉน BodyPartHealth", "TypeScript", "8-part health tracking system")
        Component(painSystem, "๐Ÿ”ฅ PainResponseSystem", "TypeScript", "Pain accumulation and response (90% complete)")
        Component(consciousnessSystem, "๐Ÿ’ค ConsciousnessSystem", "TypeScript", "4-level consciousness degradation (90% complete)")
    }

    Container_Boundary(dataLayer, "๐Ÿ“Š Data Layer") {
        Component(koreanTerminology, "๐Ÿ‡ฐ๐Ÿ‡ท KoreanTerminology", "JSON/TypeScript", "Bilingual Korean-English terms")
        Component(anatomyData, "๐Ÿซ€ AnatomyData", "JSON/TypeScript", "70 vital points (5 severity, 7 categories, 14 meridians)")
        Component(trigramData, "๐Ÿ“Š TrigramData", "JSON/TypeScript", "8 I Ching trigrams + techniques")
        Component(audioAssets, "๐ŸŽต AudioAssets", "WebM/OGG", "Damage-scaled audio + Korean traditional")
        Component(archetypeData, "๐Ÿ‘ค ArchetypeData", "JSON/TypeScript", "5 player archetypes (๋ฌด์‚ฌ, ์•”์‚ด์ž, ํ•ด์ปค, ์ •๋ณด์š”์›, ์กฐ์งํญ๋ ฅ๋ฐฐ)")
        Component(skeletalData, "๐Ÿฆด SkeletalData", "TypeScript", "28-bone hierarchy + 7 hand poses + muscle tension")
    }

    Container_Boundary(rendering, "๐ŸŽจ Rendering Layer") {
        Component(threeScene, "โš”๏ธ ThreeScene", "Three.js", "3D combat scene with WebGL 2.0 where available (WebGL 1 fallback)")
        Component(particleSystem, "โœจ ParticleSystem", "Three.js Instances", "Ki energy, hit effects, impact particles (1000+)")
        Component(hudOverlay, "๐Ÿ“Š HUDOverlay", "Html (drei)", "Health bars, stance indicators, damage numbers, combo counter")
        Component(skeletalRenderer, "๐ŸŽญ SkeletalRenderer", "Three.js Skeleton", "28-bone character animation @ 60fps")
    }

    Rel(inputHandler, combatController, "Sends input events")
    Rel(combatController, trigramEngine, "Requests stance changes (8 stances)")
    Rel(combatController, vitalPointEngine, "Checks hit targets (70 points)")
    Rel(combatController, damageCalculator, "Calculates damage")
    Rel(combatController, bodyPartHealth, "Updates 8 body parts")
    Rel(combatController, painSystem, "Tracks pain accumulation")
    Rel(combatController, consciousnessSystem, "Manages consciousness levels")
    Rel(damageCalculator, effectsProcessor, "Triggers effects")
    Rel(effectsProcessor, animationSystem, "Execute technique animations")

    Rel(trigramEngine, trigramData, "Loads 8 stance data")
    Rel(vitalPointEngine, anatomyData, "References 70 vital points + meridians")
    Rel(combatController, koreanTerminology, "Gets Korean terms")
    Rel(effectsProcessor, audioAssets, "Plays damage-scaled sounds")
    Rel(animationSystem, skeletalData, "Loads bone hierarchy + hand poses")
    Rel(combatController, archetypeData, "Loads 5 archetype data")

    Rel(effectsProcessor, threeScene, "Updates 3D visuals")
    Rel(effectsProcessor, particleSystem, "Spawns particle effects")
    Rel(combatController, hudOverlay, "Updates HUD overlays")
    Rel(animationSystem, skeletalRenderer, "Updates bone transforms @ 60fps")

    UpdateLayoutConfig($c4ShapeInRow="4", $c4BoundaryInRow="1")

๐Ÿงฉ Component Implementation Status (Q2 2026)

Combat System (9.6/10 - Production-Ready)

  • Combat Realism: 13/13 systems complete (100%)
    • โœ… Body Part Health: 100% (8 parts tracked with Korean/English labels)
    • โœ… Vital Point Targeting: 100% (70/70 points with TCM meridian mapping)
    • โœ… Enhanced Anatomy: 95% (polygon-based detection, 13 zones, <0.01ms)
    • โœ… Visual Feedback: 97% (damage numbers, hit effects, combo counter, limb exposure)
    • โœ… Pain Response: 100% (production-ready with comprehensive tests)
    • โœ… Consciousness Levels: 100% (production-ready, 4-level gradation)
    • โœ… Breathing Disruption: 95% (full CombatSystem integration with UI)
    • โœ… Trauma Visualization: 90% (per-player injury tracking)
    • โœ… Balance/Vulnerability: 70% (transitions refined)
    • โœ… Combat Readiness HUD: 85% (EndScreen integration complete)
    • โœ… Injury-Based Movement: 60% (dynamic speed modifiers)
    • โœ… Bone Impact Audio: 80% (anatomical region detection)
    • โœ… Grappling System: 95% (4 animation states, visual feedback, audio hooks)
    • โœ… Limb Exposure/Counter-Attacks: 100% (AI integration, visual indicators, 132 tests)

Vital Point System (9.5/10 - Excellent)

  • 70/70 vital points with Korean names (100% complete)
  • 4 regions: Head (12), Torso (24), Arms (17), Legs (17)
  • 5 severity levels: Lethal (4), Critical (18), Major (28), Moderate (16), Minor (4)
  • 7 categories: Neurological (22), Skeletal (15), Joint (12), Organ (9), Muscular (7), Vascular (3), Respiratory (2)
  • 14 TCM Meridians mapped to vital points
  • 127 Medical References cited
  • Visual overlay controls with filtering (severity, region, search)
  • Comprehensive documentation in docs/vital-points/

Trigram System (10/10 - Complete)

  • 8/8 stances fully functional with I Ching philosophy
  • Korean cultural integration: โ˜ฐ ๊ฑด Geon, โ˜ฑ ํƒœ Tae, โ˜ฒ ๋ฆฌ Li, โ˜ณ ์ง„ Jin, โ˜ด ์† Son, โ˜ต ๊ฐ Gam, โ˜ถ ๊ฐ„ Gan, โ˜ท ๊ณค Gon
  • Stance-specific techniques with trigram advantage matrix
  • Transition cost calculation (Ki/Stamina)

Skeletal Animation System (8.5/10 - Production-Ready, Q1 2026)

  • 28-bone hierarchy with realistic human proportions
    • Core: PELVIS (root)
    • Spine: SPINE_LOWER, SPINE_MIDDLE, SPINE_UPPER (3 bones)
    • Head: NECK, HEAD (2 bones)
    • Arms: SHOULDER, UPPER_ARM, ELBOW, FOREARM, WRIST, HAND (6 bones each ร— 2 = 12 bones)
    • Legs: HIP, THIGH, KNEE, SHIN, FOOT (5 bones each ร— 2 = 10 bones)
  • 7 hand poses for martial arts techniques
    • fist_vertical (์ˆ˜์ง์ฃผ๋จน) - Vertical punch
    • fist_horizontal (์ˆ˜ํ‰์ฃผ๋จน) - Horizontal punch
    • open_hand_knife (์ˆ˜๋„) - Knife hand strike
    • spear_hand (๊ด€์ˆ˜) - Spear hand
    • grasping (์žก๊ธฐ) - Grappling
    • open_palm (ํŽด๊ธฐ) - Palm strike
    • relaxed (ํœด์‹) - Neutral/rest
  • Muscle tension visualization (0.0-1.0 intensity mapping to bone visual intensity)
  • Technique animation with keyframe interpolation for smooth 60fps playback
  • Located in src/systems/animation/, src/types/skeletal.ts, src/types/hand-animation.ts, src/types/muscle.ts

Player Archetypes (10/10 - Complete)

  • 5/5 archetypes balanced with distinct combat styles:
    • ๋ฌด์‚ฌ (Musa) - Traditional Warrior: Honor-bound, balanced techniques
    • ์•”์‚ด์ž (Amsalja) - Shadow Assassin: Precision strikes, critical damage focus
    • ํ•ด์ปค (Hacker) - Cyber Warrior: Tech-enhanced, digital disruption
    • ์ •๋ณด์š”์› (Jeongbo Yowon) - Intelligence Operative: Analytical, tactical advantage
    • ์กฐ์งํญ๋ ฅ๋ฐฐ (Jojik Pokryeokbae) - Organized Crime: Brutal efficiency, overwhelming force

Enhanced Icon Categories

๐Ÿ–ฅ๏ธ UI Layer Icons

  • ๐Ÿ“ฑ App - Mobile-first application root
  • ๐Ÿฎ IntroScreen - Traditional Korean lantern for welcome
  • โš”๏ธ CombatScreen - Crossed swords for combat
  • ๐ŸŽฏ TrainingScreen - Target for practice mode
  • ๐ŸŽฎ GameUI - Game controller for interface
  • ๐Ÿ“Š CombatHUD - Chart/dashboard for HUD
  • โ˜ฏ๏ธ TrigramWheel - Yin-yang for Korean philosophy
  • ๐Ÿ EndScreen - Checkered flag for completion
  • ๐Ÿ”˜ BaseButton - Button for reusable component
  • ๐Ÿ‡ฐ๐Ÿ‡ท KoreanText - Korean flag for Korean text
  • โš BackgroundGrid - Grid pattern for overlay

โš™๏ธ Game Logic Icons

  • ๐ŸฅŠ CombatSystem - Boxing glove for combat orchestration
  • ๐Ÿ”ถ TrigramSystem - Diamond for trigram system
  • ๐Ÿฅ‹ StanceManager - Martial arts uniform for stance
  • ๐Ÿ”„ TransitionCalculator - Refresh for transitions
  • ๐Ÿงฎ TrigramCalculator - Abacus for calculations
  • ๐Ÿ›๏ธ KoreanCulture - Classical building for culture
  • ๐ŸŽฏ VitalPointSystem - Bullseye for targeting
  • ๐Ÿซ€ AnatomicalRegions - Heart for anatomy
  • ๐Ÿ’ฅ HitDetection - Explosion for collision
  • ๐Ÿฉธ DamageCalculator - Blood drop for damage
  • ๐ŸŽต AudioManager - Musical note for audio
  • ๐ŸŽน DefaultSoundGenerator - Piano for sound generation
  • ๐ŸŽฒ VariantSelector - Dice for randomization

๐Ÿ“ฆ Asset Loader Icons

  • ๐Ÿ–ผ๏ธ TextureLoader - Framed picture for textures
  • ๐ŸŽง AudioLoader - Headphones for audio assets
  • ๐Ÿ“‹ TrigramDataLoader - Clipboard for data
  • ๐Ÿงฌ VitalPointsDataLoader - DNA for anatomical data

๐Ÿ—„๏ธ State Management Icons

  • ๐ŸŽฎ useGameState - Game controller for game state
  • ๐Ÿ–ฑ๏ธ useUIState - Computer mouse for UI state
  • ๐Ÿ‘น useEnemyState - Ogre for enemy state

๐ŸŽจ Rendering Engine Icons

  • ๐ŸŽญ ThreeScene - Theater masks for 3D scene
  • ๐Ÿ‘ค PlayerVisuals - Bust silhouette for player
  • ๐Ÿ‘บ EnemyVisuals - Goblin for enemy
  • โœจ ParticlesLayer - Sparkles for effects
  • ๐ŸŒ… DojangBackground - Sunrise for environment

๐ŸŽฎ Three.js 3D Rendering Architecture

Black Trigram uses Three.js for 3D rendering, achieving enhanced visual capabilities with authentic Korean martial arts theming and maintaining 60fps performance targets.

๐Ÿ“ฆ Three.js Dependencies

The following Three.js packages are now installed and configured:

  • three@0.184.0 - Core Three.js 3D engine with WebGL rendering
  • @react-three/fiber@9.6.0 - React renderer for Three.js (declarative 3D in React)
  • @react-three/drei@10.7.7 - Useful helpers and abstractions (@react-three/fiber)
  • @types/three@0.184.0 - TypeScript type definitions for Three.js

๐Ÿ—๏ธ Architecture Integration

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TD
    subgraph "React 19 Application Layer"
        A[React Components]
        B[State Management - Zustand]
        C[Korean Theming - KOREAN_COLORS]
    end
    
    subgraph "Rendering Layer"
        D["@react-three/fiber Canvas"]
    end
    
    subgraph "Three.js 3D Scene"
        F[Scene Graph]
        G[3D Characters]
        H[Vital Point Markers]
        I[Particle Systems]
        J[Korean-Themed Materials]
        K[Lighting Setup]
    end
    
    subgraph "UI Overlay Layer"
        L[Html Components]
        M[Combat HUD]
        N[Status Panels]
    end
    
    A --> D
    A --> E
    B --> A
    C --> A
    C --> J
    
    D --> F
    F --> G
    F --> H
    F --> I
    F --> J
    F --> K
    
    D --> L
    L --> M
    L --> N
    
    style D fill:#00ffff,stroke:#333,stroke-width:3px
    style F fill:#ffd700,stroke:#333,stroke-width:3px
    style J fill:#ff4444,stroke:#333,stroke-width:2px
    style L fill:#98fb98,stroke:#333,stroke-width:2px

๐Ÿ“ Rendering Pipeline

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','actorBkg':'#1565C0','actorTextColor':'#fff','actorLineColor':'#455A64','signalColor':'#455A64','signalTextColor':'#fff','noteBkgColor':'#FFD600','noteTextColor':'#000','noteBorderColor':'#F57F17'}}}%%
sequenceDiagram
    participant React as React Component
    participant Canvas as @react-three/fiber Canvas
    participant Scene as Three.js Scene
    participant WebGL as WebGL Renderer
    participant Display as Browser Display
    
    React->>Canvas: Render 3D components
    Canvas->>Scene: Build scene graph
    Scene->>Scene: Apply Korean materials
    Scene->>Scene: Position characters
    Scene->>Scene: Update particles
    
    loop Animation Loop (60fps)
        Canvas->>Scene: useFrame hook
        Scene->>WebGL: Render scene
        WebGL->>Display: Draw to canvas
    end
    
    Note over React,Display: Html overlays render separately via React DOM

๐Ÿ“ File Structure

Current Implementation

  • src/components/test/
    • Hello3D.tsx - Test component demonstrating Three.js setup
    • Hello3D.test.tsx - Unit tests for Three.js infrastructure
    • Hello3D-demo.tsx - Interactive demo with controls

Planned Structure

src/components/combat/
โ”œโ”€โ”€ characters/
โ”‚   โ”œโ”€โ”€ CharacterModel3D.tsx           # Base 3D character model
โ”‚   โ”œโ”€โ”€ VitalPointMarkers3D.tsx        # 70 vital points in 3D
โ”‚   โ”œโ”€โ”€ StanceAnimation3D.tsx          # Eight trigram stances
โ”‚   โ””โ”€โ”€ DamageVisualization3D.tsx      # Blood and injury effects
โ”œโ”€โ”€ particles/
โ”‚   โ”œโ”€โ”€ KiEnergyParticles3D.tsx        # Ki energy particle system
โ”‚   โ”œโ”€โ”€ HitEffects3D.tsx               # Impact effects and sparks
โ”‚   โ””โ”€โ”€ BloodSplatter3D.tsx            # Realistic blood effects
โ”œโ”€โ”€ arena/
โ”‚   โ”œโ”€โ”€ CombatArena3D.tsx              # Complete 3D combat scene
โ”‚   โ”œโ”€โ”€ DojangFloor3D.tsx              # Traditional dojang floor
โ”‚   โ””โ”€โ”€ KoreanLighting3D.tsx           # Korean-themed lighting setup
โ””โ”€โ”€ ui/
    โ”œโ”€โ”€ CombatHUDOverlayHtml.tsx       # Html UI over 3D scene
    โ”œโ”€โ”€ PlayerNameplate3D.tsx          # Player info in 3D space
    โ””โ”€โ”€ VitalPointTooltip3D.tsx        # Interactive tooltips

๐Ÿ”ง Configuration

Vite Configuration (vite.config.ts):

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    include: [
      // Three.js dependencies
      "three",
      "@react-three/fiber",
      "@react-three/drei",
      // Audio
      "howler",
    ],
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          'three-vendor': ['three', '@react-three/fiber', '@react-three/drei'],
        },
      },
    },
  },
});

TypeScript Configuration (tsconfig.json):

{
  "compilerOptions": {
    "skipLibCheck": true,          // Handles Three.js type complexities
    "moduleResolution": "bundler",  // Optimized for Vite + Three.js
    "strict": true,                 // Strict type checking
    "jsx": "react-jsx",             // React 19 JSX transform
    "types": ["vite/client", "node"]
  }
}

Test Setup (src/test/setup.ts):

// WebGL context mocking for Three.js tests
class MockWebGLRenderingContext {
  getExtension = vi.fn();
  getParameter = vi.fn();
  // ... full WebGL API mock
}

// ResizeObserver polyfill for @react-three/fiber
class MockResizeObserver {
  observe = vi.fn();
  unobserve = vi.fn();
  disconnect = vi.fn();
}

global.ResizeObserver = MockResizeObserver;

๐ŸŽจ Core Patterns

Pattern 1: Canvas Setup with Korean Theming

import { Canvas } from "@react-three/fiber";
import { Environment, PerspectiveCamera } from "@react-three/drei";
import { KOREAN_COLORS } from "../../types/constants";
import * as THREE from "three";

export function CombatScene3D() {
  return (
    <Canvas
      gl={{
        antialias: true,
        alpha: false,
        powerPreference: 'high-performance',
      }}
      dpr={[1, 2]}
      shadows
      onCreated={({ gl, scene }) => {
        // Korean cyberpunk background
        gl.setClearColor(KOREAN_COLORS.UI_BACKGROUND_DARK, 1);
        scene.fog = new THREE.Fog(
          KOREAN_COLORS.UI_BACKGROUND_DARK,
          10,
          50
        );
      }}
    >
      {/* Korean-themed lighting */}
      <ambientLight intensity={0.4} color={KOREAN_COLORS.PRIMARY_CYAN} />
      <directionalLight
        position={[10, 10, 5]}
        intensity={1}
        castShadow
        color={KOREAN_COLORS.ACCENT_GOLD}
      />
      
      {/* Environment reflections */}
      <Environment preset="city" />
      
      {/* Camera */}
      <PerspectiveCamera makeDefault position={[0, 5, 10]} fov={75} />
      
      {/* Game content */}
      <CombatArena3D />
    </Canvas>
  );
}

Pattern 2: useFrame Animation Loop

import { useFrame } from "@react-three/fiber";
import { useRef } from "react";
import * as THREE from "three";

export function AnimatedCharacter({ stance, health }) {
  const meshRef = useRef<THREE.Mesh>(null);
  
  // 60fps animation loop
  useFrame((state, delta) => {
    if (!meshRef.current) return;
    
    // Breathing animation
    const breathScale = Math.sin(state.clock.elapsedTime * 2) * 0.02 + 1;
    meshRef.current.scale.y = breathScale;
    
    // Stance-based rotation
    meshRef.current.rotation.y = getStanceRotation(stance);
  });
  
  return (
    <mesh ref={meshRef} castShadow receiveShadow>
      <capsuleGeometry args={[0.5, 1.5, 16, 32]} />
      <meshStandardMaterial color={getHealthColor(health)} />
    </mesh>
  );
}

Pattern 3: Html Overlays for UI

{% raw %}

import { Html } from "@react-three/drei";

export function PlayerNameplate3D({ name, nameKorean, health }) {
  return (
    <Html position={[0, 2.5, 0]} center>
      <div style={{
        background: `${KOREAN_COLORS.UI_BACKGROUND_DARK}cc`,
        border: `2px solid ${KOREAN_COLORS.PRIMARY_CYAN}`,
        borderRadius: '8px',
        padding: '12px',
        fontFamily: 'Korean Font',
      }}>
        <div style={{ color: KOREAN_COLORS.ACCENT_GOLD }}>
          {nameKorean} | {name}
        </div>
        <HealthBar health={health} />
      </div>
    </Html>
  );
}

{% endraw %}

Pattern 4: Korean Materials and Lighting

// Eight Trigram color mapping
const TRIGRAM_COLORS: Record<TrigramStance, number> = {
  geon: KOREAN_COLORS.CARDINAL_CENTER,  // โ˜ฐ Heaven - Yellow
  tae: KOREAN_COLORS.PRIMARY_CYAN,      // โ˜ฑ Lake - Cyan
  li: KOREAN_COLORS.CARDINAL_SOUTH,     // โ˜ฒ Fire - Red
  jin: KOREAN_COLORS.SECONDARY_YELLOW,  // โ˜ณ Thunder - Yellow
  son: KOREAN_COLORS.CARDINAL_EAST,     // โ˜ด Wind - Green
  gam: KOREAN_COLORS.ACCENT_BLUE,       // โ˜ต Water - Blue
  gan: KOREAN_COLORS.UI_BACKGROUND_LIGHT, // โ˜ถ Mountain - Gray
  gon: KOREAN_COLORS.UI_BACKGROUND_DARK,  // โ˜ท Earth - Dark
};

// Cardinal directions lighting (์˜ค๋ฐฉ์ƒ‰)
export function CardinalLighting() {
  return (
    <>
      <pointLight position={[10, 0, 0]} color={KOREAN_COLORS.CARDINAL_EAST} />
      <pointLight position={[-10, 0, 0]} color={KOREAN_COLORS.CARDINAL_WEST} />
      <pointLight position={[0, 0, 10]} color={KOREAN_COLORS.CARDINAL_SOUTH} />
      <pointLight position={[0, 0, -10]} color={KOREAN_COLORS.CARDINAL_NORTH} />
      <pointLight position={[0, 10, 0]} color={KOREAN_COLORS.CARDINAL_CENTER} />
    </>
  );
}

๐Ÿ“Š Performance Optimization

Bundle Size Management

AssetSize (Uncompressed)Size (Gzipped)Notes
Three.js core~600KB~150KBTree-shaken imports
@react-three/fiber~100KB~30KBReact integration
@react-three/drei~200KB~60KBOnly imported helpers
Total~900KB~240KBLazy-loaded when needed

Optimization Techniques

  1. Instancing for Particles
import { Instances, Instance } from '@react-three/drei';

<Instances limit={1000}>
  <sphereGeometry args={[0.1, 8, 8]} />
  <meshBasicMaterial color={KOREAN_COLORS.PRIMARY_CYAN} />
  {particles.map((p, i) => (
    <Instance key={i} position={p.position} scale={p.scale} />
  ))}
</Instances>
  1. LOD (Level of Detail)
import { Detailed } from '@react-three/drei';

<Detailed distances={[0, 10, 20]}>
  <HighDetailCharacter />
  <MediumDetailCharacter />
  <LowDetailCharacter />
</Detailed>
  1. Object Pooling
// Reuse objects instead of creating new ones
const particlePool = new ParticlePool(createParticle, resetParticle, 100);

๐Ÿš€ Migration Strategy

Phase 1: Infrastructure Setup โœ… COMPLETE

  • Three.js dependencies installed
  • Test component created (Hello3D)
  • Korean theming verified
  • Build and test pipeline working

Phase 2: Particle Systems (In Progress)

  • Migrate ki energy particles to Three.js Instances
  • Create 3D blood splatter effects
  • Implement impact sparks with lighting
  • Performance validation (1000+ particles at 60fps)

Phase 3: Character Models โœ… COMPLETE

  • Create unified Player3D component (Player3DUnified.tsx)
  • Implement stance-based visual system (8 trigrams with color-coded auras)
  • Add health/stamina/Ki state indicators with Html overlays
  • Support all 5 player archetypes with visual differentiation
  • Integrate pain/balance/consciousness visualization
  • Add responsive scaling for mobile/desktop
  • Create conversion utilities for PlayerState integration
  • Integrate into CombatScreen3D (both players)
  • Integrate into TrainingScreen3D (trainee player)
  • Comprehensive test coverage (61 component + 29 integration tests)

Key Components:

  • src/components/three/Player3DUnified.tsx - Main unified player visualization
  • src/components/three/PlayerStateIndicators.tsx - Html overlay for stats
  • src/components/three/StanceAura.tsx - Animated stance aura effects
  • src/utils/player3DHelpers.ts - PlayerState conversion utilities
  • src/types/player-visual.ts - TypeScript interfaces for player visuals

Usage Example:

import { Player3DUnified } from '@/components/three';
import { convertPlayerStateToProps } from '@/utils/player3DHelpers';

// In CombatScreen3D or TrainingScreen3D:
<Player3DUnified
  {...convertPlayerStateToProps(
    playerState,
    [x, y, z],      // 3D position
    rotation,       // Y-axis rotation in radians
    {
      isMobile,
      facing: "right",
      showVitalPoints: true,
    }
  )}
/>

Phase 4: Combat Arena (Planned)

  • Build 3D dojang environment
  • Korean-themed lighting setup
  • Shadow and reflection effects
  • Environmental particles (dust, air)

Phase 5: UI Integration (Planned)

  • Convert Combat HUD to Html overlays
  • 3D-positioned player status panels
  • Floating damage numbers
  • Vital point targeting interface

Phase 6: Polish & Optimization (Planned)

  • Post-processing effects (bloom, color grading)
  • Advanced particle systems
  • Mobile performance optimization
  • Production deployment

๐Ÿงช Testing Strategy

Unit Tests

// Test Three.js component imports and props
describe('CharacterModel3D', () => {
  it('should be defined and importable', () => {
    expect(CharacterModel3D).toBeDefined();
  });
  
  it('should accept Korean colors', () => {
    expect(typeof KOREAN_COLORS.PRIMARY_CYAN).toBe('number');
  });
});

E2E Tests

// cypress/e2e/threejs-combat.cy.ts
describe('Three.js Combat Arena', () => {
  it('should render 3D scene without errors', () => {
    cy.visit('/combat');
    cy.get('canvas').should('exist');
    cy.wait(1000); // Allow scene to load
  });
  
  it('should maintain 60fps during combat', () => {
    // Use custom FPS counter to validate performance
  });
});

Manual Testing Checklist

  • Visual quality on desktop (1920x1080)
  • Visual quality on mobile (720p)
  • 60fps sustained on desktop
  • 55fps minimum on mobile
  • Korean colors render correctly
  • Html overlays positioned properly
  • No WebGL errors in console
  • Memory usage stays below 500MB (desktop)

๐ŸŽฌ Skeletal Animation Architecture

Black Trigram implements a comprehensive 28-bone skeletal system with hand poses and muscle tension visualization for authentic Korean martial arts movement.

Bone Hierarchy (28-Bone System)

PELVIS (root)
โ”œโ”€โ”€ SPINE_LOWER
โ”‚   โ”œโ”€โ”€ SPINE_MID
โ”‚   โ”‚   โ””โ”€โ”€ SPINE_UPPER
โ”‚   โ”‚       โ”œโ”€โ”€ NECK
โ”‚   โ”‚       โ”‚   โ””โ”€โ”€ HEAD
โ”‚   โ”‚       โ”œโ”€โ”€ SHOULDER_L โ†’ UPPER_ARM_L โ†’ ELBOW_L โ†’ FOREARM_L โ†’ WRIST_L โ†’ HAND_L
โ”‚   โ”‚       โ””โ”€โ”€ SHOULDER_R โ†’ UPPER_ARM_R โ†’ ELBOW_R โ†’ FOREARM_R โ†’ WRIST_R โ†’ HAND_R
โ”‚   โ”œโ”€โ”€ HIP_L โ†’ THIGH_L โ†’ KNEE_L โ†’ SHIN_L โ†’ FOOT_L
โ”‚   โ””โ”€โ”€ HIP_R โ†’ THIGH_R โ†’ KNEE_R โ†’ SHIN_R โ†’ FOOT_R

Total: 28 bones

  • 1 pelvis (root)
  • 3 spine bones (lower, mid, upper)
  • 2 head bones (neck, head)
  • 12 arm bones (6 per arm: shoulder, upper_arm, elbow, forearm, wrist, hand)
  • 10 leg bones (5 per leg: hip, thigh, knee, shin, foot)

Implementation: src/types/skeletal.ts - Complete bone hierarchy with TypeScript type definitions

Hand Pose System

Seven Primary Hand Poses (from src/types/hand-animation.ts):

  • fist - Closed fist for punching - ์ฃผ๋จน (Jumeok)
  • knife_hand - Knife-hand strike with rigid edge - ์ˆ˜๋„ (Sudo)
  • spear_hand - Spear-hand thrust with pointed fingers - ๊ด€์ˆ˜ (Gwansu)
  • palm_heel - Palm-heel strike with curled fingers - ์žฅ๋ ฅ (Jangnyeok)
  • grappling - Grappling hand for grabs - ์žก๊ธฐ (Japgi)
  • open - Open hand neutral position - ํŽด๊ธฐ (Pyeogi)
  • relaxed - Relaxed natural hand for walking/idle - ํœด์‹ (Hyusik)

Implementation: src/types/hand-animation.ts - Hand pose definitions and transitions

Muscle Tension Visualization

Tension Mapping (0.0-1.0):

  • High Tension (0.8-1.0): Bright red muscles - Active striking or blocking
  • Medium Tension (0.4-0.7): Orange muscles - Stance maintenance
  • Low Tension (0.0-0.3): Relaxed state - Recovery phase

Visual Feedback:

  • Tension values mapped to bone visual intensity in real-time
  • Color gradient from relaxed (dim) to maximum exertion (bright)
  • Synchronized with technique execution and stance changes

Implementation: src/types/muscle.ts - Muscle activation system with tension tracking

Technique Animation System

Keyframe Interpolation:

  • Start pose โ†’ Intermediate frames โ†’ Impact frame โ†’ Recovery
  • 60fps smooth interpolation between keyframes
  • Technique-specific timing (fast strikes, slow defensive movements)

Integration with Combat:

  • Technique selection triggers skeletal animation sequence
  • Hand pose changes synchronized with strike timing
  • Muscle tension peaks at impact frame
  • Animation completes before next input accepted

Implementation:

  • src/types/technique.ts - Technique type definitions with animation metadata
  • src/systems/animation/ - Animation system logic and keyframe management

Performance Considerations

Optimization Strategies:

  • Bone transforms cached and reused when stance is stable
  • Hand pose transitions use linear interpolation (LERP) for smooth 60fps
  • Muscle tension updates only for visible characters
  • Object pooling for animation state objects

Memory Footprint:

  • 28 bones ร— 16 bytes (Matrix4) = 448 bytes per character
  • Hand pose state: ~50 bytes per character
  • Muscle tension map: ~112 bytes (8 muscle groups)
  • Total per character: ~610 bytes

Target Performance:

  • 2 characters (player + opponent): ~1220 bytes animation overhead
  • Negligible impact on 60fps target (<1ms per frame)

๐ŸŽฏ Performance Targets (Q2 2026)

PlatformResolutionTarget FPSAchieved FPSParticlesMemoryStatus
Desktop1200x80060fps60fps1000+180MBโœ… Met
Tablet1024x76830fps55fps+750+150MBโœ… Optimized
Mobile720p30fps55fps+500+150MBโœ… Optimized

Overall Performance Rating: 8.5/10 (60fps desktop maintained, mobile optimization complete 55fps+)

๐Ÿš€ Three.js Optimization Techniques

1. Instancing for Particles

Single draw call for 1000+ particles using <Instances> from @react-three/drei.

2. LOD (Level of Detail)

Automatic polygon reduction for distant objects using <Detailed> component.

3. Skeletal Animation Optimization

  • 28 bones per character (vs thousands of vertices)
  • Cached bone matrices for stable stances
  • 7 predefined hand poses (no per-frame calculations)

4. Object Pooling

Particle systems and hit effects use object pooling to reduce garbage collection.

5. Texture Compression

WebP for UI textures (70-80% size reduction), faster loading times.

6. Geometry Merging

Static environment objects merged into single mesh for reduced draw calls.

๐Ÿ“Š Current Benchmarks (Q1 2026)

MetricDesktopMobileTarget
FPS60fps30-45fps60fps / 30fps
Memory180MB150MB<200MB
Load Time2.5s3.5s<3s / <5s
Draw Calls50-8040-60<100
Triangles50k-80k30k-50k<100k
Bundle Size240KB (gzipped)240KB (gzipped)<300KB

๐Ÿ”ฌ Performance Monitoring

  • Custom performance overlay component (PerformanceOverlay3D) for real-time FPS and frame-timing monitoring (no stats.js dependency)
  • Custom performance metrics tracked in React/Three.js state and surfaced via PerformanceOverlay3D
  • Performance tests in the Vitest suite validating PerformanceOverlay3D frame timing, overlay stability, and animation timing

๐Ÿ“ฑ Mobile Performance Optimization (Q2 2026 Complete)

Current Status: 55fps+ on mobile (exceeded 30fps baseline target)

Optimization Completed:

  1. Adaptive quality settings based on device capabilities
  2. Simplified shaders for mobile-optimized materials
  3. Reduced particle count (500 cap vs 1000 desktop)
  4. LOD aggressive tuning for earlier low-detail transitions
  5. Mobile R3F fixes and coordinate system corrections

๐Ÿ“š Documentation & Resources

Project Documentation

External Resources

Learning Resources

  • Three.js Journey - Comprehensive Three.js course
  • Discover three.js - Free online book
  • React Three Fiber Examples - Official example gallery

โœ… Success Criteria

Infrastructure:

  • Three.js packages installed and configured
  • TypeScript support enabled
  • Korean theming integration verified
  • Build pipeline working
  • Test infrastructure set up

Performance:

  • 60fps sustained on desktop at 1920x1080
  • 55fps minimum on mobile at 720p
  • 1000+ particles at 60fps (desktop)
  • Memory usage <500MB (desktop)
  • Bundle size <1MB gzipped

Quality:

  • Korean cultural aesthetics maintained
  • Smooth martial arts animations
  • Realistic vital point visualization
  • Immersive combat experience
  • Bilingual UI (Korean | English)

Documentation:

  • Architecture documented
  • Migration guide created
  • Pattern library established
  • API documentation updated
  • Team training completed

๐Ÿ”ง File Structure (Q2 2026)

Current Implementation Structure

src/
โ”œโ”€โ”€ components/               # React + Three.js components
โ”‚   โ”œโ”€โ”€ screens/             # Main game screens
โ”‚   โ”‚   โ”œโ”€โ”€ combat/          # CombatScreen3D (production-ready)
โ”‚   โ”‚   โ”œโ”€โ”€ intro/           # IntroScreen with Korean aesthetics
โ”‚   โ”‚   โ”œโ”€โ”€ training/        # TrainingScreen for practice
โ”‚   โ”‚   โ””โ”€โ”€ controls/        # ControlsScreen documentation
โ”‚   โ”œโ”€โ”€ game/                # Game-specific components
โ”‚   โ”œโ”€โ”€ shared/              # Shared components across screens
โ”‚   โ”‚   โ”œโ”€โ”€ three/           # Three.js 3D components
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ anatomy/     # BoneAttachedMuscles, SkeletalRig
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ effects/     # ParticleEffects, StanceAura
โ”‚   โ”‚   โ”œโ”€โ”€ mobile/          # Mobile touch controls
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ *Pure.tsx    # Pure DOM components (outside Canvas)
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ *.tsx        # Three.js Html components (inside Canvas)
โ”‚   โ”‚   โ””โ”€โ”€ ui/              # UI components with Korean theming
โ”‚   โ””โ”€โ”€ dev/                 # Development and testing components
โ”œโ”€โ”€ systems/                 # Core game logic systems
โ”‚   โ”œโ”€โ”€ trigram/             # 8-trigram stance system
โ”‚   โ”‚   โ”œโ”€โ”€ StanceManager.ts
โ”‚   โ”‚   โ”œโ”€โ”€ TransitionCalculator.ts
โ”‚   โ”‚   โ”œโ”€โ”€ TrigramCalculator.ts
โ”‚   โ”‚   โ””โ”€โ”€ KoreanCulture.ts
โ”‚   โ”œโ”€โ”€ vitalpoint/          # 70 anatomical vital points
โ”‚   โ”‚   โ”œโ”€โ”€ VitalPointSystem.ts
โ”‚   โ”‚   โ”œโ”€โ”€ EnhancedAnatomy.ts
โ”‚   โ”‚   โ””โ”€โ”€ HitDetection.ts
โ”‚   โ”œโ”€โ”€ CombatSystem.ts      # Main combat logic and orchestration (36,888 bytes ~36KB)
โ”‚   โ”œโ”€โ”€ EffectCalculator.ts  # Combat effect calculations
โ”‚   โ”œโ”€โ”€ PlayerEffectManager.ts # Player effect management
โ”‚   โ”œโ”€โ”€ combat/              # Combat subsystems
โ”‚   โ”‚   โ”œโ”€โ”€ PainResponseSystem.ts     # Pain response (90% complete, 37 tests)
โ”‚   โ”‚   โ”œโ”€โ”€ ConsciousnessSystem.ts    # Consciousness (90% complete, 36 tests)
โ”‚   โ”‚   โ”œโ”€โ”€ BalanceSystem.ts          # Balance and fall mechanics
โ”‚   โ”‚   โ””โ”€โ”€ CombatStateSystem.ts      # Combat state management
โ”‚   โ”œโ”€โ”€ animation/           # Skeletal animation system (Q1 2026)
โ”‚   โ”‚   โ”œโ”€โ”€ core/            # Core animation logic
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ AnimationRegistry.ts      # Animation registration and lookup
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ AnimationStateMachine.ts  # Animation state transitions
โ”‚   โ”‚   โ”œโ”€โ”€ builders/        # Builders for animation data
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ HandPoses.ts           # 7 hand pose definitions
โ”‚   โ”‚   โ””โ”€โ”€ systems/         # Animation systems and orchestration
โ”‚   โ”‚       โ””โ”€โ”€ MuscleActivation.ts    # Muscle tension visualization
โ”‚   โ”œโ”€โ”€ bodypart/            # Body part health tracking (8 parts)
โ”‚   โ”œโ”€โ”€ physics/             # Physics simulation
โ”‚   โ”œโ”€โ”€ breathing/           # Breathing disruption system (75% complete)
โ”‚   โ””โ”€โ”€ ai/                  # AI combat logic
โ”œโ”€โ”€ data/                    # Game data and constants
โ”‚   โ”œโ”€โ”€ techniques.ts        # 20 techniques (4 per archetype)
โ”‚   โ”œโ”€โ”€ archetypePhysicalAttributes.ts  # 5 player archetypes
โ”‚   โ””โ”€โ”€ archetypeClothing.ts # Clothing system per archetype
โ”œโ”€โ”€ audio/                   # Audio system (87.38% line coverage)
โ”‚   โ”œโ”€โ”€ AudioProvider.tsx    # React context provider and useAudio hook
โ”‚   โ”œโ”€โ”€ AudioAssetRegistry.ts # Sound library and metadata
โ”‚   โ”œโ”€โ”€ AudioManager.ts      # Audio playback and routing
โ”‚   โ””โ”€โ”€ BoneImpactAudioMap.ts # Bone impact audio system (60% complete)
โ”œโ”€โ”€ types/                   # TypeScript type definitions
โ”‚   โ”œโ”€โ”€ constants/           # Korean colors, fonts, animations
โ”‚   โ”œโ”€โ”€ skeletal.ts          # 28-bone skeletal system (Q1 2026)
โ”‚   โ”œโ”€โ”€ muscle.ts            # Muscle tension system (Q1 2026)
โ”‚   โ”œโ”€โ”€ hand-animation.ts    # 7 hand pose definitions (Q1 2026)
โ”‚   โ”œโ”€โ”€ technique.ts         # Technique type definitions
โ”‚   โ”œโ”€โ”€ player-visual.ts     # Player visual properties
โ”‚   โ”œโ”€โ”€ physics.ts           # Physics types
โ”‚   โ””โ”€โ”€ clothing.ts          # Clothing system types
โ”œโ”€โ”€ utils/                   # Utility functions
โ”‚   โ”œโ”€โ”€ player3DHelpers.ts   # PlayerState conversion utilities
โ”‚   โ”œโ”€โ”€ combatHelpers.ts     # Combat utility functions
โ”‚   โ”œโ”€โ”€ threeObjectPool.ts   # Object pooling for performance
โ”‚   โ”œโ”€โ”€ clothingColors.ts    # Archetype clothing colors
โ”‚   โ””โ”€โ”€ performance/         # Performance monitoring utilities
โ””โ”€โ”€ hooks/                   # Custom React hooks
    โ””โ”€โ”€ useCombat.ts         # Combat-related hooks

Key Implementation Files (Q2 2026)

Combat Systems:

  • src/systems/CombatSystem.ts (36,888 bytes ~36KB) - Core combat logic with 13/13 realism systems
  • src/systems/VitalPointSystem.ts (19,583 bytes ~20KB) - 70-point vital targeting (100% complete)
  • src/systems/TrigramSystem.ts (12,843 bytes ~13KB) - 8-stance management with I Ching philosophy
  • src/systems/combat/PainResponseSystem.ts - Pain response system (100% complete, production-ready)
  • src/systems/combat/ConsciousnessSystem.ts - Consciousness levels (100% complete, 4-level gradation)
  • src/systems/breathing/BreathingDisruptionSystem.ts - Breathing disruption (95% complete)

Skeletal Animation (Q2 2026):

  • src/types/skeletal.ts (857 lines) - 28-bone hierarchy definitions, BoneName enum, SkeletalRig interface
  • src/types/muscle.ts - Muscle tension visualization system (0.0-1.0 intensity mapping)
  • src/types/hand-animation.ts - Hand pose system (7 primary poses: fist_vertical, fist_horizontal, open_hand_knife, spear_hand, grasping, open_palm, relaxed)
  • src/systems/animation/ - Animation system logic and keyframe management

Player Archetypes:

  • src/data/archetypePhysicalAttributes.ts (20,875 bytes ~21KB) - Physical attributes for 5 archetypes
  • src/data/archetypeClothing.ts (15,792 bytes ~16KB) - Clothing system per archetype
  • src/data/techniques.ts (19,730 bytes ~20KB) - 20 martial arts techniques (4 per archetype)

Three.js Components:

  • src/components/shared/three/ - 3D rendering components (Player3DUnified, StanceAura, SkeletalRig)
  • src/components/screens/combat/ - CombatScreen3D implementation (production-ready, 41.71% line coverage per docs/coverage/coverage-summary.json)
  • src/utils/player3DHelpers.ts - PlayerState to Three.js conversion utilities

Audio System (88.08% Line Coverage):

  • src/audio/AudioProvider.tsx - React context provider and useAudio hook
  • src/audio/AudioAssetRegistry.ts - Sound library with damage-scaled audio
  • src/audio/AudioManager.ts - Audio playback with Web Audio API
  • src/audio/BoneImpactAudioMap.ts - Bone impact audio system (60% complete)
  • 88.08% line coverage across audio systems (843/957 lines, per docs/coverage/audio/index.html)

Test Coverage (Q2 2026):

  • Overall: 72.34% line coverage (17,451 / 24,121 lines, 518 tests - Vitest unit + Cypress E2E, per docs/coverage/coverage-summary.json)
  • New Components: 95% test coverage
  • Core Systems: >85% test coverage
  • Audio System: 88.08% line coverage (843/957 lines)
  • Combat Realism: 518 tests passing (372 + 146 new)
  • Grappling/Limb Exposure: 132 comprehensive tests

Component Naming Conventions

Mobile Component Pattern:

  • Components with Pure suffix are pure DOM components without Three.js dependencies
  • Used for rendering outside Canvas context (e.g., StanceWheelPure, GestureRecognizerPure, MobileControlsPure)
  • Components without Pure suffix use Html from @react-three/drei and must be inside Canvas
  • Example: StanceWheelPure.tsx (position: fixed, z-index layering) vs StanceWheel.tsx (Html wrapper, Canvas-only)

Rationale:

  • Mobile touch controls must work outside Canvas for reliable event handling
  • Pure DOM components have no Three.js overhead and lighter bundle size
  • Clear naming prevents R3F hook errors ("R3F hooks can only be used inside canvas component")

๐Ÿ”„ Combat Flow Sequence

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','actorBkg':'#1565C0','actorTextColor':'#fff','actorLineColor':'#455A64','signalColor':'#455A64','signalTextColor':'#fff','noteBkgColor':'#FFD600','noteTextColor':'#000','noteBorderColor':'#F57F17'}}}%%
sequenceDiagram
    title ๐Ÿ”„ Combat Flow โ€“ Fully Frontend (Black Trigram Q1 2026)

    participant Player as "๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ Player"
    participant InputSystem as "๐ŸŽฎ InputSystem"
    participant CombatEngine as "โš”๏ธ Combat Engine"
    participant TrigramSystem as "๐Ÿ”ถ Trigram System"
    participant VitalPointSystem as "๐ŸŽฏ VitalPoint System"
    participant AudioManager as "๐ŸŽต Audio Manager"
    participant StateStore as "๐Ÿ—„๏ธ Zustand Store"
    participant ThreeScene as "๐ŸŽจ Three.js Scene"

    Note over Player,ThreeScene: ๐Ÿฅ‹ Korean Martial Arts Real-Time Combat

    Player->>InputSystem: ๐Ÿฅ‹ Press stance key (e.g., '1' for ๊ฑด/Geon)
    InputSystem->>CombatEngine: ๐Ÿ”ƒ Stance change request
    CombatEngine->>TrigramSystem: ๐Ÿ” Calculate transition (Current โ†’ Geon)
    TrigramSystem->>StateStore: โž– Deduct Ki/Stamina
    TrigramSystem-->>CombatEngine: โœ… Transition result (Success/Fail)
    CombatEngine->>AudioManager: ๐Ÿ”Š Play stance change SFX
    CombatEngine->>ThreeScene: โœจ Update player aura visuals (StanceAura3D)

    Player->>InputSystem: โš”๏ธ Click to attack (Mouse click)
    InputSystem->>CombatEngine: ๐ŸŽฏ Attack command with screen coords
    CombatEngine->>TrigramSystem: ๐Ÿ’ก Get current technique parameters
    CombatEngine->>VitalPointSystem: ๐Ÿ” Hit detection (polygon-based, <0.01ms)
    VitalPointSystem-->VitalPointSystem: ๐ŸŽฏ Compute precision vs 70 vital points
    VitalPointSystem-->>CombatEngine: โœ… Hit result (VitalPointData, Multiplier)
    CombatEngine->>CombatEngine: ๐Ÿงฎ Compute final damage (base ร— trigram_adv ร— vp_mult)
    CombatEngine->>StateStore: ๐Ÿฉธ Reduce enemy body part health (8 parts)
    CombatEngine->>AudioManager: ๐Ÿ”Š Play impact SFX (damage-scaled audio)
    CombatEngine->>ThreeScene: ๐Ÿ’ฅ Render hit effects, damage numbers (HitEffects3D)
    CombatEngine->>StateStore: โšก Update combat state (pain, consciousness, balance)
    CombatEngine-->>ThreeScene: ๐Ÿ‘บ Trigger enemy reaction animation (SkeletalAnimation)
  • AudioManager: Web Audio API plays sound buffers loaded at runtime from the Audio CDN.
  • Three.js Scene: Via @react-three/fiber Canvas component, renders 3D characters, environment, effects, and UI overlays via Html.
  • Zustand Store: All shared state (player health, Ki, stance) resides in memory; React components subscribe.

โšก Performance Architecture (Q1 2026)

Performance Targets

PlatformResolutionTarget FPSAchieved FPSParticlesMemoryStatus
High-end Desktop1920x108060fps60fps1000+<500MBโœ… Met
Mid-range Desktop1920x108060fps58-60fps750+<400MBโœ… Good
High-end Mobile1290x279655fps55-60fps500+<350MBโœ… Acceptable
Mid-range Mobile1080x240055fps50-55fps400+<300MBโš ๏ธ Needs Optimization

Overall Performance Rating: 8.0/10 (60fps maintained on desktop, mobile optimization ongoing)

Three.js-Specific Optimizations

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TD
    subgraph PM["๐Ÿ” Performance Monitoring (Q1 2026)"]
      PerfMon["๐Ÿ“ˆ Performance Monitor"]
      FPS["๐Ÿ“Š FPS Tracking - PerformanceOverlay3D"]
      Memory["๐Ÿ’พ Memory Usage - Chrome DevTools"]
      GC["๐Ÿ—‘๏ธ GC Observations - Three.js Object Disposal"]
      AssetTiming["โฑ๏ธ Asset Load Times - Three.js Models & Textures"]
      ThreeRenderer["๐ŸŽจ Three.js Renderer Stats - Draw Calls"]
    end

    subgraph OT["๐Ÿš€ Optimization Techniques (Three.js)"]
      OptEngine["โš™๏ธ Optimization Engine"]
      Instancing["๐Ÿ“ฆ Three.js Instancing - 1000+ Particles"]
      LOD["๐ŸŽญ Level of Detail - Character Models"]
      ObjectPooling["๐Ÿ”„ Object Pooling - Three.js Objects"]
      GeometryReuse["๐Ÿ”บ Geometry Reuse - Shared Meshes"]
      CodeSplitting["๐Ÿ“‚ Dynamic import - Three.js Chunks"]
      AudioCompression["๐ŸŽต OGG/WebM Streaming - Web Audio API"]
      Debounce["โณ Debounce/Throttle - useFrame Optimization"]
      Memoization["๐Ÿง  React.memo / useMemo - Component Optimization"]
      FrustumCulling["๐Ÿ‘๏ธ Frustum Culling - Auto Off-screen Culling"]
      MaterialReuse["๐ŸŽจ Material Caching - Shared Materials"]
    end

    subgraph FS["๐Ÿ›ก๏ธ Fallback Systems"]
      FallbackMgr["โš ๏ธ Fallback Manager"]
      LowQualityMode["๐Ÿ“‰ Reduced Polygon Count"]
      ReducedEffects["โŒ Disable Shadows & Post-Processing"]
      ProceduralAudio["๐ŸŽน Procedural SFX Fallback"]
      WebGLFallback["๐Ÿ–ผ๏ธ Fallback to WebGL 1.0"]
    end

    PerfMon --> FPS
    PerfMon --> Memory
    PerfMon --> GC
    PerfMon --> AssetTiming
    PerfMon --> ThreeRenderer

    OptEngine --> Instancing
    OptEngine --> LOD
    OptEngine --> ObjectPooling
    OptEngine --> GeometryReuse
    OptEngine --> CodeSplitting
    OptEngine --> AudioCompression
    OptEngine --> Debounce
    OptEngine --> Memoization
    OptEngine --> FrustumCulling
    OptEngine --> MaterialReuse

    FallbackMgr --> LowQualityMode
    FallbackMgr --> ReducedEffects
    FallbackMgr --> ProceduralAudio
    FallbackMgr --> WebGLFallback

    PM -.-> OT
    OT -.-> FS

    classDef perfMon fill:#4ecdc4,stroke:#333,stroke-width:2px,color:#000
    classDef optTech fill:#45b7d1,stroke:#333,stroke-width:2px,color:#000
    classDef fallback fill:#f9ca24,stroke:#333,stroke-width:2px,color:#000

    class PerfMon,FPS,Memory,GC,AssetTiming,ThreeRenderer perfMon
    class OptEngine,Instancing,LOD,ObjectPooling,GeometryReuse,CodeSplitting,AudioCompression,Debounce,Memoization,FrustumCulling,MaterialReuse optTech
    class FallbackMgr,LowQualityMode,ReducedEffects,ProceduralAudio,WebGLFallback fallback

Performance Monitoring (Q1 2026)

  • ๐Ÿ“ˆ FPS Tracking: PerformanceOverlay3D custom monitor component (src/utils/performance/PerformanceOverlay3D.tsx)
  • ๐Ÿ’พ Memory Usage: Chrome DevTools memory profiling + custom Three.js object tracking
  • ๐Ÿ—‘๏ธ GC Observations: Monitor Three.js object disposal (geometries, materials, textures) to prevent memory leaks
  • โฑ๏ธ Asset Timing: Three.js loading manager for 3D models, textures, and audio asset timing
  • ๐ŸŽจ Renderer Stats: Track draw calls, triangles rendered, and shader compile time

Three.js Optimization Techniques

  1. ๐Ÿ“ฆ Three.js Instancing (Implementation: src/utils/threeObjectPool.ts)

    • Use THREE.InstancedMesh for particle systems (1000+ particles at 60fps)
    • Batch hit effects, ki energy particles using instancing
    • Reduces draw calls from 1000+ to 1 per particle type
  2. ๐ŸŽญ Level of Detail (LOD) (Planned for Phase 4)

    • High-detail character models at close range (28-bone skeletal system)
    • Medium-detail models at medium distance (simplified bone hierarchy)
    • Low-detail models at far distance (capsule geometry)
    • @react-three/drei <Detailed> component for automatic LOD switching
  3. ๐Ÿ”„ Object Pooling (Implementation: src/utils/threeObjectPool.ts)

    • Pre-allocate Three.js objects (meshes, materials, geometries)
    • Recycle particle objects instead of creating/destroying
    • Pool damage numbers, hit effects, and temporary visual elements
    • Result: Reduced GC pressure, stable 60fps
  4. ๐Ÿ”บ Geometry Reuse

    • Shared geometries for identical shapes (capsules for characters, spheres for particles)
    • Single geometry instance referenced by multiple meshes
    • Dispose only when last reference removed
  5. ๐ŸŽจ Material Caching

    • Pre-create materials with Korean colors (KOREAN_COLORS.PRIMARY_CYAN, etc.)
    • Reuse materials across multiple meshes
    • Update material properties (color, emissive) instead of creating new materials
  6. ๐Ÿ—‘๏ธ Three.js Resource Disposal (์ž์› ์ •๋ฆฌ | Resource Cleanup)

    Critical for Memory Management: All Three.js GPU resources (geometries, materials, textures) must be explicitly disposed when no longer needed. Failure to dispose causes memory leaks that degrade performance over time.

    Resources Requiring Disposal:

    • โœ… Geometries: geometry.dispose()
    • โœ… Materials: material.dispose()
    • โœ… Textures: texture.dispose()
    • โš ๏ธ Vector3, Matrix4, Color: No disposal needed (just data structures)

    Best Practices:

    // โŒ BAD: Memory leak - geometry never disposed
    export const Component3D: React.FC = () => {
      const geometry = useMemo(() => new THREE.BoxGeometry(1, 1, 1), []);
      const material = useMemo(() => new THREE.MeshStandardMaterial({ color: 0xff0000 }), []);
      
      return <mesh geometry={geometry} material={material} />;
    };
    
    // โœ… GOOD: Proper cleanup on unmount
    export const Component3D: React.FC = () => {
      const geometry = useMemo(() => new THREE.BoxGeometry(1, 1, 1), []);
      const material = useMemo(() => new THREE.MeshStandardMaterial({ color: 0xff0000 }), []);
      
      // ์ž์› ์ •๋ฆฌ | Resource cleanup
      useEffect(() => {
        return () => {
          geometry.dispose();
          material.dispose();
        };
      }, [geometry, material]);
      
      return <mesh geometry={geometry} material={material} />;
    };
    

    Implementation References:

    • src/utils/particlePool.ts - Object pooling with proper disposal
    • src/components/screens/training/components/TrainingDummy3D.tsx - Component disposal patterns
    • src/components/shared/three/scene/KoreanSignage3D.tsx - Material cleanup examples

    Audit Tool:

    # Run automated disposal audit to find missing cleanup
    npx tsx scripts/audit-threejs-disposal.ts
    npx tsx scripts/audit-threejs-disposal.ts --fix-report
    

    Memory Impact:

    • Before fixes: ~4GB heap usage after 30min gameplay
    • After fixes: ~2.5GB heap usage after 30min gameplay
    • Improvement: 37.5% memory reduction, stable 60fps maintained

    Performance Monitoring:

    // Monitor memory leaks during development
    import { globalParticlePool } from '@/utils/particlePool';
    
    // Check pool stats
    console.log(globalParticlePool.getStats());
    // Output: { total: 20, active: 5, inactive: 15, maxSize: 50 }
    
    // In Chrome DevTools:
    // 1. Memory โ†’ Take heap snapshot
    // 2. Search for "THREE.BufferGeometry" or "THREE.Material"
    // 3. Check "Detached" instances - should be minimal
    
  7. ๐Ÿ‘๏ธ Frustum Culling

    • Automatic off-screen object culling by Three.js renderer
    • No rendering cost for objects outside camera view
    • Works seamlessly with skeletal animation system
  8. ๐Ÿ“‚ Code Splitting (Implementation: vite.config.ts)

    • Three.js vendor chunk (~240KB gzipped)
    • Lazy-load training screens and non-critical components
    • Dynamic import for large data files
  9. โณ useFrame Optimization

    • Selective updates in useFrame hooks (only when needed)
    • Skip animation updates for off-screen characters
    • Throttle muscle tension updates to 30fps (sufficient for visual feedback)
  10. ๐Ÿง  React Memoization

  • React.memo for pure Three.js wrapper components
  • useMemo for expensive calculations (bone transforms, hit detection)
  • useCallback for event handlers passed to children

Performance Benchmarks (Q1 2026)

Desktop Performance

Hardware: RTX 3080, Intel i7-11700K, 32GB RAM
Resolution: 1920x1080
Scene Complexity: 2 characters (28 bones each), 500 particles, 70 vital points
Result: 60fps sustained, <400MB memory, 0.8ms GC pauses
Status: โœ… Exceeds target

Mobile Performance

Hardware: iPhone 14 Pro, A16 Bionic
Resolution: 1290x2796 (downscaled to 720p for rendering)
Scene Complexity: 2 characters (simplified), 300 particles, 70 vital points
Result: 55-60fps, <350MB memory, 1.2ms GC pauses
Status: โœ… Meets target

Mid-range Mobile Performance

Hardware: Google Pixel 6a, Tensor SoC
Resolution: 1080x2400 (downscaled to 540p for rendering)
Scene Complexity: 2 characters (simplified), 200 particles, 35 visible vital points
Result: 50-55fps, <300MB memory, 2.0ms GC pauses
Status: โš ๏ธ Below 55fps target - needs optimization

Optimization Priorities (Q2 2026)

  1. ๐Ÿ”ด Critical: Mobile performance optimization (target 55fps on mid-range devices)
  2. ๐ŸŸก High: Implement LOD system for character models
  3. ๐ŸŸก High: Add post-processing effects toggle for low-end devices
  4. ๐ŸŸ  Medium: Optimize skeletal animation for mobile (reduce bone updates)
  5. ๐ŸŸ  Medium: Implement progressive 3D model loading

Fallback Systems (Graceful Degradation)

  1. ๐Ÿ“‰ Low Quality Mode

    • Detect GPU capabilities at startup. If low, reduce canvas resolution and disable sub-pixel effects.
    • Toggle via "Low Graphics" checkbox in settings (Zustand flag: useUIState.isLowGraphicsMode).
  2. โŒ Reduced Effects

    • On performance drop (FPS < 30), disable expensive particles: blood splatter, continuous ki swirl.
    • Use useUIState.isLowPerfMode to toggle off these render layers.
  3. ๐ŸŽน Procedural Audio

    • If Audio CDN fails (e.g., offline), fall back to simple beep-thump procedural sounds via DefaultSoundGenerator.ts.

๐Ÿ“Š SWOT Analysis

Traditional SWOT Quadrant Chart

%%{init: {
  "theme": "neutral",
  "themeVariables": {
    "quadrant1Fill": "#2b83ba",
    "quadrant2Fill": "#1a9641", 
    "quadrant3Fill": "#d7191c",
    "quadrant4Fill": "#756bb1",
    "quadrantTitleFill": "#ffffff",
    "quadrantPointFill": "#ffffff",
    "quadrantPointTextFill": "#000000",
    "quadrantXAxisTextFill": "#000000",
    "quadrantYAxisTextFill": "#000000"
  },
  "quadrantChart": {
    "chartWidth": 700,
    "chartHeight": 700,
    "pointLabelFontSize": 14,
    "titleFontSize": 24,
    "quadrantLabelFontSize": 18,
    "xAxisLabelFontSize": 16,
    "yAxisLabelFontSize": 16
  }
}}%%
quadrantChart
    title ๐Ÿ“Š Black Trigram (ํ‘๊ด˜) Frontend-Only SWOT Analysis
    x-axis Internal --> External
    y-axis Negative --> Positive
    quadrant-1 Opportunities
    quadrant-2 Strengths
    quadrant-3 Weaknesses
    quadrant-4 Threats

    "๐Ÿ’ก PWA & Offline Caching": [0.8, 0.9] radius: 7, color: #a4c2f4, stroke-color: #3d64ba, stroke-width: 2px
    "๐Ÿ“ฑ Mobile-First UX": [0.7, 0.8] radius: 7, color: #a4c2f4, stroke-color: #3d64ba, stroke-width: 2px
    "๐ŸŽจ Community Modding": [0.85, 0.75] radius: 7, color: #a4c2f4, stroke-color: #3d64ba, stroke-width: 2px
    "๐Ÿค– AI-Driven Tutorials": [0.75, 0.85] radius: 7, color: #a4c2f4, stroke-color: #3d64ba, stroke-width: 2px
    "๐ŸŒฑ Ecosystem Partnerships": [0.65, 0.7] radius: 6, color: #a4c2f4, stroke-color: #3d64ba, stroke-width: 2px

    "๐Ÿ› ๏ธ Zero-Install Web App": [0.2, 0.8] radius: 7, color: #a2d2a4, stroke-color: #2c882c, stroke-width: 2px
    "โฑ Fast Iteration": [0.25, 0.75] radius: 6, color: #a2d2a4, stroke-color: #2c882c, stroke-width: 2px
    "๐Ÿ’ธ Reduced Operational Costs": [0.15, 0.85] radius: 6, color: #a2d2a4, stroke-color: #2c882c, stroke-width: 2px
    "๐Ÿš€ Immediate CDN Updates": [0.1, 0.7] radius: 7, color: #a2d2a4, stroke-color: #2c882c, stroke-width: 2px
    "๐ŸŒ Global Accessibility": [0.05, 0.9] radius: 6, color: #a2d2a4, stroke-color: #2c882c, stroke-width: 2px

    "๐ŸŒ€ No Persistence (Session-Only)": [0.2, 0.25] radius: 7, color: #f5a9a9, stroke-color: #aa3939, stroke-width: 2px
    "๐Ÿข Asset Load Latency": [0.3, 0.2] radius: 7, color: #f5a9a9, stroke-color: #aa3939, stroke-width: 2px
    "๐Ÿ“ด Limited Offline Play": [0.15, 0.3] radius: 6, color: #f5a9a9, stroke-color: #aa3939, stroke-width: 2px
    "๐ŸŒ Browser Compatibility": [0.25, 0.15] radius: 7, color: #f5a9a9, stroke-color: #aa3939, stroke-width: 2px
    "โš ๏ธ Memory/GC Spikes": [0.35, 0.1] radius: 6, color: #f5a9a9, stroke-color: #aa3939, stroke-width: 2px

    "๐ŸŒฉ๏ธ CDN Outages/Latency": [0.8, 0.3] radius: 7, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px
    "โš ๏ธ WebGL Deprecation": [0.7, 0.2] radius: 7, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px
    "๐Ÿ† Competitive Mobile Games": [0.75, 0.25] radius: 7, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px
    "๐Ÿ“‰ Tech Debt (State Complexity)": [0.9, 0.2] radius: 6, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px
    "๐Ÿ”’ CDN Security Risks": [0.85, 0.15] radius: 6, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px
    "๐ŸŒ Browser Standards Changes": [0.65, 0.25] radius: 6, color: #d5a6bd, stroke-color: #9b568a, stroke-width: 2px

Mindmap of Strengths

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐ŸŸข Strengths Q1 2026))
    id1(๐Ÿ› ๏ธ Zero-Install Web App)
      id1.1[Play immediatelyโ€”no download/sign-up]
      id1.2[Instant patching via static hosting]
      id1.3[High adoption barrier removed]
    id2(โฑ Fast Iteration)
      id2.1[Front-end only; no backend migrations]
      id2.2[Rapid prototyping & feature rollout]
      id2.3[Hot reloading in dev mode]
    id3(๐Ÿ’ธ Reduced Operational Costs)
      id3.1[No server infrastructure costs]
      id3.2[AWS CloudFront + S3 multi-region with GitHub Pages DR]
      id3.3[Minimal DevOps overhead]
    id4(๐Ÿš€ Immediate CDN Updates)
      id4.1[Push new animations & sounds instantly]
      id4.2[JSON/trigram data can update in real time]
      id4.3[Rapid asset iteration in production]
    id5(๐ŸŒ Global Accessibility)
      id5.1[Runs in any modern browser]
      id5.2[Cross-platform compatibility: desktop & mobile]
      id5.3[Low barrier to entry for users]
    id6(๐Ÿ”ถ Authentic Korean Martial Arts)
      id6.1[Deep I Ching philosophy - 8 trigrams complete]
      id6.2[70/70 vital points implemented - 100% complete]
      id6.3[Korean labels, audio, cultural immersion]
      id6.4[14 TCM meridians mapped, 127 medical references]
    id7(๐ŸŽต Rich Audio-Visual Experience)
      id7.1[Three.js 3D rendering with skeletal animation]
      id7.2[28-bone system with 7 hand poses]
      id7.3[Damage-based audio scaling - 87.38% line coverage]
      id7.4[1000+ particles at 60fps on desktop]
    id8(โš™๏ธ Modular Architecture)
      id8.1[Clear separation: Combat, Trigram, VitalPoint, Animation]
      id8.2[Reusable React + Three.js components]
      id8.3[Zustand slices for isolated state]
    id9(๐Ÿ”‘ Comprehensive Testing Framework)
      id9.1[73.73% overall test coverage]
      id9.2[95% coverage on new components]
      id9.3[Vitest unit + Cypress E2E tests]
      id9.4[73 production-ready pain/consciousness tests]
    id10(๐Ÿฅ‹ Combat Realism Foundation)
      id10.1[13/13 systems complete - 100% combat realism]
      id10.2[Production-ready pain/consciousness systems]
      id10.3[8 body part health tracking with bilingual labels]

Mindmap of Weaknesses

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐ŸŸ  Weaknesses Q1 2026))
    id1(๐ŸŒ€ No Persistence Session-Only)
      id1.1[All progress lost on refresh]
      id1.2[No saved unlocks or training logs]
      id1.3[Limited long-term engagement]
    id2(๐Ÿข Asset Load Latency)
      id2.1[Three.js bundle ~240KB gzipped]
      id2.2[3D models and textures loading time]
      id2.3[Initial loading screen 2.5-3.5 seconds]
    id3(๐Ÿ“ด Limited Offline Play)
      id3.1[Without service workers, no offline mode]
      id3.2[Users with spotty connectivity struggle]
      id3.3[No cached game state]
    id4(๐ŸŒ Browser Compatibility)
      id4.1[WebGL 2 required for Three.js]
      id4.2[Web Audio API support varies]
      id4.3[Mobile browser performance gaps]
    id5(โš ๏ธ Memory/GC Concerns)
      id5.1[Three.js objects need manual disposal]
      id5.2[Skeletal animation memory overhead - 180MB desktop]
      id5.3[Particle systems can spike memory - 1000+ particles]
    id6(โš™๏ธ Combat Realism Systems)
      id6.1[13/13 systems complete - 100%]
      id6.2[4 systems remaining: trauma visualization, balance, HUD, movement]
      id6.3[1 system partially implemented: bone impact audio - mapping + selection complete, asset coverage/final mix pending]
    id7(โŒ Incomplete Features)
      id7.1[Techniques not yet stance-specific - 4 per archetype vs 3-5 per stance]
      id7.2[EndScreen3D implemented but missing final UX polish - detailed stats, meta-progression hooks]
      id7.3[Training mode limited scope]
    id8(๐Ÿ“ฑ Mobile Performance)
      id8.1[30-45fps on mobile devices - meeting 30fps baseline target]
      id8.2[Complex 3D rendering challenges]
      id8.3[Touch controls need refinement]
    id9(๐Ÿ› ๏ธ Test Coverage Gaps)
      id9.1[73.73% overall test coverage - target: 80%]
      id9.2[Some legacy components <80% coverage]
      id9.3[Combat realism systems integration tests incomplete]

Mindmap of Opportunities

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐Ÿ”ต Opportunities Q1 2026))
    id1(๐Ÿ’ก PWA & Offline Caching)
      id1.1[Implement service workers for Three.js asset caching]
      id1.2[Cache 3D models & textures for offline play]
      id1.3[Persistence via IndexedDB for vital point progress]
    id2(๐Ÿ“ฑ Mobile-First UX)
      id2.1[Optimize to 60fps for mobile devices]
      id2.2[Adaptive 3D rendering quality for devices]
      id2.3[Accelerometer-based stance changes]
      id2.4[Simplified 20-bone skeleton for mobile]
    id3(๐ŸŽจ Community Modding)
      id3.1[Allow custom 3D character models]
      id3.2[Community-created technique animations]
      id3.3[User-generated training scenarios]
    id4(๐Ÿค– AI-Driven Tutorial Modules)
      id4.1[AI coach analyzing vital point accuracy]
      id4.2[Real-time feedback on skeletal animation form]
      id4.3[Adaptive difficulty based on combat performance]
    id5(๐ŸŒฑ Martial Arts Education Market)
      id5.1[STEM gamification of traditional martial arts]
      id5.2[Korean Wave ํ•œ๋ฅ˜ global interest timing]
      id5.3[Partnerships with taekwondo schools]
    id6(๐Ÿ”ง VR/AR Integration)
      id6.1[WebXR support for immersive vital point training]
      id6.2[AR overlay for real-world practice]
      id6.3[VR dojang environment with Korean aesthetics]
    id7(โš™๏ธ Complete Combat Realism)
      id7.1[Complete remaining 4/12 systems in Q2 2026]
      id7.2[Integrate trauma visualization with injury tracking]
      id7.3[Implement bone impact audio system]
      id7.4[Achieve 100% combat realism completion]
    id8(๐Ÿ“š E-Learning Certification)
      id8.1[Structured trigram theory courses]
      id8.2[Vital point mastery certification]
      id8.3[Korean martial arts digital badges]
    id9(๐ŸŒ Global Localization)
      id9.1[Multi-language support - KR, EN, JP, CN]
      id9.2[Localized Korean terminology by region]
      id9.3[Cultural context adaptation]

Mindmap of Threats

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐Ÿ”ด Threats Q1 2026))
    id1(๐ŸŒฉ๏ธ CDN Outages / Latency)
      id1.1[Audio CDN or 3D model CDN downtime]
      id1.2[High global latency affects Three.js loading]
      id1.3[Single region CDN cold starts]
    id2(โš ๏ธ Three.js / WebGL Evolution)
      id2.1[Three.js API breaking changes in future versions]
      id2.2[WebGL 3 transition requirements]
      id2.3[Mobile browser WebGL 2 limitations]
    id3(๐Ÿ† Competitive Market)
      id3.1[Native mobile martial arts games with AAA graphics]
      id3.2[Lower-latency native rendering]
      id3.3[Established martial arts franchises]
    id4(๐Ÿ“‰ Technical Debt)
      id4.1[Three.js object disposal complexity]
      id4.2[Combat realism systems 100% complete 13 of 13]
      id4.3[State management complexity growing]
      id4.4[73.73% test coverage below 80% target]
    id5(๐Ÿ”’ CDN Security Risks)
      id5.1[MITM attacks on Three.js CDN]
      id5.2[Compromised 3D model hosting]
      id5.3[Subresource Integrity validation needed]
    id6(๐ŸŒ Browser Standards Changes)
      id6.1[Web Audio API deprecations]
      id6.2[WebGL context loss handling]
      id6.3[New security policies - CORS, CSP]
    id7(๐ŸŽฎ Player Retention)
      id7.1[No persistence reduces engagement]
      id7.2[Lack of progression system]
      id7.3[Session-only gameplay limits depth]
    id8(๐Ÿ’ฐ Monetization Limits)
      id8.1[No backend for payment processing]
      id8.2[Difficult to track premium features]
      id8.3[Limited incentive for continued development]
    id9(๐ŸŒ Cultural Sensitivity)
      id9.1[Misrepresentation of Korean culture risk]
      id9.2[Inappropriate use of traditional symbols]
      id9.3[Need cultural consultant validation]
    id10(๐Ÿ“ฑ Mobile Performance Gap)
      id10.1[30-45fps on mobile vs 60fps desktop]
      id10.2[Device fragmentation challenges]
      id10.3[Battery consumption concerns]
id6(๐Ÿ“ถ Browser Standards Evolution)
  id6.1[Changes to ES modules affect bundling]
  id6.2[New security policies - CORS, CSP]
  id6.3[Deprecated features in future standards]
id7(๐ŸŽฎ Player Retention Challenges)
  id7.1[Without persistence, limited engagement]
  id7.2[Lack of progression incentives]
  id7.3[Session-only gameplay limits depth]
id8(๐Ÿ’ฐ Monetization Limitations)
  id8.1[No backend for payment processing]
  id8.2[Limited ability to track purchases]
  id8.3[Difficult to implement premium features]
id9(๐ŸŒ Cultural Sensitivity Issues)
  id9.1[Misrepresentation of Korean culture]
  id9.2[Inappropriate use of traditional symbols]
  id9.3[Lack of cultural consultant validation]

---

## ๐ŸŽฏ Core Game Concepts

### Player Archetypes & Combat Philosophy

```mermaid
%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐Ÿฅ‹ Black Trigram Core))
    id1[๐ŸŽฎ Player Archetypes]
      id1.1[๋ฌด์‚ฌ Musa - Traditional Warrior]
        id1.1.1[Honor-bound combat]
        id1.1.2[Balanced techniques]
        id1.1.3[Strong fundamentals]
      id1.2[์•”์‚ด์ž Amsalja - Shadow Assassin]
        id1.2.1[Precision strikes]
        id1.2.2[Stealth mechanics]
        id1.2.3[Critical damage focus]
      id1.3[ํ•ด์ปค Hacker - Cyber Warrior]
        id1.3.1[Tech-enhanced combat]
        id1.3.2[Digital disruption]
        id1.3.3[Augmented abilities]
      id1.4[์ •๋ณด์š”์› Jeongbo - Intelligence Op]
        id1.4.1[Analytical combat]
        id1.4.2[Predictive strikes]
        id1.4.3[Tactical advantage]
      id1.5[์กฐ์งํญ๋ ฅ๋ฐฐ Jojik - Crime Fighter]
        id1.5.1[Brutal efficiency]
        id1.5.2[Street techniques]
        id1.5.3[Overwhelming force]
    id2[โ˜ฏ๏ธ Eight Trigrams]
      id2.1[โ˜ฐ ๊ฑด Geon - Heaven]
        id2.1.1[Direct strikes]
        id2.1.2[Overwhelming power]
      id2.2[โ˜ฑ ํƒœ Tae - Lake]
        id2.2.1[Fluid movements]
        id2.2.2[Joint manipulation]
      id2.3[โ˜ฒ ๋ฆฌ Li - Fire]
        id2.3.1[Nerve strikes]
        id2.3.2[Burning techniques]
      id2.4[โ˜ณ ์ง„ Jin - Thunder]
        id2.4.1[Explosive attacks]
        id2.4.2[Sudden impacts]
      id2.5[โ˜ด ์† Son - Wind]
        id2.5.1[Continuous pressure]
        id2.5.2[Rapid combos]
      id2.6[โ˜ต ๊ฐ Gam - Water]
        id2.6.1[Adaptive defense]
        id2.6.2[Flow counters]
      id2.7[โ˜ถ ๊ฐ„ Gan - Mountain]
        id2.7.1[Immovable defense]
        id2.7.2[Counter strikes]
      id2.8[โ˜ท ๊ณค Gon - Earth]
        id2.8.1[Grounding attacks]
        id2.8.2[Takedown focus]
    id3[๐ŸŽฏ Vital Points]
      id3.1[Critical Points]
        id3.1.1[Instant KO potential]
        id3.1.2[x5.0 damage multiplier]
      id3.2[Secondary Points]
        id3.2.1[Major damage]
        id3.2.2[x3.0 damage multiplier]
      id3.3[Standard Points]
        id3.3.1[Basic damage]
        id3.3.2[x1.5 damage multiplier]
    id4[โšก Resources]
      id4.1[โค๏ธ Health]
        id4.1.1[100 HP per fighter]
        id4.1.2[No regeneration]
      id4.2[๐Ÿ’ช Stamina]
        id4.2.1[Physical actions]
        id4.2.2[Slow regeneration]
      id4.3[๐Ÿ”ต Ki Energy]
        id4.3.1[Special techniques]
        id4.3.2[Stance transitions]

๐Ÿ—๏ธ Architecture Concepts

System Architecture Layers

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
mindmap
  root((๐Ÿ—๏ธ Architecture))
    id1[๐Ÿ–ฅ๏ธ Presentation Layer]
      id1.1[React Components]
        id1.1.1[Screens]
        id1.1.2[HUD Elements]
        id1.1.3[Controls]
      id1.2[Three.js 3D Rendering]
        id1.2.1[3D Models]
        id1.2.2[Particles]
        id1.2.3[Skeletal Animations]
      id1.3[UI/UX Design]
        id1.3.1[Korean Typography]
        id1.3.2[Cyberpunk Theme]
        id1.3.3[Responsive Layout]

    id2[โš™๏ธ Business Logic]
      id2.1[Combat System]
        id2.1.1[Damage Calculation]
        id2.1.2[Hit Detection]
        id2.1.3[Combat Flow]
      id2.2[Trigram System]
        id2.2.1[Stance Management]
        id2.2.2[Transitions]
        id2.2.3[Techniques]
      id2.3[Vital Point System]
        id2.3.1[Anatomy Mapping]
        id2.3.2[Multipliers]
        id2.3.3[Effects]

    id3[๐Ÿ—„๏ธ State Management]
      id3.1[Zustand Stores]
        id3.1.1[Game State]
        id3.1.2[UI State]
        id3.1.3[Enemy State]
      id3.2[React Context]
        id3.2.1[Audio Context]
        id3.2.2[Theme Context]
      id3.3[Session Storage]
        id3.3.1[Temporary Data]
        id3.3.2[Settings]

    id4[๐Ÿ“ฆ Asset Management]
      id4.1[Three.js Loaders]
        id4.1.1[Texture Loading]
        id4.1.2[3D Model Loading]
      id4.2[Audio System]
        id4.2.1[Howler.js]
        id4.2.2[Web Audio API]
      id4.3[Data Loading]
        id4.3.1[JSON Import]
        id4.3.2[Dynamic Loading]

    id5[๐Ÿ”ง Infrastructure]
      id5.1[Build System]
        id5.1.1[Vite]
        id5.1.2[TypeScript]
        id5.1.3[ESBuild]
      id5.2[Testing]
        id5.2.1[Vitest]
        id5.2.2[React Testing Library]
        id5.2.3[Cypress]
      id5.3[Deployment]
        id5.3.1[Static Hosting]
        id5.3.2[CDN Distribution]
        id5.3.3[CI/CD Pipeline]

๐Ÿ”„ UX Flow

User Journey Through Game

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
flowchart TD
    Start(["๐ŸŽฎ Game Load"]) --> Loading["โณ Loading Assets"]
    Loading --> Intro["๐Ÿฎ Intro Screen"]

    Intro --> |New Game| CharSelect["๐Ÿ‘ค Archetype Selection"]
    Intro --> |Training| Training["๐ŸŽฏ Training Mode"]
    Intro --> |Settings| Settings["โš™๏ธ Settings Menu"]

    CharSelect --> Combat["โš”๏ธ Combat Arena"]
    Training --> VitalPractice["๐ŸŽฏ Vital Point Practice"]
    Training --> StancePractice["โ˜ฏ๏ธ Stance Training"]

    Combat --> |Victory| Victory["๐Ÿ† Victory Screen"]
    Combat --> |Defeat| Defeat["๐Ÿ’€ Defeat Screen"]
    Combat --> |Pause| PauseMenu["โธ๏ธ Pause Menu"]

    Victory --> Intro
    Defeat --> Intro
    PauseMenu --> |Resume| Combat
    PauseMenu --> |Quit| Intro

    VitalPractice --> |Exit| Training
    StancePractice --> |Exit| Training
    Training --> |Back| Intro
    Settings --> |Back| Intro

    %% Styling
    classDef screenNode fill:#FFD700,stroke:#333,stroke-width:2px,color:#000
    classDef actionNode fill:#00FFD0,stroke:#333,stroke-width:2px,color:#000
    classDef menuNode fill:#FF6B6B,stroke:#333,stroke-width:2px,color:#000

    class Intro,CharSelect,Combat,Victory,Defeat,Training,Settings screenNode
    class Loading,VitalPractice,StancePractice actionNode
    class PauseMenu menuNode

๐Ÿ”„ Combat Mechanics & Data Relationships

Combat System Data Flow

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TB
    subgraph "๐ŸŽฎ Input Layer"
        KI[Keyboard Input]
        MI[Mouse Input]
        TI[Touch Input]
    end

    subgraph "โš™๏ธ Combat Engine"
        IS[Input System]
        SM[Stance Manager]
        TC[Technique Calculator]
        HD[Hit Detection]
        DC[Damage Calculator]
        ES[Effect System]
    end

    subgraph "๐Ÿ“Š Game State"
        PS[Player State]
        ES2[Enemy State]
        CS[Combat State]
    end

    subgraph "๐ŸŽจ Rendering"
        VS[Visual System]
        AS[Audio System]
        PS2[Particle System]
    end

    KI --> IS
    MI --> IS
    TI --> IS

    IS --> SM
    SM --> TC
    TC --> HD
    HD --> DC
    DC --> ES

    SM <--> PS
    DC <--> ES2
    ES <--> CS

    CS --> VS
    CS --> AS
    CS --> PS2

    %% Styling
    classDef inputClass fill:#87CEFA,stroke:#333,stroke-width:2px
    classDef engineClass fill:#00FFD0,stroke:#333,stroke-width:2px
    classDef stateClass fill:#FFD700,stroke:#333,stroke-width:2px
    classDef renderClass fill:#FF6B6B,stroke:#333,stroke-width:2px

    class KI,MI,TI inputClass
    class IS,SM,TC,HD,DC,ES engineClass
    class PS,ES2,CS stateClass
    class VS,AS,PS2 renderClass

Trigram Advantage Matrix

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph LR
    subgraph "โ˜ฏ๏ธ Trigram Relationships"
        G["โ˜ฐ ๊ฑด Geon"]
        T["โ˜ฑ ํƒœ Tae"]
        L["โ˜ฒ ๋ฆฌ Li"]
        J["โ˜ณ ์ง„ Jin"]
        S["โ˜ด ์† Son"]
        GM["โ˜ต ๊ฐ Gam"]
        GN["โ˜ถ ๊ฐ„ Gan"]
        K["โ˜ท ๊ณค Gon"]
    end

    %% Advantage relationships (โ†’ means "has advantage over")
    G -->|Power > Fluid| T
    T -->|Fluid > Fire| L
    L -->|Fire > Thunder| J
    J -->|Thunder > Wind| S
    S -->|Wind > Water| GM
    GM -->|Water > Mountain| GN
    GN -->|Mountain > Earth| K
    K -->|Earth > Heaven| G

    %% Defensive advantages (โ‡ข means "defends well against")
    G -.->|Blocks Earth| K
    GN -.->|Blocks Water| GM
    GM -.->|Blocks Wind| S

    %% Style colors
    style G fill:#FFD700,stroke:#333,stroke-width:3px
    style T fill:#87CEEB,stroke:#333,stroke-width:3px
    style L fill:#FF6347,stroke:#333,stroke-width:3px
    style J fill:#FF1493,stroke:#333,stroke-width:3px
    style S fill:#98FB98,stroke:#333,stroke-width:3px
    style GM fill:#4682B4,stroke:#333,stroke-width:3px
    style GN fill:#8B4513,stroke:#333,stroke-width:3px
    style K fill:#D2691E,stroke:#333,stroke-width:3px

๐Ÿ“ˆ Performance Optimization Strategy

Resource Loading Pipeline

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#455A64','secondaryColor':'#4CAF50','tertiaryColor':'#FF9800','actorBkg':'#1565C0','actorTextColor':'#fff','actorLineColor':'#455A64','signalColor':'#455A64','signalTextColor':'#fff','noteBkgColor':'#FFD600','noteTextColor':'#000','noteBorderColor':'#F57F17'}}}%%
sequenceDiagram
    participant B as Browser
    participant L as Asset Loader
    participant CDN as CDN Servers
    participant C as Cache
    participant G as Game Engine

    B->>L: Initialize game
    L->>C: Check local cache

    alt Assets cached
        C-->>L: Return cached assets
    else Assets not cached
        L->>CDN: Request assets
        CDN-->>L: Stream assets
        L->>C: Store in cache
    end

    L->>G: Assets ready
    G->>B: Start game

    Note over B,G: Lazy load non-critical assets during gameplay

Memory Management Strategy

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TD
    subgraph "๐Ÿง  Memory Pools"
        PP[Particle Pool<br/>Pre-allocated: 1000]
        DP[Damage Number Pool<br/>Pre-allocated: 50]
        EP[Effect Pool<br/>Pre-allocated: 100]
    end

    subgraph "โ™ป๏ธ Object Lifecycle"
        CR[Create/Reset]
        US[Use in Scene]
        RE[Return to Pool]
    end

    subgraph "๐Ÿ—‘๏ธ Garbage Collection Mitigation"
        RA[Reuse Allocations]
        PO[Pool Objects]
        LG[Limit Generation]
    end

    PP --> CR
    DP --> CR
    EP --> CR

    CR --> US
    US --> RE
    RE --> PP
    RE --> DP
    RE --> EP

    RA --> PO
    PO --> LG

    style PP fill:#A5D6A7,stroke:#333,stroke-width:2px
    style DP fill:#81C784,stroke:#333,stroke-width:2px
    style EP fill:#66BB6A,stroke:#333,stroke-width:2px

๐Ÿ”’ Security Considerations

Frontend Security Architecture

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TB
    subgraph "๐Ÿ›ก๏ธ Security Layers"
        CSP[Content Security Policy]
        SRI[Subresource Integrity]
        CORS[CORS Headers]
        VAL[Input Validation]
    end

    subgraph "๐Ÿ” Asset Security"
        HTTPS[HTTPS Only CDN]
        SIGN[Signed Assets]
        HASH[Asset Hashing]
    end

    subgraph "๐Ÿšซ Attack Mitigation"
        XSS[XSS Prevention]
        CSRF[CSRF Protection]
        INJ[Injection Prevention]
    end

    CSP --> XSS
    SRI --> SIGN
    CORS --> HTTPS
    VAL --> INJ

    HTTPS --> HASH
    SIGN --> HASH

    style CSP fill:#FF6B6B,stroke:#333,stroke-width:2px
    style HTTPS fill:#FFD700,stroke:#333,stroke-width:2px
    style XSS fill:#87CEEB,stroke:#333,stroke-width:2px

๐Ÿš€ Deployment Architecture

CI/CD Pipeline

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph LR
    subgraph "๐Ÿ”ง Development"
        DEV[Local Dev]
        TEST[Test Suite]
    end

    subgraph "๐Ÿ—๏ธ Build Pipeline"
        GH[GitHub Actions]
        BUILD[Vite Build]
        OPT[Optimization]
    end

    subgraph "๐Ÿ“ฆ Distribution"
        CDN1[Asset CDN]
        CDN2[App CDN]
        CACHE[Edge Cache]
    end

    subgraph "๐ŸŒ Global Delivery"
        US[US Servers]
        EU[EU Servers]
        ASIA[Asia Servers]
    end

    DEV --> TEST
    TEST --> GH
    GH --> BUILD
    BUILD --> OPT

    OPT --> CDN1
    OPT --> CDN2

    CDN1 --> CACHE
    CDN2 --> CACHE

    CACHE --> US
    CACHE --> EU
    CACHE --> ASIA

    style GH fill:#24292E,stroke:#fff,stroke-width:2px,color:#fff
    style CDN1 fill:#FF9500,stroke:#333,stroke-width:2px
    style CACHE fill:#00C851,stroke:#333,stroke-width:2px

๐Ÿ“Š Metrics & Monitoring

Performance Monitoring Dashboard

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TD
    subgraph "๐Ÿ“ˆ Client Metrics"
        FPS[FPS Counter]
        MEM[Memory Usage]
        LAT[Input Latency]
        LOAD[Asset Load Time]
    end

    subgraph "๐Ÿ“Š Game Metrics"
        DMG[Damage Dealt]
        ACC[Hit Accuracy]
        COMBO[Combo Success]
        TIME[Session Duration]
    end

    subgraph "๐Ÿ” Analytics"
        GA[Google Analytics]
        CUSTOM[Custom Events]
        ERROR[Error Tracking]
    end

    FPS --> GA
    MEM --> GA
    LAT --> CUSTOM
    LOAD --> CUSTOM

    DMG --> CUSTOM
    ACC --> CUSTOM
    COMBO --> CUSTOM
    TIME --> GA

    GA --> ERROR
    CUSTOM --> ERROR

    style FPS fill:#4CAF50,stroke:#333,stroke-width:2px
    style GA fill:#FFA726,stroke:#333,stroke-width:2px
    style ERROR fill:#EF5350,stroke:#333,stroke-width:2px

๐ŸŽฎ Future Architecture Considerations

Potential Backend Integration

%%{init: {'theme':'base', 'themeVariables': {'primaryColor':'#2979FF','primaryTextColor':'#fff','primaryBorderColor':'#0D47A1','lineColor':'#00C853','secondaryColor':'#FFD600','tertiaryColor':'#FF3D00'}}}%%
graph TD
    subgraph "Current: Frontend Only"
        FE[React + Three.js]
        LOCAL[Local State]
        CDN[Static CDN]
    end

    subgraph "Future: Optional Backend"
        API[REST API]
        DB[Database]
        AUTH[Authentication]
        LEAD[Leaderboards]
        SAVE[Save Games]
    end

    FE -.->|Future Integration| API
    LOCAL -.->|Sync| DB
    CDN -.->|Dynamic Assets| API

    API --> AUTH
    API --> LEAD
    API --> SAVE

    style FE fill:#61DAFB,stroke:#333,stroke-width:2px
    style API fill:#FF6B6B,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5
    style DB fill:#336791,stroke:#333,stroke-width:2px,stroke-dasharray: 5 5

๐Ÿ“ Architecture Decision Records (ADRs)

ADR-001: Frontend-Only Architecture

Status: Accepted
Date: 2024-01-01
Context: Need to minimize operational complexity and maximize accessibility
Decision: Build as purely frontend application with no backend dependencies
Consequences:

  • โœ… Zero server costs
  • โœ… Instant deployment
  • โœ… No database management
  • โŒ No persistence
  • โŒ Limited multiplayer options

ADR-002: React + Three.js Integration

Status: Accepted
Date: 2024-01-01
Context: Need powerful 3D rendering with modern React development
Decision: Use @react-three/fiber for seamless Three.js integration
Consequences:

  • โœ… Best of both worlds (React + Three.js)
  • โœ… Strong ecosystem (@react-three/drei helpers)
  • โœ… Type safety with TypeScript
  • โœ… Declarative 3D scene graph
  • โŒ Learning curve for Three.js concepts
  • โŒ Bundle size considerations

ADR-003: Zustand for State Management

Status: Accepted
Date: 2024-01-01
Context: Need lightweight state management without Redux complexity
Decision: Use Zustand for all global state
Consequences:

  • โœ… Minimal boilerplate
  • โœ… TypeScript friendly
  • โœ… DevTools support
  • โŒ Less ecosystem than Redux
  • โŒ Need custom persistence layer

๐Ÿ Conclusion (Q1 2026)

Black Trigram's architecture represents a modern approach to browser-based gaming, leveraging Three.js 3D rendering and React 19 while maintaining simplicity through its frontend-only design. The Q1 2026 implementation demonstrates the successful completion of the Three.js migration, with 70/70 vital points implemented (100% complete), a comprehensive 28-bone skeletal animation system, and 73.73% test coverage.

Key Architectural Strengths (Q1 2026):

  • Three.js Migration Complete: Modern 3D rendering with @react-three/fiber and @react-three/drei (60fps desktop, 30-45fps mobile with optimization ongoing)
  • Authentic Korean Martial Arts: 70/70 vital points (100% complete with 14 TCM meridians, 127 medical references), 8 trigram stances, 5 player archetypes with Korean names (๋ฌด์‚ฌ, ์•”์‚ด์ž, ํ•ด์ปค, ์ •๋ณด์š”์›, ์กฐ์งํญ๋ ฅ๋ฐฐ)
  • Advanced Animation System: 28-bone skeletal hierarchy, 7 hand poses with Korean terminology (์ฃผ๋จน, ์ˆ˜๋„, ๊ด€์ˆ˜, ์žฅ๋ ฅ, ์žก๊ธฐ, ํŽด๊ธฐ, ํœด์‹), muscle tension visualization (0.0-1.0 intensity mapping)
  • Combat Realism Foundation: 13/13 systems complete (100%) including production-ready pain/consciousness (73 tests), body part health, vital point targeting, enhanced anatomy, visual feedback, breathing disruption (75%)
  • High Test Coverage: 73.73% overall, with detailed coverage reporting for all core systems (Vitest unit + Cypress E2E, see docs/coverage/coverage-summary.json)
  • Zero Backend Complexity: Pure frontend eliminates server management costs
  • Modular Design: Clear separation of systems/ (combat, trigram, vitalpoint, animation, pain, consciousness, breathing), components/, data/, types/
  • Performance Optimized: Three.js instancing (1000+ particles), object pooling, geometry/material reuse, automatic frustum culling, skeletal animation (28 bones vs thousands of vertices)
  • Developer Friendly: TypeScript strict mode, React 19, comprehensive testing framework (73 pain/consciousness tests production-ready)

Current Status & Metrics (Q1 2026):

  • Overall Rating: 9.4/10 (Production-Ready - Combat Realism 100% Complete)
  • Vital Points: 70/70 implemented (100% complete) - up from 4.3% in 2024
  • Skeletal Animation: 28-bone system operational, 7 hand poses functional
  • Test Coverage: 73.73% overall, 87.38% audio system line coverage, 73 pain/consciousness tests
  • Performance: 60fps desktop (โœ… met), 30-45fps mobile (โš ๏ธ optimization ongoing)
  • Bundle Size: ~240KB gzipped (Three.js vendor chunk)
  • Memory: 180MB desktop, 150MB mobile
  • Combat Realism: 13/13 systems complete (100%), production-ready pain/consciousness with comprehensive tests

Areas for Q2 2026 Enhancement:

  • Combat Realism Completion: Complete remaining 4/12 systems (trauma visualization, balance/vulnerability, combat readiness HUD, injury-based movement) + finalize bone impact audio pipeline (BoneImpactAudioMap + useCombatAudio integrated; remaining work: asset coverage expansion and final mix/tuning)
  • Mobile Performance: Optimize to achieve consistent 30fps baseline on mobile devices (currently 30-45fps; stretch goal: 60fps)
  • Technique Expansion: Expand from 4 techniques/archetype to 3-5 techniques/stance (24-40 total)
  • EndScreen UX & Flow Enhancements: Improve EndScreen3D UX (results presentation, bilingual Korean/English copy, audio/visual polish), add replay/rematch flow and analytics/telemetry hooks while keeping the existing Intro โ†’ Combat โ†’ End wiring
  • Persistence Layer: Optional IndexedDB/localStorage for vital point progress and training logs
  • VR/AR Integration: WebXR support for immersive vital point training with skeletal animation
  • Advanced Analytics: Vital point targeting heatmaps, combat effectiveness metrics, skeletal animation quality scoring
  • Content Expansion: Additional training scenarios, difficulty progression, AI enhancements, stance-specific techniques

The Q1 2026 architecture successfully demonstrated the feasibility of authentic Korean martial arts simulation in the browser, and Q2 2026 has shipped the full combat realism stack (13/13 = 100%) along with mobile performance hitting 55fps+ (targeting sustained 60fps).

Key Q1 2026 Achievements:

  • โœ… 70/70 vital points complete (100%) with TCM meridians
  • โœ… 28-bone skeletal animation system operational
  • โœ… 13/13 combat realism systems complete (100%)
  • โœ… Production-ready pain/consciousness with 73 tests
  • โœ… 73.73% test coverage (from docs/coverage/coverage-summary.json)
  • โœ… 60fps desktop performance maintained
  • โš ๏ธ Mobile optimization to 60fps (Q2 2026 priority)

ํ‘๊ด˜์˜ ๊ธธ์„ ๊ฑธ์–ด๋ผ - Walk the Path of the Black Trigram


๐Ÿ” ISMS Policies

๐Ÿ›ก๏ธ Black Trigram Documentation


๐Ÿ“‹ Document Control:
โœ… Approved by: James Pether Sรถrling, CEO
๐Ÿ“ค Distribution: Public
๐Ÿท๏ธ Classification: Confidentiality: Public Integrity: Moderate Availability: Standard
๐Ÿ“… Effective Date: 2026-04-21
โฐ Next Review: 2026-10-21
๐ŸŽฏ Framework Compliance: ISO 27001 NIST CSF 2.0 CIS Controls