Technical Requirements - treytomes/redstone_sim GitHub Wiki

Technical Requirements Document: 2D Redstone Circuit Simulator

1. Technology Stack

1.1 Core Technologies

  • Programming Language: C# 10.0+
  • Framework: .NET 9.0
  • Graphics & I/O: OpenTK 4.x
  • Testing Framework: xUnit 2.x
  • Build System: .NET CLI / MSBuild

1.2 Additional Libraries

  • Dependency Injection: Microsoft.Extensions.DependencyInjection
  • Serialization: System.Text.Json
  • Logging: Microsoft.Extensions.Logging
  • Configuration: Microsoft.Extensions.Configuration

2. Architecture Overview

2.1 Core Architecture

  • Pattern: Model-View-ViewModel (MVVM) with Command pattern
  • Structure: Modular, component-based design with clear separation of concerns
  • Threading Model: Main thread for rendering, separate thread for simulation

2.2 Component Breakdown

  • Simulation Core: Handles the logic and state of the redstone circuit
  • Rendering Engine: Manages visualization using OpenTK
  • Input Handler: Processes user input from keyboard/mouse
  • UI Layer: Manages user interface elements and interactions
  • Persistence Layer: Handles saving/loading circuits

3. Module Specifications

3.1 Simulation Core

3.1.1 Grid System

  • Class: GridSystem
  • Responsibilities:
    • Maintain the 2D grid structure
    • Track component placement
    • Handle coordinate transformations
    • Support grid resizing operations
  • Key Methods:
    • PlaceComponent(Component component, Vector2i position)
    • RemoveComponent(Vector2i position)
    • GetComponentAt(Vector2i position)
    • ResizeGrid(int width, int height)

3.1.2 Component System

  • Base Class: RedstoneComponent (abstract)
  • Derived Classes:
    • RedstoneWire
    • RedstoneButton
    • RedstoneSwitch
    • RedstoneTorch
    • RedstoneRepeater
    • RedstoneTransistor
  • Interface: IPowerable
    • int PowerLevel { get; set; }
    • void UpdatePowerState()
    • bool CanReceivePowerFrom(Direction direction)
    • bool CanProvidePowerTo(Direction direction)

3.1.3 Signal Propagation System

  • Class: SignalPropagator
  • Responsibilities:
    • Calculate signal paths
    • Manage signal strength decay
    • Handle update order
    • Process component interactions
  • Key Methods:
    • PropagateSignals()
    • CalculateUpdateOrder()
    • UpdateComponentState(RedstoneComponent component)

3.1.4 Simulation Controller

  • Class: SimulationController
  • Responsibilities:
    • Manage simulation tick rate
    • Control simulation state (running, paused, step)
    • Handle timing and synchronization
  • Key Methods:
    • Start()
    • Pause()
    • Step()
    • SetSpeed(float ticksPerSecond)

3.2 Rendering Engine

3.2.1 Renderer

  • Class: RedstoneRenderer
  • Responsibilities:
    • Render grid and components
    • Handle camera transformations
    • Manage visual effects
  • Key Methods:
    • Initialize()
    • Render(float deltaTime)
    • UpdateViewport(int width, int height)

3.2.2 Asset Management

  • Class: AssetManager
  • Responsibilities:
    • Load and manage textures
    • Handle component visual states
    • Provide sprite batching
  • Key Methods:
    • LoadTextures()
    • GetComponentTexture(ComponentType type, PowerState state)
    • UnloadAssets()

3.2.3 Camera Controller

  • Class: CameraController
  • Responsibilities:
    • Handle pan and zoom operations
    • Convert between screen and world coordinates
    • Manage view boundaries
  • Key Methods:
    • Pan(Vector2 delta)
    • Zoom(float factor, Vector2 focusPoint)
    • ScreenToWorld(Vector2 screenPos)
    • WorldToScreen(Vector2 worldPos)

3.3 Input Handler

3.3.1 Input Manager

  • Class: InputManager
  • Responsibilities:
    • Process keyboard and mouse input
    • Map inputs to actions
    • Handle input modes (build, select, etc.)
  • Key Methods:
    • ProcessInput()
    • RegisterAction(InputType input, Action action)
    • SetInputMode(InputMode mode)

3.3.2 Tool System

  • Class: ToolManager
  • Responsibilities:
    • Manage available tools (place, select, delete)
    • Handle tool-specific input processing
    • Coordinate tool state changes
  • Key Methods:
    • SelectTool(ToolType tool)
    • ProcessToolInput(InputEvent input)
    • CompleteToolAction()

3.4 UI Layer

3.4.1 UI Manager

  • Class: UIManager
  • Responsibilities:
    • Manage UI elements
    • Handle UI events
    • Coordinate UI updates
  • Key Methods:
    • Initialize()
    • ProcessUIEvents()
    • UpdateUI()

3.4.2 Component Palette

  • Class: ComponentPalette
  • Responsibilities:
    • Display available components
    • Handle component selection
    • Provide component information
  • Key Methods:
    • SelectComponent(ComponentType type)
    • GetSelectedComponent()
    • UpdatePaletteVisibility(bool visible)

3.4.3 Analysis Tools UI

  • Class: AnalysisToolsPanel
  • Responsibilities:
    • Display signal tracing
    • Show timing diagrams
    • Present power statistics
  • Key Methods:
    • ShowSignalTrace(List<Vector2i> path)
    • UpdateTimingDiagram(Dictionary<Vector2i, List<PowerState>> states)
    • DisplayPowerStatistics(PowerStatistics stats)

3.5 Persistence Layer

3.5.1 Save/Load System

  • Class: CircuitPersistence
  • Responsibilities:
    • Serialize/deserialize circuit state
    • Manage file operations
    • Handle version compatibility
  • Key Methods:
    • SaveCircuit(string filename)
    • LoadCircuit(string filename)
    • ExportAsImage(string filename)

3.5.2 Circuit Data Model

  • Class: CircuitData
  • Responsibilities:
    • Define serializable circuit structure
    • Track component metadata
    • Store grid configuration
  • Properties:
    • Dictionary<Vector2i, ComponentData> Components
    • GridProperties GridConfig
    • SimulationProperties SimConfig

4. Performance Requirements

4.1 Rendering Performance

  • Target Frame Rate: 60+ FPS on standard hardware
  • Optimization Techniques:
    • Sprite batching
    • Frustum culling
    • Level-of-detail rendering
    • Hardware acceleration

4.2 Simulation Performance

  • Target Update Rate: 20+ ticks per second with 1000+ components
  • Optimization Techniques:
    • Spatial partitioning
    • Dirty region tracking
    • Lazy evaluation of inactive circuits
    • Parallelized signal calculation where possible

4.3 Memory Management

  • Maximum Memory Usage: <1GB for standard circuits
  • Techniques:
    • Object pooling for frequently created/destroyed components
    • Texture atlasing
    • Efficient grid representation

5. Testing Strategy

5.1 Unit Testing

  • Framework: xUnit 2.x
  • Coverage Target: 80%+ for core simulation logic
  • Key Test Areas:
    • Component behavior
    • Signal propagation
    • Grid operations
    • Serialization/deserialization

5.2 Integration Testing

  • Approach: Component interaction tests
  • Key Test Areas:
    • Multi-component circuits
    • Signal timing across components
    • Save/load integrity

5.3 Performance Testing

  • Tools: Custom benchmarking harness
  • Metrics:
    • FPS under various load conditions
    • Simulation ticks per second
    • Memory consumption
    • Load/save times

5.4 UI Testing

  • Approach: Automated UI tests + manual verification
  • Key Test Areas:
    • Component placement
    • Tool functionality
    • Camera controls

6. Implementation Phases

6.1 Phase 1: Core Simulation

  • Develop basic component classes
  • Create signal propagation system
  • Build simulation tick controller
  • Implement unit tests for core simulation logic

6.2 Phase 2: Rendering and Input

  • Set up OpenTK rendering pipeline
  • Implement camera system
  • Create component visualization
  • Develop input handling system
  • Build basic tool functionality
  • Add grid navigation controls

6.3 Phase 3: Component Implementation

  • Implement all basic components (wire, torch, button, etc.)
  • Add transistor component with configurable logic
  • Create component interaction rules
  • Implement power level visualization
  • Add component-specific unit tests

6.4 Phase 4: UI and Tools

  • Build component palette interface
  • Implement selection and editing tools
  • Create circuit analysis views
  • Add simulation control panel
  • Develop debug visualization options

6.5 Phase 5: Persistence and Export

  • Implement circuit serialization
  • Create save/load functionality
  • Add circuit export capabilities
  • Implement circuit sharing features
  • Build file format validation

6.6 Phase 6: Optimization and Polish

  • Performance optimization
  • Bug fixing
  • UI refinement
  • Documentation
  • Final testing

7. Technical Implementation Details

7.1 OpenTK Integration

7.1.1 Graphics Pipeline

  • Rendering Approach: 2D sprite-based rendering using OpenTK's GL API
  • Shader Implementation:
    • Basic vertex/fragment shaders for grid and components
    • Special effects shaders for signal visualization
  • Window Management:
    • GameWindow subclass for main application window
    • Event-driven rendering loop
    • Vsync support

7.1.2 Input Handling

  • Mouse Input:
    • Use OpenTK's MouseMove, MouseDown, MouseUp events
    • Implement click, drag, and scroll handling
  • Keyboard Input:
    • Use OpenTK's keyboard events for shortcuts and controls
    • Support for customizable key bindings

7.2 Data Structures

7.2.1 Grid Representation

  • Storage: Sparse dictionary-based grid (Dictionary<Vector2i, RedstoneComponent>)
  • Spatial Partitioning: Quad-tree for efficient spatial queries
  • Chunk System: Optional chunking system for large circuits

