# FREEEXILE: CLIENT ARCHITECTURE & ASSET SURVEY FOR COCOS CREATOR 3.X PORT

**Author:** `explorer_survey_1` (Teamwork Preview Explorer)  
**Date:** 2026-10-03  
**Target Port Location:** `client/cocos/` (TypeScript / Cocos Creator 3.x)  
**Input Reference:** `ORIGINAL_REQUEST.md` (2026-10-03T07:43:50Z), `AGENTS.md`, `client/webapp/`  

---

## 1. EXECUTIVE SUMMARY & MIGRATION STRATEGY

FreeExile is currently running a highly optimized HTML5 Canvas 2D WebApp client located at `client/webapp/`. The client architecture features a decoupled render loop, 2.5D isometric projection (classic 2:1 ratio), procedural tile maps, skeletal atlas animation, visceral PoE2 combat dynamics, 9-language reactive localization, and dual-layer network support (standalone local simulation & WebSocket RFC 6455 bridge to port 8080).

The objective of this survey is to establish an **authoritative technical specification** to port the entire client into **Cocos Creator 3.x (TypeScript)** at `client/cocos/`. This includes:
1. Exact mapping of kinematic math, zero-residual momentum, collision, and A* pathfinding.
2. Complete inventory of 21 animation atlas entities (characters, monsters, bosses) and 250+ environment/UI/weapon/currency assets.
3. Combat FSM, input buffering, combo cycles, telegraph decals, and hit-stop feel.
4. Scene structures for Sanctuary (Doanh Trại Bến Lưu Đày) and Procedural Dungeons (Phụ Bản Ngục Tối).
5. UI HUD components (dual liquid orbs, 40-slot backpack, minimap with fog) and reactive 9-language i18n.
6. Server-authoritative WebSocket networking using Protobuf schemas.
7. Blueprint for Cocos Creator 3.x project layout, components, prefabs, and preview toolchain.

---

## 2. KINEMATICS, MOVEMENT & CAMERA TRACKING

### 2.1. Isometric Projection Mathematics
- **Reference File:** `client/webapp/js/engine/iso_math.js` (Lines 155–183) & `client/src/render/IsometricCamera.ts`
- **Tile Geometry:** Isometric diamond with 2:1 ratio:
  $$\text{TILE\_W} = 64\text{ px}, \quad \text{TILE\_H} = 32\text{ px}$$
- **World to Screen Projection Formula:**
  Given world coordinates $(w_x, w_y, w_z)$, camera position $(c_x, c_y)$, viewport center $(v_x, v_y)$, and zoom factor $Z$:
  $$\text{relW}_x = w_x - c_x, \quad \text{relW}_y = w_y - c_y$$
  $$S_x = (\text{relW}_x - \text{relW}_y) \times \left(\frac{\text{TILE\_W}}{2}\right) \times Z + v_x$$
  $$S_y = (\text{relW}_x + \text{relW}_y) \times \left(\frac{\text{TILE\_H}}{2}\right) \times Z + v_y - (w_z \times 24 \times Z)$$
- **Screen to World Unprojection Formula:**
  Given screen coordinates $(S_x, S_y)$:
  $$s_x = \frac{S_x - v_x}{Z}, \quad s_y = \frac{S_y - v_y}{Z}$$
  $$\text{relW}_x = \frac{s_x / (\text{TILE\_W}/2) + s_y / (\text{TILE\_H}/2)}{2}$$
  $$\text{relW}_y = \frac{s_y / (\text{TILE\_H}/2) - s_x / (\text{TILE\_W}/2)}{2}$$
  $$w_x = \text{relW}_x + c_x, \quad w_y = \text{relW}_y + c_y$$

