diff --git a/README.md b/README.md index 217b4ca..aff1c04 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ A React-based web application providing: A route-scoped reverse proxy that serves the playground at `caza.la/party` while proxying to `party.caza.la`. -### [`skill`](./packages/skill) - Party Skill +### [`skill`](./packages/skill/SKILL.md) - Party Skill Agent skill for the `@cazala/party` library. diff --git a/SKILL.md b/SKILL.md deleted file mode 100644 index b9c3a21..0000000 --- a/SKILL.md +++ /dev/null @@ -1,189 +0,0 @@ ---- -name: party -description: "Programmatic guide for the @cazala/party library: engine setup, modules, particles, and performance across CPU + WebGPU." -version: 0.1.0 -license: MIT -tags: [party, particles, physics, webgpu, cpu, simulation, typescript] ---- - -# Party - -Reusable guidance for using the `@cazala/party` library programmatically: engine setup, runtime selection, particles, modules, and performance constraints across CPU + WebGPU. - -## When to use this skill - -- You need to instantiate the Party engine in a custom app (not the playground). -- You want examples for adding particles, configuring modules, or using oscillators. -- You need performance-safe patterns for WebGPU (avoiding full readbacks). - -## Quick start (minimal) - -```ts -import { - Engine, - Environment, - Boundary, - Collisions, - Particles, - Trails, -} from "@cazala/party"; - -const canvas = document.querySelector("canvas")!; - -const forces = [ - new Environment({ gravityStrength: 600, gravityDirection: "down" }), - new Boundary({ mode: "bounce", restitution: 0.9, friction: 0.1 }), - new Collisions({ restitution: 0.85 }), -]; - -const render = [ - new Trails({ trailDecay: 10, trailDiffuse: 4 }), - new Particles({ colorType: 2, hue: 0.55 }), -]; - -const engine = new Engine({ canvas, forces, render, runtime: "auto" }); - -await engine.initialize(); -engine.play(); -``` - -## Core concepts - -### Particle shape - -```ts -type IParticle = { - position: { x: number; y: number }; - velocity: { x: number; y: number }; - size: number; - mass: number; - color: { r: number; g: number; b: number; a: number }; // 0..1 floats -}; -``` - -- Pinned particles: `mass < 0` -- Removed particles: `mass === 0` - -### Runtime selection - -- `"auto"` tries WebGPU first, then falls back to CPU on `initialize()`. -- WebGPU has higher throughput but GPU → CPU readbacks are expensive. - -### Engine lifecycle - -```ts -await engine.initialize(); -engine.play(); // start loop -engine.pause(); // pause loop -engine.stop(); // cancel loop -engine.destroy(); // clean up -``` - -### Module system - -Modules are typed force or render units: - -- **Force**: apply acceleration/velocity changes or constraints. -- **Render**: draw particles/lines or post-process scene texture. - -Each module exposes inputs and helpers, and can be toggled: - -```ts -const boundary = new Boundary(); -boundary.setEnabled(false); -boundary.setRestitution(0.8); -``` - -## Common tasks - -### Add particles - -```ts -for (let i = 0; i < 200; i++) { - engine.addParticle({ - position: { x: Math.random() * 500, y: Math.random() * 500 }, - velocity: { x: (Math.random() - 0.5) * 6, y: (Math.random() - 0.5) * 6 }, - mass: 1, - size: 3, - color: { r: 1, g: 1, b: 1, a: 1 }, - }); -} -``` - -### Bulk set particles - -```ts -engine.setParticles(particlesArray); -``` - -### Use the Spawner utility - -```ts -import { Spawner } from "@cazala/party"; - -const spawner = new Spawner(); -const particles = spawner.initParticles({ - count: 5000, - shape: "text", - text: "Party", - center: { x: 0, y: 0 }, - position: { x: 0, y: 0 }, - align: { horizontal: "center", vertical: "center" }, - textSize: 80, - size: 3, - mass: 1, - colors: ["#ffffff"], -}); - -engine.setParticles(particles); -``` - -### Local queries without full readback (WebGPU-safe) - -```ts -const { particles, truncated } = engine.getParticlesInRadius( - { x: 0, y: 0 }, - 120, - { maxResults: 200 } -); -``` - -### Export + import module settings - -```ts -const settings = engine.export(); -engine.import(settings); -``` - -### Oscillate a module input - -```ts -engine.addOscillator({ - moduleName: "boundary", - inputName: "restitution", - min: 0.4, - max: 0.95, - speedHz: 0.2, -}); -``` - -## Performance notes - -- WebGPU `getParticles()` performs a full GPU → CPU readback; avoid in hot paths. -- Prefer `getParticlesInRadius(...)`, `setParticle(...)`, or `setParticleMass(...)`. -- Tune `cellSize`, `maxNeighbors`, and `constrainIterations` for performance. -- For large scenes, limit processing with `setMaxParticles(value)`. - -## API quick map - -- Engine: `initialize()`, `play()`, `pause()`, `stop()`, `destroy()` -- View: `setSize(w,h)`, `setCamera(x,y)`, `setZoom(z)` -- Particles: `addParticle`, `setParticles`, `setParticle`, `setParticleMass`, `getParticle` -- Queries: `getParticlesInRadius`, `getCount`, `getFPS` -- Modules: `getModule(name)`, module setters, `setEnabled(bool)` -- Serialization: `export()`, `import(settings)` -- Oscillators: `addOscillator`, `removeOscillator`, `clearOscillators` - -## Sources - -- Core library user guide: `docs/user-guide.md` diff --git a/packages/skill/README.md b/packages/skill/README.md deleted file mode 100644 index be12c68..0000000 --- a/packages/skill/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Party Skill - -This package contains the agent skill for the `@cazala/party` library. - -- Entry point: `SKILL.md` -- Quick reference: `REFERENCE.md` - -Install with: - -```bash -npx skills add cazala/party -``` diff --git a/packages/skill/REFERENCE.md b/packages/skill/REFERENCE.md deleted file mode 100644 index 35707c8..0000000 --- a/packages/skill/REFERENCE.md +++ /dev/null @@ -1,89 +0,0 @@ -# Party Reference - -Concise reference for the `@cazala/party` library (engine + modules + particles). - -## Engine setup - -```ts -const engine = new Engine({ - canvas, - forces: [new Environment(), new Boundary(), new Collisions()], - render: [new Trails(), new Particles()], - runtime: "auto", -}); - -await engine.initialize(); -engine.play(); -``` - -## Particle shape - -```ts -{ - position: { x: 0, y: 0 }, - velocity: { x: 0, y: 0 }, - size: 3, - mass: 1, - color: { r: 1, g: 1, b: 1, a: 1 }, -} -``` - -Pinned: `mass < 0` -Removed: `mass === 0` - -## Core API - -Lifecycle: - -- `initialize()`, `play()`, `pause()`, `stop()`, `destroy()` - -View: - -- `getSize()`, `setSize(w,h)`, `setCamera(x,y)`, `setZoom(z)` - -Particles: - -- `addParticle(p)`, `setParticles(p[])`, `setParticle(i,p)` -- `setParticleMass(i,mass)`, `getParticle(i)`, `clear()` - -Queries: - -- `getParticlesInRadius(center, radius, { maxResults })` -- `getCount()`, `getFPS()` - -Modules: - -- `getModule(name)` → module instance -- `module.setEnabled(bool)` + input setters - -Serialization: - -- `export()`, `import(settings)` - -Oscillators: - -- `addOscillator`, `removeOscillator`, `clearOscillators` - -## Force modules - -- `Environment`: gravity + inertia/friction/damping -- `Boundary`: bounce/warp/kill bounds, repel distance/strength -- `Collisions`: elastic-ish particle collisions -- `Behavior`: boids steering (cohesion/alignment/separation) -- `Fluids`: SPH density + pressure/viscosity -- `Sensors`: trail/color sampling steering -- `Interaction`: point attract/repel -- `Joints`: distance constraints -- `Grab`: single-particle dragging - -## Render modules - -- `Particles`: disc rendering, multiple color modes -- `Trails`: decay/diffuse scene texture -- `Lines`: line rendering between particle indices - -## Performance tips - -- WebGPU `getParticles()` is expensive; avoid in hot paths. -- Prefer `getParticlesInRadius`, `setParticle`, `setParticleMass`. -- Tune `cellSize`, `maxNeighbors`, `constrainIterations`, `maxParticles`. diff --git a/packages/skill/SKILL.md b/packages/skill/SKILL.md index 5be65ec..fd82275 100644 --- a/packages/skill/SKILL.md +++ b/packages/skill/SKILL.md @@ -1,189 +1,135 @@ --- name: party -description: "Programmatic guide for the @cazala/party library: engine setup, modules, particles, and performance across CPU + WebGPU." -version: 0.1.0 -license: MIT -tags: [party, particles, physics, webgpu, cpu, simulation, typescript] +description: Build creative particle effects, generative art, interactive physics scenes, and production integrations with @cazala/party across WebGPU and CPU. Use when creating or tuning simulations, composing modules, spawning shape/text/image particles, translating Party playground demos into code, optimizing performance, or authoring custom modules. --- -# Party Skill +# Party -Reusable guidance for using the `@cazala/party` library programmatically: engine setup, runtime selection, particles, modules, and performance constraints across CPU + WebGPU. +Build a visible result first, then tune it. Treat a Party scene as four layers: -## When to use this skill +1. Spawn geometry and initial velocity. +2. One or two primary force modules. +3. Render treatment such as trails, lines, or color. +4. Slow animation of a few meaningful parameters. -- You need to instantiate the Party engine in a custom app (not the playground). -- You want examples for adding particles, configuring modules, or using oscillators. -- You need performance-safe patterns for WebGPU (avoiding full readbacks). +## Start with a working scene -## Quick start (minimal) +Use semantic enums and create particles before calling `play()`: ```ts import { - Engine, - Environment, + Behavior, Boundary, - Collisions, + Engine, Particles, + ParticlesColorType, + Spawner, Trails, } from "@cazala/party"; -const canvas = document.querySelector("canvas")!; +const canvas = document.querySelector("canvas")!; +const width = window.innerWidth; +const height = window.innerHeight; const forces = [ - new Environment({ gravityStrength: 600, gravityDirection: "down" }), - new Boundary({ mode: "bounce", restitution: 0.9, friction: 0.1 }), - new Collisions({ restitution: 0.85 }), + new Boundary({ mode: "warp" }), + new Behavior({ + wander: 18, + cohesion: 1.4, + alignment: 4, + separation: 35, + viewRadius: 80, + }), ]; - const render = [ - new Trails({ trailDecay: 10, trailDiffuse: 4 }), - new Particles({ colorType: 2, hue: 0.55 }), + new Trails({ trailDecay: 8, trailDiffuse: 1 }), + new Particles({ colorType: ParticlesColorType.Hue, hue: 0.62 }), ]; - -const engine = new Engine({ canvas, forces, render, runtime: "auto" }); - -await engine.initialize(); -engine.play(); -``` - -## Core concepts - -### Particle shape - -```ts -type IParticle = { - position: { x: number; y: number }; - velocity: { x: number; y: number }; - size: number; - mass: number; - color: { r: number; g: number; b: number; a: number }; // 0..1 floats -}; -``` - -- Pinned particles: `mass < 0` -- Removed particles: `mass === 0` - -### Runtime selection - -- `"auto"` tries WebGPU first, then falls back to CPU on `initialize()`. -- WebGPU has higher throughput but GPU → CPU readbacks are expensive. - -### Engine lifecycle - -```ts -await engine.initialize(); -engine.play(); // start loop -engine.pause(); // pause loop -engine.stop(); // cancel loop -engine.destroy(); // clean up -``` - -### Module system - -Modules are typed force or render units: - -- **Force**: apply acceleration/velocity changes or constraints. -- **Render**: draw particles/lines or post-process scene texture. - -Each module exposes inputs and helpers, and can be toggled: - -```ts -const boundary = new Boundary(); -boundary.setEnabled(false); -boundary.setRestitution(0.8); -``` - -## Common tasks - -### Add particles - -```ts -for (let i = 0; i < 200; i++) { - engine.addParticle({ - position: { x: Math.random() * 500, y: Math.random() * 500 }, - velocity: { x: (Math.random() - 0.5) * 6, y: (Math.random() - 0.5) * 6 }, - mass: 1, - size: 3, - color: { r: 1, g: 1, b: 1, a: 1 }, - }); -} -``` - -### Bulk set particles - -```ts -engine.setParticles(particlesArray); -``` - -### Use the Spawner utility - -```ts -import { Spawner } from "@cazala/party"; - -const spawner = new Spawner(); -const particles = spawner.initParticles({ - count: 5000, - shape: "text", - text: "Party", +const particles = new Spawner().initParticles({ + count: 4_000, + shape: "donut", center: { x: 0, y: 0 }, - position: { x: 0, y: 0 }, - align: { horizontal: "center", vertical: "center" }, - textSize: 80, - size: 3, + radius: Math.min(width, height) * 0.38, + innerRadius: Math.min(width, height) * 0.12, + size: 2.5, mass: 1, + velocity: { speed: 120, direction: "clockwise" }, colors: ["#ffffff"], }); +const engine = new Engine({ + canvas, + forces, + render, + runtime: "auto", + cellSize: 40, + maxNeighbors: 128, +}); + +await engine.initialize(); +engine.setSize(width, height); engine.setParticles(particles); +engine.addOscillator({ + moduleName: "particles", + inputName: "hue", + min: 0, + max: 1, + speedHz: 0.01, +}); +engine.play(); ``` -### Local queries without full readback (WebGPU-safe) +Copy [the full Vite starter](assets/starter/) when building a new app. It includes responsive sizing, pointer interaction, cleanup, and five selectable scenes. Read its [tested scene source](assets/starter/src/scenes.ts) when adapting a recipe. -```ts -const { particles, truncated } = engine.getParticlesInRadius( - { x: 0, y: 0 }, - 120, - { maxResults: 200 } -); -``` +## Choose modules by visual intent -### Export + import module settings +| Intent | Start with | +| --- | --- | +| Falling, bouncing particles | `Environment` + `Boundary`; add `Collisions` if particles must hit each other | +| Orbital motion | Tangential Spawner velocity + inward `Environment` | +| Swarms and flocking | `Behavior`; add `Trails` for readable motion | +| Slime-mold filaments | `Sensors` + `Trails` + a warp `Boundary` | +| Liquid or viscous blobs | `Fluids` + `Boundary`; add gravity or pointer `Interaction` | +| Pointer fields | `Interaction` for attract/repel or `Grab` for one particle | +| Ropes and structures | `Joints` + `Lines` | +| Text/image dissolves | Text/image `Spawner` + outward velocity + `Trails` or `Behavior` | -```ts -const settings = engine.export(); -engine.import(settings); -``` +Use the smallest combination that expresses the idea. Adding every module usually makes the motion harder to control. -### Oscillate a module input +## Work creatively -```ts -engine.addOscillator({ - moduleName: "boundary", - inputName: "restitution", - min: 0.4, - max: 0.95, - speedHz: 0.2, -}); -``` +1. Define the desired silhouette and motion in one sentence. +2. Select the matching composition above. +3. Start with 2,000–5,000 particles so CPU fallback remains useful. +4. Tune spawn speed and the primary force before adding effects. +5. Add trails or color only after the motion reads clearly. +6. Oscillate one to three inputs slowly; avoid animating everything. +7. Inspect the scene near startup and after several seconds. Fix blank, explosive, static, or visually noisy states before increasing particle count. + +Read [creative-workflow.md](references/creative-workflow.md) for parameter intuition and iteration guidance. Read [recipes.md](references/recipes.md) for five compositions derived from Party playground demos. -## Performance notes +## Preserve runtime performance -- WebGPU `getParticles()` performs a full GPU → CPU readback; avoid in hot paths. -- Prefer `getParticlesInRadius(...)`, `setParticle(...)`, or `setParticleMass(...)`. -- Tune `cellSize`, `maxNeighbors`, and `constrainIterations` for performance. -- For large scenes, limit processing with `setMaxParticles(value)`. +- Use `runtime: "auto"` unless the user requires a specific runtime. +- Treat `getParticles()` as an expensive full WebGPU-to-CPU readback. Never call it in an animation, pointer-move, or drag loop. +- Use `await engine.getParticlesInRadius(...)` for bounded local queries. +- Prefer `setParticle(...)` and `setParticleMass(...)` for local mutations. +- Keep `cellSize` near the largest active neighborhood radius, and cap `maxNeighbors` deliberately. +- Scale particle count after the composition works. Large playground demos are WebGPU showcase budgets, not safe defaults. -## API quick map +## Load the right detail -- Engine: `initialize()`, `play()`, `pause()`, `stop()`, `destroy()` -- View: `setSize(w,h)`, `setCamera(x,y)`, `setZoom(z)` -- Particles: `addParticle`, `setParticles`, `setParticle`, `setParticleMass`, `getParticle` -- Queries: `getParticlesInRadius`, `getCount`, `getFPS` -- Modules: `getModule(name)`, module setters, `setEnabled(bool)` -- Serialization: `export()`, `import(settings)` -- Oscillators: `addOscillator`, `removeOscillator`, `clearOscillators` +- Read [api.md](references/api.md) for particle shape, lifecycle, modules, spawning, interaction, and queries. +- Read [creative-workflow.md](references/creative-workflow.md) before inventing or substantially tuning a visual scene. +- Read [recipes.md](references/recipes.md) when adapting a known effect or playground demo. +- Read [troubleshooting.md](references/troubleshooting.md) when output is blank, unstable, slow, or visually weak. +- Read the repository `docs/module-author-guide.md` only when authoring a new force or render module from a full Party checkout. -## Sources +## Validate the result -- Core library user guide: `docs/user-guide.md` +- Compile the implementation; do not rely on plausible-looking option names. +- Confirm particles are spawned after initialization and the canvas has a non-zero size. +- Exercise CPU fallback with a reduced count when practical. +- Verify pointer coordinates are converted from screen space to Party world space. +- Remove listeners and call `await engine.destroy()` during teardown. +- Visually inspect the running scene. A successful creative task must be coherent and interesting, not merely error-free. diff --git a/packages/skill/agents/claude.md b/packages/skill/agents/claude.md new file mode 100644 index 0000000..0f271d0 --- /dev/null +++ b/packages/skill/agents/claude.md @@ -0,0 +1,25 @@ +--- +name: party +description: Build creative particle art, generative visuals, and interactive physics scenes with the @cazala/party library. Use when creating or tuning simulations, composing modules, spawning shape/text/image particles, translating Party playground demos into code, or optimizing WebGPU/CPU performance. +tools: Read, Write, Edit, Bash, Glob, Grep +--- + +You build creative particle scenes with the `@cazala/party` library. Load the `party` skill and follow its guidance instead of relying on prior knowledge of the API — option names and modules must be verified, not guessed. + +Work in layers, and get a visible result before tuning: + +1. Spawn geometry and initial velocity. +2. One or two primary force modules. +3. Render treatment (trails, lines, color). +4. Slow animation of a few meaningful parameters. + +Defaults that keep scenes usable: + +- Copy `assets/starter/` from the skill when building a new app; adapt `assets/starter/src/scenes.ts` when reworking a recipe. +- Start with 2,000–5,000 particles so the CPU fallback stays useful; scale up only after the composition reads well. +- Use `runtime: "auto"` unless the user requires a specific runtime. +- Never call `getParticles()` in an animation, pointer, or drag loop — it is a full WebGPU-to-CPU readback. Use `getParticlesInRadius(...)` for local queries and `setParticle(...)` for local mutations. +- Convert pointer coordinates from screen space to Party world space. +- Remove listeners and `await engine.destroy()` on teardown. + +Always compile the result and visually inspect the running scene near startup and after several seconds. Fix blank, explosive, static, or visually noisy states before declaring success — a creative task must be coherent and interesting, not merely error-free. diff --git a/packages/skill/agents/openai.yaml b/packages/skill/agents/openai.yaml new file mode 100644 index 0000000..99fa494 --- /dev/null +++ b/packages/skill/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Party" + short_description: "Build creative particle art with Party" + default_prompt: "Use $party to build an interactive particle scene with a clear visual concept and a CPU fallback." diff --git a/packages/skill/assets/starter/.gitignore b/packages/skill/assets/starter/.gitignore new file mode 100644 index 0000000..1eae0cf --- /dev/null +++ b/packages/skill/assets/starter/.gitignore @@ -0,0 +1,2 @@ +dist/ +node_modules/ diff --git a/packages/skill/assets/starter/index.html b/packages/skill/assets/starter/index.html new file mode 100644 index 0000000..7a76a7d --- /dev/null +++ b/packages/skill/assets/starter/index.html @@ -0,0 +1,19 @@ + + + + + + + Party creative starter + + + + + + + diff --git a/packages/skill/assets/starter/package.json b/packages/skill/assets/starter/package.json new file mode 100644 index 0000000..2b18ce8 --- /dev/null +++ b/packages/skill/assets/starter/package.json @@ -0,0 +1,18 @@ +{ + "name": "party-creative-starter", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build" + }, + "dependencies": { + "@cazala/party": "^0.1.0" + }, + "devDependencies": { + "@webgpu/types": "^0.1.64", + "typescript": "^5.0.0", + "vite": "^5.4.0" + } +} diff --git a/packages/skill/assets/starter/src/main.ts b/packages/skill/assets/starter/src/main.ts new file mode 100644 index 0000000..5278035 --- /dev/null +++ b/packages/skill/assets/starter/src/main.ts @@ -0,0 +1,106 @@ +import "./style.css"; +import { Engine } from "@cazala/party"; +import { sceneFactories, sceneNames, type SceneName } from "./scenes"; + +function requiredElement(selector: string): T { + const element = document.querySelector(selector); + if (!element) throw new Error(`Missing required element: ${selector}`); + return element; +} + +const canvas = requiredElement("#party"); +const title = requiredElement("#scene-title"); +const status = requiredElement("#status"); +const links = requiredElement("#scene-links"); + +const requestedScene = new URLSearchParams(window.location.search).get("scene"); +const sceneName: SceneName = sceneNames.includes(requestedScene as SceneName) + ? (requestedScene as SceneName) + : "vortex"; + +for (const name of sceneNames) { + const link = document.createElement("a"); + link.href = `?scene=${name}`; + link.textContent = name; + if (name === sceneName) link.setAttribute("aria-current", "page"); + links.append(link); +} + +const viewport = { width: window.innerWidth, height: window.innerHeight }; +const scene = sceneFactories[sceneName](viewport); +title.textContent = scene.title; + +const engine = new Engine({ + canvas, + forces: scene.forces, + render: scene.render, + runtime: "auto", + ...scene.engine, +}); + +function resize(): void { + engine.setSize(window.innerWidth, window.innerHeight); +} + +function screenToWorld(event: PointerEvent): { x: number; y: number } { + const rect = canvas.getBoundingClientRect(); + const screenX = event.clientX - rect.left; + const screenY = event.clientY - rect.top; + const camera = engine.getCamera(); + const zoom = engine.getZoom(); + return { + x: camera.x + (screenX - rect.width / 2) / zoom, + y: camera.y + (screenY - rect.height / 2) / zoom, + }; +} + +function moveInteraction(event: PointerEvent): void { + if (!scene.interaction) return; + const world = screenToWorld(event); + scene.interaction.setPosition(world.x, world.y); +} + +function activateInteraction(event: PointerEvent): void { + moveInteraction(event); + scene.interaction?.setActive(true); + canvas.setPointerCapture(event.pointerId); +} + +function deactivateInteraction(event: PointerEvent): void { + scene.interaction?.setActive(false); + if (canvas.hasPointerCapture(event.pointerId)) { + canvas.releasePointerCapture(event.pointerId); + } +} + +async function start(): Promise { + await engine.initialize(); + resize(); + engine.setParticles(scene.particles); + for (const oscillator of scene.oscillators ?? []) { + engine.addOscillator(oscillator); + } + engine.play(); + status.textContent = `${engine.getActualRuntime().toUpperCase()} · ${scene.particles.length.toLocaleString()} particles`; + + window.addEventListener("resize", resize); + canvas.addEventListener("pointermove", moveInteraction); + canvas.addEventListener("pointerdown", activateInteraction); + canvas.addEventListener("pointerup", deactivateInteraction); + canvas.addEventListener("pointercancel", deactivateInteraction); + + window.addEventListener( + "beforeunload", + () => { + window.removeEventListener("resize", resize); + void engine.destroy(); + }, + { once: true } + ); +} + +void start().catch((error: unknown) => { + status.textContent = + error instanceof Error ? error.message : "Could not start Party"; + console.error(error); +}); diff --git a/packages/skill/assets/starter/src/scenes.ts b/packages/skill/assets/starter/src/scenes.ts new file mode 100644 index 0000000..91f2708 --- /dev/null +++ b/packages/skill/assets/starter/src/scenes.ts @@ -0,0 +1,332 @@ +import { + Behavior, + Boundary, + Collisions, + Environment, + Fluids, + FluidsMethod, + Interaction, + type IParticle, + type Module, + Particles, + ParticlesColorType, + Sensors, + Spawner, + Trails, + type EngineOptions, +} from "@cazala/party"; + +export type SceneName = "vortex" | "slime" | "ink" | "liquid" | "text"; + +export type OscillatorSpec = { + moduleName: string; + inputName: string; + min: number; + max: number; + speedHz: number; +}; + +export type Scene = { + title: string; + forces: Array>; + render: Array>; + particles: IParticle[]; + interaction?: Interaction; + oscillators?: OscillatorSpec[]; + engine?: Partial< + Pick< + EngineOptions, + | "cellSize" + | "clearColor" + | "constrainIterations" + | "maxNeighbors" + | "maxParticles" + > + >; +}; + +type Viewport = { width: number; height: number }; +type SceneFactory = (viewport: Viewport) => Scene; + +const spawner = new Spawner(); + +function safeExtent({ width, height }: Viewport): number { + return Math.max(320, Math.min(width, height)); +} + +function createVortex(viewport: Viewport): Scene { + const extent = safeExtent(viewport); + const interaction = new Interaction({ + mode: "attract", + strength: 6_000, + radius: extent * 0.25, + }); + + return { + title: "Neon vortex", + forces: [ + new Environment({ + gravityStrength: 750, + gravityDirection: "inwards", + }), + new Boundary({ mode: "warp" }), + new Behavior({ + wander: 12, + cohesion: 1.5, + alignment: 4.8, + repulsion: 3, + separation: 42, + viewRadius: 90, + viewAngle: Math.PI * 2, + }), + interaction, + ], + render: [ + new Trails({ trailDecay: 8, trailDiffuse: 1 }), + new Particles({ colorType: ParticlesColorType.Hue, hue: 0.62 }), + ], + particles: spawner.initParticles({ + count: 5_000, + shape: "donut", + center: { x: 0, y: 0 }, + radius: extent * 0.42, + innerRadius: extent * 0.12, + size: 2.5, + mass: 1, + velocity: { speed: 150, direction: "clockwise" }, + colors: ["#ffffff"], + }), + interaction, + oscillators: [ + { + moduleName: "particles", + inputName: "hue", + min: 0, + max: 1, + speedHz: 0.01, + }, + ], + engine: { cellSize: 48, maxNeighbors: 128 }, + }; +} + +function createSlime(viewport: Viewport): Scene { + const extent = safeExtent(viewport); + const sensors = new Sensors({ + sensorDistance: 20, + sensorAngle: Math.PI / 4.5, + sensorRadius: 3, + sensorThreshold: 0.02, + sensorStrength: 2_200, + followBehavior: "any", + fleeBehavior: "none", + }); + const interaction = new Interaction({ + mode: "repel", + strength: 5_000, + radius: extent * 0.2, + }); + + return { + title: "Slime filaments", + forces: [new Boundary({ mode: "warp" }), sensors, interaction], + render: [ + new Trails({ trailDecay: 9, trailDiffuse: 0 }), + new Particles({ colorType: ParticlesColorType.Hue, hue: 0.08 }), + ], + particles: spawner.initParticles({ + count: 6_000, + shape: "random", + center: { x: 0, y: 0 }, + bounds: { + width: Math.max(480, viewport.width * 0.9), + height: Math.max(320, viewport.height * 0.9), + }, + size: 2.25, + mass: 1, + velocity: { speed: 135, direction: "random" }, + colors: ["#ffffff"], + }), + interaction, + oscillators: [ + { + moduleName: "particles", + inputName: "hue", + min: 0, + max: 1, + speedHz: 0.008, + }, + { + moduleName: "sensors", + inputName: "sensorDistance", + min: 18, + max: 70, + speedHz: 0.012, + }, + { + moduleName: "sensors", + inputName: "sensorAngle", + min: 0.3, + max: 0.8, + speedHz: 0.009, + }, + ], + engine: { cellSize: 40, maxNeighbors: 96 }, + }; +} + +function createInk(viewport: Viewport): Scene { + const extent = safeExtent(viewport); + const interaction = new Interaction({ + mode: "attract", + strength: 4_000, + radius: extent * 0.22, + }); + + return { + title: "Viscous ink", + forces: [ + new Boundary({ mode: "bounce", restitution: 0, friction: 1 }), + new Collisions({ restitution: 0.25 }), + new Fluids({ + method: FluidsMethod.Sph, + influenceRadius: 58, + targetDensity: 0.8, + pressureMultiplier: 70, + viscosity: 7.5, + nearPressureMultiplier: 20, + nearThreshold: 30, + enableNearPressure: true, + maxAcceleration: 45, + }), + interaction, + ], + render: [ + new Particles({ + colorType: ParticlesColorType.Custom, + customColor: { r: 0.035, g: 0.04, b: 0.065, a: 1 }, + }), + ], + particles: spawner.initParticles({ + count: 4_500, + shape: "random", + center: { x: 0, y: -extent * 0.08 }, + bounds: { width: extent * 0.55, height: extent * 0.48 }, + size: 3, + mass: 0.3, + velocity: { speed: 35, direction: "out" }, + colors: ["#11131f"], + }), + interaction, + engine: { + cellSize: 58, + maxNeighbors: 192, + clearColor: { r: 0.95, g: 0.945, b: 0.91, a: 1 }, + }, + }; +} + +function createLiquid(viewport: Viewport): Scene { + const extent = safeExtent(viewport); + const interaction = new Interaction({ + mode: "repel", + strength: 7_000, + radius: extent * 0.2, + }); + + return { + title: "PIC/FLIP liquid", + forces: [ + new Environment({ + gravityStrength: 420, + gravityDirection: "down", + damping: 0.01, + }), + new Boundary({ mode: "bounce", restitution: 0.25, friction: 0.08 }), + new Fluids({ + method: FluidsMethod.Picflip, + influenceRadius: 44, + targetDensity: 2, + pressureMultiplier: 420, + flipRatio: 0.2, + }), + interaction, + ], + render: [ + new Trails({ trailDecay: 18, trailDiffuse: 1 }), + new Particles({ colorType: ParticlesColorType.Hue, hue: 0.54 }), + ], + particles: spawner.initParticles({ + count: 5_000, + shape: "grid", + center: { x: 0, y: -extent * 0.16 }, + spacing: 7, + size: 3, + mass: 1, + velocity: { speed: 0, direction: "random" }, + colors: ["#ffffff"], + }), + interaction, + oscillators: [ + { + moduleName: "particles", + inputName: "hue", + min: 0.48, + max: 0.72, + speedHz: 0.015, + }, + ], + engine: { + cellSize: 44, + maxNeighbors: 256, + constrainIterations: 8, + }, + }; +} + +function createText(viewport: Viewport): Scene { + const extent = safeExtent(viewport); + const interaction = new Interaction({ + mode: "repel", + strength: 8_000, + radius: extent * 0.22, + }); + + return { + title: "Living word", + forces: [ + new Boundary({ mode: "warp" }), + interaction, + ], + render: [ + new Trails({ trailDecay: 12, trailDiffuse: 1 }), + new Particles({ colorType: ParticlesColorType.Default }), + ], + particles: spawner.initParticles({ + count: 12_000, + shape: "text", + text: "PARTY", + font: "sans-serif", + textSize: Math.min(viewport.width * 0.18, 180), + center: { x: 0, y: 0 }, + position: { x: 0, y: 0 }, + align: { horizontal: "center", vertical: "center" }, + size: 3, + mass: 1, + velocity: { speed: 0, direction: "out" }, + colors: ["#f7f7ff", "#8be9fd", "#bd93f9"], + }), + interaction, + engine: { cellSize: 40, maxNeighbors: 64 }, + }; +} + +export const sceneFactories: Record = { + vortex: createVortex, + slime: createSlime, + ink: createInk, + liquid: createLiquid, + text: createText, +}; + +export const sceneNames = Object.keys(sceneFactories) as SceneName[]; diff --git a/packages/skill/assets/starter/src/style.css b/packages/skill/assets/starter/src/style.css new file mode 100644 index 0000000..7e3985a --- /dev/null +++ b/packages/skill/assets/starter/src/style.css @@ -0,0 +1,75 @@ +:root { + color-scheme: dark; + font-family: Inter, ui-sans-serif, system-ui, sans-serif; + background: #07070b; +} + +* { + box-sizing: border-box; +} + +html, +body, +#party { + width: 100%; + height: 100%; + margin: 0; +} + +body { + overflow: hidden; +} + +#party { + display: block; + touch-action: none; +} + +.hud { + position: fixed; + top: 1rem; + left: 1rem; + display: grid; + max-width: min(32rem, calc(100vw - 2rem)); + gap: 0.45rem; + padding: 0.8rem 0.9rem; + border: 1px solid rgb(255 255 255 / 12%); + border-radius: 0.8rem; + background: rgb(7 7 11 / 72%); + box-shadow: 0 0.5rem 2rem rgb(0 0 0 / 22%); + backdrop-filter: blur(12px); + pointer-events: none; +} + +.hud strong { + font-size: 0.95rem; +} + +.hud span, +.hud small { + color: rgb(255 255 255 / 62%); + font-size: 0.72rem; +} + +.hud nav { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + pointer-events: auto; +} + +.hud a { + padding: 0.24rem 0.48rem; + border: 1px solid rgb(255 255 255 / 14%); + border-radius: 999px; + color: rgb(255 255 255 / 68%); + font-size: 0.7rem; + text-decoration: none; +} + +.hud a[aria-current="page"], +.hud a:hover { + color: white; + border-color: rgb(255 255 255 / 40%); + background: rgb(255 255 255 / 10%); +} diff --git a/packages/skill/assets/starter/tsconfig.json b/packages/skill/assets/starter/tsconfig.json new file mode 100644 index 0000000..7378416 --- /dev/null +++ b/packages/skill/assets/starter/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["@webgpu/types"], + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/packages/skill/package.json b/packages/skill/package.json index 1ff2e4f..40c078c 100644 --- a/packages/skill/package.json +++ b/packages/skill/package.json @@ -4,9 +4,21 @@ "description": "Agent skill for the `@cazala/party` library", "private": true, "type": "module", + "scripts": { + "check": "node scripts/validate.mjs && npm run check:starter", + "check:starter": "tsc --noEmit -p assets/starter/tsconfig.json && vite build assets/starter" + }, "files": [ "SKILL.md", - "REFERENCE.md", - "README.md" - ] + "agents", + "assets", + "references", + "scripts" + ], + "devDependencies": { + "@cazala/party": "workspace:*", + "@webgpu/types": "^0.1.64", + "typescript": "^5.0.0", + "vite": "^5.4.0" + } } diff --git a/packages/skill/references/api.md b/packages/skill/references/api.md new file mode 100644 index 0000000..2411b7e --- /dev/null +++ b/packages/skill/references/api.md @@ -0,0 +1,145 @@ +# Party API reference + +Use this reference for application code. Consult the repository guides when authoring custom modules or changing Party internals. + +## Particle shape + +```ts +type IParticle = { + position: { x: number; y: number }; + velocity: { x: number; y: number }; + size: number; + mass: number; + color: { r: number; g: number; b: number; a: number }; +}; +``` + +Color channels are floats from `0` through `1`. A particle with `mass < 0` is pinned; `mass === 0` marks it as removed. + +## Engine lifecycle + +```ts +const engine = new Engine({ + canvas, + forces, + render, + runtime: "auto", + constrainIterations: 1, + cellSize: 40, + maxNeighbors: 128, + maxParticles: 10_000, + clearColor: { r: 0, g: 0, b: 0, a: 1 }, +}); + +await engine.initialize(); +engine.setSize(width, height); +engine.setParticles(particles); +engine.play(); + +engine.pause(); +engine.stop(); +await engine.destroy(); +``` + +`runtime: "auto"` attempts WebGPU and falls back to CPU during `initialize()`. Inspect the selected runtime with `engine.getActualRuntime()`. + +## View and coordinates + +- `getSize()` / `setSize(width, height)` +- `getCamera()` / `setCamera(x, y)` +- `getZoom()` / `setZoom(zoom)` +- `getClearColor()` / `setClearColor(color)` + +The camera is the world coordinate at the canvas center. Convert a pointer from canvas coordinates to world coordinates with: + +```ts +const camera = engine.getCamera(); +const zoom = engine.getZoom(); +const world = { + x: camera.x + (screenX - canvas.clientWidth / 2) / zoom, + y: camera.y + (screenY - canvas.clientHeight / 2) / zoom, +}; +``` + +## Spawner + +`new Spawner().initParticles(options)` returns `IParticle[]`. + +- Shapes: `grid`, `random`, `circle`, `donut`, `square`, `text`, `image` +- Velocity directions: `random`, `in`, `out`, `clockwise`, `counter-clockwise`, `custom` +- Shared options: `count`, `center`, `size`, `mass`, `colors`, `velocity` +- Shape options: `spacing`, `bounds`, `radius`, `innerRadius`, `squareSize`, `cornerRadius` +- Text options: `text`, `font`, `textSize`, `position`, `align` +- Image options: `imageData`, `imageSize`, `position`, `align` + +Text and image spawning require browser canvas APIs. Image spawning accepts decoded `ImageData`, not a URL. + +## Particle operations + +- `setParticles(particles)` replaces the complete collection efficiently. +- `addParticle(particle)` returns its index. +- `setParticle(index, particle)` updates one particle. +- `setParticleMass(index, mass)` pins, unpins, or removes without replacing everything. +- `clear()` removes all particles. +- `getCount()` and `getFPS()` are synchronous metrics. +- `getParticle(index)` and `getParticles()` are asynchronous. + +Use bounded queries instead of full readback in interactive code: + +```ts +const { particles, truncated } = await engine.getParticlesInRadius( + { x: 0, y: 0 }, + 120, + { maxResults: 200 } +); +``` + +## Force modules + +- `Environment`: directional, inward, or outward gravity; inertia, friction, damping. +- `Boundary`: `bounce`, `warp`, `kill`, or `none`; optional edge repulsion. +- `Collisions`: particle collision restitution. +- `Behavior`: wander, cohesion, alignment, repulsion, chase, avoid, separation. +- `Fluids`: `FluidsMethod.Sph` for particle-neighborhood fluid forces or `FluidsMethod.Picflip` for a PIC/FLIP-style velocity update. +- `Sensors`: sample rendered trails/colors ahead of particles and steer toward or away from them. +- `Interaction`: pointer-position attract or repel field. +- `Joints`: distance constraints between indexed particles. +- `Grab`: drag one indexed particle. + +## Render modules + +- `Particles`: particle discs. Use `ParticlesColorType.Default`, `.Custom`, or `.Hue`. +- `Trails`: persistent scene texture controlled by `trailDecay` and `trailDiffuse`. +- `Lines`: render line segments between indexed particles, usually with `Joints`. + +Create module instances once, keep references to modules that need live updates, and use their setters: + +```ts +const interaction = new Interaction({ mode: "repel", radius: 220 }); +interaction.setPosition(world.x, world.y); +interaction.setActive(true); +``` + +## Oscillators + +Oscillators animate numeric module inputs without rebuilding modules: + +```ts +engine.addOscillator({ + moduleName: "particles", + inputName: "hue", + min: 0, + max: 1, + speedHz: 0.01, +}); +``` + +Use `removeOscillator(moduleName, inputName)`, `clearModuleOscillators(name)`, or `clearOscillators()` to remove them. + +## Serialization and configuration + +- `engine.export()` / `engine.import(settings)` serialize module input settings. +- `setCellSize(value)` tunes the spatial grid. +- `setMaxNeighbors(value)` caps local neighbor work. +- `setConstrainIterations(value)` tunes constraint passes. +- `setMaxParticles(value | null)` caps simulation size. diff --git a/packages/skill/references/creative-workflow.md b/packages/skill/references/creative-workflow.md new file mode 100644 index 0000000..7df0c28 --- /dev/null +++ b/packages/skill/references/creative-workflow.md @@ -0,0 +1,88 @@ +# Creative workflow + +Use this process when a request describes a mood or effect instead of specific Party modules. + +## 1. Write a visual sentence + +Translate the request into a concrete sentence containing: + +- silhouette: ring, cloud, grid, text, image, stream, blob; +- motion: orbit, fall, flock, spread, follow trails, flow; +- surface: crisp particles, glowing trails, connected lines, liquid mass; +- interaction: none, pointer attract, pointer repel, drag; +- mood: palette, speed, density, persistence. + +Example: “A sparse cyan cloud leaves branching filaments while slowly avoiding the pointer.” + +## 2. Choose spawn geometry first + +Initial conditions strongly determine the result. + +- `random` + random velocity creates an even field for sensors and flocking. +- `donut` + clockwise velocity creates orbital motion immediately. +- `grid` + zero velocity gives fluids and constraints an orderly starting state. +- `text` or `image` + zero velocity preserves a readable silhouette. +- `text` or `image` + outward velocity creates an immediate dissolve. +- `circle` or `square` works well for rings, cages, and joint structures. + +Keep the spawn center near the camera, normally `{ x: 0, y: 0 }`. + +## 3. Select a primary motion system + +Prefer one dominant system, occasionally two: + +- Ballistics: `Environment`, `Boundary`, optional `Collisions`. +- Orbital field: tangential velocity plus inward `Environment`. +- Flocking: `Behavior`; begin with wander, alignment, and separation. +- Trail following: `Sensors` plus `Trails`. Sensors need rendered history to follow. +- Fluid: one `Fluids` method plus a boundary and optionally gravity. +- Structure: `Joints`; use `Lines` to expose the structure visually. + +If motion explodes, reduce force strength or spawn speed before adding damping. If it collapses into a static clump, increase separation, reduce cohesion, or introduce wander. + +## 4. Add visual treatment + +- Use `ParticlesColorType.Hue` when a single animated hue fits the concept. +- Use `ParticlesColorType.Default` to preserve colors from an image or palette Spawner. +- Use `ParticlesColorType.Custom` for a single designed color. +- Add `Trails` when direction and history matter. Higher decay removes history faster; diffusion softens it. +- Add `Lines` only when topology matters. Dense all-to-all lines obscure the particles. +- Design the clear color and particle colors together; contrast is part of the simulation. + +## 5. Add restrained animation + +Oscillate one to three parameters with low frequencies, usually `0.005–0.05 Hz` for ambient evolution. + +Good candidates: + +- `particles.hue` for color drift; +- `sensors.sensorDistance` or `sensorAngle` for changing trail topology; +- `behavior.cohesion`, `alignment`, or `separation` for breathing swarms; +- `boundary.repelStrength` for a pulsing container. + +Avoid oscillating fluid stability parameters until the base fluid is stable. + +## 6. Budget performance intentionally + +- Begin around 2,000–5,000 particles when CPU fallback matters. +- Increase to tens of thousands only after testing WebGPU and accepting a weaker CPU experience. +- Keep `cellSize` close to the largest active neighborhood radius. +- Lower `maxNeighbors` until the scene changes visibly, then restore some margin. +- Sensors and trails add render work; fluids, collisions, and behavior add neighborhood work. +- Never use `getParticles()` per frame or during pointer movement. + +## 7. Iterate visually + +Inspect at least three states: + +1. Startup: particles should be visible and composed inside the view. +2. Early motion: the main gesture should be legible within a few seconds. +3. Settled motion: the scene should not collapse, escape, saturate the canvas, or become static unintentionally. + +Change one layer at a time: spawn, force, render, then animation. Record parameter combinations that produce a distinct effect as a reusable scene factory. + +## 8. Add interaction safely + +Convert pointer positions into world coordinates. Keep a reference to `Interaction` and update its uniforms directly. Do not query all particles to implement an attractor. + +Activate on pointer press for a deliberate tool, or keep it active during pointer movement for an ambient field. Always handle pointer leave/up so forces do not remain stuck on. diff --git a/packages/skill/references/recipes.md b/packages/skill/references/recipes.md new file mode 100644 index 0000000..a219e66 --- /dev/null +++ b/packages/skill/references/recipes.md @@ -0,0 +1,158 @@ +# Creative recipes + +These recipes distill Party playground demos into smaller starting points suitable for generated apps and CPU fallback. Copy the complete, tested implementations from `assets/starter/src/scenes.ts`, then tune one layer at a time. + +## Recipe index + +| Recipe | Spawn | Primary motion | Visual signature | +| --- | --- | --- | --- | +| Neon vortex | Donut, clockwise | Inward gravity + flocking | Persistent hue-shifting trails | +| Slime filaments | Random field | Trail-sampling sensors | Branching self-following paths | +| Viscous ink | Dense random cloud | SPH + collisions | Dark cohesive blob on a light field | +| PIC/FLIP liquid | Compact grid | PIC/FLIP + gravity | Splashing colored sheet | +| Living word | Text | Pointer repulsion | Readable type that disperses under the pointer | + +The original playground demos use tens of thousands of particles and wide camera views. These versions deliberately use smaller counts and viewport-relative dimensions. + +## Neon vortex + +Use a donut spawn with tangential velocity so the composition is visible before forces settle. Add inward gravity to retain the ring and moderate flocking to create coherent strands. + +```ts +const forces = [ + new Environment({ gravityStrength: 750, gravityDirection: "inwards" }), + new Boundary({ mode: "warp" }), + new Behavior({ + wander: 12, + cohesion: 1.5, + alignment: 4.8, + repulsion: 3, + separation: 42, + viewRadius: 90, + viewAngle: Math.PI * 2, + }), +]; + +const particles = new Spawner().initParticles({ + count: 5_000, + shape: "donut", + center: { x: 0, y: 0 }, + radius: Math.min(width, height) * 0.42, + innerRadius: Math.min(width, height) * 0.12, + velocity: { speed: 150, direction: "clockwise" }, + size: 2.5, + mass: 1, +}); +``` + +Render with `Trails({ trailDecay: 8, trailDiffuse: 1 })` and hue particles. Oscillate `particles.hue` from `0` to `1` at about `0.01 Hz`. If the ring collapses, reduce inward gravity; if it becomes a uniform band, increase wander or separation slightly. + +## Slime filaments + +Sensors sample the scene texture ahead of each particle. With trails enabled, particles create the field they subsequently follow, producing branching paths. + +```ts +const sensors = new Sensors({ + sensorDistance: 20, + sensorAngle: Math.PI / 4.5, + sensorRadius: 3, + sensorThreshold: 0.02, + sensorStrength: 2_200, + followBehavior: "any", + fleeBehavior: "none", +}); + +const forces = [new Boundary({ mode: "warp" }), sensors]; +const render = [ + new Trails({ trailDecay: 9, trailDiffuse: 0 }), + new Particles({ colorType: ParticlesColorType.Hue, hue: 0.08 }), +]; +``` + +Spawn a random field with random velocity around `100–160`. Slowly oscillate `sensorDistance` between roughly `18` and `70`, `sensorAngle` between `0.3` and `0.8` radians, and hue. If the screen becomes solid, increase trail decay or reduce count. If paths do not form, confirm Trails renders before Particles and lower the sensor threshold. + +## Viscous ink + +Use SPH for local density/viscosity and collisions for a heavy, cohesive mass. A light clear color and dark particles create an ink-like graphic without a CSS inversion filter. + +```ts +const forces = [ + new Boundary({ mode: "bounce", restitution: 0, friction: 1 }), + new Collisions({ restitution: 0.25 }), + new Fluids({ + method: FluidsMethod.Sph, + influenceRadius: 58, + targetDensity: 0.8, + pressureMultiplier: 70, + viscosity: 7.5, + nearPressureMultiplier: 20, + nearThreshold: 30, + enableNearPressure: true, + maxAcceleration: 45, + }), +]; +``` + +Spawn a compact random cloud with low outward velocity, particle size around `3`, and mass around `0.3`. Use a `cellSize` close to the influence radius and raise `maxNeighbors` only as needed. Fluids are sensitive to density and scale; tune count, bounds, mass, radius, and target density together. + +## PIC/FLIP liquid + +Begin with a compact grid so density is predictable. Use a bounce boundary and downward gravity, then stir it with pointer interaction. + +```ts +const interaction = new Interaction({ + mode: "repel", + strength: 7_000, + radius: 180, +}); + +const forces = [ + new Environment({ gravityStrength: 420, gravityDirection: "down" }), + new Boundary({ mode: "bounce", restitution: 0.25, friction: 0.08 }), + new Fluids({ + method: FluidsMethod.Picflip, + influenceRadius: 44, + targetDensity: 2, + pressureMultiplier: 420, + flipRatio: 0.2, + }), + interaction, +]; +``` + +Spawn a grid with spacing around `7`, zero velocity, and 4,000–6,000 particles. Lower `flipRatio` for smoother PIC-like motion; raise it for more energetic FLIP-like motion. Do not pass SPH-only settings such as viscosity or near pressure to a PIC/FLIP constructor. + +## Living word + +Text spawning turns Canvas2D glyph pixels into particles. Keep the initial speed at zero so the word remains readable, then use pointer repulsion to make it disperse on demand. + +```ts +const particles = new Spawner().initParticles({ + count: 12_000, + shape: "text", + text: "PARTY", + font: "sans-serif", + textSize: Math.min(width * 0.18, 180), + center: { x: 0, y: 0 }, + position: { x: 0, y: 0 }, + align: { horizontal: "center", vertical: "center" }, + velocity: { speed: 0, direction: "out" }, + size: 3, + mass: 1, + colors: ["#f7f7ff", "#8be9fd", "#bd93f9"], +}); +``` + +Use a warp `Boundary`, Trails, and a repel `Interaction`. Text sampling may return fewer particles than requested because the count is capped by sampled glyph pixels. Keep zero initial velocity and let interaction provide the dramatic motion. + +## Adapting a recipe + +Change in this order: + +1. Scale spawn dimensions to the target viewport. +2. Establish the desired speed and containment. +3. Tune the primary force system. +4. Choose the palette and trail persistence. +5. Add pointer interaction. +6. Add no more than three slow oscillators. +7. Increase particle count only after testing both the selected runtime and fallback behavior. diff --git a/packages/skill/references/troubleshooting.md b/packages/skill/references/troubleshooting.md new file mode 100644 index 0000000..fffa0b0 --- /dev/null +++ b/packages/skill/references/troubleshooting.md @@ -0,0 +1,67 @@ +# Troubleshooting + +## Blank canvas + +- Ensure the canvas has visible CSS dimensions. +- Call `await engine.initialize()` before setting particles and playing. +- Call `engine.setSize(width, height)` with non-zero values. +- Verify `Spawner.initParticles(...)` returned a non-empty array. +- Include an enabled `Particles` render module. +- Spawn near the camera, normally around `{ x: 0, y: 0 }`. +- Use contrasting particle and clear colors. +- Check the browser console for WebGPU initialization errors; `runtime: "auto"` should fall back to CPU. + +## Static or weak motion + +- Give particles initial velocity or enable a force with non-zero strength. +- Confirm each relevant module is enabled. +- Increase the primary force gradually; do not compensate by enabling unrelated modules. +- For Sensors, enable Trails because sensors sample rendered history. +- For Interaction, update its position and call `setActive(true)`. + +## Explosive or unstable motion + +- Reduce spawn speed, gravity, sensor strength, pressure, or behavior gains. +- Avoid dense overlapping initial particles for collisions and SPH. +- Increase damping modestly instead of using extreme values. +- Ensure fluid parameters match the selected method; SPH-only options do not belong to PIC/FLIP. +- Increase constraint iterations only for constraint quality, not as a universal stability fix. + +## Scene disappears over time + +- Check for `Boundary({ mode: "kill" })` or `mode: "none"`. +- Use `warp` for continuous fields and `bounce` for containers. +- Reduce outward force or set a wider world/camera zoom. +- Remember that `mass === 0` marks a particle removed. + +## Poor performance + +- Reduce particle count first. +- Avoid `getParticles()` in recurring code; it triggers full WebGPU readback. +- Bound local queries with `getParticlesInRadius(..., { maxResults })` and await them. +- Reduce `maxNeighbors`, neighborhood radius, fluid complexity, or constraint iterations. +- Avoid combining collisions, fluids, behavior, and sensors unless each contributes visibly. +- Test CPU fallback independently; a WebGPU showcase budget may be unsuitable for CPU. + +## Pointer force is offset + +Use the canvas bounding rectangle, then convert canvas pixels to world coordinates using the camera and zoom. Do not pass viewport `clientX/clientY` directly to a module. + +## Text or image spawning returns no particles + +- Run in a browser environment with Canvas2D or `OffscreenCanvas` support. +- Use non-empty text and a positive `textSize`. +- Decode images and pass `ImageData`; a URL string is not accepted by `Spawner`. +- Use a particle size small enough to sample the source silhouette. + +## TypeScript rejects an option + +Use exported enums such as `ParticlesColorType` and `FluidsMethod`. Check the constructor in the installed package version instead of guessing names from playground labels. PIC/FLIP intentionally rejects SPH-only options at the type level. + +## Output runs but is visually uninteresting + +- Restate the intended silhouette, motion, surface, and interaction. +- Replace generic random particles with a deliberate shape and velocity. +- Remove modules until the primary motion reads clearly. +- Add one visual signature: trails, a controlled palette, lines, or a slow oscillator. +- Inspect the result after several seconds; creative success requires composition and evolution, not only valid code. diff --git a/packages/skill/scripts/validate.mjs b/packages/skill/scripts/validate.mjs new file mode 100644 index 0000000..e71a178 --- /dev/null +++ b/packages/skill/scripts/validate.mjs @@ -0,0 +1,54 @@ +import { access, readFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const skillDir = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const skillPath = resolve(skillDir, "SKILL.md"); +const skill = await readFile(skillPath, "utf8"); +const match = skill.match(/^---\n([\s\S]*?)\n---\n/); + +if (!match) throw new Error("SKILL.md must start with YAML frontmatter"); + +const keys = match[1] + .split("\n") + .filter((line) => /^[a-z][a-z0-9_-]*:/.test(line)) + .map((line) => line.slice(0, line.indexOf(":"))); + +if (keys.join(",") !== "name,description") { + throw new Error("SKILL.md frontmatter must contain only name and description"); +} + +if (!/^name: party$/m.test(match[1])) { + throw new Error("Skill name must be party"); +} + +const localLinks = [...skill.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)] + .map((result) => result[1]) + .filter((link) => !link.includes(":") && !link.startsWith("#")); + +await Promise.all(localLinks.map((link) => access(resolve(skillDir, link)))); + +const repoPackagePath = resolve(skillDir, "../..", "package.json"); +try { + const repoPackage = JSON.parse(await readFile(repoPackagePath, "utf8")); + if (repoPackage.name === "party") { + try { + await access(resolve(skillDir, "../..", "SKILL.md")); + throw new Error( + "Keep one canonical skill: remove the duplicate repository-root SKILL.md" + ); + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "ENOENT") { + // Expected: packages/skill is the only entry point. + } else { + throw error; + } + } + } +} catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) { + throw error; + } +} + +console.log(`Validated Party skill (${localLinks.length} local links)`); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 88e7b69..4aa3c24 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -85,7 +85,20 @@ importers: specifier: ^7.3.1 version: 7.3.1 - packages/skill: {} + packages/skill: + devDependencies: + '@cazala/party': + specifier: workspace:* + version: link:../core + '@webgpu/types': + specifier: ^0.1.64 + version: 0.1.66 + typescript: + specifier: ^5.0.0 + version: 5.9.3 + vite: + specifier: ^5.4.0 + version: 5.4.21 packages/worker: devDependencies: