Fantasy Framework

repository·main·Indexed 23 days ago

https://github.com/qq362946/fantasy

A high-performance, zero-reflection C# cross-platform distributed server framework optimized for large-scale MMOs. It supports multiple network protocols (TCP, KCP, WebSocket, HTTP) and integrates with Unity. The ecosystem includes the Fantasy CLI for project scaffolding, Fantasy.Unity for client development, and the Fantasy Control Center for managing topology and service discovery.

Tokens
207.2K
Snippets
358
Records
802
Agent score
79%

What's inside Fantasy

  1. Overview of the Timer System

    main

    The TimerComponent is a high-performance task scheduling component in the Fantasy Framework. It is designed for game logic scenarios such as delayed execution, periodic tasks, and asynchronous waiting.

    Key features include:

    • Asynchronous waiting (WaitAsync, WaitTillAsync)
    • One-time timers (OnceTimer, OnceTillTimer)
    • Repeated timers (RepeatedTimer)
    • Frame-based timers (FrameTimer)
    • Support for cancellation tokens (FCancellationToken)
    • Integration with the event system

    Recommended Usage: While you can access the TimerComponent directly, it is highly recommended to use the simplified FTask static methods for cleaner code.

  2. Overview of Fantasy Protocol Export Tools

    main

    Fantasy provides two tools to automatically generate C# code from .proto protocol definition files:

    1. Fantasy.ProtocolExportTool (CLI): A command-line tool designed for CI/CD integration and automated scripts. It supports both interactive and silent modes.
    2. Fantasy.ProtocolEditor (Visual Editor): A cross-platform desktop application built with Avalonia. It includes a .proto editor with syntax highlighting, code completion, and visual configuration editing for RoamingType.Config and RouteType.Config.

    Core Capabilities:

    • Parses .proto files to generate message classes, OpCode enums, and Helper extension methods.
    • Supports multiple serialization formats: ProtoBuf, MemoryPack, and Bson.
    • Performs format validation (detecting duplicate fields, incorrect interface types, etc.).
    • Ensures protocol ID stability via OpCode.Cache (incremental updates).
    • Supports sub-package protocol exports with independent directories.
    • Enables shared OpCode caching across main protocols and sub-packages to prevent ID conflicts.
  3. What is Fantasy?

    main
    Fantasy is a high-performance, zero-reflection C# game server framework designed for large-scale multiplayer online games. It features a distributed architecture, ECS (Entity Component System) design, and supports multiple protocols including TCP, KCP, WebSocket, and HTTP. It is optimized for Native AOT (Ahead-of-Time) compilation to ensure maximum performance and compatibility with modern deployment environments.
  4. Overview of UniRecast

    main

    UniRecast is a navigation library designed specifically for Unity3D environments. It is built upon DotRecast and leverages Recast Detour to provide advanced pathfinding capabilities.

    Key characteristics include:

    • Unity Integration: Tailored for the Unity framework.
    • Server Compatibility: Its foundation on DotRecast allows for easy integration with servers, ensuring efficient performance and seamless server-side interactions for pathfinding.
  5. Summary of Session usage in Fantasy

    main

    Session is the core of the Fantasy Framework network communication. To build network applications, you must understand how to acquire, use, and manage sessions:

    • Acquisition (Client): Obtain a Session via Scene.Connect().
    • Acquisition (Server): Session parameters are automatically provided within your Handlers.
    • Communication Types:
      • One-way messages: Use Send() for high-performance communication where no response is required.
      • RPC requests: Use Call() when you need to send a request and wait for a response.
    • Lifecycle Management: Always check the IsDisposed property to ensure the session is still valid, and call Dispose() when the session is no longer needed to free resources.
  6. Use TimerComponent for scheduling tasks in Fantasy

    main

    The TimerComponent is a core scheduling component within a Scene. It is used for delayed execution, periodic tasks, asynchronous waiting, and countdowns.

    Recommendation: Use FTask methods to simplify your implementation. Only access scene.TimerComponent.Net directly when you require low-level interfaces or specific overloads.

    Key Rules for Usage:

    • Server-side usage: On the server, prioritize using FTask.Wait, FTask.OnceTimer, or FTask.RepeatedTimer.
    • Lifecycle Management: Timers belong to a Scene. When a Scene is destroyed, all associated timers are automatically cleaned up.
    • Manual Cancellation: For repeated timers, you must manually cancel them. Ensure you save the returned timerId to perform the cancellation later.
    • Hot Reloading: For business logic that requires hot-reload friendliness, prefer using a pattern where a "Timer triggers an Event" rather than using an Action callback.
    • Precision: Timer precision is dependent on the Update() frequency and is not absolute real-time.
  7. What is SphereEvent (Cross-Server Domain Event System)?

    main

    SphereEvent is a distributed publish-subscribe mechanism designed for decoupled communication between different servers. It allows Server A to subscribe to events published by Server B, enabling cross-server business notifications (e.g., cross-server chat, guild reports, leaderboard updates) and distributed state synchronization without hard-coded RPC calls.

    FeatureEvent (Local)SphereEvent (Cross-Server)
    ScopeSingle SceneCross-Scene, Cross-Server
    CommunicationIn-process method callNetwork communication (serialized)
    SubscriptionCompile-time auto-registrationRuntime dynamic subscription
    Use CaseLocal module decouplingDistributed server collaboration
  8. What is the OnCreateScene event?

    main

    The OnCreateScene event is a built-in lifecycle event in the Fantasy framework that triggers automatically after a Scene has finished its startup process. It is the primary mechanism for executing custom initialization logic, attaching components to scenes, or loading configuration data when a scene is created.

    Execution Lifecycle

    1. Scene.Create() is called.
    2. The Scene instance is created.
    3. Core components (e.g., EventComponent, TimerComponent) are initialized.
    4. Network listening is configured (if applicable).
    5. Schedulers (MainThread/MultiThread/ThreadPool) are configured.
    6. OnCreateScene event is published via EventComponent.PublishAsync(OnCreateScene).
    7. The scene is considered fully started.
  9. What is the EventAwaiter system?

    main

    The EventAwaiterComponent is a high-performance, type-safe asynchronous waiting component. It allows coroutines to await specific types of events and provides a mechanism for other parts of the code to Notify those events.

    Unlike the standard Event system (which is a one-to-many Publish-Subscribe model where listeners execute immediately), EventAwaiter is a one-to-many Wait-Notify model where the waiter actively waits for a result.

    Key differences:

    • EventAwaiter: Uses await Wait<T>() + Notify<T>(). Supports returning data via EventAwaiterResult<T>. Best for scenarios where you need to wait for a specific condition or response (e.g., waiting for a player to click a dialog button).
    • Event: Uses Publish() + Listeners. No return value. Best for decoupled, event-driven architectures (e.g., notifying the system that a player leveled up).
    // EventAwaiter: Waiting for a player to confirm a dialog (attached to the player entity)
    var player = scene.GetEntity<Player>(playerId);
    var result = await player.EventAwaiterComponent.Wait<PlayerConfirmEvent>();
    if (result.ResultType == EventAwaiterResultType.Success)
    {
        ProcessConfirm(result.Value);
    }
    
    // Event: Publishing a level up event to all listeners (at Scene level)
    scene.EventComponent.Publish(new PlayerLevelUpEvent { PlayerId = id });
  10. What is SeparateTable and when to use it

    main

    SeparateTable is an advanced database persistence solution in the Fantasy Framework that allows you to store sub-components of a complex aggregate entity in independent database tables (collections) instead of nesting them within the parent entity's table.

    Why use SeparateTable:

    • Reduce Main Table Size: Prevents the main entity table from becoming bloated with large nested data (e.g., inventories, friend lists, or mail data), which speeds up basic queries.
    • Improve Query Performance: Allows you to query basic entity information (like Name or Level) without the overhead of loading massive sub-components.
    • Independent Index Management: You can create specific indexes for sub-tables (e.g., indexing an ItemId within a PlayerInventoryEntity table) without affecting the main table.
    • Flexible Data Management: Enables independent backups, data cleanup, or different storage strategies for specific sub-components.
  11. What is FantasyRuntime and how to choose a mode

    main

    Overview

    FantasyRuntime is an all-in-one network connection and framework initialization component for the Fantasy Unity client. It simplifies client-side code by automating Entry.Initialize() and Scene.Create() calls and providing visual configuration.

    Usage Modes

    ModeDescriptionBest For
    MonoBehaviour Component ModeAttach the FantasyRuntime component to a GameObject and configure parameters via the Unity Inspector.Visual configuration, rapid prototyping, or managing multiple independent connections.
    Runtime Static Class ModeUse the Runtime static class to globally access Scene, Session, and heartbeat components via code.Global singleton connections, code-driven scenarios, and quick access to network objects.

    Core Features

    • Automatic Initialization: Handles framework and scene setup.
    • Visual Configuration: Network parameters can be set in the Inspector.
    • Multi-Protocol Support: Supports TCP, KCP, and WebSocket.
    • Heartbeat Management: Automatic heartbeat enabling and real-time latency monitoring.
    • Event Callbacks: UnityEvent support for connection success, failure, and disconnection.
    • Multi-Instance Support: Ability to create multiple instances for different servers.
    • Global Access: Fast access to Scene and Session via the Runtime class.