Desuq Cafe

Back to Inhyeong RPG

MIRAI

Custom Framework

Modular Intelligent Response & Adaptive Interaction | 未来 — "future" in Japanese

An advanced behavior tree AI framework for Unity with FishNet networking.

Unity C# FishNet Network A* Pathfinding

Overview

MIRAI is a complete AI decision-making framework built for networked enemies in a co-op RPG. It uses a builder pattern architecture that separates decision logic, execution, and behavior construction — making complex AI behaviors reusable across different enemy types without rewriting code.

All AI decisions run on the server and sync to clients via FishNet SyncVars. The framework integrates three subsystems — adaptive memory, evolving personality, and dynamic goals — that combine to create enemies that feel alive and responsive rather than scripted.

Architecture

Decision Priority

The behavior tree evaluates top-down. Higher priorities interrupt lower ones via ConditionalAbort.

1 Combat — Attack or chase hostile players
2 Observation — Watch friendly players (memory system)
3 Return to Spawn — Leash mechanics if pulled too far
4 Goals — Pursue active objectives (collection, etc.)
5 Patrol — Follow waypoints if configured
6 Wander — Random exploration
7 Idle — Fallback behavior

Builder Pattern

Enemies don't define their own behavior trees from scratch. Instead, they select and configure builders — modular objects that construct entire behavior subtrees for a specific domain. A single ConfigureBuilders() call wires everything together.

ICombatBehaviorBuilder

Melee, ranged, or custom combat. TargetScanService, personality-driven cooldowns, special attacks via callbacks.

IMovementBehaviorBuilder

Patrol, wander, return-to-spawn, environmental awareness, stuck detection and recovery.

IGoalBehaviorBuilder

Goal validation, collection behaviors, movement to targets, extensible for future goal types.

A fast melee enemy and a slow heavy enemy can both use MeleeCombatBuilder with different parameters. Same builder, different personalities.

Node Library

50+ behavior tree nodes across specialized categories, all extending OptimizedNode with zero-overhead debug instrumentation.

Composite & Decorator Nodes
Composite: Selector, AbortableSelector (re-evaluates on ConditionalAbort signals), Sequence, Parallel, RandomSelector.

Decorator: Conditional, ConditionalAbort (Self/LowerPriority/Both abort modes), Cooldown, Inverter, Repeater, Succeeder, Timeout.
Movement Nodes
A* pathfinding integration: MoveToNode, PatrolNode, WanderNode, ReturnToSpawnNode. Tactical movement: FollowTargetNode, FleeNode, CircleTargetNode, RepositionNode, MoveToPositionNode, CheckDistanceToSpawnNode.
Combat & Support Nodes
Combat: RangedAttackNode, AoEAttackNode, PatternAttackNode, DodgeProjectileNode.

Support: HealingBehaviorNode, BuffAlliesNode, SummonAlliesNode, TauntNode.

State: EnrageNode, PhaseTransitionNode, StatusEffectNode, HealthCheckNode.
Memory, Personality & Goal Nodes
Memory: FirstContactNode, MemoryBasedAttackSelector, MemoryBasedCombatAdjuster, MemoryBasedTacticalSelector, RecordCombatEventNode, ShareMemoriesNode.

Personality: PersonalityInfluencedNode, EmotionalCombatDecisionNode, UpdatePersonalityNode.

Goals: HasActiveGoalNode, GoalExecutionNode, CollectionActionNode.
Service Nodes
Background tasks that run periodically without blocking tree evaluation. TargetScanService: Multi-phase target detection with memory-based threat prioritization, vision cone FOV, and recently-lost tracking. HealthMonitorService: Health state detection with configurable thresholds, damage/healing tracking, and recent damage accumulation.

OptimizedBlackboard

Event-driven data sharing with enum-keyed lookups, subscription system for instant reactions (<0.1s), and thread-safe operations for networked environments.

Server-Authoritative

All AI decisions run on the server. Clients receive state via SyncVars and events — they visualize behavior but never make decisions.

Soul Recollections

Memory System

Enemies remember. The Soul Recollections system tracks combat encounters per-player, records ability effectiveness, and shares intelligence with nearby allies. Memories decay based on importance levels — trivial details fade in minutes, critical events persist indefinitely.

Combat Memory

Damage dealt/received per player, observed abilities, threat level assessment, victory/defeat counts, dodge frequency.

Social Memory

Friendliness level (-1 hostile to +1 friendly), approach/flee behavior tracking, cooperation level.

