Skip to content

Latest commit

 

History

History
499 lines (422 loc) · 13.9 KB

CIRCUIT_LAB_IMPLEMENTATION.md

File metadata and controls

499 lines (422 loc) · 13.9 KB

Circuit Lab Implementation Guide

Architecture Overview

This implementation follows a modular, scalable architecture designed for educational electronics visualization.

Core Layers

┌─────────────────────────────────────────┐
│  UI Layer (React Components)            │
│  - CircuitLab, ControlPanel, Graphs    │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│  3D Rendering Layer (R3F/Three.js)     │
│  - Component3D, Wire3D, Shaders        │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│  Simulation Layer                       │
│  - CircuitSimulator, CircuitAnalyzer   │
└──────────────────┬──────────────────────┘
                   │
┌──────────────────▼──────────────────────┐
│  Data Layer (Types & State)             │
│  - Circuit, Component, Zustand Store   │
└─────────────────────────────────────────┘

File Structure Detail

/lib/circuit/types.ts

Purpose: Type definitions and interfaces Key Exports:

  • ComponentType: Enum for all electronic components
  • Component: Individual component definition
  • Circuit: Complete circuit with components and wires
  • SimulationState: Real-time simulation state
  • VisualizationOptions: Display settings

Usage:

import { Circuit, Component, ComponentType } from "@/lib/circuit/types";

/lib/circuit/simulator.ts

Purpose: Physics and circuit simulation engine Key Classes:

  • CircuitSimulator: Main simulation engine
    • step(deltaTime): Advance simulation by time delta
    • updateComponentStates(): Calculate component behavior
    • getComponentHistory(): Retrieve historical data
  • CircuitAnalyzer: Circuit analysis utilities
    • nodalAnalysis(): Solve node voltages
    • verifyKVL(): Check Kirchhoff's voltage law
    • verifyKCL(): Check Kirchhoff's current law

Key Methods:

simulator.start()              // Begin simulation
simulator.stop()               // Pause simulation
simulator.reset()              // Clear and reinitialize
simulator.step(16)             // Advance 16ms
simulator.setTimeScale(2)      // 2x speed
simulator.updateComponentParameter("r1", "resistance", 2000)

/lib/circuit/store.ts

Purpose: Global state management and visualization utilities Key Exports:

  • use3DStore: Zustand hook for circuit state
  • getComponentGeometry(): Get 3D geometry info
  • getComponentColor(): Calculate component color
  • getCurrentFlowIntensity(): Particle flow intensity
  • computeOptimalCameraPosition(): Auto-frame circuit

Usage:

const { circuit, visualization } = use3DStore();
use3DStore.setState({ selectedComponent: "r1" });

/lib/circuit/shaders.ts

Purpose: GLSL shader code for visual effects Key Shaders:

  • Current flow particle animation
  • Wire glow effects
  • Magnetic field visualization
  • Capacitor plate charging
  • Diode LED emission
  • Field pattern effects

Usage in Components:

<shaderMaterial
  vertexShader={currentFlowParticleVertexShader}
  fragmentShader={currentFlowParticleFragmentShader}
  uniforms={{...}}
/>

/lib/circuit/scenarios.ts

Purpose: Predefined circuit templates Key Exports:

  • simpleResistorCircuit: Basic Ohm's Law example
  • rcChargingCircuit: Exponential charging demonstration
  • logicGateCircuit: Digital logic showcase
  • blockDiagramCircuit: Control system example
  • allCircuits: Array of all available circuits
  • getCircuitById(): Lookup function
  • getCircuitsByCategory(): Filter by category

Adding New Circuits:

export const myCircuit: Circuit = {
  id: "unique-id",
  name: "Circuit Name",
  description: "...",
  components: [...],
  wires: [...],
  parameters: {...},
  metadata: {
    category: "analog",
    difficulty: "beginner",
    learningObjectives: [...]
  }
};

/components/3d/CircuitVisualizer3D.tsx

Purpose: Main 3D rendering component (React Three Fiber) Key Components:

  • Component3D: Renders individual electronic component
    • Selection highlighting
    • Hover effects
    • Rotation animations for active components
  • Wire3D: Renders connections with current flow
    • Particle system animation
    • Voltage color coding
    • Current intensity visualization
  • CircuitVisualizer3D: Main scene container
    • Lighting setup
    • Camera controls
    • Grid visualization

