# Eternal Realm (永恒之域) - Game Systems Design Document

**Version:** 1.0
**Date:** 2026-03-24
**Engine:** Three.js / WebGL (HTML5)
**Genre:** Open-World 3D Action RPG

---

## 1. Executive Summary

**Eternal Realm (永恒之域)** is an open-world 3D action RPG built entirely on web technologies, targeting modern browsers through Three.js and WebGL 2.0. The game draws deep inspiration from *The Elder Scrolls V: Skyrim* while carving its own identity through a martial-arts-infused combat system, a deeply interconnected crafting economy, and a world steeped in Eastern and Western mythological fusion. The target audience is core RPG players aged 16-40 who value exploration, character build diversity, and emergent gameplay, but who may not have access to a dedicated gaming PC or console. By delivering a AAA-inspired RPG experience in the browser, Eternal Realm removes the installation barrier entirely.

**Core Design Pillars:**

1. **Freedom (自由):** The player is never locked into a single path. Every quest has multiple resolution strategies, every build is viable through endgame, and the open world can be explored in any order after the tutorial zone. Non-linear progression is not merely permitted; it is actively rewarded through discovery-based XP bonuses and hidden content that only divergent explorers will find.

2. **Depth (深度):** Systems are easy to learn but reward mastery. The combat system offers simple light/heavy attack chains for casual players, but frame-perfect parries, elemental combo exploitation, and stance-switching unlock an entirely different tier of play. The crafting system similarly scales from simple recipe-following to deep min-maxing of material properties and enchantment stacking.

3. **Immersion (沉浸):** Despite the technical constraints of a browser-based engine, Eternal Realm prioritizes atmosphere. A dynamic weather system, a full day/night cycle with NPC schedules, ambient wildlife, and a reactive soundtrack all contribute to a world that feels alive. Dialogue is text-based with portrait art, allowing for rich branching narratives without the bandwidth cost of full voice acting.

**What Sets Eternal Realm Apart from Skyrim:**

While Skyrim provides the foundational template of an open-world first/third-person RPG with freeform character building, Eternal Realm diverges in several key areas. First, the combat system is significantly more action-oriented, incorporating a stamina-based combo system, directional blocking, and a stance mechanic that is absent in Skyrim's relatively simple swing-and-block model. Second, the magic system uses a school-based attunement model where specializing in one school unlocks cross-school synergies, rather than Skyrim's flat skill-level gating. Third, the crafting economy is fully closed-loop: every material can be sourced, every crafted item can be deconstructed, and the player economy is designed to avoid the runaway gold inflation that plagues late-game Skyrim. Finally, as a browser game, Eternal Realm is designed for session-based play with robust auto-save, cloud sync, and a UI optimized for both mouse/keyboard and touch input. The game targets 30 FPS on mid-range hardware (integrated GPUs from 2022 onward) and 60 FPS on dedicated GPUs, with aggressive LOD management and a draw call budget of under 500 per frame.

---

## 2. Combat System

### 2.1 Melee Combat

Melee combat in Eternal Realm is built on a responsive, stamina-governed action system that rewards timing and positioning over button mashing. The system supports one-handed weapons (swords, axes, maces), two-handed weapons (greatswords, warhammers, halberds), and dual-wielding configurations.

**Light and Heavy Attacks:**

Every melee weapon has a light attack chain and a heavy attack. Light attacks are fast, low-cost actions that chain into combos of up to 4 hits. Each hit in the chain increases damage slightly but also increases recovery frames, creating a natural risk/reward curve. Heavy attacks are charged actions (hold attack button for 0.4s-1.2s depending on weapon type) that deal 2.0x-3.5x base damage and have innate stagger properties.

| Attack Type | Stamina Cost | Damage Multiplier | Recovery Frames | Chain Length |
|---|---|---|---|---|
| Light 1 | 8 | 1.0x | 12 | - |
| Light 2 | 10 | 1.1x | 14 | From Light 1 |
| Light 3 | 12 | 1.2x | 18 | From Light 2 |
| Light 4 (Finisher) | 15 | 1.5x | 24 | From Light 3 |
| Heavy (min charge) | 20 | 2.0x | 30 | Any |
| Heavy (max charge) | 35 | 3.5x | 36 | Any |

Stamina costs are defined in `data/combat/melee_config.json` and are modified by weapon weight. A weapon with weight 12 applies a `weight_factor = 1 + (weight - 10) * 0.03`, so a weight-12 weapon increases all stamina costs by 6%.

**Combo System:**

Beyond the basic light chain, players unlock combo routes through the Combat skill tree. A combo route is a specific input sequence (e.g., Light-Light-Heavy, or Light-Dodge-Light) that triggers a unique animation with bonus effects. Combo routes are stored in `data/combat/combo_routes.json` as state-machine transitions:

```json
{
  "combo_id": "whirlwind_slash",
  "weapon_class": "one_handed_sword",
  "input_sequence": ["light", "light", "dodge_cancel", "heavy"],
  "damage_multiplier": 2.8,
  "stamina_cost": 45,
  "effects": ["aoe_cone_120deg", "bleed_apply"],
  "unlock_perk": "sword_mastery_3"
}
```

**Blocking and Parrying:**

Blocking is performed by holding the block input, which raises the equipped shield or weapon. While blocking, incoming melee damage is reduced by the block value of the item (shields: 40-85%, weapons: 15-35%). Blocking drains stamina proportional to the incoming damage: `stamina_drain = incoming_damage * (1 - block_efficiency) * 0.5`. If stamina reaches zero while blocking, the player enters a "guard break" stagger lasting 45 frames (0.75 seconds at 60 FPS).

Parrying is a precision mechanic. The parry window opens during the first 6 frames (100ms) of a block initiation. A successful parry negates all damage, staggers the attacker for 60 frames, and opens a riposte window that grants a guaranteed critical hit. The parry window can be expanded to 9 frames (150ms) through the "Iron Reflexes" perk and to 12 frames (200ms) through the legendary "Timeless Guardian" shield enchantment.

**Dodge and Roll System:**

Dodging costs 20 stamina and moves the player 3 meters in the input direction over 18 frames. The dodge grants invincibility frames (i-frames) during frames 3-12 (a 150ms window). During the i-frame window, all incoming damage sources are ignored, including area-of-effect spells and environmental hazards. The i-frame window can be extended to frames 2-14 (200ms) with the "Shadow Step" perk from the Evasion tree. Rolling (triggered by dodging while sprinting) covers 5 meters over 24 frames, with i-frames on frames 4-16.

The dodge system has a cooldown of 6 frames after the dodge animation completes, preventing dodge-spam. This cooldown is reduced to 3 frames with the "Fleet Footed" perk. Dodge direction is determined by movement input; if no direction is held, the player backsteps.

**Stance System:**

Players can switch between two melee stances: Aggressive (攻势) and Defensive (守势). Aggressive stance increases damage by 15% but reduces block efficiency by 20% and increases stamina costs by 10%. Defensive stance reduces damage by 10% but increases block efficiency by 15%, reduces parry window requirements by 2 frames, and reduces dodge stamina cost by 25%. Stance switching is instant and can be performed mid-combo, allowing skilled players to weave offensive and defensive moments fluidly.

### 2.2 Ranged Combat

Ranged combat encompasses bows, crossbows, and thrown weapons. Each category fills a distinct tactical niche and integrates tightly with the stealth system.

**Bow Mechanics:**

Bows use a draw-and-release system. Drawing a bow takes 0.6s-1.2s depending on bow type (shortbow vs. longbow). Damage scales linearly with draw time: a 50% draw deals 50% of maximum arrow damage. At full draw, the player can hold for up to 3 seconds before arm fatigue sets in, causing increasing aim sway (camera shake amplitude increases by 0.5 degrees per second after full draw). Bow damage is calculated as:

```
arrow_damage = (bow_base_damage + arrow_base_damage) * draw_percentage * skill_modifier
```

Where `skill_modifier = 1.0 + (archery_skill * 0.005)`, meaning an Archery skill of 100 provides a 50% damage bonus.

**Crossbow Mechanics:**

Crossbows are pre-loaded weapons that deal fixed damage without a draw mechanic but require a reload time of 1.5s-2.5s. They have higher base damage than bows (typically 1.5x-2.0x) and superior armor penetration (crossbow bolts ignore 20% of target armor by default), but lower rate of fire and no ability to hold a shot. Crossbows are ideal for stealth openers and burst damage.

**Projectile Physics:**

All projectiles are governed by a simplified ballistic model suitable for real-time web rendering. Arrows and bolts are affected by gravity (`g = 9.81 m/s^2` scaled to game units) and have a maximum range determined by initial velocity. Wind is not simulated to keep the system deterministic and web-friendly.

```
projectile_position.y = initial_y + (velocity_y * t) - (0.5 * gravity * t^2)
projectile_position.xz = initial_xz + (velocity_xz * t)
```

Projectile collision uses a raycast-per-frame approach (not continuous) with a generous hitbox to compensate for frame-rate-dependent detection. At 30 FPS, the ray length per frame is `velocity * (1/30)`, which for a fast arrow (60 m/s) is 2 meters. To prevent tunneling through thin targets, a secondary check casts the full inter-frame ray if the simple position check misses.

**Ammunition Types:**

Ammunition is categorized by material and special type. Standard arrows deal physical damage. Specialized ammunition adds tactical options:

| Ammo Type | Bonus Effect | Crafting Requirement | Base Cost |
|---|---|---|---|
| Iron Arrow | None | Smithing 1 | 2 gold |
| Steel Arrow | +15% damage | Smithing 20 | 5 gold |
| Elven Arrow | +30% damage, +10% speed | Smithing 40 | 12 gold |
| Fire Arrow | +20 fire damage over 4s | Alchemy 15 + Smithing 10 | 8 gold |
| Frost Arrow | +15 frost damage, 20% slow for 3s | Alchemy 20 + Smithing 10 | 10 gold |
| Shock Arrow | +25 shock damage, drains 15 mana | Alchemy 25 + Smithing 15 | 15 gold |
| Poison Arrow | Applies equipped poison on hit | Alchemy 30 | 6 gold + poison |
| Armor-Piercing Bolt | Ignores 50% armor (crossbow only) | Smithing 50 | 20 gold |
| Explosive Bolt | 3m AoE, 40 fire damage (crossbow only) | Smithing 40 + Alchemy 30 | 35 gold |

Ammo data is loaded from `data/items/ammunition.json`.

**Aiming System and Accuracy:**

Aiming uses a reticle that expands and contracts based on movement state and draw time. Standing still at full draw produces maximum accuracy (reticle at minimum size: 2px radius). Moving while aiming expands the reticle by 300%, and jumping expands it by 500%. Accuracy modifiers are cumulative and are applied as a random offset to the projectile's initial velocity vector within a cone defined by the reticle size. The Archery skill reduces the reticle expansion from movement: at Archery 50, movement penalty is halved; at Archery 100, it is reduced to 25%.

Aim assist is available as an accessibility option (enabled by default on touch devices) and gently curves the projectile toward the nearest valid target within 5 degrees of the aim direction.

### 2.3 Magic Combat

Magic in Eternal Realm is organized into five schools, each with a distinct combat role. Spells cost mana to cast, have cast times ranging from instant to 3 seconds, and may have cooldowns. The magic system is designed to offer equivalent power to melee combat but through resource management and tactical positioning rather than reflexes.

**The Five Schools of Magic:**

1. **Destruction (毁灭):** Direct damage spells. Fireballs, lightning bolts, frost spikes. This is the primary offensive school and offers the highest single-target and AoE damage potential. Destruction spells scale with the Destruction skill and Intelligence attribute.