### 2.2. Zero-Residual Momentum & Player Movement
- **Reference File:** `client/webapp/js/engine/canvas_renderer.js` (Lines 31–75, 129–203)
- **Mechanics:**
  - Movement is strictly controlled by digital inputs (WASD / Arrow Keys) or analog touch joystick ($m_x, m_y$).
  - Vector magnitude: $\text{mag} = \sqrt{m_x^2 + m_y^2}$.
  - Threshold guard: If $\text{mag} \le 0.05$, the player comes to an **instant halt** ($\text{zero-residual momentum}$).
  - Movement integration:
    $$\Delta x = \left(\frac{m_x}{\text{mag}}\right) \times \text{speed} \times \text{boost} \times \Delta t$$
    $$\Delta y = \left(\frac{m_y}{\text{mag}}\right) \times \text{speed} \times \text{boost} \times \Delta t$$
    where $\text{speed} = 5.5\text{ world units/s}$, and $\text{boost} = 1.75$ during Dodge i-frame roll.
  - **Instant Snap-Freeze on Release:** When $\text{mag} \le 0.05$, `player.dirX = 0`, `player.dirY = 0`, `player.leanAngle = 0`, and `animState` switches from `run` to `idle` in $\le 1$ frame without residual rotation drift.

### 2.3. Isometric 8-Direction Heading
- **Reference File:** `client/webapp/js/engine/animation_engine.js` (Lines 76–83, 154–162)
- **Calculation:**
  $$\text{screenDirX} = (m_x - m_y) \times 0.5, \quad \text{screenDirY} = (m_x + m_y) \times 0.25$$
  $$\text{targetAngle} = \text{atan2}(\text{screenDirY}, \text{screenDirX})$$
  $$\text{deg} = \frac{\text{smoothAngle} \times 180}{\pi} \pmod{360}$$
- **8-Way Direction Bins:**
  - $337.5^\circ - 22.5^\circ \rightarrow \text{E}$
  - $22.5^\circ - 67.5^\circ \rightarrow \text{SE}$
  - $67.5^\circ - 112.5^\circ \rightarrow \text{S}$
  - $112.5^\circ - 157.5^\circ \rightarrow \text{SW}$
  - $157.5^\circ - 202.5^\circ \rightarrow \text{W}$
  - $202.5^\circ - 247.5^\circ \rightarrow \text{NW}$
  - $247.5^\circ - 292.5^\circ \rightarrow \text{N}$
  - $292.5^\circ - 337.5^\circ \rightarrow \text{NE}$
- **Turn Inertia Lerp:**
  $$\text{smoothAngle} = \text{lerpAngle}(\text{smoothAngle}, \text{targetAngle}, \text{turnRate} \times \Delta t)$$
  where $\text{turnRate} = 18.0\text{ rad/s}$. When $\text{mag} \le 0.05$, `lerpAngle` is completely skipped, freezing the facing angle immediately.

### 2.4. Camera Tracking (Exponential Lerp & Dynamic Zoom)
- **Reference File:** `client/webapp/js/engine/iso_math.js` (Lines 120–153, 185–190)
- **Follow Formula:**
  $$d_x = \text{targetW}_x - c_x, \quad d_y = \text{targetW}_y - c_y, \quad \text{dist} = \sqrt{d_x^2 + d_y^2}$$
  $$\text{If } \text{dist} > \text{deadzone} (0.0): \quad \text{factor} = 1.0 - e^{-\text{followSpeed} \times \Delta t}$$
  $$c_x \mathrel{+}= d_x \times \text{factor}, \quad c_y \mathrel{+}= d_y \times \text{factor}$$
  where $\text{followSpeed} = 8.0$.
- **Camera Boundary Clamping:** Clamped to active zone bounds $[\text{minCamWx}, \text{maxCamWx}] \times [\text{minCamWy}, \text{maxCamWy}]$.
- **Dynamic Zoom:** Smooth mouse wheel/pinch zoom in range $[0.5, 1.5]$ with lerp rate $10.0 \times \Delta t$.

### 2.5. Collision Engine & Two-Axis Wall Sliding
- **Reference File:** `client/webapp/js/engine/collision_engine.js` (Lines 24–40, 97–222)
- **Tile Passability Bitmask:**
  - Standard 20-code schema: `VOID (0)`, `WALL (2)`, `DESTRUCTIBLE_BARRICADE (3)`, `CHASM (9)`, `BOSS_GATE (10)`, `WATER (19)` are blocked.
  - Chasm leap: If `isDodge === true`, `CHASM` is passable.
  - Boss Gate: If unlocked (`bossGateBreached === true`), `BOSS_GATE` is passable.
