Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 325 additions & 0 deletions .openspec/proposals/create-visual-rpc-builder/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,325 @@
# Visual RPC Builder for MLCreator

**Proposal ID:** `create-visual-rpc-builder`
**Status:** PROPOSED
**Priority:** HIGH
**Impact:** Developer Experience, Visual Scripting, Accessibility

---

## Executive Summary

Enable visual scripters to create and execute custom Remote Procedure Calls (RPCs) without writing C# code. Currently, RPCs require C# boilerplate with specific naming conventions (`ClientRpc`/`ServerRpc` suffixes), which creates a barrier for non-programmers using GameCreator's visual scripting system.

**Solution:** A visual RPC builder system that generates type-safe RPC methods at runtime and provides GameCreator Instructions for defining, registering, and executing custom RPCs through visual scripting nodes.

**Key Benefits:**
- **Zero C# Required** - Define RPCs entirely through visual scripting
- **Type-Safe** - Automatic parameter validation and serialization
- **WebGL Optimized** - Bandwidth-efficient with batching and compression
- **GameCreator Native** - Seamless integration with visual scripting workflow
- **Multiplayer Accessible** - Democratizes multiplayer game development

---

## Problem Statement

**Current Barriers:**
1. RPCs require C# classes with `NetworkBehaviour` inheritance
2. Method names must end with `ClientRpc` or `ServerRpc` (enforced by code generator)
3. Parameters must be serializable (requires `INetworkSerializable` for custom types)
4. No visual way to define custom network messages
5. Visual scripters limited to pre-built RPC instructions

**Impact:**
- Non-programmers cannot create custom multiplayer interactions
- Simple multiplayer features require C# developer intervention
- Slower iteration for game designers
- Limits GameCreator's visual-first philosophy in multiplayer context

---

## Proposed Solution

A three-component system:

1. **RPC Definition System** - Visual nodes to define RPC signatures
2. **RPC Registry** - Runtime registration and type-safe execution
3. **Visual Scripting Instructions** - GameCreator nodes for RPC operations

**User Workflow:**
```
1. Create RPC Definition (visual node)
→ Name: "TeleportPlayer"
→ Direction: ServerRpc
→ Parameters: Vector3 position, float delay

2. Register RPC (automatic on scene load)
→ Validates signature
→ Generates NetworkBehaviour wrapper
→ Registers with NetworkManager

3. Execute RPC (visual instruction)
→ "Network: Execute RPC" node
→ Select "TeleportPlayer" from dropdown
→ Set parameters via visual scripting
→ Choose target (Self/AllPlayers/Server/etc.)
```

---

## WebGL Considerations

- **Bandwidth Impact:** Minimal - RPCs use Netcode's built-in compression
- **Build Size Impact:** <50KB for RPC builder system
- **Memory Footprint:** ~2MB for RPC registry (100 RPCs × 20KB each)
- **Performance:** 60 FPS maintained - RPC execution is async, non-blocking

**Optimizations:**
- Batch multiple RPC calls into single network message
- Delta compression for repeated parameter values
- Automatic throttling for high-frequency RPCs
- WebSocket transport optimization for WebGL builds

---

## GameCreator Integration

### Visual Scripting Components

**Instructions:**
- `InstructionDefineRPC` - Define RPC signature
- `InstructionRegisterRPC` - Register RPC with network system
- `InstructionExecuteRPC` - Execute RPC with parameters
- `InstructionExecuteRPCBatch` - Execute multiple RPCs in batch

**Conditions:**
- `ConditionRPCRegistered` - Check if RPC is registered
- `ConditionRPCExecutionSuccess` - Check last RPC execution status
- `ConditionCanExecuteRPC` - Validate RPC execution permissions

**Events:**
- `EventOnRPCReceived` - Trigger when specific RPC received
- `EventOnRPCExecuted` - Trigger after RPC execution
- `EventOnRPCFailed` - Trigger on RPC execution failure

### Example Workflow

**Scenario:** Create "Give Item to Player" RPC

```
Visual Script Flow:
1. On Scene Start
└─ Network: Define RPC
├─ Name: "GiveItemToPlayer"
├─ Direction: ServerRpc
├─ Parameters:
│ ├─ string itemId
│ ├─ int quantity
│ └─ ulong targetPlayerId
└─ Auto Register: true

2. On Button Click (Give Item)
└─ Network: Execute RPC
├─ RPC Name: "GiveItemToPlayer"
├─ Target: Server
├─ Parameters:
│ ├─ itemId: "sword_legendary"
│ ├─ quantity: 1
│ └─ targetPlayerId: [Selected Player ID]
└─ Wait For Response: true

3. On RPC Received: "GiveItemToPlayer"
└─ If Is Server
└─ Inventory: Add Item
├─ Target: [Get Player By ID]
├─ Item: [Get Item By ID]
└─ Quantity: [RPC Parameter: quantity]
```

---

## Netcode Architecture

### Network Synchronization

**RPC Definition Storage:**
- `NetworkVariable<NetworkList<RPCDefinition>>` - Synced RPC registry
- Server authoritative - only server can register RPCs
- Clients receive registry on connection

**RPC Execution Flow:**
```
Client → Execute RPC → Validate locally → Send to server
Server → Receive RPC → Validate → Execute handler → Broadcast (if ClientRpc)
Clients → Receive broadcast → Execute local handlers
```

