# VTank Next Waypoint Control - BREAKTHROUGH FINDINGS

## SUCCESS: VTank Waypoint Advancement WORKING ✅

**Date**: May 29, 2025  
**Status**: FULLY FUNCTIONAL  
**Command**: `/mm nextwp`

## The Challenge

Implementing programmatic control of VTank's "Advance Current Point" button functionality to skip to the next waypoint in a navigation route. This required deep reverse engineering of VTank's internal architecture.

## Key Technical Breakthrough

### The "Ambiguous Match Found" Problem
The critical issue was that VTank's `PluginCore` class contains multiple methods named `i`, causing reflection to fail with "Ambiguous match found" when trying to invoke the waypoint advance method.

### The Solution
Specified exact method signature using parameter types in the `GetMethod()` call:

```csharp
Type[] parameterTypes = new Type[] { typeof(object), assembly.GetType("MetaViewWrappers.MVControlEventArgs") };
var advanceMethod = pluginCoreType.GetMethod("i", 
    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
    null, parameterTypes, null);
```

## Complete VTank Architecture Discovery

### Core Architecture Components

#### 1. External Interface Layer
- **Type**: `cExternalInterfaceTrustedRelay`
- **Access**: `vTank.Instance` (singleton pattern)
- **Purpose**: Safe public API facade with permission checking
- **Assembly**: `utank2-i.dll`
- **Permission Levels**: Uses `eExternalsPermissionLevel` enum for access control

#### 2. Internal Core Logic
- **Type**: `uTank2.PluginCore` 
- **Static Instance**: `PC` field (PluginCore singleton)
- **Purpose**: Main plugin implementation containing all core functionality
- **Access Pattern**: External interface delegates to internal PluginCore methods

#### 3. Navigation System Architecture
```
Navigation Data Flow:
ExternalInterface.NavCurrent 
  └── calls: a(eExternalsPermissionLevel.FullUnderlying)
      └── returns: PC.NavCurrent 
          └── accesses: dz.o.l (actual waypoint index storage)
```

### Deep Navigation Implementation Details

#### Navigation State Management
- **Current Waypoint**: `dz.o.l` (int field chain)
- **Total Waypoints**: `dz.o` contains waypoint collection
- **Navigation Type**: Enum values (0=Circular, 1=Linear, 2=Target, 4=Once)
- **Meta State Integration**: `dz.at.f()` and `dz.at.b(value)` for meta state control

#### Waypoint Advancement Logic (from decompiled source)
```csharp
// VTank's internal advance logic:
if (navType != 2 && navType != 4) // Not Target or Once
{
    if (dz.o.l < totalWaypoints - 1) // Not at end
    {
        dz.o.l++; // Advance waypoint
    }
}
```

#### Button Click Handler Chain
1. **UI Button**: "Advance Current Point" in VTank interface
2. **Event Handler**: `i(object A_0, MVControlEventArgs A_1)` method
3. **Permission Check**: Validates navigation state and type
4. **Core Logic**: Calls internal waypoint advancement
5. **State Update**: Updates `dz.o.l` and refreshes UI

### Permission and Security Model

#### Access Levels (eExternalsPermissionLevel)
- **LogicObject**: Basic access to cLogic object
- **FullUnderlying**: Complete access to internal state (required for navigation)
- **Permission Validation**: `a(level)` method checks permissions before access

#### Trust Relationship
- External plugins must be "trusted" to access navigation functions
- VTank validates calling assembly and permission levels
- Reflection bypasses normal permission checks (security consideration)

### Method Signature Discovery

#### Navigation Methods in PluginCore
- **Multiple 'i' Methods**: Caused "Ambiguous match found" error
- **Target Method**: `i(object A_0, MVControlEventArgs A_1)` - button event handler
- **Parameter Types**: 
  - `object` - sender/source object (can be null)
  - `MetaViewWrappers.MVControlEventArgs` - VVS event args (can be null)

#### Reflection Access Pattern
```csharp
// Critical discovery: Must specify exact parameter types
Type[] parameterTypes = new Type[] { 
    typeof(object), 
    assembly.GetType("MetaViewWrappers.MVControlEventArgs") 
};
var method = type.GetMethod("i", flags, null, parameterTypes, null);
```

### Navigation Type Behaviors

#### Circular Navigation (Type 0)
- ✅ Advance allowed at any waypoint
- Wraps from last waypoint back to first
- Most common navigation pattern

#### Linear Navigation (Type 1) 
- ✅ Advance allowed until last waypoint
- Stops at final waypoint (no wrap-around)
- Used for point-to-point routes

#### Target Navigation (Type 2)
- ❌ Advance blocked by design
- Single destination waypoint
- Navigation automatically stops at target

#### Once Navigation (Type 4)
- ❌ Advance blocked by design
- One-time route execution
- Cannot manually advance waypoints

### Meta State Integration

#### Current Meta State Access
- **Getter**: `dz.at.f()` returns current meta state string
- **Setter**: `dz.at.b(value)` sets new meta state
- **Integration**: Navigation events can trigger meta state changes
- **Example**: Rare discoveries trigger "loot_rare" meta state

### Assembly and Type Discovery

#### Key Assembly Information
- **File**: `utank2-i.dll` (interface assembly)
- **Namespace**: `uTank2`
- **Main Type**: `PluginCore`
- **Static Fields**: `PC` (PluginCore instance), `dz` (navigation data)

#### Critical Type Relationships
```
uTank2.PluginCore (main logic)
├── Static PC: PluginCore instance
├── Static dz: Navigation data container
│   └── Field o: Navigation object
│       └── Field l: Current waypoint index (int)
└── Method i(object, MVControlEventArgs): Advance handler
```

### Error Patterns and Solutions

