AgentSkillsCN

algorithm-animation

使用Remotion创建动画算法可视化。当用户请求算法动画、算法教学视频,或希望以直观的方式展示排序、搜索、树、图,以及动态规划等算法时,本技能便能助您轻松实现。它支持生成完整的Remotion项目,为每个步骤提供算法的可视化呈现。

SKILL.md
--- frontmatter
name: algorithm-animation
description: Create animated algorithm visualizations using Remotion. Use when the user requests algorithm animations, educational videos about algorithms, or visual demonstrations of sorting, searching, tree, graph, or dynamic programming algorithms. Supports generating complete Remotion projects with step-by-step algorithm visualizations.

Algorithm Animation with Remotion

Create professional algorithm visualization videos using React and Remotion.

Quick Start

IMPORTANT: Before starting, ask the user:

  1. Programming Language for code examples:

    • JavaScript/TypeScript (推荐 - Remotion uses React/TypeScript)
    • Python
    • C++
    • Java
    • 其他 (用户指定)
  2. Natural Language for explanations:

    • 中文 (Chinese)
    • English
    • 双语 (Bilingual - Chinese + English)

When a user requests an algorithm animation:

  1. Ask for programming language preference (JavaScript/Python/C++/Java/etc.)
  2. Ask for natural language preference (中文/English/双语)
  3. Initialize project using the init script
  4. Generate component for the specific algorithm
  5. Implement algorithm logic using reference patterns with chosen languages
  6. Preview and render the video

Supported Algorithm Types

  • Sorting: Bubble sort, quick sort, merge sort, insertion sort, selection sort, heap sort
  • Searching: Binary search, linear search, DFS, BFS
  • Tree: Tree traversal (in-order, pre-order, post-order), BST operations
  • Graph: Dijkstra's algorithm, Bellman-Ford, Kruskal, Prim, topological sort
  • Dynamic Programming: Fibonacci, knapsack, LCS, edit distance

Workflow

Step 1: Initialize Remotion Project

bash
bash scripts/init_project.sh <project-name>
cd <project-name>

Or manually copy files from assets/remotion-template/ to the project directory.

Step 2: Generate Algorithm Component

Standard Mode (basic visualization):

bash
python3 scripts/generate_component.py <algorithm-type> <algorithm-name>

Educational Mode (with detailed explanations and code):

bash
python3 scripts/generate_component.py <algorithm-type> <algorithm-name> --educational

Algorithm types: sorting, searching, tree, graph, dp

Examples:

bash
# Standard mode
python3 scripts/generate_component.py sorting bubble-sort

# Educational mode with explanations
python3 scripts/generate_component.py sorting bubble-sort --educational

python3 scripts/generate_component.py searching binary-search --educational
python3 scripts/generate_component.py tree in-order-traversal --educational

Educational mode generates components with:

  • Introduction slides explaining the algorithm
  • Step-by-step text descriptions
  • Code snippets with line highlighting
  • Slower pacing with longer frame durations
  • Educational annotations

Step 3: Implement Algorithm Logic

Consult the reference files for implementation patterns:

Each reference file contains:

  • Step generation patterns
  • Complete algorithm implementations
  • Visualization code
  • Color schemes
  • Animation effects

For educational animations, see the educational-animations reference for:

  • Introduction slide patterns
  • Step descriptions with code references
  • Variable timing for different step types
  • Code highlighting components
  • Best practices for pacing and explanations

Step 4: Register Composition

Add the component to src/Root.tsx:

typescript
import { Composition } from 'remotion';
import { BubbleSort } from './BubbleSort';

export const RemotionRoot: React.FC = () => {
  return (
    <>
      <Composition
        id="BubbleSort"
        component={BubbleSort}
        durationInFrames={300}
        fps={30}
        width={1920}
        height={1080}
        defaultProps={{
          arraySize: 10,
        }}
      />
    </>
  );
};

Step 5: Preview and Render

Preview (opens Remotion Studio):

bash
npm start

Render video:

bash
npm run build BubbleSort out/bubble-sort.mp4

Common Patterns

Animation Structure

All algorithm animations follow this pattern:

typescript
interface AlgorithmStep {
  // Current state
  data: any;
  // Highlighted elements
  active: number[];
  // Completed elements
  completed: number[];
}

// 1. Generate steps
const steps = useMemo(() => generateSteps(initialData), [initialData]);

// 2. Calculate current step
const currentStepIndex = Math.floor(frame / framesPerStep);
const currentStep = steps[currentStepIndex];

// 3. Render visualization based on current step
return <Visualization step={currentStep} />;

Color Scheme

