Skip to content

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

feat(water): a river follows a Spline and runs with a current the surface and the code can both read

yhh137dc57c6a49
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e11bd60ba..cfcec33cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Rivers and splines.** A WaterBody can be a river: put a Spline on its entity and it lays a ribbon along the curve, as wide as the curve says at each point and at its height, with a current (`flowSpeed`, faster where it narrows) that the shader carries the waves and ripples along and that `Waters.sample` reports as `flow`. Splines are a new optional module (`esengine/spline`): a curve through points with a width each, measured by the distance along it.
- **Lake outlines and shores.** A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside.
- **Water bodies.** Water gets a component and a chapter of its own. A WaterBody builds an ocean (without an edge, following the camera, in rings that coarsen with distance) or a rectangular lake, lifts its geometry with the waves, follows its own up when it is tilted, and answers for its surface from code (`Waters.sample`) with the same formula the shader draws. Water is an optional module (`esengine/water`): a 2D game carries none of it.
- **Cyber Rooftop update.** Cyber Rooftop gets a rebuilt rooftop model and textures, a wet roof material with a planar reflection under a rain sky, rain, fog and bloom in the scene, a larger set of HUD icons and inventory art, and a wider build footprint.
diff --git a/desktop b/desktop
index c4fa33320..f1447f30b 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c4fa33320633711dc5c740ff3689da72a97ed54d
+Subproject commit f1447f30bd1debe8d4d077d6e7d87350140180a8
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index cf025eb59..410d1b46f 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -17,7 +17,8 @@ changes.
| Field | What it does |
|---|---|
-| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`. |
+| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`. **River**: follows the `Spline` on the same entity. |
+| `flowSpeed` | A river's current, in world units a second where it is as wide as its widest. |
| `boundary` | A lake's outline: three points or more round it on its own xz plane. Empty is the rectangle. |
| `shoreWidth` | How far in from the edge, and how deep, the waves take to come to full height. 0 leaves them whole to the edge. |
| `material` | A material on the Water shader. Empty uses the stock water. |
@@ -59,6 +60,37 @@ With a `Terrain` in the scene and the lake level, the ground under it is the ter
cross it (the depth test does that), and the waves die out as it shallows. The field is rebuilt when the terrain changes or the lake moves; a tilted
lake, or one over no terrain, is as deep as it likes. The outline should not cross itself.
+## Rivers
+
+A river is a ribbon laid along the `Spline` on its own entity ([Splines](#splines)): a row of vertices across the water every `cellSize` along the curve,
+as wide as the curve says there, at the height of the curve under it, so a river runs downhill. Put a `Spline` and a `WaterBody` with `form` River on one
+entity and the river is built when the scene runs.
+
+- **The current.** `flowSpeed` is how fast the water runs where the river is as wide as its widest; a narrower reach runs faster and a wider one slower,
+ within a quarter and double of it, as the same water through a different width does. The direction is the curve's.
+- **The surface rides it.** The shader carries the waves and ripples downstream: two copies of the surface are moved along the current a cycle at a time, each
+ fading in as the other fades out, so the moment one is put back at its start is hidden by the other, and the surface does not stretch where the river bends.
+- **Flat geometry.** A river's geometry is not lifted by the waves (its surface is drawn flat and moved only in the shading), so a river has no waves to read
+ back: `Waters.sample` gives its curve's height, a normal of up, and the current in `flow` (world units a second, along the river; zero elsewhere).
+- **Banks.** The edge is the ribbon's own, so it is as crisp as the geometry. Foam where it meets the ground comes from the depth of the scene, as at any shore.
+
+## Splines
+
+`Spline` is data and nothing draws it: `points` (each an `x`, `y`, `z` in the entity's own space and a `width`) and `closed`. A river reads the one on its
+entity; anything else that follows a path can read it with `SplineCurve`:
+
+```ts
+const curve = new SplineCurve(spline.points, spline.closed);
+curve.position(s); // the point a distance s along it
+curve.tangent(s); // the direction of travel there
+curve.width(s); // the width there, eased from one point's to the next's
+curve.nearest(x, z); // the nearest place on it in the xz plane: s, how far, which side
+```
+
+It is a centripetal Catmull-Rom curve (it passes through every point, and does not loop or cusp where they are close at one end and far at the other)
+measured by distance along it, so a place on it is `s` units from its start and not a parameter that runs fast where the points are close. Past either
+end of an open curve it is the end; a closed curve goes round. Splines are an optional module (`esengine/spline`).
+
## Asking the surface
`Waters.sample(x, y, z)` (the `WatersRes` resource) answers for the body that holds a point:
@@ -66,7 +98,8 @@ lake, or one over no terrain, is as deep as it likes. The outline should not cro
- `depth`: how far the point is above the surface along the body's up (negative under it), in world units;
- `normal`: the surface's normal there, in world space;
- `surface`: the world position on the surface straight above or below the point;
-- `inside`: whether the point is over the body's extent: inside a lake's outline (an ocean has none, so it is always).
+- `inside`: whether the point is over the body's extent: inside a lake's outline or a river's banks (an ocean has none, so it is always);
+- `flow`: how the water moves there, in world units a second (a river's current; still water is zero).
It reads the same formula the shader draws, at the time of the frame. The body's position, rotation and uniform scale are taken into account.
`Waters.heightAt(x, z)` is the short form for an untilted body. A point over no water answers `null`.
@@ -99,8 +132,8 @@ What is not there yet, so nobody is surprised:
Without the chain the water is drawn over the scene as a translucent surface; without float targets the depth is `u_fallbackDepth` everywhere, so
there is no shore foam and no change of colour with depth.
- Like glass, it refracts the opaque scene only: a boat's hull seen through it is, but another transparent surface is not.
-- Rivers along a curve and flow are not built yet. A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die
- toward the shore without breaking on it.
+- A river does not carve the ground, rapids and falls are not foamed by how fast or steep the water runs, and two bodies do not blend where they meet.
+ A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die toward the shore without breaking on it.
- Nothing floats on it or swims in it yet: `Waters.sample` gives what a buoyancy force needs, but there is no force.
- A camera under the surface sees the water turned over, and nothing else changes: no underwater fog or tint.
- It does not react to what moves through it: no ripples, no wake.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
index c3cc642bc..e0042ac5e 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -13,7 +13,8 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
| 字段 | 作用 |
|---|---|
-| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓。 |
+| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓。**河流**:沿同一实体上的 `Spline`。 |
+| `flowSpeed` | 河流的流速,世界单位每秒,指河面最宽处的流速。 |
| `boundary` | 湖泊的轮廓:它自己的 xz 平面上围一圈的三个或更多点。留空就是矩形。 |
| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度。0 表示波浪一直完整到岸边。 |
| `material` | 使用 Water 着色器的材质。留空用内置的水。 |
@@ -41,6 +42,29 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
场景里有 `Terrain` 且湖面水平时,它下面的地面就是地形:水填满低处,在山丘与它相交的地方被山丘截断(深度测试做到这一点),波浪随变浅而消失。地形一变或湖面一动,这张场就会重建;倾斜的湖,或没有地形的湖,要多深有多深。轮廓不应自相交。
+## 河流
+
+河流是沿着它自己实体上的 `Spline`([样条](#样条))铺开的一条带子:沿曲线每隔 `cellSize` 一排横跨水面的顶点,宽度取曲线在那里的宽度,高度取曲线在它下面的高度,所以河流是顺着坡往下流的。在同一个实体上放一个 `Spline` 和一个 `form` 为 River 的 `WaterBody`,场景运行时河流就建出来了。
+
+- **水流。** `flowSpeed` 是河面最宽处的流速;窄的河段更快、宽的河段更慢,范围在它的四分之一到两倍之间,和同样的水流过不同宽度时的情形一致。方向就是曲线的方向。
+- **表面随水流动。** 着色器把波浪和涟漪顺流带走:表面的两份拷贝每次沿水流前进一个周期,一份淡入的同时另一份淡出,所以其中一份被放回起点的那一刻被另一份遮住,河道拐弯处表面也不会被拉长。
+- **几何体是平的。** 河流的几何体不被波浪抬起(表面画成平的,只在着色里流动),所以河流没有可读回的波浪:`Waters.sample` 给出它的曲线高度、向上的法线,以及 `flow` 里的水流(世界单位每秒,沿河道方向;别处为零)。
+- **河岸。** 边缘就是这条带子自己的边,和几何体一样清晰。它和地面相接处的泡沫来自场景深度,和任何岸边一样。
+
+## 样条
+
+`Spline` 是数据,什么也不画:`points`(每个点是实体自身空间里的 `x`、`y`、`z` 和一个 `width`)和 `closed`。河流读取它实体上的那一个;任何沿路径走的东西都可以用 `SplineCurve` 读它:
+
+```ts
+const curve = new SplineCurve(spline.points, spline.closed);
+curve.position(s); // 沿曲线走过 s 距离的那个点
+curve.tangent(s); // 那里的前进方向
+curve.width(s); // 那里的宽度,从一个点的宽度平滑过渡到下一个点的
+curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在哪一侧
+```
+
+它是向心 Catmull-Rom 曲线(穿过每一个点,点在一头密、另一头疏时也不会打圈或出尖),按沿曲线的距离来度量,所以曲线上的位置是离起点 `s` 个单位,而不是在点靠得近的地方跑得很快的参数。开放曲线越过两端就停在端点;闭合曲线会绕回去。样条是一个可选模块(`esengine/spline`)。
+
## 查询表面
`Waters.sample(x, y, z)`(资源 `WatersRes`)为包含这个点的水体作答:
@@ -48,7 +72,8 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- `depth`:这个点沿水体上方向高出表面多少(在下面则为负),世界单位;
- `normal`:表面在那里的法线,世界空间;
- `surface`:这个点正上方或正下方、表面上的世界坐标;
-- `inside`:这个点是否在水体范围之上:在湖泊轮廓之内(海洋没有轮廓,所以总是)。
+- `inside`:这个点是否在水体范围之上:在湖泊轮廓之内或河岸之间(海洋没有轮廓,所以总是);
+- `flow`:水在那里怎么流动,世界单位每秒(河流的水流;静水为零)。
它读的是着色器画的同一个公式,取这一帧的时间。水体的位置、旋转和均匀缩放都被考虑进去。`Waters.heightAt(x, z)` 是未倾斜水体的简写。点上方没有水则返回 `null`。
@@ -69,7 +94,7 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
-- 沿曲线的河流和水流还没有做。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
+- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫,两个水体相接处也不会融合。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
- 还没有东西能漂在上面或在里面游:`Waters.sample` 给出了浮力需要的量,但还没有这个力。
- 相机在水面以下时,看到的是翻过来的水,别的没有变化:没有水下的雾和染色。
- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index a8345c86b..e149f879b 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": 171,
- "experimental": 2359,
+ "experimental": 2368,
"deprecated": 3
},
- "total": 2645,
+ "total": 2654,
"subsystems": [
{
"id": "mobile-controls",
@@ -381,6 +381,18 @@
"Foliage"
]
},
+ {
+ "id": "spline",
+ "title": "Splines",
+ "titleZh": "样条",
+ "tier": "experimental",
+ "why": "the curve and its measuring by distance are checked, but the only thing that follows one so far is a river, and the editor has no tool to draw it",
+ "whyZh": "曲线和按距离度量已经有检查,但目前只有河流会沿着它走,编辑器里也还没有绘制它的工具",
+ "entry": [
+ "Spline",
+ "SplineCurve"
+ ]
+ },
{
"id": "water",
"title": "Water",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 3a8f78d03..91c562743 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -89,6 +89,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
StaticBatch: { category: 'graphics', summary: 'Marks a mesh that will not move, so the meshes sharing its material are merged into one draw while the game runs; it also records what became of this one.', doc: 'performance/static-batching', anchor: 'what-happens', anchorZh: '会发生什么' },
Terrain: { category: 'graphics', summary: 'Ground made from a heightmap or noise, painted by height and slope, and drawn in chunks that coarsen with distance.', doc: 'graphics/terrain', anchor: 'the-component', anchorZh: '组件' },
Foliage: { category: 'graphics', summary: 'Scatters grass or a mesh across an area and over a terrain, drawn a cell at a time, swaying in the wind and thinning out with distance.', doc: 'graphics/foliage', anchor: 'the-component', anchorZh: '组件' },
+ Spline: { category: 'graphics', summary: 'A curve through points, each with a width, read by what follows it (a river\'s WaterBody on the same entity); measured by the distance along it.', doc: 'graphics/water', anchor: 'splines', anchorZh: '样条' },
WaterBody: { category: 'graphics', summary: 'An ocean or a lake: geometry lifted by waves the code can read back, tilting with the entity, drawn by the Water shader.', doc: 'graphics/water', anchor: 'the-component', anchorZh: '组件' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
ReflectionProbe: { category: 'graphics', summary: 'A box inside which reflections come from a bake rather than from the sky — the specular half of what a light probe volume answers.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 2f0a07a5a..edde48c74 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -4646,6 +4646,24 @@
}
]
},
+ {
+ "name": "Spline",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "points",
+ "type": "object[]",
+ "default": "[{\"x\":-10,\"y\":0,\"z\":0,\"width\":4},{\"x\":10,\"y\":0,\"z\":0,\"width\":4}]",
+ "doc": "The points the curve passes through, in order, in the entity's own space. Each carries the width of whatever follows the curve there."
+ },
+ {
+ "key": "closed",
+ "type": "boolean",
+ "default": "false",
+ "doc": "Join the end of the curve to its start (three points or more)."
+ }
+ ]
+ },
{
"name": "Sprite",
"source": "cpp",
@@ -7037,10 +7055,11 @@
"key": "form",
"type": "enum",
"default": "Lake",
- "doc": "An ocean is without edge and follows the camera; a lake is a rectangle of its own size.",
+ "doc": "An ocean is without edge and follows the camera; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.",
"values": [
"Ocean",
- "Lake"
+ "Lake",
+ "River"
]
},
{
@@ -7097,6 +7116,13 @@
"doc": "Rings of an ocean, each twice as coarse as the one inside it.",
"range": "1–8, step 1"
},
+ {
+ "key": "flowSpeed",
+ "type": "number",
+ "default": "2",
+ "doc": "A river's current, in world units a second where it is as wide as its widest. A narrower reach runs faster.",
+ "range": "0–50"
+ },
{
"key": "waveHeight",
"type": "number",
@@ -7135,6 +7161,7 @@
"cellSize",
"cells",
"rings",
+ "flowSpeed",
"waveHeight",
"waveLength",
"waveSpeed",
diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.ts
index a51e6d31f..50a4688d5 100644
--- a/pipeline/src/bundle/engineSubpaths.ts
+++ b/pipeline/src/bundle/engineSubpaths.ts
@@ -19,6 +19,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
'esengine/fx-lighting': 'fx-lighting/index.js',
'esengine/foliage': 'foliage/index.js',
'esengine/water': 'water/index.js',
+ 'esengine/spline': 'spline/index.js',
'esengine/logic': 'logic/index.js',
'esengine/debug-channel': 'debug-channel/index.js',
'esengine/ai': 'ai/index.js',
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index 2dd44bc08..6eea2529c 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -27,7 +27,7 @@ import { NATIVE_PLATFORMS, type ExportPlatform } from './platforms';
/** An engine subsystem a build target may lack. */
export type Subsystem =
- | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'water' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'
+ | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'water' | 'spline' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'
| 'spine' | 'dragonbones' | 'video' | 'ai' | 'logic' | 'replication' | 'gameplay';
/**
@@ -47,6 +47,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
fxLighting: [],
foliage: ['Foliage'],
water: ['WaterBody'],
+ spline: ['Spline'],
particles: ['ParticleEmitter', 'ParticleForceField'],
postprocess: ['PostProcessVolume'],
physics: [
@@ -99,6 +100,7 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {
fxLighting: 'Post-process effects (occlusion, reflections, exposure)',
foliage: 'Foliage',
water: 'Water',
+ spline: 'Splines',
particles: 'Particles',
postprocess: 'Post-processing',
physics: 'Physics (Box2D)',
@@ -130,6 +132,7 @@ export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {
fxLighting: 'esengine/fx-lighting',
foliage: 'esengine/foliage',
water: 'esengine/water',
+ spline: 'esengine/spline',
physics: 'esengine/physics',
physics3d: 'esengine/physics3d',
spine: 'esengine/spine',
diff --git a/pipeline/tests/engine-installs.test.ts b/pipeline/tests/engine-installs.test.ts
index b54b59350..0c0b9b27c 100644
--- a/pipeline/tests/engine-installs.test.ts
+++ b/pipeline/tests/engine-installs.test.ts
@@ -29,6 +29,10 @@ describe('the engine modules a package installs', () => {
expect(engineInstalls({ subsystems: ['water'] }).subpaths).toEqual(['esengine/water']);
});
+ it('takes splines from a Spline, so a game without one carries none', () => {
+ expect(engineInstalls({ subsystems: ['spline'] }).subpaths).toEqual(['esengine/spline']);
+ });
+
it('takes the effect groups a post-process volume names, and none for a volume with no effects', async () => {
const { collectSubsystems } = await import('../src/project/targetSupport');
const volume = (types: string[]) => ({ entities: [{ components: [{ type: 'PostProcessVolume', data: { effects: types.map((type) => ({ type })) } }] }] });
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c168ea5c7..f26843ea1 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1731 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1740 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -8831,6 +8831,53 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
## Sprite — const @public
```
BuiltinComponentDef<SpriteData>
@@ -11129,6 +11176,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -11159,6 +11207,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -11964,6 +12013,11 @@ MotionDriver<AnimatorBlend2DMotion>
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12414,6 +12468,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -14659,6 +14718,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
## spriteMotionDriver — const @experimental
```
MotionDriver<AnimatorClipMotion>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6e3ef88ef..f48a444c7 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 164 beta · 1750 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1759 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -9044,6 +9044,53 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
## Sprite — const @public
```
BuiltinComponentDef<SpriteData>
@@ -11342,6 +11389,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -11372,6 +11420,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -12192,6 +12241,11 @@ MotionDriver<AnimatorBlend2DMotion>
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12667,6 +12721,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -14922,6 +14981,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
## spriteMotionDriver — const @experimental
```
MotionDriver<AnimatorClipMotion>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d08161ec1..891c4295b 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 161 beta · 1730 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1739 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8826,6 +8826,53 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
## Sprite — const @public
```
BuiltinComponentDef<SpriteData>
@@ -11124,6 +11171,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -11154,6 +11202,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -11959,6 +12008,11 @@ MotionDriver<AnimatorBlend2DMotion>
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12409,6 +12463,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -14664,6 +14723,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
## spriteMotionDriver — const @experimental
```
MotionDriver<AnimatorClipMotion>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 8079df4ea..3ec71f5ea 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1752 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1761 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -9119,6 +9119,53 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
## Sprite — const @public
```
BuiltinComponentDef<SpriteData>
@@ -11423,6 +11470,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -11453,6 +11501,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -12258,6 +12307,11 @@ MotionDriver<AnimatorBlend2DMotion>
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12713,6 +12767,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -14968,6 +15027,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
## spriteMotionDriver — const @experimental
```
MotionDriver<AnimatorClipMotion>
diff --git a/sdk/etc/spline.api.md b/sdk/etc/spline.api.md
new file mode 100644
index 000000000..8ffeb6978
--- /dev/null
+++ b/sdk/etc/spline.api.md
@@ -0,0 +1,57 @@
+# API surface — esengine/spline
+
+<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
+Symbols: 0 public · 0 beta · 7 experimental · 0 deprecated
+
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index 86c11b255..8ebd9c51f 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/water
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 25 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 27 experimental · 0 deprecated
## GroundDepth — type @experimental
```
@@ -59,6 +59,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -89,6 +90,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -132,6 +134,16 @@ speed: number
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## oceanReach — function @experimental
```
(cells: number, rings: number, cellSize: number): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 4398cc1da..d660207be 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 115 public · 159 beta · 1743 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1752 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8833,6 +8833,53 @@ type: "spine"
'2.1' | '3.8' | '4.1' | '4.2' | '4.3'
```
+## Spline — const @experimental
+```
+ComponentDef<SplineData>
+```
+
+## SplineCurve — class @experimental
+```
+closed: boolean
+count: number
+length: number
+nearest: (x: number, z: number) => SplineNearest
+position: (s: number) => [number, number, number]
+tangent: (s: number) => [number, number, number]
+width: (s: number) => number
+static new (points: readonly SplinePoint[], closed?: boolean): SplineCurve
+static prototype: SplineCurve
+```
+
+## SplineData — interface @experimental
+```
+closed: boolean
+points: SplinePoint[]
+```
+
+## SplineNearest — interface @experimental
+```
+distance: number
+s: number
+side: number
+```
+
+## SplinePlugin — class @experimental
+```
+build: (_app: App) => void
+name: string
+static new (): SplinePlugin
+static prototype: SplinePlugin
+```
+
+## SplinePoint — interface @experimental
+```
+width: number
+x: number
+y: number
+z: number
+```
+
## Sprite — const @public
```
BuiltinComponentDef<SpriteData>
@@ -11131,6 +11178,7 @@ ComponentDef<WaterBodyData>
boundary: Point2[]
cellSize: number
cells: number
+flowSpeed: number
form: number
material: number
rings: number
@@ -11161,6 +11209,7 @@ static prototype: WaterPlugin
```
depth: number
entity: number
+flow: [number, number, number]
inside: boolean
normal: [number, number, number]
surface: [number, number, number]
@@ -11990,6 +12039,11 @@ MotionDriver<AnimatorBlend2DMotion>
(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
+## buildRiverMesh — function @experimental
+```
+(curve: SplineCurve, step: number, across: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -12440,6 +12494,11 @@ Plugin
(module: ESEngineModule, options?: CreateWebAppOptions): App
```
+## currentShare — function @experimental
+```
+(width: number, widest: number): number
+```
+
## currentTimeOfDay — function @beta
```
(): TimeOfDayState | null
@@ -14695,6 +14754,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## splinePlugin — const @experimental
+```
+Plugin
+```
+
## spriteMotionDriver — const @experimental
```
MotionDriver<AnimatorClipMotion>
diff --git a/sdk/package.json b/sdk/package.json
index bb97220cd..44486d340 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -24,6 +24,7 @@
"./dist/fx-lighting/index.js",
"./dist/foliage/index.js",
"./dist/water/index.js",
+ "./dist/spline/index.js",
"./dist/logic/index.js",
"./dist/debug-channel/index.js",
"./dist/ai/index.js",
@@ -106,6 +107,10 @@
"import": "./dist/water/index.js",
"types": "./dist/water/index.d.ts"
},
+ "./spline": {
+ "import": "./dist/spline/index.js",
+ "types": "./dist/spline/index.d.ts"
+ },
"./logic": {
"import": "./dist/logic/index.js",
"types": "./dist/logic/index.d.ts"
diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.ts
index 93486529c..5eb834963 100644
--- a/sdk/src/app/pluginSets.ts
+++ b/sdk/src/app/pluginSets.ts
@@ -67,7 +67,7 @@ export const presentationBasePlugins = (): Plugin[] => [
*/
export const PLUGIN_BUILD_ORDER: readonly string[] = [
'Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',
- 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', 'water', 'tilemap', 'postProcess', 'timeline',
+ 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', 'spline', 'water', 'tilemap', 'postProcess', 'timeline',
'gameplay',
'perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication',
'services',
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index e607e95de..c2993db9a 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -787,11 +787,14 @@ export {
export {
Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
} from './foliage/foliagePlugin';
-// Water is an optional module too (`esengine/water`).
+// Splines and water are optional modules too (`esengine/spline`, `esengine/water`).
+export { Spline, SplinePlugin, splinePlugin, type SplineData } from './spline/splinePlugin';
+export { SplineCurve, type SplinePoint, type SplineNearest } from './spline/curve';
export {
WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
} from './water/waterPlugin';
export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './water/waves';
+export { buildRiverMesh, currentShare } from './water/riverMesh';
export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './water/waterMesh';
export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './water/shore';
export {
diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.ts
index 17822f492..cc0ff43f7 100644
--- a/sdk/src/platform/nativeModuleRegistry.ts
+++ b/sdk/src/platform/nativeModuleRegistry.ts
@@ -31,6 +31,7 @@ import * as FxAtmosphereModule from '../postprocess/fxAtmosphere';
import * as FxLightingModule from '../postprocess/fxLighting';
import * as FoliageModule from '../foliage';
import * as WaterModule from '../water';
+import * as SplineModule from '../spline';
import * as ScriptGraphModule from '../logic';
import * as AiModule from '../ai';
import * as ReplicationModule from '../net/replication';
@@ -57,6 +58,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {
'esengine/fx-lighting': FxLightingModule,
'esengine/foliage': FoliageModule,
'esengine/water': WaterModule,
+ 'esengine/spline': SplineModule,
'esengine/logic': ScriptGraphModule,
'esengine/ai': AiModule,
'esengine/replication': ReplicationModule,
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 2e3b08e07..d7e505bac 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -739,6 +739,12 @@ const WATER = `#pragma shader "Water"
#pragma param u_shoreOrigin vec2 default(0,0)
#pragma param u_shoreSize vec2 default(1,1)
#pragma param u_shoreRange float default(16) range(0.01,10000) ui(slider)
+// A river's current: how fast it runs (world units a second, 0 for still water) along the direction the mesh's vertex colour gives (red and green) at the speed
+// its blue says (half is the nominal), and how long, in seconds, each of the two copies of the surface the shader carries downstream lives before the other takes over.
+#pragma param u_flowSpeed float default(0) range(0,50) ui(slider)
+#pragma param u_flowCycle float default(2) range(0.2,20) ui(slider)
+// How much of the waves lifts the geometry: 1 for a lake or an ocean, 0 for a river, whose surface is drawn flat and moved only in the shading.
+#pragma param u_geoWaves float default(1) range(0,1) ui(slider)
#pragma param u_sceneColor texture default(white)
#pragma param u_sceneDepthMap texture default(white) texel(data)
@@ -764,7 +770,7 @@ void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
if (u_waveSpace < 0.5) return;
float cell = u_cellSize > 0.0 ? u_cellSize * exp2(es_vertexColor.r * 7.0) : 0.0;
float damp = u_shoreOn > 0.5 ? es_vertexColor.g : 1.0;
- local.y += waterWaveHeight(uv + u_origin, u_time.x, cell) * damp;
+ local.y += waterWaveHeight(uv + u_origin, u_time.x, cell) * damp * u_geoWaves;
}
#pragma end
@@ -792,7 +798,7 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, ve
if (mc.u_cellSize > 0.0) { cell = mc.u_cellSize * exp2(es_vertexColor.r * 7.0); }
var damp = 1.0;
if (mc.u_shoreOn > 0.5) { damp = es_vertexColor.g; }
- (*local).y = (*local).y + waterWaveHeight(uv + mc.u_origin, tc.u_time.x, cell) * damp;
+ (*local).y = (*local).y + waterWaveHeight(uv + mc.u_origin, tc.u_time.x, cell) * damp * mc.u_geoWaves;
}
#pragma end
@@ -865,6 +871,16 @@ vec2 waveSlope(vec2 p, float time, float dist, out float crest) {
return slope;
}
+/// The slope of the surface at p and how near it is to a crest: the waves, and the ripples they carry, flattened with distance.
+vec2 waterSurface(vec2 p, float time, float dist, out float crest) {
+ vec2 slope = waveSlope(p, time, dist, crest);
+ float rippleFade = clamp(1.0 - dist / (u_rippleLength * 180.0), 0.0, 1.0);
+ float e = u_rippleLength * 0.1;
+ vec2 ripple = vec2(ripples(p + vec2(e, 0.0), time) - ripples(p - vec2(e, 0.0), time),
+ ripples(p + vec2(0.0, e), time) - ripples(p - vec2(0.0, e), time)) / (2.0 * e);
+ return slope + ripple * (u_rippleStrength * u_rippleLength * rippleFade);
+}
+
void main() {
#ifdef MESH_NORMALS
highp vec3 P = v_worldXYZ;
@@ -883,13 +899,25 @@ void main() {
float shoreDepth = shoreTex.g * u_shoreRange;
float damp = u_shoreOn > 0.5 ? shoreTex.b : 1.0;
float crest;
- vec2 slope = waveSlope(wp, time, waterDist, crest) * damp;
+ vec2 slope;
+ if (u_flowSpeed > 0.0) {
+ // A river: the surface rides the current. Two copies of it are carried downstream a cycle at a time, each fading in as the other fades
+ // out, so the moment one is put back at its start is hidden by the other.
+ vec2 flow = (v_color.rg * 2.0 - 1.0) * (v_color.b * 2.0) * u_flowSpeed;
+ float cycle = max(u_flowCycle, 0.1);
+ float ph0 = fract(time / cycle);
+ float ph1 = fract(time / cycle + 0.5);
+ float w0 = 1.0 - abs(2.0 * ph0 - 1.0);
+ float crest0, crest1;
+ vec2 s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, crest0);
+ vec2 s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, crest1);
+ slope = mix(s1, s0, w0);
+ crest = mix(crest1, crest0, w0);
+ } else {
+ slope = waterSurface(wp, time, waterDist, crest);
+ }
+ slope *= damp;
crest *= damp;
- float rippleFade = clamp(1.0 - waterDist / (u_rippleLength * 180.0), 0.0, 1.0);
- float e = u_rippleLength * 0.1;
- vec2 ripple = vec2(ripples(wp + vec2(e, 0.0), time) - ripples(wp - vec2(e, 0.0), time),
- ripples(wp + vec2(0.0, e), time) - ripples(wp - vec2(0.0, e), time)) / (2.0 * e);
- slope += ripple * (u_rippleStrength * u_rippleLength * rippleFade);
vec3 N = normalize(vec3(-slope.x, 1.0, -slope.y));
vec3 Ngeo = vec3(0.0, 1.0, 0.0);
#ifdef MESH_NORMALS
@@ -1025,6 +1053,16 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
return out;
}
+/// The slope of the surface at p (x, y) and how near it is to a crest (z): the waves, and the ripples they carry, flattened with distance.
+fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
+ let waves = waveSlope(p, time, dist);
+ let rippleFade = clamp(1.0 - dist / (mc.u_rippleLength * 180.0), 0.0, 1.0);
+ let eps = mc.u_rippleLength * 0.1;
+ let ripple = vec2f(ripples(p + vec2f(eps, 0.0), time) - ripples(p - vec2f(eps, 0.0), time),
+ ripples(p + vec2f(0.0, eps), time) - ripples(p - vec2f(0.0, eps), time)) / (2.0 * eps);
+ return vec3f(waves.slope + ripple * (mc.u_rippleStrength * mc.u_rippleLength * rippleFade), waves.crest);
+}
+
#ifdef ES_GBUFFER
@fragment fn fs_main(v : VSOut) -> FragOut {
#else
@@ -1051,14 +1089,23 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
let shoreDepth = shoreTex.g * mc.u_shoreRange;
var damp = 1.0;
if (mc.u_shoreOn > 0.5) { damp = shoreTex.b; }
- var waves = waveSlope(wp, time, waterDist);
- waves.crest = waves.crest * damp;
- var slope = waves.slope * damp;
- let rippleFade = clamp(1.0 - waterDist / (mc.u_rippleLength * 180.0), 0.0, 1.0);
- let eps = mc.u_rippleLength * 0.1;
- let ripple = vec2f(ripples(wp + vec2f(eps, 0.0), time) - ripples(wp - vec2f(eps, 0.0), time),
- ripples(wp + vec2f(0.0, eps), time) - ripples(wp - vec2f(0.0, eps), time)) / (2.0 * eps);
- slope = slope + ripple * (mc.u_rippleStrength * mc.u_rippleLength * rippleFade);
+ var surface = vec3f(0.0);
+ if (mc.u_flowSpeed > 0.0) {
+ // A river: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.
+ let flow = (v.v_color.rg * 2.0 - vec2f(1.0)) * (v.v_color.b * 2.0) * mc.u_flowSpeed;
+ let cycle = max(mc.u_flowCycle, 0.1);
+ let ph0 = fract(time / cycle);
+ let ph1 = fract(time / cycle + 0.5);
+ let w0 = 1.0 - abs(2.0 * ph0 - 1.0);
+ let s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist);
+ let s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist);
+ surface = mix(s1, s0, w0);
+ } else {
+ surface = waterSurface(wp, time, waterDist);
+ }
+ var waves : Waves;
+ waves.crest = surface.z * damp;
+ var slope = surface.xy * damp;
var N = normalize(vec3f(-slope.x, 1.0, -slope.y));
var Ngeo = vec3f(0.0, 1.0, 0.0);
#ifdef MESH_NORMALS
diff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.ts
index fd300e6ee..dfd98fcae 100644
--- a/sdk/src/runtime/optionalPlugins.ts
+++ b/sdk/src/runtime/optionalPlugins.ts
@@ -27,6 +27,7 @@ import { registerTimelineSupport } from '../timeline/timelineSupport';
import { registerTerrainSupport } from '../terrain/terrainSupport';
import { registerFoliageSupport } from '../foliage/foliageSupport';
import { registerWaterSupport } from '../water/waterSupport';
+import { registerSplineSupport } from '../spline/splineSupport';
import { registerScriptGraphSupport } from '../logic/logicSupport';
import { registerAiSupport } from '../ai/aiSupport';
import { registerReplicationSupport } from '../net/replication/replicationSupport';
@@ -46,6 +47,7 @@ export function installOptionalPlugins(): void {
registerTerrainSupport();
registerFoliageSupport();
registerWaterSupport();
+ registerSplineSupport();
registerScriptGraphSupport();
registerAiSupport();
registerReplicationSupport();
diff --git a/sdk/src/spline/curve.ts b/sdk/src/spline/curve.ts
new file mode 100644
index 000000000..e08fdba59
--- /dev/null
+++ b/sdk/src/spline/curve.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file curve.ts
+ * @brief A smooth curve through a list of points, measured by the distance along it.
+ *
+ * @details A centripetal Catmull-Rom curve (it passes through every point and does not loop where they are unevenly spaced) cut into short straight pieces, with the length of each summed, so a place on
+ * the curve is a distance `s` from its start and not a parameter that runs fast where the points are close and slow where
+ * they are far. That is what a river's width and speed, a road's banking or a rail's pace are written against. The points are
+ * in the curve's own space; where it is in the world is its entity's Transform.
+ *
+ * Each point carries a width, interpolated along the curve (a river narrows at a rapid, a road widens at a junction).
+ */
+
+/** A point of a curve: where it is, and how wide the thing along it is there. */
+export interface SplinePoint {
+ x: number;
+ y: number;
+ z: number;
+ width: number;
+}
+
+/** Where on a curve a point is nearest, and how far from it. */
+export interface SplineNearest {
+ /** The distance along the curve. */
+ s: number;
+ /** The distance from the query point to the curve. */
+ distance: number;
+ /** Which side of the curve the point is on: the sign of the xz cross product of the curve's heading and the offset to the point. */
+ side: number;
+}
+
+const SAMPLES_PER_SEGMENT = 16;
+
+/** The curve through `points`, open or closed. */
+export class SplineCurve {
+ /** The straight pieces the curve is cut into: positions, widths, and the distance along the curve at each (one longer than the pieces). */
+ private readonly px: Float64Array;
+ private readonly py: Float64Array;
+ private readonly pz: Float64Array;
+ private readonly pw: Float64Array;
+ private readonly ps: Float64Array;
+ readonly count: number;
+ /** The length of the curve. */
+ readonly length: number;
+ readonly closed: boolean;
+
+ constructor(points: readonly SplinePoint[], closed = false) {
+ this.closed = closed && points.length >= 3;
+ const n = points.length;
+ const segments = n < 2 ? 0 : this.closed ? n : n - 1;
+ const total = segments * SAMPLES_PER_SEGMENT + (this.closed ? 0 : 1);
+ const count = n === 0 ? 0 : n === 1 ? 1 : total;
+ this.count = count;
+ this.px = new Float64Array(count); this.py = new Float64Array(count); this.pz = new Float64Array(count);
+ this.pw = new Float64Array(count); this.ps = new Float64Array(count);
+ if (n === 1) { this.px[0] = points[0]!.x; this.py[0] = points[0]!.y; this.pz[0] = points[0]!.z; this.pw[0] = points[0]!.width; }
+ // Past either end of an open curve the points go on in the line the last two make, which keeps the curve's end from curling back.
+ const at = (i: number): SplinePoint => {
+ if (this.closed) return points[((i % n) + n) % n]!;
+ if (i < 0) { const a = points[0]!, b = points[1]!; return { x: 2 * a.x - b.x, y: 2 * a.y - b.y, z: 2 * a.z - b.z, width: a.width }; }
+ if (i >= n) { const a = points[n - 1]!, b = points[n - 2]!; return { x: 2 * a.x - b.x, y: 2 * a.y - b.y, z: 2 * a.z - b.z, width: a.width }; }
+ return points[i]!;
+ };
+ let k = 0;
+ for (let seg = 0; seg < segments; seg++) {
+ const p0 = at(seg - 1), p1 = at(seg), p2 = at(seg + 1), p3 = at(seg + 2);
+ const last = !this.closed && seg === segments - 1;
+ for (let j = 0; j < SAMPLES_PER_SEGMENT + (last ? 1 : 0); j++) {
+ const t = j / SAMPLES_PER_SEGMENT;
+ const at3 = centripetal(p0, p1, p2, p3, t);
+ this.px[k] = at3[0];
+ this.py[k] = at3[1];
+ this.pz[k] = at3[2];
+ // Widths blend along the segment: a smooth ease, so a width does not turn a corner at a point.
+ this.pw[k] = p1.width + (p2.width - p1.width) * (t * t * (3 - 2 * t));
+ k++;
+ }
+ }
+ let length = 0;
+ for (let i = 0; i < count; i++) {
+ if (i > 0) length += Math.hypot(this.px[i]! - this.px[i - 1]!, this.py[i]! - this.py[i - 1]!, this.pz[i]! - this.pz[i - 1]!);
+ this.ps[i] = length;
+ }
+ if (this.closed && count > 0) length += Math.hypot(this.px[0]! - this.px[count - 1]!, this.py[0]! - this.py[count - 1]!, this.pz[0]! - this.pz[count - 1]!);
+ this.length = length;
+ }
+
+ /** The index of the piece `s` falls in, and how far along it (0 to 1). */
+ private locate(s: number): [number, number] {
+ const n = this.count;
+ if (n < 2) return [0, 0];
+ const wrapped = this.closed ? ((s % this.length) + this.length) % this.length : Math.min(Math.max(s, 0), this.length);
+ let lo = 0, hi = n - 1;
+ // The last piece of a closed curve runs from the last sample back to the first, past the end of the table.
+ const tail = this.closed ? this.ps[n - 1]! : Infinity;
+ if (this.closed && wrapped >= tail) return [n - 1, (wrapped - tail) / Math.max(this.length - tail, 1e-12)];
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (this.ps[mid]! <= wrapped) lo = mid; else hi = mid;
+ }
+ const span = this.ps[lo + 1]! - this.ps[lo]!;
+ return [lo, span > 0 ? (wrapped - this.ps[lo]!) / span : 0];
+ }
+
+ private next(i: number): number { return this.closed ? (i + 1) % this.count : Math.min(i + 1, this.count - 1); }
+
+ /** The point a distance `s` along the curve. Past either end of an open curve it is the end; a closed curve goes round. */
+ position(s: number): [number, number, number] {
+ if (this.count === 0) return [0, 0, 0];
+ const [i, t] = this.locate(s);
+ const j = this.next(i);
+ return [lerp(this.px[i]!, this.px[j]!, t), lerp(this.py[i]!, this.py[j]!, t), lerp(this.pz[i]!, this.pz[j]!, t)];
+ }
+
+ /** The unit direction of travel at distance `s`. */
+ tangent(s: number): [number, number, number] {
+ if (this.count < 2) return [0, 0, 1];
+ const [i] = this.locate(s);
+ const j = this.next(i);
+ let dx = this.px[j]! - this.px[i]!, dy = this.py[j]! - this.py[i]!, dz = this.pz[j]! - this.pz[i]!;
+ if (j === i) { dx = this.px[i]! - this.px[i - 1]!; dy = this.py[i]! - this.py[i - 1]!; dz = this.pz[i]! - this.pz[i - 1]!; }
+ const len = Math.hypot(dx, dy, dz) || 1;
+ return [dx / len, dy / len, dz / len];
+ }
+
+ /** The width at distance `s`. */
+ width(s: number): number {
+ if (this.count === 0) return 0;
+ const [i, t] = this.locate(s);
+ return lerp(this.pw[i]!, this.pw[this.next(i)]!, t);
+ }
+
+ /** Where on the curve (x, z) is nearest, measured in the xz plane. */
+ nearest(x: number, z: number): SplineNearest {
+ let bestD2 = Infinity, bestS = 0, bestSide = 0;
+ const pieces = this.closed ? this.count : this.count - 1;
+ for (let i = 0; i < pieces; i++) {
+ const j = this.next(i);
+ const ax = this.px[i]!, az = this.pz[i]!;
+ const ex = this.px[j]! - ax, ez = this.pz[j]! - az;
+ const len2 = ex * ex + ez * ez;
+ const t = len2 > 0 ? Math.min(Math.max(((x - ax) * ex + (z - az) * ez) / len2, 0), 1) : 0;
+ const dx = x - (ax + t * ex), dz = z - (az + t * ez);
+ const d2 = dx * dx + dz * dz;
+ if (d2 < bestD2) {
+ bestD2 = d2;
+ const pieceLength = i === this.count - 1 ? this.length - this.ps[i]! : this.ps[j]! - this.ps[i]!;
+ bestS = this.ps[i]! + t * pieceLength;
+ bestSide = Math.sign(ex * dz - ez * dx);
+ }
+ }
+ return { s: bestS, distance: Math.sqrt(bestD2), side: bestSide };
+ }
+}
+
+function lerp(a: number, b: number, t: number): number { return a + (b - a) * t; }
+
+/**
+ * The centripetal Catmull-Rom curve between p1 and p2 (`t` 0 to 1), through p0 and p3: its knots are spaced by the square root of the distance
+ * between points, which is what keeps it from looping or cusping where the points are close at one end and far at the other, as the
+ * uniform one does.
+ */
+function centripetal(p0: SplinePoint, p1: SplinePoint, p2: SplinePoint, p3: SplinePoint, t: number): [number, number, number] {
+ const knot = (a: SplinePoint, b: SplinePoint): number => Math.max(Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z) ** 0.5, 1e-4);
+ const t0 = 0, t1 = t0 + knot(p0, p1), t2 = t1 + knot(p1, p2), t3 = t2 + knot(p2, p3);
+ const u = t1 + t * (t2 - t1);
+ const mix = (a: [number, number, number], b: [number, number, number], ta: number, tb: number): [number, number, number] => {
+ const wa = (tb - u) / (tb - ta), wb = (u - ta) / (tb - ta);
+ return [a[0] * wa + b[0] * wb, a[1] * wa + b[1] * wb, a[2] * wa + b[2] * wb];
+ };
+ const v = (p: SplinePoint): [number, number, number] => [p.x, p.y, p.z];
+ const a1 = mix(v(p0), v(p1), t0, t1), a2 = mix(v(p1), v(p2), t1, t2), a3 = mix(v(p2), v(p3), t2, t3);
+ const b1 = mix(a1, a2, t0, t2), b2 = mix(a2, a3, t1, t3);
+ return mix(b1, b2, t1, t2);
+}
diff --git a/sdk/src/spline/index.ts b/sdk/src/spline/index.ts
new file mode 100644
index 000000000..307ab6094
--- /dev/null
+++ b/sdk/src/spline/index.ts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export { Spline, SplinePlugin, splinePlugin, type SplineData } from './splinePlugin';
+export { SplineCurve, type SplinePoint, type SplineNearest } from './curve';
+
+// Importing this subpath INSTALLS splines — see tilemap/index.ts.
+import { registerSplineSupport } from './splineSupport';
+
+registerSplineSupport();
diff --git a/sdk/src/spline/splinePlugin.ts b/sdk/src/spline/splinePlugin.ts
new file mode 100644
index 000000000..9df2125bc
--- /dev/null
+++ b/sdk/src/spline/splinePlugin.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file splinePlugin.ts
+ * @brief The Spline component: a curve through a few points, authored once and read by whatever follows it.
+ *
+ * @details A `Spline` is data and nothing draws it: a river, a road or a camera rail reads it from the same entity and builds what it needs
+ * (see {@link SplineCurve}). The points are in the entity's own space, so moving or turning the entity moves the whole curve.
+ * There is nothing to run each frame, so the plugin only keeps the component known to a build that carries it.
+ */
+import type { App, Plugin } from '../app/app';
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import type { SplinePoint } from './curve';
+
+/** The fields of the `Spline` component. @experimental */
+export interface SplineData {
+ /** The points the curve passes through, in the entity's own space, in order, each with the width of whatever follows it there. */
+ points: SplinePoint[];
+ /** Whether the curve joins its end to its start. Needs three points. */
+ closed: boolean;
+}
+
+/**
+ * A curve through points. It is read by what follows it (a river's `WaterBody`, on the same entity).
+ *
+ * @experimental
+ */
+export const Spline: ComponentDef<SplineData> = defineComponent<SplineData>('Spline', {
+ points: [{ x: -10, y: 0, z: 0, width: 4 }, { x: 10, y: 0, z: 0, width: 4 }] as SplinePoint[],
+ closed: false,
+}, {
+ fields: {
+ points: { category: 'Shape', tooltip: 'The points the curve passes through, in order, in the entity\'s own space. Each carries the width of whatever follows the curve there.' },
+ closed: { category: 'Shape', tooltip: 'Join the end of the curve to its start (three points or more).' },
+ },
+});
+
+export class SplinePlugin implements Plugin {
+ name = 'spline';
+ build(_app: App): void {
+ // Data only: nothing runs each frame.
+ }
+}
+
+export const splinePlugin: Plugin = new SplinePlugin();
diff --git a/sdk/src/spline/splineSupport.ts b/sdk/src/spline/splineSupport.ts
new file mode 100644
index 000000000..21453f8ae
--- /dev/null
+++ b/sdk/src/spline/splineSupport.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file splineSupport.ts — what a build that ships splines tells the core.
+ *
+ * A call, not a file's side effect — see tilemap/tilemapSupport.ts.
+ */
+import { addEntryPlugin } from '../runtime/entryPlugins';
+import { SplinePlugin } from './splinePlugin';
+
+export function registerSplineSupport(): void {
+ addEntryPlugin('spline', () => new SplinePlugin());
+}
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
index bd2a18901..2ed20db70 100644
--- a/sdk/src/water/index.ts
+++ b/sdk/src/water/index.ts
@@ -4,6 +4,7 @@ export {
WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
} from './waterPlugin';
export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './waves';
+export { buildRiverMesh, currentShare } from './riverMesh';
export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './waterMesh';
export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './shore';
diff --git a/sdk/src/water/riverMesh.ts b/sdk/src/water/riverMesh.ts
new file mode 100644
index 000000000..309ea48ab
--- /dev/null
+++ b/sdk/src/water/riverMesh.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file riverMesh.ts
+ * @brief The geometry of a river: a ribbon laid along a curve, as wide as the curve says at every point.
+ *
+ * @details Stations are cut along the curve a `step` apart and each is a row of vertices across the width, from one bank to the other, in the
+ * body's own space with the height of the curve under them (a river runs downhill). The uv is the position, as for a lake, so the Water
+ * shader's body space is the same. The vertex colour carries the current: red and green the direction of travel on the xz plane (0.5
+ * is none), blue how fast the water runs there against its nominal speed, half being the nominal: a narrow reach is quick and a wide one slow,
+ * which is what the same water through a different width does.
+ */
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
+import type { SplineCurve } from '../spline/curve';
+
+/** What the current is at a station: the speed against the nominal one, for a reach this wide against the curve's widest. */
+export function currentShare(width: number, widest: number): number {
+ return Math.min(Math.max(widest / Math.max(width, 1e-3), 0.25), 2) / 2;
+}
+
+/** A river along `curve`, a station every `step` along it and `across` cells from bank to bank. */
+export function buildRiverMesh(curve: SplineCurve, step: number, across: number): MeshData {
+ const stations = Math.max(2, Math.ceil(curve.length / Math.max(step, 1e-3)) + 1);
+ const cells = Math.max(1, Math.floor(across));
+ let widest = 0;
+ for (let i = 0; i < stations; i++) widest = Math.max(widest, curve.width((i / (stations - 1)) * curve.length));
+ const positions: number[] = [], colors: number[] = [];
+ for (let i = 0; i < stations; i++) {
+ const s = (i / (stations - 1)) * curve.length;
+ const [cx, cy, cz] = curve.position(s);
+ const [tx, , tz] = curve.tangent(s);
+ const along = Math.hypot(tx, tz) || 1;
+ const dx = tx / along, dz = tz / along;
+ // The bank to the right of the heading (looking along it from above, +x right, +z toward the viewer): the perpendicular (-dz, dx).
+ const nx = -dz, nz = dx;
+ const half = curve.width(s) / 2;
+ const share = currentShare(half * 2, widest);
+ for (let k = 0; k <= cells; k++) {
+ const v = (k / cells) * 2 - 1;
+ positions.push(cx + nx * v * half, cy, cz + nz * v * half);
+ colors.push(dx * 0.5 + 0.5, dz * 0.5 + 0.5, share, 1);
+ }
+ }
+ const stride = cells + 1;
+ const indices: number[] = [];
+ for (let i = 0; i < stations - 1; i++) {
+ for (let k = 0; k < cells; k++) {
+ const a = i * stride + k, b = i * stride + k + 1, c = (i + 1) * stride + k, d = (i + 1) * stride + k + 1;
+ // Facing up for a heading along +x with the right bank toward +z: (a, b, c) turns the way the lake's cells do.
+ indices.push(a, b, c, c, b, d);
+ }
+ }
+ return pack(positions, colors, indices);
+}
+
+function pack(positions: number[], colors: number[], indices: number[]): MeshData {
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const vertexCount = positions.length / 3;
+ const vertices = new Uint8Array(vertexCount * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const posAt = channels[0]!.offset, uvAt = channels[1]!.offset, colorAt = channels[2]!.offset, normalAt = channels[3]!.offset;
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < vertexCount; i++) {
+ const base = i * vertexStride;
+ for (let k = 0; k < 3; k++) {
+ const value = positions[i * 3 + k]!;
+ view.setFloat32(base + posAt + k * 4, value, true);
+ if (value < min[k]!) min[k] = value;
+ if (value > max[k]!) max[k] = value;
+ }
+ view.setFloat32(base + normalAt, 0, true);
+ view.setFloat32(base + normalAt + 4, 1, true);
+ view.setFloat32(base + normalAt + 8, 0, true);
+ view.setFloat32(base + uvAt, positions[i * 3]!, true);
+ view.setFloat32(base + uvAt + 4, positions[i * 3 + 2]!, true);
+ for (let k = 0; k < 4; k++) view.setUint8(base + colorAt + k, Math.round(Math.min(Math.max(colors[i * 4 + k]!, 0), 1) * 255));
+ }
+ return { channels, vertexStride, vertexCount, vertices, indices: new Uint32Array(indices), aabbMin: min, aabbMax: max };
+}
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 7df9bc252..945dc5d08 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -33,8 +33,11 @@ import type { Entity } from '../types';
import { waveHeight, waveSlope, type WaveParams } from './waves';
import { buildBoxMesh, buildOceanMesh, oceanSnap } from './waterMesh';
import { ShoreField, type Point2 } from './shore';
+import { buildRiverMesh, currentShare } from './riverMesh';
+import { Spline, type SplineData } from '../spline/splinePlugin';
+import { SplineCurve } from '../spline/curve';
-/** What a body of water is. River arrives with the spline it follows. */
+/** What a body of water is. A river follows the `Spline` on its own entity. */
export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
/** The fields of the `WaterBody` component. @experimental */
@@ -54,6 +57,8 @@ export interface WaterBodyData {
cellSize: number;
cells: number;
rings: number;
+ /** A river's current, in world units a second where the river is as wide as its widest; a narrower reach runs faster. */
+ flowSpeed: number;
/** The waves: the height of the tallest, the length of the longest, a multiplier on their speed, and the heading in degrees. */
waveHeight: number;
waveLength: number;
@@ -67,12 +72,13 @@ export interface WaterBodyData {
* @experimental
*/
export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
- form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, cellSize: 1, cells: 64, rings: 5,
+ form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, cellSize: 1, cells: 64, rings: 5, flowSpeed: 2,
waveHeight: 0.3, waveLength: 14, waveSpeed: 1, waveDirection: 30,
}, {
assetFields: [{ field: 'material', type: 'material' }],
fields: {
- form: { enum: [{ label: 'Ocean', value: WaterForm.Ocean }, { label: 'Lake', value: WaterForm.Lake }], category: 'Shape', tooltip: 'An ocean is without edge and follows the camera; a lake is a rectangle of its own size.' },
+ form: { enum: [{ label: 'Ocean', value: WaterForm.Ocean }, { label: 'Lake', value: WaterForm.Lake }, { label: 'River', value: WaterForm.River }], category: 'Shape', tooltip: 'An ocean is without edge and follows the camera; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.' },
+ flowSpeed: { min: 0, max: 50, category: 'Waves', tooltip: 'A river\'s current, in world units a second where it is as wide as its widest. A narrower reach runs faster.' },
material: { category: 'Look', tooltip: 'A material on the Water shader. Empty uses the stock water.' },
sizeX: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along x.' },
sizeZ: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along z.' },
@@ -96,6 +102,8 @@ export interface WaterSample {
depth: number;
/** The surface's normal at the point, in world space. */
normal: [number, number, number];
+ /** How the water moves there, in world units a second (a river's current; still water is zero). */
+ flow: [number, number, number];
/** The world position of the surface above or below the point. */
surface: [number, number, number];
/** Whether the point is over the body's extent (an ocean has none, so it is always). */
@@ -109,6 +117,9 @@ interface Built {
mesh: number;
/** A lake's baked shore, and the texture the shader reads it from. */
field: ShoreField | null;
+ /** A river's curve, the width it is drawn at its widest, and the shoreless texture it does not have. */
+ curve: SplineCurve | null;
+ widest: number;
shoreTexture: number;
child: Entity;
instance: number;
@@ -138,6 +149,21 @@ export class Waters {
const q = toLocal(t, x, y, z, scale);
const d = built.data;
const field = built.field;
+ if (d.form === WaterForm.River) {
+ const curve = built.curve;
+ if (!curve) continue;
+ const near = curve.nearest(q[0], q[2]);
+ const half = curve.width(near.s) / 2;
+ if (near.distance > half) continue;
+ // A river's surface is the curve's own height and its normal is up; what moves is the water.
+ const level = curve.position(near.s)[1];
+ const tangent = curve.tangent(near.s);
+ const run = Math.hypot(tangent[0], tangent[2]) || 1;
+ const speed = d.flowSpeed * currentShare(half * 2, built.widest) * 2;
+ const flow = rotate(t.worldRotation, (tangent[0] / run) * speed * scale, 0, (tangent[2] / run) * speed * scale);
+ const normal = rotate(t.worldRotation, 0, 1, 0);
+ return { entity, depth: (q[1] - level) * scale, normal, flow, surface: fromLocal(t, q[0], level, q[2], scale), inside: true };
+ }
const inside = d.form === WaterForm.Ocean || (field ? field.inside(q[0], q[2]) : false);
if (!inside) continue;
const params = paramsOf(d);
@@ -149,7 +175,7 @@ export class Waters {
const len = Math.hypot(sx, 1, sz);
const normal = rotate(t.worldRotation, -sx / len, 1 / len, -sz / len);
const onSurface = fromLocal(t, q[0], h, q[2], scale);
- return { entity, depth: (q[1] - h) * scale, normal, surface: onSurface, inside };
+ return { entity, depth: (q[1] - h) * scale, normal, flow: [0, 0, 0], surface: onSurface, inside };
}
return null;
}
@@ -202,8 +228,8 @@ function fromLocal(t: TransformData, x: number, y: number, z: number, scale: num
}
/** What shapes the geometry: when it changes the child is rebuilt; the waves and the material are not part of it. */
-function signatureOf(d: WaterBodyData, ground: string): string {
- return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.boundary, d.shoreWidth, d.cellSize, d.cells, d.rings, d.material, ground]);
+function signatureOf(d: WaterBodyData, ground: string, spline: SplineData | null): string {
+ return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.boundary, d.shoreWidth, d.cellSize, d.cells, d.rings, d.material, ground, d.form === WaterForm.River ? spline : null]);
}
export class WaterPlugin implements Plugin {
@@ -225,11 +251,12 @@ export class WaterPlugin implements Plugin {
const eye = this.eye(app);
for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {
const data = app.world.get(entity, WaterBody) as WaterBodyData;
- const signature = signatureOf(data, this.groundKey(app, entity, data));
+ const spline = data.form === WaterForm.River ? app.world.tryGet(entity, Spline) as SplineData | null : null;
+ const signature = signatureOf(data, this.groundKey(app, entity, data), spline);
let built = waters.built_.get(entity);
if (!built || built.signature !== signature) {
if (built) this.destroy(app, built);
- built = { signature, data: { ...data }, mesh: 0, field: null, shoreTexture: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
+ built = { signature, data: { ...data }, mesh: 0, field: null, curve: null, widest: 0, shoreTexture: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
waters.built_.set(entity, built);
}
built.data = { ...data };
@@ -284,6 +311,14 @@ export class WaterPlugin implements Plugin {
let mesh: number;
if (d.form === WaterForm.Ocean) {
mesh = assets.createMesh(buildOceanMesh(d.cells, d.rings, d.cellSize));
+ } else if (d.form === WaterForm.River) {
+ // A river: the Spline on its entity, laid as a ribbon.
+ const spline = app.world.tryGet(entity, Spline) as SplineData | null;
+ if (!spline || spline.points.length < 2) { log.warn('water', 'a river needs a Spline of two points or more on its entity'); return; }
+ built.curve = new SplineCurve(spline.points, spline.closed);
+ for (let i = 0; i <= 64; i++) built.widest = Math.max(built.widest, built.curve.width((i / 64) * built.curve.length));
+ const across = Math.min(64, Math.max(2, Math.ceil(built.widest / Math.max(d.cellSize, 0.05))));
+ mesh = assets.createMesh(buildRiverMesh(built.curve, d.cellSize, across));
} else {
// A lake: its outline (or its rectangle), the ground under it, and what the two say about the waves and the shore.
const poly = outlineOf(d);
@@ -375,6 +410,8 @@ export class WaterPlugin implements Plugin {
set('u_waveSpace', 1);
set('u_origin', { x: ox, y: oz });
set('u_cellSize', d.cellSize);
+ set('u_flowSpeed', d.form === WaterForm.River ? d.flowSpeed : 0);
+ set('u_geoWaves', d.form === WaterForm.River ? 0 : 1);
set('u_waveHeight', d.waveHeight);
set('u_waveLength', d.waveLength);
set('u_waveSpeed', d.waveSpeed);
@@ -389,6 +426,8 @@ export class WaterPlugin implements Plugin {
if (built.shoreTexture) getResourceManager()?.releaseTexture(built.shoreTexture);
built.shoreTexture = 0;
built.field = null;
+ built.curve = null;
+ built.widest = 0;
if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
built.child = 0 as Entity;
built.instance = 0;
diff --git a/sdk/tests/spline.test.ts b/sdk/tests/spline.test.ts
new file mode 100644
index 000000000..c8b01eaa9
--- /dev/null
+++ b/sdk/tests/spline.test.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { SplineCurve, type SplinePoint } from '../src/spline/curve';
+import { buildRiverMesh, currentShare } from '../src/water/riverMesh';
+import { MeshChannel } from '../src/asset/meshFormat';
+
+const pt = (x: number, y: number, z: number, width = 1): SplinePoint => ({ x, y, z, width });
+
+describe('SplineCurve', () => {
+ it('is as long as the line between two points, and runs along it', () => {
+ const c = new SplineCurve([pt(0, 0, 0, 2), pt(10, 0, 0, 6)]);
+ expect(c.length).toBeCloseTo(10, 6);
+ expect(c.position(0)).toEqual([0, 0, 0]);
+ expect(c.position(5)[0]).toBeCloseTo(5, 6);
+ expect(c.position(100)[0]).toBeCloseTo(10, 6);
+ expect(c.position(-5)[0]).toBeCloseTo(0, 6);
+ expect(c.tangent(5)[0]).toBeCloseTo(1, 6);
+ });
+
+ it('eases a width from one point\'s to the next\'s', () => {
+ const c = new SplineCurve([pt(0, 0, 0, 2), pt(10, 0, 0, 6)]);
+ expect(c.width(0)).toBeCloseTo(2, 6);
+ expect(c.width(10)).toBeCloseTo(6, 6);
+ expect(c.width(5)).toBeCloseTo(4, 2);
+ expect(c.width(2.5)).toBeLessThan(3);
+ });
+
+ it('passes through every point it was given', () => {
+ const points = [pt(0, 0, 0), pt(10, 0, 4), pt(20, 2, -3), pt(30, 3, 5)];
+ const c = new SplineCurve(points);
+ for (const p of points) expect(c.nearest(p.x, p.z).distance).toBeLessThan(0.05);
+ });
+
+ it('measures by the distance along it, not by the points', () => {
+ // Points on a wide circle, bunched at one end and far apart at the other: equal steps along the curve are equal steps in space.
+ const on = (deg: number): SplinePoint => pt(60 * Math.cos((deg * Math.PI) / 180), 0, 60 * Math.sin((deg * Math.PI) / 180));
+ const c = new SplineCurve([on(0), on(6), on(12), on(70), on(160)]);
+ const steps: number[] = [];
+ for (let s = 0; s < c.length - 1; s += 1) {
+ const a = c.position(s), b = c.position(s + 1);
+ steps.push(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]));
+ }
+ expect(Math.min(...steps)).toBeGreaterThan(0.97);
+ expect(Math.max(...steps)).toBeLessThan(1.0001);
+ });
+
+ it('goes round when it is closed', () => {
+ const c = new SplineCurve([pt(0, 0, 0), pt(10, 0, 0), pt(10, 0, 10), pt(0, 0, 10)], true);
+ const a = c.position(7), b = c.position(7 + c.length);
+ expect(b[0]).toBeCloseTo(a[0], 6);
+ expect(b[2]).toBeCloseTo(a[2], 6);
+ // The piece back from the last point to the first is part of it.
+ expect(c.length).toBeGreaterThan(40);
+ expect(c.nearest(-0.0, 5).distance).toBeLessThan(3);
+ });
+
+ it('finds the nearest place on it, and says which side', () => {
+ const c = new SplineCurve([pt(0, 0, 0), pt(20, 0, 0)]);
+ const left = c.nearest(7, 2), right = c.nearest(7, -2);
+ expect(left.s).toBeCloseTo(7, 4);
+ expect(left.distance).toBeCloseTo(2, 6);
+ expect(right.s).toBeCloseTo(7, 4);
+ expect(right.distance).toBeCloseTo(2, 6);
+ expect(left.side).toBe(-right.side);
+ expect(left.side).not.toBe(0);
+ });
+
+ it('survives a point, or none', () => {
+ expect(new SplineCurve([pt(3, 4, 5)]).position(2)).toEqual([3, 4, 5]);
+ expect(new SplineCurve([]).length).toBe(0);
+ expect(new SplineCurve([]).position(1)).toEqual([0, 0, 0]);
+ });
+});
+
+function positions(mesh: { channels: { semantic: number; offset: number }[]; vertexStride: number; vertexCount: number; vertices: Uint8Array }): Float32Array {
+ const channel = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;
+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
+ const out = new Float32Array(mesh.vertexCount * 3);
+ for (let i = 0; i < mesh.vertexCount; i++) for (let k = 0; k < 3; k++) out[i * 3 + k] = view.getFloat32(i * mesh.vertexStride + channel.offset + k * 4, true);
+ return out;
+}
+
+describe('a river\'s mesh', () => {
+ // Along +x, widening from 2 to 6, falling a unit over its length.
+ const curve = new SplineCurve([pt(0, 1, 0, 2), pt(20, 0, 0, 6)]);
+ const mesh = buildRiverMesh(curve, 2, 4);
+ const p = positions(mesh);
+
+ it('faces up, whichever way it runs', () => {
+ for (const c of [curve, new SplineCurve([pt(0, 0, 0, 3), pt(0, 0, 20, 3)]), new SplineCurve([pt(0, 0, 0, 3), pt(-12, 0, -9, 3)])]) {
+ const m = buildRiverMesh(c, 2, 3);
+ const q = positions(m);
+ for (let t = 0; t < m.indices.length; t += 3) {
+ const a = m.indices[t]!, b = m.indices[t + 1]!, d = m.indices[t + 2]!;
+ const f = (q[b * 3 + 2]! - q[a * 3 + 2]!) * (q[d * 3]! - q[a * 3]!) - (q[b * 3]! - q[a * 3]!) * (q[d * 3 + 2]! - q[a * 3 + 2]!);
+ expect(f).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ it('is as wide as the curve at each station and lies at its height', () => {
+ const stride = 5;
+ const stations = mesh.vertexCount / stride;
+ for (const i of [0, Math.floor(stations / 2), stations - 1]) {
+ const s = (i / (stations - 1)) * curve.length;
+ const first = i * stride, last = i * stride + 4;
+ const width = Math.hypot(p[first * 3]! - p[last * 3]!, p[first * 3 + 2]! - p[last * 3 + 2]!);
+ expect(width).toBeCloseTo(curve.width(s), 4);
+ expect(p[first * 3 + 1]).toBeCloseTo(curve.position(s)[1], 4);
+ }
+ });
+
+ it('carries the direction of the current in its colour, and a narrow reach runs faster than a wide one', () => {
+ const colorAt = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!.offset;
+ const rgb = (v: number): number[] => [0, 1, 2].map((k) => mesh.vertices[v * mesh.vertexStride + colorAt + k]! / 255);
+ const first = rgb(0), last = rgb(mesh.vertexCount - 1);
+ // Heading along +x: red high, green at rest.
+ expect(first[0]).toBeGreaterThan(0.95);
+ expect(first[1]).toBeCloseTo(0.5, 1);
+ expect(first[2]).toBeGreaterThan(last[2]);
+ expect(currentShare(2, 6)).toBe(1);
+ expect(currentShare(6, 6)).toBe(0.5);
+ expect(currentShare(60, 6)).toBe(0.125);
+ });
+});
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 44f1bfe7c..5ce4e79d7 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -325,6 +325,16 @@ export const SUBSYSTEMS = [
whyZh: '地面和上面的植物在编辑器里两个后端都能画出来并有检查,但还没有东西和地面碰撞,创作面板也还没有被拿来定下这套接口的形状',
entry: ['Terrain', 'Foliage'],
},
+ {
+ id: 'spline',
+ title: 'Splines',
+ titleZh: '样条',
+ source: ['spline'],
+ tier: 'experimental',
+ why: 'the curve and its measuring by distance are checked, but the only thing that follows one so far is a river, and the editor has no tool to draw it',
+ whyZh: '曲线和按距离度量已经有检查,但目前只有河流会沿着它走,编辑器里也还没有绘制它的工具',
+ entry: ['Spline', 'SplineCurve'],
+ },
{
id: 'water',
title: 'Water',
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 6b2f3e42d..4b298761d 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -123,6 +123,7 @@ const DISPOSITION = {
SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],
// — code-only: an example demonstrates it from TypeScript, honestly —
+ Spline: ['owed', 'no example carries a spline yet; the first river, with a spline tool in the editor, goes into one'],
WaterBody: ['owed', 'no example carries a body of water yet; the first of the water work that is shown off (rivers, with the spline) goes into one'],
Replicated: ['code-only', 'multiplayer-arena declares its replicated set beside the server systems that own it; the wire table is a contract both ends compile against, not scene content'],
diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjs
index 54fea290c..812694086 100644
--- a/tools/lib/sdkProgram.mjs
+++ b/tools/lib/sdkProgram.mjs
@@ -66,6 +66,7 @@ export const ENTRIES = {
'fx-lighting': 'src/postprocess/fxLighting.ts',
'foliage': 'src/foliage/index.ts',
'water': 'src/water/index.ts',
+ 'spline': 'src/spline/index.ts',
'logic': 'src/logic/index.ts',
'debug-channel': 'src/debug-channel/index.ts',
'ai': 'src/ai/index.ts',
diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.js
index 321f513d6..f35a7691b 100644
--- a/tools/nativeScriptModules.js
+++ b/tools/nativeScriptModules.js
@@ -72,6 +72,7 @@ export const MODULES = {
'esengine/fx-lighting': { disposition: 'native-subpath' },
'esengine/foliage': { disposition: 'native-subpath' },
'esengine/water': { disposition: 'native-subpath' },
+ 'esengine/spline': { disposition: 'native-subpath' },
'esengine/logic': { disposition: 'native-subpath' },
'esengine/ai': { disposition: 'native-subpath' },
'esengine/replication': { disposition: 'native-subpath' },
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 88ff64b61..765e333b7 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2561,6 +2561,8 @@ export const NOTED = {
{"note":"Water gets a component and a chapter of its own. A WaterBody builds an ocean (without an edge, following the camera, in rings that coarsen with distance) or a rectangular lake, lifts its geometry with the waves, follows its own up when it is tilted, and answers for its surface from code (`Waters.sample`) with the same formula the shader draws. Water is an optional module (`esengine/water`): a 2D game carries none of it."},
"feat(water): a lake takes an outline of its own and calms its waves toward the shore":
{"note":"A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside."},
+ "feat(water): a river follows a Spline and runs with a current the surface and the code can both read":
+ {"note":"A WaterBody can be a river: put a Spline on its entity and it lays a ribbon along the curve, as wide as the curve says at each point and at its height, with a current (`flowSpeed`, faster where it narrows) that the shader carries the waves and ripples along and that `Waters.sample` reports as `flow`. Splines are a new optional module (`esengine/spline`): a curve through points with a width each, measured by the distance along it."},
"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":
{"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":