Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,59 @@ export default defineClientPlugin({
})
```

### Particle effects

A plugin can add particle effects from `setup` with `ctx.registerParticle`. They show in the editor's Particles tab with the plugin's name, can be placed in scenes (a `ParticleEffect` object) and are played by logic graphs (Spawn Effect, Play / Stop / Burst Effect). Their name in scene files and graphs is `<package>:<name>`, which `registerParticle` returns. Build them from the engine's emitters: `PooledEmitter` simulates particles with gravity, drag, wind, bouncing and settling, and only needs to know where each one starts. Load textures from the plugin's assets with `ctx.assetUrl()`. Particle effects only exist on the client:

```ts
// client.ts
import type { PooledParticle } from '@mavonengine/core/Particles/System/PooledEmitter'
import type { Vector3 } from 'three'
import ParticleEffect from '@mavonengine/core/Particles/System/ParticleEffect'
import PooledEmitter from '@mavonengine/core/Particles/System/PooledEmitter'
import { defineClientPlugin } from '@mavonengine/core/Plugins/types'

class HailEmitter extends PooledEmitter {
constructor(position: Vector3) {
super(position, {
maxParticles: 400,
rate: 120,
lifetime: [4, 4],
size: [0.05, 0.05],
color: [0xE8F0FF, 0xE8F0FF],
gravity: 9.8,
bounce: 0.3,
restFor: [1, 2],
})
}

protected spawn(particle: PooledParticle) {
particle.position.set((Math.random() - 0.5) * 20, 12, (Math.random() - 0.5) * 20)
}
}

class Hail extends ParticleEffect {
constructor(position: Vector3) {
super()
this.emitters.push(new HailEmitter(position))
}
}