Props:

<CircuitVisualizer3D
  components={circuit.components}
  wires={circuit.wires}
  selectedComponentId={selectedId}
  hoveredComponentId={hoveredId}
  onComponentSelected={(id) => {}}
  onComponentHovered={(id) => {}}
/>

/components/3d/CircuitLab.tsx

Purpose: Main page container orchestrating all components State Management:

  • circuit: Current circuit definition
  • simulator: Active simulation engine
  • isRunning: Play/pause state
  • selectedComponentId: User selection
  • showGraphs: Toggle graph panel

Animation Loop:

  • Uses requestAnimationFrame for smooth 60 FPS
  • Calls simulator.step() with actual delta time
  • Updates circuit state for re-render

/components/3d/ControlPanel.tsx

Purpose: Interactive control interface (right sidebar) Sections:

  • Simulation: Play, pause, reset, time scale
  • Component Info: Voltage, current, power, temperature
  • Visualization: Toggle display options
  • Learning Mode: Formula hints, explanations, path highlighting
  • Quick Reference: Common formulas in tabs

Features:

  • Expandable/collapsible sections
  • Smooth transitions with Framer Motion
  • Real-time parameter updates
  • Responsive to selected component

/components/3d/VisualizationGraphs.tsx

Purpose: Real-time data plotting with Recharts Charts:

  • Voltage vs Time
  • Current vs Time
  • Power vs Time (area chart)

Features:

  • Multi-component plotting
  • Color-coded traces
  • Automatic downsampling for performance
  • Tooltip on hover
  • Legend with component names

/components/3d/CircuitSelector.tsx

Purpose: Modal gallery for circuit selection Layout:

  • Category tabs (Analog, Digital, Control)
  • Grid of circuit cards
  • Difficulty badges
  • Learning objectives preview
  • Info animation on hover

/components/3d/LearningMode.tsx

Purpose: Educational reference system Components:

  • LearningPanel: Detailed formula reference
    • Formulas tab with equations
    • Explanation tab with descriptions
    • Quick formula reference boxes
  • LearningTooltip: Hover-based hints
  • formulaReferences: Comprehensive formula database for all component types

Simulation Algorithm

1. Initialization Phase

1. Create CircuitSimulator with Circuit
2. Initialize component states
3. Set node voltages (grounds to 0V, sources to their voltage)
4. Record initial history

2. Simulation Loop (per frame)

1. Measure deltaTime since last frame
2. Call simulator.step(deltaTime)
3. For each component:
   a. Read input node voltages
   b. Calculate component-specific behavior
   c. Update component state (V, I, P, T)
   d. Write output voltages to nodes
4. Update wire currents
5. Record historical data
6. Render updated scene

3. Component Update (per component)

Resistor:
  V = node_voltage
  I = V / R

Capacitor:
  I = C * dV/dt
  V_new = V_old + (I / C) * dt

Inductor:
  V = node_voltage
  I_new = I_old + (V / L) * dt

Diode:
  if V > 0.7V:  // forward biased
    I = (V - 0.7) / r_dynamic
  else:
    I = -I_leakage

BJT:
  if Vbe > 0.7V:  // active
    I_c = β * I_b
  else:  // cutoff
    I_c = 0

OpAmp:
  V_out = A * (V_+ - V_-)  (limited by supply voltage)

4. Analysis Algorithms

Nodal Analysis:
  1. For each node, sum currents = 0
  2. For each component, calculate current based on voltage
  3. Iteratively update node voltages until convergence

Transient Response:
  - Direct integration of differential equations
  - Exponential solutions for linear circuits
  - Numerical integration for non-linear components

Key Design Patterns

1. Component Patterns

  • Compound Components: CircuitLab orchestrates multiple sub-components
  • Controlled Components: 3D components receive data via props
  • Hook-based State: Zustand store for global state

2. Simulation Patterns

  • Model-Update-Render: Simulator updates models, React renders
  • Delta Time Integration: Frame-rate independent simulation
  • Decoupled Physics: Component updates independent of order

3. Visual Patterns

  • Particle System: Current flow using instanced geometry
  • Material-based Feedback: Color and glow for state indication
  • Shader-driven Animation: GLSL handles frame-based animations

Extending the System

Adding a New Component Type

  1. Extend ComponentType enum (types.ts)