Ability Memory

Per-ability damage output, range, AoE characteristics, cooldowns, usage frequency, success rate.

Intelligence Sharing

Radius-based sharing with allies. Warns about dangerous players, shares ability intel, coordinates group tactics.

Memory-driven behaviors include adaptive attack range (learning player dodge patterns), threat-based target prioritization, and tactical selection that shifts between aggressive and cautious approaches based on past combat outcomes. Network sync uses selective batching — critical updates sync immediately, minor ones are deferred.

Soul Personality

Personality System

Every enemy has a personality that evolves through gameplay. Seven attributes (0–100) drive eight behavior modifiers that affect everything from attack cooldowns to retreat thresholds to wander radius. Personality shifts happen in response to combat events, damage types, and player behavior.

Attributes

Resonance

Connection to original purpose. High = focused, low = erratic.

Tethering

Connection to location. High = tight leash, low = wanders far.

Clarity

Self-awareness. High = intelligent decisions, low = basic instincts.

Essence Yearning

Drive to seek spiritual essence. Affects collection goal priority.

Harmony

Integration of components. High = smooth actions, low = jerky, disjointed.

Memory Weave

Experience retention. High = remembers encounters longer.

Emotional Echo

Current emotional state: Neutral, Rage, Fear, Curiosity, Sorrow, Joy.

Behavior Modifiers

Each modifier scales from 0.5–2.0× and is derived from combinations of personality attributes.

Aggression Caution Exploration Coordination Learning Speed Range Preference Unpredictability Essence Attraction

Enemy Tiers

Remnants

3–4 attributes, slow evolution

Bound Spirits

5–6 attributes, adds Curiosity

Manifested

All 7 active, fast evolution

Ancients

Max values, personality phases

Ability Intelligence

Learning System

A three-layer memory architecture enables enemies to make intelligent ability decisions. Species knowledge is shared across all enemies of the same type, individual experience tracks per-enemy learning, and player-specific memory adapts to your playstyle.

Tag-Aware Selection

Abilities are understood through SpellTags (AoE, Shield, CC, Healing, etc.). AI scores abilities based on context — AoE gets +60 with 4+ enemies, shields get +40 at low HP.

Situational Learning

Learns "AoE + many enemies = effective" across discrete situation buckets (HP level, enemy count, ally count). Needs 3+ samples before trusting situational data.

Personality Expression

Aggressive enemies love AoE and damage, hate defense. Cautious enemies love shields and escape, hate channeled abilities. Same abilities, different preferences.

Runtime Learning

Enemies can learn new abilities at runtime by collecting CrystallizedEssence items, or programmatically (e.g., boss phases). Equip strategies include replace-weakest, add-to-empty, and manual.

Goal System

The AIGoalManager evaluates goals by priority and feasibility. Goals automatically pause during combat or leash-return and resume when conditions allow. Currently implemented: collection goals with a three-stage approach (far → mid-range → collect). The system is extensible — the base AIGoal class supports exploration, defense, escort, and hunt goal types.

Priority-Based

Goals scored 0–100, evaluated against current conditions. Combat always takes priority.

Lifecycle Management

Activation, execution, completion, and cancellation with reward/consequence callbacks.

Builder Integration

StandardGoalBuilder handles validation, movement, and collection. Extensible for future goal types.

Visual Debugger

A custom Unity Editor tool for real-time inspection of AI decision-making. Built with UIElements, it renders the full node graph in a pannable/zoomable GraphView with nine specialized tabs, a search engine, and a breakpoint system. Zero-overhead design — only the actively debugged tree has instrumentation cost.

Graph View

Live node state visualization with color coding, execution count badges, and smart collision-detection layout for 100+ node trees.

Activity Log

AI decisions translated to plain language. "Story mode" for understanding why the enemy just did what it did.

9 Debug Tabs

Blackboard, Active Path, Activity Log, Changes, Performance, Condition Inspector, Service Monitor, Breakpoints, Ability Knowledge.

Accessible via Tools → Inhyeong → Mirai → Behavior Tree Visual Debugger

Performance

Designed for many simultaneous AI agents in a networked environment.

AI Level of Detail

Close (<20u): full complexity, every-frame eval. Mid (20–50u): simplified, 0.2–0.5s intervals. Far (>50u): minimal behavior, 1s+ intervals, systems paused.

Network Optimization

Batched non-critical updates, delta compression for memory sync, throttled SyncVar frequency, server-only service execution.

Private Repository Inhyeong RPG Devlog