- **Circle-AABB Collision Test:**
  Entity circle of radius $R = 0.35$ against adjacent tiles:
  $$c_x = \text{clamp}(w_x, t_x, t_x + 1), \quad c_y = \text{clamp}(w_y, t_y, t_y + 1)$$
  $$\text{Blocked if } (w_x - c_x)^2 + (w_y - c_y)^2 < R^2$$
- **Two-Axis Wall Sliding Algorithm:**
  1. Test direct destination $(w_x + \Delta x, w_y + \Delta y)$. If clear, proceed.
  2. Test X-axis movement $(w_x + \Delta x, w_y)$. If clear, slide along X.
  3. Test Y-axis movement $(w_x, w_y + \Delta y)$. If clear, slide along Y.
  4. If both single axes clear, select the dominant axis $(\max(|\Delta x|, |\Delta y|))$ to prevent getting stuck in diagonal corners.
  5. 45-degree isometric corner deflection fallback.

### 2.6. Zero-Heap A* Grid Pathfinder
- **Reference File:** `client/webapp/js/engine/grid_pathfinder.js` (Lines 10–67, 100–200)
- **Data Structures:** Pre-allocated typed arrays: `visitedIteration (Uint32Array)`, `cameFrom (Int32Array)`, `gScore (Float32Array)`, `fScore (Float32Array)`, flat 1-based binary min-heap `heapNode (Int32Array)`, `heapF (Float32Array)`.
- **Search Logic:**
  - Fast DDA Supercover Line-of-Sight check first. If direct LoS exists, skip A*.
  - 8-directional search with diagonal corner-cutting avoidance.
  - Move cost: Orthogonal $= 1.0$, Diagonal $= 1.414$.
  - Heuristic: Euclidean distance $\sqrt{(g_x - x)^2 + (g_y - y)^2}$.
  - Reconstructed path returned into pre-allocated Float32Array coordinates.

---

## 3. ANIMATION ENGINE & SKELETAL FSM

### 3.1. Atlas Manifest Architecture
- **Reference File:** `client/webapp/assets/animations/*_anim_manifest.json` & `animation_engine.js`
- **Standard Layout:**
  - Texture size: $1280 \times 960$ (Hero/Classes) or $1280 \times 480$ (Monsters).
  - Frame size: $160 \times 192$ (Hero/Classes) or $160 \times 160$ (Monsters).
  - Columns: $\text{cols} = \min(8, \lfloor \text{texture\_width} / \text{frame\_width} \rfloor) = 8$.
  - Fixed Pivot: $[0.5, 0.90]$ (bottom-center anchor).
- **Global Index & Aliasing:**
  - Clips: `idle`, `run`, `attack_slash`, `skill_whirlwind`, `dodge`, `hurt`, `death`.
  - Clip aliasing: Some clips have `atlas_clip` (e.g., `attack_thrust` $\rightarrow$ `attack_slash`). Aliased clips are skipped during sequential index calculation to prevent frame shifting.

### 3.2. Motion-Matched Foot-Speed Synchronization
- **Formula:**
  $$\text{playback\_fps} = \text{base\_fps} \times \max\left(0.2, \frac{v_{\text{current}}}{v_{\text{base}}}\right)$$
  where $v_{\text{base}} = 4.2\text{ world units/s}$, and `base_fps` for run $= 12-14\text{ fps}$.
- **Footstep Event Keyframes:**
  - Hero `run`: Frames $0$ and $4$ trigger footstep dust particle and audio FX.
  - Hellhound `run`: Frames $1$ and $4$.
  - Skeleton Warrior `run`: Frames $0$ and $3$.