export enum ComponentType {
  // ...
  TRANSFORMER = "transformer",
}
  1. Add to getComponentGeometry() (store.ts)
[ComponentType.TRANSFORMER]: {
  geometry: "transformer",
  scale: [1.0, 1.0, 0.8],
  color: "#FF8800",
}
  1. Create geometry factory (componentGeometries.ts)
export function createTransformerGeometry(): THREE.Group {
  const group = new THREE.Group();
  // Create primary and secondary coils
  return group;
}
  1. Add simulation logic (simulator.ts)
case ComponentType.TRANSFORMER:
  this.updateTransformer(comp, dt);
  break;

private updateTransformer(comp: Component, dt: number): void {
  // Implement coupled inductor equations
}
  1. Add to component selector (scenarios.ts - optional preset)

Adding a New Circuit Scenario

export const newCircuit: Circuit = {
  id: "unique-id",
  name: "Circuit Name",
  description: "What this circuit demonstrates",
  components: [/* ... */],
  wires: [/* ... */],
  parameters: {
    voltage: 5,
    frequency: 0,
    timeStep: 0.001,
  },
  metadata: {
    category: "analog",
    difficulty: "beginner",
    learningObjectives: [
      "Learning goal 1",
      "Learning goal 2",
    ],
  },
};

// Add to allCircuits array
export const allCircuits = [
  simpleResistorCircuit,
  newCircuit, // <- Add here
];

Customizing Visual Style

Theme Configuration (in ControlPanel and CircuitLab):

// Dark theme (default)
className="bg-slate-900 text-purple-400"

// Light theme (add as variant)
className="bg-slate-100 text-purple-600"

// High contrast (add as accessibility option)
className="bg-black text-lime-400"

Performance Considerations

Optimization Strategies Implemented

  1. Memory Management

    • History buffer capped at 10,000 points
    • Old entries automatically removed (FIFO)
    • Prevents memory leaks in long simulations
  2. Render Optimization

    • Component geometries created once, reused
    • Instanced rendering for similar components
    • LOD system (disabled for small circuits)
  3. Shader Efficiency

    • Minimal texture lookups
    • Early fragment discard for invisible areas
    • Pre-compiled material templates
  4. Data Structures

    • Sparse component state updates
    • Efficient wire path calculations
    • Memoized getter functions

Performance Profiling

Browser DevTools:

  1. Open Chrome DevTools → Performance tab
  2. Start recording
  3. Let simulation run for 5-10 seconds
  4. Stop and analyze:
    • Look for long frames (>16.67ms for 60 FPS)
    • Identify bottleneck functions
    • Check memory heap size

Typical Metrics:

  • Frame time: 5-12ms (60+ FPS)
  • Memory: 50-150MB
  • GPU utilization: 20-40% (simple circuits)

Debugging

Circuit Not Updating

  1. Check if simulator is initialized
  2. Verify isRunning state is true
  3. Check console for JavaScript errors
  4. Verify components have valid connections

Graphs Not Showing Data

  1. Ensure simulation has been running long enough
  2. Check simulationState.history has data
  3. Verify component IDs match between circuit and graph

Performance Issues

  1. Reduce number of wires in circuit
  2. Disable graph rendering on complex circuits
  3. Lower time resolution in graphs
  4. Check for memory leaks via DevTools

Testing

Manual Testing Checklist

  • Circuit loads without errors
  • Play/Pause buttons work
  • Time scale slider responds
  • Components highlight on selection
  • Graphs update in real-time
  • Circuit selector loads all circuits
  • Control panel responsive to component selection
  • Smooth 60 FPS animation
  • No memory leaks after 5 minute run

Unit Testing Template

describe("CircuitSimulator", () => {
  it("should initialize with zero state", () => {
    const circuit = simpleResistorCircuit;
    const sim = new CircuitSimulator(circuit);
    sim.initialize();
    expect(sim.getState().time).toBe(0);
  });

  it("should calculate Ohm's Law correctly", () => {
    // V = IR, given V=5, R=1000
    // I should be 5/1000 = 0.005A
  });
});

Deployment

Build for Production

npm run build

Deployment Checklist

  • All dependencies installed
  • No console errors
  • Tested on target browsers
  • Images/assets included
  • Performance acceptable (60 FPS)
  • Mobile responsiveness (for future)

This implementation provides a solid foundation for interactive electronics education with room for extensions and optimizations.