7.2.2 Component Hierarchy

RedstoneComponent (abstract)
├── WireComponent
├── SourceComponent (abstract)
│   ├── ButtonComponent
│   ├── SwitchComponent
│   └── TorchComponent
├── LogicComponent (abstract)
│   ├── RepeaterComponent
│   └── TransistorComponent
└── SpecialComponent (abstract)
    └── ... (future components)

7.2.3 Signal Propagation Model

  • Update Queue: Priority queue for component updates
  • Dependency Graph: Directed graph for tracking signal dependencies
  • Propagation Algorithm:
    1. Identify changed power sources
    2. Build update graph
    3. Topologically sort components
    4. Process updates in order

7.3 Serialization

7.3.1 Circuit File Format

  • Format: Custom JSON-based format
  • Structure:
    {
      "version": "1.0",
      "metadata": {
        "name": "Example Circuit",
        "author": "User",
        "created": "2023-11-01T12:00:00Z"
      },
      "grid": {
        "width": 100,
        "height": 100
      },
      "components": [
        {
          "type": "wire",
          "position": { "x": 10, "y": 15 },
          "properties": { }
        },
        {
          "type": "repeater",
          "position": { "x": 11, "y": 15 },
          "rotation": 1,
          "properties": {
            "delay": 2,
            "locked": false
          }
        }
      ],
      "powerStates": {
        "10,15": 0,
        "11,15": 0
      }
    }

7.3.2 Export Formats

  • Image Export: PNG with optional transparent background
  • Circuit Sharing: Compressed binary format for efficient sharing

7.4 Threading Model

7.4.1 Main Thread Responsibilities

  • UI rendering and updates
  • Input processing
  • OpenGL context operations

7.4.2 Simulation Thread

  • Run simulation ticks at configured rate
  • Process component updates
  • Calculate signal propagation

7.4.3 Synchronization

  • Thread-safe queue for cross-thread communication
  • Double-buffered state for rendering
  • Lock-free data structures where possible

7.5 Error Handling and Logging

7.5.1 Exception Handling

  • Custom exception types for simulation-specific errors
  • Global exception handler for UI thread
  • Graceful degradation for non-critical failures

7.5.2 Logging System

  • Structured logging using Microsoft.Extensions.Logging
  • Log levels: Debug, Info, Warning, Error, Critical
  • Log targets: Console, file, and in-application log viewer

8. Technical Dependencies

8.1 Required NuGet Packages

  • OpenTK (4.x): Graphics and input handling
  • Microsoft.Extensions.DependencyInjection: DI container
  • Microsoft.Extensions.Logging: Logging infrastructure
  • Microsoft.Extensions.Configuration: Configuration management
  • System.Text.Json: JSON serialization
  • xUnit (2.x): Testing framework
  • Moq: Mocking library for testing
  • BenchmarkDotNet: Performance testing

8.2 Development Tools

  • Visual Studio 2022 or later / Visual Studio Code with C# extensions
  • .NET 9.0 SDK
  • Git for version control
  • GitHub Actions for CI/CD

9. Technical Constraints and Considerations

9.1 Platform Support

  • Primary: Windows 10/11 (x64)
  • Secondary: macOS, Linux (via .NET cross-platform capabilities)
  • Minimum Specifications:
    • CPU: Dual-core 2.0 GHz or better
    • RAM: 4 GB minimum, 8 GB recommended
    • GPU: OpenGL 3.3+ compatible
    • Storage: 100 MB for application, variable for circuit files

9.2 Performance Optimization Priorities

  1. Simulation tick rate consistency
  2. Rendering performance for large circuits
  3. Memory usage for component-dense areas
  4. Load/save times for large circuits

9.3 Extensibility Considerations

  • Plugin architecture for future component types
  • Event system for custom behaviors
  • Scripting API for automation (future consideration)

10. Development Standards

10.1 Code Standards

  • Follow Microsoft's C# coding conventions
  • Use nullable reference types
  • Implement proper XML documentation
  • Follow SOLID principles

10.2 Source Control Practices

  • Feature branching workflow
  • Pull request reviews required
  • Semantic versioning
  • Automated CI/CD pipeline

10.3 Testing Requirements

  • Unit tests required for all core simulation logic
  • Integration tests for component interactions
  • Performance tests for critical paths
  • UI tests for main workflows

10.4 Documentation

  • API documentation generated from XML comments
  • Architecture overview document
  • User manual and tutorials
  • Developer guidelines for contributions

This technical requirements document provides a comprehensive blueprint for implementing the 2D Redstone Circuit Simulator using C#, .NET 9.0, OpenTK, and xUnit. The modular architecture and clear separation of concerns will facilitate development across the implementation phases while ensuring the system meets all functional and performance requirements.

⚠️ **GitHub.com Fallback** ⚠️