### RPCs

**Generated RPC Methods:**
- `ExecuteCustomRPCServerRpc(string rpcName, byte[] parameters)` - Server execution
- `ExecuteCustomRPCClientRpc(string rpcName, byte[] parameters, ClientRpcParams clientParams)` - Client execution
- `BroadcastRPCClientRpc(string rpcName, byte[] parameters)` - Broadcast to all clients

**RPC Naming:** All generated methods follow Netcode conventions with proper suffixes.

### NetworkVariables

**RPC Registry:**
```csharp
private NetworkVariable<int> m_RegisteredRPCCount = new NetworkVariable<int>(
0,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Server
);

public int RegisteredRPCCount => m_RegisteredRPCCount.Value;
```

**RPC Execution Stats:**
```csharp
private NetworkVariable<RPCStats> m_RPCStats = new NetworkVariable<RPCStats>(
new RPCStats(),
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Server
);
```

### Authority

- **Server Authority:** All RPC registrations and validations
- **Client Execution:** Clients can execute ServerRpc (request to server)
- **Server Broadcast:** Server can broadcast ClientRpc to all/specific clients
- **Validation:** Server validates all RPC calls before execution

---

## Implementation Tasks

1. **Create RPC Definition System** (8 hours)
- Define `RPCDefinition` struct with `INetworkSerializable`
- Create `RPCParameter` class for type-safe parameters
- Implement RPC signature validation

2. **Build RPC Registry** (10 hours)
- Create `NetworkRPCRegistry` NetworkBehaviour
- Implement RPC registration and lookup
- Add type-safe parameter serialization/deserialization
- Implement RPC execution routing

3. **Create Visual Scripting Instructions** (12 hours)
- `InstructionDefineRPC` with parameter builder UI
- `InstructionExecuteRPC` with parameter mapping
- `InstructionRegisterRPC` with validation
- `InstructionExecuteRPCBatch` for batching

4. **Create Visual Scripting Conditions** (4 hours)
- `ConditionRPCRegistered`
- `ConditionRPCExecutionSuccess`
- `ConditionCanExecuteRPC`

5. **Create Visual Scripting Events** (4 hours)
- `EventOnRPCReceived` with parameter extraction
- `EventOnRPCExecuted`
- `EventOnRPCFailed` with error details

6. **Add WebGL Optimizations** (6 hours)
- RPC batching system
- Delta compression for parameters
- Throttling for high-frequency RPCs
- WebSocket transport optimization

7. **Create Editor Tools** (8 hours)
- RPC definition inspector
- RPC registry viewer
- RPC execution debugger
- Performance profiler

8. **Write Documentation** (6 hours)
- User guide for visual scripters
- API reference for C# developers
- Example scenes and tutorials
- Troubleshooting guide

9. **Testing** (8 hours)
- Unit tests for RPC registry
- Integration tests for RPC execution
- WebGL build testing
- Performance benchmarks

10. **Polish and Optimization** (4 hours)
- Code review and refactoring
- Performance optimization
- Error message improvements
- UI/UX refinements

---

## Testing Strategy

### Unit Tests
- RPC definition validation
- Parameter serialization/deserialization
- RPC registry lookup and registration
- Type safety enforcement

### Integration Tests
- RPC execution across network (host/client)
- Batched RPC execution
- RPC targeting (Self/AllPlayers/Server/etc.)
- Error handling and validation

### WebGL Validation
- Browser testing (Chrome, Firefox, Safari)
- Bandwidth measurement (target: <10KB/s per player)
- Build size verification (target: <50KB overhead)
- Performance profiling (maintain 60 FPS)

### Manual Testing
- Visual scripting workflow (non-programmer perspective)
- Complex RPC scenarios (nested parameters, batching)
- Error recovery (network failures, invalid parameters)
- Multi-player scenarios (2-8 players)

---

## Documentation

### User Guide (Visual Scripters)
- "Creating Your First RPC" tutorial
- RPC parameter types reference
- Common RPC patterns (teleport, give item, trigger effect)
- Troubleshooting common issues

### API Reference (C# Developers)
- `NetworkRPCRegistry` class documentation
- `RPCDefinition` struct reference
- Custom parameter type serialization
- Advanced RPC patterns

### Example Scenes
- **BasicRPC** - Simple ServerRpc and ClientRpc examples
- **ItemSharing** - Give items between players
- **TeleportSystem** - Teleport players across map
- **AbilitySystem** - Networked abilities with cooldowns
- **BatchedRPCs** - High-frequency RPC optimization

---

## Success Metrics

- ✅ Visual scripters can create custom RPCs in <5 minutes
- ✅ Zero C# code required for 90% of multiplayer interactions
- ✅ RPC execution latency <50ms (same as native Netcode RPCs)
- ✅ Bandwidth overhead <5% compared to hand-written RPCs
- ✅ WebGL builds maintain 60 FPS with 100+ RPCs/second
- ✅ 100% test coverage for RPC registry and execution
- ✅ Documentation rated 4.5/5 by visual scripters

---

**Estimated Effort:** 70 hours
**Priority:** HIGH
**Dependencies:** None (uses existing Netcode infrastructure)
**Risk Level:** LOW (builds on proven Netcode patterns)
Loading