diff --git a/.claude/rules/plugin-maintenance.md b/.claude/rules/plugin-maintenance.md new file mode 100644 index 00000000..86c40dd9 --- /dev/null +++ b/.claude/rules/plugin-maintenance.md @@ -0,0 +1,38 @@ +# Plugin Maintenance + +The `claude-plugin/` folder contains AI agent documentation for end users who install JEngine packages. + +## When to Update + +Update the plugin documentation when: +- New public API added to JEngine.Util or JEngine.UI +- API signature changes +- New usage patterns discovered +- Common mistakes identified + +## Files to Update + +| Package Change | Plugin File to Update | +|---------------|----------------------| +| JAction API | `claude-plugin/skills/jaction/SKILL.md` | +| JObjectPool API | `claude-plugin/skills/jobjectpool/SKILL.md` | +| MessageBox API | `claude-plugin/skills/messagebox/SKILL.md` | +| Editor UI components | `claude-plugin/skills/editor-ui/SKILL.md` | +| Design Tokens | `claude-plugin/skills/editor-ui/SKILL.md` | +| New utility class | Create new skill in `claude-plugin/skills/` | +| General patterns | `claude-plugin/CLAUDE.md` | + +## Checklist for API Changes + +- [ ] Update relevant SKILL.md with new/changed API +- [ ] Add code examples for new features +- [ ] Document common mistakes if any +- [ ] Bump version in `claude-plugin/claude.json` (CI does this automatically on release) + +## Version Sync + +Plugin version is automatically bumped by CI when packages are released. +For manual updates, bump the version in `claude-plugin/claude.json`: +- Patch (x.x.1) for doc fixes +- Minor (x.1.0) for new API coverage +- Major (1.0.0) for breaking skill changes diff --git a/.github/workflows/release-plugin.yml b/.github/workflows/release-plugin.yml new file mode 100644 index 00000000..934e0dd8 --- /dev/null +++ b/.github/workflows/release-plugin.yml @@ -0,0 +1,60 @@ +name: Release Plugin + +on: + push: + paths: + - 'claude-plugin/**' + branches: + - master + workflow_dispatch: + inputs: + bump_type: + description: 'Version bump type' + required: true + default: 'patch' + type: choice + options: + - patch + - minor + - major + +jobs: + release-plugin: + runs-on: ubuntu-latest + # Only run on master branch, skip automated version bump commits + if: | + (github.ref == 'refs/heads/master' || github.event_name == 'workflow_dispatch') && + (github.event_name == 'workflow_dispatch' || !contains(github.event.head_commit.message || '', 'chore(plugin): bump version')) + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Bump plugin version + id: bump + run: | + BUMP_TYPE="${{ github.event.inputs.bump_type || 'patch' }}" + CURRENT=$(jq -r '.version' claude-plugin/claude.json) + + IFS='.' read -r major minor patch <<< "$CURRENT" + case $BUMP_TYPE in + major) NEW_VERSION="$((major+1)).0.0" ;; + minor) NEW_VERSION="$major.$((minor+1)).0" ;; + patch) NEW_VERSION="$major.$minor.$((patch+1))" ;; + esac + + jq --arg v "$NEW_VERSION" '.version = $v' claude-plugin/claude.json > tmp.json + mv tmp.json claude-plugin/claude.json + + echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT + echo "Bumped plugin version from $CURRENT to $NEW_VERSION" + + - name: Commit and tag + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add claude-plugin/claude.json + git commit -m "chore(plugin): bump version to ${{ steps.bump.outputs.version }}" + git tag "plugin-v${{ steps.bump.outputs.version }}" + git push origin master --tags diff --git a/CLAUDE.md b/CLAUDE.md index a1055dd3..a1e108c1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,6 +5,7 @@ @.claude/rules/coding-patterns.md @.claude/rules/commit-conventions.md @.claude/rules/package-creation.md +@.claude/rules/plugin-maintenance.md ## Project Overview diff --git a/README.md b/README.md index eeb295d7..9a14fa84 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ - **Zero/Minimal GC** - UniTask (GC-free async) + Nino (high-performance serialization) - **All Platforms** - iOS, Android, Windows, macOS, WebGL, WeChat, Douyin, Alipay, TapTap - **Secure Updates** - Obfuscate hot update DLL + encrypt resources (assets & DLL/PDB) with XOR/AES/ChaCha20 +- **AI-Accelerated** - Intelligent AI [seamlessly integrated](claude-plugin/), deeply understands JEngine to boost productivity - **Commercial Ready** - Production-proven by individuals and enterprise teams ## Overview diff --git a/README_zh_cn.md b/README_zh_cn.md index f3f32f33..a7746dc1 100644 --- a/README_zh_cn.md +++ b/README_zh_cn.md @@ -18,6 +18,7 @@ - **零/极低GC** - UniTask(无GC异步)+ Nino(高性能序列化) - **全平台支持** - iOS、Android、Windows、macOS、WebGL、微信、抖音、支付宝、TapTap - **安全更新** - 热更DLL混淆 + 资源(资产和DLL/PDB)支持XOR/AES/ChaCha20加密 +- **AI赋能** - AI[深度理解JEngine](claude-plugin/),无缝融入开发流程,效率倍增 - **商用验证** - 经个人和企业团队生产环境验证 ## 概述 diff --git a/claude-plugin/CLAUDE.md b/claude-plugin/CLAUDE.md new file mode 100644 index 00000000..c6768bfe --- /dev/null +++ b/claude-plugin/CLAUDE.md @@ -0,0 +1,56 @@ +# JEngine Framework + +Unity framework for runtime hot updates. Unity 2022.3+, C#. + +## Available Packages + +### JEngine.Util (com.jasonxudeveloper.jengine.util) +- **JAction**: Fluent API for chainable action sequences with zero-allocation async +- **JObjectPool**: Thread-safe generic object pool using lock-free CAS + +### JEngine.UI (com.jasonxudeveloper.jengine.ui) +- **MessageBox**: Async modal dialogs with UniTask (runtime) +- **Editor Components**: JButton, JTextField, JStack, JCard, etc. (editor) +- **Design Tokens**: Theme-aware colors, spacing, typography + +## Key Patterns + +### Always Use UniTask (not System.Threading.Tasks.Task) +```csharp +using Cysharp.Threading.Tasks; +public async UniTask LoadAsync() { } +``` + +### JAction - Always Dispose After Async +```csharp +using var action = await JAction.Create() + .Do(static () => Debug.Log("Start")) + .Delay(1f) + .Do(static () => Debug.Log("After 1s")) + .ExecuteAsync(); +``` + +### JObjectPool - Reset State on Return +```csharp +var pool = new JObjectPool>( + onReturn: static list => list.Clear() +); +var list = pool.Rent(); +pool.Return(list); +``` + +### MessageBox - Await the Result +```csharp +bool ok = await MessageBox.Show("Title", "Message?", "Yes", "No"); +if (ok) { /* confirmed */ } +``` + +### Editor UI - Use Design Tokens +```csharp +using JEngine.UI.Editor.Theming; +using JEngine.UI.Editor.Components.Button; +using JEngine.UI.Editor.Components.Layout; + +var stack = new JStack(GapSize.MD) + .Add(new JButton("Action", () => DoIt(), ButtonVariant.Primary)); +``` diff --git a/claude-plugin/README.md b/claude-plugin/README.md new file mode 100644 index 00000000..c24851cd --- /dev/null +++ b/claude-plugin/README.md @@ -0,0 +1,51 @@ +# JEngine Claude Code Plugin + +AI-powered development guide for JEngine Unity framework. + +## Installation (Recommended: Marketplace) + +Add the JEngine marketplace for **automatic updates**: + +```bash +# Add marketplace (one-time) +claude plugin marketplace add https://github.com/JasonXuDeveloper/JEngine/tree/master/claude-plugin/marketplace.json + +# Install plugin +claude plugin install jengine@jengine-marketplace +``` + +After this, plugin updates automatically when Claude Code starts. + +## Alternative: Direct Install + +```bash +claude plugin install https://github.com/JasonXuDeveloper/JEngine/tree/master/claude-plugin +``` + +(Note: Direct installs require manual updates) + +## Features + +After installation, Claude Code automatically: +- Suggests JAction for sequential tasks, timers, and delays +- Suggests JObjectPool for object pooling and GC optimization +- Suggests MessageBox for confirmation dialogs +- Suggests Editor UI components for custom inspectors and editor windows +- Follows JEngine coding conventions (UniTask, namespaces, etc.) + +## Skills Included + +### JEngine.Util (Runtime) +- `/jaction` - Chainable task system with zero-allocation async +- `/jobjectpool` - Thread-safe object pooling + +### JEngine.UI (Runtime + Editor) +- `/messagebox` - Async modal dialogs +- `/editor-ui` - Editor UI components (JButton, JStack, Tokens, etc.) + +## Requirements + +- Claude Code CLI +- JEngine packages installed in your Unity project: + - `com.jasonxudeveloper.jengine.util` + - `com.jasonxudeveloper.jengine.ui` diff --git a/claude-plugin/claude.json b/claude-plugin/claude.json new file mode 100644 index 00000000..c4f03c82 --- /dev/null +++ b/claude-plugin/claude.json @@ -0,0 +1,10 @@ +{ + "name": "jengine", + "displayName": "JEngine Framework", + "version": "1.0.0", + "description": "AI development guide for JEngine Unity hot-update framework", + "author": "JasonXuDeveloper", + "repository": "https://github.com/JasonXuDeveloper/JEngine", + "skills": ["skills/*/SKILL.md"], + "claudeMd": "CLAUDE.md" +} diff --git a/claude-plugin/marketplace.json b/claude-plugin/marketplace.json new file mode 100644 index 00000000..2782dfda --- /dev/null +++ b/claude-plugin/marketplace.json @@ -0,0 +1,20 @@ +{ + "name": "jengine-marketplace", + "description": "JEngine Framework plugins for AI-assisted Unity development", + "owner": { + "name": "JasonXuDeveloper", + "url": "https://github.com/JasonXuDeveloper" + }, + "plugins": [ + { + "name": "jengine", + "description": "AI development guide for JEngine Unity hot-update framework", + "source": { + "source": "github", + "repo": "JasonXuDeveloper/JEngine", + "path": "claude-plugin", + "ref": "master" + } + } + ] +} diff --git a/claude-plugin/skills/editor-ui/SKILL.md b/claude-plugin/skills/editor-ui/SKILL.md new file mode 100644 index 00000000..7710ca35 --- /dev/null +++ b/claude-plugin/skills/editor-ui/SKILL.md @@ -0,0 +1,411 @@ +--- +name: editor-ui +description: JEngine Editor UI components. Triggers on: custom inspector, editor window, Unity editor UI, UIElements, VisualElement, progress bar, status bar, breadcrumb, form field +--- + +# JEngine Editor UI Components + +Modern UI component library for Unity Editor using UIElements with automatic dark/light theme support. + +## When to Use +- Building custom inspectors +- Creating Editor windows +- Designing Editor tools with consistent styling + +## Namespaces +```csharp +using JEngine.UI.Editor.Components.Button; +using JEngine.UI.Editor.Components.Layout; +using JEngine.UI.Editor.Components.Form; +using JEngine.UI.Editor.Components.Feedback; +using JEngine.UI.Editor.Components.Navigation; +using JEngine.UI.Editor.Theming; +``` + +## Button Components + +### JButton - Themed Buttons +```csharp +// Variants: Primary, Secondary, Success, Danger, Warning +var btn = new JButton("Click Me", () => DoAction(), ButtonVariant.Primary); + +// Fluent API +btn.SetVariant(ButtonVariant.Danger) + .WithText("Delete") + .WithEnabled(true) + .FullWidth() + .Compact() + .WithMinWidth(100); +``` + +### JIconButton - Small Icon Buttons +```csharp +// For toolbars and inline actions +var iconBtn = new JIconButton("X", () => Close(), "Close panel") + .WithSize(24, 24) + .WithTooltip("Close"); +``` + +### JToggleButton - Two-State Toggle +```csharp +var toggle = new JToggleButton( + onText: "Enabled", + offText: "Disabled", + initialValue: false, + onVariant: ButtonVariant.Success, + offVariant: ButtonVariant.Danger, + onValueChanged: value => Debug.Log($"Now: {value}")); + +// Access value +toggle.Value = true; +toggle.SetValue(false, notify: false); +``` + +### JButtonGroup - Responsive Button Row +```csharp +var group = new JButtonGroup( + new JButton("Save", Save, ButtonVariant.Primary), + new JButton("Cancel", Cancel, ButtonVariant.Secondary)) + .NoWrap() + .FixedWidth(); +``` + +## Layout Components + +### JStack - Vertical Layout +```csharp +// Gap sizes: Xs (2px), Sm (4px), MD (8px), Lg (12px), Xl (16px) +var stack = new JStack(GapSize.MD) + .Add(new Label("Title")) + .Add(new JButton("Action")) + .WithGap(GapSize.Lg); +``` + +### JRow - Horizontal Layout +```csharp +var row = new JRow() + .Add(new JButton("Left")) + .Add(new JButton("Right")) + .WithJustify(JustifyContent.SpaceBetween) // Start, Center, End, SpaceBetween + .WithAlign(AlignItems.Center) // Start, Center, End, Stretch + .NoWrap(); +``` + +### JCard - Bordered Container +```csharp +var card = new JCard() + .Add(new Label("Card Content")) + .Compact() + .NoMargin(); +``` + +### JSection - Card with Header +```csharp +var section = new JSection("Settings") + .Add(new JFormField("Name", new JTextField())) + .Add(new JFormField("Enabled", new JToggle())) + .WithTitle("New Title") + .NoHeader() + .NoMargin(); + +// Access header and content +section.Header.text = "Updated"; +section.Content.Add(new Label("More content")); +``` + +## Form Components + +### JTextField - Styled Text Input +```csharp +var field = new JTextField("initial value", "placeholder"); +field.RegisterValueChangedCallback(evt => Debug.Log(evt.newValue)); + +// Fluent API +field.SetReadOnly(true) + .SetMultiline(true); + +// Access value +string text = field.Value; +field.Value = "new value"; + +// Bind to SerializedProperty +field.BindProperty(serializedProperty); +``` + +### JDropdown - Generic Dropdown +```csharp +// String dropdown +var stringDropdown = new JDropdown( + new List { "Option A", "Option B" }, + defaultValue: "Option A"); + +// Enum dropdown (recommended) +var enumDropdown = JDropdown.ForEnum(MyEnum.Default); +enumDropdown.OnValueChanged(value => Debug.Log(value)); + +// Generic dropdown with custom formatting +var customDropdown = new JDropdown( + items, + defaultValue: items[0], + formatSelectedValue: x => x.DisplayName, + formatListItem: x => x.FullDescription); + +// Access +enumDropdown.Value = MyEnum.Other; +enumDropdown.Choices = newList; +``` + +### JToggle - Toggle Switch +```csharp +var toggle = new JToggle(initialValue: false) + .OnValueChanged(value => Debug.Log(value)) + .WithClass("my-toggle"); + +toggle.Value = true; +toggle.SetValueWithoutNotify(false); // No callback +``` + +### JObjectField - Unity Object Picker +```csharp +var objectField = new JObjectField(allowSceneObjects: false); +objectField.RegisterValueChangedCallback(evt => + Debug.Log($"Selected: {evt.newValue?.name}")); + +// Access +Texture2D texture = objectField.Value; +objectField.BindProperty(serializedProperty); +``` + +### JFormField - Label + Control Layout +```csharp +var formField = new JFormField("Player Name", new JTextField()) + .WithLabelWidth(150) + .NoLabel(); + +// Add multiple controls +formField.Add(new JButton("Browse")); +``` + +## Feedback Components + +### JProgressBar - Progress Indicator +```csharp +var progress = new JProgressBar(initialProgress: 0f) + .SetProgress(0.5f) + .WithHeight(12) + .WithColor(Color.green) + .WithVariant(ButtonVariant.Success) + .WithSuccessOnComplete(); + +progress.Progress = 0.75f; +``` + +### JStatusBar - Status Message with Accent +```csharp +// Status types: Info, Success, Warning, Error +var status = new JStatusBar("Ready", StatusType.Info) + .SetStatus(StatusType.Success) + .WithText("Operation complete!"); + +status.Text = "Processing..."; +status.Status = StatusType.Warning; +``` + +### JLogView - Scrollable Log Output +```csharp +var logView = new JLogView(maxLines: 100) + .LogInfo("Started processing") + .LogError("Something went wrong") + .Log("Custom message", isError: false) + .WithMinHeight(150) + .WithMaxHeight(400); + +logView.Clear(); +logView.MaxLines = 200; +``` + +## Navigation Components + +### JBreadcrumb - Path Navigation +```csharp +// Quick creation +var breadcrumb = JBreadcrumb.FromPath("Package", "Scene", "Object"); + +// Manual building +var bc = new JBreadcrumb() + .AddItem("Root") + .AddItem("Child"); +bc.Build(); + +bc.SetPath("New", "Path"); +bc.Clear(); +``` + +## Design Tokens + +The `Tokens` class provides named constants that adapt to Unity's dark/light theme. + +### Colors +```csharp +// Backgrounds (layered from deep to elevated) +Tokens.Colors.BgBase // Deepest background +Tokens.Colors.BgSubtle // Secondary containers +Tokens.Colors.BgSurface // Cards, panels (most common) +Tokens.Colors.BgElevated // Hover states, important elements +Tokens.Colors.BgOverlay // Modals, tooltips +Tokens.Colors.BgHover // Hover state +Tokens.Colors.BgInput // Input field background + +// Text hierarchy +Tokens.Colors.TextPrimary // Highest contrast +Tokens.Colors.TextSecondary // Body text +Tokens.Colors.TextMuted // Helper text +Tokens.Colors.TextHeader // Headers +Tokens.Colors.TextSectionHeader // Section titles + +// Button colors +Tokens.Colors.Primary, PrimaryHover, PrimaryActive, PrimaryText +Tokens.Colors.Secondary, SecondaryHover, SecondaryActive, SecondaryText +Tokens.Colors.Success, SuccessHover, SuccessActive +Tokens.Colors.Danger, DangerHover, DangerActive +Tokens.Colors.Warning, WarningHover, WarningActive + +// Borders +Tokens.Colors.Border, BorderFocus, BorderHover, BorderSubtle + +// Status (aliases) +Tokens.Colors.StatusInfo, StatusSuccess, StatusWarning, StatusError + +// Theme check +if (Tokens.IsDarkTheme) { } +``` + +### Spacing +```csharp +Tokens.Spacing.Xs // 2px +Tokens.Spacing.Sm // 4px +Tokens.Spacing.MD // 8px +Tokens.Spacing.Lg // 12px +Tokens.Spacing.Xl // 16px +Tokens.Spacing.Xxl // 24px +``` + +### Font Sizes +```csharp +Tokens.FontSize.Xs // 10px - metadata +Tokens.FontSize.Sm // 11px - hints +Tokens.FontSize.Base // 12px - body (default) +Tokens.FontSize.MD // 13px - emphasis +Tokens.FontSize.Lg // 14px - section labels +Tokens.FontSize.Xl // 16px - section headers +Tokens.FontSize.Title // 18px - panel headers +``` + +### Border Radius +```csharp +Tokens.BorderRadius.Sm // 3px +Tokens.BorderRadius.MD // 5px +Tokens.BorderRadius.Lg // 8px +``` + +### Layout Constants +```csharp +Tokens.Layout.FormLabelWidth // 140px +Tokens.Layout.FormLabelMinWidth // 60px +Tokens.Layout.MinTouchTarget // 24px +Tokens.Layout.MinControlWidth // 80px +``` + +### Transitions +```csharp +Tokens.Transition.Fast // 150ms +Tokens.Transition.Normal // 200ms +``` + +## JTheme Utilities + +```csharp +// Apply common styles +JTheme.ApplyTransition(element); // Smooth hover transitions +JTheme.ApplyPointerCursor(element); // Hand cursor +JTheme.ApplyTextCursor(element); // Text I-beam cursor +JTheme.ApplyGlassCard(element); // Card styling + +// Input field styles +JTheme.ApplyInputContainerStyle(element); +JTheme.ApplyInputElementStyle(element); +JTheme.ApplyInputTextStyle(element); +JTheme.ApplyInputHoverState(element); +JTheme.ApplyInputFocusState(element); +JTheme.ApplyInputNormalState(element); +JTheme.HideFieldLabel(field); + +// Get button colors by variant +Color btnColor = JTheme.GetButtonColor(ButtonVariant.Primary); +Color hoverColor = JTheme.GetButtonHoverColor(ButtonVariant.Primary); +Color activeColor = JTheme.GetButtonActiveColor(ButtonVariant.Primary); +``` + +## Enums + +```csharp +// Button styling +enum ButtonVariant { Primary, Secondary, Success, Danger, Warning } + +// Layout gaps +enum GapSize { Xs, Sm, MD, Lg, Xl } + +// Status indicators +enum StatusType { Info, Success, Warning, Error } + +// Row alignment +enum JustifyContent { Start, Center, End, SpaceBetween } +enum AlignItems { Start, Center, End, Stretch } +``` + +## Example: Complete Editor Window + +```csharp +public class MyEditorWindow : EditorWindow +{ + [MenuItem("Tools/My Window")] + public static void ShowWindow() => GetWindow("My Window"); + + public void CreateGUI() + { + var root = new JStack(GapSize.MD); + root.style.paddingTop = Tokens.Spacing.Lg; + root.style.paddingRight = Tokens.Spacing.Lg; + root.style.paddingBottom = Tokens.Spacing.Lg; + root.style.paddingLeft = Tokens.Spacing.Lg; + + // Breadcrumb navigation + root.Add(JBreadcrumb.FromPath("Tools", "My Window")); + + // Settings section + var settings = new JSection("Settings") + .Add(new JFormField("Name", new JTextField())) + .Add(new JFormField("Type", JDropdown.ForEnum())) + .Add(new JFormField("Enabled", new JToggle(true))); + root.Add(settings); + + // Progress section + var progress = new JProgressBar(0.3f).WithSuccessOnComplete(); + root.Add(new JFormField("Progress", progress)); + + // Status + root.Add(new JStatusBar("Ready", StatusType.Info)); + + // Buttons + root.Add(new JButtonGroup( + new JButton("Apply", Apply, ButtonVariant.Primary), + new JButton("Reset", Reset, ButtonVariant.Secondary))); + + // Log output + var log = new JLogView(50).WithMaxHeight(200); + root.Add(log); + + rootVisualElement.Add(root); + } +} +``` diff --git a/claude-plugin/skills/jaction/SKILL.md b/claude-plugin/skills/jaction/SKILL.md new file mode 100644 index 00000000..8a745d4c --- /dev/null +++ b/claude-plugin/skills/jaction/SKILL.md @@ -0,0 +1,116 @@ +--- +name: jaction +description: JAction chainable task system. Triggers on: sequential tasks, delays, timers, repeat loops, WaitUntil, async workflows, zero-allocation async +--- + +# JAction - Chainable Task Execution + +Fluent API for composing complex action sequences in Unity with automatic object pooling and zero-allocation async. + +## When to Use +- Sequential workflows with delays +- Polling conditions (WaitUntil/WaitWhile) +- Repeat loops with intervals +- Game timers and scheduled events +- Zero-GC async operations + +## Core API + +### Execution Methods +- `.Execute(float timeout = 0)` - Synchronous execution (BLOCKS main thread - use sparingly) +- `.ExecuteAsync(float timeout = 0)` - Asynchronous via PlayerLoop (RECOMMENDED) + +### Action Execution +- `.Do(Action)` - Execute synchronous action +- `.Do(Action, T state)` - Execute with state parameter (zero-allocation for reference types) +- `.Do(Func)` - Execute async action +- `.Do(Func, T state)` - Async with state + +### Delays & Waits +- `.Delay(float seconds)` - Wait specified seconds +- `.DelayFrame(int frames)` - Wait specified frame count +- `.WaitUntil(Func)` - Wait until condition true +- `.WaitWhile(Func)` - Wait while condition true + +### Loops +- `.Repeat(Action, int count, float interval)` - Repeat N times with interval +- `.RepeatWhile(Action, Func, float frequency, float timeout)` - Repeat while condition +- `.RepeatUntil(Action, Func, float frequency, float timeout)` - Repeat until condition + +### Configuration +- `.Parallel()` - Enable concurrent action execution +- `.OnCancel(Action)` - Register cancellation callback + +### Lifecycle +- `.Cancel()` - Stop execution +- `.Reset()` - Clear state for reuse +- `.Dispose()` - Return to object pool +- `JAction.PooledCount` - Check pooled instances +- `JAction.ClearPool()` - Empty the pool + +## Patterns + +### Basic Sequence (use ExecuteAsync in production) +```csharp +using var action = await JAction.Create() + .Do(static () => Debug.Log("Step 1")) + .Delay(1f) + .Do(static () => Debug.Log("Step 2")) + .ExecuteAsync(); +``` + +### Always Use `using var` for Async (CRITICAL) +```csharp +// CORRECT - auto-disposes and returns to pool +using var action = await JAction.Create() + .Do(() => LoadAsset()) + .WaitUntil(() => assetLoaded) + .ExecuteAsync(); + +// WRONG - memory leak, never returns to pool +await JAction.Create() + .Do(() => LoadAsset()) + .ExecuteAsync(); +``` + +### State Parameter for Zero-Allocation (Reference Types Only) +```csharp +// CORRECT - no closure allocation with reference types +var data = new MyData(); +JAction.Create() + .Do(static (MyData d) => d.Process(), data) + .Execute(); + +// WARNING: State overloads DO NOT work with value types (int, float, struct, bool, etc.) +// Value types get boxed when passed as generic parameters, defeating zero-allocation +// For value types, use closures instead (allocation is acceptable): +int count = 5; +JAction.Create() + .Do(() => Debug.Log($"Count: {count}")) // Closure is fine for value types + .Execute(); +``` + +### Set Timeouts for Production +```csharp +using var action = await JAction.Create() + .WaitUntil(() => networkReady) + .ExecuteAsync(timeout: 30f); // Prevents infinite waits +``` + +### With Cancellation +```csharp +var action = JAction.Create() + .OnCancel(() => Debug.Log("Cancelled!")) + .Do(() => LongRunningTask()); + +var task = action.ExecuteAsync(); +// Later... +action.Cancel(); +``` + +## Common Mistakes +- NOT using `using var` after ExecuteAsync (memory leak, never returns to pool) +- Using Execute() in production (blocks main thread, causes frame drops) +- Using state overloads with value types (causes boxing - use closures instead) +- Forgetting to call Execute() or ExecuteAsync() (nothing happens) +- Code in .Do() runs atomically and cannot be interrupted - keep callbacks lightweight diff --git a/claude-plugin/skills/jobjectpool/SKILL.md b/claude-plugin/skills/jobjectpool/SKILL.md new file mode 100644 index 00000000..a2696f21 --- /dev/null +++ b/claude-plugin/skills/jobjectpool/SKILL.md @@ -0,0 +1,91 @@ +--- +name: jobjectpool +description: JObjectPool thread-safe pooling. Triggers on: object pool, GC optimization, reusable instances, bullet pool, spawn pool, reduce garbage collection +--- + +# JObjectPool - Thread-Safe Object Pooling + +Thread-safe, lock-free generic object pooling for Unity using CAS operations. Works with job system and async operations. + +## When to Use +- Frequently instantiated objects (bullets, enemies, effects) +- Reducing GC during gameplay +- Multi-threaded object reuse (safe from any thread) +- High-frequency object lifecycle operations + +## Core API + +### Constructor +```csharp +new JObjectPool( + int maxSize = 64, // Maximum pooled objects (excess discarded) + Action onRent = null, // Called when renting (for initialization) + Action onReturn = null // Called when returning (for cleanup) +) +``` +Note: `T` must be a reference type with a parameterless constructor (`where T : class, new()`). + +### Methods +- `.Rent()` - Get object from pool or create new +- `.Return(T obj)` - Return object to pool (null values ignored) +- `.Clear()` - Remove all pooled objects +- `.Prewarm(int count)` - Pre-allocate objects (won't exceed maxSize) +- `.Count` - Current available count (approximate, thread-safe) + +### Static Access +- `JObjectPool.Shared()` - Global shared pool per type (default config: maxSize=64) + +## Patterns + +### Basic Pool +```csharp +var pool = new JObjectPool(maxSize: 100); +var bullet = pool.Rent(); +// ... use bullet ... +pool.Return(bullet); +``` + +### With Initialization on Rent +```csharp +var pool = new JObjectPool( + maxSize: 50, + onRent: static enemy => enemy.Reset() +); +``` + +### Reset State on Return (RECOMMENDED) +```csharp +var pool = new JObjectPool>( + maxSize: 32, + onReturn: static list => list.Clear() +); +``` + +### Prewarm During Loading +```csharp +var pool = new JObjectPool(); +pool.Prewarm(50); // Pre-create during loading screen +``` + +### Shared Pool (Simple Objects) +```csharp +// Good for simple reusable objects without custom callbacks +var sb = JObjectPool.Shared().Rent(); +sb.Append("Hello"); +sb.Clear(); // Clean up before returning +JObjectPool.Shared().Return(sb); +``` + +## Best Practices +1. **Pre-allocate during loading** to prevent in-game allocation spikes +2. **Reset state on return** to prevent data leaks between reuses +3. **Set appropriate maxSize** based on expected concurrent usage +4. **Use shared pools** for simple objects without custom callbacks +5. **Monitor pool Count** to optimize sizing + +## Common Mistakes +- Returning null to pool (ignored, but wasteful) +- Not clearing object state on return (causes bugs from stale data) +- Forgetting to return objects (pool becomes ineffective) +- Setting maxSize too low (causes frequent allocations) +- Setting maxSize too high (wastes memory) diff --git a/claude-plugin/skills/messagebox/SKILL.md b/claude-plugin/skills/messagebox/SKILL.md new file mode 100644 index 00000000..aead7e62 --- /dev/null +++ b/claude-plugin/skills/messagebox/SKILL.md @@ -0,0 +1,81 @@ +--- +name: messagebox +description: MessageBox async dialogs. Triggers on: confirmation dialog, modal, prompt, alert, user confirmation, yes/no dialog +--- + +# MessageBox - Async Modal Dialogs + +Built on UniTask for non-blocking async operations with automatic object pooling. + +## When to Use +- Confirmation dialogs (Yes/No, OK/Cancel) +- Information prompts (OK only) +- Awaiting user decisions in gameplay + +## API + +### Show Method +```csharp +public static UniTask Show( + string title, + string content, + string ok = "OK", + string no = "Cancel" +) +``` +Returns `true` for confirm, `false` for cancel. + +### Management +- `MessageBox.CloseAll()` - Dismiss all active dialogs (for scene transitions) +- `MessageBox.Dispose()` - Release all pooled instances (app shutdown) +- `MessageBox.ActiveCount` - Currently displayed dialogs +- `MessageBox.PooledCount` - Cached instances in pool + +## Patterns + +### Confirmation Dialog +```csharp +bool confirmed = await MessageBox.Show( + "Delete Item", + "Are you sure you want to delete this item?", + ok: "Delete", + no: "Cancel" +); + +if (confirmed) +{ + DeleteItem(); +} +``` + +### Custom Button Text +```csharp +bool saved = await MessageBox.Show( + "Save Changes", + "Keep your changes?", + ok: "Save", + no: "Discard" +); +``` + +### Single Button (Notification) +```csharp +// Pass null or empty string to hide cancel button +await MessageBox.Show( + "Success", + "Operation completed!", + ok: "OK", + no: null +); +``` + +### Clean Up Before Scene Change +```csharp +MessageBox.CloseAll(); +SceneManager.LoadScene("NextScene"); +``` + +## Common Mistakes +- Forgetting to await (dialog shows but code continues immediately) +- Not handling both true/false return values +- Not calling CloseAll() before scene transitions