### 3.3. Kinetic Phases State Machine
- **Phases:** `IDLE`, `RUN`, `WIND_UP`, `IMPACT`, `RECOVERY`, `HIT_STOP`, `DODGE`.
- **Damage Keyframe Alignment:**
  - If `frameIndex < clip.hit_frame` $\rightarrow$ `WIND_UP`
  - If `frameIndex === clip.hit_frame` $\rightarrow$ `IMPACT` (triggers `onHit` callback, damage calculation, screen shake, and hit-stop)
  - If `frameIndex > clip.hit_frame` $\rightarrow$ `RECOVERY`

---

## 4. COMBAT MECHANICS, COMBOS & VISCERAL FEEL

### 4.1. Combat Input & Combo Cycles
- **Reference File:** `client/webapp/js/engine/combat_skills.js` (Lines 305–335) & `client/webapp/js/ui/skill_bar_controller.js`
- **Skill Mapping:**
  - `LMB`: Primary Weapon Attack (`attack_slash`), 3-step combo cycle ($1 \rightarrow 2 \rightarrow 3$).
    - Step 1: Base damage ($1.0\times$)
    - Step 2: Intermediate strike ($1.3\times$)
    - Step 3: Finisher cleave ($1.75\times$ damage + heavy screen shake)
  - `Q` / `1`: Liệt Huyết Cuồng Trảm (Infernal Blood Cleave) — Flying projectile slash ($560\text{ px/s}$).
  - `2` / `E`: Huyết Lôi Ma Kích (Blood Lightning Lance) — 7-segment fractal lightning dart ($920\text{ px/s}$).
  - `4` / `R`: Hủ Cốt Hàn Độc (Necrotic Bone Javelins) — 3-javelin forward spread ($500\text{ px/s}$).
  - `Space` / `Shift`: Huyễn Ảnh Bộ (Phantom Evasion Dodge) — 0.25s i-frame, $1.75\times$ speed boost, ghost trails.
  - `4` (Item): Bình Khí Huyết (Health Potion) — 6.0s CD, 3 charges.

### 4.2. Visceral Feel Engine
- **Reference File:** `client/webapp/js/engine/combat_feel_engine.js` (Lines 1–250)
- **Hit-Stop Micro-Freeze:**
  - On impact, freezes frame advancement for 2–4 frames ($33-66\text{ ms}$).
  - Freezes both attacker and target animations (`hitStopTimer`).
- **Pre-Allocated 64-Slot Damage Number Pool:**
  - Zero garbage collection: Fixed ring buffer of 64 `DamageNumberSlot` instances.
  - Animation: Pop-in scale bounce ($1.6\times \rightarrow 1.0\times$ for normal, $2.0\times \rightarrow 1.2\times$ for crit in first 20% of lifetime), upward deceleration drift ($-28\text{px}$ to $-42\text{px}$), and alpha fadeout in final 35%.
- **Directional Screen Shake:**
  - Intensity: $2.5$ to $8.5\text{ px}$, duration $0.12$ to $0.45\text{ s}$.

### 4.3. Attack Telegraph Decals
- **Reference File:** `client/webapp/js/engine/telegraph_renderer.js`
- **Decal Types:** `cone`, `circle`, `ring`, `line`.
- **Windup Timing:** 0.6s to 1.2s warning progression ($0.0 \rightarrow 1.0$).
- **PoE2 Stagger Interruption:** If boss/monster poise breaks (`staggerTimer > 0`) or entity dies, active telegraph is **instantly cancelled**.

### 4.4. Target Dummy Telemetry
- **Reference File:** `client/webapp/js/engine/target_dummy_telemetry.js`
- **Metrics Tracked:** Real-time combo streak, rolling window DPS (5s burst / 30s sustained), peak DPS, highest single hit, total damage, crit rate.
- **Safety:** Target Dummy is immortal (`isDummy: true`, HP locked to 100%).

---

## 5. SCENE ARCHITECTURE & DEPTH SORTING

### 5.1. Sanctuary (Doanh Trại Bến Lưu Đày)
- **Reference Files:** `client/webapp/js/data/sanctuary_props_catalog.js`, `world_renderer.js`
- **Zone ID:** `zone_boundless_sanctuary`
- **Safe Haven Guarantee:** Zero hostile monsters allowed. 100% walkable central plaza ($r \le 4.5$).
- **Districts:**
  1. Central Plaza & Waypoint: Stone Waypoint at $(0, 0)$.
  2. East District (Blacksmith Bone Forge): Lò Rèn Huyết Thiết $(9.5, 0.0)$, NPC Thiết Tượng Huyết Đồ $(7.5, 0.0)$.
  3. West District (Outcast Bazaar): Sạp Hàng Chợ Đen $(-9.5, 0.0)$, NPC Gian Thương Cẩu Khấu $(-7.5, 0.0)$.
  4. South-West Martial District: Cổ Thụ Hoàng Kim $(-8.5, 6.5)$, NPC Huyết Vu Bà Bà $(-6.5, 5.5)$.
  5. North District (Town Headquarters): Trụ Sở Mái Ngói $(0.0, -14.5)$, NPC Bách Hiểu Sinh $(6.5, 5.5)$.
  6. Astral Map Portal Device: Located at $(0.0, -6.0)$.

### 5.2. Dungeon & Wilderness (Phụ Bản Ngục Tối)
- **Reference Files:** `server/world/procedural_map_engine.py`, `boss_gate_controller.js`, `wilderness_zone_packs.js`
- **Zone ID:** `zone_tang_kiem_nhai` (and 9 other wilderness zones).
- **Procedural Tile Grid:** Compact `Uint8Array` ($60 \times 45$ to $120 \times 90$ tiles).
- **Encounter Progression & Boss Gate:**
  - Boss Gate starts in `LOCKED` state, blocking movement across the threshold tile.
  - Tracking: `zoneEncounterProgress` records defeated monster packs.
  - Unlock threshold: When required kills are reached (e.g. 3 packs), `BossGateController.unlock()` turns gate tile to walkable floor and triggers rune explosion visual.
  - Breach: Entering the unlocked gate transitions into the Boss Arena (`boss_abyssal_tyrant` or `boss_blood_bone_ravager`).

### 5.3. 2.5D Isometric Depth Sorting (Y-Sorting)
- **Reference File:** `client/webapp/js/engine/entity_renderer.js` (Lines 50–116)
- **Sorting Metric:**
  $$\text{depth} = w_x + w_y$$
- **Entities in Sorting Queue:**
  - Environment props (using ground footprint center $w_x + \text{offsetX} + w_y + \text{offsetY}$)
  - Monsters & Bosses
  - NPCs
  - Player character
  - Ground loot drops
- Entities are rendered in ascending order of depth, guaranteeing pixel-perfect occlusion between foreground props, characters, and background walls.

---

## 6. UI HUD & REACTIVE MULTI-LANGUAGE (i18n)

### 6.1. Dual Liquid Orbs (Life & Mana)
- **Reference File:** `client/webapp/js/ui/hud_orbs.js`
- **Rendering:** High-DPI canvas circular clip mask ($r = 78\text{px}$).
- **Fluid Dynamics:** Real-time sinusoidal wave equation:
  $$y_{\text{wave}}(x) = y_{\text{fill}} + \sin(x \times 0.05 + t \times 3.0) \times 4.5 + \cos(x \times 0.03 - t \times 2.0) \times 2.5$$
- **Color Gradients:**
  - Life Orb: Crimson dark `#7f1d1d` $\rightarrow$ Blood red `#dc2626` $\rightarrow$ Highlight `#f87171`.
  - Mana Orb: Deep abyss `#1e1b4b` $\rightarrow$ Azure `#2563eb` $\rightarrow$ Etheric `#60a5fa`.
- **Low-HP Alert:** Triggers red screen vignette pulse when $\text{HP} / \text{MaxHP} < 25\%$.

### 6.2. Minimap with Fog of War
- **Reference File:** `client/webapp/js/ui/minimap_hud.js`
- **Viewport:** $120 \times 80\text{ px}$.
- **Radar Blips:** Player dot (white with heading cone), Waypoints (emerald green `#10b981`), Boss Gate (crimson `#ef4444`), POIs (amber `#f59e0b`).
- **Fog of War States:**
  - $0 = \text{UNEXPLORED}$ (solid black)
  - $1 = \text{EXPLORED\_FOGGED}$ (darkened biome tint)
  - $2 = \text{VISIBLE}$ (full biome color)

### 6.3. 40-Slot Survival Backpack & Stash
- **Reference File:** `client/webapp/js/ui/inventory_stash.js`
- **Grid Layout:** 40 slots ($8 \times 5$ or $5 \times 8$).
- **Item Sizes:** $1 \times 1$ (currencies, gems, consumables), $2 \times 3$ (shields, helmets), $2 \times 4$ (two-handed weapons).
- **Rarity Tier Styling:** Phàm Phẩm (gray), Linh Phẩm (blue), Cực Phẩm (amber), Thần Thoại (red/crimson).

### 6.4. NPC Dialogue System
- **Reference Files:** `client/webapp/js/ui/dialogue_npc.js`, `npc_dialogue_catalog.js`
- **Node-Based Conversation Trees:** Multi-step branching dialogues with speaker name, title, avatar portrait, and action triggers (e.g. open shop, open forge, start quest).

### 6.5. 9-Language Reactive Localization (i18n)
- **Reference Files:** `client/webapp/js/data/i18n.js`, `i18n_catalog.js`, `chat_i18n_catalog.js`
- **Supported Locales:** `vi` (Vietnamese), `en` (English), `zh` (Chinese), `ja` (Japanese), `ko` (Korean), `th` (Thai), `de` (German), `ru` (Russian), `es` (Spanish).
- **Zero-Reload Rule:** Language switches instantaneously in-place via event subscription (`FreeExileI18n.subscribe()`). Calling `location.reload()` is strictly forbidden.

---

## 7. ASSET INVENTORY & DIRECTORY MAPPING

| Category | Source Directory (`client/webapp/assets/`) | Quantity | Key Assets & Types | Target Cocos Path (`client/cocos/assets/resources/`) |
| :--- | :--- | :--- | :--- | :--- |
| **Animation Atlases** | `animations/` | 63 files (21 entities) | 2 Bosses (`abyssal_tyrant`, `blood_bone_ravager`), 7 Characters (`sword_master`, `sword_maiden`, `feral_berserker`, `wild_archer`, `glacial_lancer`, `shadow_assassin`, `hero`), 12 Mobs. Each has `_anim_atlas.png`, `_anim_atlas_normal.png`, `_anim_manifest.json`. | `textures/animations/` |
| **Characters** | `characters/` | 26 files | Standee sprites, concept illustrations, hero variants. | `textures/characters/` |
| **Monsters & Bosses** | `monsters/` | 58 files | High-res monster albedo & normal textures, boss concept art. | `textures/monsters/` |
| **Environment Props** | `environment/` | 56 files | 3D-on-2D PBR props: `forge_blacksmith`, `stall_market_outcast`, `house_traditional_tile`, `tree_golden_ancient`, `astral_map_device_altar`. | `textures/environment/` |
| **Map Tiles & Styles** | `map/` & `map/styles/` | 123 map files + 30 style folders | 10 base terrain tiles (`grass`, `stone`, `water`, `swamp`, `dirt`, `lava`, `snow`, `void`, `sand`, `flesh`), wall tiles, and 30 full Biome styles (`STY_01` to `STY_30`). | `textures/map/` |
| **Weapons** | `weapons/` | 45 files | Swords, scythes, bows, staves, shields, daggers with PBR normals. | `textures/weapons/` |
| **Currencies** | `currencies/` | 43 files | Bloodstones, bone relics, crafting orbs with icons & sheets. | `textures/currencies/` |
| **Skills & VFX** | `skills/` & `savage_vfx/` | 21 skill files + VFX presets | 15 class skill manifests, `martial_skills_atlas.png`, particle shaders. | `textures/skills/` |
| **UI Components** | `ui/` | 15 subfolders + 9 root files | HUD orbs, minimap frames, bag grids, tooltips, dialogue boxes, status effect icons. | `textures/ui/` |
| **Banners & Loading**| `banners/`, `loading/` | 13 files | Panoramic deadlands banners, login parallax layers, loading screens. | `textures/banners/` |
| **Portraits** | `portraits/` | 6 files | Class portraits for hero selection & HUD. | `textures/portraits/` |
| **Audio (SFX)** | `js/audio/sfx_engine.js` | Procedural Engine | Procedural Web Audio API sound synthesis (slash, hit, slam, footsteps, magic, UI clicks). | `audio/` (Procedural TS generator or cached wave buffers) |

---

## 8. NETWORKING & PROTOBUF SPECIFICATIONS

### 8.1. Protocol & Ports
- **WebSocket Gateway Bridge:** Runs on `ws://127.0.0.1:8080` (`server/gateway/ws_gateway_bridge.py`).
- **Wire Format:** RFC 6455 WebSocket frames carrying binary Protobuf payloads or JSON telemetry frames.
- **Heartbeat & Telemetry:** Periodic ping/pong packets every 2000ms calculating live RTT.

### 8.2. Core Protobuf Messages
- **Definition Files:** `proto/network.proto`, `proto/combat.proto`, `proto/map_zone.proto`
- **Packets:**
  1. `freeexile.network.PlayerMoveInput`:
     - Fields: `entity_id` (uint32), `dir_x` (float), `dir_y` (float), `input_sequence` (uint32), `biometrics` (TouchBiometrics).
  2. `freeexile.network.WorldStateSync`:
     - Fields: `server_tick` (uint64), `entities` (repeated EntitySnapshot).
  3. `freeexile.combat.CastMartialSkillRequest`:
     - Fields: `caster_entity_id` (uint32), `skill_id` (uint32), `target_x` (float), `target_y` (float), `active_weapon_set` (uint32), `client_timestamp_ms` (uint64).
  4. `freeexile.combat.PhantomEvasionRequest`:
     - Fields: `entity_id` (uint32), `evasion_dir_x` (float), `evasion_dir_y` (float), `client_timestamp_ms` (uint64).
  5. `freeexile.combat.CombatDamageEvent`:
     - Fields: `source_entity_id`, `target_entity_id`, `raw_damage`, `mitigated_damage`, `is_critical`, `target_evaded`, `element`.
  6. `freeexile.map_zone.EnterZoneRequest` & `EnterZoneResponse`:
     - Fields: `player_id`, `portal_id`, `zone_info`, `spawn_x`, `spawn_y`.

---

## 9. TARGET COCOS CREATOR 3.X ARCHITECTURE (`client/cocos/`)

### 9.1. Recommended Project Layout
```
client/cocos/
├── package.json                   # npm packages (protobufjs, long)
├── tsconfig.json                  # Strict TypeScript configuration
├── project.json                   # Cocos Creator 3.x project metadata
└── assets/
    ├── resources/                 # Dynamic assets loaded via resources.load()
    │   ├── data/                  # JSON manifests, catalogs, i18n dictionaries
    │   ├── textures/              # Sprites, atlases, normal maps, UI textures
    │   ├── audio/                 # Audio buffers or synthesized SFX presets
    │   └── prefabs/               # Entity prefabs (Hero, Monster, Boss, Prop, Drop)
    ├── scenes/
    │   ├── MainGame.scene         # Unified 2.5D game world scene
    │   ├── Login.scene            # Onboarding & character creation scene
    │   └── Loading.scene          # Asset preloader & zone transition scene
    └── scripts/
        ├── core/                  # Engine lifecycle, constants, event bus
        │   ├── GameApp.ts         # Singleton bootstrap & service locator
        │   ├── Constants.ts       # Tile dimensions (64x32), speeds, math constants
        │   └── EventBus.ts        # Typed custom events (locale, combat, zone)
        ├── math/
        │   └── IsoMath.ts         # 2:1 isometric coordinate conversion
        ├── kinematics/
        │   ├── PlayerController.ts# WASD/Joystick inputs, zero-residual momentum
        │   ├── CameraFollow.ts    # Exponential lerp, deadzone, bounds clamp
        │   ├── CollisionEngine.ts # Tile passability bitmasks, circle-AABB sliding
        │   └── GridPathfinder.ts  # Zero-heap A* pathfinding & DDA LoS raycast
        ├── animation/
        │   ├── AtlasAnimator.ts   # Manifest frame mapping, pivot [0.5, 0.90]
        │   ├── AnimationFSM.ts    # Idle, Run, Attack, Hurt, Dodge state machine
        │   └── DirectionResolver.ts# 8-direction heading calculation & turn lerp
        ├── combat/
        │   ├── CombatManager.ts   # Skill slots (Q/W/E/Space), combo cycles
        │   ├── CombatFeel.ts      # Hit-stop micro-freeze, screen shake matrix
        │   ├── DamageNumberPool.ts# 64-slot ring buffer damage text pool
        │   ├── TelegraphDecal.ts  # Cones, circles, rings with PoE2 cancel
        │   └── TargetDummy.ts     # Immortality & rolling DPS telemetry
        ├── scenes_mgmt/
        │   ├── SanctuaryWorld.ts  # Sanctuary district layout & safe haven rules
        │   ├── DungeonWorld.ts    # Tile grid loading & encounter tracking
        │   ├── BossGate.ts        # Locked -> Unlocked -> Breached threshold
        │   └── YDepthSorter.ts    # Automatic sorting by (wx + wy)
        ├── ui/
        │   ├── HudOrbs.ts         # Fluid Life & Mana liquid wave dynamics
        │   ├── Minimap.ts         # 120x80 radar with player cone & fog states
        │   ├── InventoryBag.ts    # 40-slot survival bag & tabbed stash
        │   ├── DialogueNpc.ts     # Branching dialogue trees & merchant menus
        │   ├── SkillBarHud.ts     # Cooldown sweeps & charge counters
        │   └── ReactiveI18n.ts    # 9-language reactive localization
        └── network/
            ├── NetworkBridge.ts   # RFC 6455 WebSocket client (port 8080)
            ├── ProtobufHandler.ts # Encoding/decoding Protobuf packets
            └── ClientPrediction.ts# Server-authoritative state reconciliation
```

### 9.2. Component Architecture Highlights
1. **Component-Based Entities (`Node` + TypeScript Component):**
   - Each dynamic entity in the scene (Hero, Mob, Boss, Prop) has a `Node` with `AtlasAnimator`, `Transform`, and `UIOpacity`.
   - `YDepthSorter` runs every frame in `lateUpdate()`, updating `node.setSiblingIndex()` based on `(wx + wy)` order.
2. **Cocos 2D Rendering Pipeline:**
   - Cocos Creator 3.x utilizes a modern 2D SpriteBatch renderer that executes draw calls efficiently.
   - Batching is maximized because all clips within an entity share a single spritesheet atlas (`[entity]_anim_atlas.png`).
3. **Pure TypeScript Implementation:**
   - Zero external browser-specific dependencies (`window`, `document`, DOM HTML elements are replaced by Cocos `UITransform`, `Label`, `Sprite`, `Graphics`, `Button`, `ProgressBar`).
   - Web Audio API procedural synthesis can be encapsulated directly inside a TypeScript helper or exported to standard audio assets.
4. **Protobuf Integration:**
   - Direct integration with `protobufjs` via `client/src/proto/bundle.js` and `bundle.d.ts`.
   - Zero schema drift between Python/C++ server and Cocos client.

---

## 10. CONCLUSION & ACTIONABLE TRANSITION PLAN

The FreeExile WebApp client exhibits an exceptionally modular, well-tested, and mathematically rigorous structure. Every kinematic algorithm, animation state, combat rule, and UI behavior is documented with exact source code references above. 

The implementation team can immediately begin the Cocos Creator 3.x project setup at `client/cocos/` by copying the asset bundles from `client/webapp/assets/` and implementing the modular TypeScript components defined in Section 9.