export default defineClientPlugin({
setup(ctx) {
// 'my-custom-plugin:Hail'
ctx.registerParticle('Hail', {
preview: {
cameraPosition: [0, 4, 12],
cameraTarget: [0, 2, 0]
},
spawn: position => new Hail(position),
icon: ctx.assetUrl('icons/hail.svg'),
})
},
})
```

### Brushes

The editor's Brushes panel comes with sculpt brushes (raise, lower, smooth, flatten, noise) for a `Terrain`, paint brushes for its material layers, and scatter brushes that paint models onto anything. A plugin can add to both kinds.
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/Editor/EditorHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export type PropertyField
| { type: 'checkbox', label: string, getValue(): boolean, setValue(v: boolean): void }
/** A choice from a list. `refresh` updates the options, called when the field shows */
| { type: 'select', label: string, options(): { value: string, label: string }[], getValue(): string, setValue(v: string): void, refresh?(): Promise<unknown> }
/** A row of buttons, for actions rather than values (Play, Stop...) */
| { type: 'buttons', label: string, buttons: { label: string, onClick(): void }[] }
/** A small looping preview of the registered particle effect `getValue()` names, by itself */
| { type: 'particlePreview', label: string, getValue(): string }

export interface EditorHelperAttachment {
addBindings?(folder: ContainerApi): void
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/Game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Camera from './Camera'
import { registerTslNode } from './Graph/Material/tslNodes'
import { pluginNodeType, registerNode } from './Graph/NodeRegistry'
import InputManager from './InputManager'
import { pluginParticleName, registerParticle } from './Particles/System/ParticlePreviewRegistry'
import ParticleSystem from './Particles/System/ParticleSystem'
import { onPluginMessage } from './Plugins/devMessages'
import PluginHost from './Plugins/PluginHost'
Expand Down Expand Up @@ -219,6 +220,11 @@ export default class Game extends BaseGame {
assetUrl: path => `${pluginAssetBase(loaded.package)}${path.replace(LEADING_SLASHES_RE, '')}`,
registerPrefab: prefab => registerPrefab({ ...prefab, plugin: loaded.package }),
registerBrush: brush => registerBrush({ ...brush, plugin: loaded.package }),
registerParticle: (name, entry) => {
const key = pluginParticleName(loaded.package, name)
registerParticle(key, { label: name, ...entry, plugin: loaded.package })
return key
},
registerNode: (definition, tsl) => {
const type = pluginNodeType(loaded.package, definition.type)
registerNode({ ...definition, type, plugin: loaded.package })
Expand Down
163 changes: 163 additions & 0 deletions packages/core/src/Graph/Logic/GraphPreview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import type { Object3D } from 'three'
import type { ParticleHost } from '../../Particles/ParticleEffectObject'
import type { GraphEntity } from '../NodeRegistry'
import type { GraphData, GraphValue } from '../types'
import { BoxGeometry, EdgesGeometry, Group, LineBasicMaterial, LineSegments, Vector3 } from 'three'
import { ParticleEffectObject, PARTICLES_FINISHED, spawnedEffectId } from '../../Particles/ParticleEffectObject'
import { getParticleNames } from '../../Particles/System/ParticlePreviewRegistry'
import { GraphRuntime } from './GraphRuntime'

/** The id Self has in a preview */
export const PREVIEW_SELF = 'self'

export interface GraphPreviewOptions {
/** The registered particle effect Self is. Without one Self is a box marker */
selfEffect?: string
/** Where its Log nodes write */
log?(message: string): void
/** Told each step as it runs */
onStep?(node: string): void
}

/** Reads and moves the Object3D `target()` gives at the time */
function objectEntity(id: string, target: () => Object3D): GraphEntity {
return {
id,
getPosition: () => target().position.toArray(),
setPosition: ([x = 0, y = 0, z = 0]) => {
target().position.set(x, y, z)
},
getRotation: () => {
const { x, y, z } = target().rotation
return [x, y, z]
},
setRotation: ([x = 0, y = 0, z = 0]) => {
target().rotation.set(x, y, z)
},
getScale: () => target().scale.toArray(),
setScale: ([x = 1, y = 1, z = 1]) => {
target().scale.set(x, y, z)
},
}
}

/**
* A logic graph running in a world of its own, for the graph editor: what it spawns and moves lives under `root`,
* which the preview draws, so the scene stays as it is. Self is a particle effect or a marker; the scene's objects
* aren't there, and messages it sends only reach itself.
*/
export class GraphPreview {
/** What the preview draws */
readonly root = new Group()
runtime?: GraphRuntime
private readonly effects = new Map<string, ParticleEffectObject>()
private readonly marker: LineSegments
private self: Object3D

constructor() {
const box = new BoxGeometry(0.6, 0.6, 0.6)
this.marker = new LineSegments(new EdgesGeometry(box), new LineBasicMaterial({ color: 0xFFAA00 }))
box.dispose()
this.self = this.marker
}

private readonly particles: ParticleHost = {
find: id => this.effects.get(id),
spawn: (effect, [x = 0, y = 0, z = 0], burst) => {
if (!getParticleNames().includes(effect))
return undefined
const id = spawnedEffectId(effect, id => this.effects.has(id))
const object = this.addEffect(id, effect, new Vector3(x, y, z), burst > 0)
object.spawned = true
if (burst > 0)
object.burst(burst)
return object
},
}

private addEffect(id: string, effect: string, position: Vector3, once: boolean): ParticleEffectObject {
const object = new ParticleEffectObject(id, { effect, playing: !once }, position, {
parent: this.root,
onFinished: finished => this.runtime?.trigger(PARTICLES_FINISHED, { effect: finished.id }),
removeWhenFinished: once,
})
// Away from the scene: its colliders aren't here
if (object.effect)
object.effect.collideWithScene = false
this.effects.set(id, object)
return object
}

/** Run `graph` from the start, in a fresh world. Throws when it has problems, as GraphRuntime does */
run(graph: GraphData, options: GraphPreviewOptions = {}) {
// Checked before anything is torn down, so a broken graph leaves the last one running
const runtime = new GraphRuntime(graph, {
// Whatever Self is once the world below is set up
self: objectEntity(PREVIEW_SELF, () => this.self),
find: (id) => {
const object = this.effects.get(id)
return object
? objectEntity(id, () => object.instance)
: undefined
},
services: { particles: this.particles },
log: options.log,
onStep: options.onStep,
})

this.clear()
if (options.selfEffect && getParticleNames().includes(options.selfEffect)) {
const object = this.addEffect(PREVIEW_SELF, options.selfEffect, new Vector3(), false)
this.self = object.instance
}
else {
this.self = this.marker
this.root.add(this.marker)
}

this.runtime = runtime
runtime.start()
}

/** Fire `event` in the graph, as the game would: `keydown` with `{ code }`, a plugin's own... */
trigger(event: string, payload: Record<string, GraphValue> = {}) {
this.runtime?.trigger(event, payload)
}

/** What a Send Message node would send */
message(name: string, value: GraphValue = 0) {
this.runtime?.message(name, value)
}

/** Move time on: the graph, then the effects */
update(delta: number) {
this.runtime?.update(delta)
for (const [id, object] of this.effects) {
if (!object.garbageCollect)
object.update(delta)
if (object.garbageCollect)
this.effects.delete(id)
}
}

/** How many effects are out, Self's included */
get effectCount(): number {
return this.effects.size
}

private clear() {
this.effects.forEach(object => object.destroy())
this.effects.clear()
this.marker.position.set(0, 0, 0)
this.marker.rotation.set(0, 0, 0)
this.marker.scale.set(1, 1, 1)
this.marker.removeFromParent()
}

dispose() {
this.clear()
this.runtime = undefined
this.marker.geometry.dispose()
;(this.marker.material as LineBasicMaterial).dispose()
}
}
3 changes: 3 additions & 0 deletions packages/core/src/Graph/Logic/GraphRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export interface GraphRuntimeOptions {
emit?(name: string, value: GraphValue): void
/** Told each step as it runs, for debugging */
onStep?(node: string): void
/** What the graph's nodes act on instead of the game's own, by name, see `NodeEvalContext.services` */
services?: Record<string, unknown>
/** The most steps one event may run, so a loop in the exec edges can't hang the game. Default 10 000 */
maxSteps?: number
}
Expand Down Expand Up @@ -141,6 +143,7 @@ export class GraphRuntime {
? this.options.find?.(target)
: self,
variables: this.variables,
services: this.options.services,
}
}

Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/Graph/NodeRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ export interface NodeEvalContext {
entity?(id: string): GraphEntity | undefined
/** The graph's variables, in a logic graph */
variables?: Map<string, GraphValue>
/**
* What the side running a logic graph offers its nodes, by name (e.g. `particles`). Unset in the scene, where nodes
* use the game's own; a preview sets its own so the graph acts on the preview's world instead
*/
services?: Record<string, unknown>
}

/** What a `run` implementation (a step of a logic graph) gets besides its inputs */
Expand Down
60 changes: 60 additions & 0 deletions packages/core/src/Particles/Effects/Debris.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { Vector3 } from 'three/webgpu'
import type { PooledParticle } from '../System/PooledEmitter'
import { NormalBlending } from 'three/webgpu'
import ParticleEffect from '../System/ParticleEffect'
import { registerParticle } from '../System/ParticlePreviewRegistry'
import PooledEmitter, { randomDirection } from '../System/PooledEmitter'

/**
* Chunks of rock and dirt thrown up, falling and bouncing off whatever they land on (terrain, primitives, scattered
* rocks), rolling to a stop and fading
*/
export class DebrisEmitter extends PooledEmitter {
constructor(position: Vector3) {
super(position, {
maxParticles: 120,
// A handful every so often while it plays; burst it where something hits
repeat: { every: 2.5, count: 20 },
lifetime: [3, 4.5],
size: [0.13, 0.1],
color: [0x7A6A58, 0x5E544A],
fadeIn: 0,
// Solid until the last fifth of its life
fadeOut: 0.2,
gravity: 9.8,
drag: 0.1,
bounce: 0.4,
friction: 0.35,
// Too heavy for the wind
windInfluence: 0,
blending: NormalBlending,
hardness: 0.85,
})
}

protected spawn(particle: PooledParticle): void {
particle.position.set(0, 0.3, 0)
randomDirection(particle.velocity, 1).multiplyScalar(2.5 + Math.random() * 3.5)
// Thrown up more than out
particle.velocity.y = Math.abs(particle.velocity.y) + 2
}
}

const preview = {
cameraPosition: [0, 2.5, 7] as [number, number, number],
cameraTarget: [0, 0.8, 0] as [number, number, number],
}

registerParticle('Debris', {
preview,
spawn: position => new Debris(position),
icon: `<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><g fill="#8a7a66"><path d="M14 44 L20 36 L28 40 L26 48 L16 50 Z"/><path d="M36 22 L44 18 L48 26 L42 31 L35 29 Z"/><path d="M40 46 L46 42 L52 46 L49 52 L41 52 Z"/><path d="M24 16 L29 14 L31 19 L26 21 Z"/></g><path d="M6 54 H58" stroke="#8a8f98" stroke-width="2"/><path d="M28 34 Q32 22 36 26" stroke="#c9bba6" stroke-width="1.5" fill="none" stroke-dasharray="2 3"/></svg>`,
})

/** Rocks and dirt thrown up and bouncing off the ground and what's on it: playing, a handful every few seconds */
export default class Debris extends ParticleEffect {
constructor(position: Vector3) {
super()
this.emitters.push(new DebrisEmitter(position))
}
}
53 changes: 53 additions & 0 deletions packages/core/src/Particles/Effects/DustPuff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { Vector3 } from 'three/webgpu'
import type { PooledParticle } from '../System/PooledEmitter'
import { NormalBlending } from 'three/webgpu'
import ParticleEffect from '../System/ParticleEffect'
import { registerParticle } from '../System/ParticlePreviewRegistry'
import PooledEmitter from '../System/PooledEmitter'

/** A ring of dust thrown out along the ground, slowing, spreading and settling */
export class DustEmitter extends PooledEmitter {
constructor(position: Vector3) {
super(position, {
maxParticles: 120,
// A puff every so often while it plays; burst it for one where something lands
repeat: { every: 1.6, count: 24 },
lifetime: [1, 2],
size: [0.35, 1.6],
color: [0xA0907A, 0x8C806E],
opacity: 0.45,
fadeIn: 0.08,
gravity: 0.4,
drag: 2.8,
windInfluence: 1,
blending: NormalBlending,
hardness: 0,
})
}

protected spawn(particle: PooledParticle): void {
const angle = Math.random() * Math.PI * 2
const out = 1.2 + Math.random() * 1.8
particle.position.set(Math.cos(angle) * 0.2, 0.1, Math.sin(angle) * 0.2)
particle.velocity.set(Math.cos(angle) * out, 0.3 + Math.random() * 0.6, Math.sin(angle) * out)
}
}

const preview = {
cameraPosition: [0, 1.6, 5] as [number, number, number],
cameraTarget: [0, 0.3, 0] as [number, number, number],
}

registerParticle('Dust Puff', {
preview,
spawn: position => new DustPuff(position),
icon: `<svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><g fill="#b5a58c"><circle cx="20" cy="42" r="9" opacity="0.7"/><circle cx="32" cy="38" r="11" opacity="0.85"/><circle cx="45" cy="42" r="9" opacity="0.7"/><circle cx="11" cy="47" r="5" opacity="0.5"/><circle cx="54" cy="47" r="5" opacity="0.5"/></g><path d="M6 52 H58" stroke="#8a8f98" stroke-width="2"/></svg>`,
})

/** A puff of dust where something lands, falls or skids: puffing every so often while it plays */
export default class DustPuff extends ParticleEffect {
constructor(position: Vector3) {
super()
this.emitters.push(new DustEmitter(position))
}
}
Loading