Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(particles): GPU particles collide with scene depth and distance functions, fire sub-emitters from an event buffer, and drag trails

yhh3410c419b37f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fcdb0cbb4..f956041e3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **GPU particles can hit things, tell each other, and drag trails.** `collisionMode: Depth` collides with what the camera sees, `Sdf` with `ParticleCollider` spheres, boxes and capsules that need no physics (and run on the CPU too). A GPU emitter's births, deaths and collisions go to a buffer: a `gpuSimulation` child spawns from it in its own kernel, with no trip to the CPU, and `collisionEvents` read back to the game a frame or two late. `trailEnabled` now works on the GPU.
- **Plants can be touched, felled and harvested.** A `FoliageContact` on a character parts `Foliage` grass around it, on both backends. A kind in `PlacedFoliage` or `WorldRules.plants` with an `interaction` leans away with any material, becomes an entity with a physics capsule while something is near, and can be damaged, felled and harvested through `PlantInteractionRes`, with stumps, regrowth and `saveState` / `loadState`; what became of a plant outlasts its chunk.
- **A side-on character comes ready to run and jump.** `PlatformerController2D` beside a `CharacterController2D` reads the keyboard or a game's input, and has coyote time, a jump buffer, jump cut, air jumps and a drop through one-way platforms. `CharacterController2D` gains `stepHeight`, `followPlatform` (it rides what it stands on, sideways too), `dynamicBodies` (block, push or ignore them), `constantSlopeSpeed` and `dropThrough`, and reports `floorEntity` and `floorVelocity`. The 2D platformer template and example use it.
- **A 2D character can be rigged in the editor, with no other program.** Right-click an image to create an `.esrig`, then cut it into parts, drag out bones, cover the parts with a mesh, bind by distance and paint weights with add, remove and smooth brushes, and push vertices into named deforms, all on one canvas that can try poses without changing the rig. Saving writes an `.esmesh` and an `.esprefab` beside it, so a built game carries no authoring data. Bones are ordinary entities, so clips, the Animator's blends, layers and masks all reach them, and a deform is a `MeshMorph` weight clips can key.
diff --git a/desktop b/desktop
index 0603d1b68..9f96242b9 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 0603d1b68d8e6355dc556e6e693ce1f3f3b37111
+Subproject commit 9f96242b9777560eb48a1921b56a8c0d9745c1da
diff --git a/docs/astro/src/content/docs/world/particles.mdx b/docs/astro/src/content/docs/world/particles.mdx
index 582c1fa6b..20b550e78 100644
--- a/docs/astro/src/content/docs/world/particles.mdx
+++ b/docs/astro/src/content/docs/world/particles.mdx
@@ -231,7 +231,7 @@ Shown once `collisionEnabled` is on. See [Floor collision](#floor-collision) and
| Property | Type | Default | Description |
|---|---|---|---|
| `collisionEnabled` | boolean | `false` | Turn collision on. |
-| `collisionMode` | `ParticleCollisionMode` | `Floor` | `Floor` (a horizontal plane), `Physics2D` or `Physics3D` (cast through the physics world). |
+| `collisionMode` | `ParticleCollisionMode` | `Floor` | `Floor` (a horizontal plane), `Physics2D` or `Physics3D` (cast through the physics world, CPU only), `Depth` (what the camera sees, GPU only) or `Sdf` (every `ParticleCollider`). See [GPU collision](#gpu-collision). |
| `collisionFloor` | number | `0` | World height of the floor plane. |
| `collisionBounce` | number | `0.5` | 0 = stop dead, 1 = fully elastic. |
| `collisionFriction` | number | `0.1` | Horizontal speed shed per bounce, 0..1. |
@@ -242,6 +242,7 @@ Shown once `collisionEnabled` is on. See [Floor collision](#floor-collision) and
| `collisionFallback` | `ParticleCollisionFallback` | `Floor` | `Floor` or `Skip`, when physics is unavailable, the budget is spent or a particle is too far away. |
| `collisionEvents` | boolean | `false` | Emit `ParticleCollisionEvent`s. |
| `collisionEventBudget` | number | `32` | Most events this emitter raises per update, 0..1024. |
+| `collisionThickness` | number | `30` | `Depth` mode: how far behind a visible surface a particle still counts as having hit it. Past this it has gone round the back. |
## Emitter shapes
@@ -615,12 +616,12 @@ world.insert(entity, ParticleEmitter, {
});
```
-It runs the same emitter, with the same shapes, curl noise, force fields (the first eight), gravity, damping, floor plane,
-color / size / speed over life and sprite sheets. Each emitter draws from a fixed seed of its own, so a scene replays the same
-particles. What it does not do:
+It runs the same emitter, with the same shapes, curl noise, force fields (the first eight), gravity, damping, color / size /
+speed over life, sprite sheets, sub-emitters and trails. Each emitter draws from a fixed seed of its own, so a scene replays the
+same particles. What it does not do:
-- **No sub-emitters, no per-particle trails, no scene-query collision** (`Physics2D` / `Physics3D`). A GPU emitter collides
- with the floor plane only.
+- **No scene-query collision** (`Physics2D` / `Physics3D`). A kernel cannot ask the physics world, so these fall back as
+ `collisionFallback` says. Use [`Depth` or `Sdf`](#gpu-collision) instead.
- **Not sorted.** An `Additive` or cut-out look is exact; a deep pile of `Normal`-blended particles draws in slot order.
- **Not in a UI tree.** An emitter under a `Canvas` draws through the screen overlay, which the kernel does not feed; leave it
on the CPU.
@@ -630,6 +631,61 @@ It needs a device with compute — WebGPU. On WebGL2 and in mini-game runtimes t
20,000 particles**, so a scene built for a million still plays, thinner. Design the look to survive the cap if a platform
without WebGPU matters to you.
+### GPU collision
+
+Two collision modes are made for a kernel, since neither asks anything per particle that a million particles cannot afford.
+
+**`Depth` collides with what the camera sees.** The frame's depth is copied after the scene is drawn, and next frame the kernel
+reprojects each particle into it with the view that saw it. A particle just behind a surface has hit that surface; one further behind than
+`collisionThickness` has gone round the back, and passes.
+
+```ts
+world.insert(entity, ParticleEmitter, {
+ gpuSimulation: true,
+ collisionEnabled: true,
+ collisionMode: ParticleCollisionMode.Depth,
+ collisionThickness: 50,
+ collisionBounce: 0.3,
+});
+```
+
+It needs no setup and costs one copy a frame, whatever the scene holds, and it has the limits of the picture it reads. Only what the camera
+sees and what writes depth counts: nothing off screen stops a particle, a surface turned away from the camera does not exist, a 2D scene of sprites
+writes none, and a particle behind the front of a box meets the front rather than the top. It is on a frame's delay. The one camera that drew first
+is the one that counts. For a scene that must hold whatever the camera does, use `Sdf`.
+
+**`Sdf` collides with shapes you place.** A **`ParticleCollider`** is a sphere, box or capsule that draws nothing and needs no physics. The emitter bounces off the first 64
+in the scene that share a bit of `collisionMask` with its `mask`. `inverted` keeps particles in instead of out: a jar, a dome round a spell.
+
+```ts
+const ball = world.spawn();
+world.insert(ball, Transform, { position: { x: 0, y: 100, z: 0 } });
+world.insert(ball, ParticleCollider, { shape: ParticleColliderShape.Sphere, radius: 120 });
+```
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `shape` | `ParticleColliderShape` | `Sphere` | `Sphere`, `Box` or `Capsule`. A box and a capsule turn with the entity; a capsule's axis is its up. |
+| `radius` | number | `50` | A sphere's radius, and a capsule's round its axis. Scaled by the entity's largest scale. |
+| `halfHeight` | number | `50` | How far a capsule's axis runs each way from its centre. |
+| `halfExtents` | Vec3 | `50, 50, 50` | A box's half size. |
+| `inverted` | boolean | `false` | Keeps particles in rather than out. |
+| `mask` | bitmask | all (`65535`) | Which emitters it stops: one that shares a bit in its `collisionMask`. |
+
+Every particle asks every collider its mask lets through, so a million particles against many colliders is a real cost; keep them few. `Sdf` also runs on the CPU, so the look survives a device with no compute. `Depth` does not: on WebGL2 it does what `collisionFallback` says.
+
+A particle has no size to either mode: it is a point, stopped where its centre meets the surface.
+
+### GPU events, sub-emitters and trails
+
+A kernel appends what happens to a buffer: each birth, death or collision the emitter's `subEmitterTrigger` asks for, or each collision when `collisionEvents` is on. That buffer is what the other two read.
+
+**A sub-emitter runs with no trip to the CPU.** Give a GPU emitter a `subEmitter` that is also `gpuSimulation`, and its kernel lights slots straight from the parent's events, `burstCount` each, at the event's place, keeping `subEmitterInheritVelocity` of its speed. A parent runs before its child in the frame, so a spark is born where its drop died. At most 4,096 events an emitter a frame are kept; more are dropped. A child on the CPU is not fed by a GPU parent.
+
+**The game hears collisions a frame or two late.** With `collisionEvents` on, `ParticleCollisionEvent`, `collisionStats` and the rest read as they do for any other collision, in the same units, once the GPU hands them back. `collisionEventBudget` is how many are read back a time, and `hits` counts the rest. Reading back is the one thing here that costs a trip to the CPU, so leave it off unless the game needs to know.
+
+**Trails** use the same `trailEnabled`, `trailWidth`, `trailPoints` and `trailMinDistance`. Each particle's path is kept in a buffer of its own and drawn as quads along it, narrowing and fading from the head. They cost memory for every slot whether alive or not: `maxParticles` x `trailPoints` x 60 bytes, so 100,000 particles with 12 points is 72 MB. Each piece turns to face the camera that first drew it that frame, so a second camera sees them slightly edge on.
+
## Performance & best practices
- **Budget `maxParticles`.** It's a fixed pool; size it to the worst case, not
diff --git a/docs/astro/src/content/docs/zh-cn/world/particles.mdx b/docs/astro/src/content/docs/zh-cn/world/particles.mdx
index 31a08aa47..f203ef470 100644
--- a/docs/astro/src/content/docs/zh-cn/world/particles.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/particles.mdx
@@ -566,7 +566,7 @@ world.insert(entity, ParticleEmitter, {
它跑的是同一个发射器:形状、旋度噪声、力场(前八个)、重力、阻尼、地面平面、颜色 / 尺寸 / 速度随生命曲线和精灵表都一样。
每个发射器用自己固定的种子,所以场景每次回放的粒子相同。它不做的事:
-- **没有子发射器、逐粒子拖尾和场景查询碰撞**(`Physics2D` / `Physics3D`)。GPU 发射器只和地面平面碰撞。
+- **没有场景查询碰撞**(`Physics2D` / `Physics3D`)。kernel 问不了物理世界,这两种模式会按 `collisionFallback` 处理。请改用 [`Depth` 或 `Sdf`](#gpu-碰撞)。
- **不排序。** `Additive` 或镂空的效果是精确的;一大堆 `Normal` 混合的粒子按槽位顺序绘制。
- **不能放在 UI 树里。** `Canvas` 下的发射器走屏幕叠加层绘制,kernel 不会喂给它;请留在 CPU 上。
- **`Particle.aliveCount` 是上界。** 真实状态在 GPU 里,不做回读。
@@ -574,6 +574,55 @@ world.insert(entity, ParticleEmitter, {
它需要支持 compute 的设备——WebGPU。在 WebGL2 和小游戏运行时里,同一个发射器改在 CPU 上跑,**上限 20,000 个粒子**,
所以为百万粒子做的场景仍能播放,只是更稀。如果在意没有 WebGPU 的平台,请让效果在这个上限下仍然成立。
+### GPU 碰撞
+
+有两种碰撞模式是专门给 kernel 准备的,它们都不需要逐粒子做一百万个粒子负担不起的事。
+
+**`Depth` 和相机看到的东西碰撞。** 场景画完后拷一份这一帧的深度,下一帧 kernel 用当时的相机把每个粒子重投影进去。粒子刚好落在表面后方就算撞上;比 `collisionThickness` 更靠后,说明它已经绕到背面,直接穿过。
+
+```ts
+world.insert(entity, ParticleEmitter, {
+ gpuSimulation: true,
+ collisionEnabled: true,
+ collisionMode: ParticleCollisionMode.Depth,
+ collisionThickness: 50,
+ collisionBounce: 0.3,
+});
+```
+
+它不需要任何设置,每帧只多一次拷贝,和场景内容无关,但也受这张深度图的限制:只有相机看得到、且写入深度的东西才算。屏幕外的东西挡不住粒子,背对相机的面不存在,只有精灵的 2D 场景没有深度,落到盒子正面背后的粒子碰到的是正面而不是顶面。它有一帧延迟,并且只认这一帧最先绘制的相机。不管相机怎样都要挡住的场景,请用 `Sdf`。
+
+**`Sdf` 和你放置的形状碰撞。** **`ParticleCollider`** 是球、盒子或胶囊,不绘制、不需要物理。发射器会被场景里前 64 个与 `collisionMask` 有共同位的碰撞体弹开。`inverted` 让粒子留在里面:罐子、法术的护罩。
+
+```ts
+const ball = world.spawn();
+world.insert(ball, Transform, { position: { x: 0, y: 100, z: 0 } });
+world.insert(ball, ParticleCollider, { shape: ParticleColliderShape.Sphere, radius: 120 });
+```
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `shape` | `ParticleColliderShape` | `Sphere` | `Sphere`、`Box` 或 `Capsule`。盒子和胶囊随实体旋转;胶囊的轴是实体的上方向。 |
+| `radius` | number | `50` | 球的半径,胶囊绕轴的半径。按实体最大的缩放值缩放。 |
+| `halfHeight` | number | `50` | 胶囊的轴从中心向两端延伸的长度。 |
+| `halfExtents` | Vec3 | `50, 50, 50` | 盒子的半尺寸。 |
+| `inverted` | boolean | `false` | 把粒子留在里面,而不是挡在外面。 |
+| `mask` | bitmask | 全部(`65535`) | 挡住哪些发射器:`collisionMask` 有共同位的。 |
+
+每个粒子都要询问所有符合 mask 的碰撞体,所以百万粒子配上很多碰撞体确实有开销,请控制数量。`Sdf` 在 CPU 上也能跑,没有 compute 的设备效果不变;`Depth` 不行,在 WebGL2 上按 `collisionFallback` 处理。
+
+粒子在这两种模式下都没有体积,是一个点,中心碰到表面时停下。
+
+### GPU 事件、子发射器和拖尾
+
+kernel 把发生的事追加到一个缓冲里:`subEmitterTrigger` 要的出生、死亡或碰撞,或开启 `collisionEvents` 时的每次碰撞。下面两个功能都读这个缓冲。
+
+**子发射器全程不经过 CPU。** 给 GPU 发射器设一个同样开启 `gpuSimulation` 的 `subEmitter`,子发射器的 kernel 会直接按父发射器的事件点亮粒子槽,每个事件 `burstCount` 个,位置在事件处,并继承 `subEmitterInheritVelocity` 比例的速度。每帧父发射器先运行,所以火花就诞生在水滴消失的地方。每个发射器每帧最多保留 4096 个事件,多余的丢弃。在 CPU 上运行的子发射器不会被 GPU 父发射器驱动。
+
+**游戏逻辑晚一两帧收到碰撞。** 开启 `collisionEvents` 后,等 GPU 交回数据,`ParticleCollisionEvent`、`collisionStats` 等的读法和其他碰撞一样,单位也相同。`collisionEventBudget` 是每次回读的数量,其余的计入 `hits`。回读是这里唯一需要经过 CPU 的部分,游戏不需要就不要开。
+
+**拖尾** 用同样的 `trailEnabled`、`trailWidth`、`trailPoints` 和 `trailMinDistance`。每个粒子的路径存在单独的缓冲里,沿路径画成四边形,从头部开始逐渐变窄变淡。无论粒子是否存活,每个槽都占内存:`maxParticles` x `trailPoints` x 60 字节,10 万粒子配 12 个点就是 72 MB。每一段都朝向这一帧最先绘制的相机,所以第二个相机看到的会略微偏向侧面。
+
## 性能与最佳实践
- **控制 `maxParticles`。** 它是固定池;按最坏情况定大小,别更高。多个小发射器比一个巨大的
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index f140e0ec0..1942e1b33 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -2,11 +2,11 @@
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
"public": 115,
- "beta": 176,
- "experimental": 2933,
+ "beta": 178,
+ "experimental": 2934,
"deprecated": 3
},
- "total": 3224,
+ "total": 3227,
"subsystems": [
{
"id": "mobile-controls",
@@ -2392,6 +2392,30 @@
"minigame"
]
},
+ {
+ "name": "ParticleColliderData",
+ "kind": "interface",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
+ {
+ "name": "ParticleColliderShape",
+ "kind": "enum",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "ParticleCollisionBudget",
"kind": "interface",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 43708ce40..c394b0d04 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -217,6 +217,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
TilemapLayer: { category: 'world', summary: 'One layer of tiles — its tileset, cell size, orientation, sorting and collision.', doc: 'world/tilemaps', anchor: 'the-tilemaplayer-component', anchorZh: 'tilemaplayer-组件' },
ParticleModelUnits: { category: 'world', summary: 'Imported particle sizes, speeds and gravity in model units; the particle plugin applies the largest absolute world-scale axis to the emitter.', doc: 'world/particles' },
ParticleEmitter: { category: 'world', summary: 'A particle system: emission, lifetime, shape, forces, noise, colour and size over life, sub-emitters and trails.', doc: 'world/particles', anchor: 'particleemitter-reference', anchorZh: 'particleemitter-字段参考' },
+ ParticleCollider: { category: 'world', summary: 'A sphere, box or capsule particles bounce off with no physics, for an emitter in Sdf collision mode, on the GPU or the CPU.', doc: 'world/particles', anchor: 'gpu-collision' },
ParticleForceField: { category: 'world', summary: 'A field that pushes particles around — point, directional, vortex or drag.', doc: 'world/particles', anchor: 'force-fields', anchorZh: '力场' },
Marker: { category: 'world', summary: 'A named point or region of gameplay interest — spawn point, waypoint, trigger zone — queryable like any component.', doc: 'gameplay/markers', anchor: 'marker-component-reference', anchorZh: 'marker-组件参考' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 5c5a021da..171e156c0 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -4101,6 +4101,55 @@
}
]
},
+ {
+ "name": "ParticleCollider",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "shape",
+ "type": "enum",
+ "default": "Sphere",
+ "values": [
+ "Sphere",
+ "Box",
+ "Capsule"
+ ]
+ },
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "50",
+ "range": "≥ 0"
+ },
+ {
+ "key": "halfHeight",
+ "type": "number",
+ "default": "50",
+ "range": "≥ 0"
+ },
+ {
+ "key": "halfExtents",
+ "type": "Vec3",
+ "default": "(50, 50, 50)"
+ },
+ {
+ "key": "inverted",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "mask",
+ "type": "number",
+ "default": "65535",
+ "range": "0–65535, step 1"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "ParticleEmitter",
"source": "cpp",
@@ -4522,7 +4571,9 @@
"values": [
"Floor",
"Physics2D",
- "Physics3D"
+ "Physics3D",
+ "Depth",
+ "Sdf"
]
},
{
@@ -4563,6 +4614,12 @@
"default": "32",
"range": "0–1024, step 1"
},
+ {
+ "key": "collisionThickness",
+ "type": "number",
+ "default": "30",
+ "range": "≥ 0"
+ },
{
"key": "collisionBounce",
"type": "number",
diff --git a/pipeline/src/export/liteEngine.ts b/pipeline/src/export/liteEngine.ts
index b51e80419..23c81d296 100644
--- a/pipeline/src/export/liteEngine.ts
+++ b/pipeline/src/export/liteEngine.ts
@@ -18,7 +18,7 @@ import type { ModuleChoice } from '../project/format';
export const LITE_OMITS: readonly Subsystem[] = ['particles', 'postprocess', 'tilemap'];
/** What a script says when it uses one of them. Broad on purpose: a comment that names one only costs the saving. */
-const SCRIPT_MENTIONS = /\b(ParticleEmitter|ParticleForceField|Particle|ParticlePlugin|PostProcess\w*|Tilemap\w*|TilemapLayer|Tilemaps)\b|esengine\/tilemap/;
+const SCRIPT_MENTIONS = /\b(ParticleEmitter|ParticleForceField|ParticleCollider|Particle|ParticlePlugin|PostProcess\w*|Tilemap\w*|TilemapLayer|Tilemaps)\b|esengine\/tilemap/;
const SCRIPT_EXT = /\.(?:[cm]?[jt]sx?)$/;
const SKIP_DIRS = new Set(['node_modules', '.git', '.esengine', 'dist', 'build', 'out']);
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index d24256b7f..47b466db4 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -53,7 +53,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
importedScene: ['NodeVisibility', 'ParticleModelUnits'],
// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).
characterShaders: [],
- particles: ['ParticleEmitter', 'ParticleForceField'],
+ particles: ['ParticleEmitter', 'ParticleForceField', 'ParticleCollider'],
postprocess: ['PostProcessVolume'],
physics: [
'RigidBody2D', 'BoxCollider2D', 'CircleCollider2D', 'CapsuleCollider2D', 'SegmentCollider2D',
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 812aca794..8ae23fcc9 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 2070 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2071 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"6bf8e03097b59051"
+"5e943b68bf754ab0"
```
## ANCHOR_AXES — const @experimental
@@ -6741,6 +6741,29 @@ static new (module: NonNullable<EngineApi>, registry: CppRegistry, resolve?: Par
static prototype: ParticleAPI
```
+## ParticleCollider — const @experimental
+```
+BuiltinComponentDef<ParticleColliderData>
+```
+
+## ParticleColliderData — interface @beta
+```
+enabled: boolean
+halfExtents: Vec3
+halfHeight: number
+inverted: boolean
+mask: number
+radius: number
+shape: ParticleColliderShape
+```
+
+## ParticleColliderShape — enum @beta
+```
+Box = 1
+Capsule = 2
+Sphere = 0
+```
+
## ParticleCollisionBudget — interface @beta
```
events: number
@@ -6777,9 +6800,11 @@ Skip = 1
## ParticleCollisionMode — enum @beta
```
+Depth = 3
Floor = 0
Physics2D = 1
Physics3D = 2
+Sdf = 4
```
## ParticleCollisionStats — interface @beta
@@ -6833,6 +6858,7 @@ collisionMask: number
collisionMaxDistance: number
collisionMode: ParticleCollisionMode
collisionQueryBudget: number
+collisionThickness: number
colorEasing: ParticleEasing
colorGradient: { stops: { t: number; color: Color; }[]; }
damping: number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 811feec3f..d7a328b30 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,11 +1,11 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 169 beta · 2089 experimental · 3 deprecated
+Symbols: 115 public · 171 beta · 2090 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"6bf8e03097b59051"
+"5e943b68bf754ab0"
```
## ANCHOR_AXES — const @experimental
@@ -6947,6 +6947,29 @@ static new (module: NonNullable<EngineApi>, registry: CppRegistry, resolve?: Par
static prototype: ParticleAPI
```
+## ParticleCollider — const @experimental
+```
+BuiltinComponentDef<ParticleColliderData>
+```
+
+## ParticleColliderData — interface @beta
+```
+enabled: boolean
+halfExtents: Vec3
+halfHeight: number
+inverted: boolean
+mask: number
+radius: number
+shape: ParticleColliderShape
+```
+
+## ParticleColliderShape — enum @beta
+```
+Box = 1
+Capsule = 2
+Sphere = 0
+```
+
## ParticleCollisionBudget — interface @beta
```
events: number
@@ -6983,9 +7006,11 @@ Skip = 1
## ParticleCollisionMode — enum @beta
```
+Depth = 3
Floor = 0
Physics2D = 1
Physics3D = 2
+Sdf = 4
```
## ParticleCollisionStats — interface @beta
@@ -7039,6 +7064,7 @@ collisionMask: number
collisionMaxDistance: number
collisionMode: ParticleCollisionMode
collisionQueryBudget: number
+collisionThickness: number
colorEasing: ParticleEasing
colorGradient: { stops: { t: number; color: Color; }[]; }
damping: number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 7150b9fcd..3900405d2 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 166 beta · 2069 experimental · 3 deprecated
+Symbols: 115 public · 168 beta · 2070 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6736,6 +6736,29 @@ static new (module: NonNullable<EngineApi>, registry: CppRegistry, resolve?: Par
static prototype: ParticleAPI
```
+## ParticleCollider — const @experimental
+```
+BuiltinComponentDef<ParticleColliderData>
+```
+
+## ParticleColliderData — interface @beta
+```
+enabled: boolean
+halfExtents: Vec3
+halfHeight: number
+inverted: boolean
+mask: number
+radius: number
+shape: ParticleColliderShape
+```
+
+## ParticleColliderShape — enum @beta
+```
+Box = 1
+Capsule = 2
+Sphere = 0
+```
+
## ParticleCollisionBudget — interface @beta
```
events: number
@@ -6772,9 +6795,11 @@ Skip = 1
## ParticleCollisionMode — enum @beta
```
+Depth = 3
Floor = 0
Physics2D = 1
Physics3D = 2
+Sdf = 4
```
## ParticleCollisionStats — interface @beta
@@ -6828,6 +6853,7 @@ collisionMask: number
collisionMaxDistance: number
collisionMode: ParticleCollisionMode
collisionQueryBudget: number
+collisionThickness: number
colorEasing: ParticleEasing
colorGradient: { stops: { t: number; color: Color; }[]; }
damping: number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9fc6e9490..efdee775a 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 2091 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2092 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7032,6 +7032,29 @@ static new (module: NonNullable<EngineApi>, registry: CppRegistry, resolve?: Par
static prototype: ParticleAPI
```
+## ParticleCollider — const @experimental
+```
+BuiltinComponentDef<ParticleColliderData>
+```
+
+## ParticleColliderData — interface @beta
+```
+enabled: boolean
+halfExtents: Vec3
+halfHeight: number
+inverted: boolean
+mask: number
+radius: number
+shape: ParticleColliderShape
+```
+
+## ParticleColliderShape — enum @beta
+```
+Box = 1
+Capsule = 2
+Sphere = 0
+```
+
## ParticleCollisionBudget — interface @beta
```
events: number
@@ -7068,9 +7091,11 @@ Skip = 1
## ParticleCollisionMode — enum @beta
```
+Depth = 3
Floor = 0
Physics2D = 1
Physics3D = 2
+Sdf = 4
```
## ParticleCollisionStats — interface @beta
@@ -7124,6 +7149,7 @@ collisionMask: number
collisionMaxDistance: number
collisionMode: ParticleCollisionMode
collisionQueryBudget: number
+collisionThickness: number
colorEasing: ParticleEasing
colorGradient: { stops: { t: number; color: Color; }[]; }
damping: number
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index f1ff37bd9..079a0e890 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -44,6 +44,7 @@ addMeshRenderer: (entity: Entity, component: MeshRenderer) => void
addMeshSkin: (entity: Entity, component: MeshSkin) => void
addOccluder: (entity: Entity, component: Occluder) => void
addParent: (entity: Entity, component: Parent) => void
+addParticleCollider: (entity: Entity, component: ParticleCollider) => void
addParticleEmitter: (entity: Entity, component: ParticleEmitter) => void
addParticleForceField: (entity: Entity, component: ParticleForceField) => void
addPlanarReflection: (entity: Entity, component: PlanarReflection) => void
@@ -106,6 +107,7 @@ getMeshRenderer: (entity: Entity) => MeshRenderer
getMeshSkin: (entity: Entity) => MeshSkin
getOccluder: (entity: Entity) => Occluder
getParent: (entity: Entity) => Parent
+getParticleCollider: (entity: Entity) => ParticleCollider
getParticleEmitter: (entity: Entity) => ParticleEmitter
getParticleForceField: (entity: Entity) => ParticleForceField
getPlanarReflection: (entity: Entity) => PlanarReflection
@@ -162,6 +164,7 @@ hasMeshRenderer: (entity: Entity) => boolean
hasMeshSkin: (entity: Entity) => boolean
hasOccluder: (entity: Entity) => boolean
hasParent: (entity: Entity) => boolean
+hasParticleCollider: (entity: Entity) => boolean
hasParticleEmitter: (entity: Entity) => boolean
hasParticleForceField: (entity: Entity) => boolean
hasPlanarReflection: (entity: Entity) => boolean
@@ -221,6 +224,7 @@ removeMeshRenderer: (entity: Entity) => void
removeMeshSkin: (entity: Entity) => void
removeOccluder: (entity: Entity) => void
removeParent: (entity: Entity) => void
+removeParticleCollider: (entity: Entity) => void
removeParticleEmitter: (entity: Entity) => void
removeParticleForceField: (entity: Entity) => void
removePlanarReflection: (entity: Entity) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 79f9c47b5..911420bd4 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 2082 experimental · 3 deprecated
+Symbols: 115 public · 166 beta · 2083 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6743,6 +6743,29 @@ static new (module: NonNullable<EngineApi>, registry: CppRegistry, resolve?: Par
static prototype: ParticleAPI
```
+## ParticleCollider — const @experimental
+```
+BuiltinComponentDef<ParticleColliderData>
+```
+
+## ParticleColliderData — interface @beta
+```
+enabled: boolean
+halfExtents: Vec3
+halfHeight: number
+inverted: boolean
+mask: number
+radius: number
+shape: ParticleColliderShape
+```
+
+## ParticleColliderShape — enum @beta
+```
+Box = 1
+Capsule = 2
+Sphere = 0
+```
+
## ParticleCollisionBudget — interface @beta
```
events: number
@@ -6779,9 +6802,11 @@ Skip = 1
## ParticleCollisionMode — enum @beta
```
+Depth = 3
Floor = 0
Physics2D = 1
Physics3D = 2
+Sdf = 4
```
## ParticleCollisionStats — interface @beta
@@ -6835,6 +6860,7 @@ collisionMask: number
collisionMaxDistance: number
collisionMode: ParticleCollisionMode
collisionQueryBudget: number
+collisionThickness: number
colorEasing: ParticleEasing
colorGradient: { stops: { t: number; color: Color; }[]; }
damping: number
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index d197fc768..210c922f9 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -173,6 +173,9 @@ export {
ParticleRenderMode,
type ParticleEmitterData,
ParticleForceField,
+ ParticleCollider,
+ ParticleColliderShape,
+ type ParticleColliderData,
ForceFieldType,
type ParticleForceFieldData,
PostProcessVolume,
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 6489dce63..959227c6c 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -1301,6 +1301,54 @@ export function createOccluderData(): OccluderPtrData {
};
}
+export interface ParticleColliderPtrData {
+ shape: number;
+ radius: number;
+ halfHeight: number;
+ halfExtents: Vec3;
+ inverted: boolean;
+ mask: number;
+ enabled: boolean;
+}
+
+export function fillParticleCollider(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: ParticleColliderPtrData,
+): void {
+ out.shape = u32[ptr >> 2] | 0;
+ out.radius = f32[(ptr + 4) >> 2];
+ out.halfHeight = f32[(ptr + 8) >> 2];
+ const halfExtents_ = out.halfExtents; halfExtents_.x = f32[(ptr + 12) >> 2]; halfExtents_.y = f32[((ptr + 12) >> 2) + 1]; halfExtents_.z = f32[((ptr + 12) >> 2) + 2];
+ out.inverted = u8[ptr + 24] !== 0;
+ out.mask = u32[(ptr + 28) >> 2];
+ out.enabled = u8[ptr + 32] !== 0;
+}
+
+export function writeParticleCollider(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: ParticleColliderPtrData,
+): void {
+ u32[ptr >> 2] = data.shape | 0;
+ f32[(ptr + 4) >> 2] = data.radius;
+ f32[(ptr + 8) >> 2] = data.halfHeight;
+ f32[(ptr + 12) >> 2] = data.halfExtents.x; f32[((ptr + 12) >> 2) + 1] = data.halfExtents.y; f32[((ptr + 12) >> 2) + 2] = data.halfExtents.z;
+ u8[ptr + 24] = data.inverted ? 1 : 0;
+ u32[(ptr + 28) >> 2] = data.mask;
+ u8[ptr + 32] = data.enabled ? 1 : 0;
+}
+
+export function createParticleColliderData(): ParticleColliderPtrData {
+ return {
+ shape: 0,
+ radius: 0,
+ halfHeight: 0,
+ halfExtents: { x: 0, y: 0, z: 0 },
+ inverted: false,
+ mask: 0,
+ enabled: false,
+ };
+}
+
export interface ParticleEmitterPtrData {
rate: number;
burstCount: number;
@@ -1374,6 +1422,7 @@ export interface ParticleEmitterPtrData {
collisionFallback: number;
collisionEvents: boolean;
collisionEventBudget: number;
+ collisionThickness: number;
collisionBounce: number;
collisionFriction: number;
collisionLifetimeLoss: number;
@@ -1455,9 +1504,10 @@ export function fillParticleEmitter(
out.collisionFallback = u32[(ptr + 328) >> 2] | 0;
out.collisionEvents = u8[ptr + 332] !== 0;
out.collisionEventBudget = u32[(ptr + 336) >> 2] | 0;
- out.collisionBounce = f32[(ptr + 340) >> 2];
- out.collisionFriction = f32[(ptr + 344) >> 2];
- out.collisionLifetimeLoss = f32[(ptr + 348) >> 2];
+ out.collisionThickness = f32[(ptr + 340) >> 2];
+ out.collisionBounce = f32[(ptr + 344) >> 2];
+ out.collisionFriction = f32[(ptr + 348) >> 2];
+ out.collisionLifetimeLoss = f32[(ptr + 352) >> 2];
}
export function writeParticleEmitter(
@@ -1536,9 +1586,10 @@ export function writeParticleEmitter(
u32[(ptr + 328) >> 2] = data.collisionFallback | 0;
u8[ptr + 332] = data.collisionEvents ? 1 : 0;
u32[(ptr + 336) >> 2] = data.collisionEventBudget | 0;
- f32[(ptr + 340) >> 2] = data.collisionBounce;
- f32[(ptr + 344) >> 2] = data.collisionFriction;
- f32[(ptr + 348) >> 2] = data.collisionLifetimeLoss;
+ f32[(ptr + 340) >> 2] = data.collisionThickness;
+ f32[(ptr + 344) >> 2] = data.collisionBounce;
+ f32[(ptr + 348) >> 2] = data.collisionFriction;
+ f32[(ptr + 352) >> 2] = data.collisionLifetimeLoss;
}
export function createParticleEmitterData(): ParticleEmitterPtrData {
@@ -1615,6 +1666,7 @@ export function createParticleEmitterData(): ParticleEmitterPtrData {
collisionFallback: 0,
collisionEvents: false,
collisionEventBudget: 0,
+ collisionThickness: 0,
collisionBounce: 0,
collisionFriction: 0,
collisionLifetimeLoss: 0,
@@ -2902,6 +2954,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
MeshLightmap: { fill: fillMeshLightmap, write: writeMeshLightmap, create: createMeshLightmapData },
MeshRenderer: { fill: fillMeshRenderer, write: writeMeshRenderer, create: createMeshRendererData },
Occluder: { fill: fillOccluder, write: writeOccluder, create: createOccluderData },
+ ParticleCollider: { fill: fillParticleCollider, write: writeParticleCollider, create: createParticleColliderData },
ParticleEmitter: { fill: fillParticleEmitter, write: writeParticleEmitter, create: createParticleEmitterData },
ParticleForceField: { fill: fillParticleForceField, write: writeParticleForceField, create: createParticleForceFieldData },
PlanarReflection: { fill: fillPlanarReflection, write: writePlanarReflection, create: createPlanarReflectionData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 359bd540a..2f822c53d 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -7,7 +7,7 @@
import type { AssetFieldType } from '../scene/scene';
import type { FieldMeta } from './component';
import type { Color, Entity, Quat, Vec2, Vec3, Vec4 } from '../types';
-import type { AlignContent, AlignItems, AlignSelf, BillboardMode, BodyType, CanvasScaleMode, ClearFlags, Dimension, EmitterShape, FlexDirection, FlexWrap, ForceFieldType, JustifyContent, LightType, MaskMode, Padding, ParticleCollisionFallback, ParticleCollisionMode, ParticleEasing, ParticleRenderMode, ProjectionType, ReflectionAxis, ReflectionQuality, ReflectionUpdate, ScrollMovement, ShapeType, SimulationSpace, SpringBoneShape, SpriteDrawMode, SpriteMaskInteraction, SubEmitterTrigger, TextAlign, TilemapOrientation, TilemapStaggerAxis, TilemapStaggerIndex, UIDisplay, UIFillMethod, UIFillOrigin, UIPointerEvents, UIPositionType, UIVisualFit, UIVisualType } from '../wasm/wasm.generated';
+import type { AlignContent, AlignItems, AlignSelf, BillboardMode, BodyType, CanvasScaleMode, ClearFlags, Dimension, EmitterShape, FlexDirection, FlexWrap, ForceFieldType, JustifyContent, LightType, MaskMode, Padding, ParticleColliderShape, ParticleCollisionFallback, ParticleCollisionMode, ParticleEasing, ParticleRenderMode, ProjectionType, ReflectionAxis, ReflectionQuality, ReflectionUpdate, ScrollMovement, ShapeType, SimulationSpace, SpringBoneShape, SpriteDrawMode, SpriteMaskInteraction, SubEmitterTrigger, TextAlign, TilemapOrientation, TilemapStaggerAxis, TilemapStaggerIndex, UIDisplay, UIFillMethod, UIFillOrigin, UIPointerEvents, UIPositionType, UIVisualFit, UIVisualType } from '../wasm/wasm.generated';
/**
* Single-source-of-truth hash of the C++/TS boundary ABI (component
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BillboardMode, BodyType, Canv
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '6bf8e03097b59051';
+export const ABI_LAYOUT_HASH = '5e943b68bf754ab0';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -736,6 +736,29 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: [],
},
+ ParticleCollider: {
+ defaults: {
+ shape: 0,
+ radius: 50,
+ halfHeight: 50,
+ halfExtents: { x: 50, y: 50, z: 50 },
+ inverted: false,
+ mask: 65535,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ shape: { enum: [{ label: 'Sphere', value: 0 }, { label: 'Box', value: 1 }, { label: 'Capsule', value: 2 }], category: "Shape" },
+ radius: { min: 0, category: "Shape" },
+ halfHeight: { min: 0, category: "Shape" },
+ halfExtents: { category: "Shape" },
+ inverted: { category: "Shape" },
+ mask: { min: 0, max: 65535, step: 1, category: "Shape", bitmask: { source: "collisionLayers" } },
+ },
+ },
ParticleEmitter: {
defaults: {
rate: 10,
@@ -810,6 +833,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
collisionFallback: 0,
collisionEvents: false,
collisionEventBudget: 32,
+ collisionThickness: 30,
collisionBounce: 0.5,
collisionFriction: 0.1,
collisionLifetimeLoss: 0,
@@ -884,13 +908,14 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
trailMinDistance: { min: 0, category: "Trail", shownWhen: { field: "trailEnabled", values: [1] } },
collisionEnabled: { category: "Collision" },
collisionFloor: { category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
- collisionMode: { enum: [{ label: 'Floor', value: 0 }, { label: 'Physics2D', value: 1 }, { label: 'Physics3D', value: 2 }], category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
+ collisionMode: { enum: [{ label: 'Floor', value: 0 }, { label: 'Physics2D', value: 1 }, { label: 'Physics3D', value: 2 }, { label: 'Depth', value: 3 }, { label: 'Sdf', value: 4 }], category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionMask: { min: 0, max: 65535, step: 1, category: "Collision", bitmask: { source: "collisionLayers" }, shownWhen: { field: "collisionEnabled", values: [1] } },
collisionQueryBudget: { min: 0, max: 4096, step: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionMaxDistance: { min: 0, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionFallback: { enum: [{ label: 'Floor', value: 0 }, { label: 'Skip', value: 1 }], category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionEvents: { category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionEventBudget: { min: 0, max: 1024, step: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
+ collisionThickness: { min: 0, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionBounce: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionFriction: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
collisionLifetimeLoss: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
@@ -1800,6 +1825,22 @@ export interface ParentData {
entity: Entity;
}
+/**
+ * The fields of the engine's `ParticleCollider` component, generated from
+ * the C++ struct so the two shapes cannot drift.
+ *
+ * @beta
+ */
+export interface ParticleColliderData {
+ shape: ParticleColliderShape;
+ radius: number;
+ halfHeight: number;
+ halfExtents: Vec3;
+ inverted: boolean;
+ mask: number;
+ enabled: boolean;
+}
+
/**
* The fields of the engine's `ParticleEmitter` component, generated from
* the C++ struct so the two shapes cannot drift.
@@ -1879,6 +1920,7 @@ export interface ParticleEmitterData {
collisionFallback: ParticleCollisionFallback;
collisionEvents: boolean;
collisionEventBudget: number;
+ collisionThickness: number;
collisionBounce: number;
collisionFriction: number;
collisionLifetimeLoss: number;
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index e37c6a3a3..1fb02165e 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -19,7 +19,7 @@ import type {
SortingGroupData, GroupOpacityData, SpriteMaskData, LightProbeVolumeData, OccluderData,
ReflectionProbeData, PlanarReflectionData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
- TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
+ TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, ParticleColliderData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
CameraData as CameraDataCpp, ParticleEmitterData as ParticleEmitterDataCpp,
MeshRendererData as MeshRendererDataCpp,
} from './component.generated';
@@ -28,7 +28,7 @@ import type {
// C++ enum and the editor dropdowns derive from the same values. ScaleMode's
// canonical values come from CanvasScaleMode (only its Cocos-compat aliases
// ShowAll/NoBorder are TS-side).
-import { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, LightType, CanvasScaleMode, ShapeType, ParticleEasing, ParticleCollisionMode, ParticleCollisionFallback, ParticleRenderMode, ReflectionAxis, ReflectionQuality, ReflectionUpdate, SpriteMaskInteraction, SpriteDrawMode, BillboardMode } from '../wasm/wasm.generated';
+import { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, ParticleColliderShape, LightType, CanvasScaleMode, ShapeType, ParticleEasing, ParticleCollisionMode, ParticleCollisionFallback, ParticleRenderMode, ReflectionAxis, ReflectionQuality, ReflectionUpdate, SpriteMaskInteraction, SpriteDrawMode, BillboardMode } from '../wasm/wasm.generated';
import { BlendMode } from '../render/blend';
import { getDefaultContext } from './context';
import type {
@@ -818,7 +818,7 @@ export function ensureBuiltinComponentsRegistered(): void {
// EmitterShape, SimulationSpace, LightType and ShapeType are re-exported from the
// generated module; their values and the editor dropdowns built from them now have
// one source.
-export { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, LightType, ShapeType, SpriteMaskInteraction, SpriteDrawMode };
+export { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, ParticleColliderShape, LightType, ShapeType, SpriteMaskInteraction, SpriteDrawMode };
// Canonical values single-sourced from the C++ CanvasScaleMode enum (generated);
// ShowAll/NoBorder are Cocos-compat aliases with no C++ member.
@@ -846,7 +846,7 @@ export type {
SortingGroupData, GroupOpacityData, SpriteMaskData, LightProbeVolumeData, OccluderData,
ReflectionProbeData, PlanarReflectionData,
CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
- TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
+ TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, ParticleColliderData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
};
export type LocalTransformData = TransformData;
@@ -1167,6 +1167,11 @@ export const ParticleForceField = defineBuiltin<ParticleForceFieldData>('Particl
metaDefaults<ParticleForceFieldData>('ParticleForceField')
);
+// A shape particles bounce off with no physics: an emitter in `Sdf` collision mode, on the GPU or the CPU, asks its distance.
+export const ParticleCollider = defineBuiltin<ParticleColliderData>('ParticleCollider',
+ metaDefaults<ParticleColliderData>('ParticleCollider')
+);
+
/**
* One layer of a tile lattice: `cellSize` is its step in world units, and
* `orientation` with the stagger fields cover isometric and hex, so it is not
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index b0f8dd133..d0b7db61a 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -350,6 +350,18 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 12 },
],
},
+ ParticleCollider: {
+ ptrFn: 'getParticleColliderPtr',
+ fields: [
+ { name: 'shape', type: 'i32', offset: 0 },
+ { name: 'radius', type: 'f32', offset: 4 },
+ { name: 'halfHeight', type: 'f32', offset: 8 },
+ { name: 'halfExtents', type: 'vec3', offset: 12 },
+ { name: 'inverted', type: 'bool', offset: 24 },
+ { name: 'mask', type: 'u32', offset: 28 },
+ { name: 'enabled', type: 'bool', offset: 32 },
+ ],
+ },
ParticleEmitter: {
ptrFn: 'getParticleEmitterPtr',
fields: [
@@ -425,9 +437,10 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'collisionFallback', type: 'i32', offset: 328 },
{ name: 'collisionEvents', type: 'bool', offset: 332 },
{ name: 'collisionEventBudget', type: 'i32', offset: 336 },
- { name: 'collisionBounce', type: 'f32', offset: 340 },
- { name: 'collisionFriction', type: 'f32', offset: 344 },
- { name: 'collisionLifetimeLoss', type: 'f32', offset: 348 },
+ { name: 'collisionThickness', type: 'f32', offset: 340 },
+ { name: 'collisionBounce', type: 'f32', offset: 344 },
+ { name: 'collisionFriction', type: 'f32', offset: 348 },
+ { name: 'collisionLifetimeLoss', type: 'f32', offset: 352 },
],
},
ParticleForceField: {
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 6a3666010..c069e950d 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -199,6 +199,17 @@ export enum MaskMode {
Stencil = 1,
}
+/**
+ * The engine's `ParticleColliderShape`, generated from the C++ enum.
+ *
+ * @beta
+ */
+export enum ParticleColliderShape {
+ Sphere = 0,
+ Box = 1,
+ Capsule = 2,
+}
+
/**
* The engine's `ParticleCollisionFallback`, generated from the C++ enum.
*
@@ -218,6 +229,8 @@ export enum ParticleCollisionMode {
Floor = 0,
Physics2D = 1,
Physics3D = 2,
+ Depth = 3,
+ Sdf = 4,
}
/**
@@ -760,6 +773,16 @@ export interface Parent {
entity: number;
}
+export interface ParticleCollider {
+ shape: number;
+ radius: number;
+ halfHeight: number;
+ halfExtents: Vec3;
+ inverted: boolean;
+ mask: number;
+ enabled: boolean;
+}
+
export interface ParticleEmitter {
rate: number;
burstCount: number;
@@ -833,6 +856,7 @@ export interface ParticleEmitter {
collisionFallback: number;
collisionEvents: boolean;
collisionEventBudget: number;
+ collisionThickness: number;
collisionBounce: number;
collisionFriction: number;
collisionLifetimeLoss: number;
@@ -1239,6 +1263,10 @@ export interface Registry {
getParent(entity: Entity): Parent;
addParent(entity: Entity, component: Parent): void;
removeParent(entity: Entity): void;
+ hasParticleCollider(entity: Entity): boolean;
+ getParticleCollider(entity: Entity): ParticleCollider;
+ addParticleCollider(entity: Entity, component: ParticleCollider): void;
+ removeParticleCollider(entity: Entity): void;
hasParticleEmitter(entity: Entity): boolean;
getParticleEmitter(entity: Entity): ParticleEmitter;
addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
@@ -1388,6 +1416,7 @@ export interface ESEngineModule {
MeshSkin: new () => MeshSkin;
Occluder: new () => Occluder;
Parent: new () => Parent;
+ ParticleCollider: new () => ParticleCollider;
ParticleEmitter: new () => ParticleEmitter;
ParticleForceField: new () => ParticleForceField;
PlanarReflection: new () => PlanarReflection;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 5e008fbbb..46ae3da81 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -627,6 +627,48 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"tooltip": "Half the solid box, in world units, from the entity's position.",
},
},
+ "ParticleCollider": {
+ "halfExtents": {
+ "category": "Shape",
+ },
+ "halfHeight": {
+ "category": "Shape",
+ "min": 0,
+ },
+ "inverted": {
+ "category": "Shape",
+ },
+ "mask": {
+ "bitmask": {
+ "source": "collisionLayers",
+ },
+ "category": "Shape",
+ "max": 65535,
+ "min": 0,
+ "step": 1,
+ },
+ "radius": {
+ "category": "Shape",
+ "min": 0,
+ },
+ "shape": {
+ "category": "Shape",
+ "enum": [
+ {
+ "label": "Sphere",
+ "value": 0,
+ },
+ {
+ "label": "Box",
+ "value": 1,
+ },
+ {
+ "label": "Capsule",
+ "value": 2,
+ },
+ ],
+ },
+ },
"ParticleEmitter": {
"addedVelocityMax": {
"category": "Velocity",
@@ -845,6 +887,14 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"label": "Physics3D",
"value": 2,
},
+ {
+ "label": "Depth",
+ "value": 3,
+ },
+ {
+ "label": "Sdf",
+ "value": 4,
+ },
],
"shownWhen": {
"field": "collisionEnabled",
@@ -865,6 +915,16 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
},
"step": 1,
},
+ "collisionThickness": {
+ "category": "Collision",
+ "min": 0,
+ "shownWhen": {
+ "field": "collisionEnabled",
+ "values": [
+ 1,
+ ],
+ },
+ },
"colorEasing": {
"category": "Color",
"enum": [
diff --git a/sdk/tests/particle-sdf-collision-wasm.test.ts b/sdk/tests/particle-sdf-collision-wasm.test.ts
new file mode 100644
index 000000000..8c8c5e6ef
--- /dev/null
+++ b/sdk/tests/particle-sdf-collision-wasm.test.ts
@@ -0,0 +1,160 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The CPU's answer to a `ParticleCollider`, on the real engine: what a device with no compute plays. The kernel's answer to the same shapes is
+ * measured in the picture by the particle-gpu-collision editor check.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { App } from '../src/app/app';
+import { ParticleCollider, ParticleEmitter, Transform } from '../src/ecs/component';
+import { Particle, ParticlePlugin } from '../src/particle';
+import type { ParticleCollisionEventPayload } from '../src/particle/collision';
+import type { Entity } from '../src/types';
+import type { ESEngineModule } from '../src/wasm';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+const SDF = 4, DEPTH = 3;
+let engine: ESEngineModule;
+const apps: App[] = [];
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); });
+
+async function scene() {
+ const app = App.new(); apps.push(app);
+ app.connectCpp(new engine.Registry(), engine, { ownedRegistry: true });
+ app.addPlugin(new ParticlePlugin());
+ const world = app.world;
+ /** One particle at a time, straight along +x from the origin at 100 units a second. */
+ const shot = (fields: Record<string, unknown> = {}): Entity => {
+ const e = world.spawn();
+ world.insert(e, Transform, {});
+ world.insert(e, ParticleEmitter, {
+ shape: 0, angleSpreadMin: 0, angleSpreadMax: 0, rate: 0, burstCount: 1, burstInterval: 100, maxParticles: 4,
+ lifetimeMin: 4, lifetimeMax: 4, speedMin: 100, speedMax: 100, gravity: { x: 0, y: 0, z: 0 }, damping: 0, simulationSpace: 0,
+ collisionEnabled: true, collisionMode: SDF, collisionEvents: true, collisionEventBudget: 8, collisionBounce: 1, collisionFriction: 0, enabled: true,
+ playOnStart: true, ...fields,
+ } as never);
+ // The module's one particle system knows entities by number, and a new world uses the same numbers.
+ const particles = app.getResource(Particle);
+ particles.reset(e);
+ particles.play(e);
+ return e;
+ };
+ const collider = (x: number, fields: Record<string, unknown>, rotation?: { x: number; y: number; z: number; w: number }): Entity => {
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x, y: 0, z: 0 }, ...(rotation ? { rotation } : {}) });
+ world.insert(e, ParticleCollider, { enabled: true, mask: 65535, ...fields } as never);
+ return e;
+ };
+ /** Runs until the first hit, and hands it back. */
+ const firstHit = async (frames = 120): Promise<ParticleCollisionEventPayload | null> => {
+ for (let i = 0; i < frames; i++) {
+ await app.stepFrames(1, 1 / 60);
+ const events = app.getResource(Particle).collisionEvents;
+ if (events.length > 0) return events[0]!;
+ }
+ return null;
+ };
+ return { app, world, shot, collider, firstHit };
+}
+
+describe.skipIf(!HAS_WASM)('a particle against a distance function, on the CPU', () => {
+ beforeAll(async () => { engine = await loadWasmModule(); });
+
+ it('bounces off a sphere at its surface', async () => {
+ const s = await scene();
+ s.collider(50, { shape: 0, radius: 20 });
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit).not.toBeNull();
+ expect(hit!.x).toBeCloseTo(30, 0);
+ expect(hit!.normalX).toBeCloseTo(-1, 1);
+ });
+
+ it('bounces off a box at its face', async () => {
+ const s = await scene();
+ s.collider(50, { shape: 1, halfExtents: { x: 10, y: 40, z: 40 } });
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit!.x).toBeCloseTo(40, 0);
+ expect(hit!.normalX).toBeCloseTo(-1, 1);
+ });
+
+ it('turns a box with its entity', async () => {
+ const s = await scene();
+ // Turned 45 degrees about z, its near corner points back along the path: the face it meets leans.
+ const half = Math.sin(Math.PI / 8), whole = Math.cos(Math.PI / 8);
+ s.collider(60, { shape: 1, halfExtents: { x: 10, y: 100, z: 100 } }, { x: 0, y: 0, z: half, w: whole });
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit).not.toBeNull();
+ expect(hit!.normalX).toBeCloseTo(-Math.SQRT1_2, 1);
+ expect(Math.abs(hit!.normalY)).toBeCloseTo(Math.SQRT1_2, 1);
+ });
+
+ it('takes a capsule along its up, and rounds its ends', async () => {
+ const s = await scene();
+ s.collider(50, { shape: 2, radius: 10, halfHeight: 30 });
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit!.x).toBeCloseTo(40, 0);
+ const over = await scene();
+ // Past the end of its axis the shape is only its cap, so a path that clears the cap clears the shape.
+ const e = over.world.spawn();
+ over.world.insert(e, Transform, { position: { x: 50, y: -60, z: 0 } });
+ over.world.insert(e, ParticleCollider, { shape: 2, radius: 10, halfHeight: 30, enabled: true, mask: 65535 } as never);
+ over.shot();
+ expect(await over.firstHit(60)).toBeNull();
+ });
+
+ it('keeps it in when inverted', async () => {
+ const s = await scene();
+ s.collider(0, { shape: 0, radius: 40, inverted: true });
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit!.x).toBeCloseTo(40, 0);
+ expect(hit!.normalX).toBeCloseTo(-1, 1);
+ });
+
+ it('passes one that shares no bit of its mask', async () => {
+ const s = await scene();
+ s.collider(50, { shape: 0, radius: 20, mask: 2 });
+ s.shot({ collisionMask: 1 });
+ expect(await s.firstHit(60)).toBeNull();
+ });
+
+ it('passes one that is switched off', async () => {
+ const s = await scene();
+ s.collider(50, { shape: 0, radius: 20, enabled: false });
+ s.shot();
+ expect(await s.firstHit(60)).toBeNull();
+ });
+
+ it('does not catch what is already leaving', async () => {
+ const s = await scene();
+ // Born inside and heading out: the way out is the way it is already going.
+ s.collider(0, { shape: 0, radius: 40 });
+ s.shot();
+ expect(await s.firstHit(30)).toBeNull();
+ });
+
+ it('takes a sphere\'s size from its largest scale', async () => {
+ const s = await scene();
+ const e = s.world.spawn();
+ s.world.insert(e, Transform, { position: { x: 50, y: 0, z: 0 }, scale: { x: 1, y: 2, z: 1 } });
+ s.world.insert(e, ParticleCollider, { shape: 0, radius: 10, enabled: true, mask: 65535 } as never);
+ s.shot();
+ const hit = await s.firstHit();
+ expect(hit!.x).toBeCloseTo(30, 0);
+ });
+
+ it('falls back as it says where a mode needs what the CPU has not got', async () => {
+ const s = await scene();
+ s.shot({ collisionMode: DEPTH, collisionFallback: 0, collisionFloor: 0, angleSpreadMin: -90, angleSpreadMax: -90 });
+ const hit = await s.firstHit();
+ expect(hit).not.toBeNull();
+ expect(hit!.normalY).toBeCloseTo(1, 1);
+ const other = await scene();
+ other.shot({ collisionMode: DEPTH, collisionFallback: 1, collisionFloor: 0, angleSpreadMin: -90, angleSpreadMax: -90 });
+ expect(await other.firstHit(30)).toBeNull();
+ });
+});
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index c5d4d803b..ffa4574a6 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -27,6 +27,7 @@
#include "esengine/ecs/components/Light.hpp"
#include "esengine/ecs/components/MeshRenderer.hpp"
#include "esengine/ecs/components/Occluder.hpp"
+#include "esengine/ecs/components/ParticleCollider.hpp"
#include "esengine/ecs/components/ParticleEmitter.hpp"
#include "esengine/ecs/components/ParticleForceField.hpp"
#include "esengine/ecs/components/PlanarReflection.hpp"
@@ -220,6 +221,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::Parent>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "ParticleCollider") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::ParticleCollider>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "ParticleEmitter") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::ParticleEmitter>(Entity::fromRaw(raw));
@@ -499,6 +505,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::Parent>());
};
}
+ if (std::strcmp(name, "ParticleCollider") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::ParticleCollider>());
+ };
+ }
if (std::strcmp(name, "ParticleEmitter") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::ParticleEmitter>());
@@ -658,6 +669,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "MeshSkin") == 0) return true;
if (std::strcmp(name, "Occluder") == 0) return true;
if (std::strcmp(name, "Parent") == 0) return true;
+ if (std::strcmp(name, "ParticleCollider") == 0) return true;
if (std::strcmp(name, "ParticleEmitter") == 0) return true;
if (std::strcmp(name, "ParticleForceField") == 0) return true;
if (std::strcmp(name, "PlanarReflection") == 0) return true;
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index fbf0b57e2..5f495a476 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 042cfceefbe1ff33
+ * @schema_hash c6adadad4db185c0
*/
-#define ES_EDITOR_API_SCHEMA_HASH "042cfceefbe1ff33"
+#define ES_EDITOR_API_SCHEMA_HASH "c6adadad4db185c0"
#include <emscripten/bind.h>
#include <string>
@@ -30,6 +30,7 @@
#include "../ecs/components/Light.hpp"
#include "../ecs/components/MeshRenderer.hpp"
#include "../ecs/components/Occluder.hpp"
+#include "../ecs/components/ParticleCollider.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/PlanarReflection.hpp"
@@ -102,6 +103,7 @@ std::vector<std::string> editor_getComponentNames() {
"MeshSkin",
"Occluder",
"Parent",
+ "ParticleCollider",
"ParticleEmitter",
"ParticleForceField",
"PlanarReflection",
@@ -483,6 +485,18 @@ std::string editor_getComponentSchema(const std::string& name) {
return R"JSON([
{"key":"entity","type":"entity","group":"Parent"}
])JSON";
+ } else if (name == "ParticleCollider") {
+ return R"JSON([
+ {"key":"shape","type":"int","group":"ParticleCollider"},
+ {"key":"radius","type":"float","group":"ParticleCollider"},
+ {"key":"halfHeight","type":"float","group":"ParticleCollider"},
+ {"key":"halfExtents.x","type":"float","group":"ParticleCollider"},
+ {"key":"halfExtents.y","type":"float","group":"ParticleCollider"},
+ {"key":"halfExtents.z","type":"float","group":"ParticleCollider"},
+ {"key":"inverted","type":"bool","group":"ParticleCollider"},
+ {"key":"mask","type":"int","group":"ParticleCollider"},
+ {"key":"enabled","type":"bool","group":"ParticleCollider"}
+ ])JSON";
} else if (name == "ParticleEmitter") {
return R"JSON([
{"key":"rate","type":"float","group":"ParticleEmitter"},
@@ -571,6 +585,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"collisionFallback","type":"int","group":"ParticleEmitter"},
{"key":"collisionEvents","type":"bool","group":"ParticleEmitter"},
{"key":"collisionEventBudget","type":"int","group":"ParticleEmitter"},
+ {"key":"collisionThickness","type":"float","group":"ParticleEmitter"},
{"key":"collisionBounce","type":"float","group":"ParticleEmitter"},
{"key":"collisionFriction","type":"float","group":"ParticleEmitter"},
{"key":"collisionLifetimeLoss","type":"float","group":"ParticleEmitter"}
@@ -1017,6 +1032,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
return true;
} else if (name == "Parent") {
return false;
+ } else if (name == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) reg.emplace<esengine::ecs::ParticleCollider>(entity);
+ return true;
} else if (name == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) reg.emplace<esengine::ecs::ParticleEmitter>(entity);
return true;
@@ -1163,6 +1181,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Occluder>(entity)) { reg.remove<esengine::ecs::Occluder>(entity); return true; }
} else if (name == "Parent") {
if (reg.has<esengine::ecs::Parent>(entity)) { esengine::ecs::setParent(reg, entity, INVALID_ENTITY); return true; }
+ } else if (name == "ParticleCollider") {
+ if (reg.has<esengine::ecs::ParticleCollider>(entity)) { reg.remove<esengine::ecs::ParticleCollider>(entity); return true; }
} else if (name == "ParticleEmitter") {
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) { reg.remove<esengine::ecs::ParticleEmitter>(entity); return true; }
} else if (name == "ParticleForceField") {
@@ -1250,6 +1270,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "MeshSkin") return reg.has<esengine::ecs::MeshSkin>(entity);
if (name == "Occluder") return reg.has<esengine::ecs::Occluder>(entity);
if (name == "Parent") return reg.has<esengine::ecs::Parent>(entity);
+ if (name == "ParticleCollider") return reg.has<esengine::ecs::ParticleCollider>(entity);
if (name == "ParticleEmitter") return reg.has<esengine::ecs::ParticleEmitter>(entity);
if (name == "ParticleForceField") return reg.has<esengine::ecs::ParticleForceField>(entity);
if (name == "PlanarReflection") return reg.has<esengine::ecs::PlanarReflection>(entity);
@@ -1314,6 +1335,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::MeshSkin>(entity)) result.push_back("MeshSkin");
if (reg.has<esengine::ecs::Occluder>(entity)) result.push_back("Occluder");
if (reg.has<esengine::ecs::Parent>(entity)) result.push_back("Parent");
+ if (reg.has<esengine::ecs::ParticleCollider>(entity)) result.push_back("ParticleCollider");
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) result.push_back("ParticleEmitter");
if (reg.has<esengine::ecs::ParticleForceField>(entity)) result.push_back("ParticleForceField");
if (reg.has<esengine::ecs::PlanarReflection>(entity)) result.push_back("PlanarReflection");
@@ -1623,6 +1645,16 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "halfExtents.z") { c.halfExtents.z = value; }
else { return false; }
return true;
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "radius") { c.radius = value; }
+ else if (field == "halfHeight") { c.halfHeight = value; }
+ else if (field == "halfExtents.x") { c.halfExtents.x = value; }
+ else if (field == "halfExtents.y") { c.halfExtents.y = value; }
+ else if (field == "halfExtents.z") { c.halfExtents.z = value; }
+ else { return false; }
+ return true;
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -1682,6 +1714,7 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "trailMinDistance") { c.trailMinDistance = value; }
else if (field == "collisionFloor") { c.collisionFloor = value; }
else if (field == "collisionMaxDistance") { c.collisionMaxDistance = value; }
+ else if (field == "collisionThickness") { c.collisionThickness = value; }
else if (field == "collisionBounce") { c.collisionBounce = value; }
else if (field == "collisionFriction") { c.collisionFriction = value; }
else if (field == "collisionLifetimeLoss") { c.collisionLifetimeLoss = value; }
@@ -2221,6 +2254,14 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "halfExtents.x") { return c.halfExtents.x; }
else if (field == "halfExtents.y") { return c.halfExtents.y; }
else if (field == "halfExtents.z") { return c.halfExtents.z; }
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "radius") { return c.radius; }
+ else if (field == "halfHeight") { return c.halfHeight; }
+ else if (field == "halfExtents.x") { return c.halfExtents.x; }
+ else if (field == "halfExtents.y") { return c.halfExtents.y; }
+ else if (field == "halfExtents.z") { return c.halfExtents.z; }
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -2280,6 +2321,7 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "trailMinDistance") { return c.trailMinDistance; }
else if (field == "collisionFloor") { return c.collisionFloor; }
else if (field == "collisionMaxDistance") { return c.collisionMaxDistance; }
+ else if (field == "collisionThickness") { return c.collisionThickness; }
else if (field == "collisionBounce") { return c.collisionBounce; }
else if (field == "collisionFriction") { return c.collisionFriction; }
else if (field == "collisionLifetimeLoss") { return c.collisionLifetimeLoss; }
@@ -2677,6 +2719,13 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
if (field != "entity") return false;
esengine::ecs::setParent(reg, entity, static_cast<Entity>(value));
return true;
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "shape") { c.shape = static_cast<i32>(value); }
+ else if (field == "mask") { c.mask = static_cast<u32>(value); }
+ else { return false; }
+ return true;
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -2962,6 +3011,11 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
if (!reg.has<esengine::ecs::Parent>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::Parent>(entity);
if (field == "entity") { return static_cast<i32>(static_cast<u32>(c.entity)); }
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "shape") { return static_cast<i32>(c.shape); }
+ else if (field == "mask") { return static_cast<i32>(c.mask); }
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -3255,6 +3309,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "inverted") { c.inverted = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -3530,6 +3591,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (!reg.has<esengine::ecs::Occluder>(entity)) return false;
const auto& c = reg.get<esengine::ecs::Occluder>(entity);
if (field == "enabled") { return c.enabled; }
+ } else if (comp == "ParticleCollider") {
+ if (!reg.has<esengine::ecs::ParticleCollider>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::ParticleCollider>(entity);
+ if (field == "inverted") { return c.inverted; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
const auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index b85f4e776..f63c1e8fb 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -30,6 +30,7 @@
#include "../ecs/components/Light.hpp"
#include "../ecs/components/MeshRenderer.hpp"
#include "../ecs/components/Occluder.hpp"
+#include "../ecs/components/ParticleCollider.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/PlanarReflection.hpp"
@@ -230,6 +231,11 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
.value("Scissor", esengine::ecs::MaskMode::Scissor)
.value("Stencil", esengine::ecs::MaskMode::Stencil);
+ enum_<esengine::ecs::ParticleColliderShape>("ParticleColliderShape")
+ .value("Sphere", esengine::ecs::ParticleColliderShape::Sphere)
+ .value("Box", esengine::ecs::ParticleColliderShape::Box)
+ .value("Capsule", esengine::ecs::ParticleColliderShape::Capsule);
+
enum_<esengine::ecs::ParticleCollisionFallback>("ParticleCollisionFallback")
.value("Floor", esengine::ecs::ParticleCollisionFallback::Floor)
.value("Skip", esengine::ecs::ParticleCollisionFallback::Skip);
@@ -237,7 +243,9 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
enum_<esengine::ecs::ParticleCollisionMode>("ParticleCollisionMode")
.value("Floor", esengine::ecs::ParticleCollisionMode::Floor)
.value("Physics2D", esengine::ecs::ParticleCollisionMode::Physics2D)
- .value("Physics3D", esengine::ecs::ParticleCollisionMode::Physics3D);
+ .value("Physics3D", esengine::ecs::ParticleCollisionMode::Physics3D)
+ .value("Depth", esengine::ecs::ParticleCollisionMode::Depth)
+ .value("Sdf", esengine::ecs::ParticleCollisionMode::Sdf);
enum_<esengine::ecs::ParticleEasing>("ParticleEasing")
.value("Linear", esengine::ecs::ParticleEasing::Linear)
@@ -1024,6 +1032,7 @@ struct ParticleEmitterJS {
i32 collisionFallback;
bool collisionEvents;
i32 collisionEventBudget;
+ f32 collisionThickness;
f32 collisionBounce;
f32 collisionFriction;
f32 collisionLifetimeLoss;
@@ -1102,6 +1111,7 @@ void particleemitterApplyJS(esengine::ecs::ParticleEmitter& c, const ParticleEmi
c.collisionFallback = js.collisionFallback;
c.collisionEvents = js.collisionEvents;
c.collisionEventBudget = js.collisionEventBudget;
+ c.collisionThickness = js.collisionThickness;
c.collisionBounce = js.collisionBounce;
c.collisionFriction = js.collisionFriction;
c.collisionLifetimeLoss = js.collisionLifetimeLoss;
@@ -1187,6 +1197,7 @@ ParticleEmitterJS particleemitterToJS(const esengine::ecs::ParticleEmitter& c) {
js.collisionFallback = c.collisionFallback;
js.collisionEvents = c.collisionEvents;
js.collisionEventBudget = c.collisionEventBudget;
+ js.collisionThickness = c.collisionThickness;
js.collisionBounce = c.collisionBounce;
js.collisionFriction = c.collisionFriction;
js.collisionLifetimeLoss = c.collisionLifetimeLoss;
@@ -2112,6 +2123,15 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
value_object<ParentJS>("Parent")
.field("entity", &ParentJS::entity);
+ value_object<esengine::ecs::ParticleCollider>("ParticleCollider")
+ .field("shape", &esengine::ecs::ParticleCollider::shape)
+ .field("radius", &esengine::ecs::ParticleCollider::radius)
+ .field("halfHeight", &esengine::ecs::ParticleCollider::halfHeight)
+ .field("halfExtents", &esengine::ecs::ParticleCollider::halfExtents)
+ .field("inverted", &esengine::ecs::ParticleCollider::inverted)
+ .field("mask", &esengine::ecs::ParticleCollider::mask)
+ .field("enabled", &esengine::ecs::ParticleCollider::enabled);
+
value_object<ParticleEmitterJS>("ParticleEmitter")
.field("rate", &ParticleEmitterJS::rate)
.field("burstCount", &ParticleEmitterJS::burstCount)
@@ -2185,6 +2205,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("collisionFallback", &ParticleEmitterJS::collisionFallback)
.field("collisionEvents", &ParticleEmitterJS::collisionEvents)
.field("collisionEventBudget", &ParticleEmitterJS::collisionEventBudget)
+ .field("collisionThickness", &ParticleEmitterJS::collisionThickness)
.field("collisionBounce", &ParticleEmitterJS::collisionBounce)
.field("collisionFriction", &ParticleEmitterJS::collisionFriction)
.field("collisionLifetimeLoss", &ParticleEmitterJS::collisionLifetimeLoss);
@@ -2497,6 +2518,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (r.has<esengine::ecs::MeshSkin>(entity)) { if (!names.empty()) names += "|"; names += "MeshSkin"; }
if (r.has<esengine::ecs::Occluder>(entity)) { if (!names.empty()) names += "|"; names += "Occluder"; }
if (r.has<esengine::ecs::Parent>(entity)) { if (!names.empty()) names += "|"; names += "Parent"; }
+ if (r.has<esengine::ecs::ParticleCollider>(entity)) { if (!names.empty()) names += "|"; names += "ParticleCollider"; }
if (r.has<esengine::ecs::ParticleEmitter>(entity)) { if (!names.empty()) names += "|"; names += "ParticleEmitter"; }
if (r.has<esengine::ecs::ParticleForceField>(entity)) { if (!names.empty()) names += "|"; names += "ParticleForceField"; }
if (r.has<esengine::ecs::PlanarReflection>(entity)) { if (!names.empty()) names += "|"; names += "PlanarReflection"; }
@@ -2556,6 +2578,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (name == "MeshSkin") return static_cast<int>(componentTypeId<esengine::ecs::MeshSkin>());
if (name == "Occluder") return static_cast<int>(componentTypeId<esengine::ecs::Occluder>());
if (name == "Parent") return static_cast<int>(componentTypeId<esengine::ecs::Parent>());
+ if (name == "ParticleCollider") return static_cast<int>(componentTypeId<esengine::ecs::ParticleCollider>());
if (name == "ParticleEmitter") return static_cast<int>(componentTypeId<esengine::ecs::ParticleEmitter>());
if (name == "ParticleForceField") return static_cast<int>(componentTypeId<esengine::ecs::ParticleForceField>());
if (name == "PlanarReflection") return static_cast<int>(componentTypeId<esengine::ecs::PlanarReflection>());
@@ -3256,6 +3279,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
esengine::ecs::setParent(r, entity, INVALID_ENTITY);
}))
+ // ParticleCollider
+ .function("hasParticleCollider", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::ParticleCollider>(static_cast<Entity>(e));
+ }))
+ .function("getParticleCollider", optional_override([](Registry& r, u32 e) -> esengine::ecs::ParticleCollider& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::ParticleCollider s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::ParticleCollider>(entity)) return s_dummy;
+ return r.get<esengine::ecs::ParticleCollider>(entity);
+ }), allow_raw_pointers())
+ .function("addParticleCollider", optional_override([](Registry& r, u32 e, const esengine::ecs::ParticleCollider& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::ParticleCollider>(entity, c);
+ }))
+ .function("removeParticleCollider", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::ParticleCollider>(entity)) return;
+ r.remove<esengine::ecs::ParticleCollider>(entity);
+ }))
+
// ParticleEmitter
.function("hasParticleEmitter", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::ParticleEmitter>(static_cast<Entity>(e));
@@ -3879,6 +3923,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("MeshSkin")));
arr.set(i++, val(std::string("Occluder")));
arr.set(i++, val(std::string("Parent")));
+ arr.set(i++, val(std::string("ParticleCollider")));
arr.set(i++, val(std::string("ParticleEmitter")));
arr.set(i++, val(std::string("ParticleForceField")));
arr.set(i++, val(std::string("PlanarReflection")));
@@ -4111,6 +4156,13 @@ static_assert(offsetof(esengine::ecs::MeshRenderer, enabled) == 44, "ABI offset
static_assert(offsetof(esengine::ecs::MeshRenderer, mesh) == 48, "ABI offset drift: esengine::ecs::MeshRenderer.mesh (EHT expected 48)");
static_assert(offsetof(esengine::ecs::Occluder, halfExtents) == 0, "ABI offset drift: esengine::ecs::Occluder.halfExtents (EHT expected 0)");
static_assert(offsetof(esengine::ecs::Occluder, enabled) == 12, "ABI offset drift: esengine::ecs::Occluder.enabled (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, shape) == 0, "ABI offset drift: esengine::ecs::ParticleCollider.shape (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, radius) == 4, "ABI offset drift: esengine::ecs::ParticleCollider.radius (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, halfHeight) == 8, "ABI offset drift: esengine::ecs::ParticleCollider.halfHeight (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, halfExtents) == 12, "ABI offset drift: esengine::ecs::ParticleCollider.halfExtents (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, inverted) == 24, "ABI offset drift: esengine::ecs::ParticleCollider.inverted (EHT expected 24)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, mask) == 28, "ABI offset drift: esengine::ecs::ParticleCollider.mask (EHT expected 28)");
+static_assert(offsetof(esengine::ecs::ParticleCollider, enabled) == 32, "ABI offset drift: esengine::ecs::ParticleCollider.enabled (EHT expected 32)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, rate) == 0, "ABI offset drift: esengine::ecs::ParticleEmitter.rate (EHT expected 0)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, burstCount) == 4, "ABI offset drift: esengine::ecs::ParticleEmitter.burstCount (EHT expected 4)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, burstInterval) == 8, "ABI offset drift: esengine::ecs::ParticleEmitter.burstInterval (EHT expected 8)");
@@ -4183,9 +4235,10 @@ static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionMaxDistance) ==
static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionFallback) == 328, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionFallback (EHT expected 328)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionEvents) == 332, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionEvents (EHT expected 332)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionEventBudget) == 336, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionEventBudget (EHT expected 336)");
-static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionBounce) == 340, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionBounce (EHT expected 340)");
-static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionFriction) == 344, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionFriction (EHT expected 344)");
-static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionLifetimeLoss) == 348, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionLifetimeLoss (EHT expected 348)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionThickness) == 340, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionThickness (EHT expected 340)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionBounce) == 344, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionBounce (EHT expected 344)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionFriction) == 348, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionFriction (EHT expected 348)");
+static_assert(offsetof(esengine::ecs::ParticleEmitter, collisionLifetimeLoss) == 352, "ABI offset drift: esengine::ecs::ParticleEmitter.collisionLifetimeLoss (EHT expected 352)");
static_assert(offsetof(esengine::ecs::ParticleForceField, type) == 0, "ABI offset drift: esengine::ecs::ParticleForceField.type (EHT expected 0)");
static_assert(offsetof(esengine::ecs::ParticleForceField, strength) == 4, "ABI offset drift: esengine::ecs::ParticleForceField.strength (EHT expected 4)");
static_assert(offsetof(esengine::ecs::ParticleForceField, radius) == 8, "ABI offset drift: esengine::ecs::ParticleForceField.radius (EHT expected 8)");
@@ -4384,7 +4437,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "6bf8e03097b59051";
+static const char* kEsAbiLayoutHash = "5e943b68bf754ab0";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/ecs/components/ParticleCollider.hpp b/src/esengine/ecs/components/ParticleCollider.hpp
new file mode 100644
index 000000000..5c77f2cb7
--- /dev/null
+++ b/src/esengine/ecs/components/ParticleCollider.hpp
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ParticleCollider.hpp
+ * @brief A shape particles bounce off without any physics: a signed distance a compute kernel can answer per particle.
+ * @details A scene query per particle is not something a million particles can afford, and nothing on the GPU can ask one. A distance
+ * function can be asked of every particle, so an emitter whose `collisionMode` is `Sdf` bounces off every one of these near
+ * it. The CPU simulation answers the same functions, so the look survives a device with no compute.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../math/Math.hpp"
+
+namespace esengine::ecs {
+
+ES_ENUM(stability=beta)
+enum class ParticleColliderShape : i32 {
+ Sphere = 0,
+ Box = 1,
+ Capsule = 2,
+};
+
+ES_COMPONENT(stability=beta)
+struct ParticleCollider {
+ ES_PROPERTY(enum=ParticleColliderShape, category=Shape)
+ i32 shape{static_cast<i32>(ParticleColliderShape::Sphere)};
+
+ // A sphere's radius, and a capsule's round its axis.
+ ES_PROPERTY(min=0, category=Shape)
+ f32 radius{50.0f};
+
+ // A capsule's axis runs along the entity's up, this far each way from its centre.
+ ES_PROPERTY(min=0, category=Shape)
+ f32 halfHeight{50.0f};
+
+ ES_PROPERTY(category=Shape)
+ glm::vec3 halfExtents{50.0f, 50.0f, 50.0f};
+
+ // Keeps particles in rather than out: a dome round a spell, the inside of a jar.
+ ES_PROPERTY(category=Shape)
+ bool inverted{false};
+
+ // Which emitters it stops: one that shares a bit with this in its collisionMask.
+ ES_PROPERTY(bitmask_source=collisionLayers, min=0, max=65535, step=1, category=Shape)
+ u32 mask{65535};
+
+ ES_PROPERTY()
+ bool enabled{true};
+
+ ParticleCollider() = default;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index 70efc5179..13c4bb76b 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -60,6 +60,8 @@ enum class ParticleCollisionMode : i32 {
Floor = 0,
Physics2D = 1,
Physics3D = 2,
+ Depth = 3,
+ Sdf = 4,
};
ES_ENUM(stability=beta)
@@ -99,8 +101,8 @@ struct ParticleEmitter {
i32 maxParticles{1000};
// Simulated by a compute kernel (WebGPU); elsewhere the emitter runs on the CPU, capped. Gravity, damping,
- // noise, force fields, the floor plane and over-life curves apply; sub-emitters, trails and
- // scene-query collision are CPU-only.
+ // noise, force fields, over-life curves, the floor plane, depth and distance-function collision,
+ // sub-emitters and trails apply; a Physics2D/Physics3D scene query is CPU-only.
ES_PROPERTY(category=Emission, tooltip="Simulate on the GPU (WebGPU compute). Falls back to a capped CPU simulation elsewhere. Sub-emitters, trails and physics collision are CPU-only.")
bool gpuSimulation{false};
@@ -329,6 +331,11 @@ struct ParticleEmitter {
ES_PROPERTY(min=0, max=1024, step=1, category=Collision, shown_when=collisionEnabled:true)
i32 collisionEventBudget{32};
+ // Depth mode: how far behind what the camera saw a particle still counts as having hit it, in world units.
+ // Past this it has gone round the back, and passes.
+ ES_PROPERTY(min=0, category=Collision, shown_when=collisionEnabled:true)
+ f32 collisionThickness{30.0f};
+
// Restitution: 0 = particles stop dead on the floor, 1 = a full elastic bounce.
ES_PROPERTY(min=0, max=1, category=Collision, shown_when=collisionEnabled:true)
f32 collisionBounce{0.5f};
diff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cpp
index f9031522e..f0a39cc0b 100644
--- a/src/esengine/particle/ParticleSystem.cpp
+++ b/src/esengine/particle/ParticleSystem.cpp
@@ -65,7 +65,44 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
force_fields_.push_back(inst);
}
+ sdf_colliders_.clear();
+ auto colliderView = registry.activeView<ecs::Transform, ecs::ParticleCollider>();
+ for (auto colliderEntity : colliderView) {
+ const auto& collider = colliderView.get<ecs::ParticleCollider>(colliderEntity);
+ if (!collider.enabled) continue;
+ auto& colliderTransform = colliderView.get<ecs::Transform>(colliderEntity);
+ colliderTransform.ensureDecomposed();
+ const glm::vec3 scale = colliderTransform.worldScale;
+ SdfColliderInstance inst;
+ inst.position = colliderTransform.worldPosition;
+ inst.rotation = colliderTransform.worldRotation;
+ inst.shape = static_cast<f32>(collider.shape);
+ inst.inverted = collider.inverted ? 1.0f : 0.0f;
+ inst.mask = collider.mask & 0xffffu;
+ // A distance function cannot be stretched and stay one, so a round shape takes the largest of its scale.
+ const f32 round = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
+ if (collider.shape == static_cast<i32>(ecs::ParticleColliderShape::Box)) {
+ inst.ext[0] = collider.halfExtents.x * std::abs(scale.x);
+ inst.ext[1] = collider.halfExtents.y * std::abs(scale.y);
+ inst.ext[2] = collider.halfExtents.z * std::abs(scale.z);
+ } else {
+ inst.ext[0] = collider.radius * round;
+ inst.ext[1] = collider.halfHeight * std::abs(scale.y);
+ }
+ sdf_colliders_.push_back(inst);
+ }
+
auto view = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();
+ // A GPU parent's events feed its child in the kernel; the child cannot know how many slots that lights.
+ for (auto& [stateEntity, childState] : states_) childState.gpuFed = false;
+ for (auto parentEntity : view) {
+ const auto& parent = view.get<ecs::ParticleEmitter>(parentEntity);
+ if (parent.subEmitter == 0 || !parent.enabled) continue;
+ auto parentState = states_.find(parentEntity), childState = states_.find(Entity::fromRaw(parent.subEmitter));
+ if (parentState != states_.end() && childState != states_.end() && parentState->second.gpu && childState->second.gpu) {
+ childState->second.gpuFed = true;
+ }
+ }
// Share the App cap across active scene emitters. Rotate remainder slots so
// a budget smaller than the emitter count never permanently starves a tail.
collision_quotas_.clear();
@@ -203,6 +240,18 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
// The kernel does what updateParticles would; this side only keeps the clocks it needs.
state.noise_time += dt;
state.gpuDt += dt;
+ if (emitter.collisionEnabled) {
+ CollisionStats stats; stats.emitter = entity.raw;
+ stats.mode = static_cast<u32>(emitter.collisionMode);
+ for (const GpuCollisions& reported : gpu_collisions_) {
+ if (reported.entity != entity) continue;
+ stats.hits += reported.total;
+ stats.events += static_cast<u32>(reported.events.size());
+ stats.eventDropped += reported.total - static_cast<u32>(reported.events.size());
+ collision_events_.insert(collision_events_.end(), reported.events.begin(), reported.events.end());
+ }
+ collision_stats_.push_back(stats);
+ }
continue;
}
@@ -238,6 +287,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 frameDt) {
emitter.subEmitterInheritVelocity, emitter.subEmitterChance);
}
}
+ gpu_collisions_.clear();
}
void ParticleSystem::play(Entity entity) {
@@ -343,6 +393,8 @@ bool ParticleSystem::peekGpuStep(Entity entity, GpuStep& out) const {
out.spawnCount = std::min(out.smoothCount + state.gpuBurst, state.gpuCapacity);
out.firstIndex = state.gpuSpawned;
out.drawCount = std::min(state.gpuSpawned + out.spawnCount, state.gpuCapacity);
+ out.fed = state.gpuFed;
+ if (state.gpuFed) out.drawCount = state.gpuCapacity;
return true;
}
@@ -736,10 +788,12 @@ void ParticleSystem::collisionStep(const ecs::ParticleEmitter& emitter, EmitterS
Particle& p, glm::vec3 from, const EmitterFrame& frame, bool world) {
const u32 ordinal = state.collisionOrdinal++;
if (emitter.collisionMode == 0) { floorCollision(emitter, state, p, frame, world); return; }
+ if (emitter.collisionMode == static_cast<i32>(ecs::ParticleCollisionMode::Sdf)) { sdfCollision(emitter, state, p, frame, world); return; }
auto& stats = collision_stats_[collision_stats_index_];
auto fallback = [&] {
if (emitter.collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter, state, p, frame, world); }
};
+ // Depth is a picture only the GPU keeps; here it is what it is on any other unknown mode.
if (emitter.collisionMode != 1 && emitter.collisionMode != 2) { ++stats.unavailable; fallback(); return; }
const glm::vec3 start = world ? from : frame.position + frame.rotation * from;
const glm::vec3 end = world ? p.position : frame.position + frame.rotation * p.position;
@@ -778,6 +832,50 @@ void ParticleSystem::floorCollision(const ecs::ParticleEmitter& emitter, Emitter
}
}
+f32 sdfDistance(const SdfColliderInstance& c, const glm::vec3& point) {
+ const glm::vec3 q = glm::inverse(c.rotation) * (point - c.position);
+ f32 d = 0.0f;
+ if (c.shape > 1.5f) {
+ const f32 along = std::clamp(q.y, -c.ext[1], c.ext[1]);
+ d = glm::length(glm::vec3(q.x, q.y - along, q.z)) - c.ext[0];
+ } else if (c.shape > 0.5f) {
+ const glm::vec3 over = glm::abs(q) - glm::vec3(c.ext[0], c.ext[1], c.ext[2]);
+ d = glm::length(glm::max(over, glm::vec3(0.0f))) + std::min(std::max({over.x, over.y, over.z}), 0.0f);
+ } else {
+ d = glm::length(q) - c.ext[0];
+ }
+ return c.inverted > 0.5f ? -d : d;
+}
+
+void ParticleSystem::sdfCollision(const ecs::ParticleEmitter& emitter, EmitterState& state, Particle& p,
+ const EmitterFrame& frame, bool world) {
+ const glm::vec3 point = world ? p.position : frame.position + frame.rotation * p.position;
+ const glm::vec3 velocity = world ? p.velocity : frame.rotation * p.velocity;
+ const SdfColliderInstance* nearest = nullptr;
+ f32 least = 0.0f;
+ for (const SdfColliderInstance& c : sdf_colliders_) {
+ if ((c.mask & emitter.collisionMask) == 0) continue;
+ const f32 d = sdfDistance(c, point);
+ if (d < least) { least = d; nearest = &c; }
+ }
+ if (!nearest) return;
+ // The way out of the shape, measured: the same answer whichever shape it is.
+ const f32 e = std::max(0.01f, -least * 0.1f);
+ const glm::vec3 gradient(
+ sdfDistance(*nearest, point + glm::vec3(e, 0, 0)) - sdfDistance(*nearest, point - glm::vec3(e, 0, 0)),
+ sdfDistance(*nearest, point + glm::vec3(0, e, 0)) - sdfDistance(*nearest, point - glm::vec3(0, e, 0)),
+ sdfDistance(*nearest, point + glm::vec3(0, 0, e)) - sdfDistance(*nearest, point - glm::vec3(0, 0, e)));
+ const f32 size = glm::length(gradient);
+ if (size < 1e-6f) return;
+ const glm::vec3 normal = gradient / size;
+ if (glm::dot(velocity, normal) >= 0.0f) return;
+ collide(emitter, state, p, point - normal * least, normal, 0xffffffffu, frame, world);
+}
+
+void ParticleSystem::addGpuCollisions(Entity entity, u32 total, const CollisionEvent* events, u32 count) {
+ gpu_collisions_.push_back({entity, total, std::vector<CollisionEvent>(events, events + count)});
+}
+
void ParticleSystem::collide(const ecs::ParticleEmitter& emitter, EmitterState& state, Particle& p,
glm::vec3 point, glm::vec3 normal, u32 body, const EmitterFrame& frame, bool world) {
auto& stats = collision_stats_[collision_stats_index_];
diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hpp
index e145ba6d4..e02c5c3db 100644
--- a/src/esengine/particle/ParticleSystem.hpp
+++ b/src/esengine/particle/ParticleSystem.hpp
@@ -8,6 +8,7 @@
#include "../ecs/components/Transform.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
+#include "../ecs/components/ParticleCollider.hpp"
#include "Particle.hpp"
#include "ParticleBursts.hpp"
#include "ParticleEasing.hpp"
@@ -50,6 +51,20 @@ struct ForceFieldInstance {
bool falloff = true;
};
+// A scene ParticleCollider flattened to what a distance function needs, gathered once per update(). The GPU kernel
+// reads the same record: three vec4s and four words, so the layout is the same in both languages.
+struct SdfColliderInstance {
+ glm::vec3 position{0.0f};
+ f32 shape = 0.0f;
+ glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
+ f32 ext[3] = {0.0f, 0.0f, 0.0f}; // sphere: radius. box: half extents. capsule: radius, half height.
+ f32 inverted = 0.0f;
+ u32 mask = 0xffffu;
+ u32 pad[3] = {0, 0, 0};
+};
+/// How far a world point is outside a collider, negative inside; what the kernel's sdfOne answers.
+f32 sdfDistance(const SdfColliderInstance& c, const glm::vec3& point);
+
// Fixed-width batch records shared by Web and native heaps. Integers keep their
// bits (including generational entity IDs); they are not converted through float.
struct CollisionQuery {
@@ -82,6 +97,7 @@ struct GpuStep {
u32 smoothCount = 0;
u32 drawCount = 0; ///< Slots that may hold a live particle once this step has run.
bool reset = false; ///< Kill everything first (a reset() since the last step).
+ bool fed = false; ///< A GPU parent's events spawn into it, so any slot may be live whatever was scheduled.
};
struct EmitterState {
@@ -114,6 +130,7 @@ struct EmitterState {
u32 gpuSmooth = 0, gpuBurst = 0;
u32 gpuSpawned = 0;
bool gpuReset = false;
+ bool gpuFed = false;
explicit EmitterState(u32 capacity) : pool(capacity) {}
};
@@ -145,6 +162,10 @@ public:
/// The kernel ran this step: the time and births it covered are spent.
void commitGpuStep(Entity entity, const GpuStep& step);
const std::vector<ForceFieldInstance>& forceFields() const { return force_fields_; }
+ const std::vector<SdfColliderInstance>& sdfColliders() const { return sdf_colliders_; }
+
+ /// Collisions a kernel reported, a frame or two late since they come back from the GPU; they reach the game as any others do.
+ void addGpuCollisions(Entity entity, u32 total, const CollisionEvent* events, u32 count);
// update() integrates; resolveCollisions() completes all queries in this same
// frame before rendering. No reply survives into the next update.
@@ -218,6 +239,7 @@ private:
void collide(const ecs::ParticleEmitter&, EmitterState&, Particle&, glm::vec3 point,
glm::vec3 normal, u32 body, const EmitterFrame&, bool world);
void floorCollision(const ecs::ParticleEmitter&, EmitterState&, Particle&, const EmitterFrame&, bool world);
+ void sdfCollision(const ecs::ParticleEmitter&, EmitterState&, Particle&, const EmitterFrame&, bool world);
f32 randomRange(f32 min, f32 max);
@@ -255,6 +277,9 @@ private:
// Active scene force fields, rebuilt each update() and applied to world-space
// particles during integration.
std::vector<ForceFieldInstance> force_fields_;
+ std::vector<SdfColliderInstance> sdf_colliders_;
+ struct GpuCollisions { Entity entity; u32 total; std::vector<CollisionEvent> events; };
+ std::vector<GpuCollisions> gpu_collisions_;
// RAII: auto-unregisters from the registry's onDestroy when this system is
// destroyed, so a torn-down system never leaves a dangling `this` behind.
Connection destroyConn_;
diff --git a/src/esengine/renderer/frame/GpuParticles.cpp b/src/esengine/renderer/frame/GpuParticles.cpp
index acdf3aee0..ce06ce0fa 100644
--- a/src/esengine/renderer/frame/GpuParticles.cpp
+++ b/src/esengine/renderer/frame/GpuParticles.cpp
@@ -33,8 +33,25 @@ enum Flags : u32 {
kColorLut = 1u << 4,
kSpeedLut = 1u << 5,
kFloor = 1u << 6,
+ kDepth = 1u << 7,
+ kSdf = 1u << 8,
+ kEmitBirth = 1u << 9,
+ kEmitDeath = 1u << 10,
+ kEmitHit = 1u << 11,
+ kFed = 1u << 12,
+ kTrail = 1u << 13,
};
+// An event a kernel appends and another reads: where and which kind, how fast, and the surface it hit with the slot that hit it.
+constexpr u32 kEventBytes = 48;
+constexpr u32 kEventHeaderBytes = 16;
+// The most events one emitter keeps of a frame. Past it they are dropped: a child would have nowhere to put so many anyway.
+constexpr u32 kMaxEvents = 4096;
+constexpr u32 kMaxColliders = 64;
+static_assert(sizeof(particle::SdfColliderInstance) == 64, "the kernel's Collider is 64 bytes");
+// The depth a frame leaves, at most this many texels across: a particle needs where a surface is, not its edges.
+constexpr u32 kDepthGridMax = 640;
+
// Mirrors the kernel's `Params`: vec4s only, so the layout is the same in both languages with no padding to get wrong.
struct ParamsBlock {
u32 p0[4]; // capacity, firstIndex, spawnCount, smoothCount
@@ -60,12 +77,20 @@ struct ParamsBlock {
f32 colorLut[kLutSize][4];
f32 sizeLut[kLutSize / 4][4];
f32 speedLut[kLutSize / 4][4];
+ u32 p12[4]; // frame, eventCapacity, subBurst, colliderCount
+ f32 p13[4]; // eventChance, inheritVelocity, thickness, depthValid
+ u32 p14[4]; // trailPoints, collisionMask, depthGridW, depthGridH
+ f32 p15[4]; // trailWidth, trailMinDistance, 0, 0
+ f32 camera[4]; // the eye (w 1) or the way to the viewer (w 0), as the draw's vertex stage has it
+ f32 depthClip[4][4], depthWorld[4][4]; // the view the depth was left by, and its inverse
+ f32 depthOrigin[4]; // the render origin it was seen from
};
-static_assert(sizeof(ParamsBlock) == 93 * 16, "the kernel's Params is 93 vec4s");
+static_assert(sizeof(ParamsBlock) == 107 * 16, "the kernel's Params is 107 vec4s");
constexpr u32 kJobStride = 2048; // a uniform binding starts on a multiple of 256
static_assert(sizeof(ParamsBlock) <= kJobStride && kJobStride % 256 == 0);
constexpr u32 kMaxJobs = 64;
+// In pieces: MSVC refuses one string literal past 16 KB, and takes adjacent ones to 64.
const char* const kKernel = R"WGSL(
struct State { pa: vec4<f32>, vl: vec4<f32>, ms: vec4<f32> };
struct Inst { px: f32, py: f32, pz: f32, sx: f32, sy: f32, rot: f32, color: u32, u0: f32, v0: f32, us: f32, vs: f32 };
@@ -83,12 +108,28 @@ struct Params {
colorLut: array<vec4<f32>, 32>,
sizeLut: array<vec4<f32>, 8>,
speedLut: array<vec4<f32>, 8>,
+ p12: vec4<u32>, p13: vec4<f32>, p14: vec4<u32>, p15: vec4<f32>,
+ camera: vec4<f32>,
+ depthClip: mat4x4<f32>, depthWorld: mat4x4<f32>,
+ depthOrigin: vec4<f32>,
};
+struct EventRec { at: vec4<f32>, vel: vec4<f32>, normal: vec4<f32> };
+struct Events { count: atomic<u32>, head: u32, capacity: u32, pad: u32, rec: array<EventRec> };
+struct EventsIn { count: u32, head: u32, capacity: u32, pad: u32, rec: array<EventRec> };
+struct Collider { at: vec4<f32>, rot: vec4<f32>, ext: vec4<f32>, mask: vec4<u32> };
@group(0) @binding(0) var<uniform> P: Params;
@group(0) @binding(1) var<storage, read_write> states: array<State>;
@group(0) @binding(2) var<storage, read_write> insts: array<Inst>;
+@group(0) @binding(3) var<storage, read_write> events: Events;
+@group(0) @binding(4) var<storage, read> parentEvents: EventsIn;
+@group(0) @binding(5) var<storage, read> depthGrid: array<f32>;
+@group(0) @binding(6) var<storage, read> colliders: array<Collider>;
+@group(0) @binding(7) var<storage, read_write> trail: array<vec4<f32>>;
+@group(0) @binding(8) var<storage, read_write> segments: array<Inst>;
var<private> rng: u32;
+var<private> hitPoint: vec3<f32>;
+var<private> hitNormal: vec3<f32>;
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
@@ -230,6 +271,216 @@ fn applyField(k: u32, pos: vec3<f32>, vel: vec3<f32>, dt: f32) -> vec3<f32> {
fn hide(i: u32) {
insts[i] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0);
+ if ((P.p1.y & 8192u) != 0u) {
+ let n = P.p14.x - 1u;
+ for (var j = 0u; j < n; j = j + 1u) {
+ segments[i * n + j] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0);
+ }
+ }
+}
+
+)WGSL"
+R"WGSL(
+// --- events: what another emitter's kernel, or the game a frame or two later, is told ---
+fn emitEvent(kind: f32, at: vec3<f32>, vel: vec3<f32>, normal: vec3<f32>, slot: u32) {
+ if (P.p13.x < 1.0 && rand() >= P.p13.x) { return; }
+ let k = atomicAdd(&events.count, 1u);
+ if (k < P.p12.y) {
+ events.rec[k] = EventRec(vec4<f32>(at, kind), vec4<f32>(vel, 0.0), vec4<f32>(normal, f32(slot)));
+ }
+}
+
+// --- the depth the last frame left: reprojected with the camera that saw it, so a turning camera does not smear it ---
+fn depthAt(tx: i32, ty: i32) -> f32 {
+ let w = i32(P.p14.z);
+ let h = i32(P.p14.w);
+ if (tx < 0 || ty < 0 || tx >= w || ty >= h) { return 1.0; }
+ return depthGrid[u32(ty * w + tx)];
+}
+fn unproject(uv: vec2<f32>, depth: f32) -> vec3<f32> {
+ let world = P.depthWorld * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
+ return world.xyz / world.w;
+}
+fn texelSurface(tx: i32, ty: i32, depth: f32) -> vec3<f32> {
+ return unproject((vec2<f32>(f32(tx), f32(ty)) + 0.5) / vec2<f32>(f32(P.p14.z), f32(P.p14.w)), depth);
+}
+fn depthHit(point: vec3<f32>, vel: vec3<f32>, dt: f32) -> bool {
+ let rel = point - P.depthOrigin.xyz;
+ let clip = P.depthClip * vec4<f32>(rel, 1.0);
+ if (clip.w <= 0.0) { return false; }
+ let ndc = clip.xyz / clip.w;
+ if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { return false; }
+ let uv = vec2<f32>((ndc.x + 1.0) * 0.5, (1.0 - ndc.y) * 0.5);
+ let tx = i32(uv.x * f32(P.p14.z));
+ let ty = i32(uv.y * f32(P.p14.w));
+ let depth = depthAt(tx, ty);
+ if (depth >= 1.0) { return false; }
+ let ray = normalize(unproject(uv, 1.0) - unproject(uv, 0.0));
+ let surface = texelSurface(tx, ty, depth);
+ let behind = dot(rel - surface, ray);
+ // A particle may cross more than the thickness in a step, and still have hit what it crossed.
+ if (behind < 0.0 || behind > max(P.p13.z, length(vel) * dt)) { return false; }
+ // The surface's slope from the texels beside it, each way from whichever is nearer: an edge belongs to what stands in front.
+ var normal = -ray;
+ let l = depthAt(tx - 1, ty);
+ let r = depthAt(tx + 1, ty);
+ let u = depthAt(tx, ty - 1);
+ let d = depthAt(tx, ty + 1);
+ let useR = abs(r - depth) <= abs(l - depth);
+ let useD = abs(d - depth) <= abs(u - depth);
+ let hx = select(l, r, useR);
+ let hy = select(u, d, useD);
+ if (hx < 1.0 && hy < 1.0) {
+ let across = texelSurface(select(tx - 1, tx + 1, useR), ty, hx) - surface;
+ let along = texelSurface(tx, select(ty - 1, ty + 1, useD), hy) - surface;
+ let n = cross(across, along);
+ let size = length(n);
+ if (size > 1e-8) {
+ normal = n / size;
+ if (dot(normal, ray) > 0.0) { normal = -normal; }
+ }
+ }
+ if (dot(vel, normal) >= 0.0) { return false; }
+ hitNormal = normal;
+ hitPoint = surface + P.depthOrigin.xyz + normal * (0.001 * P.p13.z);
+ return true;
+}
+
+// --- the distance functions (ParticleSystem sdfDistance) ---
+fn turnBack(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
+ let u = -q.xyz;
+ return v + 2.0 * cross(u, cross(u, v) + q.w * v);
+}
+fn sdfOne(k: u32, point: vec3<f32>) -> f32 {
+ let c = colliders[k];
+ let q = turnBack(c.rot, point - c.at.xyz);
+ var d: f32;
+ if (c.at.w > 1.5) {
+ let along = clamp(q.y, -c.ext.y, c.ext.y);
+ d = length(vec3<f32>(q.x, q.y - along, q.z)) - c.ext.x;
+ } else if (c.at.w > 0.5) {
+ let over = abs(q) - c.ext.xyz;
+ d = length(max(over, vec3<f32>(0.0))) + min(max(over.x, max(over.y, over.z)), 0.0);
+ } else {
+ d = length(q) - c.ext.x;
+ }
+ if (c.ext.w > 0.5) { return -d; }
+ return d;
+}
+fn sdfHit(point: vec3<f32>, vel: vec3<f32>) -> bool {
+ var least = 0.0;
+ var found = P.p12.w;
+ for (var k = 0u; k < P.p12.w; k = k + 1u) {
+ if ((colliders[k].mask.x & P.p14.y) == 0u) { continue; }
+ let d = sdfOne(k, point);
+ if (d < least) { least = d; found = k; }
+ }
+ if (found == P.p12.w) { return false; }
+ let e = max(0.01, -least * 0.1);
+ let g = vec3<f32>(
+ sdfOne(found, point + vec3<f32>(e, 0.0, 0.0)) - sdfOne(found, point - vec3<f32>(e, 0.0, 0.0)),
+ sdfOne(found, point + vec3<f32>(0.0, e, 0.0)) - sdfOne(found, point - vec3<f32>(0.0, e, 0.0)),
+ sdfOne(found, point + vec3<f32>(0.0, 0.0, e)) - sdfOne(found, point - vec3<f32>(0.0, 0.0, e)));
+ let size = length(g);
+ if (size < 1e-6) { return false; }
+ let normal = g / size;
+ if (dot(vel, normal) >= 0.0) { return false; }
+ hitNormal = normal;
+ hitPoint = point - normal * least;
+ return true;
+}
+
+// --- trails: each piece of the path as a quad the particle draw already knows, turned to lie along it as seen ---
+fn segmentBetween(a: vec3<f32>, b: vec3<f32>, width: f32, color: vec4<f32>) -> Inst {
+ let mid = (a + b) * 0.5 - P.shift.xyz;
+ var fwd = P.camera.xyz;
+ if (P.camera.w > 0.5) { fwd = normalize(P.camera.xyz - mid); }
+ var refUp = vec3<f32>(0.0, 1.0, 0.0);
+ if (abs(fwd.y) > 0.999) { refUp = vec3<f32>(0.0, 0.0, 1.0); }
+ let right = normalize(cross(refUp, fwd));
+ let up = cross(fwd, right);
+ let d = b - a;
+ let x = dot(d, right);
+ let y = dot(d, up);
+ return Inst(mid.x, mid.y, mid.z, sqrt(x * x + y * y), width, atan2(y, x), pack4x8unorm(color), 0.0, 0.0, 1.0, 1.0);
+}
+fn stepTrail(i: u32, head: vec3<f32>, born: bool, color: vec4<f32>) {
+ let points = P.p14.x;
+ let n = points - 1u;
+ let base = i * points;
+ var count = u32(trail[base].w);
+ if (born || count == 0u) {
+ trail[base] = vec4<f32>(head, 1.0);
+ count = 1u;
+ } else {
+ let last = trail[base].xyz;
+ if (distance(head, last) >= P.p15.y) {
+ for (var k = n; k > 0u; k = k - 1u) { trail[base + k] = trail[base + k - 1u]; }
+ count = min(count + 1u, points);
+ trail[base] = vec4<f32>(head, f32(count));
+ }
+ }
+ var prev = head;
+ for (var j = 0u; j < n; j = j + 1u) {
+ if (j >= count) {
+ segments[i * n + j] = Inst(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0u, 0.0, 0.0, 1.0, 1.0);
+ continue;
+ }
+ let next = trail[base + j].xyz;
+ let fadeOut = 1.0 - (f32(j) + 0.5) / f32(n);
+ segments[i * n + j] = segmentBetween(prev, next, P.p15.x * fadeOut, vec4<f32>(color.rgb, color.a * fadeOut));
+ prev = next;
+ }
+}
+
+)WGSL"
+R"WGSL(
+fn bornState(origin: vec3<f32>, inherit: vec3<f32>, world: bool) -> State {
+ let life = rr(P.p2.z, P.p2.w);
+ let startSize = rr(P.p3.z, P.p3.w);
+ let endSize = rr(P.p4.x, P.p4.y);
+ let rot = rr(P.p4.z, P.p4.w);
+ let angVel = rr(P.p5.x, P.p5.y);
+
+ var pos = vec3<f32>(0.0);
+ var dir = vec3<f32>(0.0, 1.0, 0.0);
+ let shape = P.p1.z;
+ if (shape == 1u) {
+ let angle = rr(0.0, 6.283185307179586);
+ let radius = rr(0.0, P.p7.z);
+ pos = vec3<f32>(cos(angle) * radius, sin(angle) * radius, 0.0);
+ if (radius > 0.001) { dir = pos / radius; } else { dir = planarAim(); }
+ } else if (shape == 2u) {
+ let h = P.p8.xyz * 0.5;
+ let x = rr(-h.x, h.x);
+ let y = rr(-h.y, h.y);
+ var z = 0.0;
+ if (P.p8.z > 0.0) { z = rr(-h.z, h.z); }
+ pos = vec3<f32>(x, y, z);
+ dir = planarAim();
+ } else if (shape == 3u) {
+ dir = coneDir(P.p7.w);
+ pos = coneDir(P.p7.w) * rr(0.0, P.p7.z);
+ } else if (shape == 4u || shape == 5u) {
+ var cap2 = 3.141592653589793;
+ if (shape == 5u) { cap2 = 1.5707963267948966; }
+ dir = coneDir(cap2);
+ pos = coneDir(cap2) * (P.p7.z * pow(rr(0.0, 1.0), 1.0 / 3.0));
+ } else {
+ dir = planarAim();
+ }
+ let speed = rr(P.p3.x, P.p3.y);
+ let R = mat3x3<f32>(P.rot0.xyz, P.rot1.xyz, P.rot2.xyz);
+ var wpos: vec3<f32>;
+ var wdir: vec3<f32>;
+ if (!world) {
+ wpos = origin + pos * P.scale.xyz;
+ wdir = dir;
+ } else {
+ wpos = origin + R * (pos * P.scale.xyz);
+ wdir = R * dir;
+ }
+ return State(vec4<f32>(wpos, 0.0), vec4<f32>(wdir * speed + inherit, max(life, 1e-4)), vec4<f32>(startSize, endSize, rot, angVel));
}
@compute @workgroup_size(64)
@@ -249,68 +500,57 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
var st = states[i];
var stepDt = dt;
+ var born = false;
+ rng = pcg(P.p1.x ^ (i * 2654435761u) ^ (P.p12.x * 40503u));
// Born this step? Slot i holds the particle whose absolute index lands on it.
let first = P.p0.y % cap;
let rel = (i + cap - first) % cap;
if (rel < P.p0.z) {
rng = pcg(P.p1.x ^ ((P.p0.y + rel) * 2654435761u));
- let life = rr(P.p2.z, P.p2.w);
- let startSize = rr(P.p3.z, P.p3.w);
- let endSize = rr(P.p4.x, P.p4.y);
- let rot = rr(P.p4.z, P.p4.w);
- let angVel = rr(P.p5.x, P.p5.y);
-
- var pos = vec3<f32>(0.0);
- var dir = vec3<f32>(0.0, 1.0, 0.0);
- let shape = P.p1.z;
- if (shape == 1u) {
- let angle = rr(0.0, 6.283185307179586);
- let radius = rr(0.0, P.p7.z);
- pos = vec3<f32>(cos(angle) * radius, sin(angle) * radius, 0.0);
- if (radius > 0.001) { dir = pos / radius; } else { dir = planarAim(); }
- } else if (shape == 2u) {
- let h = P.p8.xyz * 0.5;
- let x = rr(-h.x, h.x);
- let y = rr(-h.y, h.y);
- var z = 0.0;
- if (P.p8.z > 0.0) { z = rr(-h.z, h.z); }
- pos = vec3<f32>(x, y, z);
- dir = planarAim();
- } else if (shape == 3u) {
- dir = coneDir(P.p7.w);
- pos = coneDir(P.p7.w) * rr(0.0, P.p7.z);
- } else if (shape == 4u || shape == 5u) {
- var cap2 = 3.141592653589793;
- if (shape == 5u) { cap2 = 1.5707963267948966; }
- dir = coneDir(cap2);
- pos = coneDir(cap2) * (P.p7.z * pow(rr(0.0, 1.0), 1.0 / 3.0));
- } else {
- dir = planarAim();
- }
- let speed = rr(P.p3.x, P.p3.y);
- var wpos: vec3<f32>;
- var wdir: vec3<f32>;
- if (local) {
- wpos = pos * P.scale.xyz;
- wdir = dir;
- } else {
- wpos = P.origin.xyz + R * (pos * P.scale.xyz);
- wdir = R * dir;
- }
- st = State(vec4<f32>(wpos, 0.0), vec4<f32>(wdir * speed, max(life, 1e-4)), vec4<f32>(startSize, endSize, rot, angVel));
+ var at = P.origin.xyz;
+ if (local) { at = vec3<f32>(0.0); }
+ st = bornState(at, vec3<f32>(0.0), !local);
+ born = true;
// Rate-born particles are spread across the step they were born in, so a fast emitter draws a line, not a row of clumps.
if (rel < P.p0.w) { stepDt = dt * (1.0 - (f32(rel) + 0.5) / f32(P.p0.w)); }
- } else if (st.pa.w >= st.vl.w) {
+ } else if ((flags & 4096u) != 0u) {
+ // Or a parent's event lit it, each event its child's burst, from where the ring stopped last frame.
+ let burst = max(P.p12.z, 1u);
+ let lit = min(min(parentEvents.count, parentEvents.capacity) * burst, cap);
+ let fromHead = (i + cap - events.head % cap) % cap;
+ if (fromHead < lit) {
+ let e = parentEvents.rec[fromHead / burst];
+ rng = pcg(P.p1.x ^ ((events.head + fromHead) * 2654435761u) ^ (P.p12.x * 40503u));
+ var at = e.at.xyz;
+ var carried = e.vel.xyz * P.p13.y;
+ if (local) { at = transpose(R) * (at - P.origin.xyz); carried = transpose(R) * carried; }
+ st = bornState(at, carried, !local);
+ born = true;
+ }
+ }
+ if (!born && st.pa.w >= st.vl.w) {
hide(i);
return;
}
+ if (born && (flags & 512u) != 0u) {
+ var bornAt = st.pa.xyz;
+ var bornVel = st.vl.xyz;
+ if (local) { bornAt = P.origin.xyz + R * bornAt; bornVel = R * bornVel; }
+ emitEvent(1.0, bornAt, bornVel, vec3<f32>(0.0), i);
+ }
let life = st.vl.w;
var age = st.pa.w + stepDt;
if (age >= life) {
st.pa.w = life;
states[i] = st;
+ if ((flags & 1024u) != 0u) {
+ var deadAt = st.pa.xyz;
+ var deadVel = st.vl.xyz;
+ if (local) { deadAt = P.origin.xyz + R * deadAt; deadVel = R * deadVel; }
+ emitEvent(0.0, deadAt, deadVel, vec3<f32>(0.0), i);
+ }
hide(i);
return;
}
@@ -332,16 +572,27 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
pos = pos + vec3<f32>(flow, 0.0) * P.p6.z * stepDt;
}
- if ((flags & 64u) != 0u) {
+ if ((flags & (64u | 128u | 256u)) != 0u) {
var point = pos;
var velW = vel;
if (local) { point = P.origin.xyz + R * pos; velW = R * vel; }
- if (point.y < P.p9.w && velW.y < 0.0) {
- let approach = velW.y;
+ var collided = false;
+ if ((flags & 64u) != 0u && point.y < P.p9.w && velW.y < 0.0) {
+ hitPoint = vec3<f32>(point.x, P.p9.w, point.z);
+ hitNormal = vec3<f32>(0.0, 1.0, 0.0);
+ collided = true;
+ } else if ((flags & 128u) != 0u && P.p13.w > 0.5) {
+ collided = depthHit(point, velW, stepDt);
+ } else if ((flags & 256u) != 0u) {
+ collided = sdfHit(point, velW);
+ }
+ if (collided) {
+ let approach = dot(velW, hitNormal);
let fr = clamp(P.p10.y, 0.0, 1.0);
let bounce = clamp(P.p10.x, 0.0, 1.0);
- velW = vec3<f32>(velW.x, 0.0, velW.z) * (1.0 - fr) - vec3<f32>(0.0, approach * bounce, 0.0);
- point = vec3<f32>(point.x, P.p9.w, point.z);
+ let incoming = velW;
+ velW = (velW - hitNormal * approach) * (1.0 - fr) - hitNormal * approach * bounce;
+ point = hitPoint;
if (local) {
pos = transpose(R) * (point - P.origin.xyz);
vel = transpose(R) * velW;
@@ -349,10 +600,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
pos = point;
vel = velW;
}
+ if ((flags & 2048u) != 0u) { emitEvent(2.0, point, incoming, hitNormal, i); }
age = age + clamp(P.p10.z, 0.0, 1.0) * life;
if (age >= life) {
st.pa.w = life;
states[i] = st;
+ if ((flags & 1024u) != 0u) { emitEvent(0.0, point, velW, vec3<f32>(0.0), i); }
hide(i);
return;
}
@@ -395,11 +648,50 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
worldPos = P.origin.xyz + vec3<f32>(rel3.x * P.local.x - rel3.y * P.local.y, rel3.x * P.local.y + rel3.y * P.local.x, rel3.z);
worldSize = worldSize * vec2<f32>(P.local.z, P.local.w);
}
+ if ((flags & 8192u) != 0u) { stepTrail(i, worldPos, born, color); }
worldPos = worldPos - P.shift.xyz;
insts[i] = Inst(worldPos.x, worldPos.y, worldPos.z, worldSize.x, worldSize.y, rotation, pack4x8unorm(color), u0, v0, us, vs);
}
)WGSL";
+// Before an emitter's kernel: its events are this frame's. After: the ring has moved on by what its parent lit.
+const char* const kEventControl = R"WGSL(
+struct Control { p: vec4<u32> };
+struct Events { count: atomic<u32>, head: u32, capacity: u32, pad: u32 };
+struct EventsIn { count: u32, head: u32, capacity: u32, pad: u32 };
+@group(0) @binding(0) var<uniform> C: Control;
+@group(0) @binding(1) var<storage, read_write> events: Events;
+@group(0) @binding(2) var<storage, read> parentEvents: EventsIn;
+
+@compute @workgroup_size(1)
+fn begin() {
+ atomicStore(&events.count, 0u);
+ events.capacity = C.p.x;
+}
+@compute @workgroup_size(1)
+fn finish() {
+ let lit = min(min(parentEvents.count, parentEvents.capacity) * max(C.p.y, 1u), C.p.z);
+ events.head = (events.head + lit) % max(C.p.z, 1u);
+}
+)WGSL";
+
+// The scene's depth left where next frame's kernel can read it: no texture survives a graph, and a buffer is what the kernel already has.
+const char* const kDepthCopy = R"WGSL(
+struct Grid { size: vec4<u32> };
+@group(0) @binding(0) var<uniform> G: Grid;
+@group(0) @binding(1) var depth: texture_depth_2d;
+@group(0) @binding(2) var<storage, read_write> grid: array<f32>;
+
+@compute @workgroup_size(8, 8)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (gid.x >= G.size.x || gid.y >= G.size.y) { return; }
+ let dims = vec2<f32>(textureDimensions(depth));
+ let at = (vec2<f32>(gid.xy) + 0.5) / vec2<f32>(G.size.xy) * dims;
+ let texel = clamp(vec2<i32>(at), vec2<i32>(0), vec2<i32>(dims) - vec2<i32>(1));
+ grid[gid.y * G.size.x + gid.x] = textureLoad(depth, texel, 0);
+}
+)WGSL";
+
void set4(f32 (&dst)[4], f32 a, f32 b, f32 c, f32 d) { dst[0] = a; dst[1] = b; dst[2] = c; dst[3] = d; }
void set4(u32 (&dst)[4], u32 a, u32 b, u32 c, u32 d) { dst[0] = a; dst[1] = b; dst[2] = c; dst[3] = d; }
@@ -414,6 +706,10 @@ struct GpuParticles::Job {
Slot* slot;
particle::ParticleSystem* system;
particle::GpuStep step;
+ u32 subEmitter = 0; ///< The child its events feed.
+ f32 inheritVelocity = 0; ///< What of a parent's speed that child keeps.
+ u32 eventCapacity = 0;
+ u32 reportEvents = 0; ///< How many of its events the game asks to hear about.
};
GpuParticles::GpuParticles(GfxDevice& device) : device_(device) {}
@@ -429,6 +725,10 @@ bool GpuParticles::available() const {
void GpuParticles::freeSlot(Slot& slot) {
if (slot.state != BufferHandle::Invalid) device_.deleteBuffer(slot.state);
if (slot.instances != BufferHandle::Invalid) device_.deleteBuffer(slot.instances);
+ if (slot.events != BufferHandle::Invalid) device_.deleteBuffer(slot.events);
+ if (slot.trail != BufferHandle::Invalid) device_.deleteBuffer(slot.trail);
+ if (slot.segments != BufferHandle::Invalid) device_.deleteBuffer(slot.segments);
+ if (slot.readback != ReadbackHandle::Invalid) device_.discardReadback(slot.readback);
slot = {};
}
@@ -441,6 +741,18 @@ void GpuParticles::release() {
paramsCapacity_ = 0;
if (kernel_ != ComputeHandle::Invalid) device_.deleteCompute(kernel_);
kernel_ = ComputeHandle::Invalid;
+ for (ComputeHandle* k : {&beginEvents_, &finishEvents_, &depthCopy_}) {
+ if (*k != ComputeHandle::Invalid) device_.deleteCompute(*k);
+ *k = ComputeHandle::Invalid;
+ }
+ for (BufferHandle* b : {&control_, &emptyRead_, &emptyEvents_, &emptyTrail_, &emptySegments_, &colliders_, &depthGrid_, &depthParams_}) {
+ if (*b != BufferHandle::Invalid) device_.deleteBuffer(*b);
+ *b = BufferHandle::Invalid;
+ }
+ controlCapacity_ = 0;
+ collidersCapacity_ = 0;
+ depthW_ = depthH_ = 0;
+ depthValid_ = false;
failed_ = false;
}
@@ -449,6 +761,10 @@ void GpuParticles::beginFrame() {
jobs_.clear();
lastDispatches_ = 0;
drawn_ = 0;
+ depthCopied_ = false;
+ wantsDepth_ = wantsDepthNext_;
+ wantsDepthNext_ = false;
+ pollReadbacks();
// Given back after a few seconds unseen: an emitter off screen keeps its particles for a moment, not for ever.
for (auto it = slots_.begin(); it != slots_.end();) {
if (frame_ > it->second.lastUsed + 300) {
@@ -473,6 +789,58 @@ bool GpuParticles::ensureKernel() {
return true;
}
+bool GpuParticles::ensureEventKernels() {
+ if (beginEvents_ != ComputeHandle::Invalid && finishEvents_ != ComputeHandle::Invalid) return true;
+ std::string log;
+ beginEvents_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kEventControl, "begin"}, &log);
+ finishEvents_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kEventControl, "finish"}, &log);
+ if (beginEvents_ == ComputeHandle::Invalid || finishEvents_ == ComputeHandle::Invalid) {
+ ES_LOG_ERROR("GpuParticles: the event kernels did not compile: {}", log);
+ return false;
+ }
+ return true;
+}
+
+void GpuParticles::ensureEmpties() {
+ // A kernel's layout is fixed, so what an emitter does not use is still bound; written-to bindings may not share a buffer.
+ const auto make = [this](BufferHandle& b, u32 size) {
+ if (b == BufferHandle::Invalid) b = device_.createBuffer({GfxBufferUsage::Storage, size, false}, GfxContent::transient(), nullptr);
+ };
+ make(emptyRead_, 128);
+ make(emptyEvents_, 128);
+ make(emptyTrail_, 64);
+ make(emptySegments_, 64);
+}
+
+void GpuParticles::pollReadbacks() {
+ for (auto& [id, slot] : slots_) {
+ if (slot.readback == ReadbackHandle::Invalid) continue;
+ const GfxReadbackStatus status = device_.pollReadback(slot.readback);
+ if (status == GfxReadbackStatus::Pending) continue;
+ const ReadbackHandle handle = slot.readback;
+ slot.readback = ReadbackHandle::Invalid;
+ if (status != GfxReadbackStatus::Ready) continue;
+ std::vector<u8> bytes(slot.readbackBytes);
+ if (!device_.takeReadback(handle, bytes.data(), bytes.size()) || !slot.system) continue;
+ u32 total = 0;
+ std::memcpy(&total, bytes.data(), sizeof(u32));
+ const u32 kept = std::min(total, (slot.readbackBytes - kEventHeaderBytes) / kEventBytes);
+ std::vector<particle::CollisionEvent> out;
+ out.reserve(kept);
+ u32 hits = 0;
+ for (u32 k = 0; k < kept; ++k) {
+ f32 r[12];
+ std::memcpy(r, bytes.data() + kEventHeaderBytes + k * kEventBytes, sizeof(r));
+ if (r[3] < 1.5f) continue;
+ ++hits;
+ out.push_back({id, static_cast<u32>(r[11]), 0xffffffffu, slot.collisionMode,
+ r[0], r[1], r[2], r[8], r[9], r[10], r[4], r[5], r[6], 1u});
+ }
+ // Past what was kept, the kinds are not known; every event of an emitter that only reports hits is one.
+ slot.system->addGpuCollisions(Entity::fromRaw(id), total > kept ? hits + (total - kept) : hits, out.data(), static_cast<u32>(out.size()));
+ }
+}
+
GpuParticles::Slot* GpuParticles::ensureSlot(Entity entity, u32 capacity) {
Slot& slot = slots_[entity.raw];
slot.lastUsed = frame_;
@@ -493,12 +861,58 @@ GpuParticles::Slot* GpuParticles::ensureSlot(Entity entity, u32 capacity) {
}
bool GpuParticles::submit(Entity entity, const ecs::ParticleEmitter& emitter, const ecs::Transform& transform,
- particle::ParticleSystem& system, const particle::GpuStep& step, BufferHandle& instances) {
+ particle::ParticleSystem& system, const particle::GpuStep& step, const glm::vec4& eye,
+ BufferHandle& instances, BufferHandle& segments, u32& segmentCount) {
if (!ensureKernel() || step.capacity == 0) return false;
Slot* slot = ensureSlot(entity, step.capacity);
if (!slot) return false;
instances = slot->instances;
drawn_ += step.drawCount;
+ slot->system = &system;
+ slot->collisionMode = static_cast<u32>(emitter.collisionMode);
+
+ const bool collides = emitter.collisionEnabled;
+ const i32 mode = emitter.collisionMode;
+ const bool depthMode = collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Depth);
+ const bool sdfMode = collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Sdf);
+ if (depthMode) wantsDepthNext_ = true;
+
+ // What an emitter fires: its child's trigger, and what the game asks to hear.
+ const bool hasChild = emitter.subEmitter != 0;
+ const i32 trigger = emitter.subEmitterTrigger;
+ const u32 report = collides && emitter.collisionEvents ? static_cast<u32>(std::clamp(emitter.collisionEventBudget, 0, 1024)) : 0u;
+ const bool emitsBirth = hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Birth);
+ const bool emitsDeath = hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Death);
+ const bool emitsHit = (hasChild && trigger == static_cast<i32>(ecs::SubEmitterTrigger::Collision)) || report > 0;
+ const bool emits = emitsBirth || emitsDeath || emitsHit;
+ const u32 eventCapacity = emits ? kMaxEvents : 1u;
+ if (emits || step.fed) {
+ const u32 bytes = kEventHeaderBytes + eventCapacity * kEventBytes;
+ if (slot->events == BufferHandle::Invalid || slot->eventBytes != bytes) {
+ if (slot->events != BufferHandle::Invalid) device_.deleteBuffer(slot->events);
+ slot->events = device_.createBuffer({GfxBufferUsage::Storage, bytes, false}, GfxContent::transient(), nullptr);
+ slot->eventBytes = bytes;
+ if (slot->events == BufferHandle::Invalid) return false;
+ }
+ }
+
+ const bool trailOn = emitter.trailEnabled && emitter.trailWidth > 0.0f;
+ const u32 points = static_cast<u32>(std::clamp(emitter.trailPoints, 2, particle::kMaxTrailPoints));
+ if (trailOn) {
+ if (slot->trail == BufferHandle::Invalid || slot->trailPoints != points) {
+ if (slot->trail != BufferHandle::Invalid) device_.deleteBuffer(slot->trail);
+ if (slot->segments != BufferHandle::Invalid) device_.deleteBuffer(slot->segments);
+ slot->trail = device_.createBuffer({GfxBufferUsage::Storage, step.capacity * points * 16u, false}, GfxContent::transient(), nullptr);
+ slot->segments = device_.createBuffer({GfxBufferUsage::Storage, step.capacity * (points - 1u) * kInstanceBytes, false}, GfxContent::transient(), nullptr);
+ slot->trailPoints = points;
+ if (slot->trail == BufferHandle::Invalid || slot->segments == BufferHandle::Invalid) {
+ ES_LOG_ERROR("GpuParticles: could not allocate trails for {} particles", step.capacity);
+ return false;
+ }
+ }
+ segments = slot->segments;
+ segmentCount = step.drawCount * (points - 1u);
+ }
// A second camera's collect asks for the same step until the first has run it.
for (const Job& queued : jobs_) {
@@ -518,7 +932,17 @@ bool GpuParticles::submit(Entity entity, const ecs::ParticleEmitter& emitter, co
if (local) flags |= kLocal;
const bool noiseOn = emitter.noiseStrength > 0.0f && emitter.noiseFrequency > 0.0f;
if (noiseOn) flags |= kNoise;
- if (emitter.collisionEnabled) flags |= kFloor;
+ if (collides && mode == static_cast<i32>(ecs::ParticleCollisionMode::Floor)) flags |= kFloor;
+ // A scene query is the CPU's to ask; here, what the emitter says to do when one is not to be had.
+ if (collides && (mode == static_cast<i32>(ecs::ParticleCollisionMode::Physics2D) || mode == static_cast<i32>(ecs::ParticleCollisionMode::Physics3D))
+ && emitter.collisionFallback == static_cast<i32>(ecs::ParticleCollisionFallback::Floor)) flags |= kFloor;
+ if (depthMode) flags |= kDepth;
+ if (sdfMode) flags |= kSdf;
+ if (emitsBirth) flags |= kEmitBirth;
+ if (emitsDeath) flags |= kEmitDeath;
+ if (emitsHit) flags |= kEmitHit;
+ if (step.fed) flags |= kFed;
+ if (trailOn) flags |= kTrail;
const auto* colorLut = system.colorLut(entity);
const auto* sizeLut = system.sizeLut(entity);
@@ -577,10 +1001,80 @@ bool GpuParticles::submit(Entity entity, const ecs::ParticleEmitter& emitter, co
if (speedLut) b.speedLut[k >> 2][k & 3] = (*speedLut)[k];
}
+ set4(b.p12, static_cast<u32>(frame_), eventCapacity, static_cast<u32>(std::max(emitter.burstCount, 1)),
+ sdfMode ? static_cast<u32>(std::min<std::size_t>(system.sdfColliders().size(), kMaxColliders)) : 0u);
+ // A report must hear every hit; a chance belongs to a child.
+ set4(b.p13, report > 0 || !hasChild ? 1.0f : std::clamp(finite(emitter.subEmitterChance, 1.0f), 0.0f, 1.0f), 0.0f,
+ std::max(finite(emitter.collisionThickness), 0.0f), 0.0f);
+ set4(b.p14, points, emitter.collisionMask & 0xffffu, depthW_, depthH_);
+ set4(b.p15, finite(emitter.trailWidth), std::max(finite(emitter.trailMinDistance), 0.0f), 0.0f, 0.0f);
+ set4(b.camera, eye.x, eye.y, eye.z, eye.w);
+ job.subEmitter = emitter.subEmitter;
+ job.inheritVelocity = std::clamp(finite(emitter.subEmitterInheritVelocity), 0.0f, 1.0f);
+ job.eventCapacity = eventCapacity;
+ job.reportEvents = report;
+
jobs_.push_back(job);
return true;
}
+void GpuParticles::declareDepthCopy(rg::RenderGraph& graph, rg::ResourceId scene, u32 sceneW, u32 sceneH, const glm::mat4& clip) {
+ if (!wantsDepth_ || depthCopied_ || scene == rg::kNoResource || !device_.supportsCompute()) return;
+ depthCopied_ = true;
+ rg::TargetDesc token;
+ token.width = 1;
+ token.height = 1;
+ token.format = GfxPixelFormat::RGBA8;
+ token.storage = true;
+ token.linearFilter = false;
+ rg::PassDesc pass;
+ pass.name = "gpu_particle_depth";
+ pass.compute = true;
+ pass.keep = true;
+ pass.dependencies = {scene};
+ pass.write = graph.createTarget(token);
+ const glm::dvec3 origin = renderOrigin();
+ pass.execute = [this, &graph, scene, sceneW, sceneH, clip, origin](const rg::PassContext&) {
+ const TextureHandle depth = graph.depthTextureOf(scene);
+ if (depth == TextureHandle::Invalid) { depthValid_ = false; return; }
+ if (depthCopy_ == ComputeHandle::Invalid) {
+ std::string log;
+ depthCopy_ = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, kDepthCopy, "main"}, &log);
+ if (depthCopy_ == ComputeHandle::Invalid) {
+ ES_LOG_ERROR("GpuParticles: the depth copy did not compile: {}", log);
+ return;
+ }
+ }
+ const u32 w = std::max(std::min(sceneW, kDepthGridMax), 1u);
+ const u32 h = std::max(1u, static_cast<u32>(static_cast<u64>(sceneH) * w / std::max(sceneW, 1u)));
+ if (w != depthW_ || h != depthH_ || depthGrid_ == BufferHandle::Invalid) {
+ if (depthGrid_ != BufferHandle::Invalid) device_.deleteBuffer(depthGrid_);
+ depthGrid_ = device_.createBuffer({GfxBufferUsage::Storage, w * h * 4u, false}, GfxContent::transient(), nullptr);
+ if (depthGrid_ == BufferHandle::Invalid) { depthW_ = depthH_ = 0; depthValid_ = false; return; }
+ depthW_ = w;
+ depthH_ = h;
+ }
+ if (depthParams_ == BufferHandle::Invalid) {
+ depthParams_ = device_.createBuffer({GfxBufferUsage::Uniform, 16, true}, GfxContent::transient(), nullptr);
+ if (depthParams_ == BufferHandle::Invalid) return;
+ }
+ const u32 size[4] = {w, h, 0, 0};
+ device_.updateBuffer(depthParams_, 0, size, sizeof(size));
+ const GfxComputeBinding bindings[3] = {
+ GfxComputeBinding::uniform(0, depthParams_),
+ GfxComputeBinding::depth(1, depth),
+ GfxComputeBinding::storage(2, depthGrid_),
+ };
+ if (device_.dispatchCompute(depthCopy_, bindings, 3, (w + 7) / 8, (h + 7) / 8)) {
+ depthValid_ = true;
+ depthClip_ = clip;
+ depthWorld_ = glm::inverse(clip);
+ depthOrigin_ = glm::vec3(origin);
+ }
+ };
+ graph.addPass(std::move(pass));
+}
+
rg::ResourceId GpuParticles::declare(rg::RenderGraph& graph) {
if (jobs_.empty()) return rg::kNoResource;
// The pass is tied to the scene by what it writes, the way the other compute passes are: a single texel nobody samples.
@@ -612,22 +1106,116 @@ void GpuParticles::run() {
return;
}
}
+ ensureEmpties();
+
+ // A parent runs before what its events feed, however the scene happens to list them.
+ std::vector<Job*> order;
+ order.reserve(jobs_.size());
+ const auto parentOf = [this](const Job& child) -> Job* {
+ for (Job& candidate : jobs_) {
+ if (candidate.subEmitter == child.entity.raw && &candidate != &child) return &candidate;
+ }
+ return nullptr;
+ };
+ std::vector<u8> placed(jobs_.size(), 0);
+ const auto place = [&](auto&& self, Job& job, u32 depth) -> void {
+ const std::size_t index = static_cast<std::size_t>(&job - jobs_.data());
+ if (placed[index]) return;
+ placed[index] = 1;
+ if (depth < kMaxJobs) {
+ if (Job* parent = parentOf(job)) self(self, *parent, depth + 1);
+ }
+ order.push_back(&job);
+ };
+ for (Job& job : jobs_) place(place, job, 0);
+
+ const std::vector<particle::SdfColliderInstance>& colliders = jobs_.front().system->sdfColliders();
+ const u32 colliderBytes = static_cast<u32>(std::min<std::size_t>(colliders.size(), kMaxColliders)) * sizeof(particle::SdfColliderInstance);
+ if (colliderBytes > 0 && (colliders_ == BufferHandle::Invalid || collidersCapacity_ < colliderBytes)) {
+ if (colliders_ != BufferHandle::Invalid) device_.deleteBuffer(colliders_);
+ collidersCapacity_ = kMaxColliders * sizeof(particle::SdfColliderInstance);
+ colliders_ = device_.createBuffer({GfxBufferUsage::Storage, collidersCapacity_, true}, GfxContent::transient(), nullptr);
+ }
+ if (colliderBytes > 0 && colliders_ != BufferHandle::Invalid) device_.updateBuffer(colliders_, 0, colliders.data(), colliderBytes);
+
std::vector<u8> staging(needed, 0);
for (std::size_t i = 0; i < jobs_.size(); ++i) {
- std::memcpy(staging.data() + i * kJobStride, &jobs_[i].block, sizeof(ParamsBlock));
+ Job& job = jobs_[i];
+ if (const Job* parent = parentOf(job)) job.block.p13[1] = parent->inheritVelocity;
+ if (depthValid_) {
+ job.block.p13[3] = 1.0f;
+ set4(job.block.p14, job.block.p14[0], job.block.p14[1], depthW_, depthH_);
+ std::memcpy(job.block.depthClip, &depthClip_[0][0], sizeof(job.block.depthClip));
+ std::memcpy(job.block.depthWorld, &depthWorld_[0][0], sizeof(job.block.depthWorld));
+ set4(job.block.depthOrigin, depthOrigin_.x, depthOrigin_.y, depthOrigin_.z, 0.0f);
+ }
+ std::memcpy(staging.data() + i * kJobStride, &job.block, sizeof(ParamsBlock));
}
device_.updateBuffer(params_, 0, staging.data(), needed);
- for (std::size_t i = 0; i < jobs_.size(); ++i) {
- const Job& job = jobs_[i];
- const GfxComputeBinding bindings[3] = {
- GfxComputeBinding::uniform(0, params_, static_cast<u32>(i) * kJobStride, sizeof(ParamsBlock)),
+
+ bool anyEvents = false;
+ for (const Job& job : jobs_) anyEvents = anyEvents || job.slot->events != BufferHandle::Invalid;
+ if (anyEvents) {
+ if (!ensureEventKernels()) anyEvents = false;
+ const u32 controlBytes = static_cast<u32>(jobs_.size()) * 256u;
+ if (anyEvents && (control_ == BufferHandle::Invalid || controlCapacity_ < controlBytes)) {
+ if (control_ != BufferHandle::Invalid) device_.deleteBuffer(control_);
+ controlCapacity_ = std::max(controlBytes, 256u * 8u);
+ control_ = device_.createBuffer({GfxBufferUsage::Uniform, controlCapacity_, true}, GfxContent::transient(), nullptr);
+ if (control_ == BufferHandle::Invalid) { controlCapacity_ = 0; anyEvents = false; }
+ }
+ if (anyEvents) {
+ std::vector<u8> control(controlBytes, 0);
+ for (std::size_t i = 0; i < jobs_.size(); ++i) {
+ const u32 words[4] = {jobs_[i].eventCapacity, jobs_[i].block.p12[2], jobs_[i].slot->capacity, 0u};
+ std::memcpy(control.data() + i * 256u, words, sizeof(words));
+ }
+ device_.updateBuffer(control_, 0, control.data(), controlBytes);
+ }
+ }
+
+ for (Job* jobPtr : order) {
+ const Job& job = *jobPtr;
+ const u32 i = static_cast<u32>(jobPtr - jobs_.data());
+ const Job* parent = parentOf(job);
+ const BufferHandle ownEvents = job.slot->events != BufferHandle::Invalid ? job.slot->events : emptyEvents_;
+ const bool fed = (job.block.p1[1] & kFed) != 0u;
+ const BufferHandle inEvents = fed && parent && parent->slot->events != BufferHandle::Invalid ? parent->slot->events : emptyRead_;
+ const bool controlled = anyEvents && job.slot->events != BufferHandle::Invalid;
+ if (controlled) {
+ const GfxComputeBinding control[2] = {
+ GfxComputeBinding::uniform(0, control_, i * 256u, 16u),
+ GfxComputeBinding::storage(1, ownEvents),
+ };
+ device_.dispatchCompute(beginEvents_, control, 2, 1);
+ }
+ const GfxComputeBinding bindings[9] = {
+ GfxComputeBinding::uniform(0, params_, i * kJobStride, sizeof(ParamsBlock)),
GfxComputeBinding::storage(1, job.slot->state),
GfxComputeBinding::storage(2, job.slot->instances),
+ GfxComputeBinding::storage(3, ownEvents),
+ GfxComputeBinding::storageRead(4, inEvents),
+ GfxComputeBinding::storageRead(5, depthValid_ && depthGrid_ != BufferHandle::Invalid ? depthGrid_ : emptyRead_),
+ GfxComputeBinding::storageRead(6, colliders_ != BufferHandle::Invalid ? colliders_ : emptyRead_),
+ GfxComputeBinding::storage(7, job.slot->trail != BufferHandle::Invalid ? job.slot->trail : emptyTrail_),
+ GfxComputeBinding::storage(8, job.slot->segments != BufferHandle::Invalid ? job.slot->segments : emptySegments_),
};
- if (device_.dispatchCompute(kernel_, bindings, 3, (job.slot->capacity + 63) / 64)) {
+ if (device_.dispatchCompute(kernel_, bindings, 9, (job.slot->capacity + 63) / 64)) {
++lastDispatches_;
job.system->commitGpuStep(job.entity, job.step);
}
+ if (controlled && fed) {
+ const GfxComputeBinding control[3] = {
+ GfxComputeBinding::uniform(0, control_, i * 256u, 16u),
+ GfxComputeBinding::storage(1, ownEvents),
+ GfxComputeBinding::storageRead(2, inEvents),
+ };
+ device_.dispatchCompute(finishEvents_, control, 3, 1);
+ }
+ if (job.reportEvents > 0 && controlled && job.slot->readback == ReadbackHandle::Invalid) {
+ job.slot->readbackBytes = kEventHeaderBytes + std::min(job.reportEvents, job.eventCapacity) * kEventBytes;
+ job.slot->readback = device_.requestBufferReadback(job.slot->events, 0, job.slot->readbackBytes);
+ }
}
jobs_.clear();
}
diff --git a/src/esengine/renderer/frame/GpuParticles.hpp b/src/esengine/renderer/frame/GpuParticles.hpp
index 177a701f0..11e85a0ed 100644
--- a/src/esengine/renderer/frame/GpuParticles.hpp
+++ b/src/esengine/renderer/frame/GpuParticles.hpp
@@ -13,9 +13,13 @@
* One compute pass per frame, declared into the render graph ahead of the scene pass it feeds. It carries every
* emitter the frame's collect asked to step, each with its own block of parameters.
*
+ * It can collide with what the camera last saw (the depth a frame leaves is copied where next frame's kernel can read
+ * it, with the view it was seen by) and with the distance functions of ParticleCollider. It can tell other kernels:
+ * what an emitter fires is appended to a buffer, and a child emitter's kernel spawns from it with no trip to the CPU.
+ *
* What it is not: the particles are not sorted (an additive or cut-out look is exact, a deep alpha-blended pile
- * draws in slot order), do not spawn sub-emitters or trails, and collide only with the floor plane. Where the device
- * cannot compute, ParticleSystem simulates the same emitter on the CPU, capped.
+ * draws in slot order), and a scene query is not something a kernel can ask. Where the device cannot compute,
+ * ParticleSystem simulates the same emitter on the CPU, capped.
*/
#pragma once
@@ -23,6 +27,7 @@
#include "../graph/RenderGraph.hpp"
#include "../rhi/GfxEnums.hpp"
+#include "../../math/Math.hpp"
#include <unordered_map>
#include <vector>
@@ -52,11 +57,20 @@ public:
* @brief Queues the step an emitter needs and says where its particles are. The step is committed to the emitter only
* once the kernel has run it; an emitter already queued this frame is not queued twice.
* @param drawCount How many slots may hold a live particle once the step has run.
+ * @param eye Where the frame is seen from, as FrameConstants::camera has it: what a trail's quads are turned to face.
* @param instances The buffer to draw them from.
+ * @param segments The buffer to draw its trails from, and how many; untouched where it has none.
* @return false when there is nothing to draw (no compute, no memory).
*/
bool submit(Entity entity, const ecs::ParticleEmitter& emitter, const ecs::Transform& transform,
- particle::ParticleSystem& system, const particle::GpuStep& step, BufferHandle& instances);
+ particle::ParticleSystem& system, const particle::GpuStep& step, const glm::vec4& eye,
+ BufferHandle& instances, BufferHandle& segments, u32& segmentCount);
+
+ /// An emitter collided with the depth last frame, so the scene must draw into a target whose depth can be read.
+ bool wantsDepth() const { return wantsDepth_; }
+
+ /// Copies the scene's depth for next frame's kernel, once a frame. @p clip is the view that drew it, in the device's clip range.
+ void declareDepthCopy(rg::RenderGraph& graph, rg::ResourceId scene, u32 sceneW, u32 sceneH, const glm::mat4& clip);
/// Adds the compute pass for what was submitted. The resource it writes must be named by the pass that draws the result.
rg::ResourceId declare(rg::RenderGraph& graph);
@@ -73,20 +87,53 @@ private:
struct Slot {
BufferHandle state = BufferHandle::Invalid;
BufferHandle instances = BufferHandle::Invalid;
+ BufferHandle events = BufferHandle::Invalid;
+ BufferHandle trail = BufferHandle::Invalid;
+ BufferHandle segments = BufferHandle::Invalid;
u32 capacity = 0;
+ u32 eventBytes = 0;
+ u32 trailPoints = 0;
u64 lastUsed = 0;
+ ReadbackHandle readback = ReadbackHandle::Invalid;
+ u32 readbackBytes = 0;
+ u32 collisionMode = 0;
+ particle::ParticleSystem* system = nullptr;
};
struct Job;
bool ensureKernel();
+ bool ensureEventKernels();
+ void ensureEmpties();
+ void pollReadbacks();
Slot* ensureSlot(Entity entity, u32 capacity);
void freeSlot(Slot& slot);
void run();
GfxDevice& device_;
ComputeHandle kernel_ = ComputeHandle::Invalid;
+ ComputeHandle beginEvents_ = ComputeHandle::Invalid;
+ ComputeHandle finishEvents_ = ComputeHandle::Invalid;
+ ComputeHandle depthCopy_ = ComputeHandle::Invalid;
BufferHandle params_ = BufferHandle::Invalid;
u32 paramsCapacity_ = 0;
+ BufferHandle control_ = BufferHandle::Invalid;
+ u32 controlCapacity_ = 0;
+ BufferHandle emptyRead_ = BufferHandle::Invalid;
+ BufferHandle emptyEvents_ = BufferHandle::Invalid;
+ BufferHandle emptyTrail_ = BufferHandle::Invalid;
+ BufferHandle emptySegments_ = BufferHandle::Invalid;
+ BufferHandle colliders_ = BufferHandle::Invalid;
+ u32 collidersCapacity_ = 0;
+ BufferHandle depthGrid_ = BufferHandle::Invalid;
+ BufferHandle depthParams_ = BufferHandle::Invalid;
+ u32 depthW_ = 0, depthH_ = 0;
+ bool depthValid_ = false;
+ bool depthCopied_ = false;
+ bool wantsDepth_ = false;
+ bool wantsDepthNext_ = false;
+ glm::mat4 depthClip_{1.0f};
+ glm::mat4 depthWorld_{1.0f};
+ glm::vec3 depthOrigin_{0.0f};
bool failed_ = false;
u64 frame_ = 0;
u32 lastDispatches_ = 0;
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index c0936df71..d94b2a8e8 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -397,7 +397,7 @@ public:
|| output_transform_ != OutputTransform::None
|| displayLutActive()
|| view_exposure_ != 0.0f
- || presentScales() || present_required_);
+ || presentScales() || present_required_ || compute_needs_depth_);
}
/**
@@ -421,6 +421,8 @@ public:
* viewport are the same geometry, same size and offset, and differ
* only in intent; the two rects cannot say which is which.
*/
+ /// A compute pass reads the scene's depth, which only a scene drawn into a target of the graph's has.
+ void setComputeNeedsDepth(bool needs) { compute_needs_depth_ = needs; }
void setPresentRequired(bool required) { present_required_ = required; }
/**
@@ -672,6 +674,7 @@ private:
u32 output_vp_x_ = 0;
u32 output_vp_y_ = 0;
bool present_required_ = false;
+ bool compute_needs_depth_ = false;
u32 output_vp_w_ = 0;
u32 output_vp_h_ = 0;
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 0f1299861..ee8c83dca 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -417,7 +417,12 @@ void RenderFrame::beginFrame() {
void RenderFrame::applySceneDepthNeed() {
#ifdef ES_ENABLE_POSTPROCESS
if (!post_process_) return;
- post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_
+ bool computeNeedsDepth = false;
+#ifdef ES_ENABLE_GPU_PARTICLES
+ computeNeedsDepth = gpu_particles_ && gpu_particles_->wantsDepth();
+#endif
+ post_process_->setComputeNeedsDepth(computeNeedsDepth);
+ post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_ || computeNeedsDepth
|| draw_list_.depthMask() != 0);
#endif
}
@@ -809,6 +814,11 @@ void RenderFrame::end() {
if (!glass && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
};
graph_.addPass(std::move(scene));
+#ifdef ES_ENABLE_GPU_PARTICLES
+ if (gpu_particles_) {
+ gpu_particles_->declareDepthCopy(graph_, scene_resource_, width_, height_, toClipDepthRange(view_projection_, device_.clipDepthRange()));
+ }
+#endif
if (glass) {
#ifdef ES_ENABLE_POSTPROCESS
rg::PassDesc copy;
diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cpp
index 3ef678307..9b72f82e1 100644
--- a/src/esengine/renderer/graph/RenderGraph.cpp
+++ b/src/esengine/renderer/graph/RenderGraph.cpp
@@ -235,7 +235,7 @@ void RenderGraph::cull(std::vector<bool>& live) const {
wanted[finalTarget_] = true;
for (i32 i = static_cast<i32>(passes_.size()) - 1; i >= 0; --i) {
const PassDesc& pass = passes_[static_cast<usize>(i)];
- if (pass.write >= resources_.size() || !wanted[pass.write]) continue;
+ if (!pass.keep && (pass.write >= resources_.size() || !wanted[pass.write])) continue;
live[static_cast<usize>(i)] = true;
for (ResourceId read : pass.reads) {
if (read < resources_.size()) wanted[read] = true;
diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hpp
index 2786e17a9..a53252b36 100644
--- a/src/esengine/renderer/graph/RenderGraph.hpp
+++ b/src/esengine/renderer/graph/RenderGraph.hpp
@@ -110,6 +110,8 @@ struct PassDesc {
* writing `ctx.output`, which has to be a target declared with `storage`. Ordered, culled and recycled like any pass.
*/
bool compute = false;
+ /// Wanted by a later frame rather than by this picture: not culled for nothing having read it yet.
+ bool keep = false;
/// Its target's depth is only for testing while it draws, and nothing reads it afterwards (see RenderPassDesc::discardDepth).
bool discardDepth = false;
bool clear = false;
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cpp
index 352d0c13f..172c923c2 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp
@@ -99,6 +99,8 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
// A GPU emitter's particles are in a buffer a kernel writes: this frame's step is queued, and the draw is told
// where to read them. The CPU has nothing per particle to do.
BufferHandle gpuInstances = BufferHandle::Invalid;
+ BufferHandle gpuSegments = BufferHandle::Invalid;
+ u32 gpuSegmentCount = 0;
u32 particleCount = 0;
if (state->gpu) {
#ifdef ES_ENABLE_GPU_PARTICLES
@@ -108,7 +110,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
buffers.reserveStream(LayoutId::ParticleInstance);
particle::GpuStep step;
if (!particle_system_->peekGpuStep(entity, step)) continue;
- if (!gpu->submit(entity, emitter, transform, *particle_system_, step, gpuInstances)) continue;
+ if (!gpu->submit(entity, emitter, transform, *particle_system_, step, collect_ctx.camera.eye, gpuInstances, gpuSegments, gpuSegmentCount)) continue;
particleCount = step.drawCount;
#else
continue; // no compute in this build: ParticleSystem never marks an emitter GPU-simulated
@@ -250,6 +252,15 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
// with the instance slice based at instByteOffset.
pushBatchDraw(draw_list, clips, instByteOffset, 0, 0, 6, key);
+ // A kernel writes a GPU emitter's trails as quads the particle draw already knows how to draw.
+ if (gpuSegments != BufferHandle::Invalid && gpuSegmentCount > 0) {
+ BatchDrawKey segmentKey = key;
+ segmentKey.textureId = ctx.white_texture_id;
+ segmentKey.instanceCount = gpuSegmentCount;
+ segmentKey.instanceBuffer = gpuSegments;
+ pushBatchDraw(draw_list, clips, 0, 0, 0, 6, segmentKey);
+ }
+
// --- Per-particle trails --------------------------------------------------
// Each live particle drags a tapering ribbon along its recorded path. Built on
// the CPU and streamed through the Batch face (triangle strip), exactly like the
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index f6178a7c1..daef73efe 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0xa0aa3df7a75dbd67ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0x979ff0f0e2eab4b6ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index 90733d1d9..4247c1b6e 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xa0aa3df7a75dbd67ULL
+#define ES_ABI_ENGINE_DIGEST 0x979ff0f0e2eab4b6ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 330ff3f43..cf1947a7b 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -124,6 +124,7 @@ const DISPOSITION = {
NetGhost: ['derived', 'replication tags a remote proxy with it; the authority writes it, never the scene'],
Planet: ['owed', 'authored by a game today (star-neighbors, a round planet from its own generator); an example that registers a planet provider is owed'],
MeshInstances: ['derived', 'the foliage and world generation systems write it, one entity a kind and part of a cell; its places are data a system computes, not something a scene authors'],
+ ParticleCollider: ['owed', 'no example has a GPU emitter bouncing off a shape yet; the particle-gpu scenes are where the first one goes'],
PlantProxy: ['derived', 'the plant interaction makes it for a plant near a contact, and takes it away again; a scene never holds one'],
FoliageContact: ['owed', 'no example has a character walking through plants yet; wilds gains one when it gets a player'],
PlacedFoliage: ['derived', 'a generated world grows its plants through the same machinery without the component, and a project that places plants by hand writes the kinds and records with a script from its own rules; the lists are generated data, not something a scene is authored by hand with'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index de6208a18..59525d85e 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -98,6 +98,9 @@ const DISPOSITION = {
'NavLink.radius': 'extent',
'NavVolume.halfExtents': 'extent',
'ParticleForceField.radius': 'extent',
+ 'ParticleCollider.radius': 'extent',
+ 'ParticleCollider.halfExtents': 'extent',
+ 'ParticleCollider.halfHeight': 'extent',
'ParticleEmitter.shapeRadius': 'extent',
'ParticleEmitter.shapeSize': 'extent',
'PostProcessVolume.size': 'extent',
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 9de11fb61..f8fa5781e 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4224,6 +4224,8 @@ export const NOTED = {
{"note": "A side-on character comes ready to run and jump."},
"feat(foliage): plants part for what touches them, come near as entities with colliders, and can be felled and harvested":
{"note": "Plants can be touched, felled and harvested."},
+ "feat(particles): GPU particles collide with scene depth and distance functions, fire sub-emitters from an event buffer, and drag trails":
+ {"note": "GPU particles can hit things, tell each other, and drag trails."},
"fix(assets): one hot load at a time per asset, so two rescans cannot lose a texture":
{"note": "A texture stays on a scene that rescans as it is placed."},
"feat(rig): the 2D rig editor, from an image to a character in the scene":