API 参考取自源码中的 Go 文档注释,以英文书写。
package particles
import "github.com/nsgo-dev/game/pkg/particles"概述
Package particles provides a deterministic 2D particle emitter stepped by game.Loop and drawn through sprite.Batch.
索引
- 常量
- func MarshalConfig3DJSON(cfg Emitter3DConfig) ([]byte, error)
- func MarshalConfig3DYAML(cfg Emitter3DConfig) ([]byte, error)
- func MarshalConfigJSON(cfg Config) ([]byte, error)
- func MarshalConfigYAML(cfg Config) ([]byte, error)
- func NewParticlePipeline(cx *core.Scope, dev *gpu.Device, opts ParticlePipelineOptions) (*gpu.Pipeline, error)
- func ParticleVertexLayouts() []gpu.VertexBufferLayout
- func SaveConfig3DFile(path string, cfg Emitter3DConfig) error
- func SaveConfigFile(path string, cfg Config) error
- type BillboardMode3D
- type Burst
- type BurstDoc
- type CircleCollider
- type Collider
- type CollisionConfig
- type CollisionDoc
- type CollisionMode
- type ColorCurve
- type ColorStop
- type ColorStopDoc
- type Config
- type Curve
- type Emitter
- func NewEmitter(cfg Config) *Emitter
- func (e *Emitter) Attach(posFn func() (float32, float32))
- func (e *Emitter) AttachTrail(cfg TrailConfig)
- func (e *Emitter) AttachTransform(fn func() (x, y, rotation float32))
- func (e *Emitter) Burst(count int)
- func (e *Emitter) Children() []*Emitter
- func (e *Emitter) Clear()
- func (e *Emitter) Config() Config
- func (e *Emitter) Count() int
- func (e *Emitter) Detach()
- func (e *Emitter) DetachTrail()
- func (e *Emitter) Draw(d *core.Drawing)
- func (e *Emitter) Follow(x, y float32)
- func (e *Emitter) ParticleTrails() []*Trail
- func (e *Emitter) ParticleWorldPos(p Particle) (x, y float32)
- func (e *Emitter) Particles() []Particle
- func (e *Emitter) ReloadConfig(cfg Config)
- func (e *Emitter) Reset()
- func (e *Emitter) TotalCount() int
- func (e *Emitter) TrailCount() int
- func (e *Emitter) Update(dt time.Duration)
- type Emitter3D
- func NewEmitter3D(cfg Emitter3DConfig) *Emitter3D
- func (e *Emitter3D) Active() bool
- func (e *Emitter3D) AppendInstances(dst []byte, camRight, camUp math3d.Vec3) []byte
- func (e *Emitter3D) AppendParticles(dst []Particle3D) []Particle3D
- func (e *Emitter3D) Burst(count int)
- func (e *Emitter3D) Clear()
- func (e *Emitter3D) Config() Emitter3DConfig
- func (e *Emitter3D) Count() int
- func (e *Emitter3D) Particle(i int) Particle3D
- func (e *Emitter3D) ParticleWorldPos(i int) math3d.Vec3
- func (e *Emitter3D) Particles() []Particle3D
- func (e *Emitter3D) ReloadConfig(cfg Emitter3DConfig)
- func (e *Emitter3D) Reset()
- func (e *Emitter3D) SortByDepth(camPos, camForward math3d.Vec3)
- func (e *Emitter3D) Step(dt time.Duration)
- func (e *Emitter3D) Update(dt time.Duration)
- type Emitter3DConfig
- type EmitterDoc
- type EmitterFieldsDoc
- type FloatCurve
- type FloatStop
- type FloatStopDoc
- type GPUParticles3D
- func NewGPUParticles3D(cx *core.Scope, dev *gpu.Device, opts GPUParticles3DOptions) (*GPUParticles3D, error)
- func (g *GPUParticles3D) ByteSize() uint64
- func (g *GPUParticles3D) Capacity() int
- func (g *GPUParticles3D) Close() error
- func (g *GPUParticles3D) Count() uint32
- func (g *GPUParticles3D) Draw(pass *gpu.RenderPass)
- func (g *GPUParticles3D) InstanceBuffer() *gpu.Buffer
- func (g *GPUParticles3D) QuadIndexBuffer() *gpu.Buffer
- func (g *GPUParticles3D) QuadVertexBuffer() *gpu.Buffer
- func (g *GPUParticles3D) Upload(e *Emitter3D, camRight, camUp math3d.Vec3) error
- func (g *GPUParticles3D) UploadBytes(data []byte) error
- func (g *GPUParticles3D) Valid() bool
- type GPUParticles3DOptions
- type HotConfig
- func LoadHotConfigFile(path string) (*HotConfig, error)
- func NewHotConfig(initial Config) *HotConfig
- func (h *HotConfig) Apply(cfg Config)
- func (h *HotConfig) Bind(e *Emitter)
- func (h *HotConfig) Config() Config
- func (h *HotConfig) Flush() bool
- func (h *HotConfig) OnReload(fn func(Config))
- func (h *HotConfig) ReloadBytes(data []byte) error
- func (h *HotConfig) ReloadFile(path string) error
- func (h *HotConfig) ReloadHook() func(path string) error
- func (h *HotConfig) StageBytes(data []byte) error
- func (h *HotConfig) Unbind(e *Emitter)
- func (h *HotConfig) Version() uint64
- type MultiCollider
- type Particle
- type Particle3D
- type ParticleBlendMode
- type ParticlePipelineOptions
- type RectCollider
- type Shape
- type Shape3D
- type ShapeDoc
- type SimulationSpace
- type SubEmitterDoc
- type SubEmitterRule
- type SubEmitterTrigger
- type System
- func NewSystem(emitters ...*Emitter) *System
- func (s *System) Add(e *Emitter)
- func (s *System) Clear()
- func (s *System) Draw(d *core.Drawing)
- func (s *System) Emitters() []*Emitter
- func (s *System) Remove(e *Emitter)
- func (s *System) Reset()
- func (s *System) TotalCount() int
- func (s *System) Update(dt time.Duration)
- type TileGridCollider
- type Trail
- func NewTrail(cfg TrailConfig) *Trail
- func (t *Trail) AddPoint(x, y float32)
- func (t *Trail) Attach(posFn func() (float32, float32))
- func (t *Trail) Clear()
- func (t *Trail) Config() TrailConfig
- func (t *Trail) Detach()
- func (t *Trail) Draw(d *core.Drawing)
- func (t *Trail) EvaluateAt(u float32) (width float32, color core.Color)
- func (t *Trail) Follow(x, y float32)
- func (t *Trail) PointCount() int
- func (t *Trail) Points() []TrailPoint
- func (t *Trail) SetConfig(cfg TrailConfig)
- func (t *Trail) Update(dt float32)
- type TrailConfig
- type TrailDoc
- type TrailManager
- func NewTrailManager() *TrailManager
- func (m *TrailManager) Add(cfg TrailConfig) *Trail
- func (m *TrailManager) AddTrail(tr *Trail)
- func (m *TrailManager) Clear()
- func (m *TrailManager) Count() int
- func (m *TrailManager) Draw(d *core.Drawing)
- func (m *TrailManager) Remove(tr *Trail)
- func (m *TrailManager) Trails() []*Trail
- func (m *TrailManager) Update(dt float32)
- type TrailPoint
常量
const (
// ParticleQuadVertexStride is the byte size of one unit-quad vertex: corner (float32x2) + UV (float32x2).
ParticleQuadVertexStride = 16
// ParticleQuadCornerOffset is the byte offset of the float32x2 corner in [-0.5, 0.5]².
ParticleQuadCornerOffset = 0
// ParticleQuadUVOffset is the byte offset of the float32x2 texture coordinate in [0, 1]².
ParticleQuadUVOffset = 8
// ParticleInstanceStride is the byte size of one packed 3D particle instance: center (12), right (12), up (12), RGBA8 color (4).
ParticleInstanceStride = 40
// ParticleInstanceCenterOffset is the byte offset of the float32x3 world-space quad center.
ParticleInstanceCenterOffset = 0
// ParticleInstanceRightOffset is the byte offset of the float32x3 world-space quad right vector (scaled by width).
ParticleInstanceRightOffset = 12
// ParticleInstanceUpOffset is the byte offset of the float32x3 world-space quad up vector (scaled by height).
ParticleInstanceUpOffset = 24
// ParticleInstanceColorOffset is the byte offset of the unorm8x4 RGBA particle color.
ParticleInstanceColorOffset = 36
// Shader @location indices for [ParticleVertexLayouts].
ParticleCornerLocation = 0
ParticleUVLocation = 1
ParticleCenterLocation = 2
ParticleRightLocation = 3
ParticleUpLocation = 4
ParticleColorLocation = 5
)Interleaved vertex and per-instance layouts for instanced 3D particle drawing on gpu.View.
Slot 0 holds the shared 4-vertex unit quad ([StepVertex]); slot 1 holds one 40-byte instance per live particle ([StepInstance]) written by Emitter3D.AppendInstances.
const FormatVersion = 1FormatVersion is the current schema version of an emitter definition, written by MarshalConfigYAML and MarshalConfigJSON and required by UnmarshalConfigYAML and UnmarshalConfigJSON.
const ParticleSoftCircleWGSL = `struct Camera {
view: mat4x4<f32>,
proj: mat4x4<f32>,
view_proj: mat4x4<f32>,
eye: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: Camera;
struct VertexIn {
@location(0) corner: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) center: vec3<f32>,
@location(3) right: vec3<f32>,
@location(4) up: vec3<f32>,
@location(5) color: vec4<f32>,
}
struct VertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex
fn vs_main(in: VertexIn) -> VertexOut {
var out: VertexOut;
let world_pos = in.center + in.right * in.corner.x + in.up * in.corner.y;
out.clip = camera.view_proj * vec4<f32>(world_pos, 1.0);
out.uv = in.uv;
out.color = in.color;
return out;
}
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
let d = in.uv * 2.0 - vec2<f32>(1.0, 1.0);
let mask = clamp(1.0 - dot(d, d), 0.0, 1.0);
return vec4<f32>(in.color.rgb, in.color.a * mask * mask);
}
`ParticleSoftCircleWGSL is a WGSL shader module for soft radial-falloff instanced 3D billboard particles without requiring a texture.
It binds the standard camera uniform at @group(0) @binding(0). Entry points are "vs_main" and "fs_main".
const ParticleTexturedWGSL = `struct Camera {
view: mat4x4<f32>,
proj: mat4x4<f32>,
view_proj: mat4x4<f32>,
eye: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: Camera;
@group(1) @binding(0) var particle_tex: texture_2d<f32>;
@group(1) @binding(1) var particle_sampler: sampler;
struct VertexIn {
@location(0) corner: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) center: vec3<f32>,
@location(3) right: vec3<f32>,
@location(4) up: vec3<f32>,
@location(5) color: vec4<f32>,
}
struct VertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex
fn vs_main(in: VertexIn) -> VertexOut {
var out: VertexOut;
let world_pos = in.center + in.right * in.corner.x + in.up * in.corner.y;
out.clip = camera.view_proj * vec4<f32>(world_pos, 1.0);
out.uv = in.uv;
out.color = in.color;
return out;
}
@fragment
fn fs_textured(in: VertexOut) -> @location(0) vec4<f32> {
return textureSample(particle_tex, particle_sampler, in.uv) * in.color;
}
`ParticleTexturedWGSL is a WGSL shader module for textured instanced 3D billboard particles.
It binds the standard camera uniform at @group(0) @binding(0), the particle texture at @group(1) @binding(0), and the sampler at @group(1) @binding(1). Entry points are "vs_main" and "fs_textured".
const ParticleWGSL = `struct Camera {
view: mat4x4<f32>,
proj: mat4x4<f32>,
view_proj: mat4x4<f32>,
eye: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: Camera;
struct VertexIn {
@location(0) corner: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) center: vec3<f32>,
@location(3) right: vec3<f32>,
@location(4) up: vec3<f32>,
@location(5) color: vec4<f32>,
}
struct VertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex
fn vs_main(in: VertexIn) -> VertexOut {
var out: VertexOut;
let world_pos = in.center + in.right * in.corner.x + in.up * in.corner.y;
out.clip = camera.view_proj * vec4<f32>(world_pos, 1.0);
out.uv = in.uv;
out.color = in.color;
return out;
}
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
return in.color;
}
`ParticleWGSL is a WGSL shader module for solid-colored instanced 3D billboard particles.
Its @group(0) @binding(0) camera uniform block matches render3d.CameraWGSL (view, proj, view_proj, eye) byte for byte, so render3d.CameraBuffer binds directly to it. Entry points are "vs_main" and "fs_main".
const SchemaURL = "https://game.nsgo.dev/schemas/particles.v1.json"SchemaURL is where the JSON Schema of version 1 2D particle emitter definitions is published.
函数
func MarshalConfig3DJSON(cfg Emitter3DConfig) ([]byte, error)MarshalConfig3DJSON encodes cfg into the versioned JSON form of the 3D emitter definition (version: 1).
func MarshalConfig3DYAML(cfg Emitter3DConfig) ([]byte, error)MarshalConfig3DYAML encodes cfg as a versioned YAML 3D emitter definition (version: 1) with fixed key order and 2-space indentation, so saving the same Emitter3DConfig always yields the same bytes.
func MarshalConfigJSON(cfg Config) ([]byte, error)MarshalConfigJSON encodes cfg into the versioned JSON form of the emitter definition (version: 1). Files people write use YAML (MarshalConfigYAML, SaveConfigFile); the JSON form is for programs that exchange definitions as JSON.
func MarshalConfigYAML(cfg Config) ([]byte, error)MarshalConfigYAML encodes cfg as a versioned YAML emitter definition (version: 1) with fixed key order and 2-space indentation, so saving the same Config always yields the same bytes.
func NewParticlePipeline(cx *core.Scope, dev *gpu.Device, opts ParticlePipelineOptions) (*gpu.Pipeline, error)NewParticlePipeline compiles the built-in 3D particle WGSL module and creates a gpu.Pipeline configured for GPUParticles3D.Draw, scoped to cx.
func ParticleVertexLayouts() []gpu.VertexBufferLayoutParticleVertexLayouts returns the two vertex buffer layouts (slot 0 = unit quad per-vertex, slot 1 = packed particle per-instance) expected by ParticleWGSL, ParticleTexturedWGSL and GPUParticles3D.Draw.
func SaveConfig3DFile(path string, cfg Emitter3DConfig) errorSaveConfig3DFile writes cfg as a versioned YAML 3D emitter definition file to path.
func SaveConfigFile(path string, cfg Config) errorSaveConfigFile encodes cfg as a versioned YAML emitter definition and writes it to path.
类型
type BillboardMode3D uint8BillboardMode3D selects how Emitter3D orients each particle quad toward the camera when packing GPU instances.
const (
// BillboardSpherical aligns every particle quad with the camera's view plane (right and up axes), applying per-particle roll rotation. This is the zero value and fastest mode.
BillboardSpherical BillboardMode3D = iota
// BillboardCylindrical locks each quad's up axis to [Emitter3D.Axis] (defaulting to +Y) and rotates only around that axis to face the camera.
BillboardCylindrical
// BillboardStretched aligns each quad's height axis with the particle's velocity vector and stretches its length proportionally to speed while facing the camera across the velocity axis.
BillboardStretched
)func (m BillboardMode3D) String() stringString returns the canonical string name of the billboard mode.
type Burst struct {
// Time is the elapsed emitter time when the first burst fires (>= 0).
Time time.Duration
// Count is how many particles to emit on each firing (> 0).
Count int
// Cycles is how many times the burst fires: 0 or 1 means once, and a negative value repeats indefinitely every Interval.
Cycles int
// Interval is the delay between repeated firings when Cycles != 1 (must be > 0 to repeat).
Interval time.Duration
}Burst schedules an automatic burst of particles during Emitter.Update.
type BurstDoc struct {
// Time is the elapsed emitter time when the first burst fires, as a Go duration string such as "250ms".
Time time.Duration `yaml:"time,omitempty"`
// Count is the number of particles emitted on each firing.
Count int `yaml:"count,omitempty" schema:"minimum=0"`
// Cycles is how many times the burst fires (0 or 1 means once; negative repeats indefinitely every interval).
Cycles int `yaml:"cycles,omitempty"`
// Interval is the delay between repeated firings as a Go duration string such as "1s".
Interval time.Duration `yaml:"interval,omitempty"`
}BurstDoc describes one scheduled particle burst in YAML.
type CircleCollider struct {
X, Y, Radius float32
}CircleCollider resolves particle collisions against a solid circle centered at (X, Y) with Radius.
func (c *CircleCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)ResolveParticle implements Collider with zero heap allocations.
type Collider interface {
ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)
}Collider resolves a particle's movement from (prevX, prevY) to (x, y) with the given radius. When hit is true, (hitX, hitY) is the resolved particle center position and (nx, ny) is the unit surface normal pointing out of the obstacle.
type CollisionConfig struct {
// Enabled turns collision checking on during Update when true and Collider is non-nil.
Enabled bool
// Mode controls the particle's response on impact.
Mode CollisionMode
// Bounce is the restitution factor applied to the normal velocity component in CollideBounce mode.
Bounce float32
// Friction damps tangential velocity on impact in CollideBounce mode, clamped to [0, 1].
Friction float32
// Radius is the particle's collision radius in points (>= 0).
Radius float32
// Collider tests and resolves particle contacts. Not serialized in JSON configs.
Collider Collider
}CollisionConfig configures particle collision detection and response on an Emitter.
type CollisionDoc struct {
// Enabled turns particle collision checking on when a runtime Collider is attached.
Enabled bool `yaml:"enabled,omitempty"`
// Mode selects the impact response: "none", "stop", "bounce" or "kill".
Mode string `yaml:"mode,omitempty" schema:"enum=none|stop|bounce|kill"`
// Bounce is the restitution factor applied to normal velocity in "bounce" mode.
Bounce float32 `yaml:"bounce,omitempty"`
// Friction damps tangential velocity on impact in "bounce" mode, clamped to [0, 1].
Friction float32 `yaml:"friction,omitempty"`
// Radius is the particle collision radius in points.
Radius float32 `yaml:"radius,omitempty"`
}CollisionDoc describes particle collision settings in YAML.
type CollisionMode uint8CollisionMode controls how a particle responds when it hits a Collider.
const (
// CollideNone disables collision response.
CollideNone CollisionMode = iota
// CollideStop halts the particle at the contact point with zero velocity.
CollideStop
// CollideBounce reflects the particle's velocity using Bounce (restitution) and Friction.
CollideBounce
// CollideKill immediately expires the particle upon impact.
CollideKill
)func (m CollisionMode) String() stringString returns the canonical string name of the collision mode.
type ColorCurve []ColorStopColorCurve maps a particle's normalized age in [0, 1] to a core.Color by linear RGBA interpolation between stops ordered by T. An empty curve returns opaque white (0xffffffff).
func (c ColorCurve) At(t float32) core.ColorAt returns the curve's color at normalized age t, clamped to [0, 1].
type ColorStop struct {
T float32
Color core.Color
}ColorStop is one control point on a ColorCurve at normalized particle age T in [0, 1].
type ColorStopDoc struct {
// T is the normalized particle age in [0, 1].
T float32 `yaml:"t"`
// Color is a quoted hex color string "#rrggbb" or "#rrggbbaa".
Color string `yaml:"color"`
}ColorStopDoc is one control point on a color curve at normalized age t in [0, 1].
type Config struct {
X, Y float32
Rotation float32
Space SimulationSpace
Shape Shape
Rate float32
Bursts []Burst
MaxParticles int
LifetimeMin time.Duration
LifetimeMax time.Duration
SpeedMin float32
SpeedMax float32
AngleMin float32
AngleMax float32
GravityX float32
GravityY float32
InitialRotationMin float32
InitialRotationMax float32
RotationSpeedMin float32
RotationSpeedMax float32
SizeCurve FloatCurve
AlphaCurve FloatCurve
RotationCurve FloatCurve
ColorCurve ColorCurve
Seed uint64
Z int
FrameNames []string
Collision CollisionConfig
Trail *TrailConfig
SubEmitters []SubEmitterRule
}Config is a serializable, reloadable snapshot of an Emitter's configuration.
func LoadConfigFS(fsys fs.FS, name string) (Config, error)LoadConfigFS reads and decodes a versioned YAML emitter definition file from fsys. Its errors are *loaderr.Error values that name the file.
func LoadConfigFile(path string) (Config, error)LoadConfigFile reads and decodes a versioned YAML emitter definition file from disk. Its errors are *loaderr.Error values that name path.
func UnmarshalConfigJSON(data []byte) (Config, error)UnmarshalConfigJSON decodes the versioned JSON form of an emitter definition into a Config. Its errors are *loaderr.Error values, as UnmarshalConfigYAML's are.
func UnmarshalConfigYAML(data []byte) (Config, error)UnmarshalConfigYAML decodes a versioned YAML emitter definition into a Config. It refuses unknown fields, a key with no value, a second YAML document, a version other than FormatVersion or one inside a sub-emitter, an integer field written with a fraction, a shape size that does not apply to its kind, durations that are not strings such as "500ms", and colors that are not quoted "#rrggbb" or "#rrggbbaa" strings.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as LoadConfigFile does.
type Emitter struct {
// Atlas holds the image that Frames reference. Draw skips particle sprites when Atlas is nil.
Atlas *sprite.Atlas
// Frames are the atlas frames particles choose from at spawn time.
Frames []sprite.Frame
// X and Y are the emitter's position in the drawing.
X, Y float32
// Rotation is the emitter's rotation in radians, clockwise on the screen.
Rotation float32
// Space controls whether particles simulate in world space (SpaceWorld, default) or emitter-local space (SpaceLocal).
Space SimulationSpace
// Shape controls where particles spawn relative to X, Y; its zero value is Point.
Shape Shape
// Rate is how many particles emit per second during Update; 0 or less disables continuous emission.
Rate float32
// Bursts schedules automatic bursts of particles at specific elapsed times during Update.
Bursts []Burst
// MaxParticles caps how many particles may be live at once, 256 when 0 or less.
MaxParticles int
// LifetimeMin and LifetimeMax give how long each particle lives; both 0 defaults to one second, and a LifetimeMax below LifetimeMin matches LifetimeMin.
LifetimeMin, LifetimeMax time.Duration
// SpeedMin and SpeedMax give each particle's initial speed in points per second.
SpeedMin, SpeedMax float32
// AngleMin and AngleMax give each particle's initial direction of travel in radians, clockwise from +X.
AngleMin, AngleMax float32
// GravityX and GravityY are constant acceleration applied to live particles, in points per second squared.
GravityX, GravityY float32
// InitialRotationMin and InitialRotationMax give each particle's starting rotation in radians.
InitialRotationMin, InitialRotationMax float32
// RotationSpeedMin and RotationSpeedMax give each particle's angular velocity in radians per second.
RotationSpeedMin, RotationSpeedMax float32
// SizeCurve scales each particle over its normalized life in [0, 1]; empty scales by 1.
SizeCurve FloatCurve
// AlphaCurve fades each particle over its normalized life in [0, 1]; empty keeps opacity at 1.
AlphaCurve FloatCurve
// RotationCurve adds rotation in radians over a particle's normalized life in [0, 1]; empty adds 0.
RotationCurve FloatCurve
// ColorCurve evaluates a color over each particle's normalized life in [0, 1] and stores it on Particle.Color. Draw tints each particle's sprite by the color's RGB, and its alpha channel multiplies AlphaCurve into Particle.Alpha.
ColorCurve ColorCurve
// Seed seeds the emitter's PCG PRNG for deterministic emission and motion.
Seed uint64
// Z sets the sprite Z order used when drawing this emitter's particles.
Z int
// Collision configures optional particle collision detection and response against a Collider.
Collision CollisionConfig
// Trail, when non-nil, automatically attaches a 2D ribbon trail to each emitted particle.
Trail *TrailConfig
// SubEmitters configures child bursts triggered on particle birth, death, or collision.
SubEmitters []SubEmitterRule
// contains filtered or unexported fields
}Emitter spawns, updates and draws 2D particles deterministically from a seeded PRNG.
Call Update from a game.Loop's fixed step and Draw from a Canvas's Draw callback. Continuous emission runs whenever Rate > 0; call Burst to emit particles on demand regardless of Rate.
Two emitters configured with the same fields and Seed and stepped identically produce bit-for-bit identical particles and draw operations.
func NewEmitter(cfg Config) *EmitterNewEmitter constructs an Emitter initialized from cfg.
func (e *Emitter) Attach(posFn func() (float32, float32))Attach binds a position callback so the emitter tracks a moving object on every Update. Calling Attach immediately syncs X, Y to posFn(). Passing nil detaches.
func (e *Emitter) AttachTrail(cfg TrailConfig)AttachTrail enables automatic per-particle ribbon trails on the emitter using cfg.
func (e *Emitter) AttachTransform(fn func() (x, y, rotation float32))AttachTransform binds a position and rotation callback so the emitter tracks a moving, rotating object on every Update. Calling AttachTransform immediately syncs X, Y, Rotation. Passing nil detaches.
func (e *Emitter) Burst(count int)Burst immediately emits up to count particles without waiting for Update or requiring Rate > 0, stopping at MaxParticles.
func (e *Emitter) Children() []*EmitterChildren returns the managed child emitters created for SubEmitters.
func (e *Emitter) Clear()Clear removes all live particles, trails, and child sub-emitter particles, and resets the fractional emission accumulator without resetting the PRNG.
func (e *Emitter) Config() ConfigConfig returns a deep-copied Config reflecting the emitter's current settings.
func (e *Emitter) Count() intCount returns the number of currently live particles in this emitter (excluding child sub-emitters).
func (e *Emitter) Detach()Detach clears any callback bound via Attach or AttachTransform.
func (e *Emitter) DetachTrail()DetachTrail disables automatic per-particle ribbon trails on the emitter. Existing particle trails fade out naturally as their points expire.
func (e *Emitter) Draw(d *core.Drawing)Draw draws particle trails, all live particles through a reusable sprite.Batch (oldest first), and any managed child sub-emitters into d.
func (e *Emitter) Follow(x, y float32)Follow moves the emitter smoothly to (x, y), recording the previous position so multi-particle continuous emission interpolates along the motion path.
func (e *Emitter) ParticleTrails() []*TrailParticleTrails returns the currently live particle trails in spawn order.
func (e *Emitter) ParticleWorldPos(p Particle) (x, y float32)ParticleWorldPos converts a particle's coordinates to world coordinates. For SpaceWorld emitters this returns (p.X, p.Y) unchanged; for SpaceLocal emitters it applies X, Y, and Rotation.
func (e *Emitter) Particles() []ParticleParticles returns the live particles in spawn order. The returned slice is backed by the emitter's storage and reused on subsequent updates; copy it to retain a snapshot.
func (e *Emitter) ReloadConfig(cfg Config)ReloadConfig applies cfg to a running Emitter without resetting live particles, PRNG state, attachment callbacks, or runtime colliders.
func (e *Emitter) Reset()Reset clears all live particles, trails, and child sub-emitters and re-seeds the PRNG from Seed so subsequent updates replay identically.
func (e *Emitter) TotalCount() intTotalCount returns the number of live particles in this emitter plus all managed child sub-emitters recursively.
func (e *Emitter) TrailCount() intTrailCount returns the total number of active and fading particle trails owned by the emitter.
func (e *Emitter) Update(dt time.Duration)Update advances live particles by dt, removes expired ones, resolves collisions, updates trails and sub-emitters, and emits new particles at Rate. Non-positive dt does nothing.
type Emitter3D struct {
// Position is the emitter's world-space origin.
Position math3d.Vec3
// Direction is the primary emission axis; zero defaults to +Y (0, 1, 0).
Direction math3d.Vec3
// Up is the reference up axis used to build the emitter's local frame; zero picks a deterministic perpendicular axis.
Up math3d.Vec3
// Rotation is an optional emitter orientation quaternion; zero is treated as identity. In SpaceLocal it rotates all live particles when packing; in SpaceWorld it rotates spawned offsets and velocities.
Rotation math3d.Quat
// Space controls whether particles simulate in world coordinates (SpaceWorld, default) or emitter-local coordinates (SpaceLocal).
Space SimulationSpace
// Shape controls where new particles spawn relative to Position; its zero value is Point3D.
Shape Shape3D
// Billboard selects how quads face the camera when AppendInstances packs GPU data.
Billboard BillboardMode3D
// Blend records the preferred GPU blend mode for pipelines built for this emitter.
Blend ParticleBlendMode
// StretchFactor scales velocity elongation in seconds for BillboardStretched (length = size + speed * StretchFactor); <= 0 defaults to 0.05.
StretchFactor float32
// Axis is the locked world up axis for BillboardCylindrical; zero defaults to +Y (0, 1, 0).
Axis math3d.Vec3
// Rate is how many particles emit per second during Step/Update; 0 or less disables continuous emission.
Rate float32
// MaxParticles caps how many particles may be live at once, 256 when 0 or less.
MaxParticles int
// LifetimeMin and LifetimeMax give how long each particle lives; both 0 defaults to one second, and a LifetimeMax below LifetimeMin matches LifetimeMin.
LifetimeMin, LifetimeMax time.Duration
// SpeedMin and SpeedMax give each particle's initial speed in world units per second.
SpeedMin, SpeedMax float32
// Spread is the emission cone half-angle in radians around Direction, clamped to [0, pi]. Zero emits straight along Direction; pi emits uniformly in all directions.
Spread float32
// Drag is exponential linear velocity damping in 1/s (>= 0); zero disables drag.
Drag float32
// Gravity is constant acceleration applied to live particles in world units per second squared.
Gravity math3d.Vec3
// SizeMin and SizeMax give each particle's base world-space quad size before SizeCurve; both <= 0 defaults to 1.
SizeMin, SizeMax float32
// InitialRotationMin and InitialRotationMax give each particle's starting roll angle in radians.
InitialRotationMin, InitialRotationMax float32
// RotationSpeedMin and RotationSpeedMax give each particle's roll angular velocity in radians per second.
RotationSpeedMin, RotationSpeedMax float32
// SizeCurve scales each particle's base size over its normalized age in [0, 1]; empty scales by 1.
SizeCurve FloatCurve
// AlphaCurve fades each particle over its normalized age in [0, 1]; empty keeps opacity at 1.
AlphaCurve FloatCurve
// RotationCurve adds roll rotation in radians over a particle's normalized age in [0, 1]; empty adds 0.
RotationCurve FloatCurve
// ColorCurve evaluates a color over each particle's normalized age in [0, 1]; empty uses Color (or opaque white when Color is 0).
ColorCurve ColorCurve
// Color is the base particle color used when ColorCurve is empty; zero means opaque white (0xffffffff).
Color core.Color
// Seed seeds the emitter's PCG PRNG for deterministic emission and motion.
Seed uint64
// contains filtered or unexported fields
}Emitter3D spawns, updates and packs 3D particles deterministically from a seeded PRNG for instanced GPU rendering.
It shares the emitter model of 2D Emitter (Rate, MaxParticles, LifetimeMin/Max, SpeedMin/Max, curves, SimulationSpace, Seed, Burst, Clear, Reset) and stores live particles in dense structure-of-arrays slices with swap-remove expiration so stepping and packing 10,000 particles allocates zero memory in steady state.
Two emitters configured with the same fields and Seed and stepped identically produce bit-for-bit identical particles and packed GPU instance bytes.
func NewEmitter3D(cfg Emitter3DConfig) *Emitter3DNewEmitter3D constructs an Emitter3D initialized from cfg.
func (e *Emitter3D) Active() boolActive reports whether the emitter currently has at least one live particle.
func (e *Emitter3D) AppendInstances(dst []byte, camRight, camUp math3d.Vec3) []byteAppendInstances packs all live particles into dst in the little-endian 40-byte ParticleInstanceStride GPU layout facing (camRight, camUp) and returns the extended slice.
If Emitter3D.SortByDepth was called since the last mutation, instances are written in back-to-front sorted order. It allocates only when dst lacks capacity for Count() * ParticleInstanceStride more bytes.
func (e *Emitter3D) AppendParticles(dst []Particle3D) []Particle3DAppendParticles appends snapshots of all live particles to dst and returns the extended slice.
func (e *Emitter3D) Burst(count int)Burst immediately emits up to count particles without waiting for Step or requiring Rate > 0, stopping at MaxParticles.
func (e *Emitter3D) Clear()Clear removes all live particles and resets the fractional emission accumulator without resetting the PRNG.
func (e *Emitter3D) Config() Emitter3DConfigConfig returns a deep-copied Emitter3DConfig reflecting the emitter's current settings.
func (e *Emitter3D) Count() intCount returns the number of currently live particles.
func (e *Emitter3D) Particle(i int) Particle3DParticle returns a snapshot of the live particle at index i (0 <= i < Count()).
func (e *Emitter3D) ParticleWorldPos(i int) math3d.Vec3ParticleWorldPos returns the world-space position of particle i. For SpaceWorld emitters this returns the stored position directly; for SpaceLocal emitters it applies the emitter's Rotation and Position.
func (e *Emitter3D) Particles() []Particle3DParticles returns a slice containing snapshots of all live particles.
func (e *Emitter3D) ReloadConfig(cfg Emitter3DConfig)ReloadConfig applies cfg to e without clearing live particles or resetting the PRNG. If the new MaxParticles is smaller than the live particle count, excess particles are dropped.
func (e *Emitter3D) Reset()Reset clears all live particles and re-seeds the PRNG from Seed so subsequent steps replay identically.
func (e *Emitter3D) SortByDepth(camPos, camForward math3d.Vec3)SortByDepth orders live particles back-to-front along camForward from camPos so alpha-blended particles pack farthest first in subsequent Emitter3D.AppendInstances calls.
It uses a deterministic, zero-allocation 4-pass radix sort over IEEE-754 depth keys. The sorted order remains active until the next Step, Burst, Clear, or Reset.
func (e *Emitter3D) Step(dt time.Duration)Step advances live particles by dt, removes expired ones via dense swap-remove, evaluates lifetime curves, and emits new particles at Rate. Non-positive dt does nothing.
func (e *Emitter3D) Update(dt time.Duration)Update advances live particles by dt, expires dead ones, and emits new particles at Rate. It is equivalent to Emitter3D.Step and matches 2D Emitter.Update for use in game.Loop.
type Emitter3DConfig struct {
Position math3d.Vec3
Direction math3d.Vec3
Up math3d.Vec3
Rotation math3d.Quat
Space SimulationSpace
Shape Shape3D
Billboard BillboardMode3D
Blend ParticleBlendMode
StretchFactor float32
Axis math3d.Vec3
Rate float32
MaxParticles int
LifetimeMin time.Duration
LifetimeMax time.Duration
SpeedMin float32
SpeedMax float32
Spread float32
Drag float32
Gravity math3d.Vec3
SizeMin float32
SizeMax float32
InitialRotationMin float32
InitialRotationMax float32
RotationSpeedMin float32
RotationSpeedMax float32
SizeCurve FloatCurve
AlphaCurve FloatCurve
RotationCurve FloatCurve
ColorCurve ColorCurve
Color core.Color
Seed uint64
}Emitter3DConfig is a serializable, reloadable snapshot of an Emitter3D's configuration.
func LoadConfig3DFS(fsys fs.FS, name string) (Emitter3DConfig, error)LoadConfig3DFS reads and decodes a versioned YAML 3D emitter definition file from fsys.
func LoadConfig3DFile(path string) (Emitter3DConfig, error)LoadConfig3DFile reads and decodes a versioned YAML 3D emitter definition file from disk.
func UnmarshalConfig3DJSON(data []byte) (Emitter3DConfig, error)UnmarshalConfig3DJSON decodes the versioned JSON form of a 3D emitter definition into an Emitter3DConfig.
func UnmarshalConfig3DYAML(data []byte) (Emitter3DConfig, error)UnmarshalConfig3DYAML decodes a versioned YAML 3D emitter definition into an Emitter3DConfig. It refuses unknown fields, keys with no value, trailing YAML documents, unsupported versions, fractions in integer fields, shape fields that do not apply to the shape kind, and non-finite numbers.
type EmitterDoc struct {
// Version is the schema version; it must be FormatVersion (1).
Version int `yaml:"version" schema:"required"`
// EmitterFieldsDoc holds the emitter fields written alongside version at the top level.
EmitterFieldsDoc `yaml:",inline"`
}EmitterDoc describes the versioned YAML schema of a 2D particle emitter definition (version: 1) for JSON Schema generation.
type EmitterFieldsDoc struct {
// X is the emitter's default horizontal position in points.
X float32 `yaml:"x,omitempty"`
// Y is the emitter's default vertical position in points.
Y float32 `yaml:"y,omitempty"`
// Rotation is the emitter's rotation in radians, clockwise on screen.
Rotation float32 `yaml:"rotation,omitempty"`
// Space controls whether particles simulate in world coordinates ("world") or emitter-local coordinates ("local").
Space string `yaml:"space,omitempty" schema:"enum=world|local"`
// Shape controls where new particles spawn relative to the emitter's origin.
Shape *ShapeDoc `yaml:"shape,omitempty"`
// Rate is how many particles emit per second during Update; 0 disables continuous emission.
Rate float32 `yaml:"rate,omitempty"`
// Bursts schedules automatic bursts of particles at specific elapsed times during Update.
Bursts []BurstDoc `yaml:"bursts,omitempty"`
// MaxParticles caps how many particles may be live at once (defaults to 256 when 0 or omitted).
MaxParticles int `yaml:"maxParticles,omitempty"`
// LifetimeMin is the minimum particle lifetime as a Go duration string such as "300ms".
LifetimeMin time.Duration `yaml:"lifetimeMin,omitempty"`
// LifetimeMax is the maximum particle lifetime as a Go duration string such as "700ms".
LifetimeMax time.Duration `yaml:"lifetimeMax,omitempty"`
// SpeedMin is the minimum initial particle speed in points per second.
SpeedMin float32 `yaml:"speedMin,omitempty"`
// SpeedMax is the maximum initial particle speed in points per second.
SpeedMax float32 `yaml:"speedMax,omitempty"`
// AngleMin is the minimum initial direction of travel in radians, clockwise from +X.
AngleMin float32 `yaml:"angleMin,omitempty"`
// AngleMax is the maximum initial direction of travel in radians, clockwise from +X.
AngleMax float32 `yaml:"angleMax,omitempty"`
// GravityX is constant horizontal acceleration in points per second squared.
GravityX float32 `yaml:"gravityX,omitempty"`
// GravityY is constant vertical acceleration in points per second squared.
GravityY float32 `yaml:"gravityY,omitempty"`
// InitialRotationMin is the minimum starting particle rotation in radians.
InitialRotationMin float32 `yaml:"initialRotationMin,omitempty"`
// InitialRotationMax is the maximum starting particle rotation in radians.
InitialRotationMax float32 `yaml:"initialRotationMax,omitempty"`
// RotationSpeedMin is the minimum angular velocity in radians per second.
RotationSpeedMin float32 `yaml:"rotationSpeedMin,omitempty"`
// RotationSpeedMax is the maximum angular velocity in radians per second.
RotationSpeedMax float32 `yaml:"rotationSpeedMax,omitempty"`
// SizeCurve scales each particle over its normalized lifetime in [0, 1].
SizeCurve []FloatStopDoc `yaml:"sizeCurve,omitempty"`
// AlphaCurve fades each particle's opacity over its normalized lifetime in [0, 1].
AlphaCurve []FloatStopDoc `yaml:"alphaCurve,omitempty"`
// RotationCurve adds rotation in radians over a particle's normalized lifetime in [0, 1].
RotationCurve []FloatStopDoc `yaml:"rotationCurve,omitempty"`
// ColorCurve tints each particle over its normalized lifetime in [0, 1].
ColorCurve []ColorStopDoc `yaml:"colorCurve,omitempty"`
// Seed seeds the emitter's deterministic PCG PRNG.
Seed uint64 `yaml:"seed,omitempty"`
// Z sets the sprite Z draw order of emitted particles.
Z int `yaml:"z,omitempty"`
// FrameNames lists the atlas frame names particles pick from at spawn time.
FrameNames []string `yaml:"frameNames,omitempty"`
// Collision configures optional particle collision response.
Collision *CollisionDoc `yaml:"collision,omitempty"`
// Trail configures optional per-particle 2D ribbon trails.
Trail *TrailDoc `yaml:"trail,omitempty"`
// SubEmitters configures child bursts triggered on particle birth, death or collision.
SubEmitters []SubEmitterDoc `yaml:"subEmitters,omitempty"`
}EmitterFieldsDoc describes the fields of a 2D particle emitter configuration (used at the top level and inside sub-emitters without version).
type FloatCurve []FloatStopFloatCurve maps a particle's normalized age in [0, 1] to a float32 by linear interpolation between stops ordered by T. An empty curve returns 1 at any age.
func (c FloatCurve) At(t float32) float32At returns the curve's value at normalized age t, clamped to [0, 1].
type FloatStop struct {
T float32
Value float32
}FloatStop is one control point on a FloatCurve at normalized particle age T in [0, 1].
type FloatStopDoc struct {
// T is the normalized particle age in [0, 1].
T float32 `yaml:"t"`
// Value is the curve value at T.
Value float32 `yaml:"value"`
}FloatStopDoc is one control point on a float curve at normalized age t in [0, 1].
type GPUParticles3D struct {
// contains filtered or unexported fields
}GPUParticles3D owns the static unit-quad geometry and dynamic per-instance vertex buffer needed to draw an Emitter3D in a single gpu.RenderPass.DrawIndexedInstanced call.
Its buffers belong to the *core.Scope passed to NewGPUParticles3D and are released automatically when that scope is disposed, or earlier via GPUParticles3D.Close. Use it on the engine goroutine, like the gpu.Device it came from.
func NewGPUParticles3D(cx *core.Scope, dev *gpu.Device, opts GPUParticles3DOptions) (*GPUParticles3D, error)NewGPUParticles3D creates the static quad vertex/index buffers and an initial instance vertex buffer on dev, scoped to cx.
func (g *GPUParticles3D) ByteSize() uint64ByteSize returns the total GPU memory held by the quad and instance buffers.
func (g *GPUParticles3D) Capacity() intCapacity returns the maximum number of particle instances the current GPU buffer holds without growing.
func (g *GPUParticles3D) Close() errorClose releases all GPU buffers now rather than waiting for scope disposal. Safe to call more than once.
func (g *GPUParticles3D) Count() uint32Count returns the number of particle instances currently uploaded for drawing.
func (g *GPUParticles3D) Draw(pass *gpu.RenderPass)Draw binds the unit quad and instance buffers to pass and records one gpu.RenderPass.DrawIndexedInstanced call for all uploaded particles. The pass must already have a pipeline built with ParticleVertexLayouts and its bind groups set. When g is invalid or has 0 uploaded particles, Draw records nothing.
func (g *GPUParticles3D) InstanceBuffer() *gpu.BufferInstanceBuffer returns the dynamic per-instance vertex buffer (slot 1).
func (g *GPUParticles3D) QuadIndexBuffer() *gpu.BufferQuadIndexBuffer returns the static unit-quad uint16 index buffer.
func (g *GPUParticles3D) QuadVertexBuffer() *gpu.BufferQuadVertexBuffer returns the static unit-quad vertex buffer (slot 0).
func (g *GPUParticles3D) Upload(e *Emitter3D, camRight, camUp math3d.Vec3) errorUpload packs e's live particles facing (camRight, camUp) into reusable scratch storage and uploads them to the GPU instance buffer. If e has more live particles than the current GPU buffer capacity, the instance buffer grows automatically.
func (g *GPUParticles3D) UploadBytes(data []byte) errorUploadBytes uploads pre-packed instance bytes (whose length must be a multiple of ParticleInstanceStride) to the GPU instance buffer. This allows packing several emitters into one byte slice and drawing them in a single instanced draw call.
func (g *GPUParticles3D) Valid() boolValid reports whether all underlying GPU buffers are open and belong to a live device.
type GPUParticles3DOptions struct {
// Label names the GPU buffers in capture tools.
Label string
// Capacity is the initial maximum number of particle instances the GPU buffer holds before growing; defaults to 256 when <= 0.
Capacity int
// Retained keeps the buffers retained across GPU device loss.
Retained bool
}GPUParticles3DOptions configures NewGPUParticles3D.
type HotConfig struct {
// contains filtered or unexported fields
}HotConfig holds a live, versioned emitter Config and pushes hot-reloaded definitions to bound Emitters. It is composable with file-watching hot-reload hooks via ReloadHook.
func LoadHotConfigFile(path string) (*HotConfig, error)LoadHotConfigFile loads a versioned YAML emitter definition from path and returns a HotConfig bound to that file path.
func NewHotConfig(initial Config) *HotConfigNewHotConfig creates a HotConfig initialized with initial.
func (h *HotConfig) Apply(cfg Config)Apply updates the stored Config and reloads all bound Emitters immediately.
func (h *HotConfig) Bind(e *Emitter)Bind registers e to receive config updates whenever Apply, ReloadBytes, ReloadFile, or Flush runs, and immediately applies the current config to e.
func (h *HotConfig) Config() ConfigConfig returns a copy of the currently active Config.
func (h *HotConfig) Flush() boolFlush applies any config staged via StageBytes to all bound Emitters and reports whether a reload occurred.
func (h *HotConfig) OnReload(fn func(Config))OnReload sets an optional callback invoked after a config reload succeeds.
func (h *HotConfig) ReloadBytes(data []byte) errorReloadBytes decodes a versioned YAML emitter definition and, if valid, applies the new Config to all bound Emitters. An invalid definition returns an error and leaves the current Config and Emitters unchanged.
func (h *HotConfig) ReloadFile(path string) errorReloadFile reads a versioned YAML emitter definition from path (or the stored file path if path is empty) and applies it.
func (h *HotConfig) ReloadHook() func(path string) errorReloadHook returns a file-change callback suitable for plugging into hot-reload watchers (such as tooling/hotreload).
func (h *HotConfig) StageBytes(data []byte) errorStageBytes decodes a versioned YAML emitter definition from a background watcher thread without touching Emitters yet. Call Flush from the game loop thread to apply the staged config safely.
func (h *HotConfig) Unbind(e *Emitter)Unbind removes e from receiving further hot-reload updates.
func (h *HotConfig) Version() uint64Version returns the monotonic reload counter (starts at 1 and increments on each successful reload).
type MultiCollider []ColliderMultiCollider combines multiple Colliders and reports the earliest/first hit.
func (m MultiCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)ResolveParticle implements Collider with zero heap allocations.
type Particle struct {
// Frame is the atlas frame this particle draws.
Frame sprite.Frame
// X and Y are the particle's position in the drawing (or emitter-local coordinates when Emitter.Space is SpaceLocal).
X, Y float32
// VX and VY are the particle's velocity in points per second.
VX, VY float32
// Age is how long the particle has lived so far.
Age time.Duration
// Lifetime is how long the particle lives before expiring.
Lifetime time.Duration
// Size is the particle's uniform scale evaluated from Emitter.SizeCurve.
Size float32
// Alpha is the particle's opacity in [0, 1], evaluated from Emitter.AlphaCurve and Emitter.ColorCurve.
Alpha float32
// Rotation is the particle's angle in radians, clockwise on the screen.
Rotation float32
// Color is the particle's color evaluated from Emitter.ColorCurve.
Color core.Color
// contains filtered or unexported fields
}Particle is the live state of one emitted particle.
type Particle3D struct {
// Position is the particle's position in world space (or emitter-local space when Space is SpaceLocal).
Position math3d.Vec3
// Velocity is the particle's velocity in world units per second.
Velocity math3d.Vec3
// Age is how long the particle has lived so far.
Age time.Duration
// Lifetime is how long the particle lives before expiring.
Lifetime time.Duration
// Size is the particle's world-space quad size after applying SizeCurve.
Size float32
// Alpha is the particle's opacity in [0, 1] after applying AlphaCurve and ColorCurve.
Alpha float32
// Rotation is the particle's roll angle in radians.
Rotation float32
// Color is the particle's RGB color evaluated from ColorCurve (or Emitter3D.Color when empty) with alpha in the low byte.
Color core.Color
}Particle3D is a read-only snapshot of one live particle in an Emitter3D.
type ParticleBlendMode uint8ParticleBlendMode selects how 3D particles blend into the color target in a GPU pipeline.
const (
// BlendAlpha uses standard non-premultiplied alpha blending (srcAlpha, 1-srcAlpha). Call [Emitter3D.SortByDepth] before packing for correct transparency order.
BlendAlpha ParticleBlendMode = iota
// BlendAdditive uses additive blending (srcAlpha, 1). Order-independent, so depth sorting is unnecessary for fire, sparks and glow effects.
BlendAdditive
// BlendPremultiplied uses premultiplied alpha blending (1, 1-srcAlpha).
BlendPremultiplied
)func (m ParticleBlendMode) BlendState() *gpu.BlendStateBlendState returns the gpu.BlendState corresponding to m.
func (m ParticleBlendMode) String() stringString returns the canonical string name of the blend mode.
type ParticlePipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// CameraLayout is the bind group layout for @group(0) (required; matches render3d.CameraBuffer.Layout()).
CameraLayout *gpu.BindGroupLayout
// TextureLayout is an optional bind group layout for @group(1) (texture at binding 0, sampler at binding 1). When non-nil, NewParticlePipeline compiles ParticleTexturedWGSL instead of ParticleWGSL.
TextureLayout *gpu.BindGroupLayout
// ColorFormat is the color target format; FormatUndefined defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing when not FormatUndefined.
DepthFormat gpu.TextureFormat
// DepthWrite controls whether particles write to the depth buffer; false (the default) is standard for translucent particles.
DepthWrite bool
// Blend selects alpha, additive, or premultiplied blending; the zero value is BlendAlpha.
Blend ParticleBlendMode
// SoftCircle selects [ParticleSoftCircleWGSL] (smooth radial falloff) when TextureLayout is nil.
SoftCircle bool
// SampleCount sets the MSAA sample count (0 or 1 for non-MSAA).
SampleCount int
// Retained opts into automatic pipeline recreation across GPU device loss.
Retained bool
}ParticlePipelineOptions configures NewParticlePipeline.
type RectCollider struct {
X, Y, W, H float32
}RectCollider resolves particle collisions against an axis-aligned rectangle [X, X+W] x [Y, Y+H].
func (c *RectCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)ResolveParticle implements Collider with zero heap allocations.
type Shape struct {
// contains filtered or unexported fields
}Shape describes where an Emitter places each new particle relative to its X, Y position. Its zero value is Point, which emits at X, Y.
func Circle(radius float32) ShapeCircle returns a shape that emits particles uniformly over a disk of radius centered on X, Y.
func Point() ShapePoint returns a shape that emits particles at the emitter's X, Y position.
func Rect(width, height float32) ShapeRect returns a shape that emits particles uniformly inside a width by height rectangle centered on X, Y.
func Ring(radius float32) ShapeRing returns a shape that emits particles uniformly on the circumference of a circle of radius centered on X, Y.
func (s Shape) Height() float32Height returns the height of a rect shape, or 0 for other kinds.
func (s Shape) Kind() stringKind returns the canonical name of s: "point", "circle", "ring" or "rect".
func (s Shape) Radius() float32Radius returns the radius of a circle or ring shape, or 0 for other kinds.
func (s Shape) Width() float32Width returns the width of a rect shape, or 0 for other kinds.
type Shape3D struct {
// contains filtered or unexported fields
}Shape3D describes where an Emitter3D places each new particle relative to its Position. Its zero value is Point3D, which emits at Position.
func Box(width, height, depth float32) Shape3DBox returns a 3D shape that emits particles uniformly inside a width × height × depth box centered on Position, aligned with the emitter's basis (width along side, height along Direction, depth along forward).
func Cone(radius, angle float32) Shape3DCone returns a 3D shape that emits particles from a disk of radius perpendicular to Direction and directs them outward within a cone of half-angle angle (in radians, clamped to [0, pi/2]).
func Hemisphere(radius float32) Shape3DHemisphere returns a 3D shape that emits particles uniformly throughout the upper hemisphere (along the emitter's Direction) of radius centered on Position.
func Point3D() Shape3DPoint3D returns a 3D shape that emits particles at the emitter's Position.
func Ring3D(radius float32) Shape3DRing3D returns a 3D shape that emits particles uniformly on the circumference of a circle of radius in the plane perpendicular to Direction.
func Sphere(radius float32) Shape3DSphere returns a 3D shape that emits particles uniformly throughout a sphere of radius centered on Position.
func (s Shape3D) String() stringString returns the canonical string name of the 3D shape kind.
type ShapeDoc struct {
// Kind selects the shape: "point", "circle", "ring" or "rect".
Kind string `yaml:"kind,omitempty" schema:"enum=point|circle|ring|rect"`
// Radius is the radius in points for "circle" and "ring" shapes.
Radius float32 `yaml:"radius,omitempty"`
// Width is the width in points for a "rect" shape.
Width float32 `yaml:"width,omitempty"`
// Height is the height in points for a "rect" shape.
Height float32 `yaml:"height,omitempty"`
}ShapeDoc describes a 2D emission shape in YAML.
type SimulationSpace uint8SimulationSpace controls whether particles simulate in world coordinates or emitter-local coordinates.
const (
// SpaceWorld simulates particles in world coordinates so they keep their positions when the emitter moves (default).
SpaceWorld SimulationSpace = iota
// SpaceLocal simulates particles in emitter-local coordinates and transforms them by the emitter's current X, Y, and Rotation at Draw time.
SpaceLocal
)func (s SimulationSpace) String() stringString returns the canonical string name of the simulation space.
type SubEmitterDoc struct {
// Trigger selects which parent particle event fires the burst: "birth", "death" or "collision".
Trigger string `yaml:"trigger,omitempty" schema:"enum=birth|death|collision"`
// BurstCount is how many child particles to emit on each trigger event.
BurstCount int `yaml:"burstCount,omitempty"`
// InheritVelocity multiplies parent velocity added to each spawned child particle.
InheritVelocity float32 `yaml:"inheritVelocity,omitempty"`
// Config configures the child emitter (without a version key).
Config *EmitterFieldsDoc `yaml:"config,omitempty"`
}SubEmitterDoc describes one child burst rule in YAML.
type SubEmitterRule struct {
// Trigger selects when the sub-emitter fires.
Trigger SubEmitterTrigger
// Config configures the child emitter spawned by this rule.
Config Config
// BurstCount is how many child particles to emit on each trigger event; defaults to 1 when <= 0.
BurstCount int
// InheritVelocity adds InheritVelocity * parentVelocity to each spawned child particle's initial velocity.
InheritVelocity float32
}SubEmitterRule spawns a burst of child particles from a parent particle event.
type SubEmitterTrigger uint8SubEmitterTrigger specifies which parent particle lifecycle event fires a SubEmitterRule.
const (
// TriggerOnBirth fires when a parent particle is spawned.
TriggerOnBirth SubEmitterTrigger = iota
// TriggerOnDeath fires when a parent particle expires (or is killed by CollideKill).
TriggerOnDeath
// TriggerOnCollision fires when a parent particle hits a Collider.
TriggerOnCollision
)func (t SubEmitterTrigger) String() stringString returns the canonical string name of the sub-emitter trigger.
type System struct {
// contains filtered or unexported fields
}System manages multiple Emitters (and their sub-emitters and trails) as a single unit stepped by game.Loop.
func NewSystem(emitters ...*Emitter) *SystemNewSystem creates a System pre-populated with any provided emitters.
func (s *System) Clear()Clear clears all live particles from all registered emitters.
func (s *System) Draw(d *core.Drawing)Draw draws all registered emitters into d in registration order.
func (s *System) Emitters() []*EmitterEmitters returns the slice of registered emitters.
func (s *System) Remove(e *Emitter)Remove unregisters an emitter from the system.
func (s *System) TotalCount() intTotalCount returns the total number of live particles across all registered emitters and their sub-emitters.
func (s *System) Update(dt time.Duration)Update advances all registered emitters by dt.
type TileGridCollider struct {
// TileSize is the width and height of one tile in points. Non-positive disables collisions.
TileSize float32
// OriginX and OriginY are the world coordinates of tile (0, 0)'s top-left corner.
OriginX float32
OriginY float32
// SolidAt reports whether the tile at (col, row) is solid.
SolidAt func(col, row int) bool
}TileGridCollider resolves particle collisions against a uniform 2D tile grid via a SolidAt lookup callback.
func (c *TileGridCollider) ResolveParticle(prevX, prevY, x, y, radius float32) (hit bool, hitX, hitY, nx, ny float32)ResolveParticle implements Collider with zero heap allocations.
type Trail struct {
// contains filtered or unexported fields
}Trail builds and draws a smooth 2D ribbon from a sequence of sampled positions.
func NewTrail(cfg TrailConfig) *TrailNewTrail creates a new Trail with the given configuration.
func (t *Trail) AddPoint(x, y float32)AddPoint appends (x, y) to the trail head if it is at least MinDistance from the previous point.
func (t *Trail) Attach(posFn func() (float32, float32))Attach binds a position callback sampled automatically on each Update call. Passing nil detaches any existing callback.
func (t *Trail) Config() TrailConfigConfig returns a copy of the trail's configuration.
func (t *Trail) Draw(d *core.Drawing)Draw builds the ribbon strip along perpendicular normals and draws it into d. Does nothing if fewer than 2 points are active.
func (t *Trail) EvaluateAt(u float32) (width float32, color core.Color)EvaluateAt evaluates the ribbon width and color at normalized parameter u in [0, 1], where 0 is the newest head and 1 is the oldest tail.
func (t *Trail) Follow(x, y float32)Follow records the current position of a tracked object into the trail.
func (t *Trail) PointCount() intPointCount returns the number of active vertices in the trail.
func (t *Trail) Points() []TrailPointPoints returns the active trail vertices from oldest (tail, index 0) to newest (head, last index). The returned slice is backed by internal storage; copy it to retain a snapshot.
func (t *Trail) SetConfig(cfg TrailConfig)SetConfig updates the trail's configuration without clearing live points.
func (t *Trail) Update(dt float32)Update advances all point ages by dt seconds, removes expired points, and samples any attached callback. Non-positive dt does nothing.
type TrailConfig struct {
// MaxPoints caps the number of recorded polyline vertices; defaults to 64 when <= 0.
MaxPoints int
// Lifetime is how long each vertex lives in seconds before expiring; defaults to 0.5 when <= 0.
Lifetime float32
// MinDistance is the minimum distance in points from the newest vertex before appending a new vertex.
// Zero or negative records every distinct point (exact duplicates refresh the newest vertex's age).
MinDistance float32
// Width is the base ribbon width in points; defaults to 4 when <= 0.
Width float32
// WidthCurve scales Width along the trail from head (t=0, newest) to tail (t=1, oldest). Empty keeps 1.
WidthCurve Curve
// ColorGradient evaluates color along the trail from head (t=0, newest) to tail (t=1, oldest).
// When empty, Color is used (defaulting to opaque white when 0).
ColorGradient ColorCurve
// Color is the fallback solid color when ColorGradient is empty; defaults to opaque white when 0.
Color core.Color
// Texture is an optional image mapped across each ribbon segment when non-empty.
Texture core.ImageSource
}TrailConfig configures a 2D ribbon trail.
type TrailDoc struct {
// MaxPoints caps the recorded polyline vertices per trail (defaults to 64 when 0).
MaxPoints int `yaml:"maxPoints,omitempty"`
// Lifetime is how long each trail vertex lives in seconds (defaults to 0.5 when 0).
Lifetime float32 `yaml:"lifetime,omitempty"`
// MinDistance is the minimum spacing in points between consecutive trail vertices.
MinDistance float32 `yaml:"minDistance,omitempty"`
// Width is the base ribbon width in points (defaults to 4 when 0).
Width float32 `yaml:"width,omitempty"`
// WidthCurve scales Width from head (t=0) to tail (t=1).
WidthCurve []FloatStopDoc `yaml:"widthCurve,omitempty"`
// ColorGradient evaluates color from head (t=0) to tail (t=1).
ColorGradient []ColorStopDoc `yaml:"colorGradient,omitempty"`
// Color is the fallback solid hex color "#rrggbb" or "#rrggbbaa" when colorGradient is empty.
Color string `yaml:"color,omitempty"`
// TextureURI is an optional image URI mapped across trail segments.
TextureURI string `yaml:"textureURI,omitempty"`
}TrailDoc describes per-particle ribbon trail settings in YAML.
type TrailManager struct {
// contains filtered or unexported fields
}TrailManager updates and draws a collection of trails (such as moving sprite or projectile ribbons).
func NewTrailManager() *TrailManagerNewTrailManager creates an empty TrailManager.
func (m *TrailManager) Add(cfg TrailConfig) *TrailAdd creates a new Trail with cfg, registers it with the manager, and returns it.
func (m *TrailManager) AddTrail(tr *Trail)AddTrail registers an existing Trail with the manager.
func (m *TrailManager) Clear()Clear removes all points from all managed trails without unregistering them.
func (m *TrailManager) Count() intCount returns the number of trails registered with the manager.
func (m *TrailManager) Draw(d *core.Drawing)Draw draws all managed trails into d in registration order.
func (m *TrailManager) Remove(tr *Trail)Remove unregisters tr from the manager.
func (m *TrailManager) Trails() []*TrailTrails returns the slice of managed trails.
func (m *TrailManager) Update(dt float32)Update advances all managed trails by dt seconds.
type TrailPoint struct {
X, Y float32
Age float32
Length float32
}TrailPoint is one recorded vertex along a Trail polyline.