2. **Restoration (恢复):** Healing and protective magic. Heals, wards (magical shields that absorb damage), and cleanse effects. Restoration is the primary support school and is critical for sustainability in prolonged fights. Restoration spells scale with the Restoration skill and Willpower attribute.

3. **Conjuration (召唤):** Summoning and binding magic. Summon elemental familiars, raise undead, conjure bound weapons. Conjuration provides action economy advantages by putting additional combatants on the field. Summoned creatures have their own HP pools and AI, and scale with the Conjuration skill. Maximum active summons: 1 (base), 2 (with "Twin Souls" perk), 3 (with legendary "Master Summoner" enchantment).

4. **Alteration (变化):** Utility and battlefield control. Telekinesis, magical armor buffs, paralysis, slow effects, and environmental manipulation (creating light, water walking). Alteration provides tactical advantages without directly dealing damage.

5. **Illusion (幻术):** Mind-affecting magic. Fear, frenzy (causes enemies to attack allies), calm, invisibility, and muffle. Illusion is the stealth-mage school and is the primary enabler of magic-stealth hybrid builds. Illusion spells have level caps on affected targets: a base-level Fear spell only affects enemies up to level 10, scaling with skill level.

**Mana Economy:**

Base mana pool is `100 + (Intelligence * 8) + (level * 3)`. At level 1 with 10 Intelligence, this gives 183 mana. Mana regenerates passively at a rate of `2% of max mana per second` out of combat and `0.5% per second` in combat. The Willpower attribute adds `0.05%` per point to the in-combat regeneration rate. Mana potions restore a flat amount (50/100/200 for minor/standard/greater) over 2 seconds.

Spell costs are defined per spell in `data/magic/spells.json` and are reduced by skill level:

```
effective_cost = base_cost * (1 - skill_level * 0.004)
```

At skill level 100, spells cost 60% of their base cost. At skill level 125 (achievable through enchantments), spells cost 50%. Specific perks can reduce costs for individual schools by an additional 15-25%.

**Spell Scaling Formula:**

Spell damage (for Destruction) is calculated as:

```
spell_damage = base_spell_damage * (1 + skill_level * 0.01) * (1 + intelligence * 0.02) * perk_multiplier * elemental_modifier
```

For example, Fireball has a base damage of 50. With Destruction skill 60, Intelligence 25, the "Augmented Flames 2" perk (1.3x), and no elemental modifier:

```
damage = 50 * (1 + 0.6) * (1 + 0.5) * 1.3 * 1.0 = 50 * 1.6 * 1.5 * 1.3 = 156
```

**Elemental Interactions:**

The three primary elements (Fire, Frost, Shock) form an interaction triangle stored in `data/magic/elemental_table.json`:

| Attacker \ Target Status | Burning | Frozen | Shocked | Wet | Oiled |
|---|---|---|---|---|---|
| Fire spell | 1.0x (extends) | 1.5x (removes) | 1.0x | 1.3x (creates steam) | 2.0x (explosion) |
| Frost spell | 1.0x (removes) | 1.0x (extends) | 1.0x | 1.5x (freeze solid) | 1.0x |
| Shock spell | 1.0x | 1.3x (shatter) | 1.0x (extends) | 1.8x (chain) | 1.0x |

Environmental interactions are also supported: fire spells can ignite oil pools, frost spells can freeze water surfaces (creating walkable ice for 10 seconds), and shock spells chain between targets standing in water (50% damage to secondary targets within 5 meters).

**Area of Effect Calculations:**

AoE spells use sphere or cone collision checks. For spherical AoE (e.g., Fireball explosion):

```
targets_hit = all_entities_within(explosion_center, aoe_radius)
for each target:
    distance_factor = 1.0 - (distance_to_center / aoe_radius) * falloff_rate
    actual_damage = spell_damage * max(distance_factor, 0.25)  // minimum 25% at edge
```

The `falloff_rate` varies by spell: Fireball uses 0.5 (gentle falloff, good edge damage), while Chain Lightning uses 0.8 (concentrated center damage). AoE radius for Fireball is 4 meters base, increased to 6 meters with the "Impact Master" perk.

Cone spells (e.g., Flame Breath) check against a frustum defined by origin, direction, angle (typically 45-60 degrees), and range (typically 8-12 meters). All entities within the frustum take full damage with no distance falloff, making cone spells highly effective in corridors.

### 2.4 Stealth System

The stealth system governs detection, sneaking, and the application of stealth-based damage bonuses. It is designed to support pure stealth gameplay as a complete playstyle, not merely a combat opener.

**Detection Model:**

NPC detection is governed by three independent sensory channels, each producing a detection score from 0 to 100. When any channel's score exceeds the NPC's awareness threshold (default 80, varies by enemy type), the NPC transitions from "unaware" to "suspicious." If the combined weighted score exceeds 150, the NPC enters "alert" state and begins actively searching.

1. **Visual Detection (视觉):** Based on lighting level at the player's position (0.0 = pitch dark, 1.0 = full sunlight), distance to observer, and player's visual profile (affected by armor type and active camouflage effects).

```
visual_score = (light_level * 100) * (1 / (distance * 0.1)) * visual_profile * (1 - sneak_skill * 0.005)
```

Where `visual_profile` is 1.0 for heavy armor, 0.7 for light armor, 0.4 for clothing, and 0.0 for magical invisibility. The sneak skill reduces visual detection linearly, with skill 100 halving the score.

2. **Audio Detection (听觉):** Based on noise generated by player actions. Each action has a noise value defined in `data/stealth/noise_values.json`:

| Action | Base Noise Value |
|---|---|
| Standing still | 0 |
| Walking (no sneak) | 30 |
| Walking (sneaking) | 10 |
| Running | 60 |
| Sprinting | 90 |
| Attacking (melee) | 50 |
| Casting spell (non-silent) | 40 |
| Opening door | 20 |
| Dropping item | 15 |
| Heavy armor movement penalty | +20 per piece |

Audio detection is reduced by distance: `audio_score = noise_value * (1 / (distance * 0.15)) * (1 - sneak_skill * 0.004)`. The "Muffle" enchantment reduces all noise values by 50%, and the Illusion spell "Silence" reduces them to zero for 30 seconds.

3. **Proximity Detection (感知):** A short-range awareness that simulates an NPC's peripheral senses (smell, spatial awareness). This provides a minimum detection floor so that players cannot stand directly behind an NPC indefinitely. Proximity detection activates within 2 meters and scales inversely with distance: `proximity_score = (2.0 - distance) * 50`. This channel is unaffected by lighting or noise but is reduced by the Sneak skill: `final_proximity = proximity_score * (1 - sneak_skill * 0.006)`.

**Sneak Attack Mechanics:**

Attacking an unaware target triggers a sneak attack, which applies a damage multiplier based on weapon type and active perks:

| Weapon Type | Base Sneak Multiplier | Max Multiplier (with perks) |
|---|---|---|
| Dagger | 3.0x | 15.0x (Assassin's Blade perk) |
| One-handed (other) | 2.0x | 6.0x |
| Two-handed | 1.5x | 4.0x |
| Bow | 2.0x | 6.0x (Ranger's Mark perk) |
| Crossbow | 2.5x | 7.5x |
| Destruction spell | 1.5x | 3.0x (Quiet Casting + Silent Storm perk) |

Sneak attacks with melee weapons also have a chance to trigger an instant kill on enemies whose remaining HP after the sneak attack damage would be below 15% of their max HP. This threshold is increased to 25% with the "Throat Cutter" perk.

**AI Awareness and Suspicion:**

When an NPC becomes suspicious, they enter a search behavior: they move toward the last detected stimulus, look around for 10 seconds, then return to patrol if no further stimuli are detected. During the suspicious state, all detection thresholds are reduced by 30%, making the NPC harder to evade. If the NPC spots a dead body, they immediately enter alert state, raise an alarm within a 30-meter radius, and all nearby NPCs enter a heightened alert state for 120 seconds.

The suspicion system uses a decay model: after a stimulus, suspicion decays at 5 points per second. Repeated stimuli within the decay window accumulate, making it progressively harder to remain undetected. This prevents players from repeatedly poking at an NPC's awareness boundary without consequence.

### 2.5 Damage Model

The damage model is the central formula engine that resolves all combat interactions. It is intentionally transparent and deterministic (no hidden rolls) so that players can reason about outcomes and optimize their builds.

**Complete Damage Formula:**

```
final_damage = (base_damage * attack_multiplier * skill_modifier * perk_bonus * stance_modifier
               * sneak_multiplier * critical_multiplier * elemental_modifier)
               * (1 - damage_reduction)
               + flat_bonus_damage
```

Each component is resolved in order:

- `base_damage`: Weapon or spell base damage, loaded from `data/items/weapons.json` or `data/magic/spells.json`.
- `attack_multiplier`: From attack type (light chain position, heavy charge level, combo route).
- `skill_modifier`: `1.0 + (relevant_skill * 0.005)`, so skill 100 = 1.5x.
- `perk_bonus`: Multiplicative bonus from relevant perks (e.g., "Armsman" rank 5 = 1.4x for one-handed).
- `stance_modifier`: 1.15 (Aggressive) or 0.90 (Defensive) for melee; 1.0 for ranged/magic.
- `sneak_multiplier`: 1.0 if detected, otherwise per sneak attack table (Section 2.4).
- `critical_multiplier`: 1.0 if no crit, otherwise 1.5x base (modified by perks up to 2.5x).
- `elemental_modifier`: From elemental interaction table (Section 2.3), default 1.0.
- `damage_reduction`: Calculated from target's armor and resistances (see below).
- `flat_bonus_damage`: From enchantments, poisons, and buffs (applied after percentage reduction).

**Worked Example - Melee Attack:**

A player with a Steel Sword (base damage 22), One-Handed skill 45, "Armsman 2" perk (1.2x), in Aggressive stance, landing the third hit of a light chain (1.2x), against a Bandit with 120 armor rating:

```
base = 22, attack_mult = 1.2, skill_mod = 1.0 + (45 * 0.005) = 1.225
perk = 1.2, stance = 1.15, sneak = 1.0, crit = 1.0, elem = 1.0
raw_damage = 22 * 1.2 * 1.225 * 1.2 * 1.15 * 1.0 * 1.0 * 1.0 = 44.67

armor_reduction = armor_rating / (armor_rating + 300) = 120 / 420 = 0.2857
final_damage = 44.67 * (1 - 0.2857) = 44.67 * 0.7143 = 31.91 -> rounded to 32
```

**Armor Reduction (Diminishing Returns):**

Armor provides damage reduction using a hyperbolic formula that ensures diminishing returns and prevents 100% reduction:

```
damage_reduction = armor_rating / (armor_rating + K)
```

Where `K = 300` for physical damage. This means:

| Armor Rating | Damage Reduction |
|---|---|
| 0 | 0% |
| 100 | 25.0% |
| 200 | 40.0% |
| 300 | 50.0% |
| 500 | 62.5% |
| 750 | 71.4% |
| 1000 | 76.9% |
| 1500 | 83.3% |

The practical armor cap is around 1200 (80% reduction). Beyond this, investing in armor provides negligible returns, and players are better served by HP, dodge, or resistance stacking. Armor values for equipment are defined in `data/items/armor.json`, with full sets ranging from 80 (Hide) to 600 (Dragonscale/Dragonplate), before smithing improvements.

**Critical Hit System:**

Critical hits are determined by a probability roll on each attack. Base critical chance is 5%. Each point of the Luck attribute adds 0.5% crit chance. Specific perks add flat crit chance for their weapon type (e.g., "Keen Edge" adds 10% for swords). Some weapons have innate crit bonuses defined in their item data.

```
crit_chance = base_crit (5%) + luck_bonus + perk_bonus + weapon_bonus + enchantment_bonus
crit_damage = base_crit_mult (1.5x) + perk_crit_bonus + enchantment_crit_bonus
```

Critical hits are visually communicated through a screen flash, a distinct sound effect, and floating damage numbers displayed in gold rather than white.

**Elemental Damage Types and Resistances:**

There are five damage types: Physical, Fire, Frost, Shock, and Poison. Each entity has a resistance value (0-100) for each type. Resistance reduces damage of that type by the percentage value:

```
elemental_reduction = resistance_value / 100  // 50 resistance = 50% reduction
```

Resistance can exceed 100 (immunity) through stacking effects, and can be negative (vulnerability) due to debuffs. Resistance values for enemies are defined in `data/enemies/resistances.json`. Fire Atronachs, for example, have Fire resistance 100 (immune) and Frost resistance -50 (150% frost damage taken).

**Status Effects:**

Elemental damage can apply status effects with associated durations and mechanics:

- **Burning (燃烧):** 5 fire damage per second for 4 seconds. Duration refreshes on reapplication. Affected targets take 10% increased fire damage.
- **Chilled (冰冻):** 20% movement and attack speed reduction for 5 seconds. If reapplied twice within the duration, upgrades to Frozen (complete immobilization for 3 seconds, target takes 30% more physical damage).
- **Shocked (雷击):** Drains 5 mana per second for 4 seconds. Shocked targets have a 15% chance to fail spellcasting (spell fizzles, mana still spent).
- **Poisoned (中毒):** Variable damage over time depending on poison type (see Alchemy section). Reduces healing received by 30% for the duration.
- **Bleeding (流血):** Caused by certain physical attacks (daggers, axes, perks). Deals 3% of max HP per second for 6 seconds. Stacks up to 3 times. Reduced by armor.
- **Staggered (失衡):** Interrupts current action, brief vulnerability window (30 frames). Caused by heavy attacks, shield bashes, and specific spells.

### 2.6 Enemy AI

Enemy AI operates on a hierarchical finite state machine (HFSM) with behavior trees for in-state decision-making. The system is designed for web performance, targeting a maximum AI update budget of 2ms per frame across all active enemies (typically 8-12 in a combat encounter).

**State Machine:**

Each enemy operates in one of seven states, with defined transition conditions:

```
[Patrol] --(detect_stimulus > suspicious_threshold)--> [Suspicious]
[Suspicious] --(detect_stimulus > alert_threshold)--> [Alert]
[Suspicious] --(suspicion_decay_timer > 10s)--> [Patrol]
[Alert] --(target_visible)--> [Combat]
[Alert] --(search_timer > 30s)--> [Search]
[Combat] --(target_lost_for > 5s)--> [Search]
[Combat] --(hp < flee_threshold)--> [Flee]
[Search] --(detect_stimulus > alert_threshold)--> [Combat]
[Search] --(search_timer > 45s)--> [Return]
[Flee] --(distance_to_target > 30m)--> [Search]
[Flee] --(allies_nearby > 2)--> [Combat]  // courage in numbers
[Return] --(at_home_position)--> [Patrol]
```

State data and transition thresholds are defined per enemy type in `data/enemies/ai_profiles.json`.

**Behavior Parameters:**

Each AI profile defines key behavioral parameters:

| Parameter | Bandit (melee) | Bandit (archer) | Mage | Wolf | Dragon |
|---|---|---|---|---|---|
| Aggression | 0.7 | 0.5 | 0.6 | 0.9 | 0.8 |
| Flee HP threshold | 15% | 20% | 25% | 30% | 0% (never) |
| Preferred range | 1.5m | 15m | 10m | 1.5m | 20m (air), 5m (ground) |
| Block frequency | 0.4 | 0.1 | 0.0 | 0.0 | 0.0 |
| Dodge frequency | 0.2 | 0.3 | 0.4 | 0.5 | 0.1 |
| Call for help radius | 20m | 25m | 30m | 40m (pack) | 0m (solo) |

**Enemy Archetypes and Combat Strategies:**

Enemies are designed in archetypes that create varied combat encounters:

- **Melee Bruiser (e.g., Orc Berserker):** High HP, high damage, slow attacks. Uses heavy attacks frequently, rarely blocks, charges at the player. Countered by: dodge timing, kiting, frost spells for slowing.
- **Shield Bearer (e.g., Imperial Legionnaire):** Medium HP, high block rate, uses shield bash to stagger. Requires guard-breaking through stamina drain, power attacks, or flanking. Countered by: heavy attacks, shield bash, frost spells (drain stamina).
- **Ranged Harasser (e.g., Forsworn Archer):** Low HP, maintains distance, retreats when approached. Will reposition to high ground if available. Countered by: closing distance quickly, shock spells (instant hit), using cover.
- **Spellcaster (e.g., Necromancer):** Medium HP, summons minions and casts debuffs before switching to direct damage. Prioritize killing summons or interrupting caster. Countered by: rushing the caster, shock spells (drain mana), silence effects.
- **Pack Hunter (e.g., Wolf pack):** Low individual HP, always fights in groups of 3-6. Attempts to flank and surround. One wolf always circles behind. Countered by: AoE spells, positioning against walls, picking off individuals.
- **Boss (e.g., Dragon Priest):** High HP, multiple phases, unique mechanics per boss. See boss design philosophy below.

**Boss Fight Design Philosophy:**

Boss encounters in Eternal Realm follow a three-phase structure. Each phase transition occurs at 66% and 33% HP and introduces new mechanics. The design philosophy centers on "readable danger": every boss attack is telegraphed with a 0.5-1.0 second wind-up animation and a distinct audio cue, giving players time to react. Boss attacks that can one-shot the player are telegraphed for a full 1.5 seconds with a glowing ground indicator.

Bosses are immune to stagger (except during specific vulnerability windows), have 50% reduced effectiveness from crowd-control effects, and are immune to instant-kill mechanics. Boss HP scales with difficulty mode but their attack patterns remain the same, ensuring the fight is learned once and executed at higher precision on harder difficulties. Boss loot is guaranteed (see Section 4.4) and includes at least one unique item not obtainable elsewhere.

---

## 3. Character Progression

### 3.1 Attributes

Eternal Realm uses eight primary attributes that define a character's fundamental capabilities. Each attribute starts at a base value of 10 (modified by race) and can be increased by spending attribute points gained at each level-up. The soft cap for each attribute is 50 (beyond which each point costs 2 attribute points), and the hard cap is 75 (beyond which no further investment is possible, though enchantments and buffs can exceed this).

| Attribute | Chinese | Effect Per Point | Derived Stats |
|---|---|---|---|
| **Strength (力量)** | 力量 | +2 melee damage, +3 carry weight | Power attack damage, equipment requirements |
| **Dexterity (敏捷)** | 敏捷 | +1% attack speed, +0.3% dodge distance | Ranged accuracy, pickpocket chance, lockpicking ease |
| **Constitution (体质)** | 体质 | +12 max HP, +0.5 HP regen/s | Poison/disease resistance, bleeding resistance |
| **Intelligence (智力)** | 智力 | +8 max mana, +2% spell damage | Enchantment power, trap detection range |
| **Willpower (意志)** | 意志 | +0.05% mana regen in combat, +5 max mana | Status effect duration reduction, fear resistance |
| **Endurance (耐力)** | 耐力 | +8 max stamina, +0.3 stamina regen/s | Sprint duration, swim speed, environmental resistance |
| **Perception (感知)** | 感知 | +1.5m detection range, +1% crit chance vs. unaware | Stealth detection, hidden item discovery, dialogue insight |
| **Luck (运气)** | 运气 | +0.5% crit chance, +1% gold find, +0.5% rare drop | Critical damage, vendor prices, gambling outcomes |

**Derived Stats and Their Formulas:**

Derived stats are automatically calculated from attributes and cannot be directly modified (except through enchantments that specifically target them):

```
Max HP = 100 + (Constitution * 12) + (Level * 5) + racial_bonus
Max Mana = 100 + (Intelligence * 8) + (Willpower * 5) + (Level * 3) + racial_bonus
Max Stamina = 100 + (Endurance * 8) + (Level * 4) + racial_bonus
Carry Weight = 100 + (Strength * 3) + perk_bonus
Physical Damage Bonus = Strength * 2  (added to melee base damage)
Spell Power = 1.0 + (Intelligence * 0.02)  (multiplier to spell damage)
Attack Speed = 1.0 + (Dexterity * 0.01)  (multiplier to animation speed, capped at 1.5)
Critical Chance = 5% + (Luck * 0.5%) + (Perception * 0.15% vs unaware targets)
Movement Speed = base_speed * (1 + Dexterity * 0.003)  (capped at 1.2x base)
```

All attribute data and derived stat formulas are defined in `data/character/attributes.json` for easy tuning.

### 3.2 Skills and Skill Trees

Skills represent learned competencies that improve through use. Eternal Realm uses a "learning by doing" model: casting Destruction spells levels Destruction, swinging swords levels One-Handed, and successfully picking locks levels Lockpicking. There are 18 skills organized into four categories.

**Combat Skills (6):**
- **One-Handed (单手):** Swords, axes, maces, daggers used in one hand. Governs damage and unlocks combo routes.
- **Two-Handed (双手):** Greatswords, warhammers, halberds. Higher base damage, slower attacks.
- **Archery (弓术):** Bows and crossbows. Governs damage, draw speed, and zoom steadiness.
- **Block (格挡):** Shield and weapon blocking. Governs block efficiency and unlocks parry-related perks.
- **Destruction (毁灭):** Offensive magic. Governs spell damage and mana cost reduction.
- **Conjuration (召唤):** Summoning magic. Governs summon strength, duration, and number.

**Stealth Skills (4):**
- **Sneak (潜行):** Governs detection avoidance and sneak attack multipliers.
- **Lockpicking (开锁):** Governs lockpick durability and sweet spot size.
- **Pickpocket (扒窃):** Governs success chance based on item weight/value.
- **Speech (话术):** Governs persuasion/intimidation checks and vendor price modifiers.

**Magic Skills (4):**
- **Restoration (恢复):** Healing and ward spells. Governs healing power and ward strength.
- **Alteration (变化):** Utility magic. Governs spell duration and armor spell strength.
- **Illusion (幻术):** Mind-affecting magic. Governs the maximum level of affected targets.
- **Enchanting (附魔):** Creating magical items. Governs enchantment magnitude and charges.

**Crafting Skills (4):**
- **Smithing (锻造):** Creating and improving weapons/armor. Governs available recipes and improvement tiers.
- **Alchemy (炼金):** Creating potions and poisons. Governs effect magnitude and duration.
- **Cooking (烹饪):** Preparing buff food from ingredients. Governs buff strength and duration.
- **Mining/Gathering (采集):** Resource harvesting efficiency. Governs yield and rare material discovery.

**Skill Leveling Formula:**

Each skill has an XP requirement that scales with skill level:

```
xp_to_next_level = base_xp * (1.08 ^ current_level)
```

Where `base_xp` varies by skill (combat skills: 50, stealth skills: 40, magic skills: 55, crafting skills: 35). XP gained per action also varies:

| Action | XP Gained | Skill |
|---|---|---|
| Hit enemy with one-handed weapon | 4 * damage_dealt / 10 | One-Handed |
| Block an attack | 6 * damage_blocked / 10 | Block |
| Cast Destruction spell in combat | 5 * mana_spent / 10 | Destruction |
| Successfully sneak past enemy | 8 per enemy | Sneak |
| Pick a lock | 10 * lock_difficulty_tier | Lockpicking |
| Smith an item | 15 * item_tier | Smithing |
| Brew a potion | 12 * potion_complexity | Alchemy |

Skill levels range from 1 to 100 base, with a hard cap of 150 achievable only through legendary skill resets (see Perk System).

### 3.3 Perk System

Each skill has an associated perk tree with 8-12 perks arranged in a branching structure. Perks are unlocked by spending perk points (1 per level-up) and meeting the skill level prerequisite. The system contains 172 perks total across all 18 skills.

**Design Philosophy:**

Perks are designed to be transformative, not merely numerical. While early perks in a tree provide percentage bonuses (e.g., "+20% one-handed damage"), deeper perks fundamentally change how a skill works (e.g., "Dual-wielding power attacks hit all enemies in a cone" or "Destruction spells below half cost are cast instantly"). This ensures that investing in a skill tree feels meaningful at every tier and that high-level characters play qualitatively differently from low-level ones.

**Perk Tree Structure:**

Each perk tree has a root perk (no prerequisite beyond skill level 1), mid-tier perks (skill level 25-50), and capstone perks (skill level 75-100). Trees branch into 2-3 specialization paths. For example, the One-Handed tree branches into:

- **Swordsman Path:** Focuses on critical hits, bleed effects, and finesse.
  - Keen Edge (Skill 30): +10% crit chance with swords.
  - Bleeding Strikes (Skill 50): Sword attacks apply Bleed for 6s.
  - Master Duelist (Skill 90): Successful parries with swords grant 3 seconds of +50% attack speed.

- **Axeman Path:** Focuses on raw damage, armor penetration, and AoE cleave.
  - Deep Wounds (Skill 30): Axes deal +15% damage to targets below 50% HP.
  - Armor Rend (Skill 50): Axe heavy attacks reduce target armor by 20% for 8s.
  - Whirlwind (Skill 90): Power attack spins 360 degrees, hitting all nearby enemies for full damage.

- **Brawler Path:** Focuses on maces, stagger, and shield synergy.
  - Bone Breaker (Skill 30): Mace attacks ignore 15% of armor.
  - Concussive Force (Skill 50): Heavy attacks with maces have a 30% chance to stagger.
  - Skull Crusher (Skill 90): Mace critical hits stun the target for 2 seconds.

**Key Perks for Build Archetypes:**

- **Warrior:** Armsman 5 (One-Handed), Juggernaut 5 (Heavy Armor), Shield Wall 3 (Block)
- **Archer:** Overdraw 5 (Archery), Ranger (move at full speed with drawn bow), Bullseye (15% chance to paralyze)
- **Mage:** Augmented Elements (Destruction), Dual Casting (Destruction/Restoration), Impact (stagger on dual-cast)
- **Thief:** Assassin's Blade (15x dagger sneak), Backstab (6x one-handed sneak), Shadow Warrior (enter sneak mid-combat to reset detection)

**Respec Mechanics:**

Players can reset a single skill tree by visiting the "Shrine of Renewal" (更新之祠) found in each major city. The cost is `500 * skill_level` gold and resets the skill to level 1 while refunding all invested perk points. Alternatively, players can "Legendary" a skill at level 100, resetting it to 1 and refunding perk points, but retaining a permanent +5% effectiveness bonus to that skill. This legendary reset can be performed up to 10 times per skill, allowing a theoretical skill cap of 150 and providing a source of infinite perk points for dedicated players.

### 3.4 Leveling

Character level is derived from skill progression, not from a separate XP pool. Each skill level-up contributes to an overall character XP pool:

```
character_xp_from_skill = skill_level * skill_weight
```

Where `skill_weight` is 1.0 for all skills (ensuring no skill is "more valuable" for leveling). Character XP required for each level follows a polynomial curve:

```
xp_to_level_N = 25 * N^1.8
```

This produces a curve where early levels come quickly (level 2 requires 25 XP, about 3-4 skill level-ups) and later levels require significant multi-skill investment (level 50 requires approximately 18,750 XP).

**Level Cap:** 80 (achievable by reaching approximately skill level 60 across all 18 skills, or skill level 100 in ~10 skills with moderate progress in others). With legendary resets, there is theoretically no level cap, but content is balanced for levels 1-80.

**Per-Level Rewards:**

At each level-up, the player receives:
- 1 attribute point (to spend on any attribute)
- 1 perk point (to spend on any unlocked perk)
- +5 to max HP, +3 to max mana, +4 to max stamina (automatic, in addition to attribute choices)

**Level Scaling of World Content:**

Eternal Realm uses a zone-based level scaling system rather than fully dynamic scaling. Each zone has a minimum and maximum level range defined in `data/world/zone_levels.json`:

| Zone | Level Range | Example |
|---|---|---|
| Tutorial Valley | 1-5 | Scripted introduction |
| Greenwood Forest | 3-15 | Starting exploration area |
| Stonereach Mountains | 10-25 | Mid-game dungeon area |
| Shadowfen Swamp | 15-30 | Stealth-focused content |
| Dragon's Spine | 25-45 | High-level combat area |
| The Abyss | 40-60 | Endgame dungeon |
| Eternal Sanctum | 55-80 | Final content tier |

Within a zone, enemy levels are randomly selected within the range when the zone is first entered, then fixed for that playthrough. Named enemies and bosses have fixed levels. Quest rewards scale to the player's level at the time of quest completion (within the zone's range), ensuring rewards are always relevant.

### 3.5 Races and Starting Classes

**Eight Playable Races:**

Each race provides attribute bonuses, a unique racial ability (usable once per in-game day with a 24-minute real-time cooldown), and starting skill bonuses that provide a 10-point head start in specific skills.

| Race | Chinese Name | Attribute Bonuses | Racial Ability | Starting Skill Bonuses |
|---|---|---|---|---|
| Human (人族) | 人族 | +2 to all attributes | Rally: +20% XP gain for 60s | Speech +10, One-Handed +5, Block +5 |
| Elf (精灵) | 精灵 | +5 INT, +3 WIL, +2 DEX | Arcane Surge: Restore 100% mana instantly | Destruction +10, Alteration +5, Enchanting +5 |
| Dwarf (矮人) | 矮人 | +5 CON, +3 STR, +2 END | Stone Skin: 80% damage reduction for 10s | Smithing +10, Block +5, Two-Handed +5 |
| Orc (兽人) | 兽人 | +5 STR, +3 END, +2 CON | Blood Rage: 2x damage dealt & taken for 30s | Two-Handed +10, Smithing +5, One-Handed +5 |
| Shadow Kin (影族) | 影族 | +5 DEX, +3 PER, +2 LCK | Shadow Cloak: Invisibility for 30s | Sneak +10, Lockpicking +5, Pickpocket +5 |
| Dragonborn (龙裔) | 龙裔 | +3 STR, +3 INT, +2 WIL, +2 CON | Dragon Shout: 15m cone, 80 damage, staggers | Destruction +5, Two-Handed +5, Block +5, Conjuration +5 |
| Fae (妖精) | 妖精 | +5 WIL, +3 INT, +2 PER | Nature's Embrace: AoE heal, 100 HP to all allies in 10m | Restoration +10, Alchemy +5, Illusion +5 |
| Beastfolk (兽民) | 兽民 | +5 END, +3 DEX, +2 PER | Predator's Sprint: 3x move speed for 15s, +50% sneak attack for duration | Archery +10, Sneak +5, Cooking +5 |

Race data is loaded from `data/character/races.json`.

**Six Starting Class Templates:**

Classes are not binding; they are starting templates that pre-allocate the first 5 attribute points and provide starting equipment. Players can develop in any direction regardless of class choice.

| Class | Chinese Name | Starting Attributes | Starting Equipment |
|---|---|---|---|
| Warrior (战士) | 战士 | +2 STR, +2 CON, +1 END | Iron Sword, Wooden Shield, Iron Armor Set |
| Mage (法师) | 法师 | +2 INT, +2 WIL, +1 PER | Novice Staff, Cloth Robes, 3 Mana Potions |
| Rogue (盗贼) | 盗贼 | +2 DEX, +2 PER, +1 LCK | Iron Dagger, Leather Armor Set, 20 Lockpicks |
| Ranger (游侠) | 游侠 | +2 DEX, +1 STR, +1 PER, +1 END | Shortbow, 50 Iron Arrows, Leather Armor Set |
| Spellsword (魔剑士) | 魔剑士 | +1 STR, +2 INT, +1 WIL, +1 DEX | Iron Sword, Novice Spell Tome (Flames), Light Armor Set |
| Monk (武僧) | 武僧 | +2 END, +2 WIL, +1 STR | Quarterstaff, Cloth Robes, 3 Healing Poultices |

**Long-Term Build Impact:**

Race choice has a meaningful but not deterministic impact on long-term builds. The +10 skill bonus saves approximately 2-3 hours of leveling in that skill, and the racial ability remains relevant throughout the game. Attribute bonuses represent roughly 5 level-ups worth of attribute points, which is significant early game but becomes proportionally less impactful as the character reaches higher levels. The design intent is that any race can play any build effectively, but some combinations are 10-15% more efficient in their niche (e.g., Shadow Kin rogues, Elf mages, Orc warriors).

---

## 4. Economy and Crafting

### 4.1 Currency and Trade

The economy of Eternal Realm is designed as a closed-loop system where gold flows through clearly defined sources (faucets) and sinks (drains), preventing the runaway inflation that plagues many RPGs.

**Gold Economy Flow:**

*Gold Sources (Faucets):*
- Enemy drops: 5-50 gold per kill depending on enemy level and type (humanoids carry more than beasts). Defined in `data/loot/gold_tables.json`.
- Quest rewards: 50-2000 gold depending on quest tier. Main quest rewards are in the 200-1000 range.
- Selling items to vendors: The primary gold source for most players. Vendor buy prices are 33% of item base value by default.
- Treasure chests: 20-500 gold per chest, scaled by dungeon level.
- Trade goods: Specialty items (gems, pelts, rare herbs) designed specifically as vendor fodder.

*Gold Sinks (Drains):*
- Vendor purchases: Gear, materials, recipes, spell tomes. Vendor sell prices are 100% of base value, reduced by Speech skill (minimum 80%).
- Crafting material costs: Rare materials from specialized vendors (e.g., Daedra Hearts at 500 gold each).
- Training: Paying NPCs to gain skill XP directly, costing `100 * target_skill_level` per session, with 5 sessions per trainer per level-up.
- Property: Purchasing houses (5,000-50,000 gold), which serve as storage and fast-travel points.
- Respec costs: Shrine of Renewal costs `500 * skill_level`.
- Enchantment charging: Recharging depleted enchanted weapons costs gold based on enchantment level.
- Fast travel: 10-100 gold based on distance (optional; walking is free).
- Repair costs: Equipment degrades with use and requires gold to repair at smiths, or free repair with sufficient Smithing skill.

**Trade Goods and Regional Pricing:**

Each of the seven regions in the game world has a regional price modifier for specific trade goods, encouraging caravan-style trading for players who enjoy the merchant fantasy. Price data is defined in `data/economy/regional_prices.json`:

| Trade Good | Base Value | Greenwood Price | Stonereach Price | Shadowfen Price | Dragon's Spine Price |
|---|---|---|---|---|---|
| Timber Bundle | 20 | 15 (cheap, abundant) | 30 (scarce) | 25 | 35 (high demand) |
| Iron Ingot | 25 | 30 | 15 (local mines) | 25 | 20 |
| Shadowfern Herb | 40 | 50 | 45 | 20 (local) | 60 (exotic) |
| Dragon Scale | 200 | 250 | 220 | 230 | 120 (common locally) |
| Enchanted Gem | 150 | 130 | 180 | 160 | 200 |

**Shop System and NPC Merchants:**

Each merchant NPC has a gold reserve that limits how much they can buy from the player. Gold reserves range from 500 (general store) to 5,000 (master merchant in the capital). Merchant gold resets every 48 in-game hours (48 real-time minutes). Merchants specialize in categories (weaponsmith, alchemist, general goods) and offer better prices for their specialty (+10% buy price). The Speech skill modifies all vendor transactions:

```
sell_price = base_value * 0.33 * (1 + speech_skill * 0.003) * (1 + haggling_perk_bonus)
buy_price = base_value * (1 - speech_skill * 0.002) * (1 - haggling_perk_bonus)
```

At Speech 100 with max haggling perks, sell prices reach approximately 50% of base value and buy prices drop to 80%.

### 4.2 Item System

Items are the physical representation of player power and progression. The item system is designed to provide a steady stream of upgrades while ensuring that crafted items, looted items, and vendor items all have viable roles.

**Item Categories and Slot System:**

The player has 12 equipment slots:

| Slot | Category | Examples |
|---|---|---|
| Head | Armor | Helmets, hoods, circlets |
| Chest | Armor | Cuirasses, robes |
| Hands | Armor | Gauntlets, gloves |
| Feet | Armor | Boots, shoes |
| Legs | Armor | Greaves, pants |
| Main Hand | Weapon | Swords, axes, staves, bows |
| Off Hand | Weapon/Shield | Shields, secondary weapons, spell focus |
| Ring 1 | Accessory | Stat-boosting rings |
| Ring 2 | Accessory | Stat-boosting rings |
| Amulet | Accessory | Stat-boosting necklaces |
| Cloak | Accessory | Environmental resistance, stealth bonuses |
| Belt | Accessory | Potion slots, carry weight bonuses |

**Rarity Tiers:**

Items come in five rarity tiers, each providing a stat multiplier to the item's base stats:

| Tier | Color | Stat Multiplier | Drop Weight | Enchantment Slots |
|---|---|---|---|---|
| Common (普通) | White | 1.0x | 60% | 0 |
| Uncommon (优秀) | Green | 1.15x | 25% | 1 |
| Rare (稀有) | Blue | 1.35x | 10% | 1-2 |
| Epic (史诗) | Purple | 1.6x | 4% | 2 |
| Legendary (传说) | Orange | 2.0x | 1% | 2-3 + unique effect |

Legendary items always have a unique named effect that cannot be disenchanted or replicated. There are 50 legendary items in the game, each with lore significance and a specific acquisition method (boss drop, quest reward, or hidden world placement).

**Weapon and Armor Progression by Material Tier:**

Materials define the base stats of craftable gear. Each material tier requires a minimum Smithing skill and provides progressive stat increases. Weapon and armor base values are defined in `data/items/material_tiers.json`:

| Material | Smithing Req. | Weapon Base Damage (Sword) | Armor Base Rating (Chest) | Weight Modifier |
|---|---|---|---|---|
| Iron (铁) | 1 | 18 | 35 | 1.0x |
| Steel (钢) | 15 | 24 | 48 | 1.0x |
| Dwarven (矮人) | 30 | 30 | 58 | 1.2x |
| Elven (精灵) | 35 | 28 | 42 (light) | 0.7x |
| Orcish (兽人) | 45 | 35 | 65 | 1.3x |
| Ebony (乌木) | 60 | 40 | 72 | 1.1x |
| Dragonscale (龙鳞) | 75 | 34 (light) | 55 (light) | 0.6x |
| Dragonplate (龙骨) | 80 | 45 | 82 | 1.4x |
| Daedric (魔族) | 90 | 50 | 90 | 1.5x |

**Unique and Legendary Items:**

Legendary items serve as long-term aspirational goals and build-defining pieces. Examples:

- **Frostmourne (霜之哀伤):** Daedric Greatsword, 55 base damage, unique effect "Soul Harvest" -- killing blows restore 25% HP and grant a stacking +5% damage buff for 30 seconds. Found in the Eternal Sanctum final boss encounter.
- **Veil of Shadows (暗影之纱):** Legendary Hood, unique effect "Unseen" -- while sneaking and stationary, the wearer becomes completely invisible (visual detection score reduced to 0). Quest reward from the Thieves Guild questline.
- **Staff of the Archmage (大法师之杖):** Legendary Staff, unique effect "Spell Amplification" -- all spells cost 15% less mana and deal 20% more damage. All spell schools benefit. Reward from the Mage Academy questline.

### 4.3 Crafting Systems

Crafting in Eternal Realm is divided into four disciplines, each with its own progression, recipes, and integration points with other game systems. Crafting is designed to be the most reliable path to top-tier gear, superior to random loot drops for min-maxed builds, but requiring significant skill investment.

**Smithing (锻造):**

Smithing covers the creation and improvement of weapons and armor. The workflow follows three stages:

1. **Material Gathering:** Raw materials are obtained through Mining (ore nodes in the world), enemy drops (leather from animals, bones from undead), and vendor purchases. Ore must be smelted into ingots at a forge (2 ore = 1 ingot). Material nodes respawn every 72 in-game hours (72 real-time minutes). Node locations are fixed and documented in `data/world/resource_nodes.json`.

2. **Crafting Recipes:** Each item has a recipe requiring specific materials. Recipes are unlocked automatically when the player reaches the required Smithing skill level. Higher-tier materials require more ingots and supplementary materials:

```json
{
  "recipe_id": "ebony_sword",
  "output": "weapon_ebony_sword",
  "smithing_required": 60,
  "materials": [
    {"item": "ebony_ingot", "quantity": 3},
    {"item": "leather_strips", "quantity": 2},
    {"item": "fire_salt", "quantity": 1}
  ],
  "crafting_time": 5.0,
  "xp_granted": 120
}
```

3. **Improvement:** Existing weapons and armor can be improved at a workbench, increasing their base damage or armor rating. Each improvement tier costs materials and requires a higher Smithing skill. Improvement adds a flat bonus to the item's base stat:

| Improvement Tier | Smithing Required | Bonus | Material Cost |
|---|---|---|---|
| Fine | Skill 15 | +5 | 1 ingot of same material |
| Superior | Skill 30 | +10 | 2 ingots |
| Exquisite | Skill 50 | +16 | 3 ingots + 1 rare material |
| Flawless | Skill 70 | +23 | 4 ingots + 2 rare materials |
| Legendary | Skill 100 | +32 | 5 ingots + 3 rare materials + 1 legendary component |

Improvement is applied cumulatively from the base tier, not stacking. A Legendary improvement to an Ebony Sword (base 40) yields 40 + 32 = 72 damage, before other modifiers.

**Alchemy (炼金):**

Alchemy transforms gathered ingredients into potions and poisons. It is the most experimental crafting discipline, encouraging players to discover effects through trial and error.

*Ingredient Discovery:* Each ingredient has 4 hidden effects (stored in `data/crafting/ingredients.json`). The first effect is revealed when the ingredient is eaten (consuming it applies the first effect at 30% magnitude and reveals it in the alchemy UI). Subsequent effects are revealed by combining the ingredient with others that share a common effect, or through the "Experimenter" perk which reveals additional effects.

*Potion Brewing:* Potions are created by combining 2-3 ingredients at an alchemy lab. If any two ingredients share a common effect, a potion is created with that effect. If multiple effects overlap, the potion has multiple effects. Conflicting effects (e.g., "Restore Health" + "Damage Health") produce a potion with both effects, creating interesting risk/reward items.

Potion magnitude is calculated as:

```
magnitude = base_effect_magnitude * (1 + alchemy_skill * 0.008) * (1 + alchemist_perk_bonus)
            * ingredient_quality_modifier
```

Where `ingredient_quality_modifier` ranges from 0.8 (common ingredients like wheat) to 1.5 (rare ingredients like Daedra Heart). Potion duration follows a similar formula with a separate duration multiplier.

*Poison Making:* Poisons follow the same crafting process but produce items that are applied to weapons (1 application per poison, consumed on next hit). Poisons are defined by negative effects: Damage Health, Damage Stamina, Damage Mana, Slow, Weakness to Element, Paralysis. High-level poisons combining Paralysis + Damage Health are among the strongest single-hit damage sources in the game.

**Key Potions and Their Formulas:**

| Potion | Base Magnitude | Key Ingredients | Duration |
|---|---|---|---|
| Restore Health | 50 HP | Wheat + Blue Mountain Flower | Instant |
| Restore Mana | 40 Mana | Moon Sugar + Red Mountain Flower | Instant |
| Fortify Strength | +8 STR | Bear Claw + Glowing Mushroom | 60s |
| Resist Fire | 40% | Snowberry + Dragon's Tongue | 90s |
| Invisibility | Complete | Vampire Dust + Nirnroot + Chaurus Egg | 30s |
| Paralysis Poison | 4s paralyze | Canis Root + Imp Stool + Human Heart | On hit |

**Enchanting (附魔):**

Enchanting allows players to add magical effects to weapons, armor, and accessories. The system uses soul gems as a power source and requires knowledge of specific enchantments.

*Soul Gems:* Filled by killing creatures while a Soul Trap effect is active (spell or weapon enchantment). Soul gem tiers determine enchantment power:

| Soul Gem Tier | Soul Capacity | Enchantment Power Multiplier |
|---|---|---|
| Petty | 250 | 0.4x |
| Lesser | 500 | 0.6x |
| Common | 1000 | 0.8x |
| Greater | 2000 | 1.0x |
| Grand | 3000 | 1.2x |
| Black (humanoid souls) | 3000 | 1.3x + unique enchantments unlocked |

*Disenchanting:* To learn an enchantment, the player must disenchant an existing enchanted item, destroying it but permanently learning the enchantment. This creates a meaningful choice: use a powerful found item now, or sacrifice it to gain the ability to replicate its enchantment on optimal gear later.

*Enchantment Application:* The magnitude of an applied enchantment depends on Enchanting skill, soul gem tier, and perks:

```
enchant_magnitude = base_enchant_power * soul_gem_multiplier * (1 + enchanting_skill * 0.01)
                    * perk_multiplier
```

At Enchanting 100 with Grand soul gems and the "Enchanter 5" perk (2.0x), enchantment magnitude is: `base * 1.2 * 2.0 * 2.0 = base * 4.8x`. This allows endgame enchanted items to far exceed naturally found enchanted items in power, rewarding the crafting investment.

Items have limited enchantment slots (see Rarity Tiers in Section 4.2). The "Extra Effect" perk allows one additional enchantment per item beyond its slot limit.

**Cooking (烹饪):**

Cooking is a simpler crafting system providing accessible, consumable buffs. Cooking requires a campfire or kitchen and uses ingredients primarily sourced from hunting (meat), foraging (vegetables, herbs), and vendors.

Cooked food provides long-duration, low-magnitude buffs that stack with potion effects:

| Recipe | Ingredients | Effect | Duration |
|---|---|---|---|
| Grilled Venison | Venison + Salt | +10 max HP, +2 HP regen/s | 600s (10 min) |
| Herb Bread | Flour + Herb Bundle + Salt | +8 max Stamina, +1 Stamina regen/s | 600s |
| Dragon Stew | Dragon Meat + Fire Salt + Rare Spices | +25 max HP, +15 max Stamina, +5% damage | 900s (15 min) |
| Mana Tea | Moon Sugar + Frost Mirriam + Water | +20 max Mana, +1% mana regen in combat | 600s |

Cooking skill increases buff magnitudes by up to 100% at skill level 100. Cooking is intentionally low-investment, high-value to encourage all players to engage with it casually.

### 4.4 Loot Tables

The loot system uses weighted random selection with modifiers based on enemy type, dungeon type, player level, and active effects (such as the Luck attribute and magic find enchantments).

**Enemy-Type Loot Generation:**

Each enemy type references a loot table in `data/loot/enemy_loot.json`. A loot table consists of multiple pools, each with a roll chance and a list of weighted items:

```json
{
  "enemy_type": "bandit_melee",
  "gold_range": [5, 25],
  "loot_pools": [
    {
      "pool_name": "equipped_weapon",
      "roll_chance": 0.75,
      "items": [
        {"item_id": "iron_sword", "weight": 40, "level_min": 1, "level_max": 10},
        {"item_id": "steel_sword", "weight": 30, "level_min": 5, "level_max": 20},
        {"item_id": "orcish_sword", "weight": 15, "level_min": 15, "level_max": 40},
        {"item_id": "ebony_sword", "weight": 5, "level_min": 25, "level_max": 80}
      ]
    },
    {
      "pool_name": "consumable",
      "roll_chance": 0.40,
      "items": [
        {"item_id": "health_potion_minor", "weight": 60},
        {"item_id": "health_potion_standard", "weight": 25},
        {"item_id": "lockpick", "weight": 15}
      ]
    }
  ]
}
```

Items are filtered by the player's current level (items outside the level range are excluded), then selected by weighted random from the remaining pool.

**Dungeon-Type Loot Modifiers:**

Dungeons apply global modifiers to all loot generated within them:

| Dungeon Type | Gold Modifier | Rarity Upgrade Chance | Special Drops |
|---|---|---|---|
| Bandit Camp | 1.0x | 5% | Stolen goods, lockpicks |
| Ancient Tomb | 1.3x | 10% | Enchanted items, spell tomes |
| Dwemer Ruin | 1.5x | 15% | Dwemer materials, schematics |
| Dragon Lair | 2.0x | 20% | Dragon materials, shout words |
| Daedric Shrine | 1.8x | 25% | Daedric materials, unique enchantments |

The "Rarity Upgrade Chance" is a flat probability applied after initial item generation that upgrades the item's rarity by one tier (e.g., Common becomes Uncommon). This is additive with the player's Luck-based rarity bonus: `luck_rarity_bonus = Luck * 0.3%`.

**Boss Loot Guarantees:**

Boss enemies (flagged in `data/enemies/boss_flags.json`) have guaranteed loot drops in addition to their normal loot table:

- Always drop 3x the gold of their normal counterpart.
- Always drop 1 item of Rare or higher quality.
- Always drop 1 unique boss-specific item (first kill only; subsequent kills drop an Epic-quality version).
- World bosses (dragons, daedric princes) always drop 1 Legendary item from a curated list of 3-5 possible drops.

**Level-Scaled Drops:**

All dropped equipment has its base stats scaled to a level within the zone's level range. The item level determines which material tier is used for its base stats, and higher item levels have a progressively higher chance of rolling with enchantments:

```
enchantment_chance = 5% + (item_level * 0.5%) + dungeon_modifier + luck_bonus
```

At item level 50 in a Daedric Shrine with 20 Luck: `5% + 25% + 25% + 6% = 61%` chance of the item having at least one enchantment.

---

## 5. Balance Philosophy

### 5.1 Power Curve Design

The power curve in Eternal Realm follows an S-curve model: rapid early growth, a stable mid-game plateau, and a gradual late-game ascent. This is achieved through the interaction of diminishing returns on individual systems with multiplicative scaling across systems.

**Player Power vs. Enemy Power:**

Player power grows through four independent axes: attributes, skill levels, perks, and gear. Each axis individually follows diminishing returns (attributes have soft caps, skills have exponential XP requirements, perks have limited points, gear has material tier caps), but together they multiply, creating a compound growth curve.

Enemy power scales linearly within each zone. A level 40 enemy has approximately 2.5x the HP and 2.0x the damage of a level 20 enemy. However, a well-built level 40 player character typically deals 4.0x the damage and has 3.0x the effective HP of a level 20 character, due to perk synergies and gear enchantments. This intentional gap rewards build investment and ensures that content trivializes as the player out-levels it, providing a satisfying sense of progression.

The "challenge sweet spot" is designed to be enemies within 5 levels of the player. Enemies more than 10 levels below the player deal less than 10% of the player's HP in damage and die in 1-2 hits. Enemies more than 10 levels above the player deal 50%+ of the player's HP per hit and require sustained engagement, serving as aspirational challenges.

**Soft Caps and Diminishing Returns:**

- **Armor Rating:** The hyperbolic formula `DR = AR / (AR + 300)` ensures that armor stacking yields diminishing returns. The practical cap is approximately 80% reduction at 1200 AR. Going from 600 to 1200 AR gains only 13.5% reduction, while going from 0 to 600 AR gains 66.7%.
- **Attribute Scaling:** Points above 50 cost double, making the investment after 50 half as efficient per gold/point.
- **Enchantment Stacking:** Multiple enchantments of the same type on different gear slots stack additively, not multiplicatively, preventing exponential scaling. "Fortify One-Handed" on 4 pieces gives 4x the single enchantment value, not (1.x)^4.
- **Attack Speed:** Hard-capped at 1.5x base, preventing animation-breaking speeds.

**The "Viable Builds" Spectrum:**

Balance is tuned so that all pure builds (warrior, mage, rogue) and all common hybrid builds (spellsword, nightblade, battlemage) can complete all game content on Normal difficulty. The definition of "viable" is: can defeat the final boss within 5 minutes without consumable stacking. On Legendary difficulty, the viable build spectrum narrows to require optimized gear and perk selection, but no single build is excluded. Balance testing uses automated build simulations defined in `data/balance/build_benchmarks.json`.

### 5.2 Economy Balance

**Gold Inflation Prevention:**

The economy is balanced around a target gold-per-hour rate of 300 gold at level 10, 800 gold at level 30, and 1500 gold at level 50. This is achieved by:

1. Vendor gold reserves limiting sell volume (players cannot dump 10,000 gold worth of loot at one vendor in one visit).
2. Scaling gold sinks (property, training, respec) that increase in cost faster than gold income.
3. Repair costs that passively drain gold from players who use high-tier equipment frequently.
4. A deliberate scarcity of "vendor fodder" enemies (most enemies drop materials, not finished goods).

**Crafting vs. Loot Value Balance:**

Crafted items are designed to be approximately 15% more powerful than equivalent-tier dropped items, justified by the time and skill investment required. However, crafted items cannot have unique legendary effects, which are exclusive to drops and quest rewards. This creates a meaningful choice: craft for reliable, optimized stats, or farm for unique effects. The "ideal endgame setup" typically includes 3-4 crafted pieces and 2-3 unique drops, ensuring both systems are engaged.

**Vendor Price Formulas:**

All vendor pricing follows a unified formula defined in `data/economy/vendor_config.json`:

```
vendor_sell_price = item_base_value * 1.0 * speech_modifier * faction_modifier * rarity_modifier
vendor_buy_price = item_base_value * 0.33 * speech_modifier * faction_modifier
```

Where `faction_modifier` ranges from 0.9 (Honored status, best prices) to 1.1 (Hostile status, worst prices). Players who invest in faction reputation gain a sustained economic advantage.

### 5.3 Combat Balance

**DPS Equivalence Across Weapon Types:**

All weapon types are balanced to achieve approximately equal sustained DPS when used optimally. The balancing metric is "DPS per stamina point spent," ensuring that faster weapons and slower weapons converge:

| Weapon Type | Base Damage | Attack Speed | Stamina/Hit | DPS (sustained) | DPS per Stamina |
|---|---|---|---|---|---|
| Dagger | 12 | 1.5x | 6 | 18.0 | 3.0 |
| Sword | 18 | 1.1x | 8 | 19.8 | 2.475 |
| Axe | 20 | 1.0x | 9 | 20.0 | 2.22 |
| Mace | 22 | 0.9x | 10 | 19.8 | 1.98 |
| Greatsword | 30 | 0.7x | 14 | 21.0 | 1.50 |
| Warhammer | 36 | 0.6x | 18 | 21.6 | 1.20 |

Daggers have the highest DPS-per-stamina but lowest raw DPS and require being in close range. Two-handed weapons have the highest raw DPS but burn stamina faster and are more punishable on whiff. This table represents base-level balance; perks, enchantments, and skill bonuses can skew individual weapon types higher for specialized builds.

**Magic vs. Martial Parity:**

Magic builds achieve competitive DPS through burst windows rather than sustained damage. A Destruction mage deals approximately 80% of a warrior's sustained DPS but has access to AoE damage (effectively multiplying DPS against groups), crowd control (reducing incoming damage), and ranged safety (avoiding melee damage entirely). The trade-off is mana as a limited resource: a mage who exhausts their mana pool must either use potions (a gold cost), switch to a backup weapon, or wait for regeneration. This creates a gameplay rhythm distinct from martial builds.

**Stealth Build Viability:**

Stealth builds trade sustained DPS for burst damage and avoidance. A fully built stealth character can one-shot most non-boss enemies through sneak attacks (15x dagger damage with perks), effectively achieving "infinite DPS" against unaware targets. Against bosses (who are immune to instant kills), stealth builds rely on poison application (which ignores armor), critical hit stacking, and Shadow Warrior resets (re-entering stealth mid-combat to deliver repeated sneak attacks). The DPS is lower than a warrior in a stand-up fight but is competitive when played skillfully.

**Boss Difficulty Tuning:**

Bosses are tuned against a "reference build" at the recommended level with average gear. The reference build should defeat the boss in 3-5 minutes on Normal difficulty, taking approximately 4-6 healing potion equivalents of damage. Boss HP and damage values are defined in `data/enemies/boss_stats.json` and are the most frequently adjusted values during balance passes.

### 5.4 Difficulty Modes

Four difficulty modes modify the core combat experience. Difficulty can be changed at any time from the pause menu, and the current difficulty is saved with the save file.

| Parameter | Easy (简单) | Normal (普通) | Hard (困难) | Legendary (传说) |
|---|---|---|---|---|
| Player damage dealt | 1.5x | 1.0x | 0.75x | 0.5x |
| Player damage taken | 0.5x | 1.0x | 1.5x | 3.0x |
| Enemy HP modifier | 0.75x | 1.0x | 1.5x | 2.5x |
| Enemy damage modifier | 0.75x | 1.0x | 1.25x | 2.0x |
| Enemy AI aggression | -20% | Base | +15% | +30% |
| Enemy dodge frequency | -50% | Base | +25% | +50% |
| Loot quality bonus | -10% | 0% | +10% | +25% |
| XP modifier | 0.8x | 1.0x | 1.2x | 1.5x |

On Legendary difficulty, enemies are genuinely lethal: a same-level enemy deals approximately 50% of a well-geared player's HP per hit, and boss attacks can one-shot careless players. This demands mastery of dodge timing, parrying, potion management, and build optimization. The compensating XP and loot bonuses ensure that Legendary players progress faster in character power, partially offsetting the increased challenge.

Difficulty modifiers are stored in `data/balance/difficulty_modes.json` and are applied as final multipliers after all other damage calculations.

---

## 6. System Interactions

### 6.1 Cross-System Synergies

The true depth of Eternal Realm emerges not from any single system but from the intersections between them. Every major system is designed to feed into and benefit from at least two other systems, creating a web of reinforcing loops that reward holistic engagement.

**Crafting Enhances Combat:**

The most direct cross-system synergy is between crafting and combat. A player who invests in Smithing can create weapons that exceed the damage of any dropped equivalent by 15-20%, and can improve found weapons to legendary quality. Combined with Enchanting, a crafted weapon can carry two powerful enchantments tailored to the player's exact build. The "triple craft" combination of Smithing + Alchemy + Enchanting is the most powerful synergy in the game: the player uses Alchemy to create "Fortify Smithing" potions that boost smithing improvement results, and "Fortify Enchanting" potions that boost enchantment magnitude. This creates a feedback loop:

1. Brew "Fortify Enchanting" potion (Alchemy skill + ingredients).
2. Drink potion, enchant gear with "Fortify Smithing" and "Fortify Alchemy" (Enchanting skill + soul gems).
3. Wear Fortify Alchemy gear, brew stronger potions.
4. Repeat until diminishing returns plateau (approximately 3 iterations).
5. Use final Fortify Smithing potion + gear to improve weapons/armor to maximum values.

This loop is intentionally present as a reward for multi-discipline investment, but is gated by requiring skill level 70+ in all three crafting disciplines, representing 40+ hours of gameplay investment. The diminishing returns ensure the loop converges rather than exploding to infinite power.

**Stealth Interacts with Magic:**

The Illusion school is the bridge between stealth and magic. The "Quiet Casting" perk (Illusion tree, skill 50) makes all spell schools silent, enabling stealth mages to cast Destruction spells without breaking stealth. The "Invisibility" spell (Illusion, skill 75) provides on-demand stealth without requiring physical cover. Combined with the "Silent Storm" perk (Destruction tree, skill 90), a stealth mage can deliver sneak-attack-multiplied spell damage from invisibility.

Alteration also supports stealth through utility: the "Detect Life" spell reveals enemy positions through walls (effectively radar), "Muffle" reduces movement noise, and "Telekinesis" can trigger distant distractions. A pure stealth character benefits enormously from dipping into Alteration and Illusion even without investing in direct combat magic.

Conjuration provides the "shadow summoner" archetype: summon creatures from stealth, let them engage enemies, then pick off distracted targets with sneak attacks. Summoned creatures do not reveal the summoner's position unless the casting is detected.

**Economy Supports Progression:**

Gold enables three progression-critical functions: training (directly purchasing skill XP), crafting materials (buying rare ingredients and soul gems that would take hours to farm), and property (houses provide crafting stations, storage, and rest bonuses that accelerate all other progression). A player who efficiently manages their gold can accelerate their character build by an estimated 20-30% compared to a player who ignores the economy.

The Speech skill is the linchpin of economic engagement: higher Speech means better vendor prices (both buying and selling), access to persuasion-based quest shortcuts (saving combat time), and the ability to invest in merchants (increasing their gold reserves, enabling larger transactions). Speech also unlocks the "Fence" perk, which allows selling stolen goods to any merchant, opening up theft as a gold source that integrates with the stealth system.

**Alchemy Bridges All Systems:**

Alchemy is the most cross-cutting system in the game. Potions enhance combat (Fortify Damage, Resist Element, Restore HP), support crafting (Fortify Smithing, Fortify Enchanting), enable stealth (Invisibility, Muffle), and generate income (high-value potions are the single best gold source per unit of effort). Poisons add a damage channel that bypasses armor, making them critical for stealth builds against high-armor targets. Alchemy ingredients are gathered through exploration, creating a feedback loop where exploring the world directly enhances the player's ability to engage with all other systems.

### 6.2 Build Archetypes

The following archetypes represent the primary build identities supported by the system design. Each archetype lists its primary systems, key perks, and typical gameplay loop.

**Pure Warrior (纯战士):**
- **Primary Systems:** One-Handed or Two-Handed, Block, Heavy Armor, Smithing.
- **Key Perks:** Armsman/Barbarian (damage), Juggernaut (armor), Shield Wall (block efficiency), Smithing perks for improvement.
- **Gameplay Loop:** Engage enemies directly, block/parry attacks, use power attacks to stagger, rely on high HP and armor for survivability. Use smithing to maintain gear superiority. Consumable-light; relies on natural HP regeneration and occasional healing potions.
- **Strengths:** Highest sustained DPS, best survivability against physical damage, simplest execution.
- **Weaknesses:** Vulnerable to magic damage, limited ranged options, no crowd control.

**Pure Mage (纯法师):**
- **Primary Systems:** Destruction, Restoration, Conjuration or Alteration, Enchanting.
- **Key Perks:** Augmented Elements (damage), Dual Casting + Impact (stagger on spells), Recovery (mana regen), Enchanter (mana cost reduction on gear).
- **Gameplay Loop:** Open with AoE damage or summons, manage mana through potion use and regeneration, use wards for defense, enchant gear for mana cost reduction to achieve near-infinite casting in late game.
- **Strengths:** Best AoE damage, ranged safety, crowd control, versatility through spell selection.
- **Weaknesses:** Mana-dependent, squishy without wards, slow start before key perks.

**Pure Rogue (纯盗贼):**
- **Primary Systems:** Sneak, One-Handed (daggers), Archery, Alchemy, Light Armor.
- **Key Perks:** Assassin's Blade (15x dagger sneak), Ranger's Mark (bow sneak damage), Shadow Warrior (re-enter stealth in combat), Poisoner (double poison effectiveness).
- **Gameplay Loop:** Scout areas, plan approach routes, eliminate targets one by one from stealth. Use poison for high-armor targets. Fall back to archery when stealth is broken. Use alchemy for invisibility and buff potions.
- **Strengths:** Highest burst damage (sneak attacks), complete control of engagement, excellent exploration.
- **Weaknesses:** Weak when detected in open combat, boss fights require skill to re-stealth, gear-dependent.

**Spellsword (魔剑士):**
- **Primary Systems:** One-Handed, Destruction, Light/Heavy Armor, Enchanting.
- **Key Perks:** Armsman (melee damage), Augmented Elements (spell damage), Dual Flurry (one-hand + spell dual-wield speed), Enchanter (buff enchantments on gear).
- **Gameplay Loop:** Alternate between melee and magic based on situation. Use Destruction for ranged openers, close to melee for sustained damage, use Restoration for self-healing. Enchant gear to reduce spell costs and boost weapon damage.
- **Strengths:** Extreme versatility, good at every range, self-sufficient healing.
- **Weaknesses:** Master of none; each individual capability is 70-80% of a pure build's power.

**Nightblade (夜刃):**
- **Primary Systems:** Sneak, Illusion, One-Handed (daggers), Alchemy, Light Armor.
- **Key Perks:** Quiet Casting (silent spells), Assassin's Blade, Frenzy Master (turn enemies against each other), Poisoner.
- **Gameplay Loop:** Use Illusion magic (Frenzy, Fear) to manipulate enemies from stealth, then eliminate survivors with sneak attacks. Invisibility spell for repositioning. Alchemy for powerful poisons and support potions.
- **Strengths:** Complete encounter control, can clear entire dungeons without direct combat, excellent against groups.
- **Weaknesses:** Low direct combat power if caught, heavily perk-dependent, complex execution.

**Battlemage (战斗法师):**
- **Primary Systems:** Heavy Armor, Destruction, Conjuration, Two-Handed, Enchanting.
- **Key Perks:** Juggernaut (armor), Atromancy (long summon duration), Augmented Elements, Barbarian (two-hand damage).
- **Gameplay Loop:** Summon a creature for tanking/DPS, cast AoE Destruction spells, then wade into melee with a two-handed weapon for cleanup. Heavy armor provides survivability during melee engagement. Enchant gear for mana cost reduction and weapon damage.
- **Strengths:** Combines the survivability of a warrior with the AoE of a mage, good action economy through summons.
- **Weaknesses:** Very attribute-hungry (needs STR, INT, CON), slow to reach full potential, mana management is critical.

---

## 7. Technical Implementation Notes

### 7.1 Three.js/WebGL Considerations

Eternal Realm targets a draw call budget of 500 per frame, a triangle budget of 500,000 per frame, and a texture memory budget of 512 MB. These constraints are significantly tighter than native PC RPGs and require aggressive optimization throughout all visual systems.

**Performance Budgets for Particle Effects:**

Spell effects are the highest-cost visual system. Each particle system is budgeted as follows:

| Effect Category | Max Particles | Max Draw Calls | Texture Budget | Example |
|---|---|---|---|---|
| Small spell (single target) | 200 | 2 | 256x256 atlas | Firebolt, Heal |
| Medium spell (AoE) | 500 | 4 | 512x512 atlas | Fireball explosion, Blizzard |
| Large spell (ultimate) | 1000 | 6 | 512x512 atlas | Meteor, Storm Call |
| Ambient (ongoing) | 100 | 1 | 128x128 atlas | Enchantment glow, torch fire |
| UI feedback | 50 | 1 | 128x128 atlas | Damage numbers, level-up flash |

All particle systems use `THREE.Points` or instanced `THREE.InstancedMesh` rather than individual mesh objects to minimize draw calls. Particles are rendered with additive blending for light effects and alpha blending for smoke/dust, using a shared particle material pool to reduce shader compilations.

Particle LOD is implemented by distance: beyond 20 meters, particle counts are halved; beyond 40 meters, particle systems are replaced with billboard sprites; beyond 60 meters, they are culled entirely. This is managed by a central `ParticleManager` class that enforces the per-frame budget and prioritizes player-facing effects.

**LOD System for Spell Effects:**

All spell effects use a three-tier LOD system:

- **LOD 0 (0-15m):** Full effect with all particles, dynamic lighting (point light attached to the projectile), and post-processing bloom contribution.
- **LOD 1 (15-35m):** Reduced particles (50%), no dynamic lighting (replaced by vertex color bake), no bloom contribution.
- **LOD 2 (35m+):** Sprite billboard replacement, no particles, no dynamic lighting.

Dynamic lighting from spells is capped at 4 simultaneous point lights across all active spell effects. When the cap is reached, the oldest light is removed. Light intensity is calculated using `THREE.PointLight` with quadratic attenuation and a maximum range of 8 meters, ensuring minimal impact on the forward rendering pipeline.

**Physics Simplifications for Web Platform:**

Eternal Realm does not use a full rigid-body physics engine. Instead, it employs a simplified physics model:

- **Character Movement:** Capsule-based collision with a custom swept-sphere test against the navmesh and static geometry. No physics-based character control; all movement is kinematic.
- **Projectiles:** Raycast-per-frame (not continuous collision detection), with the secondary tunneling check described in Section 2.2.
- **Environmental Interaction:** Trigger volumes only (entering a water volume applies "Wet" status, entering a fire volume applies "Burning"). No destructible environment or dynamic objects beyond scripted events.
- **Ragdoll:** Not implemented. Death animations use pre-baked animation clips selected by damage direction. This saves significant CPU cost compared to real-time ragdoll simulation.
- **Cloth/Hair:** Simulated using vertex shader sine-wave displacement, not cloth physics. Provides convincing motion at negligible GPU cost.

The physics update runs at a fixed 30 Hz tick rate, decoupled from the render frame rate, to ensure deterministic behavior across different hardware. Physics state interpolation smooths the visual result at higher frame rates.

### 7.2 Data-Driven Architecture

All game balance data, item definitions, enemy stats, loot tables, and progression curves are stored in JSON files loaded at runtime. No balance values are hard-coded in the game logic.

**JSON-Based Game Data Loading:**

The data loading pipeline operates in three stages:

1. **Manifest Loading:** On game start, `data/manifest.json` is fetched. This file lists all data files with their paths, version hashes, and load priority. Critical data (attributes, base items) loads first; secondary data (lore text, ambient dialogue) loads asynchronously during gameplay.

2. **Validation:** Each JSON file is validated against a JSON Schema (stored in `data/schemas/`) on load. Invalid data triggers a console warning and falls back to default values, ensuring the game remains playable even with corrupted data files.

3. **Runtime Access:** Data is accessed through a singleton `GameData` service that provides typed getters:

```javascript
// Example: accessing weapon data
const weapon = GameData.getItem("weapon_ebony_sword");
// Returns: { id, name, name_cn, base_damage, weight, material, value, ... }

// Example: evaluating a formula at runtime
const damage = GameData.evaluateFormula("melee_damage", {
  base_damage: weapon.base_damage,
  skill_level: player.skills.one_handed,
  strength: player.attributes.strength,
  // ...
});
```

**Runtime Formula Evaluation:**

Formulas are defined as string expressions in JSON and evaluated by a sandboxed expression parser (no `eval()` for security). The parser supports basic arithmetic, comparison operators, `min()`, `max()`, `floor()`, `ceil()`, and variable substitution:

```json
{
  "formula_id": "melee_damage",
  "expression": "(base_damage + strength * 2) * (1 + skill_level * 0.005) * perk_multiplier * stance_modifier",
  "variables": ["base_damage", "strength", "skill_level", "perk_multiplier", "stance_modifier"]
}
```

This architecture allows balance tuning by modifying JSON files without rebuilding the game, and supports hot-reloading in development mode via a WebSocket-based file watcher.

**Mod Support Considerations:**

While full mod support is not in the initial release scope, the data-driven architecture is designed to accommodate it. The `data/manifest.json` system supports overlay loading: a mod provides its own manifest that lists JSON files to override or extend. Mod files are loaded after base game files, with mod values taking precedence. This allows mods to add new items, modify balance values, create new enemies, and alter loot tables without modifying base game files. A future modding API will expose the `GameData` service and provide hooks for custom game logic written in JavaScript.

### 7.3 Network Considerations

**Save System Design:**

Eternal Realm is a single-player game with no real-time multiplayer. The save system uses a two-tier approach:

1. **LocalStorage (Primary):** Game state is serialized to JSON and stored in the browser's LocalStorage. Save data is compressed using LZ-String to stay within the 5-10 MB LocalStorage limit. Each save file is approximately 200-500 KB compressed, allowing 10-20 save slots. Auto-save triggers on zone transitions, quest completions, and every 5 minutes of real-time play.

2. **Cloud Sync (Secondary):** When the player is signed in (via OAuth with Google/Discord/custom account), save data is synced to a backend server. Cloud saves are uploaded on auto-save triggers and downloaded on game start if the cloud save is newer than the local save. The sync protocol uses versioned saves with conflict resolution: if both local and cloud have been modified since the last sync, the player is prompted to choose which to keep.

Save data structure (simplified):

```json
{
  "version": "1.0.0",
  "timestamp": 1742860800,
  "play_time_seconds": 36000,
  "character": {
    "name": "Aldric",
    "race": "human",
    "class": "warrior",
    "level": 25,
    "attributes": { "strength": 28, "dexterity": 15, "...": "..." },
    "skills": { "one_handed": 52, "block": 38, "...": "..." },
    "perks": ["armsman_3", "juggernaut_2", "shield_wall_1"],
    "inventory": [ "..." ],
    "equipment": { "main_hand": "steel_sword_fine", "...": "..." }
  },
  "world_state": {
    "quests": { "main_quest_01": "completed", "...": "..." },
    "discovered_locations": ["greenwood_village", "stonereach_mine"],
    "killed_bosses": ["bandit_chief_01"],
    "containers_looted": ["chest_0042", "chest_0117"],
    "npc_dispositions": { "merchant_01": 75, "...": "..." }
  }
}
```

**Anti-Cheat for Client-Side Game:**

As a browser game, all game logic runs client-side, making traditional anti-cheat impossible. Eternal Realm takes a pragmatic approach:

- **No competitive multiplayer:** Since the game is single-player, cheating is a personal choice that does not affect other players. There is no leaderboard or competitive element.
- **Save integrity checks:** Save files include a SHA-256 checksum of the game state. If the checksum does not match on load, the save is flagged as "modified" and achievements are disabled for that playthrough. This discourages casual editing without punishing it.
- **Obfuscation only:** Game data in memory is lightly obfuscated (XOR encoding with a session-specific key) to prevent trivial memory editors, but no attempt is made to prevent determined modification. The design philosophy is that players who want to cheat in a single-player game should be allowed to do so without it affecting the experience of players who do not.
- **Achievement validation:** Achievements that are synced to the player's account are validated server-side by checking that the save state is consistent with the achievement criteria (e.g., "defeat the final boss" checks that the boss is in the killed list and the player's level is within a plausible range).

---

## 8. Appendix

### 8.1 Key Formulas Reference Table

A consolidated reference of all major formulas used across game systems.

| Formula Name | Expression | Section Reference |
|---|---|---|
| **Melee Damage** | `(base_damage + STR*2) * attack_mult * (1 + skill*0.005) * perk * stance * sneak * crit * elem * (1 - DR) + flat_bonus` | 2.5 |
| **Armor Damage Reduction** | `AR / (AR + 300)` | 2.5 |
| **Spell Damage** | `base_spell_dmg * (1 + skill*0.01) * (1 + INT*0.02) * perk * elem_modifier` | 2.3 |
| **Effective Spell Cost** | `base_cost * (1 - skill_level * 0.004)` | 2.3 |
| **Max HP** | `100 + (CON * 12) + (Level * 5) + racial_bonus` | 3.1 |
| **Max Mana** | `100 + (INT * 8) + (WIL * 5) + (Level * 3) + racial_bonus` | 3.1 |
| **Max Stamina** | `100 + (END * 8) + (Level * 4) + racial_bonus` | 3.1 |
| **Attack Speed** | `min(1.0 + DEX * 0.01, 1.5)` | 3.1 |
| **Critical Chance** | `5% + (LCK * 0.5%) + perk_bonus + weapon_bonus + enchant_bonus` | 2.5 |
| **Visual Detection** | `(light * 100) * (1 / (dist * 0.1)) * profile * (1 - sneak_skill * 0.005)` | 2.4 |
| **Audio Detection** | `noise * (1 / (dist * 0.15)) * (1 - sneak_skill * 0.004)` | 2.4 |
| **Skill XP to Next Level** | `base_xp * (1.08 ^ current_level)` | 3.2 |
| **Character XP to Level N** | `25 * N^1.8` | 3.4 |
| **Potion Magnitude** | `base_magnitude * (1 + alchemy_skill * 0.008) * perk * ingredient_quality` | 4.3 |
| **Enchantment Magnitude** | `base_power * soul_gem_mult * (1 + enchanting_skill * 0.01) * perk` | 4.3 |
| **Vendor Sell Price** | `base_value * 0.33 * speech_mod * faction_mod` | 5.2 |
| **Vendor Buy Price** | `base_value * 1.0 * speech_mod * faction_mod * rarity_mod` | 5.2 |
| **Enchantment Drop Chance** | `5% + (item_level * 0.5%) + dungeon_mod + luck_bonus` | 4.4 |
| **Stamina Drain on Block** | `incoming_damage * (1 - block_efficiency) * 0.5` | 2.1 |
| **Projectile Position Y** | `initial_y + (vel_y * t) - (0.5 * 9.81 * t^2)` | 2.2 |
| **Mana Regen (Combat)** | `max_mana * (0.005 + WIL * 0.0005) per second` | 2.3 |
| **Weight Stamina Factor** | `1 + (weapon_weight - 10) * 0.03` | 2.1 |