Use consistent colors across all animations:

  • Green (#16a085): Default/unprocessed
  • Red (#e74c3c): Currently active/comparing
  • Orange (#f39c12): Swapping/moving
  • Blue (#3498db): Completed/sorted
  • Purple (#9b59b6): Special (pivot, target, etc.)
  • Yellow (#f1c40f): Queue/frontier
  • Gray (#555): Inactive/out of range

Timing

Standard animations:

typescript
const framesPerStep = Math.floor(durationInFrames / steps.length);
const currentStepIndex = Math.min(
  Math.floor(frame / framesPerStep),
  steps.length - 1
);

Educational animations (variable timing):

typescript
// Each step can have custom duration
interface DetailedStep {
  // ... other fields
  duration?: number; // Frames for this step
}

// Recommended durations at 30fps:
// - Simple comparisons: 30-45 frames (1-1.5s)
// - Important operations: 60 frames (2s)  
// - Round completion: 60-90 frames (2-3s)
// - Introduction slides: 90 frames (3s)

Spring Animations

typescript
const scale = spring({
  frame: frame % framesPerStep,
  fps,
  config: { damping: 200, stiffness: 200, mass: 1 },
});

Customization

Modify these parameters in compositions:

  • durationInFrames: Total video length (e.g., 300 = 10 seconds at 30fps)
    • Standard animations: 300-450 frames (10-15 seconds)
    • Educational animations: 600-900+ frames (20-30+ seconds for detailed explanations)
  • fps: Frames per second (typically 30 or 60)
  • width, height: Video dimensions (e.g., 1920x1080)
  • defaultProps: Algorithm-specific parameters (array size, target value, etc.)

Educational Components

The template includes reusable educational components in assets/remotion-template/src/components/ExplanationComponents.tsx:

ExplanationPanel

Display text explanations with fade in/out and scale animation:

typescript
<ExplanationPanel
  title="Algorithm Overview"
  content="Bubble sort repeatedly compares adjacent elements..."
  startFrame={0}
  endFrame={90}
  position="center" // 'top' | 'bottom' | 'left' | 'right' | 'center'
  size="large"      // Optional: 'small' | 'medium' | 'large' (auto-adjusts based on content)
/>

Features:

  • Dynamic font sizing: Automatically adjusts based on content length
    • Large (< 60 chars): 72px title, 40px content
    • Medium (60-100 chars): 52px title, 32px content
    • Small (> 100 chars): 36px title, 24px content
  • Center position: Best for introduction slides (more prominent)
  • Scale animation: Smooth entrance effect (0.9 → 1.0)

CodeHighlight

Show code with line highlighting and multi-language support:

typescript
<CodeHighlight
  code={algorithmCode}
  highlightedLine={5}  // Which line to highlight
  startFrame={100}
  endFrame={200}
  language="cpp"       // 'typescript' | 'javascript' | 'python' | 'cpp' | 'java'
/>

Supported languages:

  • JavaScript/TypeScript
  • Python
  • C++
  • Java

See references/code-languages.md for code examples in different languages.

StepDescription

Display current step information:

typescript
<StepDescription
  step="Comparing Elements"
  description="比较 arr[2] 和 arr[3]"
  codeReference="Line 12-15"
/>

Content Verification (CRITICAL)

IMPORTANT: Always verify the correctness of animations before finalizing:

1. Save Algorithm Code

After creating the animation, save the displayed code to a file:

bash
# Create algorithm-code file in the project directory
# Example: algorithm-code.cpp, algorithm-code.py, etc.

2. Create Verification Document

Create a VERIFICATION.md file with the following sections:

a) Algorithm Structure Validation

  • Verify data structure is correct (tree, array, graph, etc.)
  • Check initial values match the algorithm logic
  • Confirm edge cases are handled

b) Algorithm Logic Validation

  • Verify each step follows the algorithm correctly
  • Check loop conditions and termination
  • Validate update operations (swap, insert, delete, etc.)
  • Confirm sorting/searching criteria

c) Manual Execution Test

  • Walk through the algorithm manually with the same input
  • Compare expected vs. actual results at each step
  • Verify final output is correct

d) Code Line Reference Validation

  • Ensure all codeReference and codeLine values are accurate
  • Check that highlighted lines match the current operation
  • Verify code syntax is correct for the chosen language

e) Educational Content Validation

  • Verify all explanations are accurate
  • Check terminology is correct
  • Confirm complexity analysis is right (Big-O notation)
  • Validate algorithmic concepts

f) Visual Animation Validation

  • Check color coding is consistent
  • Verify state transitions are logical
  • Ensure no steps are skipped or duplicated

3. Create Project Summary

Create a PROJECT-SUMMARY.md documenting:

  • Algorithm information
  • File structure
  • Animation content breakdown
  • Build instructions
  • Verification results

Example Verification Checklist:

markdown
| Component | Status |
|-----------|--------|
| Data structure | ✅ Correct |
| Algorithm logic | ✅ Correct |
| Final result | ✅ Correct (value: X) |
| Code line numbers | ✅ Accurate |
| Explanations | ✅ Accurate |
| Visual design | ✅ Clear |

Never skip verification! Incorrect algorithm animations can mislead learners.

Tips

  1. Start with references: Copy implementation patterns from reference files
  2. Test incrementally: Use Remotion Studio to preview changes in real-time
  3. Keep steps granular: More steps = smoother animation
  4. Add titles and labels: Make videos educational with clear annotations
  5. Use consistent styling: Follow the color scheme for visual consistency
  6. Always verify correctness: Create verification documents for every animation
  7. Save algorithm code: Keep code files for reference and documentation

Troubleshooting

Animations too fast/slow: Adjust durationInFrames or frames per step calculation

Incorrect rendering: Check step generation logic, ensure all states are captured

TypeScript errors: Verify imports and type definitions, check tsconfig.json

Video rendering fails: Ensure all dependencies are installed: npm install

Algorithm behaves incorrectly: Review VERIFICATION.md and manually trace execution