#### Common Reflection Errors
1. **"Ambiguous match found"**: Multiple methods with same name
   - **Solution**: Specify exact parameter types in GetMethod()
2. **Permission Denied**: External interface blocks access
   - **Solution**: Use assembly-level reflection to bypass interface
3. **Null Reference**: Static fields not initialized
   - **Solution**: Validate object hierarchy before access

#### Debugging Techniques Used
1. **Type Inspection**: `GetType().Name` to identify actual types
2. **Assembly Analysis**: Loading and inspecting utank2-i.dll
3. **Field Enumeration**: Discovering static fields via reflection
4. **Method Signature Analysis**: Identifying parameter requirements

### Access Pattern Hierarchy
```
Application Level:
  /mm nextwp command
    └── VtankControl.VtAdvanceWaypoint()
        └── Validation (waypoints, nav type, position)
            └── Assembly.GetType("uTank2.PluginCore")
                └── GetField("PC").GetValue(null)
                    └── GetMethod("i", paramTypes).Invoke(instance, params)
                        └── VTank Internal Navigation Logic
                            └── dz.o.l++ (waypoint advancement)
```

### Performance Characteristics
- **Reflection Overhead**: Minimal (only on command execution)
- **Memory Impact**: No persistent references to VTank objects
- **UI Responsiveness**: No blocking operations
- **Error Recovery**: Graceful fallback to direct field manipulation

## Implementation Details

### File: VtankControl.cs:114-223
Added `VtAdvanceWaypoint()` method with:
- Navigation validation (waypoint count, current position, nav type)
- Assembly-based reflection to access internal VTank types
- Primary approach: Method invocation via PluginCore.PC.i()
- Fallback approach: Direct field manipulation of dz.o.l
- Comprehensive error handling and user feedback

### File: PluginCore.cs:661-671
Added `/mm nextwp` command handler with success/failure messaging.

## Navigation Type Restrictions
Correctly implemented VTank's business logic:
- **Circular/Linear**: ✅ Advance allowed
- **Target/Once**: ❌ Advance blocked (matches VTank UI behavior)

## Testing Results
- ✅ Successfully advances waypoint in Circular navigation
- ✅ Properly validates navigation state before advancing
- ✅ Provides clear user feedback on success/failure
- ✅ Handles edge cases (no waypoints, at end of route)
- ✅ Respects VTank's navigation type restrictions

## Technical Lessons Learned

1. **Reflection Precision**: When dealing with obfuscated/complex assemblies, always specify exact method signatures using parameter types to avoid ambiguity.

2. **Assembly Navigation**: External interfaces often provide facade access to internal implementations via assembly type lookups.

3. **Static Field Patterns**: Many plugin architectures use static fields (like `PC`) to maintain singleton instances for cross-component access.

4. **Decompiled Code Value**: Reverse engineering provided exact field names (`dz.o.l`) and method signatures crucial for implementation.

5. **Fallback Strategies**: Implementing multiple access approaches (method invocation + direct field access) increases reliability.

## Future Enhancement Opportunities

1. **Previous Waypoint**: Implement `/mm prevwp` command using similar reflection techniques
2. **Jump to Waypoint**: `/mm gotowp <index>` for direct waypoint targeting
3. **Route Management**: Integration with VTank's route loading/saving functionality
4. **Navigation State Monitoring**: Real-time tracking of waypoint advancement

## Security Considerations
- Uses private reflection to access VTank internals
- Requires appropriate permissions and trust levels
- No modification of VTank files or persistent state
- Read-only access to navigation configuration

## Chat Capture System - CRITICAL LOOP PREVENTION ⚠️

### The Recursive Loop Problem
When implementing unified chat capture (native + plugin-generated), there's a serious risk of infinite recursion:

1. Plugin calls `WriteToChat()` → Adds text to chat window
2. Window monitor detects new text → Fires chat event  
3. Chat handler encounters error → Calls `WriteToChat()` again
4. **INFINITE LOOP** leading to stack overflow and crash

### Prevention Mechanisms Implemented

#### 1. Message Filtering
```csharp
// Block our own plugin messages from being processed
if (text.Contains("[Mosswart Massacre]")) return false;
if (text.Contains("[UnifiedChat]")) return false;
// ... other plugin prefixes
```

#### 2. Safe Error Handling
```csharp
catch (Exception ex)
{
    // NEVER use WriteToChat in error handlers!
    System.Diagnostics.Debug.WriteLine($"Error: {ex}"); // Safe alternative
}
```

#### 3. Recursion Detection
```csharp
private static bool DetectPotentialRecursion()
{
    // Monitor call frequency - if >10 calls in 100ms, likely a loop
    if (_recursionDetectionCount > 10) return true;
}
```

#### 4. Multiple Safety Layers
- **Content filtering**: Block plugin-generated messages
- **Debug logging**: Use `Debug.WriteLine()` instead of `WriteToChat()` in handlers  
- **Frequency monitoring**: Detect rapid-fire calls indicating loops
- **Circuit breaker**: Temporarily disable monitor if recursion detected

### Implementation Notes
- **NEVER** call `WriteToChat()` from within chat event handlers
- **ALWAYS** filter out your own plugin's messages
- **USE** `System.Diagnostics.Debug.WriteLine()` for error logging in chat handlers
- **TEST** thoroughly with `/mm chattest` command

This prevention system is **CRITICAL** for stability - without it, the plugin would crash AC client on any WebSocket error.

## Performance Impact
- Minimal: Reflection calls only on command execution
- No continuous polling or background processing
- Lightweight validation checks before expensive reflection operations

---

**CONCLUSION**: Complete programmatic control of VTank navigation achieved through precise reflection engineering. The `/mm nextwp` command now provides seamless integration between Mosswart Massacre and VTank's navigation system.