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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(foliage): plants part for what touches them, come near as entities with colliders, and can be felled and harvested
yhh538d21471872
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8dcf95a35..fcdb0cbb4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **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.- **2D bones can reach for things and follow each other.** `IK2D` on the last bone of a limb bends it to a target after the animation has played, exactly for two bones and iteratively for more, with a weight clips can key. `BoneConstraint2D` limits a joint's rotation, which a chain through it keeps to, or copies another entity's rotation or position, or looks at it. Both follow a character mirrored by a negative scale. `esengine/rig2d` also makes all of this from code.diff --git a/desktop b/desktopindex d42be8143..0603d1b68 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit d42be8143ad2e44d5eb2dd72cea70c5f5de10a0e+Subproject commit 0603d1b68d8e6355dc556e6e693ce1f3f3b37111diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdxindex 46c4bb604..0295ea0ff 100644--- a/docs/astro/src/content/docs/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/graphics/foliage.mdx@@ -89,6 +89,60 @@ Ground cover far off then costs a share of what it does near, and the ground's oPlants stand upright and are scaled uniformly; the records carry no tilt. The paths in `kinds` are the project's, listed so a package carries them.+## Touching plants++A forest cannot be entities and does not need to be: only what stands near something can be touched. Put a **`FoliageContact`** on the character (or anything else plants+should feel). It does two things, one for each way plants are drawn.++| Field | What it does |+|---|---|+| `radius` | How far from the entity plants lean away, in world units. |+| `strength` | How hard: 1 is a full lean. |+| `recovery` | Seconds grass takes to stand up again behind it. |++**Grass parts.** A `Foliage` cell is one mesh, so its bend is worked out in the vertices: the **Foliage** shader takes four places (`u_contact0` to `u_contact3`) and moves each blade+away from them by how far up the blade it is, less the further it stands above or below. The four are the contacts nearest the streaming source, then the places they recently left, which close over `recovery`,+so a character leaves a parting that closes behind it. `u_contactBend` is how far a blade parts as a share of the contact's reach. A contact past the four does not part anything, which a player sees+as grass unmoved round a creature far off. Nothing needs to be turned on but the component.++**Placed plants come near.** A kind in `PlacedFoliage` or `WorldRules.plants` opts in with `interaction`. It stays a placement in its `MeshInstances` set, and within `activationDistance` of a contact each plant is also given an entity,+a **`PlantProxy`**, which goes when the contact does. The picture never changes hands, so nothing pops. The entity is what a ray or a collision finds, and a game's own components can go on it.++| `interaction` field | What it does |+|---|---|+| `activationDistance` | How near a contact a plant becomes an entity, in world units. 0 keeps it data. |+| `radius`, `height` | The capsule that stands for it to physics, standing on its foot, in the mesh's units (multiplied by its scale). Either 0 has none. |+| `bend` | How far it leans from a contact, in radians. It is a shear of the placement, with a spring, so any material bends with it and it rustles when let go. |+| `health` | What `damage` must take to fell it. 0 cannot be felled that way. |+| `fallSeconds`, `fallAngle`, `lieSeconds` | How long it takes to come down (default 1.8), how far (default 85 degrees), and how long it lies before it sinks away (default 30). |+| `felledKind`, `harvestedKind` | The kind it leaves when felled, a stump, or becomes with nothing left to take, a bare bush: an index into `kinds`, or a plant's name in `WorldRules.plants`. Absent leaves nothing. |+| `yields` | How many times `harvest` can take from it. |+| `regrowSeconds` | Seconds after felling or the last harvest before it stands again, growing back from small. 0 is never. |++The plants are reached through a resource, from `esengine/foliage`:++```ts+import { FoliageContact, PlantInteractionRes } from 'esengine/foliage';++const plants = app.getResource(PlantInteractionRes);++// Whatever an axe swung here reaches, nearest first.+const [tree] = plants.near(player.x, player.z, 2);+if (tree) plants.damage(tree, 25, { x: player.x, z: player.z }); // comes down away from the blow at no health left++// What a ray found.+const hit = physics.raycast(eye, forward);+const plant = hit && plants.of(hit.entity);+if (plant) inventory.berries += plants.harvest(plant, 1);++plants.on((event) => { if (event.type === 'landed') spawnDust(event.plant); });+```++A felled plant comes down as an entity with its own meshes, a kinematic body turning about its foot, so it stops what it lies across while it lies there, and its placement is gone at once, from the far version too.++**What became of a plant lasts.** It is kept against the plant's key, not its cell, so a felled tree is felled when its chunk is let go and grown again. `plants.saveState()` is all of it as plain data, the clock of what is regrowing included, and `plants.loadState(state)` puts it back, before or after the cells are grown.+A world's plants are known by their places in its plan. A `PlacedFoliage`'s are known by their index in `records` under its `stateKey` (or its entity's name), so a save outlives everything but reordering the records; give two fields different names.+## In a packageFoliage is an optional module, like terrain: a package carries it when a scene has a `Foliage` or `PlacedFoliage` component or a script imports `esengine/foliage`. It stands on a `Terrain` when the scene has one and needs no terrain module to stand on a flat floor.@@ -96,7 +150,10 @@ Foliage is an optional module, like terrain: a package carries it when a scene h## Limits- **Position only.** The area is taken to be unrotated and unscaled; the terrain's position and uniform scale are followed, a rotation is not.-- **No collision and no interaction.** Plants do not bend away from a character; the wind is the only thing that moves them.+- **Only placed plants can be felled.** Scattered `Foliage` parts for a contact, but is one mesh a cell, so it has no plants to collide with, fell or harvest: a forest that must be cut is a `PlacedFoliage` or `WorldRules.plants`.+- **A plant falls by a rule, not by the solver.** It turns about its foot to `fallAngle` and does not settle on a slope or roll, so on steep ground a trunk can stand off the ground or into it. Its body is kinematic: it pushes what it lands on and nothing pushes it.+- **Collision takes the 3D physics module.** A proxy's capsule is added when the module is loaded, which a scene with a `CharacterController3D` or a body does by itself; without one, plants still lean and can be felled, and nothing collides. A capsule is the one shape: a wide crown or a fork is not followed.+- **A fallen plant is not in a save.** A tree still coming down is saved as felled, and is gone on loading.- **The far version of a mesh is a card, not an impostor.** It shows the rectangle of the plant's texture you name, from every side the same; atree whose texture has no such picture shows its texture there.- **Cells are grown within the frame's budget**, nearest first, so the distance fills in over a moment.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdxindex e8b382752..fc25fa029 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx@@ -67,6 +67,54 @@ MCP 的 `audit_vegetation` 会给出配置上限和当前绘制统计。先用 `植物是直立、等比缩放的,记录里没有倾斜。`kinds` 里的路径是项目路径,列出来是为了让包带上它们。+## 触碰植物++森林不可能全是实体,也不需要:能被碰到的只有附近的东西。给角色(或其他植物应该感知的东西)加一个 **`FoliageContact`**。它做两件事,分别对应植物的两种绘制方式。++| 字段 | 作用 |+|---|---|+| `radius` | 植物从实体倒开的距离,世界单位。 |+| `strength` | 力度:1 表示完全倒开。 |+| `recovery` | 它走后草重新立起来的秒数。 |++**草会分开。** `Foliage` 的一个格子是一个网格,所以弯曲在顶点里算:**Foliage** 着色器接收四个位置(`u_contact0` 到 `u_contact3`),按草叶高度把每片叶子推开,高出或低于接触点越多推得越少。这四个是离流式来源最近的接触点,然后是它们刚离开的位置,这些位置会在 `recovery` 内收拢,所以角色身后留下的是一条慢慢合上的分痕。`u_contactBend` 是叶子分开的距离占接触范围的比例。超过四个时,多余的接触点不会分开任何草,玩家看到的是远处生物周围的草不动。除了加这个组件,不需要打开别的东西。++**放置的植物靠近才激活。** `PlacedFoliage` 或 `WorldRules.plants` 里的种类用 `interaction` 开启。它仍然是 `MeshInstances` 里的一个实例,但接触点在 `activationDistance` 内时,每棵植物还会多一个实体 **`PlantProxy`**,接触点离开后实体消失。画面全程不换手,所以不会跳变。这个实体就是射线或碰撞找到的东西,游戏自己的组件也可以挂上去。++| `interaction` 字段 | 作用 |+|---|---|+| `activationDistance` | 接触点多近时植物变成实体,世界单位。0 表示始终是数据。 |+| `radius`、`height` | 代表它的胶囊体,立在根部,单位是网格单位(乘以缩放)。任一为 0 则没有。 |+| `bend` | 从接触点倒开的最大角度,弧度。这是对实例矩阵的错切,带弹簧,所以任何材质都能弯,放开时会晃一下。 |+| `health` | `damage` 要打掉多少才砍倒。0 表示不能这样砍倒。 |+| `fallSeconds`、`fallAngle`、`lieSeconds` | 倒下用时(默认 1.8)、倒下角度(默认 85 度)、躺多久后沉入地下(默认 30)。 |+| `felledKind`、`harvestedKind` | 砍倒后留下的种类(树桩)、采完后变成的种类(光秃的灌木):`kinds` 的下标,或 `WorldRules.plants` 里的名字。不写则什么都不留。 |+| `yields` | `harvest` 能取多少次。 |+| `regrowSeconds` | 砍倒或采完后多少秒重新长出,从小长大。0 表示不再长。 |++通过 `esengine/foliage` 的资源访问:++```ts+import { FoliageContact, PlantInteractionRes } from 'esengine/foliage';++const plants = app.getResource(PlantInteractionRes);++// 这一斧够得着的植物,由近到远。+const [tree] = plants.near(player.x, player.z, 2);+if (tree) plants.damage(tree, 25, { x: player.x, z: player.z }); // 血量归零时朝远离这一击的方向倒下++// 射线打到的植物。+const hit = physics.raycast(eye, forward);+const plant = hit && plants.of(hit.entity);+if (plant) inventory.berries += plants.harvest(plant, 1);++plants.on((event) => { if (event.type === 'landed') spawnDust(event.plant); });+```++砍倒的植物以带自身网格的实体倒下,是绕根部转动的运动学刚体,躺着时会挡住路过的东西;它的实例立刻消失,远景版本也一样。++**植物的结局会保留。** 状态按植物的 key 记录,不按格子,所以砍倒的树在区块卸载再生成后依然是倒的。`plants.saveState()` 把这些都导出成普通数据,包括再生用的时钟;`plants.loadState(state)` 还原,在格子生成前后调用都可以。世界的植物用规划里的位置标识。`PlacedFoliage` 的植物用 `records` 里的下标加 `stateKey`(或实体名)标识,所以除了重排 records,存档都有效;两片植被要起不同的名字。+## 在包里植被和地形一样是可选模块:场景里有 `Foliage` 或 `PlacedFoliage` 组件,或脚本导入了 `esengine/foliage`,包里才会带上它。场景里有 `Terrain` 时植被立在地形上;平地上不需要地形模块。@@ -74,6 +122,9 @@ MCP 的 `audit_vegetation` 会给出配置上限和当前绘制统计。先用 `## 限制- **只有位置。** 区域被当作不旋转、不缩放;地形的位置和均匀缩放会被跟随,旋转不会。-- **没有碰撞,也没有交互。** 植物不会被角色压弯;风是唯一能让它们动的东西。+- **只有放置的植物能砍。** 散布的 `Foliage` 会为接触点分开,但一个格子是一个网格,没有单棵植物可以碰撞、砍伐或采集;要砍的森林请用 `PlacedFoliage` 或 `WorldRules.plants`。+- **倒下靠规则,不靠求解器。** 它绕根部转到 `fallAngle`,不会贴合斜坡或滚动,所以陡坡上树干可能悬空或插进地里。刚体是运动学的:它推开落点的东西,但没有东西能推它。+- **碰撞需要 3D 物理模块。** 代理的胶囊体在模块加载后才有,场景里有 `CharacterController3D` 或刚体时会自动加载;没有的话植物仍能弯曲和砍倒,只是没有碰撞。形状只有胶囊体,宽树冠或分叉不会贴合。+- **倒下中的植物不进存档。** 正在倒的树存为已砍倒,读档后直接消失。- **网格的远景版本是卡片,不是 impostor。** 它显示你指定的那个纹理矩形,从各个方向看都一样;纹理里没有这样一张图的树,卡片上就是它的纹理。- **格子在每帧预算内生长**,由近及远,所以远处会在一小会儿内填满。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 491718501..f140e0ec0 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 176,- "experimental": 2921,+ "experimental": 2933,"deprecated": 3},- "total": 3212,+ "total": 3224,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex ef1bc629d..43708ce40 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -192,6 +192,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {FixedJoint3D: { category: 'physics', summary: 'Locks two 3D bodies together in the pose they were placed in — no freedom at all.', doc: 'gameplay/physics-3d', anchor: 'joints', anchorZh: '关节' },CharacterController2D: { category: 'physics', summary: 'Kinematic character movement that slides along walls, climbs slopes and reports ground contact.', doc: 'gameplay/physics', anchor: 'character-controller', anchorZh: '角色控制器' },PlatformerController2D: { category: 'physics', summary: 'Runs and jumps a CharacterController2D from the keyboard or a game, with coyote time, a jump buffer and dropping through one-way platforms.', doc: 'gameplay/physics', anchor: 'platformer-controller' },+ FoliageContact: { category: 'physics', summary: 'Something plants feel: grass parts around it, shrubs lean away, and placed plants near it become entities with colliders.', doc: 'graphics/foliage', anchor: 'touching-plants' },+ PlantProxy: { category: 'physics', summary: 'The entity standing in for a placed plant while something is near it, which a ray or a collision finds.', doc: 'graphics/foliage', anchor: 'touching-plants' },OneWayPlatform2D: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },DistanceJoint2D: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },HingeJoint2D: { category: 'physics', summary: 'Pins two bodies at a point and lets them rotate — a hinge, with optional limits and a motor.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 9ada30ca8..5c5a021da 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -2549,6 +2549,43 @@"cardTent"]},+ {+ "name": "FoliageContact",+ "source": "ts",+ "fields": [+ {+ "key": "radius",+ "type": "number",+ "default": "40",+ "doc": "How far from this entity plants lean away.",+ "range": "≥ 0.01"+ },+ {+ "key": "strength",+ "type": "number",+ "default": "1",+ "doc": "How hard they lean: 1 is a full lean, 0 none.",+ "range": "0–2, step 0.01"+ },+ {+ "key": "recovery",+ "type": "number",+ "default": "0.6",+ "doc": "How long grass takes to stand up again behind it.",+ "range": "≥ 0, step 0.05"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "radius",+ "strength",+ "recovery"+ ]+ },{"name": "FollowTarget","source": "ts",@@ -4854,6 +4891,12 @@"type": "array","default": "empty","doc": "Where each plant stands: kind index, x, y, z, turn about the vertical in radians and scale, six numbers a plant, in this entity's space."+ },+ {+ "key": "stateKey",+ "type": "string",+ "default": "empty",+ "doc": "The name a save keeps what became of these plants under. Empty takes the entity's name."}],"animatable": [@@ -5145,6 +5188,22 @@"seaOpacity"]},+ {+ "name": "PlantProxy",+ "source": "ts",+ "fields": [+ {+ "key": "source",+ "type": "string",+ "default": "empty"+ },+ {+ "key": "key",+ "type": "string",+ "default": "empty"+ }+ ]+ },{"name": "PlatformerController2D","source": "ts",diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex 2eaeaa678..d24256b7f 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -45,7 +45,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>fxBasic: [],fxAtmosphere: ['Weather', 'TimeOfDay'],fxLighting: [],- foliage: ['Foliage', 'PlacedFoliage'],+ foliage: ['Foliage', 'PlacedFoliage', 'FoliageContact', 'PlantProxy'],worldgen: ['WorldGen', 'WorldZone'],water: ['WaterBody', 'WaterZone', 'Floating'],spline: ['Spline', 'PathFollower', 'TerrainBand2D'],diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.mdindex f6e14883c..9ba462d99 100644--- a/sdk/etc/foliage.api.md+++ b/sdk/etc/foliage.api.md@@ -1,7 +1,7 @@# API surface — esengine/foliage<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 32 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 44 experimental · 0 deprecated## BladeParams — interface @experimental```@@ -25,6 +25,19 @@ v1: numberComponentDef<FoliageData>```+## FoliageContact — const @experimental+```+ComponentDef<FoliageContactData>+```++## FoliageContactData — interface @experimental+```+enabled: boolean+radius: number+recovery: number+strength: number+```+## FoliageData — interface @experimental```bladeHeight: number@@ -103,6 +116,7 @@ kinds: PlacedKind[]records: number[]sizeX: numbersizeZ: number+stateKey: string```## PlacedFoliageField — class @experimental@@ -135,6 +149,7 @@ drawDistance: numberfar: PlacedPart[]farDistance: numberfarKeep: number | undefined+interaction: PlantInteractionDef | undefinedlod2Distance: number | undefinedlodDistance: numberparts: PlacedPart[]@@ -155,9 +170,11 @@ tint: [number, number, number, number]## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: number@@ -165,8 +182,17 @@ yaw: numberz: number```+## PlantEvent — interface @experimental+```+plant: PlantRef+type: "removed" | "activated" | "deactivated" | "damaged" | "felled" | "landed" | "harvested" | "regrown"+```+## PlantGrowth — class @experimental```+@internal observer_: PlacementObserver | null+@internal placeTurned: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, kindIndex: number) => void+@internal writeSet: (app: App, cell: GrownCell, set: PlacementSet) => voidapp_: App | nullgrowCell: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>) => voidgrowFar: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number; }, thinnedBy?: number) => void@@ -185,12 +211,60 @@ static prototype: PlantGrowthResourceDef<PlantGrowth>```+## PlantInteraction — class @experimental+```+@internal addCell: (grown: GrownCell, source: string, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, half: number) => void+@internal addFarCell: (grown: GrownCell, source: string, kinds: readonly PlacedKind[], ready: ReadyKinds) => void+@internal app_: App | null+@internal placementsOf: (grown: GrownCell, set: PlacementSet) => readonly Plant[]+@internal removeCell: (grown: GrownCell) => void+@internal step: (dt: number) => void+activeCount: number+changedCount: number+damage: (plant: PlantRef, amount: number, from?: { x: number; z: number; }) => boolean+fell: (plant: PlantRef, toward?: { x: number; z: number; }) => boolean+find: (source: string, key: string) => PlantRef | null+harvest: (plant: PlantRef, amount?: number) => number+loadState: (state: PlantSaveState) => void+maxActivatedPerFrame: number+maxActive: number+near: (x: number, z: number, radius: number) => PlantRef[]+of: (entity: Entity) => PlantRef | null+on: (listener: (event: PlantEvent) => void) => () => void+remove: (plant: PlantRef) => boolean+saveState: () => PlantSaveState+static new (): PlantInteraction+static prototype: PlantInteraction+```++## PlantInteractionDef — interface @experimental+```+activationDistance: number | undefined+bend: number | undefined+fallAngle: number | undefined+fallSeconds: number | undefined+felledKind: string | number | undefined+harvestedKind: string | number | undefined+health: number | undefined+height: number | undefined+lieSeconds: number | undefined+radius: number | undefined+regrowSeconds: number | undefined+yields: number | undefined+```++## PlantInteractionRes — const @experimental+```+ResourceDef<PlantInteraction>+```+## PlantKind — interface @experimental```drawDistance: numberfar: PlacedPart[]farDistance: numberfarKeep: number | undefined+interaction: PlantInteractionDef | undefinedlod2Distance: number | undefinedlodDistance: numberparts: PlacedPart[]@@ -200,6 +274,44 @@ tints: [number, number, number][] | undefinedunit: number | undefined```+## PlantProxy — const @experimental+```+ComponentDef<PlantProxyData>+```++## PlantProxyData — interface @experimental+```+key: string+source: string+```++## PlantRef — interface @experimental+```+entity: number | null+health: number+key: string+kind: number+scale: number+source: string+state: PlantState+x: number+y: number+yields: number+z: number+```++## PlantSaveState — interface @experimental+```+clock: number+plants: { source: string; key: string; state: PlantState; shownAs: number; health: number; yields: number; regrowAt: number; }[]+version: 1+```++## PlantState — type @experimental+```+'standing' | 'felled' | 'harvested' | 'removed'+```+## ScatterParams — interface @experimental```cellKey: number@@ -250,6 +362,11 @@ Plugin(app: App): PlantGrowth```+## plantInteractionOf — function @experimental+```+(app: App): PlantInteraction+```+## rng — function @experimental```(seed: number): () => numberdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6b09f3eba..812aca794 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -7429,9 +7429,11 @@ static prototype: Planets## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d1f88472d..811feec3f 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -7635,9 +7635,11 @@ static prototype: Planets## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cffc0d7d9..7150b9fcd 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -7424,9 +7424,11 @@ static prototype: Planets## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 98569e3b4..9fc6e9490 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7720,9 +7720,11 @@ static prototype: Planets## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c003963c2..79f9c47b5 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -7431,9 +7431,11 @@ static prototype: Planets## Plant — interface @experimental```+key: string | undefinedphase: numberscale: numbershade: number+shear: readonly [number, number] | undefinedup: readonly [number, number, number] | undefinedx: numbery: numberdiff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.tsindex ce4cf4867..d8ffe3b56 100644--- a/sdk/src/foliage/builder.ts+++ b/sdk/src/foliage/builder.ts@@ -30,6 +30,10 @@ export interface Plant {shade: number;/** The ground's normal it leans with (a stone on a slope), after its turn; upright when absent. */up?: readonly [number, number, number];+ /** Who it is, within what grew it: what became of it is kept against this. Only a kind that can be touched has one. */+ key?: string;+ /** How far it leans, sideways per unit of height along x and z: a shear, so any material bends with it. */+ shear?: readonly [number, number];}/** What a place is, as the ground answers: how high it is and how much it faces up. */@@ -322,6 +326,10 @@ export function buildPlacements(plants: readonly Plant[]): Float32Array {if (lean) lean(column);for (let row = 0; row < 3; row++) out[at + row * 4 + c] = column[row]! * scale;}+ if (plant.shear) {+ out[at + 1] = out[at + 1]! + plant.shear[0] * scale;+ out[at + 9] = out[at + 9]! + plant.shear[1] * scale;+ }out[at + 3] = plant.x;out[at + 7] = plant.y;out[at + 11] = plant.z;diff --git a/sdk/src/foliage/foliageContacts.ts b/sdk/src/foliage/foliageContacts.tsnew file mode 100644index 000000000..3e9853351--- /dev/null+++ b/sdk/src/foliage/foliageContacts.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file foliageContacts.ts+ * @brief Grass that parts for a `FoliageContact` and stands up again behind it: four places a Foliage material is told about each frame.+ *+ * @details A field of grass is one mesh a cell, so the bend can only be worked out where the vertices are. The shader takes four contacts, and this+ * fills them: each contact nearest what is looked from, and where one has left, a place that shrinks away over its `recovery`, so a character+ * leaves a parting that closes behind it rather than grass snapping up at its heels. It runs in play only; in the editor a material asset is+ * left as authored, so looking at a scene never saves one.+ */+import type { App } from '../app/app';+import { defineSystem, Schedule } from '../ecs/system';+import { Res, Time, type TimeData } from '../ecs/resource';+import { Query } from '../ecs/query';+import { Transform, type TransformData } from '../ecs/component';+import { isEditor, isPlayMode } from '../ecs/env';+import { Material } from '../render/material';+import { chunksOf } from '../residency/chunks';+import type { Entity } from '../types';+import { FoliageContact, type FoliageContactData } from './plantInteraction';++/** The most places the Foliage shader parts plants around at once. */+export const FOLIAGE_CONTACTS = 4;+const UNIFORMS = Array.from({ length: FOLIAGE_CONTACTS }, (_, i) => `u_contact${i}`);++/** A place plants are parted around: where, and how far it reaches now. */+export interface ContactPlace { x: number; y: number; z: number; w: number }++/** A place a contact left, closing. */+interface ContactTrail { x: number; y: number; z: number; reach: number; recovery: number; age: number }++/** What is kept of the contacts between frames: the places they left, and where each was when it last left one. */+export interface ContactMemory {+ trails: Map<number, ContactTrail[]>;+ last: Map<number, { x: number; y: number; z: number }>;+}++export const contactMemory = (): ContactMemory => ({ trails: new Map(), last: new Map() });++/** How far behind itself a contact leaves its last place, as a share of its reach. */+const TRAIL_STEP = 0.75;++/**+ * Follows the contacts for one frame: each one that has moved on leaves a place behind it, and what was left shrinks.+ * The answer is the contacts themselves first, nearest `focus`, then what they left, newest first, as many as the shader has room for. Unused places reach nowhere.+ */+export function contactPlaces(+ contacts: readonly { id: number; x: number; y: number; z: number; radius: number; strength: number; recovery: number }[],+ memory: ContactMemory, focus: { x: number; z: number } | null, dt: number,+): ContactPlace[] {+ const { trails, last: lastAt } = memory;+ const live: { place: ContactPlace; d: number }[] = [];+ for (const c of contacts) {+ const reach = c.radius * c.strength;+ if (reach <= 0) continue;+ const was = lastAt.get(c.id);+ if (!was) lastAt.set(c.id, { x: c.x, y: c.y, z: c.z });+ else if (Math.hypot(c.x - was.x, c.z - was.z) > reach * TRAIL_STEP) {+ let list = trails.get(c.id);+ if (!list) trails.set(c.id, list = []);+ list.push({ x: was.x, y: was.y, z: was.z, reach, recovery: c.recovery, age: 0 });+ was.x = c.x; was.y = c.y; was.z = c.z;+ }+ live.push({ place: { x: c.x, y: c.y, z: c.z, w: reach }, d: focus ? Math.hypot(c.x - focus.x, c.z - focus.z) : 0 });+ }+ const left: { place: ContactPlace; age: number }[] = [];+ for (const [id, list] of trails) {+ for (let i = list.length - 1; i >= 0; i--) {+ const t = list[i]!;+ t.age += dt;+ const remaining = t.recovery > 0 ? 1 - t.age / t.recovery : 0;+ if (remaining <= 0) { list.splice(i, 1); continue; }+ left.push({ place: { x: t.x, y: t.y, z: t.z, w: t.reach * remaining }, age: t.age });+ }+ if (list.length === 0) trails.delete(id);+ }+ live.sort((a, b) => a.d - b.d);+ left.sort((a, b) => a.age - b.age);+ const out: ContactPlace[] = [...live.map((l) => l.place), ...left.map((l) => l.place)].slice(0, FOLIAGE_CONTACTS);+ while (out.length < FOLIAGE_CONTACTS) out.push({ x: 0, y: 0, z: 0, w: 0 });+ return out;+}++/** Installs the system that tells Foliage materials about the contacts. Returns what clears them. */+export function installFoliageContacts(app: App): () => void {+ const memory = contactMemory();+ let written = false;+ const clear = (): void => {+ if (!written) return;+ written = false;+ memory.trails.clear();+ memory.last.clear();+ for (const material of Material.materialsDeclaring(UNIFORMS[0]!)) {+ for (const name of UNIFORMS) Material.setUniform(material, name, { x: 0, y: 0, z: 0, w: 0 });+ }+ };+ const system = defineSystem(+ [Query(FoliageContact, Transform), Res(Time)],+ (query: Iterable<[Entity, FoliageContactData, TransformData]>, time: TimeData) => {+ if (isEditor() && !isPlayMode()) { clear(); return; }+ const contacts = [];+ for (const [entity, contact, transform] of query) {+ if (!contact.enabled) continue;+ const p = transform.worldPosition;+ contacts.push({ id: entity as number, x: p.x, y: p.y, z: p.z, radius: contact.radius, strength: contact.strength, recovery: contact.recovery });+ }+ const source = chunksOf(app).sources_()[0];+ const places = contactPlaces(contacts, memory, source ? { x: source.x, z: source.z } : null, time.delta);+ written = true;+ for (const material of Material.materialsDeclaring(UNIFORMS[0]!)) {+ for (let i = 0; i < FOLIAGE_CONTACTS; i++) Material.setUniform(material, UNIFORMS[i]!, places[i]!);+ }+ },+ { name: 'FoliageContactSystem' },+ );+ // The frame after the last one goes still runs, to clear what it wrote.+ app.addSystemToSchedule(Schedule.PostUpdate, system, { activeWhen: [FoliageContact] });+ return clear;+}diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.tsindex 62dd26526..6004c9a04 100644--- a/sdk/src/foliage/foliagePlugin.ts+++ b/sdk/src/foliage/foliagePlugin.ts@@ -28,6 +28,7 @@ import { Material } from '../render/material';import { currentWeather, currentWeatherDrive, WeatherDrive } from '../postprocess/weather';import { isEditor, isPlayMode } from '../ecs/env';import type { Zones } from '../worldgen/zones';+import { installFoliageContacts } from './foliageContacts';import {buildBillboardMesh, buildGrassMesh, buildInstancedMesh, scatterCell,type Ground, type Plant,@@ -188,11 +189,13 @@ export class FoliagePlugin implements Plugin {name = 'foliage';/** No foliage, no work; the frame after the last one goes still runs its sweep. */readonly activeWhen = [Foliage];+ private clearContacts_: (() => void) | null = null;build(app: App): void {const field = new FoliageField();field.app_ = app;app.insertResource(FoliageRes, field);+ this.clearContacts_ = installFoliageContacts(app);app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {if (!app.hasResource(Assets)) return;@@ -254,6 +257,8 @@ export class FoliagePlugin implements Plugin {}cleanup(app?: App): void {+ this.clearContacts_?.();+ this.clearContacts_ = null;if (!app?.hasResource(FoliageRes)) return;const field = app.getResource(FoliageRes);for (const entity of field.built_.keys()) {diff --git a/sdk/src/foliage/foliageShader.ts b/sdk/src/foliage/foliageShader.tsindex bbbf7a7a2..e7f77f785 100644--- a/sdk/src/foliage/foliageShader.ts+++ b/sdk/src/foliage/foliageShader.ts@@ -34,13 +34,37 @@ const FOLIAGE = `#pragma shader "Foliage"// Grass thins out toward the distance its cells switch to their far version (the Foliage component writes it; 0 thins nothing): each blade// by its own random key, down to the third the far version keeps, so a near cell beside a far one is not three times as dense.#pragma param u_thinDistance float default(0) range(0,1000000) ui(slider)+// How far plants part from what touches them, as a share of its reach. The four contacts are written each frame (a FoliageContact): where each is, and how far it reaches now.+#pragma param u_contactBend float default(0.7) range(0,2) ui(slider)+#pragma param u_contact0 vec4 default(0,0,0,0)+#pragma param u_contact1 vec4 default(0,0,0,0)+#pragma param u_contact2 vec4 default(0,0,0,0)+#pragma param u_contact3 vec4 default(0,0,0,0)#pragma vertexbounds 30#pragma vertexoffset+// How far one contact parts a vertex: away from it on the ground, most near it and nothing at its reach or far above or below it.+vec2 foliageContactPush(vec4 contact, vec3 at) {+ if (contact.w <= 0.0) return vec2(0.0);+ vec2 away = at.xz - contact.xz;+ float len = length(away);+ float near = clamp(1.0 - len / contact.w, 0.0, 1.0);+ float level = 1.0 - smoothstep(contact.w * 1.2, contact.w * 2.0, abs(at.y - contact.y));+ return len > 1e-4 ? away / len * near * near * (3.0 - 2.0 * near) * level * contact.w : vec2(0.0);+}void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {float weight = es_vertexColor.r;float phase = es_vertexColor.g * 6.2831853;// The wind is in the world, so its phase is by the world's own position, not the render origin's.vec3 anchor = (esInstanceModel() * vec4(local, 1.0)).xyz + u_renderOrigin.xyz;+ vec2 parted = foliageContactPush(u_contact0, anchor) + foliageContactPush(u_contact1, anchor)+ + foliageContactPush(u_contact2, anchor) + foliageContactPush(u_contact3, anchor);+ // Bounded so a blade cannot leave what its cell's bounds allow for; the wind has the rest of that.+ float partedLen = length(parted);+ if (partedLen > 0.0) {+ parted *= min(partedLen * u_contactBend, 24.0) / partedLen * weight;+ local.xz += parted;+ local.y -= length(parted) * 0.6 * weight;+ }float angle = radians(u_windDirection);vec2 dir = vec2(sin(angle), cos(angle));float t = u_time.x * u_windSpeed;@@ -62,10 +86,28 @@ void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {#pragma end#pragma vertexoffset wgsl+fn foliageContactPush(contact : vec4f, at : vec3f) -> vec2f {+ if (contact.w <= 0.0) { return vec2f(0.0); }+ let away = at.xz - contact.xz;+ let len = length(away);+ let near = clamp(1.0 - len / contact.w, 0.0, 1.0);+ let level = 1.0 - smoothstep(contact.w * 1.2, contact.w * 2.0, abs(at.y - contact.y));+ if (len <= 1e-4) { return vec2f(0.0); }+ return away / len * near * near * (3.0 - 2.0 * near) * level * contact.w;+}fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {let weight = es_vertexColor.r;let phase = es_vertexColor.g * 6.2831853;let anchor = (esInstanceModel() * vec4f(*local, 1.0)).xyz + frame.renderOrigin.xyz;+ var parted = foliageContactPush(mc.u_contact0, anchor) + foliageContactPush(mc.u_contact1, anchor)+ + foliageContactPush(mc.u_contact2, anchor) + foliageContactPush(mc.u_contact3, anchor);+ let partedLen = length(parted);+ if (partedLen > 0.0) {+ parted = parted * min(partedLen * mc.u_contactBend, 24.0) / partedLen * weight;+ (*local).x = (*local).x + parted.x;+ (*local).z = (*local).z + parted.y;+ (*local).y = (*local).y - length(parted) * 0.6 * weight;+ }let angle = radians(mc.u_windDirection);let dir = vec2f(sin(angle), cos(angle));let t = tc.u_time.x * mc.u_windSpeed;diff --git a/sdk/src/foliage/index.ts b/sdk/src/foliage/index.tsindex 481314c3c..b2f60b065 100644--- a/sdk/src/foliage/index.ts+++ b/sdk/src/foliage/index.ts@@ -8,7 +8,11 @@ export {type PlacedFoliageData,} from './placedFoliage';export { PlantGrowth, PlantGrowthRes, plantGrowthOf } from './plantGrowth';-export { PLACED_STRIDE, type PlacedKind, type PlacedPart, type PlantKind } from './plantKind';+export { PLACED_STRIDE, type PlacedKind, type PlacedPart, type PlantKind, type PlantInteractionDef } from './plantKind';+export {+ FoliageContact, PlantProxy, PlantInteraction, PlantInteractionRes, plantInteractionOf,+ type FoliageContactData, type PlantProxyData, type PlantRef, type PlantEvent, type PlantState, type PlantSaveState,+} from './plantInteraction';export {scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, softenNormals, buildBillboardMesh, rng,type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,diff --git a/sdk/src/foliage/placedFoliage.ts b/sdk/src/foliage/placedFoliage.tsindex f1974e50b..fcd5e75e5 100644--- a/sdk/src/foliage/placedFoliage.ts+++ b/sdk/src/foliage/placedFoliage.ts@@ -17,7 +17,7 @@import type { App, Plugin } from '../app/app';import { defineSystem, Schedule } from '../ecs/system';import { defineResource } from '../ecs/resource';-import { defineComponent, RuntimeOnly, Transform, type ComponentDef, type TransformData } from '../ecs/component';+import { defineComponent, getComponent, RuntimeOnly, Transform, type ComponentDef, type TransformData } from '../ecs/component';import { Assets } from '../asset/AssetPlugin';import { log } from '../util/logger';import { chunksOf, ProceduralChunksRes } from '../residency/chunks';@@ -25,6 +25,7 @@ import type { Entity } from '../types';import type { Plant } from './builder';import { PLACED_STRIDE, type PlacedKind, type PlacedPart } from './plantKind';import { plantGrowthOf, prepareKinds, releaseKinds, type GrownCell, type ReadyKinds } from './plantGrowth';+import { plantInteractionOf } from './plantInteraction';export { PLACED_STRIDE, type PlacedKind, type PlacedPart };@@ -35,6 +36,8 @@ export interface PlacedFoliageData {cellSize: number;kinds: PlacedKind[];records: number[];+ /** The name a save keeps what became of these plants under. Empty takes the entity's name. */+ stateKey: string;}/**@@ -43,7 +46,7 @@ export interface PlacedFoliageData {* @experimental*/export const PlacedFoliage: ComponentDef<PlacedFoliageData> = defineComponent<PlacedFoliageData>('PlacedFoliage', {- sizeX: 256, sizeZ: 256, cellSize: 32, kinds: [] as PlacedKind[], records: [] as number[],+ sizeX: 256, sizeZ: 256, cellSize: 32, kinds: [] as PlacedKind[], records: [] as number[], stateKey: '',}, {// The kinds name meshes, materials and textures inside a list, which the component's own fields cannot declare; they are listed here// so a package carries them, and loaded by path when a cell is grown.@@ -71,6 +74,7 @@ export const PlacedFoliage: ComponentDef<PlacedFoliageData> = defineComponent<PlcellSize: { min: 4, category: 'Area', tooltip: 'Side of the cells the area is cut into. Each kind in a cell is one mesh a part, culled whole.' },kinds: { category: 'Plants', tooltip: 'What each kind of plant is made of: its parts (mesh, cheaper mesh, material, texture, tint) and how far it is drawn.' },records: { category: 'Plants', tooltip: 'Where each plant stands: kind index, x, y, z, turn about the vertical in radians and scale, six numbers a plant, in this entity\'s space.' },+ stateKey: { category: 'Plants', tooltip: 'The name a save keeps what became of these plants under. Empty takes the entity\'s name.' },},});@@ -198,6 +202,12 @@ export class PlacedFoliagePlugin implements Plugin {const cells = this.cellsAcross(data);const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;const growth = plantGrowthOf(app), chunks = chunksOf(app);+ const interactive = data.kinds.some((k) => k.interaction);+ const sourceOf = (): string => {+ const name = getComponent('Name');+ const named = name && app.world.has(entity, name) ? (app.world.get(entity, name) as { value?: string }).value : '';+ return `placed:${data.stateKey || named || entity}`;+ };let reach = 1, farReach = 0;for (const kind of data.kinds) { reach = Math.max(reach, kind.drawDistance); if ((kind.far?.length ?? 0) > 0) farReach = Math.max(farReach, kind.farDistance); }const generation = `${built.epoch}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${sx}:${sz}`;@@ -222,7 +232,11 @@ export class PlacedFoliagePlugin implements Plugin {make: (cx, cz) => {if (!built.ready) return null;const made = spawn(cx, cz, 'PlacedCell');- if (made?.by) growth.growCell(app, made.cell, data.kinds, built.ready, made.by);+ if (made?.by) {+ if (interactive) made.cell.sets = [];+ growth.growCell(app, made.cell, data.kinds, built.ready, made.by);+ if (interactive) plantInteractionOf(app).addCell(made.cell, sourceOf(), data.kinds, built.ready, made.by, Math.max(data.sizeX / cells.x * sx, data.sizeZ / cells.z * sz) / 2);+ }return made?.cell ?? null;},publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },@@ -235,7 +249,11 @@ export class PlacedFoliagePlugin implements Plugin {make: (cx, cz) => {if (!built.ready) return null;const made = spawn(cx, cz, 'FarCell');- if (made?.by) growth.growFar(app, made.cell, data.kinds, built.ready, made.by, made.at);+ if (made?.by) {+ if (interactive) made.cell.sets = [];+ growth.growFar(app, made.cell, data.kinds, built.ready, made.by, made.at);+ if (interactive) plantInteractionOf(app).addFarCell(made.cell, sourceOf(), data.kinds, built.ready);+ }return made?.cell ?? null;},publish: (_cx, _cz, cell) => { if (cell.entity !== null) app.world.setParent(cell.entity, entity); },@@ -247,6 +265,7 @@ export class PlacedFoliagePlugin implements Plugin {private sort(built: BuiltPlaced, cells: { x: number; z: number }): Map<number, Map<number, Plant[]>> {if (built.cells) return built.cells;const data = built.data, a = data.records;+ const keyed = data.kinds.some((k) => k.interaction);const w = data.sizeX / cells.x, d = data.sizeZ / cells.z;const sorted = new Map<number, Map<number, Plant[]>>();for (let i = 0; i + PLACED_STRIDE <= a.length; i += PLACED_STRIDE) {@@ -258,7 +277,7 @@ export class PlacedFoliagePlugin implements Plugin {if (!byKind) sorted.set(key, byKind = new Map());let list = byKind.get(kind);if (!list) byKind.set(kind, list = []);- list.push({ x, y: a[i + 2]!, z, yaw: a[i + 4]!, scale: a[i + 5]!, phase: 0, shade: 1 });+ list.push({ x, y: a[i + 2]!, z, yaw: a[i + 4]!, scale: a[i + 5]!, phase: 0, shade: 1, ...(keyed && data.kinds[kind]?.interaction ? { key: String(i / PLACED_STRIDE) } : {}) });}built.cells = sorted;return sorted;diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.tsindex 5f33ec97e..a18039312 100644--- a/sdk/src/foliage/plantGrowth.ts+++ b/sdk/src/foliage/plantGrowth.ts@@ -36,8 +36,30 @@ export interface ReadyPart { part: PlacedPart; mesh: number; lod1: number; lod2?/** Every kind's parts in hand, and the parts that stand for each far off; `owned` are the meshes made here, which `releaseKinds` gives back. */export interface ReadyKinds { kinds: ReadyPart[][]; far: ReadyPart[][]; owned: number[]; lease: AssetLease<AssetScope> }+/** One set of placements in a cell: the entity holding them, the kind and the plants it was made for. */+export interface PlacementSet {+ entity: Entity;+ kind: number;+ plants: readonly Plant[];+ /** Made to show plants that turned into this kind (a stump), rather than the ones grown as it. */+ turned: boolean;+}+/** One grown cell: its entity (none where nothing stands), what it owns so far, and whether it has been let go. */-export interface GrownCell { entity: Entity | null; handles: number[]; dead: boolean; assets?: AssetLease<AssetScope> }+export interface GrownCell {+ entity: Entity | null;+ handles: number[];+ dead: boolean;+ assets?: AssetLease<AssetScope>;+ /** Its placement sets, kept where a plant in it can change; absent, they are made and forgotten. */+ sets?: PlacementSet[];+}++/** Who decides what a cell's sets show, where its plants can be touched. */+export interface PlacementObserver {+ placementsOf(cell: GrownCell, set: PlacementSet): readonly Plant[];+ removeCell(cell: GrownCell): void;+}/*** Loads the meshes, materials and textures of every part of every kind, once. A part whose normals are turned toward up (`soft`) is a mesh of its own,@@ -113,6 +135,8 @@ export class PlantGrowth {/** The pieces not yet made, in the order they were asked. */readonly queue: { cell: GrownCell; run: () => void }[] = [];app_: App | null = null;+ /** @internal Installed with the plant interaction, the first time a kind wants it. */+ observer_: PlacementObserver | null = null;/** How many pieces are still waiting to be made. */get pending(): number { return this.queue.length; }@@ -125,7 +149,7 @@ export class PlantGrowth {* Makes one entity under `parent` that draws `part`'s mesh at every place in `plants`, relative to `parent`. `from` and `to` are the distances* from the eye between which a plant is drawn (0 for no limit); `lod` is the distance past which the part's cheaper mesh stands in, and `shadow` the one past which it casts no shadow. All of them are scaled by the quality level's `detailScale`.*/- private place(app: App, parent: Entity, name: string, part: ReadyPart, plants: readonly Plant[], lod: number, from: number, to: number, shadow = 0, far = false, mesh = part.mesh, lod1 = part.lod1): void {+ private place(app: App, parent: Entity, name: string, part: ReadyPart, plants: readonly Plant[], lod: number, from: number, to: number, shadow = 0, far = false, mesh = part.mesh, lod1 = part.lod1): Entity {const world = app.world;// The quality level's share of the kind's distances: a weaker device changes to the cheaper mesh sooner and draws less far.const quality = app.hasResource(Quality) ? app.getResource(Quality) : null;@@ -144,16 +168,48 @@ export class PlantGrowth {const placements = getComponent('MeshInstances');if (placements) world.insert(e, placements, { lod1Mesh: lod1, lodDistance: lod1 ? lod : 0, minDistance: from, drawDistance: to, shadowDistance: shadow });world.setParent(e, parent);+ if (plants.length > 0) this.writePlacements(app, e, plants);+ return e;+ }++ /** Tells the engine where a set's plants stand. An empty list clears it. */+ private writePlacements(app: App, entity: Entity, plants: readonly Plant[]): void {const api = engineApi(app);const set = api?.meshInstances_set;- if (!set || !api._malloc || !api._free || !api.HEAPU8 || plants.length === 0) return;+ if (!set || !api._malloc || !api._free || !api.HEAPU8) return;+ const registry = app.world.getCppRegistry() as CppRegistry;+ if (plants.length === 0) { set(registry, entity, 0, 0); return; }const data = buildPlacements(plants);- const registry = world.getCppRegistry() as CppRegistry;withScratch({ _malloc: api._malloc, _free: api._free }, (alloc) => {const ptr = alloc(data.byteLength);// Read after the allocation: it may have grown the memory, which replaces the buffer.new Float32Array(api.HEAPU8!.buffer, ptr, data.length).set(data);- set(registry, e, ptr, data.length / PLACEMENT_FLOATS);+ set(registry, entity, ptr, data.length / PLACEMENT_FLOATS);+ });+ }++ /** @internal Writes a set as its observer says it should be now. */+ writeSet(app: App, cell: GrownCell, set: PlacementSet): void {+ if (!app.world.valid(set.entity)) return;+ this.writePlacements(app, set.entity, this.observer_ ? this.observer_.placementsOf(cell, set) : set.plants);+ }++ /** Places a set, remembering it where the cell's plants can change, and shows it as it should be now. */+ private track(app: App, cell: GrownCell, entity: Entity, kind: number, plants: readonly Plant[], turned = false): void {+ if (!cell.sets) return;+ const set: PlacementSet = { entity, kind, plants, turned };+ cell.sets.push(set);+ if (this.observer_) this.writeSet(app, cell, set);+ }++ /** @internal The sets that show plants that have turned into `kindIndex`, made at once: there are few, and a stump must stand when its tree starts down. */+ placeTurned(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, kindIndex: number): void {+ const kind = kinds[kindIndex], parts = ready.kinds[kindIndex], parent = cell.entity;+ if (!kind || !parts || parent === null || !app.world.valid(parent)) return;+ parts.forEach((r, j) => {+ const shadow = kind.lodDistance > 0 ? kind.lodDistance * 2 : 0;+ const e = this.place(app, parent, `turned ${kindIndex}:${j}`, r, [], kind.lodDistance, 0, kind.drawDistance, shadow);+ this.track(app, cell, e, kindIndex, [], true);});}@@ -176,8 +232,8 @@ export class PlantGrowth {const shadow = kind.lodDistance > 0 ? kind.lodDistance * 2 : 0;// A third mesh takes over where the kind's `lod2Distance` is: two sets, each drawn between its own distances.const third = r.lod2 && (kind.lod2Distance ?? 0) > 0 ? kind.lod2Distance! : 0;- this.place(app, entity, `${kindIndex}:${j}`, r, plants, kind.lodDistance, 0, third || kind.drawDistance, shadow);- if (third) this.place(app, entity, `${kindIndex}:${j}:lod2`, r, plants, 0, third, kind.drawDistance, shadow, false, r.lod2, 0);+ this.track(app, cell, this.place(app, entity, `${kindIndex}:${j}`, r, plants, kind.lodDistance, 0, third || kind.drawDistance, shadow), kindIndex, plants);+ if (third) this.track(app, cell, this.place(app, entity, `${kindIndex}:${j}:lod2`, r, plants, 0, third, kind.drawDistance, shadow, false, r.lod2, 0), kindIndex, plants);} catch (error) {log.error('foliage', 'growing a piece of a cell of plants failed', error);}@@ -200,13 +256,14 @@ export class PlantGrowth {const parts = ready.far[kindIndex], kind = kinds[kindIndex];if (!kind || !parts || parts.length === 0) continue;const kept = thinPlants(plants, kind.farKeep ?? 1, thinnedBy);- for (const r of parts) this.place(app, entity, `far ${kindIndex}`, r, kept, 0, kind.drawDistance, kind.farDistance, 0, true);+ for (const r of parts) this.track(app, cell, this.place(app, entity, `far ${kindIndex}`, r, kept, 0, kind.drawDistance, kind.farDistance, 0, true), kindIndex, kept);}}/** Lets a cell go: what it made is despawned, and what it had not yet made is left unmade. */release(app: App, cell: GrownCell): void {cell.dead = true;+ this.observer_?.removeCell(cell);try {if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);} finally {diff --git a/sdk/src/foliage/plantInteraction.ts b/sdk/src/foliage/plantInteraction.tsnew file mode 100644index 000000000..bf5c64509--- /dev/null+++ b/sdk/src/foliage/plantInteraction.ts@@ -0,0 +1,740 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file plantInteraction.ts+ * @brief Plants that are data until something comes near: a collider and an entity close by, a lean when touched, felling and harvest that last.+ *+ * @details A forest cannot be entities and does not need to be: only what stands near a `FoliageContact` can be touched. So a kind with an+ * `interaction` stays a placement in its `MeshInstances` set, and the plants within its `activationDistance` of a contact are each also+ * given an entity (`PlantProxy`, with a collider where the kind has one) that goes when the contact does. The picture never changes hands, so+ * nothing pops. What happens to a plant is kept against its key, not its cell: a felled tree stays felled when its chunk is let go and+ * grown again, and `saveState` is the same table. A tree comes down as an entity with its own meshes, and its placement is taken out for good.+ */+import type { App } from '../app/app';+import { defineSystem, Schedule } from '../ecs/system';+import { defineResource, Res, Time, type TimeData } from '../ecs/resource';+import { defineComponent, getComponent, MeshRenderer, RuntimeOnly, Transform, type ComponentDef, type MeshRendererData, type TransformData } from '../ecs/component';+import { isEditor, isPlayMode } from '../ecs/env';+import { log } from '../util/logger';+import type { Entity } from '../types';+import type { AssetLease, AssetScope } from '../asset/AssetLease';+import type { Plant } from './builder';+import type { PlacedKind } from './plantKind';+import { plantGrowthOf, type GrownCell, type PlacementSet, type PlantGrowth, type ReadyKinds } from './plantGrowth';++/** The fields of the `FoliageContact` component. @experimental */+export interface FoliageContactData {+ /** How far from the entity plants lean away, in world units. */+ radius: number;+ /** How hard: 1 is a full lean, 0 none. */+ strength: number;+ /** Seconds grass takes to stand up again behind it. */+ recovery: number;+ /** Off: it neither bends plants nor brings them near. */+ enabled: boolean;+}++/**+ * Something plants feel: grass and shrubs lean away from it, and the plants near it become entities with colliders.+ *+ * @experimental+ */+export const FoliageContact: ComponentDef<FoliageContactData> = defineComponent<FoliageContactData>('FoliageContact', {+ radius: 40, strength: 1, recovery: 0.6, enabled: true,+}, {+ fields: {+ radius: { min: 0.01, unit: 'wu', tooltip: 'How far from this entity plants lean away.' },+ strength: { min: 0, max: 2, step: 0.01, tooltip: 'How hard they lean: 1 is a full lean, 0 none.' },+ recovery: { min: 0, step: 0.05, unit: 's', tooltip: 'How long grass takes to stand up again behind it.' },+ },+});++/** The fields of the `PlantProxy` component. @experimental */+export interface PlantProxyData {+ /** The table the plant's state is kept in: a world's, or a `PlacedFoliage`'s. */+ source: string;+ /** The plant, within its source. */+ key: string;+}++/**+ * Marks the entity standing in for a plant while something is near it. What a ray or a collision hits; `PlantInteraction.of` says which plant it is.+ *+ * @experimental+ */+export const PlantProxy: ComponentDef<PlantProxyData> = defineComponent<PlantProxyData>('PlantProxy', { source: '', key: '' });++/** What has become of a plant. @experimental */+export type PlantState = 'standing' | 'felled' | 'harvested' | 'removed';++/** One plant as a game asks about it. @experimental */+export interface PlantRef {+ source: string;+ key: string;+ /** The kind it shows now: a felled tree's stump is a kind of its own. */+ kind: number;+ x: number;+ y: number;+ z: number;+ scale: number;+ state: PlantState;+ /** What is left of its `health`. */+ health: number;+ /** How many more times it can be harvested. */+ yields: number;+ /** Its `PlantProxy`, while something is near. */+ entity: Entity | null;+}++/** Something that happened to a plant. @experimental */+export interface PlantEvent {+ type: 'activated' | 'deactivated' | 'damaged' | 'felled' | 'landed' | 'harvested' | 'removed' | 'regrown';+ plant: PlantRef;+}++/** The change kept against one plant. A plant with none is as it was grown. */+interface PlantChange {+ state: PlantState;+ /** The kind it shows instead, or -1 for nothing. */+ shownAs: number;+ health: number;+ yields: number;+ /** The clock at which it stands again; 0 for never. */+ regrowAt: number;+}++interface CellPlant { plant: Plant; kind: number }++interface InteractiveCell {+ grown: GrownCell;+ source: string;+ kinds: readonly PlacedKind[];+ ready: ReadyKinds;+ plants: Map<string, CellPlant>;+ half: number;+ reach: number;+ /** The cell entity's place in the world, read once it has one. */+ at: { x: number; y: number; z: number } | null;+ /** The kinds a set has been made for, to show what a plant turned into. */+ shown: Set<number>;+}++interface ActivePlant {+ cell: InteractiveCell;+ key: string;+ proxy: Entity | null;+ /** The lean, as a shear: sideways per unit of height, and how fast it is changing. */+ leanX: number; leanZ: number; speedX: number; speedZ: number;+ /** It has come to rest and been drawn so: nothing to write until something moves it. */+ settled: boolean;+ kind: number;+}++interface Falling {+ root: Entity;+ elapsed: number;+ seconds: number;+ lie: number;+ angle: number;+ axisX: number; axisZ: number;+ landed: boolean;+ plant: PlantRef;+ assets: AssetLease<AssetScope> | null;+}++/** How much of a lean each second gives way, and how hard it is pulled to where it should be: a rustle that settles in about a second. */+const LEAN_PULL = 90, LEAN_DAMP = 9, LEAN_REST = 0.0005;+const SCAN_SECONDS = 0.1, GROW_IN_SECONDS = 1.5, SINK_SECONDS = 1.5;+const stateId = (source: string, key: string): string => `${source}\n${key}`;++/** The saved form of what has become of the plants. @experimental */+export interface PlantSaveState {+ version: 1;+ clock: number;+ plants: { source: string; key: string; state: PlantState; shownAs: number; health: number; yields: number; regrowAt: number }[];+}++/** Everything plants know about being touched. @experimental */+export class PlantInteraction {+ /** @internal */ app_: App | null = null;+ private readonly cells_ = new Map<GrownCell, InteractiveCell>();+ private readonly changes_ = new Map<string, PlantChange>();+ private readonly active_ = new Map<string, ActivePlant>();+ private readonly falling_ = new Set<Falling>();+ /** Plants coming back: when they started, on the clock. */+ private readonly growing_ = new Map<string, number>();+ private readonly listeners_ = new Set<(event: PlantEvent) => void>();+ private clock_ = 0;+ private untilScan_ = 0;++ /** The most plants that are entities at once; a contact in a thicket past this finds the furthest still data. */+ maxActive = 512;+ /** The most made per frame, so walking into a wood costs a few frames and not one long one. */+ maxActivatedPerFrame = 48;++ /** How many plants are entities now. */+ get activeCount(): number { return this.active_.size; }+ /** How many plants have had something happen to them, across every source: what a save holds. */+ get changedCount(): number { return this.changes_.size; }++ /** Hears what happens to plants. Returns what stops it. */+ on(listener: (event: PlantEvent) => void): () => void {+ this.listeners_.add(listener);+ return () => { this.listeners_.delete(listener); };+ }++ /** The plant an entity stands for, a `PlantProxy` that a ray or a collision found. */+ of(entity: Entity): PlantRef | null {+ const world = this.app_?.world;+ if (!world?.valid(entity) || !world.has(entity, PlantProxy)) return null;+ const proxy = world.get(entity, PlantProxy) as PlantProxyData;+ return this.find(proxy.source, proxy.key);+ }++ /** A plant by its source and key, where its cell is grown now. */+ find(source: string, key: string): PlantRef | null {+ for (const cell of this.cells_.values()) {+ if (cell.source !== source) continue;+ const entry = cell.plants.get(key);+ if (entry) return this.refOf(cell, key, entry);+ }+ return null;+ }++ /** The plants with an `interaction` within `radius` of a place on the ground, nearest first: what an axe swung here could reach. Cut ones are not among them. */+ near(x: number, z: number, radius: number): PlantRef[] {+ const out: { ref: PlantRef; d: number }[] = [];+ for (const cell of this.cells_.values()) {+ const at = this.cellAt(cell);+ if (!at || Math.abs(x - at.x) > cell.half + radius || Math.abs(z - at.z) > cell.half + radius) continue;+ for (const [key, entry] of cell.plants) {+ const d = Math.hypot(at.x + entry.plant.x - x, at.z + entry.plant.z - z);+ if (d > radius || this.kindNow(cell, key, entry) < 0) continue;+ out.push({ ref: this.refOf(cell, key, entry), d });+ }+ }+ return out.sort((a, b) => a.d - b.d).map((p) => p.ref);+ }++ /** Takes `amount` of a plant's `health`, and fells it at nothing left, away from `from` where given. False for a plant that cannot be hurt. */+ damage(plant: PlantRef, amount: number, from?: { x: number; z: number }): boolean {+ const found = this.located(plant);+ if (!found) return false;+ const interaction = found.cell.kinds[found.kind]?.interaction;+ const health = interaction?.health ?? 0;+ const change = this.changes_.get(stateId(plant.source, plant.key));+ if (health <= 0 || (change && change.state !== 'standing')) return false;+ const left = (change ? change.health : health) - Math.max(0, amount);+ const next = this.changeFor(found.cell, plant.key, found.kind);+ next.health = Math.max(0, left);+ const ref = this.refOf(found.cell, plant.key, found.entry);+ this.emit('damaged', ref);+ // A blow shakes what can shake.+ const active = this.active_.get(stateId(plant.source, plant.key));+ const at = this.cellAt(found.cell);+ if (active && from && at && (interaction?.bend ?? 0) > 0) {+ const dx = at.x + found.entry.plant.x - from.x, dz = at.z + found.entry.plant.z - from.z, len = Math.hypot(dx, dz) || 1;+ active.speedX += dx / len * 2; active.speedZ += dz / len * 2;+ active.settled = false;+ }+ if (left <= 0) {+ if (from && at) {+ const dx = at.x + found.entry.plant.x - from.x, dz = at.z + found.entry.plant.z - from.z;+ this.fell(ref, { x: dx, z: dz });+ } else this.fell(ref);+ }+ return true;+ }++ /** Brings a plant down, toward a direction on the ground or along its own turn. Only what still stands; false otherwise. */+ fell(plant: PlantRef, toward?: { x: number; z: number }): boolean {+ const found = this.located(plant);+ if (!found) return false;+ const id = stateId(plant.source, plant.key);+ const had = this.changes_.get(id);+ if (had && had.state !== 'standing') return false;+ const interaction = found.cell.kinds[found.kind]?.interaction;+ const change = this.changeFor(found.cell, plant.key, found.kind);+ change.state = 'felled';+ change.health = 0;+ change.shownAs = this.resolveKind(interaction?.felledKind);+ change.regrowAt = (interaction?.regrowSeconds ?? 0) > 0 ? this.clock_ + interaction!.regrowSeconds! : 0;+ this.startFall(found.cell, found.kind, found.entry.plant, toward, plant);+ this.deactivate(id);+ this.refreshCell(found.cell, found.kind, change.shownAs);+ this.writeFar(found.cell.source);+ this.emit('felled', this.refOf(found.cell, plant.key, found.entry));+ return true;+ }++ /** Takes up to `amount` from a plant, and answers how much it got. At nothing left it becomes its `harvestedKind`, or is gone until it regrows. */+ harvest(plant: PlantRef, amount = 1): number {+ const found = this.located(plant);+ if (!found) return 0;+ const interaction = found.cell.kinds[found.kind]?.interaction;+ const yields = interaction?.yields ?? 0;+ const had = this.changes_.get(stateId(plant.source, plant.key));+ if (yields <= 0 || (had && had.state !== 'standing')) return 0;+ const left = had ? had.yields : yields;+ const taken = Math.min(left, Math.max(0, Math.floor(amount)));+ if (taken === 0) return 0;+ const change = this.changeFor(found.cell, plant.key, found.kind);+ change.yields = left - taken;+ if (change.yields === 0) {+ change.state = 'harvested';+ change.shownAs = this.resolveKind(interaction?.harvestedKind);+ change.regrowAt = (interaction?.regrowSeconds ?? 0) > 0 ? this.clock_ + interaction!.regrowSeconds! : 0;+ this.deactivate(stateId(plant.source, plant.key));+ this.refreshCell(found.cell, found.kind, change.shownAs);+ this.writeFar(found.cell.source);+ }+ this.emit('harvested', this.refOf(found.cell, plant.key, found.entry));+ return taken;+ }++ /** Takes a plant away with no fall, for good: what a building placed over it or a game's own rule does. */+ remove(plant: PlantRef): boolean {+ const found = this.located(plant);+ if (!found) return false;+ const change = this.changeFor(found.cell, plant.key, found.kind);+ change.state = 'removed';+ change.shownAs = -1;+ change.regrowAt = 0;+ this.deactivate(stateId(plant.source, plant.key));+ this.refreshCell(found.cell, found.kind, -1);+ this.writeFar(found.cell.source);+ this.emit('removed', this.refOf(found.cell, plant.key, found.entry));+ return true;+ }++ /** Everything that has become of the plants, for a save. A tree coming down is saved as down. */+ saveState(): PlantSaveState {+ const plants: PlantSaveState['plants'] = [];+ for (const [id, c] of this.changes_) {+ const cut = id.indexOf('\n');+ plants.push({ source: id.slice(0, cut), key: id.slice(cut + 1), state: c.state, shownAs: c.shownAs, health: c.health, yields: c.yields, regrowAt: c.regrowAt });+ }+ return { version: 1, clock: this.clock_, plants };+ }++ /** Puts the plants back as a save has them, whatever is grown now. What had fallen and not gone yet is gone. */+ loadState(state: PlantSaveState): void {+ if (state.version !== 1) throw new Error(`plant state version ${String(state.version)} is not one this engine reads`);+ for (const f of [...this.falling_]) this.endFall(f);+ for (const id of [...this.active_.keys()]) this.deactivate(id);+ this.changes_.clear();+ this.growing_.clear();+ this.clock_ = state.clock;+ for (const p of state.plants) {+ this.changes_.set(stateId(p.source, p.key), { state: p.state, shownAs: p.shownAs, health: p.health, yields: p.yields, regrowAt: p.regrowAt });+ }+ for (const cell of this.cells_.values()) {+ for (const [key] of cell.plants) {+ const c = this.changes_.get(stateId(cell.source, key));+ if (c && c.shownAs >= 0) this.ensureShown(cell, c.shownAs);+ }+ this.writeCell(cell);+ }+ }++ /** @internal A cell of plants has been planted: the kinds with an `interaction` are known from now on. */+ addCell(grown: GrownCell, source: string, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, half: number): void {+ const plants = new Map<string, CellPlant>();+ let reach = 0;+ for (const [kind, list] of byKind) {+ const interaction = kinds[kind]?.interaction;+ if (!interaction) continue;+ reach = Math.max(reach, interaction.activationDistance ?? 0);+ for (const plant of list) if (plant.key !== undefined) plants.set(plant.key, { plant, kind });+ }+ const cell: InteractiveCell = { grown, source, kinds, ready, plants, half, reach, at: null, shown: new Set() };+ this.cells_.set(grown, cell);+ // What became of its plants while it was away.+ for (const key of plants.keys()) {+ const c = this.changes_.get(stateId(source, key));+ if (c && c.shownAs >= 0) this.ensureShown(cell, c.shownAs);+ }+ }++ /** @internal A far cell: nothing near enough to touch, so only what stands for a felled plant needs to go. It is told apart by having no reach. */+ addFarCell(grown: GrownCell, source: string, kinds: readonly PlacedKind[], ready: ReadyKinds): void {+ this.cells_.set(grown, { grown, source, kinds, ready, plants: new Map(), half: 0, reach: 0, at: null, shown: new Set() });+ }++ /** @internal What a cell's set should show now: its plants less those that have gone, each as it leans or grows. */+ placementsOf(grown: GrownCell, set: PlacementSet): readonly Plant[] {+ const cell = this.cells_.get(grown);+ if (!cell) return set.plants;+ if (set.turned) {+ const out: Plant[] = [];+ for (const [key, entry] of cell.plants) {+ const c = this.changes_.get(stateId(cell.source, key));+ if (c && c.state !== 'standing' && c.shownAs === set.kind) out.push(entry.plant);+ }+ return out;+ }+ const out: Plant[] = [];+ for (const plant of set.plants) {+ if (plant.key === undefined) { out.push(plant); continue; }+ const id = stateId(cell.source, plant.key);+ const c = this.changes_.get(id);+ if (c && c.state !== 'standing') continue;+ const active = this.active_.get(id), started = this.growing_.get(id);+ if (!active?.leanX && !active?.leanZ && started === undefined) { out.push(plant); continue; }+ const grow = started === undefined ? 1 : Math.min(1, Math.max(0.02, (this.clock_ - started) / GROW_IN_SECONDS));+ out.push({ ...plant, scale: plant.scale * grow, ...(active ? { shear: [active.leanX, active.leanZ] as const } : {}) });+ }+ return out;+ }++ /** @internal A cell has been let go: its entities go with it, and what became of its plants stays. */+ removeCell(grown: GrownCell): void {+ const cell = this.cells_.get(grown);+ if (!cell) return;+ for (const key of cell.plants.keys()) this.deactivate(stateId(cell.source, key));+ this.cells_.delete(grown);+ }++ /** @internal */+ step(dt: number): void {+ const app = this.app_;+ if (!app || (isEditor() && !isPlayMode())) return;+ this.clock_ += dt;+ this.regrow();+ this.advanceFalls(dt);+ const contacts = this.contacts();+ this.untilScan_ -= dt;+ if (this.untilScan_ <= 0) {+ this.untilScan_ = SCAN_SECONDS;+ this.scan(contacts);+ }+ this.lean(contacts, dt);+ this.advanceGrowth();+ }++ private contacts(): { x: number; y: number; z: number; radius: number; strength: number }[] {+ const world = this.app_!.world;+ const out: { x: number; y: number; z: number; radius: number; strength: number }[] = [];+ for (const e of world.getEntitiesWithComponents([FoliageContact, Transform])) {+ const c = world.get(e, FoliageContact) as FoliageContactData;+ if (!c.enabled) continue;+ const t = world.get(e, Transform) as TransformData;+ out.push({ x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z, radius: c.radius, strength: c.strength });+ }+ return out;+ }++ /** Which plants should be entities, within what each kind says, and which no longer should. */+ private scan(contacts: readonly { x: number; z: number }[]): void {+ const wanted = new Set<string>();+ let budget = this.maxActivatedPerFrame;+ for (const cell of this.cells_.values()) {+ if (cell.reach <= 0) continue;+ const at = this.cellAt(cell);+ if (!at) continue;+ for (const contact of contacts) {+ // Past the cell by further than any of its kinds reaches.+ if (Math.abs(contact.x - at.x) > cell.half + cell.reach * 1.25 || Math.abs(contact.z - at.z) > cell.half + cell.reach * 1.25) continue;+ for (const [key, entry] of cell.plants) {+ const kind = this.kindNow(cell, key, entry);+ if (kind < 0) continue;+ const reach = cell.kinds[kind]?.interaction?.activationDistance ?? 0;+ if (reach <= 0) continue;+ const dx = at.x + entry.plant.x - contact.x, dz = at.z + entry.plant.z - contact.z, d2 = dx * dx + dz * dz;+ const id = stateId(cell.source, key);+ const already = this.active_.has(id);+ // A little further to leave than to arrive, so walking along the edge does not make and unmake them.+ const limit = already ? reach * 1.25 : reach;+ if (d2 > limit * limit) continue;+ wanted.add(id);+ if (already || budget <= 0 || this.active_.size >= this.maxActive) continue;+ budget--;+ this.activate(cell, key, entry, kind, id);+ }+ }+ }+ for (const id of [...this.active_.keys()]) if (!wanted.has(id)) this.deactivate(id);+ }++ private activate(cell: InteractiveCell, key: string, entry: CellPlant, kind: number, id: string): void {+ const active: ActivePlant = { cell, key, proxy: null, leanX: 0, leanZ: 0, speedX: 0, speedZ: 0, settled: true, kind };+ active.proxy = this.spawnProxy(cell, key, entry, kind);+ this.active_.set(id, active);+ this.emit('activated', this.refOf(cell, key, entry));+ }++ private spawnProxy(cell: InteractiveCell, key: string, entry: CellPlant, kind: number): Entity | null {+ const world = this.app_!.world, at = this.cellAt(cell);+ if (!at) return null;+ const e = world.spawn(`Plant ${key}`);+ world.insert(e, RuntimeOnly);+ world.insert(e, Transform, { position: { x: at.x + entry.plant.x, y: at.y + entry.plant.y, z: at.z + entry.plant.z } });+ world.insert(e, PlantProxy, { source: cell.source, key });+ this.insertCollider(e, cell.kinds[kind], entry.plant.scale, 0);+ return e;+ }++ /** A capsule standing on the plant's foot. The physics module is optional and read by name; a game without it has plants with no collision and no complaint. */+ private insertCollider(e: Entity, kind: PlacedKind | undefined, scale: number, bodyType: number): void {+ const interaction = kind?.interaction;+ const radius = (interaction?.radius ?? 0) * scale, height = (interaction?.height ?? 0) * scale;+ if (radius <= 0 || height <= 0) return;+ const body = getComponent('RigidBody3D'), capsule = getComponent('CapsuleCollider3D');+ if (!body || !capsule) return;+ const world = this.app_!.world;+ world.insert(e, body, { bodyType, gravityScale: 0 });+ world.insert(e, capsule, { radius, halfHeight: Math.max(0, height / 2 - radius), center: { x: 0, y: height / 2, z: 0 } });+ }++ private deactivate(id: string): void {+ const active = this.active_.get(id);+ if (!active) return;+ this.active_.delete(id);+ const world = this.app_?.world;+ const entry = active.cell.plants.get(active.key);+ if (entry) this.emit('deactivated', this.refOf(active.cell, active.key, entry));+ if (active.proxy !== null && world?.valid(active.proxy)) world.despawn(active.proxy);+ // It stands straight again as data.+ if ((active.leanX || active.leanZ) && entry) this.writeKind(active.cell, active.kind);+ }++ /** Each active plant toward where its contacts push it, with a spring, so it rustles on being let go. */+ private lean(contacts: readonly { x: number; z: number; radius: number; strength: number }[], dt: number): void {+ const dirty = new Map<InteractiveCell, Set<number>>();+ const h = Math.min(dt, 1 / 30);+ for (const active of this.active_.values()) {+ const entry = active.cell.plants.get(active.key), at = this.cellAt(active.cell);+ const bend = active.cell.kinds[active.kind]?.interaction?.bend ?? 0;+ if (!entry || !at || bend <= 0) continue;+ let tx = 0, tz = 0;+ for (const c of contacts) {+ const dx = at.x + entry.plant.x - c.x, dz = at.z + entry.plant.z - c.z, d = Math.hypot(dx, dz);+ if (d >= c.radius || d < 1e-5) continue;+ const f = (1 - d / c.radius) * c.strength;+ tx += dx / d * f; tz += dz / d * f;+ }+ const size = Math.hypot(tx, tz), most = Math.tan(bend);+ const scale = size > 1 ? most / size : most;+ tx *= scale; tz *= scale;+ active.speedX += ((tx - active.leanX) * LEAN_PULL - active.speedX * LEAN_DAMP) * h;+ active.speedZ += ((tz - active.leanZ) * LEAN_PULL - active.speedZ * LEAN_DAMP) * h;+ active.leanX += active.speedX * h;+ active.leanZ += active.speedZ * h;+ if (Math.abs(active.leanX - tx) + Math.abs(active.leanZ - tz) + Math.abs(active.speedX) * h + Math.abs(active.speedZ) * h < LEAN_REST) {+ active.leanX = tx; active.leanZ = tz; active.speedX = 0; active.speedZ = 0;+ if (active.settled) continue;+ active.settled = true;+ } else active.settled = false;+ let kinds = dirty.get(active.cell);+ if (!kinds) dirty.set(active.cell, kinds = new Set());+ kinds.add(active.kind);+ }+ for (const [cell, kinds] of dirty) for (const kind of kinds) this.writeKind(cell, kind);+ }++ private regrow(): void {+ for (const [id, c] of this.changes_) {+ if (c.regrowAt <= 0 || c.regrowAt > this.clock_) continue;+ this.changes_.delete(id);+ this.growing_.set(id, this.clock_);+ const cut = id.indexOf('\n'), source = id.slice(0, cut), key = id.slice(cut + 1);+ for (const cell of this.cells_.values()) {+ if (cell.source !== source) continue;+ this.writeCell(cell);+ const entry = cell.plants.get(key);+ if (entry) this.emit('regrown', this.refOf(cell, key, entry));+ }+ }+ }++ private advanceGrowth(): void {+ if (this.growing_.size === 0) return;+ const writes = new Map<InteractiveCell, Set<number>>();+ for (const [id, started] of this.growing_) {+ const cut = id.indexOf('\n'), source = id.slice(0, cut), key = id.slice(cut + 1);+ for (const cell of this.cells_.values()) {+ if (cell.source !== source) continue;+ const entry = cell.plants.get(key);+ if (!entry) continue;+ let kinds = writes.get(cell);+ if (!kinds) writes.set(cell, kinds = new Set());+ kinds.add(entry.kind);+ }+ if (this.clock_ - started >= GROW_IN_SECONDS) this.growing_.delete(id);+ }+ for (const [cell, kinds] of writes) for (const kind of kinds) this.writeKind(cell, kind);+ }++ /** It comes down as an entity with its own meshes, turning about its foot: a shape a character can be hit by and then climb over. */+ private startFall(cell: InteractiveCell, kind: number, plant: Plant, toward: { x: number; z: number } | undefined, ref: PlantRef): void {+ const world = this.app_!.world, at = this.cellAt(cell);+ const interaction = cell.kinds[kind]?.interaction;+ const seconds = interaction?.fallSeconds ?? 1.8;+ const parts = cell.ready.kinds[kind];+ if (!at || !parts || seconds <= 0) return;+ const dx = toward?.x ?? Math.sin(plant.yaw), dz = toward?.z ?? Math.cos(plant.yaw);+ const len = Math.hypot(dx, dz) || 1;+ const root = world.spawn('Felled plant');+ world.insert(root, RuntimeOnly);+ world.insert(root, Transform, { position: { x: at.x + plant.x, y: at.y + plant.y, z: at.z + plant.z } });+ world.insert(root, PlantProxy, { source: cell.source, key: plant.key ?? '' });+ // Kinematic: the fall drives the body, and what it lands on it pushes aside.+ this.insertCollider(root, cell.kinds[kind], plant.scale, 1);+ const half = plant.yaw / 2;+ for (const r of parts) {+ const e = world.spawn('Felled part');+ world.insert(e, RuntimeOnly);+ world.insert(e, Transform, {+ rotation: { x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) },+ scale: { x: plant.scale, y: plant.scale, z: plant.scale },+ });+ world.insert(e, MeshRenderer, {+ mesh: r.mesh, material: r.material, texture: r.texture, lit: true, opaque: r.part.opaque !== false, cullBackfaces: false,+ castShadows: r.part.castShadows !== false,+ color: { r: r.part.tint[0], g: r.part.tint[1], b: r.part.tint[2], a: r.part.tint[3] },+ } as Partial<MeshRendererData>);+ world.setParent(e, root);+ }+ this.falling_.add({+ root, elapsed: 0, seconds, lie: interaction?.lieSeconds ?? 30,+ // A little short of flat: its crown takes the ground first, not its trunk.+ angle: (interaction?.fallAngle ?? 85) * Math.PI / 180,+ // Up crossed with where it falls.+ axisX: dz / len, axisZ: -dx / len,+ landed: false, plant: ref, assets: cell.ready.lease.retain() ?? null,+ });+ }++ private advanceFalls(dt: number): void {+ const world = this.app_!.world;+ for (const f of [...this.falling_]) {+ if (!world.valid(f.root)) { this.endFall(f); continue; }+ f.elapsed += dt;+ const t = Math.min(1, f.elapsed / f.seconds);+ // As a thing falls: slowly from standing, and fastest at the end.+ const a = f.angle * t * t;+ const transform = world.get(f.root, Transform) as TransformData;+ const s = Math.sin(a / 2);+ transform.rotation.x = f.axisX * s; transform.rotation.y = 0; transform.rotation.z = f.axisZ * s; transform.rotation.w = Math.cos(a / 2);+ if (t >= 1 && !f.landed) {+ f.landed = true;+ this.emit('landed', f.plant);+ }+ const after = f.elapsed - f.seconds - f.lie;+ if (after > 0) transform.position.y -= dt * (f.plant.scale / SINK_SECONDS);+ world.set(f.root, Transform, transform);+ if (after > SINK_SECONDS) this.endFall(f);+ }+ }++ private endFall(f: Falling): void {+ this.falling_.delete(f);+ const world = this.app_?.world;+ if (world?.valid(f.root)) world.despawn(f.root);+ f.assets?.release();+ f.assets = null;+ }++ private refreshCell(cell: InteractiveCell, kind: number, shownAs: number): void {+ if (shownAs >= 0) this.ensureShown(cell, shownAs);+ this.writeKind(cell, kind);+ if (shownAs >= 0) this.writeKind(cell, shownAs);+ }++ /** The sets that show plants as another kind than they were grown, made the first time one is wanted in a cell. */+ private ensureShown(cell: InteractiveCell, kind: number): void {+ if (cell.shown.has(kind) || kind >= cell.kinds.length) return;+ cell.shown.add(kind);+ this.growth().placeTurned(this.app_!, cell.grown, cell.kinds, cell.ready, kind);+ }++ /** The far cells of a source, which show every plant of theirs that has not gone. */+ private writeFar(source: string): void {+ for (const cell of this.cells_.values()) if (cell.source === source && cell.plants.size === 0) this.writeCell(cell);+ }++ private writeCell(cell: InteractiveCell): void {+ for (const set of cell.grown.sets ?? []) this.growth().writeSet(this.app_!, cell.grown, set);+ }++ private writeKind(cell: InteractiveCell, kind: number): void {+ for (const set of cell.grown.sets ?? []) if (set.kind === kind) this.growth().writeSet(this.app_!, cell.grown, set);+ }++ private growth(): PlantGrowth { return plantGrowthOf(this.app_!); }++ private cellAt(cell: InteractiveCell): { x: number; y: number; z: number } | null {+ if (cell.at) return cell.at;+ const world = this.app_!.world, e = cell.grown.entity;+ if (e === null || !world.valid(e)) return null;+ // Parented on publishing, so its place in the world is settled only after that.+ world.ensureTransformsComposed();+ const t = world.tryGet(e, Transform) as TransformData | null;+ if (!t) return null;+ cell.at = { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z };+ return cell.at;+ }++ /** The kind a plant shows now, or -1 where nothing is there. */+ private kindNow(cell: InteractiveCell, key: string, entry: CellPlant): number {+ const c = this.changes_.get(stateId(cell.source, key));+ return !c || c.state === 'standing' ? entry.kind : c.shownAs;+ }++ private resolveKind(kind: number | string | undefined): number {+ return typeof kind === 'number' ? kind : -1;+ }++ private located(plant: PlantRef): { cell: InteractiveCell; entry: CellPlant; kind: number } | null {+ for (const cell of this.cells_.values()) {+ if (cell.source !== plant.source) continue;+ const entry = cell.plants.get(plant.key);+ if (entry) return { cell, entry, kind: entry.kind };+ }+ return null;+ }++ private changeFor(cell: InteractiveCell, key: string, kind: number): PlantChange {+ const id = stateId(cell.source, key);+ let c = this.changes_.get(id);+ if (!c) {+ const interaction = cell.kinds[kind]?.interaction;+ c = { state: 'standing', shownAs: kind, health: interaction?.health ?? 0, yields: interaction?.yields ?? 0, regrowAt: 0 };+ this.changes_.set(id, c);+ }+ return c;+ }++ private refOf(cell: InteractiveCell, key: string, entry: CellPlant): PlantRef {+ const at = this.cellAt(cell);+ const c = this.changes_.get(stateId(cell.source, key));+ const interaction = cell.kinds[entry.kind]?.interaction;+ return {+ source: cell.source, key, kind: c && c.state !== 'standing' ? c.shownAs : entry.kind,+ x: (at?.x ?? 0) + entry.plant.x, y: (at?.y ?? 0) + entry.plant.y, z: (at?.z ?? 0) + entry.plant.z, scale: entry.plant.scale,+ state: c?.state ?? 'standing', health: c ? c.health : interaction?.health ?? 0, yields: c ? c.yields : interaction?.yields ?? 0,+ entity: this.active_.get(stateId(cell.source, key))?.proxy ?? null,+ };+ }++ private emit(type: PlantEvent['type'], plant: PlantRef): void {+ for (const listener of this.listeners_) {+ try { listener({ type, plant }); } catch (error) { log.error('foliage', `a plant ${type} listener failed`, error); }+ }+ }+}++/** The resource plants are touched through. @experimental */+export const PlantInteractionRes = defineResource<PlantInteraction>(new PlantInteraction(), 'PlantInteraction');++/** The App's plant interaction, installed (with its system) the first time a kind wants it. */+export function plantInteractionOf(app: App): PlantInteraction {+ if (!app.hasResource(PlantInteractionRes)) {+ const interaction = new PlantInteraction();+ interaction.app_ = app;+ app.insertResource(PlantInteractionRes, interaction);+ plantGrowthOf(app).observer_ = interaction;+ app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time)], (time: TimeData) => { interaction.step(time.delta); }, { name: 'PlantInteractionSystem' }));+ }+ return app.getResource(PlantInteractionRes);+}diff --git a/sdk/src/foliage/plantKind.ts b/sdk/src/foliage/plantKind.tsindex 45bb4666f..75946608b 100644--- a/sdk/src/foliage/plantKind.ts+++ b/sdk/src/foliage/plantKind.ts@@ -28,6 +28,37 @@ export interface PlacedPart {castShadows?: boolean;}+/**+ * What a kind of plant does when something comes near. Every length but `activationDistance` is in the plant's own units, multiplied by its scale.+ *+ * @experimental+ */+export interface PlantInteractionDef {+ /** How near a `FoliageContact` a plant becomes an entity, in world units. 0 keeps it data, which also leaves it untouchable. */+ activationDistance?: number;+ /** The capsule that stands for it to physics, while it is near: its radius and height. Either 0 has none. */+ radius?: number;+ height?: number;+ /** How far it leans from what touches it, in radians. 0 stands firm. */+ bend?: number;+ /** What `damage` must take to fell it. 0 cannot be felled that way. */+ health?: number;+ /** Seconds it takes to come down. 0 is gone at once. Default 1.8. */+ fallSeconds?: number;+ /** How far it comes down, in degrees. Default 85: a crown takes the ground before a trunk does. */+ fallAngle?: number;+ /** Seconds it lies before it sinks away. Default 30. */+ lieSeconds?: number;+ /** The kind it leaves when felled, a stump: an index into the kinds, or a plant's name in `WorldRules.plants`. Absent leaves nothing. */+ felledKind?: number | string;+ /** How many times `harvest` can take from it. 0 cannot be harvested. */+ yields?: number;+ /** The kind it becomes with nothing left to take, a bare bush. Absent leaves nothing. */+ harvestedKind?: number | string;+ /** Seconds after felling or the last harvest before it stands again, grown back. 0 is never. */+ regrowSeconds?: number;+}+/** A kind of plant: its parts, and how far it is drawn. */export interface PlacedKind {parts: PlacedPart[];@@ -52,6 +83,8 @@ export interface PlacedKind {* cheaper mesh as its far version, thinned.*/farKeep?: number;+ /** What it does when something comes near. Absent, it is only ever drawn. */+ interaction?: PlantInteractionDef;}/**diff --git a/sdk/src/worldgen/plants.ts b/sdk/src/worldgen/plants.tsindex 50a84ae6a..669c5c684 100644--- a/sdk/src/worldgen/plants.ts+++ b/sdk/src/worldgen/plants.ts@@ -34,12 +34,17 @@ export function expandPlants(plants: Readonly<Record<string, PlantKind>>): Plantconst first = kinds.length;for (const t of tints) {const tint = (part: PlacedKind['parts'][number]): PlacedKind['parts'][number] => ({ ...part, tint: [part.tint[0] * t[0], part.tint[1] * t[1], part.tint[2] * t[2], part.tint[3]] });- kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, ...(p.lod2Distance === undefined ? {} : { lod2Distance: p.lod2Distance }), drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance, ...(p.farKeep === undefined ? {} : { farKeep: p.farKeep }) });+ kinds.push({ parts: p.parts.map(tint), lodDistance: p.lodDistance, ...(p.lod2Distance === undefined ? {} : { lod2Distance: p.lod2Distance }), drawDistance: p.drawDistance, far: p.far.map(tint), farDistance: p.farDistance, ...(p.farKeep === undefined ? {} : { farKeep: p.farKeep }), ...(p.interaction ? { interaction: p.interaction } : {}) });}slots.set(name, { first, count: tints.length, scale: p.tintScale ?? 1300, seed: hashString(name), sink: p.sink ?? 0, unit: p.unit ?? 1 });reach = Math.max(reach, p.drawDistance, p.far.length > 0 ? p.farDistance : 0);if (p.far.length > 0 && p.farDistance > p.drawDistance) span = span > 0 ? Math.min(span, p.farDistance - p.drawDistance) : p.farDistance - p.drawDistance;}+ // A kind a plant turns into is named in the rules, and is a place in the list only now it has been made.+ const indexOf = (kind: number | string | undefined): number | string | undefined => (typeof kind === 'string' ? slots.get(kind)?.first : kind);+ for (const k of kinds) {+ if (k.interaction) k.interaction = { ...k.interaction, felledKind: indexOf(k.interaction.felledKind), harvestedKind: indexOf(k.interaction.harvestedKind) };+ }return {kinds, reach, span,kindAt(name, x, z) {diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex d38f784a4..ec1044c6f 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -34,6 +34,7 @@ import { flattenModifier } from '../terrain/source';import { buildBillboardMesh, buildInstancedMesh, type Plant } from '../foliage/builder';import { chunksOf, ProceduralChunksRes, streamingSourcesOf, type ChunkLayerStatus, type ChunkSource } from '../residency/chunks';import { plantGrowthOf, prepareKinds, type GrownCell, type ReadyKinds } from '../foliage/plantGrowth';+import { plantInteractionOf } from '../foliage/plantInteraction';import { PlanetRegistryRes, type PlanetFacts } from '../terrain/planetQuery';import { faceOf } from '../terrain/sphere';import { Environment } from './fields';@@ -864,7 +865,7 @@ export class WorldGenPlugin implements Plugin {if (k < 0) continue;let list = by.get(k);if (!list) by.set(k, list = []);- list.push({ x: p.x - out.at[0], y: p.y - out.at[1] - plants.sinkOf(p.plant), z: p.z - out.at[2], yaw: p.yaw, scale: p.scale * plants.unitOf(p.plant), phase: 0, shade: 1,+ list.push({ ...(plants.kinds[k]?.interaction ? { key: p.id } : {}), x: p.x - out.at[0], y: p.y - out.at[1] - plants.sinkOf(p.plant), z: p.z - out.at[2], yaw: p.yaw, scale: p.scale * plants.unitOf(p.plant), phase: 0, shade: 1,...(leanOf(p) ? { up: leanOf(p)! } : {}) });}if (by.size > 0) out.planted = by;@@ -928,8 +929,15 @@ export class WorldGenPlugin implements Plugin {chunk.entities.push(e);chunk.grown = { entity: e, handles: [], dead: false };const growth = plantGrowthOf(app);+ const interactive = built.plants.kinds.some((k) => k.interaction);+ if (interactive) chunk.grown.sets = [];if (chunk.far) growth.growFar(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted, { x: chunk.at[0], z: chunk.at[2], half: chunk.side / 2 }, chunk.thinnedBy);else growth.growCell(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted);+ if (interactive) {+ const source = `world:${built.data.world}`;+ if (chunk.far) plantInteractionOf(app).addFarCell(chunk.grown, source, built.plants.kinds, built.plantsReady);+ else plantInteractionOf(app).addCell(chunk.grown, source, built.plants.kinds, built.plantsReady, chunk.planted, chunk.side / 2);+ }}for (const d of chunk.decor) {const handle = assets?.createMesh(d.data) ?? 0;diff --git a/sdk/tests/plant-interaction-wasm.test.ts b/sdk/tests/plant-interaction-wasm.test.tsnew file mode 100644index 000000000..f471b5b48--- /dev/null+++ b/sdk/tests/plant-interaction-wasm.test.ts@@ -0,0 +1,626 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The real engine and the real 3D solver under plants that can be touched: a character is stopped by a tree it walks into and not by one that was+ * felled, and what the engine is told to draw is read as it is told.+ */+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { App } from '../src/app/app';+import { MeshRenderer, Transform } from '../src/ecs/component';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Assets } from '../src/asset/AssetPlugin';+import type { Assets as AssetsApi } from '../src/asset/Assets';+import { ownedAssetLease } from '../src/asset/AssetLease';+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';+import { buildPlacements } from '../src/foliage/builder';+import { PlacedFoliage, PlacedFoliagePlugin } from '../src/foliage/placedFoliage';+import { FoliageContact, PlantInteractionRes, PlantProxy, plantInteractionOf, type PlantEvent, type PlantRef } from '../src/foliage/plantInteraction';+import { contactMemory, contactPlaces } from '../src/foliage/foliageContacts';+import type { PlacedKind } from '../src/foliage/plantKind';+import { WorldStreamingSource } from '../src/residency/components';+import { Physics3D, Physics3DPlugin } from '../src/physics3d/Physics3DPlugin';+import { Physics3DRuntime } from '../src/physics3d/physics3dRuntime';+import { CapsuleCollider3D, CharacterController3D, RigidBody3D, BoxCollider3D } from '../src/physics3d/Physics3DComponents';+import { expandPlants } from '../src/worldgen/plants';+import { WorldGen, WorldGenPlugin } from '../src/worldgen/worldgenPlugin';+import type { WorldRules } from '../src/worldgen/rules';+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';+import type { Entity } from '../src/types';+import type { ESEngineModule } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++const part = (mesh: string): PlacedKind['parts'][number] => ({ mesh, lod1Mesh: '', material: '', texture: '', tint: [1, 1, 1, 1], opaque: true });+const TREE: PlacedKind = {+ parts: [part('tree.mesh')], lodDistance: 0, drawDistance: 500, far: [], farDistance: 0,+ interaction: { activationDistance: 10, radius: 0.5, height: 6, health: 3, felledKind: 1, fallSeconds: 1, lieSeconds: 1, regrowSeconds: 0 },+};+const STUMP: PlacedKind = { parts: [part('stump.mesh')], lodDistance: 0, drawDistance: 500, far: [], farDistance: 0 };+const BUSH: PlacedKind = {+ parts: [part('bush.mesh')], lodDistance: 0, drawDistance: 500, far: [], farDistance: 0,+ interaction: { activationDistance: 6, bend: 0.5, yields: 3, harvestedKind: 3, regrowSeconds: 2 },+};+const BARE: PlacedKind = { parts: [part('bare.mesh')], lodDistance: 0, drawDistance: 500, far: [], farDistance: 0 };+const FAR_TREE: PlacedKind = { ...TREE, far: [part('card.mesh')], farDistance: 2000, drawDistance: 40 };++function triangle(): MeshData {+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ ]);+ return {+ channels, vertexStride, vertexCount: 3,+ vertices: new Uint8Array(new Float32Array([0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1]).buffer),+ indices: new Uint32Array([0, 1, 2]), aabbMin: [0, 0, 0], aabbMax: [1, 1, 0],+ };+}++let core: ESEngineModule;+const apps: App[] = [];+afterEach(() => {+ while (apps.length) apps.pop()!.quit?.();+ setEditorMode(false); setPlayMode(false);+ vi.restoreAllMocks();+});++interface Scene {+ app: App; world: App['world'];+ receipts: Set<number>;+ /** The last placements the engine was told for each set, by entity: x of each plant, and the whole floats. */+ drawn: Map<Entity, Float32Array>;+ writes: { n: number };+ /** The plants the engine draws of one mesh, all sets together. */+ countOf(mesh: string): number;+ meshHandle(mesh: string): number;+ tick(n?: number): Promise<void>;+ contact(x: number, z: number, fields?: Record<string, unknown>): Entity;+ plants(): ReturnType<typeof plantInteractionOf>;+ field(kinds: PlacedKind[], records: number[], fields?: Record<string, unknown>): Promise<Entity>;+}++async function scene(options: { physics?: boolean; rules?: WorldRules } = {}): Promise<Scene> {+ core.setActiveContext(null);+ const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });+ setPlayMode(true);+ if (options.physics) {+ const module = await loadSideModule<Physics3DWasmModule>('physics3d');+ app.addPlugin(new Physics3DPlugin('', { fixedTimestep: 1 / 60, pixelsPerUnit: 1 }, async () => module));+ await app.getResource(Physics3DRuntime).initPromise;+ }+ let next = 1;+ const handles = new Map<string, number>(), receipts = new Set<number>();+ const acquire = async (type: string, path: string) => {+ const id = next++; receipts.add(id);+ const key = `${type}:${path}`;+ if (!handles.has(key)) handles.set(key, next++);+ return ownedAssetLease(key, 1, type === 'world-rules' ? options.rules : { handle: handles.get(key)! }, () => { receipts.delete(id); });+ };+ app.insertResource(Assets, {+ acquireTyped: acquire, acquireTexture: (path: string) => acquire('texture', path),+ readMeshData: async () => triangle(), createMesh: () => next++, releaseBuiltMesh: () => {},+ onInvalidate: () => () => {}, resolveLoadPath: (p: string) => p,+ } as unknown as AssetsApi);+ const drawn = new Map<Entity, Float32Array>(), writes = { n: 0 };+ // Read as the engine is told it: through the module, whichever way it is called.+ const mod = core as unknown as { HEAPU8: Uint8Array; meshInstances_set: (registry: unknown, entity: number, ptr: number, count: number) => void };+ const real = mod.meshInstances_set.bind(mod);+ vi.spyOn(mod, 'meshInstances_set').mockImplementation((registry, entity, ptr, count) => {+ writes.n++;+ drawn.set(entity as Entity, count > 0 ? new Float32Array(mod.HEAPU8.buffer, ptr, count * 16).slice() : new Float32Array(0));+ real(registry, entity, ptr, count);+ });+ const source = app.world.spawn(); app.world.insert(source, Transform, {}); app.world.insert(source, WorldStreamingSource, {});+ app.addPlugin(new PlacedFoliagePlugin());+ const world = app.world;+ const s: Scene = {+ app, world, receipts, drawn, writes,+ meshHandle: (mesh) => handles.get(`mesh:${mesh}`) ?? -1,+ countOf: (mesh) => {+ let n = 0;+ for (const [e, data] of drawn) {+ if (!world.valid(e)) continue;+ const r = world.tryGet(e, MeshRenderer) as { mesh: number } | null;+ if (r?.mesh === handles.get(`mesh:${mesh}`)) n += data.length / 16;+ }+ return n;+ },+ tick: async (n = 1) => { for (let i = 0; i < n; i++) { await app.tick(1 / 60); await Promise.resolve(); } },+ contact: (x, z, fields = {}) => {+ const e = world.spawn();+ world.insert(e, Transform, { position: { x, y: 0, z } });+ world.insert(e, FoliageContact, { radius: 3, ...fields });+ return e;+ },+ plants: () => plantInteractionOf(app),+ field: async (kinds, records, fields = {}) => {+ const e = world.spawn('Wood');+ world.insert(e, Transform, {});+ world.insert(e, PlacedFoliage, { sizeX: 400, sizeZ: 400, cellSize: 50, kinds, records, ...fields });+ await s.tick(30);+ return e;+ },+ };+ return s;+}++const move = (s: Scene, e: Entity, x: number, z: number): void => {+ s.world.update(e, Transform, (t) => { t.position.x = x; t.position.z = z; });+};+const proxies = (s: Scene): Entity[] => [...s.world.getEntitiesWithComponents([PlantProxy])];+const one = (s: Scene, key = '0'): PlantRef => s.plants().find('placed:Wood', key)!;++describe.skipIf(!HAS_WASM)('plants that can be touched', () => {+ beforeAll(async () => { core = await loadWasmModule(); });++ describe('from data to an entity and back', () => {+ it('stays data with nothing near, and is one entity with something near', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1, 0, 100, 0, 0, 0, 1]);+ expect(proxies(s)).toHaveLength(0);+ expect(s.countOf('tree.mesh')).toBe(2);+ const c = s.contact(5, 0);+ await s.tick(10);+ expect(proxies(s)).toHaveLength(1);+ const p = s.world.get(proxies(s)[0]!, PlantProxy);+ expect(p.key).toBe('0');+ // The picture never changes hands, so nothing pops.+ expect(s.countOf('tree.mesh')).toBe(2);+ move(s, c, 100, 100);+ await s.tick(10);+ expect(proxies(s)).toHaveLength(0);+ expect(s.plants().activeCount).toBe(0);+ });++ it('does not flicker at the edge of its reach', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ const heard: PlantEvent[] = [];+ const c = s.contact(9.9, 0);+ await s.tick(1);+ s.plants().on((e) => heard.push(e));+ await s.tick(10);+ const entered = proxies(s).length;+ expect(entered).toBe(1);+ for (let i = 0; i < 10; i++) { move(s, c, i % 2 ? 9.9 : 11, 0); await s.tick(7); }+ expect(heard.filter((e) => e.type === 'deactivated')).toHaveLength(0);+ });++ it('makes only so many a frame, and no more than it holds', async () => {+ const s = await scene();+ const records: number[] = [];+ for (let i = 0; i < 40; i++) records.push(0, i * 0.1, 0, 0, 0, 1);+ await s.field([TREE, STUMP], records);+ s.plants().maxActivatedPerFrame = 8;+ s.plants().maxActive = 20;+ s.contact(2, 0);+ await s.tick(7);+ expect(proxies(s).length).toBeGreaterThan(0);+ expect(proxies(s).length).toBeLessThanOrEqual(8);+ await s.tick(60);+ expect(proxies(s)).toHaveLength(20);+ });++ it('lets go of its entities with its cell', async () => {+ const s = await scene();+ const f = await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ s.contact(1, 0);+ await s.tick(10);+ expect(proxies(s)).toHaveLength(1);+ s.world.despawn(f);+ // Sooner than the next look round for what is near.+ await s.tick(2);+ expect(proxies(s)).toHaveLength(0);+ await s.tick(10);+ expect(s.receipts.size).toBe(0);+ });++ it('does nothing in the editor', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ setEditorMode(true); setPlayMode(false);+ s.contact(1, 0);+ await s.tick(10);+ expect(proxies(s)).toHaveLength(0);+ });++ it('gives no body to a kind with no capsule', async () => {+ const s = await scene({ physics: true });+ await s.field([BUSH], [0, 0, 0, 0, 0, 1]);+ s.contact(1, 0);+ await s.tick(10);+ expect(proxies(s)).toHaveLength(1);+ expect(s.world.has(proxies(s)[0]!, RigidBody3D)).toBe(false);+ });++ it('leaves a kind with no interaction exactly as it was', async () => {+ const s = await scene();+ await s.field([STUMP], [0, 0, 0, 0, 0, 1]);+ s.contact(0.5, 0);+ await s.tick(10);+ expect(s.app.hasResource(PlantInteractionRes)).toBe(false);+ expect(s.countOf('stump.mesh')).toBe(1);+ });+ });++ describe.skipIf(!hasSideModule('physics3d'))('on the real solver', () => {+ const walker = (s: Scene, x: number) => {+ const e = s.world.spawn();+ s.world.insert(e, Transform, { position: { x, y: 1, z: 0 } });+ s.world.insert(e, CharacterController3D, { radius: 0.3, halfHeight: 0.5, velocity: { x: 3, y: 0, z: 0 } });+ s.world.insert(e, FoliageContact, { radius: 1 });+ return e;+ };+ const floor = (s: Scene) => {+ const e = s.world.spawn();+ s.world.insert(e, Transform, { position: { x: 0, y: -1, z: 0 } });+ s.world.insert(e, RigidBody3D, { bodyType: 0 });+ s.world.insert(e, BoxCollider3D, { halfExtents: { x: 100, y: 1, z: 100 } });+ };+ const at = (s: Scene, e: Entity) => s.world.get(e, Transform).position;++ it('gives a near plant a capsule its size, standing on its foot', async () => {+ const s = await scene({ physics: true });+ await s.field([TREE, STUMP], [0, 3, 0, 0, 0, 2]);+ s.contact(4, 0);+ await s.tick(10);+ const [proxy] = proxies(s);+ const c = s.world.get(proxy!, CapsuleCollider3D);+ expect(c.radius).toBeCloseTo(1);+ expect(c.halfHeight).toBeCloseTo(6 - 1);+ expect(c.center!.y).toBeCloseTo(6);+ expect(s.world.get(proxy!, RigidBody3D).bodyType).toBe(0);+ });++ it('stops a character that walks into it, and a ray finds which plant', async () => {+ const s = await scene({ physics: true });+ floor(s);+ await s.field([TREE, STUMP], [0, 8, 0, 0, 0, 1]);+ const w = walker(s, 0);+ await s.tick(240);+ expect(at(s, w).x).toBeGreaterThan(6);+ expect(at(s, w).x).toBeLessThan(7.5);+ const hit = s.app.getResource(Physics3D)!.raycast({ x: 0, y: 2, z: 0 }, { x: 100, y: 0, z: 0 });+ expect(hit).not.toBeNull();+ expect(s.plants().of(hit!.entity as Entity)?.key).toBe('0');+ });++ it('is stopped by a tree that came down across its path, while it lies', async () => {+ const s = await scene({ physics: true });+ floor(s);+ const lying = { ...TREE, interaction: { ...TREE.interaction, lieSeconds: 100 } };+ await s.field([lying, STUMP], [0, 8, 0, -3, 0, 1]);+ const heard: string[] = [];+ s.plants().on((e) => heard.push(e.type));+ s.plants().fell(one(s), { x: 0, z: 1 });+ await s.tick(90);+ expect(heard).toContain('landed');+ const w = walker(s, 0);+ await s.tick(240);+ expect(at(s, w).x).toBeGreaterThan(5);+ expect(at(s, w).x).toBeLessThan(8);+ });++ it('lets it through once the tree is felled and gone', async () => {+ const s = await scene({ physics: true });+ floor(s);+ await s.field([TREE, STUMP], [0, 8, 0, 0, 0, 1]);+ const w = walker(s, 0);+ await s.tick(240);+ const stopped = at(s, w).x;+ s.plants().fell(one(s), { x: 0, z: 1 });+ await s.tick(300);+ expect(at(s, w).x).toBeGreaterThan(stopped + 3);+ });+ });++ describe('felling', () => {+ it('takes health a blow at a time, and comes down away from the last', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ const heard: string[] = [];+ s.plants().on((e) => heard.push(e.type));+ expect(s.plants().damage(one(s), 1)).toBe(true);+ expect(one(s).health).toBe(2);+ s.plants().damage(one(s), 1);+ expect(one(s).health).toBe(1);+ expect(one(s).state).toBe('standing');+ expect(s.countOf('tree.mesh')).toBe(1);+ s.plants().damage(one(s), 5, { x: -3, z: 0 });+ expect(one(s).state).toBe('felled');+ expect(heard).toEqual(['damaged', 'damaged', 'damaged', 'felled']);+ await s.tick(40);+ // Away from the blow: toward +x, so the top of it has gone that way.+ const root = s.world.getEntitiesWithComponents([PlantProxy, Transform]).find((e) => s.world.get(e, PlantProxy).key === '0');+ const r = s.world.get(root!, Transform).rotation;+ const topX = 2 * (r.x * r.y + r.w * r.z);+ expect(-Math.abs(r.z)).toBeLessThan(-0.1);+ expect(topX).toBeLessThan(0);+ });++ it('leaves the placements at once and a stump in its place', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1]);+ s.plants().fell(one(s));+ expect(s.countOf('tree.mesh')).toBe(1);+ expect(s.countOf('stump.mesh')).toBe(1);+ });++ it('comes down, tells when it lands, lies, and goes, giving back what it held', async () => {+ const s = await scene();+ const f = await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ const heard: string[] = [];+ s.plants().on((e) => heard.push(e.type));+ s.plants().fell(one(s), { x: 1, z: 0 });+ const count = () => s.world.getEntitiesWithComponents([PlantProxy]).length;+ expect(count()).toBe(1);+ await s.tick(30);+ expect(heard).not.toContain('landed');+ await s.tick(40);+ expect(heard).toContain('landed');+ s.world.despawn(f);+ await s.tick(30);+ // The field has gone and the tree is still lying: what it draws with is still held.+ expect(s.receipts.size).toBeGreaterThan(0);+ await s.tick(180);+ expect(count()).toBe(0);+ expect(s.receipts.size).toBe(0);+ });++ it('does not fell what is not standing, nor hurt what has no health', async () => {+ const s = await scene();+ await s.field([{ ...TREE, interaction: { ...TREE.interaction, health: 0 } }, STUMP], [0, 0, 0, 0, 0, 1]);+ expect(s.plants().damage(one(s), 1)).toBe(false);+ expect(one(s).state).toBe('standing');+ expect(s.plants().fell(one(s))).toBe(true);+ expect(s.plants().fell(one(s))).toBe(false);+ expect(s.countOf('stump.mesh')).toBe(1);+ });++ it('takes it out of its far version too, and leaves the others', async () => {+ const s = await scene();+ await s.field([FAR_TREE, STUMP], [0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1]);+ expect(s.countOf('card.mesh')).toBe(2);+ s.plants().fell(one(s));+ expect(s.countOf('card.mesh')).toBe(1);+ });+ });++ describe('harvest', () => {+ it('gives what it has, then turns bare, then grows back', async () => {+ const s = await scene();+ await s.field([TREE, STUMP, BUSH, BARE], [2, 0, 0, 0, 0, 1]);+ const heard: string[] = [];+ s.plants().on((e) => heard.push(e.type));+ expect(s.plants().harvest(one(s), 2)).toBe(2);+ expect(one(s).yields).toBe(1);+ expect(s.countOf('bush.mesh')).toBe(1);+ expect(s.plants().harvest(one(s), 5)).toBe(1);+ expect(one(s).state).toBe('harvested');+ expect(s.countOf('bush.mesh')).toBe(0);+ expect(s.countOf('bare.mesh')).toBe(1);+ expect(s.plants().harvest(one(s), 1)).toBe(0);+ await s.tick(130);+ expect(heard).toContain('regrown');+ expect(one(s).state).toBe('standing');+ expect(one(s).yields).toBe(3);+ expect(s.countOf('bush.mesh')).toBe(1);+ expect(s.countOf('bare.mesh')).toBe(0);+ });++ it('grows back from small, and ends at its own size', async () => {+ const s = await scene();+ const e = await s.field([TREE, STUMP, BUSH, BARE], [2, 0, 0, 0, 0, 2]);+ void e;+ s.plants().harvest(one(s), 3);+ await s.tick(125);+ const scales = (): number[] => [...s.drawn.values()].filter((d) => d.length === 16).map((d) => d[5]!);+ expect(Math.min(...scales())).toBeLessThan(0.6);+ await s.tick(100);+ expect(Math.max(...scales())).toBeCloseTo(2, 3);+ });++ it('cannot be harvested where the kind has nothing to give', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ expect(s.plants().harvest(one(s))).toBe(0);+ });+ });++ describe('what lasts', () => {+ it('keeps a felled tree felled when its cell is let go and grown again', async () => {+ const s = await scene();+ await s.field([{ ...TREE, drawDistance: 60 }, { ...STUMP, drawDistance: 60 }], [0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1], { sizeX: 2000, sizeZ: 2000 });+ s.plants().fell(one(s));+ const source = s.world.getEntitiesWithComponents([WorldStreamingSource])[0]!;+ move(s, source, 900, 900);+ await s.tick(60);+ expect(s.plants().find('placed:Wood', '0')).toBeNull();+ move(s, source, 0, 0);+ await s.tick(60);+ expect(one(s).state).toBe('felled');+ expect(s.countOf('tree.mesh')).toBe(1);+ expect(s.countOf('stump.mesh')).toBe(1);+ });++ it('saves what became of each plant, and a new game reads it back', async () => {+ const first = await scene();+ await first.field([TREE, STUMP, BUSH, BARE], [0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1, 2, 6, 0, 0, 0, 1, 0, 9, 0, 0, 0, 1]);+ await first.tick(300);+ first.plants().fell(one(first, '0'));+ first.plants().damage(one(first, '1'), 1);+ first.plants().harvest(one(first, '2'), 3);+ const saved = JSON.parse(JSON.stringify(first.plants().saveState())) as ReturnType<ReturnType<typeof plantInteractionOf>['saveState']>;+ expect(saved.plants).toHaveLength(3);++ const second = await scene();+ await second.field([TREE, STUMP, BUSH, BARE], [0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1, 2, 6, 0, 0, 0, 1, 0, 9, 0, 0, 0, 1]);+ second.plants().loadState(saved);+ expect(one(second, '0').state).toBe('felled');+ expect(one(second, '1').health).toBe(2);+ expect(one(second, '2').state).toBe('harvested');+ expect(one(second, '3').state).toBe('standing');+ expect(second.countOf('tree.mesh')).toBe(2);+ expect(second.countOf('stump.mesh')).toBe(1);+ expect(second.countOf('bare.mesh')).toBe(1);+ expect(second.countOf('bush.mesh')).toBe(0);+ // The clock came with it: a bush that had two seconds left still has them.+ await second.tick(130);+ expect(one(second, '2').state).toBe('standing');+ });++ it('applies a save before its cells are grown', async () => {+ const first = await scene();+ await first.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ first.plants().fell(one(first));+ const saved = first.plants().saveState();+ const second = await scene();+ second.plants().loadState(saved);+ await second.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ expect(second.countOf('tree.mesh')).toBe(0);+ expect(second.countOf('stump.mesh')).toBe(1);+ });++ it('keeps states of two fields apart by their names', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1], { stateKey: 'north' });+ await s.field([TREE, STUMP], [0, 20, 0, 0, 0, 1], { stateKey: 'south' });+ s.plants().fell(s.plants().find('placed:north', '0')!);+ expect(s.plants().find('placed:south', '0')!.state).toBe('standing');+ });++ it('refuses a save from a version it does not read', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 0, 0, 0, 0, 1]);+ expect(() => s.plants().loadState({ version: 9 } as never)).toThrow(/version 9/);+ });++ it('finds what is near, nearest first, and not what is cut', async () => {+ const s = await scene();+ await s.field([TREE, STUMP], [0, 10, 0, 0, 0, 1, 0, 2, 0, 0, 0, 1, 0, 100, 0, 0, 0, 1]);+ expect(s.plants().near(0, 0, 20).map((p) => p.key)).toEqual(['1', '0']);+ s.plants().remove(one(s, '1'));+ expect(s.plants().near(0, 0, 20).map((p) => p.key)).toEqual(['0']);+ });+ });++ describe('leaning', () => {+ it('leans a shrub away from what touches it, and stands up after, with any material', async () => {+ const s = await scene();+ await s.field([TREE, STUMP, BUSH, BARE], [2, 0, 0, 0, 0, 1]);+ const c = s.contact(-1, 0);+ await s.tick(60);+ const set = [...s.drawn.values()].find((d) => d.length === 16)!;+ const lean = () => [...s.drawn.values()].filter((d) => d.length === 16).map((d) => d[1]!)[0]!;+ expect(set).toBeDefined();+ expect(lean()).toBeGreaterThan(0.05);+ expect(lean()).toBeLessThan(Math.tan(0.5) + 0.01);+ move(s, c, 100, 100);+ await s.tick(60);+ expect(lean()).toBeCloseTo(0, 3);+ });++ it('writes nothing while nothing moves', async () => {+ const s = await scene();+ await s.field([TREE, STUMP, BUSH, BARE], [2, 0, 0, 0, 0, 1]);+ s.contact(-1, 0);+ await s.tick(180);+ const before = s.writes.n;+ await s.tick(30);+ expect(s.writes.n).toBe(before);+ });++ it('shears the placement along its height', () => {+ const [m] = [buildPlacements([{ x: 5, y: 0, z: 0, yaw: 0, scale: 2, phase: 0, shade: 1, shear: [0.25, -0.5] }])];+ // A point at height 1 of the model: 2 up, and over by what the shear says, scaled with it.+ expect(m![1]).toBeCloseTo(0.5);+ expect(m![9]).toBeCloseTo(-1);+ expect(m![5]).toBeCloseTo(2);+ expect(m![3]).toBe(5);+ });+ });++ describe('the contacts grass is told about', () => {+ const contact = (id: number, x: number, z = 0, radius = 10) => ({ id, x, y: 0, z, radius, strength: 1, recovery: 1 });++ it('fills the four places, the rest reaching nowhere', () => {+ const p = contactPlaces([contact(1, 3, 4)], contactMemory(), null, 1 / 60);+ expect(p).toHaveLength(4);+ expect(p[0]).toEqual({ x: 3, y: 0, z: 4, w: 10 });+ expect(p[1]!.w).toBe(0);+ });++ it('takes the contacts nearest what is looked from', () => {+ const p = contactPlaces([contact(1, 100), contact(2, 5), contact(3, 50), contact(4, 200), contact(5, 1)], contactMemory(), { x: 0, z: 0 }, 1 / 60);+ expect(p.map((c) => c.x)).toEqual([1, 5, 50, 100]);+ });++ it('leaves a place behind as it moves on, which closes', () => {+ const memory = contactMemory();+ contactPlaces([contact(1, 0)], memory, null, 0);+ let p = contactPlaces([contact(1, 8)], memory, null, 0);+ expect(p[1]).toEqual({ x: 0, y: 0, z: 0, w: 10 });+ p = contactPlaces([contact(1, 8)], memory, null, 0.5);+ expect(p[1]!.w).toBeCloseTo(5);+ p = contactPlaces([contact(1, 8)], memory, null, 0.6);+ expect(p[1]!.w).toBe(0);+ });++ it('leaves nothing behind while it stands', () => {+ const memory = contactMemory();+ for (let i = 0; i < 10; i++) contactPlaces([contact(1, i * 0.1)], memory, null, 1 / 60);+ expect(memory.trails.size).toBe(0);+ });++ it('keeps a contact above what it left, however many it left', () => {+ const memory = contactMemory();+ for (let i = 0; i < 12; i++) contactPlaces([contact(1, i * 10)], memory, null, 0.01);+ const p = contactPlaces([contact(1, 120)], memory, null, 0.01);+ expect(p[0]!.x).toBe(120);+ expect(p[1]!.x).toBe(110);+ });++ it('reaches nowhere at no strength', () => {+ const p = contactPlaces([{ ...contact(1, 0), strength: 0 }], contactMemory(), null, 0);+ expect(p[0]!.w).toBe(0);+ });+ });++ describe('in a world\'s rules', () => {+ it('grows plants that can be felled, known by their places in the plan', async () => {+ const rules: WorldRules = {+ id: 'test:plants', versions: [1],+ plants: { oak: { ...TREE, interaction: { ...TREE.interaction, felledKind: 'stump' } }, stump: STUMP },+ biomes: [{ id: 'plain', conditions: [], recipes: [{ recipe: 'oak', layer: 'plants', density: 1 }] }],+ recipes: [{ id: 'oak', version: 1, anchor: { id: 'oak', plant: 'oak', footprint: 0.1 } }],+ layers: [{ id: 'plants', spacing: 10, drawDistance: 60, chunkSize: 16 }],+ } as WorldRules;+ const s = await scene({ rules });+ s.app.addPlugin(new WorldGenPlugin());+ const e = s.world.spawn();+ s.world.insert(e, Transform, {});+ s.world.insert(e, WorldGen, { rules: 'forest.esworld', world: 'wood', seed: 3 });+ await s.tick(90);+ const plants = s.plants().near(0, 0, 40);+ expect(plants.length).toBeGreaterThan(0);+ expect(plants[0]!.source).toBe('world:wood');+ const trees = s.countOf('tree.mesh');+ expect(trees).toBeGreaterThan(0);+ expect(s.plants().fell(plants[0]!)).toBe(true);+ expect(s.countOf('tree.mesh')).toBe(trees - 1);+ expect(s.countOf('stump.mesh')).toBe(1);+ // The plan is the same however the world is grown: the same key is the same tree in a save.+ const saved = s.plants().saveState();+ expect(saved.plants[0]!.source).toBe('world:wood');+ expect(saved.plants[0]!.key).toBe(plants[0]!.key);+ });++ it('names the kinds a plant turns into, whatever colours come before them', () => {+ const set = expandPlants({+ oak: { ...TREE, tints: [[1, 1, 1], [1, 0.9, 0.8]], interaction: { ...TREE.interaction, felledKind: 'stump' } },+ stump: { ...STUMP },+ } as never);+ expect(set.kinds).toHaveLength(3);+ expect(set.kinds[0]!.interaction!.felledKind).toBe(2);+ expect(set.kinds[1]!.interaction!.felledKind).toBe(2);+ });+ });+});diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 60f6922d4..330ff3f43 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -124,6 +124,8 @@ 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'],+ 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'],PlacedObject: ['derived', 'a generated world writes it on what it places for the game to interact with; authored, it would name a placement no rule made'],SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex ef886c40e..de6208a18 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -198,6 +198,7 @@ const DISPOSITION = {'ParticleEmitter.collisionMaxDistance': ['no-place', 'query culling threshold relative to the nearest active camera, not an emitter extent'],'CharacterController2D.skinWidth': ['no-place', 'a contact skin held off the collider; drawn, it is that outline\'s own line width'],'CharacterController2D.stepHeight': ['no-place', 'the highest ledge it walks up: a limit on motion, not a volume'],+ 'FoliageContact.radius': ['no-place', 'how far plants lean from it, seen on the plants themselves; a ring drawn for it would sit under the grass'],'CharacterController3D.stepHeight': ['no-place', 'the tallest step it will climb — a limit on motion, not a volume'],'NavVolume.cellSize': ['no-place', 'the voxel the box is diced into; the box is what has a place'],'NavVolume.cellHeight': ['no-place', 'the voxel the box is diced into; the box is what has a place'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a3b4ac4f1..9de11fb61 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4222,6 +4222,8 @@ export const NOTED = {{"note": "A 2D character can be rigged in the editor, with no other program."},"feat(physics): a side-on character runs, jumps and forgives, on a mover that handles slopes, ledges and platforms":{"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."},"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":