### 8.2 Glossary of Game Terms (English/Chinese)

| English Term | Chinese Term | Definition |
|---|---|---|
| Attribute | 属性 | One of 8 primary character statistics (STR, DEX, CON, INT, WIL, END, PER, LCK). |
| Combo Route | 连招路线 | A specific input sequence that triggers a unique attack animation with bonus effects. |
| Critical Hit | 暴击 | An attack that deals bonus damage, determined by critical chance percentage. |
| Damage Reduction (DR) | 伤害减免 | The percentage of incoming damage absorbed by armor or resistance. |
| Derived Stat | 派生属性 | A stat calculated from primary attributes (e.g., Max HP, Attack Speed). |
| Diminishing Returns | 收益递减 | A scaling model where each additional point of investment yields less benefit. |
| Draw Call | 绘制调用 | A single command sent to the GPU to render geometry; a key performance metric. |
| Enchantment | 附魔 | A magical effect applied to equipment, providing stat bonuses or special abilities. |
| Faucet/Sink | 水龙头/水槽 | Economy design terms for gold sources (faucets) and gold drains (sinks). |
| I-Frame | 无敌帧 | Invincibility frames during dodge/roll animations where damage is ignored. |
| LOD (Level of Detail) | 细节层次 | A rendering optimization that reduces visual complexity at distance. |
| Loot Table | 掉落表 | A data structure defining what items an enemy or container can drop, with probabilities. |
| Navmesh | 导航网格 | A mesh overlay defining walkable surfaces for AI pathfinding. |
| Parry | 弹反 | A precision-timed block that negates all damage and staggers the attacker. |
| Perk | 天赋 | A permanent ability unlocked by spending perk points in a skill tree. |
| Racial Ability | 种族技能 | A unique ability available to each race, usable once per in-game day. |
| Rarity Tier | 稀有度 | The quality level of an item (Common, Uncommon, Rare, Epic, Legendary). |
| Respec | 重置 | The act of resetting allocated skill points or perk points for redistribution. |
| Sneak Attack | 潜行攻击 | An attack against an unaware target that receives a damage multiplier. |
| Soft Cap | 软上限 | A threshold beyond which further investment yields reduced returns. |
| Soul Gem | 灵魂石 | A container used to capture souls for enchanting purposes. |
| Stagger | 失衡 | A status that interrupts the target's current action and briefly incapacitates them. |
| Stance | 姿态 | A combat mode (Aggressive or Defensive) that modifies damage and defense parameters. |
| Status Effect | 状态效果 | A temporary condition applied to an entity (Burning, Chilled, Poisoned, etc.). |
| Zone Level | 区域等级 | The level range of a game zone that determines enemy levels and loot scaling. |
| Spell School | 法术流派 | One of 5 categories of magic (Destruction, Restoration, Conjuration, Alteration, Illusion). |
| Triple Craft | 三重制造 | The synergy loop of Smithing + Alchemy + Enchanting for maximum gear optimization. |
| Guard Break | 破防 | A state triggered when stamina is depleted while blocking, leaving the player vulnerable. |
| Riposte | 反击 | A guaranteed critical hit opportunity that opens after a successful parry. |
| Aggro | 仇恨 | The AI targeting priority system that determines which player/NPC an enemy attacks. |
| Build Archetype | 构建原型 | A character build template (e.g., Pure Warrior, Nightblade) that defines playstyle. |

---

*End of Document*

*Eternal Realm (永恒之域) Game Systems Design Document v1.0 -- Confidential -- For Internal Use Only*
