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 WaterBody builds an ocean or a lake whose waves lift the geometry and can be read from code

yhh486da17ae8a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7352a9e8b..16b3b7bcf 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.
+- **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.
- **Hair tips.** The Hair shader can draw the soft outer band of its cards: `u_tipSoftness` is how far below the cutoff alpha a second, blended pass draws each strand's tip fading out, sorted with the other blended draws, so tips are not stair-stepped by coverage. A model imported with Character Materials also has its hair triangles put in the order that pass wants, the cards nearest the middle of the hair first. Off by default.
- **Character materials on import.** Importing a model can now give its character materials the right shader: turn on Character Materials in the model's import settings and a material whose name says skin, face, head, hair or eye gets the Skin, Hair or Eye shader with its normal and occlusion/roughness maps bound, and hair is cut out by its alpha and feathered by coverage. Off by default.
diff --git a/desktop b/desktop
index c86231940..3e00c4540 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c86231940cd41f6d214bf8b9e723fa92f92701b4
+Subproject commit 3e00c45409139baaf9e7071026f43e741f84a60b
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index e339c3315..1f70dfb64 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -225,6 +225,7 @@ export default defineConfig({
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'graphics/post-processing' },
{ label: 'Terrain', translations: { 'zh-CN': '地形' }, slug: 'graphics/terrain' },
{ label: 'Foliage', translations: { 'zh-CN': '植被' }, slug: 'graphics/foliage' },
+ { label: 'Water', translations: { 'zh-CN': '水' }, slug: 'graphics/water' },
{ label: 'Weather', translations: { 'zh-CN': '天气' }, slug: 'graphics/weather' },
{ label: 'Time of Day', translations: { 'zh-CN': '昼夜' }, slug: 'graphics/time-of-day' },
{ label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'graphics/drawing' },
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 9e7e32cdd..17c17de19 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -38,7 +38,7 @@ creates a material from a built-in template — the same list ships in code as
| **Foliage** | `foliage` | Plants that sway in the wind: a vertex bend by weights painted in the vertex colour, two-sided and translucent, with an optional cutout texture. See [Foliage](/docs/graphics/foliage/). |
| **Skin** | `skin` | Soft diffuse by colour, a warm terminator, light through thin places, two shine lobes and a fuzz — without blurring the picture. See [Skin and hair](#skin-and-hair). |
| **Hair** | `hair` | Strand lighting: Kajiya-Kay diffuse, two shifted highlights along a flow map, and light through the strands. See [Skin and hair](#skin-and-hair). |
-| **Water** | `water` | A horizontal body of water: travelling waves and ripples, the scene behind it bent and tinted by how deep the water is, reflections, and foam. See [Water](#water). |
+| **Water** | `water` | A horizontal body of water: travelling waves and ripples, the scene behind it bent and tinted by how deep the water is, reflections, and foam. See [Water](/docs/graphics/water/). |
A new material **references** its template by id — it stores `shader: "builtin:sprite-unlit"`
and writes **no shader file** to disk. The engine compiles the built-in from in-code source
@@ -49,21 +49,8 @@ shader** yourself.
## Water
-The **Water** shader (`builtin:water`) turns a horizontal plane into a body of water.
-
-- **Waves.** Four waves a few directions apart, each with a sharper crest than trough, travel at the speed their length gives them (`u_waveLength`, `u_waveHeight`, `u_waveSpeed`, `u_waveDirection`); small ripples (`u_rippleStrength`, `u_rippleLength`) ride on them. They are drawn in the surface's normal, not as displaced geometry, and fade out with distance so far water is calm rather than aliased.
-- **Refraction and depth.** What is under the water is the picture of the opaque scene, shifted by the waves in proportion to how much water there is. The depth is **measured**: before the water is drawn the frame takes a copy of how far each pixel of the scene is from the eye, so the water at a pixel is the difference between that and the water's own distance. The light is absorbed along that column — red first (`u_absorption`, `u_density`) — and the water gives back its own colour, from `u_shallowColor` to `u_deepColor` as it deepens.
-- **Reflection.** The sky, the lights and the environment reflect off it with a Fresnel term (water is 1.333), so it is clear looking down and mirror-like at a grazing angle. Add Screen Space Reflections to the volume for reflections of the scene itself.
-- **Foam.** Where the column is shallower than `u_foamWidth` (the shore, a rock, a pier's legs) and on the crests of the waves (`u_foamCrest`), broken up by moving noise.
-
-Parameters are in world units: a scene in metres wants the defaults, one in centimetres wants the lengths and `u_density` scaled.
-
-**Limits.**
-
-- It needs the same engine-copied scene as glass (a post-process chain is running) and a device whose render targets can hold floats for the depth. 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.
-- The surface is taken to lie flat: a water plane that is tilted or curved will shade as if it were level.
-- The waves do not move the geometry, so a wave does not break the shoreline or lift a floating object, and the silhouette against the sky is a straight line.
+The **Water** shader (`builtin:water`) draws a body of water: refraction by measured depth, reflection and foam. The `WaterBody` component builds an
+ocean or a lake from it, lifts the geometry with waves and answers for the surface from code. All of it is in [Water](/docs/graphics/water/).
## Skin and hair
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
new file mode 100644
index 000000000..b59d8a073
--- /dev/null
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -0,0 +1,94 @@
+---
+title: Water
+description: A WaterBody component that builds an ocean or a lake, lifts its geometry with waves the CPU can read back, follows its own up when tilted, and the Water shader that draws it.
+---
+
+Water has two halves. The **Water shader** (`builtin:water`) is the look: refraction, depth, reflection, foam. The **`WaterBody` component** is the
+body: it builds the geometry, lifts it with waves, and answers questions about its surface from the code, so what a script reads is what is drawn.
+This chapter is both, and what is not there yet.
+
+Water is an optional module: a package takes it only when a scene authors a `WaterBody` (or a script imports `esengine/water`), so a 2D game
+carries none of it.
+
+## The component
+
+Add a `WaterBody` to an entity. The entity places and tilts the water; its child is the mesh, made when the scene runs and rebuilt when the shape
+changes.
+
+| Field | What it does |
+|---|---|
+| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity. |
+| `material` | A material on the Water shader. Empty uses the stock water. |
+| `cellSize` | The cell size of the finest ring of geometry. |
+| `cells`, `rings` | An ocean's rings: cells along a ring's side, and how many rings. |
+| `waveHeight`, `waveLength`, `waveSpeed`, `waveDirection` | The waves (below). |
+
+The body writes its waves, its cell size and its position in space into its own copy of the material every frame, so editing a field moves the
+water at once and several bodies can share one material asset.
+
+## Waves
+
+Four peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) a few directions apart, each with a length, a height and a speed
+that are shares of the four numbers on the component. They **move the geometry**: the shader lifts each vertex by the wave height, and the
+fragment takes the slope per pixel from the same formula, so the lit surface is the one that is drawn and the silhouette against the sky rises
+and falls with the waves.
+
+The waves are measured in the body's own space, along its surface and up its own up, so a tilted body is tilted water. Parameters are in world
+units: a scene in metres wants the defaults, one in centimetres wants the lengths scaled.
+
+## Geometry
+
+A **lake** is a grid of `cellSize` cells. An **ocean** is rings of the same number of cells, each twice as coarse as the one inside it with a hole
+where that one sits, so it reaches far and spends its triangles near. It follows the camera on a lattice all its rings line up on, and the
+material's origin moves by as much, so the waves stay put in the world while the mesh moves under them.
+
+A coarse ring cannot draw a short wave: below three cells to a wavelength it would alias, so its vertices fade out the waves shorter than six of
+its cells (the shading still shows them, per pixel). Where two rings meet, the coarse one has half the vertices along the edge, and the surfaces
+can part by what the waves do between them; keep `waveLength` at least six of the coarsest visible ring's cells and there is no seam to see.
+
+## Asking the surface
+
+`Waters.sample(x, y, z)` (the `WatersRes` resource) answers for the body that holds a point:
+
+- `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.
+
+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`.
+
+The surface the code reads is the full wave sum; a coarse far ring of an ocean draws less of it (see above), so near the horizon the two can
+differ by the short waves, which are small.
+
+## The Water shader
+
+`builtin:water` also works on its own, on any mesh, which is how a flat plane of water was made before the component. With `u_waveSpace` at its
+default (0) the waves are measured on the world's xz plane, nothing is lifted and the surface is taken to lie flat. The component turns it to 1 (the
+mesh's uv is its local x and z) for the body's own space.
+
+- **Waves.** `u_waveLength`, `u_waveHeight`, `u_waveSpeed`, `u_waveDirection`; small ripples (`u_rippleStrength`, `u_rippleLength`) ride on them and
+ fade out with distance, so far water is calm rather than aliased.
+- **Refraction and depth.** What is under the water is the picture of the opaque scene, shifted by the waves in proportion to how much water there
+ is. The depth is **measured**: before the water is drawn the frame takes a copy of how far each pixel of the scene is from the eye, so the water at
+ a pixel is the difference between that and the water's own distance. The light is absorbed along that column, red first (`u_absorption`,
+ `u_density`), and the water gives back its own colour, from `u_shallowColor` to `u_deepColor` as it deepens.
+- **Reflection.** The sky, the lights and the environment reflect off it with a Fresnel term (water is 1.333), so it is clear looking down and
+ mirror-like at a grazing angle. Add Screen Space Reflections to the volume for reflections of the scene itself.
+- **Foam.** Where the column is shallower than `u_foamWidth` (the shore, a rock, a pier's legs) and on the crests of the waves (`u_foamCrest`),
+ broken up by moving noise.
+
+## Limits
+
+What is not there yet, so nobody is surprised:
+
+- It needs the same engine-copied scene as glass (a post-process chain is running) and a device whose render targets can hold floats for the depth.
+ 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.
+- A lake is a rectangle; a boundary of your own shape, lakes that fill a terrain basin, rivers along a curve, flow, and the waves' breaking at a
+ shore are not built yet.
+- 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.
+- The waves are the four peaked sines, not a spectrum, and they lift the surface without pushing it sideways.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index e435bddc5..4ac6e35c6 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -43,21 +43,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
## 水
-**Water** 着色器(`builtin:water`)把一个水平面变成一片水体。
-
-- **波浪。** 四道相差几个方向的波,波峰比波谷更尖,以各自波长决定的速度传播(`u_waveLength`、`u_waveHeight`、`u_waveSpeed`、`u_waveDirection`);小涟漪(`u_rippleStrength`、`u_rippleLength`)骑在它们上面。波浪画在表面法线里,不是位移几何体,并且随距离淡出,所以远处的水是平静的而不是闪烁的。
-- **折射与水深。** 水下看到的是不透明场景的画面,被波浪按水量多少偏移。水深是**量出来的**:绘制水之前,帧会拷贝一份场景每个像素离眼睛多远,水在某个像素处的深度就是那个距离与水面自己的距离之差。光沿着这段水柱被吸收——红色最先(`u_absorption`、`u_density`)——水再还给你它自己的颜色,随水变深从 `u_shallowColor` 过渡到 `u_deepColor`。
-- **反射。** 天空、灯光和环境按菲涅尔项反射(水是 1.333),所以俯视时清澈、掠射时像镜子。想要场景本身的倒影,在体积里加上屏幕空间反射。
-- **泡沫。** 水柱浅于 `u_foamWidth` 的地方(岸边、礁石、桥墩脚下)和波峰上(`u_foamCrest`)出现泡沫,由流动的噪声打散。
-
-参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度和 `u_density` 相应缩放。
-
-**限制。**
-
-- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
-- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
-- 表面被当作是平的:倾斜或弯曲的水面会按水平来着色。
-- 波浪不移动几何体,所以波不会冲破海岸线,也不会托起漂浮的物体,和天空交界的轮廓是一条直线。
+**Water** 着色器(`builtin:water`)画一片水体:按实测水深折射,以及反射和泡沫。`WaterBody` 组件用它构建海洋或湖泊,用波浪抬起几何体,并让代码能查询水面。全部内容在[水](/docs/zh-cn/graphics/water/)一章。
## 皮肤与头发
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
new file mode 100644
index 000000000..39a190b85
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -0,0 +1,68 @@
+---
+title: 水
+description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的波浪抬起几何体,倾斜时跟随自己的上方向,以及画出它的 Water 着色器。
+---
+
+水有两半。**Water 着色器**(`builtin:water`)是外观:折射、水深、反射、泡沫。**`WaterBody` 组件**是水体本身:它构建几何体,用波浪抬起它,并让代码能查询它的表面,所以脚本读到的就是画出来的。本章两者都讲,也讲还没有的部分。
+
+水是一个可选模块:只有场景里有 `WaterBody`(或脚本导入了 `esengine/water`)时,包才会带上它,所以 2D 游戏不带任何水的代码。
+
+## 组件
+
+给某个实体加一个 `WaterBody`。实体决定水的位置和倾斜;它的子实体是网格,在场景运行时生成,形状一变就重建。
+
+| 字段 | 作用 |
+|---|---|
+| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形。 |
+| `material` | 使用 Water 着色器的材质。留空用内置的水。 |
+| `cellSize` | 最细一圈几何体的格子大小。 |
+| `cells`、`rings` | 海洋的圈:每圈一边多少格,以及有几圈。 |
+| `waveHeight`、`waveLength`、`waveSpeed`、`waveDirection` | 波浪(见下)。 |
+
+水体每帧把自己的波浪、格子大小和空间位置写进自己的那份材质副本,所以改字段水立刻就变,几个水体也可以共用同一个材质资源。
+
+## 波浪
+
+四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是组件上那四个数的份额。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。
+
+波浪在水体自己的空间里度量,沿着它的表面和它自己的上方向,所以倾斜的水体就是倾斜的水。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。
+
+## 几何体
+
+**湖泊**是 `cellSize` 大小格子的网格。**海洋**是一圈圈格子数相同的网格,每圈的格子是里面那圈的两倍,中间留出里面那圈的洞,所以它能伸得很远,又把三角形花在近处。它跟着相机、落在所有圈都对齐的格点上,材质的原点同步移动,所以网格在波浪下面移动,而波浪留在世界里不动。
+
+粗的一圈画不出短的波:一个波长不到三格就会闪烁,所以它的顶点会淡掉比自己六格还短的波(着色仍然逐像素显示它们)。两圈相接处,粗的一圈沿边的顶点少一半,表面可能在顶点之间分开,分开多少取决于波浪在它们之间做了什么;让 `waveLength` 至少是看得到的最粗一圈的六格,接缝就看不出来。
+
+## 查询表面
+
+`Waters.sample(x, y, z)`(资源 `WatersRes`)为包含这个点的水体作答:
+
+- `depth`:这个点沿水体上方向高出表面多少(在下面则为负),世界单位;
+- `normal`:表面在那里的法线,世界空间;
+- `surface`:这个点正上方或正下方、表面上的世界坐标;
+- `inside`:这个点是否在水体范围之上。
+
+它读的是着色器画的同一个公式,取这一帧的时间。水体的位置、旋转和均匀缩放都被考虑进去。`Waters.heightAt(x, z)` 是未倾斜水体的简写。点上方没有水则返回 `null`。
+
+代码读到的是完整的波浪和;海洋远处的粗圈画得少一些(见上),所以在接近地平线处两者可能相差那些短波,它们本来就很小。
+
+## Water 着色器
+
+`builtin:water` 也可以单独用在任何网格上,这是组件出现之前做一块平水面的方式。`u_waveSpace` 取默认值(0)时,波浪按世界的 xz 平面度量,什么也不抬起,表面被当作是平的。组件把它设为 1(网格的 uv 是它的局部 x 和 z),使用水体自己的空间。
+
+- **波浪。** `u_waveLength`、`u_waveHeight`、`u_waveSpeed`、`u_waveDirection`;小涟漪(`u_rippleStrength`、`u_rippleLength`)骑在它们上面,并随距离淡出,所以远处的水是平静的而不是闪烁的。
+- **折射与水深。** 水下看到的是不透明场景的画面,被波浪按水量多少偏移。水深是**量出来的**:绘制水之前,帧会拷贝一份场景每个像素离眼睛多远,水在某个像素处的深度就是那个距离与水面自己的距离之差。光沿着这段水柱被吸收——红色最先(`u_absorption`、`u_density`)——水再还给你它自己的颜色,随水变深从 `u_shallowColor` 过渡到 `u_deepColor`。
+- **反射。** 天空、灯光和环境按菲涅尔项反射(水是 1.333),所以俯视时清澈、掠射时像镜子。想要场景本身的倒影,在体积里加上屏幕空间反射。
+- **泡沫。** 水柱浅于 `u_foamWidth` 的地方(岸边、礁石、桥墩脚下)和波峰上(`u_foamCrest`)出现泡沫,由流动的噪声打散。
+
+## 限制
+
+还没有的部分,免得让人意外:
+
+- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
+- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
+- 湖泊是矩形;自定义形状的边界、填满地形盆地的湖、沿曲线的河流、水流,以及波浪在岸边破碎,都还没有做。
+- 还没有东西能漂在上面或在里面游:`Waters.sample` 给出了浮力需要的量,但还没有这个力。
+- 相机在水面以下时,看到的是翻过来的水,别的没有变化:没有水下的雾和染色。
+- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。
+- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 40a8c2b3e..081feb54b 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": 2334,
+ "experimental": 2351,
"deprecated": 3
},
- "total": 2620,
+ "total": 2637,
"subsystems": [
{
"id": "mobile-controls",
@@ -381,6 +381,18 @@
"Foliage"
]
},
+ {
+ "id": "water",
+ "title": "Water",
+ "titleZh": "水体",
+ "tier": "experimental",
+ "why": "the surface draws and its waves are shared with the CPU, but only an ocean and a rectangular lake exist so far, and nothing floats or swims in it yet",
+ "whyZh": "水面能画出来,波浪也和 CPU 共用同一个公式,但目前只有海洋和矩形湖泊,还没有东西能漂浮或游泳",
+ "entry": [
+ "WaterBody",
+ "Waters"
+ ]
+ },
{
"id": "decal",
"title": "Decals",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 9ca9a1766..3a8f78d03 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: '组件' },
+ 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: '烘焙光照' },
PlanarReflection: { category: 'graphics', summary: 'Captures a mirrored view for flat lit surfaces, with layer filtering, capture quality and update controls.', doc: 'graphics/lighting' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 2ddf1cd61..d8584c81f 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -7029,6 +7029,104 @@
"handle"
]
},
+ {
+ "name": "WaterBody",
+ "source": "ts",
+ "fields": [
+ {
+ "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.",
+ "values": [
+ "Ocean",
+ "Lake"
+ ]
+ },
+ {
+ "key": "material",
+ "type": "Asset<material>",
+ "default": "none",
+ "doc": "A material on the Water shader. Empty uses the stock water."
+ },
+ {
+ "key": "sizeX",
+ "type": "number",
+ "default": "100",
+ "doc": "A lake's size along x.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "sizeZ",
+ "type": "number",
+ "default": "100",
+ "doc": "A lake's size along z.",
+ "range": "≥ 1"
+ },
+ {
+ "key": "cellSize",
+ "type": "number",
+ "default": "1",
+ "doc": "The cell size of the finest ring. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).",
+ "range": "≥ 0.05"
+ },
+ {
+ "key": "cells",
+ "type": "number",
+ "default": "64",
+ "doc": "Cells along a ring's side (an ocean).",
+ "range": "4–256, step 4"
+ },
+ {
+ "key": "rings",
+ "type": "number",
+ "default": "5",
+ "doc": "Rings of an ocean, each twice as coarse as the one inside it.",
+ "range": "1–8, step 1"
+ },
+ {
+ "key": "waveHeight",
+ "type": "number",
+ "default": "0.3",
+ "doc": "The height of the tallest wave, in world units.",
+ "range": "0–8"
+ },
+ {
+ "key": "waveLength",
+ "type": "number",
+ "default": "14",
+ "doc": "The length of the longest wave.",
+ "range": "0.5–300"
+ },
+ {
+ "key": "waveSpeed",
+ "type": "number",
+ "default": "1",
+ "doc": "A multiplier on how fast the waves travel.",
+ "range": "0–4"
+ },
+ {
+ "key": "waveDirection",
+ "type": "number",
+ "default": "30",
+ "doc": "The heading of the waves, in degrees.",
+ "range": "0–360"
+ }
+ ],
+ "animatable": [
+ "form",
+ "material",
+ "sizeX",
+ "sizeZ",
+ "cellSize",
+ "cells",
+ "rings",
+ "waveHeight",
+ "waveLength",
+ "waveSpeed",
+ "waveDirection"
+ ]
+ },
{
"name": "Weather",
"source": "ts",
diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.ts
index a0986dd0c..a51e6d31f 100644
--- a/pipeline/src/bundle/engineSubpaths.ts
+++ b/pipeline/src/bundle/engineSubpaths.ts
@@ -18,6 +18,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
'esengine/fx-atmosphere': 'fx-atmosphere/index.js',
'esengine/fx-lighting': 'fx-lighting/index.js',
'esengine/foliage': 'foliage/index.js',
+ 'esengine/water': 'water/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 853cb550a..2dd44bc08 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' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'
+ | 'text' | 'tilemap' | 'terrain' | 'foliage' | 'water' | 'timeline' | 'fxBasic' | 'fxAtmosphere' | 'fxLighting' | 'particles' | 'postprocess' | 'physics' | 'physics3d'
| 'spine' | 'dragonbones' | 'video' | 'ai' | 'logic' | 'replication' | 'gameplay';
/**
@@ -46,6 +46,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
fxAtmosphere: ['Weather', 'TimeOfDay'],
fxLighting: [],
foliage: ['Foliage'],
+ water: ['WaterBody'],
particles: ['ParticleEmitter', 'ParticleForceField'],
postprocess: ['PostProcessVolume'],
physics: [
@@ -97,6 +98,7 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {
fxAtmosphere: 'Post-process effects (sky, fog, rain)',
fxLighting: 'Post-process effects (occlusion, reflections, exposure)',
foliage: 'Foliage',
+ water: 'Water',
particles: 'Particles',
postprocess: 'Post-processing',
physics: 'Physics (Box2D)',
@@ -127,6 +129,7 @@ export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {
fxAtmosphere: 'esengine/fx-atmosphere',
fxLighting: 'esengine/fx-lighting',
foliage: 'esengine/foliage',
+ water: 'esengine/water',
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 8624c93f8..b54b59350 100644
--- a/pipeline/tests/engine-installs.test.ts
+++ b/pipeline/tests/engine-installs.test.ts
@@ -25,6 +25,10 @@ describe('the engine modules a package installs', () => {
expect(engineInstalls({ subsystems: ['particles'] }).subpaths).toEqual([]);
});
+ it('takes water from a WaterBody, so a game without one carries none', () => {
+ expect(engineInstalls({ subsystems: ['water'] }).subpaths).toEqual(['esengine/water']);
+ });
+
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 1c87e0dc5..07b5dc639 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 · 1706 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1723 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -11038,6 +11038,11 @@ returnSpeed: number | undefined
world: World
```
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
## WEATHER_CLEAR — const @experimental
```
0
@@ -11073,6 +11078,72 @@ world: World
"world"
```
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
## WeChatSideModuleFactories — type @experimental
```
Partial<Record<SideModuleId, EmscriptenFactory>>
@@ -11835,6 +11906,16 @@ MotionDriver<AnimatorBlend2DMotion>
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -13420,6 +13501,16 @@ MeshRendererPlugin
(mode: string | undefined | null): BundleMode
```
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
## onCameraCommitChanged — function @beta
```
(fn: CameraCommitListener): () => void
@@ -14860,6 +14951,26 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
## weatherPresetId — function @beta
```
(name: string): number | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index a1333ff3b..81290845c 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 · 1725 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1742 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -11251,6 +11251,11 @@ returnSpeed: number | undefined
world: World
```
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
## WEATHER_CLEAR — const @experimental
```
0
@@ -11286,6 +11291,72 @@ world: World
"world"
```
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
## WeChatSideModuleFactories — type @experimental
```
Partial<Record<SideModuleId, EmscriptenFactory>>
@@ -12063,6 +12134,16 @@ MotionDriver<AnimatorBlend2DMotion>
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -13683,6 +13764,16 @@ MeshRendererPlugin
(mode: string | undefined | null): BundleMode
```
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
## onCameraCommitChanged — function @beta
```
(fn: CameraCommitListener): () => void
@@ -15123,6 +15214,26 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
## weatherPresetId — function @beta
```
(name: string): number | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index ff267e6d3..b68f5e242 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 · 1705 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1722 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -11033,6 +11033,11 @@ returnSpeed: number | undefined
world: World
```
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
## WEATHER_CLEAR — const @experimental
```
0
@@ -11068,6 +11073,72 @@ world: World
"world"
```
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
## WeChatSideModuleFactories — type @experimental
```
Partial<Record<SideModuleId, EmscriptenFactory>>
@@ -11830,6 +11901,16 @@ MotionDriver<AnimatorBlend2DMotion>
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -13425,6 +13506,16 @@ NodePlatformAdapter
(mode: string | undefined | null): BundleMode
```
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
## onCameraCommitChanged — function @beta
```
(fn: CameraCommitListener): () => void
@@ -14865,6 +14956,26 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
## weatherPresetId — function @beta
```
(name: string): number | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index cd2ecd6c7..cde3b7168 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 · 1727 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1744 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -11332,6 +11332,11 @@ returnSpeed: number | undefined
world: World
```
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
## WEATHER_CLEAR — const @experimental
```
0
@@ -11367,6 +11372,72 @@ world: World
"world"
```
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
## WeChatSideModuleFactories — type @experimental
```
Partial<Record<SideModuleId, EmscriptenFactory>>
@@ -12129,6 +12200,16 @@ MotionDriver<AnimatorBlend2DMotion>
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -13729,6 +13810,16 @@ MeshRendererPlugin
(mode: string | undefined | null): BundleMode
```
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
## onCameraCommitChanged — function @beta
```
(fn: CameraCommitListener): () => void
@@ -15169,6 +15260,26 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
## weatherPresetId — function @beta
```
(name: string): number | undefined
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
new file mode 100644
index 000000000..e65f9f948
--- /dev/null
+++ b/sdk/etc/water.api.md
@@ -0,0 +1,116 @@
+# API surface — esengine/water
+
+<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
+Symbols: 0 public · 0 beta · 17 experimental · 0 deprecated
+
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index af6c3ebf8..0d871f67c 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 · 1718 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1735 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -11040,6 +11040,11 @@ returnSpeed: number | undefined
world: World
```
+## WAVE_SET — const @experimental
+```
+readonly (readonly [number, number, number, number])[]
+```
+
## WEATHER_CLEAR — const @experimental
```
0
@@ -11075,6 +11080,72 @@ world: World
"world"
```
+## WaterBody — const @experimental
+```
+ComponentDef<WaterBodyData>
+```
+
+## WaterBodyData — interface @experimental
+```
+cellSize: number
+cells: number
+form: number
+material: number
+rings: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveHeight: number
+waveLength: number
+waveSpeed: number
+```
+
+## WaterForm — const @experimental
+```
+{ readonly Ocean: 0; readonly Lake: 1; readonly River: 2; }
+```
+
+## WaterPlugin — class @experimental
+```
+build: (app: App) => void
+cleanup: (app?: App) => void
+name: string
+static new (): WaterPlugin
+static prototype: WaterPlugin
+```
+
+## WaterSample — interface @experimental
+```
+depth: number
+entity: number
+inside: boolean
+normal: [number, number, number]
+surface: [number, number, number]
+```
+
+## Waters — class @experimental
+```
+@internal app_: App | null
+@internal built_: Map<number, Built>
+heightAt: (x: number, z: number) => number | null
+sample: (x: number, y: number, z: number) => WaterSample | null
+static new (): Waters
+static prototype: Waters
+```
+
+## WatersRes — const @experimental
+```
+ResourceDef<Waters>
+```
+
+## WaveParams — interface @experimental
+```
+direction: number
+height: number
+length: number
+speed: number
+```
+
## WeChatRuntimeConfig — interface @experimental
```
aot: { module: string; manifest: AotManifest; } | undefined
@@ -11861,6 +11932,16 @@ MotionDriver<AnimatorBlend2DMotion>
(source: MeshData, plants: readonly Plant[], paint?: BladeParams["paint"]): MeshData
```
+## buildOceanMesh — function @experimental
+```
+(cells: number, rings: number, cellSize: number): MeshData
+```
+
+## buildRectMesh — function @experimental
+```
+(sizeX: number, sizeZ: number, cellSize: number): MeshData
+```
+
## buildText — function @experimental
```
(init?: TextInit): TextData
@@ -13456,6 +13537,16 @@ MeshRendererPlugin
(mode: string | undefined | null): BundleMode
```
+## oceanReach — function @experimental
+```
+(cells: number, rings: number, cellSize: number): number
+```
+
+## oceanSnap — function @experimental
+```
+(rings: number, cellSize: number): number
+```
+
## onCameraCommitChanged — function @beta
```
(fn: CameraCommitListener): () => void
@@ -14896,6 +14987,26 @@ VideoPlugin
(category: string, message: string, data?: unknown): void
```
+## waterPlugin — const @experimental
+```
+Plugin
+```
+
+## waveFade — function @experimental
+```
+(length: number, cell: number): number
+```
+
+## waveHeight — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number, cell?: number): number
+```
+
+## waveSlope — function @experimental
+```
+(p: WaveParams, x: number, z: number, time: number): [number, number]
+```
+
## weatherPresetId — function @beta
```
(name: string): number | undefined
diff --git a/sdk/package.json b/sdk/package.json
index 6c44df08a..bb97220cd 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -23,6 +23,7 @@
"./dist/fx-atmosphere/index.js",
"./dist/fx-lighting/index.js",
"./dist/foliage/index.js",
+ "./dist/water/index.js",
"./dist/logic/index.js",
"./dist/debug-channel/index.js",
"./dist/ai/index.js",
@@ -101,6 +102,10 @@
"import": "./dist/foliage/index.js",
"types": "./dist/foliage/index.d.ts"
},
+ "./water": {
+ "import": "./dist/water/index.js",
+ "types": "./dist/water/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 1a1160b63..93486529c 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', 'tilemap', 'postProcess', 'timeline',
+ 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', '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 a26a09bac..07b5697e8 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -787,6 +787,12 @@ export {
export {
Foliage, FoliageField, FoliageRes, FoliagePlugin, foliagePlugin, type FoliageData,
} from './foliage/foliagePlugin';
+// Water is an optional module too (`esengine/water`).
+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 { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from './water/waterMesh';
export {
scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
diff --git a/sdk/src/platform/nativeModuleRegistry.ts b/sdk/src/platform/nativeModuleRegistry.ts
index 2725372c4..17822f492 100644
--- a/sdk/src/platform/nativeModuleRegistry.ts
+++ b/sdk/src/platform/nativeModuleRegistry.ts
@@ -30,6 +30,7 @@ import * as FxBasicModule from '../postprocess/fxBasic';
import * as FxAtmosphereModule from '../postprocess/fxAtmosphere';
import * as FxLightingModule from '../postprocess/fxLighting';
import * as FoliageModule from '../foliage';
+import * as WaterModule from '../water';
import * as ScriptGraphModule from '../logic';
import * as AiModule from '../ai';
import * as ReplicationModule from '../net/replication';
@@ -55,6 +56,7 @@ export const NATIVE_MODULE_NAMESPACES: Readonly<Record<string, unknown>> = {
'esengine/fx-atmosphere': FxAtmosphereModule,
'esengine/fx-lighting': FxLightingModule,
'esengine/foliage': FoliageModule,
+ 'esengine/water': WaterModule,
'esengine/logic': ScriptGraphModule,
'esengine/ai': AiModule,
'esengine/replication': ReplicationModule,
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 98eff904b..d3dbc062e 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -724,9 +724,68 @@ const WATER = `#pragma shader "Water"
#pragma param u_foamCrest float default(0.5) range(0,1) ui(slider)
// The depth taken where the device could not measure one.
#pragma param u_fallbackDepth float default(4) range(0,200) ui(slider)
+// Where the waves are measured. 0 is the world's xz plane, which is what a flat plane of water wants. 1 is the body's own space: the mesh's uv is its
+// local x and z (plus u_origin, which a body that follows the camera moves so the waves stay put), and the waves then lift the geometry and follow the
+// body's tilt, which is what the WaterBody component builds.
+#pragma param u_waveSpace float default(0) range(0,1) ui(slider)
+#pragma param u_origin vec2 default(0,0)
+// The cell size of the mesh's finest ring, for a body the WaterBody component built: a vertex in a coarser ring (its colour's red says which) fades the
+// waves it cannot draw, those shorter than six of its cells. 0 draws every wave at every vertex.
+#pragma param u_cellSize float default(0) range(0,100) ui(slider)
#pragma param u_sceneColor texture default(white)
#pragma param u_sceneDepthMap texture default(white) texel(data)
+#pragma vertexbounds 16
+#pragma vertexoffset
+// The height of the waves at p: the same four peaked sines the fragment takes its slope from, so the surface that is lit is the one that is drawn.
+float waterWaveHeight(vec2 p, float time, float cell) {
+ const vec4 SET[4] = vec4[4](vec4(0.0, 1.0, 1.0, 1.0), vec4(28.0, 0.62, 0.55, 1.1), vec4(-37.0, 0.37, 0.3, 1.2), vec4(71.0, 0.21, 0.15, 1.35));
+ float height = 0.0;
+ float base = radians(u_waveDirection);
+ for (int i = 0; i < 4; ++i) {
+ float length_ = u_waveLength * SET[i].y;
+ float k = 6.2831853 / length_;
+ float a = base + radians(SET[i].x);
+ vec2 d = vec2(sin(a), cos(a));
+ float omega = sqrt(9.8 * k) * u_waveSpeed * SET[i].w;
+ float fade = cell > 0.0 ? clamp((length_ / cell - 3.0) / 3.0, 0.0, 1.0) : 1.0;
+ height += u_waveHeight * SET[i].z * exp(sin(k * dot(d, p) - omega * time) - 1.0) * fade;
+ }
+ return height;
+}
+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;
+ local.y += waterWaveHeight(uv + u_origin, u_time.x, cell);
+}
+#pragma end
+
+#pragma vertexoffset wgsl
+fn waterWaveHeight(p : vec2f, time : f32, cell : f32) -> f32 {
+ var wave = array<vec4f, 4>(vec4f(0.0, 1.0, 1.0, 1.0), vec4f(28.0, 0.62, 0.55, 1.1), vec4f(-37.0, 0.37, 0.3, 1.2), vec4f(71.0, 0.21, 0.15, 1.35));
+ var height = 0.0;
+ let base = radians(mc.u_waveDirection);
+ for (var i : i32 = 0; i < 4; i = i + 1) {
+ let spec = wave[i];
+ let span = mc.u_waveLength * spec.y;
+ let k = 6.2831853 / span;
+ let a = base + radians(spec.x);
+ let d = vec2f(sin(a), cos(a));
+ let omega = sqrt(9.8 * k) * mc.u_waveSpeed * spec.w;
+ var fade = 1.0;
+ if (cell > 0.0) { fade = clamp((span / cell - 3.0) / 3.0, 0.0, 1.0); }
+ height = height + mc.u_waveHeight * spec.z * exp(sin(k * dot(d, p) - omega * time) - 1.0) * fade;
+ }
+ return height;
+}
+fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {
+ if (mc.u_waveSpace < 0.5) { return; }
+ var cell = 0.0;
+ if (mc.u_cellSize > 0.0) { cell = mc.u_cellSize * exp2(es_vertexColor.r * 7.0); }
+ (*local).y = (*local).y + waterWaveHeight(uv + mc.u_origin, tc.u_time.x, cell);
+}
+#pragma end
+
#pragma fragment
precision highp float;
@@ -807,17 +866,26 @@ void main() {
float waterDist = u_camera.w > 0.5 ? length(P - u_camera.xyz) : -dot(P, u_camera.xyz);
// The surface: the long waves, then the ripples they carry, flattened with distance so the far water is calm rather than aliased.
+ vec2 wp = u_waveSpace > 0.5 ? v_texCoord + u_origin : P.xz;
float crest;
- vec2 slope = waveSlope(P.xz, time, waterDist, crest);
+ vec2 slope = waveSlope(wp, time, waterDist, crest);
float rippleFade = clamp(1.0 - waterDist / (u_rippleLength * 180.0), 0.0, 1.0);
float e = u_rippleLength * 0.1;
- vec2 ripple = vec2(ripples(P.xz + vec2(e, 0.0), time) - ripples(P.xz - vec2(e, 0.0), time),
- ripples(P.xz + vec2(0.0, e), time) - ripples(P.xz - vec2(0.0, e), time)) / (2.0 * e);
+ 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
+ if (u_waveSpace > 0.5) {
+ // The body's own frame: the mesh's normal is its up (the hook lifts the vertices and leaves it alone), and the slope leans along
+ // its uv axes, which are its local x and z.
+ Ngeo = normalize(v_worldNormal);
+ N = perturbNormal(Ngeo, P, v_texCoord, normalize(vec3(-slope.x, -slope.y, 1.0)));
+ }
+#endif
// Seen from below, the surface turns over.
- if (viewDir.y < 0.0) { N = -N; Ngeo = -Ngeo; }
+ if (dot(viewDir, Ngeo) < 0.0) { N = -N; Ngeo = -Ngeo; }
// What is behind the water: the picture and the distance, where the frame took them.
bool haveColor = texture(u_sceneColor, vec2(0.5)).a < 0.75;
@@ -853,7 +921,7 @@ void main() {
// Foam: along the shore, where the water is shallow, broken by noise that moves; and on the crests of the waves.
float vertical = column * max(abs(viewDir.y), 0.15);
float foamScale = 1.0 / (u_rippleLength * 1.2);
- float breakup = waterNoise(P.xz * foamScale + vec2(time * 0.07, time * 0.05)) * 0.6 + waterNoise(P.xz * foamScale * 3.0 - vec2(time * 0.13, 0.0)) * 0.4;
+ float breakup = waterNoise(wp * foamScale + vec2(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2(time * 0.13, 0.0)) * 0.4;
float pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);
float shore = haveDepth && u_foamWidth > 0.0 ? clamp((1.0 - vertical / (u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0) : 0.0;
float onCrest = u_foamCrest > 0.0 ? smoothstep(1.0 - 0.3 * u_foamCrest, 1.0, crest) * smoothstep(0.35, 0.75, breakup) : 0.0;
@@ -954,16 +1022,24 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
var waterDist = -dot(P, frame.camera.xyz);
if (frame.camera.w > 0.5) { waterDist = length(P - frame.camera.xyz); }
- let waves = waveSlope(P.xz, time, waterDist);
+ var wp = P.xz;
+ if (mc.u_waveSpace > 0.5) { wp = v.v_texCoord + mc.u_origin; }
+ let waves = waveSlope(wp, time, waterDist);
var slope = waves.slope;
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(P.xz + vec2f(eps, 0.0), time) - ripples(P.xz - vec2f(eps, 0.0), time),
- ripples(P.xz + vec2f(0.0, eps), time) - ripples(P.xz - vec2f(0.0, eps), time)) / (2.0 * eps);
+ 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 N = normalize(vec3f(-slope.x, 1.0, -slope.y));
var Ngeo = vec3f(0.0, 1.0, 0.0);
- if (viewDir.y < 0.0) { N = -N; Ngeo = -Ngeo; }
+#ifdef MESH_NORMALS
+ if (mc.u_waveSpace > 0.5) {
+ Ngeo = normalize(v.v_worldNormal);
+ N = perturbNormal(Ngeo, P, v.v_texCoord, normalize(vec3f(-slope.x, -slope.y, 1.0)));
+ }
+#endif
+ if (dot(viewDir, Ngeo) < 0.0) { N = -N; Ngeo = -Ngeo; }
let haveColor = textureSampleLevel(u_sceneColor, u_sceneColor_s, vec2f(0.5), 0.0).a < 0.75;
let haveDepth = haveColor && textureSampleLevel(u_sceneDepthMap, u_sceneDepthMap_s, vec2f(0.5), 0.0).a < 0.75;
@@ -999,7 +1075,7 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
let vertical = column * max(abs(viewDir.y), 0.15);
let foamScale = 1.0 / (mc.u_rippleLength * 1.2);
- let breakup = waterNoise(P.xz * foamScale + vec2f(time * 0.07, time * 0.05)) * 0.6 + waterNoise(P.xz * foamScale * 3.0 - vec2f(time * 0.13, 0.0)) * 0.4;
+ let breakup = waterNoise(wp * foamScale + vec2f(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2f(time * 0.13, 0.0)) * 0.4;
let pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);
var shore = 0.0;
if (haveDepth && mc.u_foamWidth > 0.0) { shore = clamp((1.0 - vertical / (mc.u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0); }
diff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.ts
index 0a1b08525..fd300e6ee 100644
--- a/sdk/src/runtime/optionalPlugins.ts
+++ b/sdk/src/runtime/optionalPlugins.ts
@@ -26,6 +26,7 @@ import { registerLightingEffectSources } from '../postprocess/sources/lighting';
import { registerTimelineSupport } from '../timeline/timelineSupport';
import { registerTerrainSupport } from '../terrain/terrainSupport';
import { registerFoliageSupport } from '../foliage/foliageSupport';
+import { registerWaterSupport } from '../water/waterSupport';
import { registerScriptGraphSupport } from '../logic/logicSupport';
import { registerAiSupport } from '../ai/aiSupport';
import { registerReplicationSupport } from '../net/replication/replicationSupport';
@@ -44,6 +45,7 @@ export function installOptionalPlugins(): void {
registerLightingEffectSources();
registerTerrainSupport();
registerFoliageSupport();
+ registerWaterSupport();
registerScriptGraphSupport();
registerAiSupport();
registerReplicationSupport();
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
new file mode 100644
index 000000000..ab976c1ce
--- /dev/null
+++ b/sdk/src/water/index.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export {
+ WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
+} from './waterPlugin';
+export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './waves';
+export { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from './waterMesh';
+
+// Importing this subpath INSTALLS water — see tilemap/index.ts.
+import { registerWaterSupport } from './waterSupport';
+
+registerWaterSupport();
diff --git a/sdk/src/water/waterMesh.ts b/sdk/src/water/waterMesh.ts
new file mode 100644
index 000000000..cd985b3fe
--- /dev/null
+++ b/sdk/src/water/waterMesh.ts
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waterMesh.ts
+ * @brief The geometry of a body of water: a flat grid for a lake, rings of coarsening grids for an ocean.
+ *
+ * @details Both lie in the body's xz plane facing up, with the uv the position itself (so the Water shader's body space is local x and
+ * z), and the vertex colour's red the number of the ring the vertex is in, in sevenths (`cell * 2^(red * 7)` is its cell
+ * size): the Water shader's vertex hook fades the waves a coarse ring cannot draw by it.
+ *
+ * An ocean is rings, each a grid of the same number of cells with twice the cell size of the one inside it and a hole where that one
+ * sits. Where two rings meet the coarse one has half the vertices along the edge, so the surfaces can part there by what the waves
+ * do between its vertices; the fade keeps that to waves the coarse ring can already draw.
+ */
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
+
+/** One grid of water: its half-extent, its cell size, the hole in its middle (half-extent, 0 for none) and its ring number. */
+interface Grid {
+ half: number;
+ cell: number;
+ hole: number;
+ ring: number;
+}
+
+/** A flat rectangle of water, `sizeX` by `sizeZ`, centred on its origin. */
+export function buildRectMesh(sizeX: number, sizeZ: number, cellSize: number): MeshData {
+ const cellsX = Math.max(1, Math.round(sizeX / cellSize)), cellsZ = Math.max(1, Math.round(sizeZ / cellSize));
+ const positions: number[] = [], colors: number[] = [];
+ for (let j = 0; j <= cellsZ; j++) {
+ for (let i = 0; i <= cellsX; i++) {
+ positions.push(-sizeX / 2 + (i / cellsX) * sizeX, 0, -sizeZ / 2 + (j / cellsZ) * sizeZ);
+ colors.push(0, 0, 0, 1);
+ }
+ }
+ const indices: number[] = [];
+ const at = (i: number, j: number): number => j * (cellsX + 1) + i;
+ for (let j = 0; j < cellsZ; j++) {
+ for (let i = 0; i < cellsX; i++) quad(indices, at(i, j), at(i, j + 1), at(i + 1, j), at(i + 1, j + 1));
+ }
+ return pack(positions, colors, indices);
+}
+
+/**
+ * An ocean of `rings` rings of `cells` cells a side (a multiple of four), the innermost with `cellSize` cells. It reaches
+ * `cells * cellSize * 2^(rings - 1) / 2` out from its centre.
+ */
+export function buildOceanMesh(cells: number, rings: number, cellSize: number): MeshData {
+ const n = Math.max(4, Math.round(cells / 4) * 4);
+ const levels = Math.min(8, Math.max(1, Math.floor(rings)));
+ const grids: Grid[] = [];
+ for (let ring = 0; ring < levels; ring++) {
+ const cell = cellSize * 2 ** ring;
+ grids.push({ half: (n * cell) / 2, cell, hole: ring === 0 ? 0 : (n * cell) / 4, ring });
+ }
+ const positions: number[] = [], colors: number[] = [], indices: number[] = [];
+ for (const grid of grids) {
+ const base = positions.length / 3;
+ const stride = n + 1;
+ for (let j = 0; j <= n; j++) {
+ for (let i = 0; i <= n; i++) {
+ positions.push(-grid.half + i * grid.cell, 0, -grid.half + j * grid.cell);
+ colors.push(grid.ring / 7, 0, 0, 1);
+ }
+ }
+ for (let j = 0; j < n; j++) {
+ for (let i = 0; i < n; i++) {
+ // A cell whose middle is in the hole belongs to the finer ring inside.
+ const cx = -grid.half + (i + 0.5) * grid.cell, cz = -grid.half + (j + 0.5) * grid.cell;
+ if (grid.hole > 0 && Math.abs(cx) < grid.hole && Math.abs(cz) < grid.hole) continue;
+ quad(indices, base + j * stride + i, base + (j + 1) * stride + i, base + j * stride + i + 1, base + (j + 1) * stride + i + 1);
+ }
+ }
+ }
+ return pack(positions, colors, indices);
+}
+
+/** The outer half-extent of an ocean built with these numbers. */
+export function oceanReach(cells: number, rings: number, cellSize: number): number {
+ const n = Math.max(4, Math.round(cells / 4) * 4);
+ return (n * cellSize * 2 ** (Math.min(8, Math.max(1, Math.floor(rings))) - 1)) / 2;
+}
+
+/** The cell size of the coarsest ring: the lattice an ocean follows its camera on, so every ring stays aligned. */
+export function oceanSnap(rings: number, cellSize: number): number {
+ return cellSize * 2 ** (Math.min(8, Math.max(1, Math.floor(rings))) - 1);
+}
+
+/** Two triangles over a cell, facing up (+y) for the vertex order `p00, p01 (+z), p10 (+x), p11`. */
+function quad(indices: number[], p00: number, p01: number, p10: number, p11: number): void {
+ indices.push(p00, p01, p10, p10, p01, p11);
+}
+
+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
new file mode 100644
index 000000000..ec6a59f69
--- /dev/null
+++ b/sdk/src/water/waterPlugin.ts
@@ -0,0 +1,327 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waterPlugin.ts
+ * @brief A body of water: a component that says what it is, a mesh the plugin builds for it, and the surface it answers questions about.
+ *
+ * @details The `WaterBody` component names a form (an ocean, a lake) and the waves; this builds the geometry as a child entity, gives it a
+ * material instance of its own (the Water material with the waves, the body's space and its cell size written in), and keeps
+ * the instance in step with the component every frame, so editing a field moves the water at once.
+ *
+ * The waves are the ones the Water shader draws: `waves.ts` is the same formula, and {@link Waters.sample} answers from it in the body's
+ * own frame, so a floating object, a camera under the surface and a splash all read the surface that is on the screen. The body's
+ * transform places and tilts it (waves follow its up), and an ocean's mesh follows the camera on a lattice its rings line up on,
+ * with the material's origin moved by as much so the waves stay put in the world.
+ */
+import type { App, Plugin } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { defineResource, Time } from '../ecs/resource';
+import {
+ defineComponent, Camera, MeshRenderer, Transform,
+ type ComponentDef, type CameraData, type MeshRendererData, type TransformData,
+} from '../ecs/component';
+import { Assets } from '../asset/AssetPlugin';
+import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';
+import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';
+import { BlendMode } from '../render/blend';
+import { log } from '../util/logger';
+import type { Entity } from '../types';
+import { waveHeight, waveSlope, type WaveParams } from './waves';
+import { buildOceanMesh, buildRectMesh, oceanSnap } from './waterMesh';
+
+/** What a body of water is. River arrives with the spline it follows. */
+export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
+
+/** The fields of the `WaterBody` component. @experimental */
+export interface WaterBodyData {
+ /** {@link WaterForm}. */
+ form: number;
+ /** A material on the Water shader. Empty uses the stock one. */
+ material: number;
+ /** A lake's extent along x and z, centred on its entity. An ocean has none: it follows the camera. */
+ sizeX: number;
+ sizeZ: number;
+ /** The cell size of the finest ring, and (ocean) how many cells a ring has a side and how many rings there are. */
+ cellSize: number;
+ cells: number;
+ rings: 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;
+ waveSpeed: number;
+ waveDirection: number;
+}
+
+/**
+ * A body of water. Presence is the opt-in; its geometry is a child, rebuilt when the shape changes.
+ *
+ * @experimental
+ */
+export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
+ form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, cellSize: 1, cells: 64, rings: 5,
+ 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.' },
+ 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.' },
+ cellSize: { min: 0.05, category: 'Detail', tooltip: 'The cell size of the finest ring. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).' },
+ cells: { min: 4, max: 256, step: 4, category: 'Detail', tooltip: 'Cells along a ring\'s side (an ocean).' },
+ rings: { min: 1, max: 8, step: 1, category: 'Detail', tooltip: 'Rings of an ocean, each twice as coarse as the one inside it.' },
+ waveHeight: { min: 0, max: 8, category: 'Waves', tooltip: 'The height of the tallest wave, in world units.' },
+ waveLength: { min: 0.5, max: 300, category: 'Waves', tooltip: 'The length of the longest wave.' },
+ waveSpeed: { min: 0, max: 4, category: 'Waves', tooltip: 'A multiplier on how fast the waves travel.' },
+ waveDirection: { min: 0, max: 360, category: 'Waves', tooltip: 'The heading of the waves, in degrees.' },
+ },
+});
+
+/** What {@link Waters.sample} answers. */
+export interface WaterSample {
+ /** The body's entity. */
+ entity: Entity;
+ /** How far the point is above the surface along the body's up (negative under it), in world units. */
+ depth: number;
+ /** The surface's normal at the point, in world space. */
+ normal: [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). */
+ inside: boolean;
+}
+
+/** What the plugin knows about one body it has built. */
+interface Built {
+ signature: string;
+ data: WaterBodyData;
+ mesh: number;
+ child: Entity;
+ instance: number;
+ epoch: number;
+ pending: boolean;
+}
+
+/** Run-time access to the water: where its surface is at a point, for what floats on it or swims in it. */
+export class Waters {
+ /** @internal */ readonly built_ = new Map<Entity, Built>();
+ /** @internal */ app_: App | null = null;
+
+ /**
+ * The surface of the body that holds `(x, y, z)`: how far above it the point is (negative under), the surface's normal and the point on
+ * it straight above or below along the body's up. Null where there is no water. The body's position, rotation and uniform scale are taken
+ * into account, and the waves are read at the instant of the frame.
+ */
+ sample(x: number, y: number, z: number): WaterSample | null {
+ const world = this.app_?.world;
+ if (!world) return null;
+ const time = this.app_!.getResource(Time).elapsed;
+ for (const [entity, built] of this.built_) {
+ if (!world.valid(entity)) continue;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ if (!t) continue;
+ const scale = t.worldScale.y || 1;
+ const q = toLocal(t, x, y, z, scale);
+ const d = built.data;
+ const inside = d.form === WaterForm.Ocean || (Math.abs(q[0]) <= d.sizeX / 2 && Math.abs(q[2]) <= d.sizeZ / 2);
+ if (!inside) continue;
+ const params = paramsOf(d);
+ const h = waveHeight(params, q[0], q[2], time);
+ const [sx, sz] = waveSlope(params, q[0], q[2], time);
+ 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 null;
+ }
+
+ /** The world height of the surface above or below (x, z) for an untilted body, or null where there is none. */
+ heightAt(x: number, z: number): number | null {
+ const world = this.app_?.world;
+ if (!world) return null;
+ for (const entity of this.built_.keys()) {
+ if (!world.valid(entity)) continue;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ const s = t ? this.sample(x, t.worldPosition.y, z) : null;
+ if (s) return s.surface[1];
+ }
+ return null;
+ }
+}
+
+/** The resource the plugin installs. @experimental */
+export const WatersRes = defineResource<Waters>(new Waters(), 'Waters');
+
+function paramsOf(d: WaterBodyData): WaveParams {
+ return { height: d.waveHeight, length: d.waveLength, speed: d.waveSpeed, direction: d.waveDirection };
+}
+
+type Quat = { x: number; y: number; z: number; w: number };
+
+/** `v` turned by `q`. */
+function rotate(q: Quat, vx: number, vy: number, vz: number): [number, number, number] {
+ const tx = 2 * (q.y * vz - q.z * vy), ty = 2 * (q.z * vx - q.x * vz), tz = 2 * (q.x * vy - q.y * vx);
+ return [vx + q.w * tx + (q.y * tz - q.z * ty), vy + q.w * ty + (q.z * tx - q.x * tz), vz + q.w * tz + (q.x * ty - q.y * tx)];
+}
+
+function toLocal(t: TransformData, x: number, y: number, z: number, scale: number): [number, number, number] {
+ const inv = { x: -t.worldRotation.x, y: -t.worldRotation.y, z: -t.worldRotation.z, w: t.worldRotation.w };
+ const r = rotate(inv, x - t.worldPosition.x, y - t.worldPosition.y, z - t.worldPosition.z);
+ return [r[0] / scale, r[1] / scale, r[2] / scale];
+}
+
+function fromLocal(t: TransformData, x: number, y: number, z: number, scale: number): [number, number, number] {
+ const r = rotate(t.worldRotation, x * scale, y * scale, z * scale);
+ return [r[0] + t.worldPosition.x, r[1] + t.worldPosition.y, r[2] + t.worldPosition.z];
+}
+
+/** 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): string {
+ return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.cellSize, d.cells, d.rings, d.material]);
+}
+
+export class WaterPlugin implements Plugin {
+ name = 'water';
+
+ /** The stock material every body without one of its own is an instance of, made once from the Water shader. */
+ private stock_ = 0;
+ private stockPending_ = false;
+
+ build(app: App): void {
+ const waters = new Waters();
+ waters.app_ = app;
+ app.insertResource(WatersRes, waters);
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
+ if (!app.hasResource(Assets)) return;
+ this.sweep(app, waters);
+ const time = app.getResource(Time).elapsed;
+ 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);
+ let built = waters.built_.get(entity);
+ if (!built || built.signature !== signature) {
+ if (built) this.destroy(app, built);
+ built = { signature, data: { ...data }, mesh: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
+ waters.built_.set(entity, built);
+ }
+ built.data = { ...data };
+ if (!built.child && !built.pending) void this.build_(app, entity, built);
+ if (built.child && built.instance) this.update(app, entity, built, eye, time);
+ }
+ }, { name: 'WaterSystem' }));
+ }
+
+ cleanup(app?: App): void {
+ if (!app?.hasResource(WatersRes)) return;
+ const waters = app.getResource(WatersRes);
+ for (const built of waters.built_.values()) this.destroy(app, built);
+ waters.built_.clear();
+ if (this.stock_) Material.release(this.stock_);
+ this.stock_ = 0;
+ }
+
+ /** The world position of the active camera, or null where there is none (the editor's scene view has no entity). */
+ private eye(app: App): [number, number, number] | null {
+ for (const entity of app.world.getEntitiesWithComponents([Camera, Transform])) {
+ const camera = app.world.get(entity, Camera) as CameraData;
+ if (!camera.isActive) continue;
+ const t = app.world.get(entity, Transform) as TransformData;
+ return [t.worldPosition.x, t.worldPosition.y, t.worldPosition.z];
+ }
+ return null;
+ }
+
+ /** The material every body without one is an instance of: the Water shader, compiled once. */
+ private async stock(app: App): Promise<number> {
+ if (this.stock_) return this.stock_;
+ const assets = app.getResource(Assets);
+ const source = await assets.load<MaterialShaderSource>('material-shader', 'builtin:water');
+ const shader = source.compile([]);
+ if (this.stock_) return this.stock_;
+ this.stock_ = Material.createFromAsset({
+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:water', blendMode: BlendMode.Normal,
+ depthTest: true, depthWrite: true, cull: 0, properties: {},
+ }, shader);
+ return this.stock_;
+ }
+
+ private async build_(app: App, entity: Entity, built: Built): Promise<void> {
+ built.pending = true;
+ const epoch = built.epoch;
+ try {
+ const source = built.data.material || await this.stock(app);
+ if (built.epoch !== epoch || !app.world.valid(entity)) return;
+ const d = built.data;
+ const assets = app.getResource(Assets);
+ const mesh = assets.createMesh(d.form === WaterForm.Ocean
+ ? buildOceanMesh(d.cells, d.rings, d.cellSize)
+ : buildRectMesh(d.sizeX, d.sizeZ, d.cellSize));
+ if (mesh === 0) { log.warn('water', 'the engine refused the water geometry'); return; }
+ const instance = Material.createInstance(source);
+ if (instance === 0) { assets.releaseBuiltMesh(mesh); log.warn('water', 'the water material could not be instanced'); return; }
+ built.mesh = mesh;
+ built.instance = instance;
+ const child = app.world.spawn('Water');
+ app.world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
+ app.world.insert(child, MeshRenderer, {
+ mesh, material: instance, lit: true, opaque: false, cullBackfaces: false, color: { r: 1, g: 1, b: 1, a: 1 },
+ } as Partial<MeshRendererData>);
+ app.world.setParent(child, entity);
+ built.child = child;
+ } catch (e) {
+ log.error('water', 'building the water failed', e);
+ } finally {
+ built.pending = false;
+ }
+ }
+
+ /** Writes the component into the instance, and moves an ocean's mesh to the camera. */
+ private update(app: App, entity: Entity, built: Built, eye: [number, number, number] | null, time: number): void {
+ const d = built.data;
+ let ox = 0, oz = 0;
+ if (d.form === WaterForm.Ocean && eye) {
+ const t = app.world.get(entity, Transform) as TransformData;
+ const q = toLocal(t, eye[0], eye[1], eye[2], t.worldScale.y || 1);
+ const snap = oceanSnap(d.rings, d.cellSize);
+ ox = Math.round(q[0] / snap) * snap;
+ oz = Math.round(q[2] / snap) * snap;
+ }
+ const child = app.world.get(built.child, Transform) as TransformData;
+ if (child.position.x !== ox || child.position.z !== oz) {
+ app.world.insert(built.child, Transform, { ...child, position: { x: ox, y: 0, z: oz } });
+ }
+ const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(built.instance, name, value); };
+ set('u_waveSpace', 1);
+ set('u_origin', { x: ox, y: oz });
+ set('u_cellSize', d.cellSize);
+ set('u_waveHeight', d.waveHeight);
+ set('u_waveLength', d.waveLength);
+ set('u_waveSpeed', d.waveSpeed);
+ set('u_waveDirection', d.waveDirection);
+ void time;
+ }
+
+ private destroy(app: App, built: Built): void {
+ built.epoch++;
+ if (built.child && app.world.valid(built.child)) app.world.despawn(built.child);
+ if (built.instance) Material.release(built.instance);
+ if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
+ built.child = 0 as Entity;
+ built.instance = 0;
+ built.mesh = 0;
+ }
+
+ /** Releases the geometry of a body whose entity is gone. */
+ private sweep(app: App, waters: Waters): void {
+ for (const [entity, built] of waters.built_) {
+ if (app.world.valid(entity) && app.world.has(entity, WaterBody)) continue;
+ this.destroy(app, built);
+ waters.built_.delete(entity);
+ }
+ }
+}
+
+export const waterPlugin: Plugin = new WaterPlugin();
diff --git a/sdk/src/water/waterSupport.ts b/sdk/src/water/waterSupport.ts
new file mode 100644
index 000000000..feb566623
--- /dev/null
+++ b/sdk/src/water/waterSupport.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waterSupport.ts — what a build that ships water tells the core.
+ *
+ * A call, not a file's side effect — see tilemap/tilemapSupport.ts.
+ */
+import { addEntryPlugin } from '../runtime/entryPlugins';
+import { WaterPlugin } from './waterPlugin';
+
+export function registerWaterSupport(): void {
+ addEntryPlugin('water', () => new WaterPlugin());
+}
diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.ts
new file mode 100644
index 000000000..d1bf1f67e
--- /dev/null
+++ b/sdk/src/water/waves.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file waves.ts
+ * @brief The height of the water, in one formula the CPU and the Water shader share.
+ *
+ * @details Four peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) a few directions apart, each with its own length,
+ * weight and speed taken from four numbers. The shader's `waterWaveHeight` and `waveSlope` are the same arithmetic written in
+ * GLSL and WGSL, so what a floating object reads here is what is drawn there. Change a constant in one place and the other
+ * two places have to change with it; the table below is the one the shaders repeat.
+ *
+ * Everything here is in the body's own space: x and z along its surface, the height along its up.
+ */
+
+/** Each wave of the set: its heading off the base direction (degrees), its length and its height as shares of the body's, and its speed share. */
+export const WAVE_SET: readonly (readonly [number, number, number, number])[] = [
+ [0, 1, 1, 1],
+ [28, 0.62, 0.55, 1.1],
+ [-37, 0.37, 0.3, 1.2],
+ [71, 0.21, 0.15, 1.35],
+];
+
+/** What shapes the waves: the fields of a WaterBody, and the parameters of the Water material they are written to. */
+export interface WaveParams {
+ /** Height of the tallest wave, in world units. */
+ height: number;
+ /** Length of the longest wave. */
+ length: number;
+ /** A multiplier on how fast they travel. */
+ speed: number;
+ /** The base heading, in degrees. */
+ direction: number;
+}
+
+const TAU = Math.PI * 2;
+const GRAVITY = 9.8;
+
+/**
+ * How much of a wave a mesh of `cell`-sized cells can draw: none below three cells to a wavelength, all of it from six. The shader applies the
+ * same ramp per vertex with the cell size of the ring the vertex is in, so a coarse far ring does not alias; `cell` 0 draws every wave.
+ */
+export function waveFade(length: number, cell: number): number {
+ if (cell <= 0) return 1;
+ return Math.min(Math.max((length / cell - 3) / 3, 0), 1);
+}
+
+/** The surface's height above the body's rest plane at (x, z), `time` seconds in. */
+export function waveHeight(p: WaveParams, x: number, z: number, time: number, cell = 0): number {
+ let height = 0;
+ const base = p.direction * Math.PI / 180;
+ for (const [heading, lengthShare, heightShare, speedShare] of WAVE_SET) {
+ const length = p.length * lengthShare;
+ const k = TAU / length;
+ const a = base + heading * Math.PI / 180;
+ const omega = Math.sqrt(GRAVITY * k) * p.speed * speedShare;
+ const theta = k * (Math.sin(a) * x + Math.cos(a) * z) - omega * time;
+ height += p.height * heightShare * Math.exp(Math.sin(theta) - 1) * waveFade(length, cell);
+ }
+ return height;
+}
+
+/** The slope of the surface at (x, z): how fast its height changes along x and along z. */
+export function waveSlope(p: WaveParams, x: number, z: number, time: number): [number, number] {
+ let sx = 0, sz = 0;
+ const base = p.direction * Math.PI / 180;
+ for (const [heading, lengthShare, heightShare, speedShare] of WAVE_SET) {
+ const k = TAU / (p.length * lengthShare);
+ const a = base + heading * Math.PI / 180;
+ const dx = Math.sin(a), dz = Math.cos(a);
+ const omega = Math.sqrt(GRAVITY * k) * p.speed * speedShare;
+ const theta = k * (dx * x + dz * z) - omega * time;
+ const rise = p.height * heightShare * Math.exp(Math.sin(theta) - 1) * Math.cos(theta) * k;
+ sx += dx * rise;
+ sz += dz * rise;
+ }
+ return [sx, sz];
+}
diff --git a/sdk/tests/water.test.ts b/sdk/tests/water.test.ts
new file mode 100644
index 000000000..694f52aaf
--- /dev/null
+++ b/sdk/tests/water.test.ts
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from '../src/water/waves';
+import { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from '../src/water/waterMesh';
+import { MeshChannel } from '../src/asset/meshFormat';
+import type { MeshData } from '../src/asset/meshFormat';
+
+const params: WaveParams = { height: 0.8, length: 14, speed: 1, direction: 30 };
+
+function positions(mesh: MeshData): 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;
+}
+
+function colorRed(mesh: MeshData, i: number): number {
+ const channel = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!;
+ return mesh.vertices[i * mesh.vertexStride + channel.offset]! / 255;
+}
+
+/** Twice the signed area of a triangle on the xz plane, and the sign of its normal's y: positive faces up. */
+function facing(p: Float32Array, a: number, b: number, c: number): number {
+ const ux = p[b * 3]! - p[a * 3]!, uz = p[b * 3 + 2]! - p[a * 3 + 2]!;
+ const vx = p[c * 3]! - p[a * 3]!, vz = p[c * 3 + 2]! - p[a * 3 + 2]!;
+ return uz * vx - ux * vz;
+}
+
+describe('the waves', () => {
+ it('is the sum of the set\'s four peaked sines', () => {
+ const x = 3.7, z = -2.2, t = 1.3;
+ let expected = 0;
+ for (const [heading, lengthShare, heightShare, speedShare] of WAVE_SET) {
+ const k = 2 * Math.PI / (params.length * lengthShare);
+ const a = (params.direction + heading) * Math.PI / 180;
+ const theta = k * (Math.sin(a) * x + Math.cos(a) * z) - Math.sqrt(9.8 * k) * params.speed * speedShare * t;
+ expected += params.height * heightShare * Math.exp(Math.sin(theta) - 1);
+ }
+ expect(waveHeight(params, x, z, t)).toBeCloseTo(expected, 10);
+ });
+
+ it('has a slope that is the derivative of its height', () => {
+ const e = 1e-4;
+ for (const [x, z, t] of [[0, 0, 0], [5.5, -3.1, 2.4], [-12, 9, 7.7]] as const) {
+ const [sx, sz] = waveSlope(params, x, z, t);
+ expect(sx).toBeCloseTo((waveHeight(params, x + e, z, t) - waveHeight(params, x - e, z, t)) / (2 * e), 4);
+ expect(sz).toBeCloseTo((waveHeight(params, x, z + e, t) - waveHeight(params, x, z - e, t)) / (2 * e), 4);
+ }
+ });
+
+ it('moves with time and is calm without height', () => {
+ expect(waveHeight(params, 1, 1, 0)).not.toBeCloseTo(waveHeight(params, 1, 1, 3), 3);
+ expect(waveHeight({ ...params, height: 0 }, 1, 1, 5)).toBe(0);
+ });
+
+ it('leaves out the waves a coarse cell cannot draw', () => {
+ expect(waveFade(14, 0)).toBe(1);
+ expect(waveFade(14, 1)).toBe(1);
+ expect(waveFade(14, 14 / 3)).toBe(0);
+ expect(waveFade(14, 14 / 4.5)).toBeCloseTo(0.5, 10);
+ const fine = waveHeight(params, 2, 3, 1, 0);
+ const coarse = waveHeight(params, 2, 3, 1, 8);
+ expect(coarse).not.toBeCloseTo(fine, 3);
+ });
+});
+
+describe('a lake\'s mesh', () => {
+ const mesh = buildRectMesh(20, 10, 2);
+ const p = positions(mesh);
+
+ it('covers its rectangle in cells of the size asked, facing up', () => {
+ expect(mesh.vertexCount).toBe(11 * 6);
+ expect(mesh.indices.length / 3).toBe(10 * 5 * 2);
+ expect(mesh.aabbMin).toEqual([-10, 0, -5]);
+ expect(mesh.aabbMax).toEqual([10, 0, 5]);
+ for (let t = 0; t < mesh.indices.length; t += 3) {
+ expect(facing(p, mesh.indices[t]!, mesh.indices[t + 1]!, mesh.indices[t + 2]!)).toBeGreaterThan(0);
+ }
+ });
+
+ it('takes its uv from its position, so the shader\'s body space is local x and z', () => {
+ const channel = mesh.channels.find((c) => c.semantic === MeshChannel.TexCoord0)!;
+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
+ for (const i of [0, 7, mesh.vertexCount - 1]) {
+ expect(view.getFloat32(i * mesh.vertexStride + channel.offset, true)).toBeCloseTo(p[i * 3]!, 6);
+ expect(view.getFloat32(i * mesh.vertexStride + channel.offset + 4, true)).toBeCloseTo(p[i * 3 + 2]!, 6);
+ }
+ });
+});
+
+describe('an ocean\'s mesh', () => {
+ const cells = 16, rings = 4, cell = 1;
+ const mesh = buildOceanMesh(cells, rings, cell);
+ const p = positions(mesh);
+
+ it('reaches as far as it says and tiles its square exactly once', () => {
+ const reach = oceanReach(cells, rings, cell);
+ expect(reach).toBe(64);
+ expect(mesh.aabbMax[0]).toBe(reach);
+ let area = 0;
+ for (let t = 0; t < mesh.indices.length; t += 3) {
+ const f = facing(p, mesh.indices[t]!, mesh.indices[t + 1]!, mesh.indices[t + 2]!);
+ expect(f).toBeGreaterThan(0);
+ area += f / 2;
+ }
+ expect(area).toBeCloseTo((2 * reach) ** 2, 3);
+ });
+
+ it('marks each vertex with its ring, which the shader turns into a cell size', () => {
+ const reds = new Set<number>();
+ for (let i = 0; i < mesh.vertexCount; i++) reds.add(Math.round(colorRed(mesh, i) * 7));
+ expect([...reds].sort()).toEqual([0, 1, 2, 3]);
+ });
+
+ it('snaps to the lattice its coarsest ring lines up on', () => {
+ expect(oceanSnap(rings, cell)).toBe(8);
+ });
+});
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index 9caafe6a7..44f1bfe7c 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -325,6 +325,16 @@ export const SUBSYSTEMS = [
whyZh: '地面和上面的植物在编辑器里两个后端都能画出来并有检查,但还没有东西和地面碰撞,创作面板也还没有被拿来定下这套接口的形状',
entry: ['Terrain', 'Foliage'],
},
+ {
+ id: 'water',
+ title: 'Water',
+ titleZh: '水体',
+ source: ['water'],
+ tier: 'experimental',
+ why: 'the surface draws and its waves are shared with the CPU, but only an ocean and a rectangular lake exist so far, and nothing floats or swims in it yet',
+ whyZh: '水面能画出来,波浪也和 CPU 共用同一个公式,但目前只有海洋和矩形湖泊,还没有东西能漂浮或游泳',
+ entry: ['WaterBody', 'Waters'],
+ },
{
id: 'decal',
title: 'Decals',
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 27f4065ca..24e60bca6 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 —
+ WaterBody: ['owed', 'no example carries a body of water yet; the first lake with a boundary of its own (the next step of the water work) 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'],
// — owed: a creator-facing component nothing in the shipped corpus authors.
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index cb6dc82c2..1237f2b90 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -120,6 +120,10 @@ const DISPOSITION = {
'Foliage.heightMax': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
'Foliage.lodDistance': ['no-place', 'a distance from the camera past which the far version is drawn'],
'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],
+ 'WaterBody.sizeX': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
+ 'WaterBody.sizeZ': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
+ 'WaterBody.cellSize': ['no-place', 'the cell size of the finest ring of geometry, not a region of the entity'],
+ 'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],
'ShapeRenderer.size': ['renders', 'the shape drawn at it is the outline'],
diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjs
index 2c2dc63de..54fea290c 100644
--- a/tools/lib/sdkProgram.mjs
+++ b/tools/lib/sdkProgram.mjs
@@ -65,6 +65,7 @@ export const ENTRIES = {
'fx-atmosphere': 'src/postprocess/fxAtmosphere.ts',
'fx-lighting': 'src/postprocess/fxLighting.ts',
'foliage': 'src/foliage/index.ts',
+ 'water': 'src/water/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 aa9ba758f..321f513d6 100644
--- a/tools/nativeScriptModules.js
+++ b/tools/nativeScriptModules.js
@@ -71,6 +71,7 @@ export const MODULES = {
'esengine/fx-atmosphere': { disposition: 'native-subpath' },
'esengine/fx-lighting': { disposition: 'native-subpath' },
'esengine/foliage': { disposition: 'native-subpath' },
+ 'esengine/water': { 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 1600ab021..b67765ca3 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2557,6 +2557,8 @@ export const NOTED = {
{"note":"The Hair shader can draw the soft outer band of its cards: `u_tipSoftness` is how far below the cutoff alpha a second, blended pass draws each strand's tip fading out, sorted with the other blended draws, so tips are not stair-stepped by coverage. A model imported with Character Materials also has its hair triangles put in the order that pass wants, the cards nearest the middle of the hair first. Off by default."},
"feat(examples): Cyber Rooftop gets a wet roof, a rain sky and a fuller HUD":
{"note":"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."},
+ "feat(water): a WaterBody builds an ocean or a lake whose waves lift the geometry and can be read from code":
+ {"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."},
"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":