A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(water): water keeps ripples and foam, a disturbance spreads as a ring, and what moves in it makes a wake
yhhe84d69447ce2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0266c37fe..6deef347e 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.+- **Ripples and wakes.** A body of water keeps what disturbs it. With `ripples` above 0 the water steps a window of its surface (that follows the camera) with the wave equation: `Waters.disturb(x, y, z, radius, strength)` and a `Floating` body's wake (`wake`) put in bumps that spread as rings, fade, and bend the shading and the reflection, and leave foam that lingers and thins (`rippleSpeed`, `rippleDamping`, `foamFade`). `Waters.sample` carries the ripples, and `Waters.rippleAt` gives them alone.- **Waterline, caustics, shafts and a mirror under the water.** Under water the picture is lit and bounded like water. A camera with its lens half in the water has a waterline across it, soft and sliding as it dips; what it sees is lit by the web of caustics the waves focus the sun into (the Water material's `u_causticStrength`, `u_causticScale` and `u_causticSpeed`, also drawn on what lies under the water seen from above); the water along each ray scatters the sun into shafts (`u_shaftStrength`); and the surface seen from below, past the critical angle, mirrors the world beneath it.- **Underwater view.** A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window).- **Floating bodies.** Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries.diff --git a/desktop b/desktopindex 48d0bc660..1070ab90d 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 48d0bc66056519f7f067ad1d72dc5d95f1c3bc2a+Subproject commit 1070ab90d1db616e6681dd7cca6cde80fd6ab79adiff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 97ed66ef2..5a6eb5e96 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -86,6 +86,7 @@ a server, a test or a build that draws nothing floats things the same.| `drag` | How hard the water resists the body moving through it, per second. It brings a body to rest in still water and carries it with a river's current. || `radius` | How deep, in world units, a point of the body has to be under the surface to be wholly wet. || `points` | Points of the body, in its own space and world units, the water is asked about. Spread them (the corners of a hull) and the waves tip it. Empty is the one at its origin. |+| `wake` | How much of a ripple the body makes in water that keeps ripples ([Ripples](#ripples)). 0 makes none. |At each point the share of it under water (0 at the surface, 1 from `radius` down) gives a buoyant force against gravity of `mass * g * buoyancy * share / points`,applied at the point, and a drag against the point's velocity relative to the water (the body's own and what its turning adds there, less the current). The forces are@@ -95,6 +96,25 @@ It needs the 3D physics module, and a build of it with the force functions (`_phfloats nothing. Floating is one rigid body in one fluid: there is no added mass, no lift from the shape of a hull, and a body that is wholly under is not pushedtoward anything but by the current.+## Ripples++A body of water keeps what disturbs it when `ripples` is above 0. The water holds a square window of its surface (`rippleSize` world units a side, `ripples` cells along it)+as a grid of heights and steps it with the wave equation: every cell is pulled toward its neighbours and carries the velocity it had, so a bump put in spreads as a ring+at `rippleSpeed`, loses `rippleDamping` of its height a second, and is gone. Beside the heights the grid keeps **foam**: a disturbance feeds it where it happened and it fades+at `foamFade` a second, so a splash leaves white water that lingers and thins and does not blink out with the ring.++- **Who disturbs.** A script calls `Waters.disturb(x, y, z, radius, strength)` (the point goes to the body that holds it; `strength` is a height in world units, negative is a dip),+ and a `Floating` body does it itself: what goes down into the water, comes up out of it or moves along its surface pushes the water by its speed (`wake` multiplies it).+- **What it changes.** The shader reads the grid as a texture: the slope of the ripples bends the normal, which is what the light, the reflection and the refraction see, and the foam+ whitens the surface. The geometry is not lifted by it. The surface the code reads does carry them: `Waters.sample` adds the ripple's height to the surface, and `Waters.rippleAt(x, y, z)`+ gives it alone, so a floating ball is lifted by the ring that passes under it.+- **Where.** The window follows the active camera, in whole cells, so a lake or an ocean of any size has ripples where they are seen for the price of one grid. What the window leaves behind is+ forgotten, and what it comes to is still water. A wave reaching its edge goes out and is not reflected. The grid is stepped on the CPU, in as many substeps as keep a wave from crossing more than+ half a cell, and uploaded as an RGBA8 texture (red the height, green the foam): the same on every backend.++The grid can hold as much height as `max(2 * waveHeight, rippleSize / 50)`: a disturbance that goes on (a body moving) saturates there and does not pile up. A cell is `rippleSize / ripples`+world units, so a ripple narrower than a cell or two is not drawn. Cost is `ripples` squared per substep and one texture upload a frame: 128 is sixteen thousand cells.+## Under the surfaceWhen the active camera is under a body of water the picture is the water's. The water module reports where the camera is each frame (from [`Waters.sample`](#asking-the-surface))@@ -184,10 +204,11 @@ What is not there yet, so nobody is surprised:- Like glass, it refracts the opaque scene only: a boat's hull seen through it is, but another transparent surface is not.- A river does not carve the ground, rapids and falls are not foamed by how fast or steep the water runs, and two bodies do not blend where they meet.A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die toward the shore without breaking on it.-- Things float (see [Floating](#floating)); nothing swims yet, and a body in the water makes no ripple or wake.+- Things float (see [Floating](#floating)) and make a wake (see [Ripples](#ripples)); nothing swims yet.- Caustics and shafts follow the first directional light only, from a pattern and not a simulation: the web does not respond to the actual shape of the waves. From above the causticstake what is under the water to face up (the picture holds no normals there), so a wall under the surface is lit as a floor would be.- The mirror from below is screen-space: it shows only what the frame has on screen, and a ray that leaves the picture or meets nothing finds the water's own colour.- The body of water a camera is under is the first the surface query finds at the camera's place: a camera under two overlapping bodies takes the numbers of the first.-- It does not react to what moves through it: no ripples, no wake.+- Ripples only bend the shading and carry foam: they do not lift the geometry, they are one window of a body following the camera (a body far from every camera keeps none), and a+ body keeps one window, so two cameras in a split screen share the first's. Foam that a ripple leaves is not carried by a river's current.- 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/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex 9ef3fdec1..ac06caebf 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -61,11 +61,22 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的| `drag` | 水对物体穿行的阻力,每秒。它让物体在静水里停下来,在河里随水流前进。 || `radius` | 物体上的一个点要在水面以下多深(世界单位)才算完全湿透。 || `points` | 物体自身空间里、世界单位的点,水会针对它们作答。把它们散开(比如船体的四个角),波浪就会让它倾斜。留空就是原点那一个。 |+| `wake` | 物体在会保留涟漪的水里([涟漪](#涟漪))激起多大的涟漪。0 表示不激起。 |在每个点上,没入水里的份额(水面处为 0,从 `radius` 往下为 1)给出一个逆着重力的浮力 `mass * g * buoyancy * 份额 / 点数`,作用在这个点上,还有一个对抗这个点相对水的速度的阻力(物体自己的速度加上转动在那里带来的,再减去水流)。这些力在每个固定步长、世界步进之前施加。`buoyancy` 为 2 且只有一个点的物体,中心会停在水面以下 `radius / 2` 处。它需要 3D 物理模块,并且是带有施力函数(`_physics3d_addForce`、`_physics3d_getBodyDynamics`)的那一版;没有这些函数的构建会警告一次,什么也不会漂。漂浮是一个刚体在一种流体里:没有附加质量,没有船体形状带来的升力,完全没入的物体除了水流外不会被推向任何方向。+## 涟漪++`ripples` 大于 0 时,水体会记住扰动它的东西。水保存自己表面的一个方形窗口(边长 `rippleSize` 世界单位,沿边 `ripples` 个格子),作为一张高度网格,用波动方程推进:每个格子被拉向它的邻居,并带着它原有的速度,所以放进去的一个凸起会以 `rippleSpeed` 的速度扩散成一圈圈环,每秒损失 `rippleDamping` 的高度,最后消失。网格旁边还保存着**泡沫**:扰动在哪里发生就往哪里加泡沫,泡沫按每秒 `foamFade` 消退,所以一次水花留下的白水会逗留、变薄,而不是随着环一起突然消失。++- **谁来扰动。** 脚本调用 `Waters.disturb(x, y, z, radius, strength)`(这个点交给容纳它的水体;`strength` 是以世界单位计的高度,负数是下凹),`Floating` 物体也会自己做:落进水里、从水里升出或沿水面运动的东西,会按速度推动水(`wake` 是倍数)。+- **它改变什么。** 着色器把网格当纹理读:涟漪的斜率弯折法线,光照、反射和折射看到的就是这个法线;泡沫让表面变白。几何体不会被它抬起。代码读到的表面包含它们:`Waters.sample` 把涟漪的高度加到表面上,`Waters.rippleAt(x, y, z)` 单独给出它,所以一个漂浮的球会被从它下面经过的环托起。+- **在哪里。** 窗口以整格为单位跟随活动相机,所以任意大小的湖或海,在看得见的地方都有涟漪,代价只是一张网格。窗口离开的地方被遗忘,新到的地方是静水。到达边缘的波会出去而不是被反射。网格在 CPU 上推进,子步数以保证波一步不跨过超过半个格子为准,并作为 RGBA8 纹理上传(红是高度,绿是泡沫):各后端一致。++网格最多能容纳 `max(2 * waveHeight, rippleSize / 50)` 的高度:持续的扰动(运动的物体)会在这里饱和,而不会无限堆积。一个格子是 `rippleSize / ripples` 世界单位,所以窄于一两个格子的涟漪画不出来。代价是每个子步 `ripples` 的平方,加每帧一次纹理上传:128 是一万多个格子。+## 水面之下当活动相机在一个水体之下时,画面就是水的。水模块每帧报告相机在哪儿(来自 [`Waters.sample`](#查询表面)),后处理体积系统只要相机还在水下,就像天气带来雨一样,加上一个 **Underwater** 效果:@@ -126,9 +137,9 @@ curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫,两个水体相接处也不会融合。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。-- 东西可以漂浮(见[漂浮](#漂浮));还没有东西能游泳,水里的物体也不会激起涟漪或尾迹。+- 东西可以漂浮(见[漂浮](#漂浮)),也会激起尾迹(见[涟漪](#涟漪));还没有东西能游泳。- 焦散和光束只跟随第一盏平行光,来自一个图案而不是模拟:这张网并不响应波浪的真实形状。从上面看时,焦散把水下的东西当作朝上的面(画面里那里没有法线),所以水面下的一面墙会像地板一样被照亮。- 从下面看的镜子是屏幕空间的:它只显示帧里在屏幕上的东西,射线离开画面或什么也没碰到时,找到的是水自己的颜色。- 相机所在的水体,是水面查询在相机所在处找到的第一个:同时在两个重叠水体之下的相机,用的是第一个的数值。-- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。+- 涟漪只弯折着色并携带泡沫:不会抬起几何体;它们只是水体跟随相机的一个窗口(离所有相机都很远的水体什么也不保留),一个水体只有一个窗口,所以分屏时两个相机共用第一个的。涟漪留下的泡沫不会被河流的水流带走。- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex d0503d97a..6816a8134 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -751,6 +751,14 @@ const WATER = `#pragma shader "Water"#pragma param u_causticStrength float default(0.6) range(0,3) ui(slider)#pragma param u_causticScale float default(2) range(0.05,2000) ui(slider)#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)+// The disturbance the water keeps (WaterBody ripples): a window of the body's xz plane, red the height of the ripples (0.5 at rest, u_rippleRange above or below at 1 and 0)+// and green the foam they left, as the CPU stepped them. u_rippleSize is the window's side, u_rippleTexel one texel of it.+#pragma param u_rippleOn float default(0) range(0,1) ui(slider)+#pragma param u_rippleMap texture default(white) texel(data)+#pragma param u_rippleOrigin vec2 default(0,0)+#pragma param u_rippleSize float default(64) range(0.01,100000) ui(slider)+#pragma param u_rippleTexel float default(0.0156) range(0,1) ui(slider)+#pragma param u_rippleRange float default(1) range(0.0001,1000) ui(slider)#pragma param u_sceneColor texture default(white)#pragma param u_sceneDepthMap texture default(white) texel(data)@@ -964,6 +972,16 @@ void main() {float shoreDist = (shoreTex.r - 0.5) * 2.0 * u_shoreRange;float shoreDepth = shoreTex.g * u_shoreRange;float damp = u_shoreOn > 0.5 ? shoreTex.b : 1.0;+ // The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (reads taken before any branch).+ vec2 ripUv = (wp - u_rippleOrigin) / max(u_rippleSize, 1e-4);+ vec4 ripC = texture(u_rippleMap, ripUv);+ vec2 ripStep = vec2(u_rippleTexel);+ float ripCell = max(u_rippleSize * u_rippleTexel, 1e-5);+ float ripL = texture(u_rippleMap, ripUv - vec2(ripStep.x, 0.0)).r, ripR = texture(u_rippleMap, ripUv + vec2(ripStep.x, 0.0)).r;+ float ripD = texture(u_rippleMap, ripUv - vec2(0.0, ripStep.y)).r, ripU = texture(u_rippleMap, ripUv + vec2(0.0, ripStep.y)).r;+ bool ripIn = u_rippleOn > 0.5 && u_waveSpace > 0.5 && all(greaterThanEqual(ripUv, vec2(0.0))) && all(lessThanEqual(ripUv, vec2(1.0)));+ vec2 ripSlope = ripIn ? vec2(ripR - ripL, ripU - ripD) * u_rippleRange / ripCell : vec2(0.0);+ float ripFoam = ripIn ? ripC.g : 0.0;float crest;vec2 slope;if (u_flowSpeed > 0.0) {@@ -984,6 +1002,7 @@ void main() {}slope *= damp;crest *= damp;+ slope += ripSlope;vec3 N = normalize(vec3(-slope.x, 1.0, -slope.y));vec3 Ngeo = vec3(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -1059,7 +1078,7 @@ void main() {shore = max(shore, clamp((1.0 - min(shoreDist, shoreDepth) / (u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.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;- float foam = clamp(max(shore, onCrest * u_foamCrest), 0.0, 1.0);+ float foam = clamp(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), 0.0, 1.0);SurfaceExt ext = surfaceExtNone(N);ext.misc.x = 0.0204;@@ -1249,6 +1268,18 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {let shoreDepth = shoreTex.g * mc.u_shoreRange;var damp = 1.0;if (mc.u_shoreOn > 0.5) { damp = shoreTex.b; }+ // The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (taken in uniform control flow).+ let ripUv = (wp - mc.u_rippleOrigin) / max(mc.u_rippleSize, 1e-4);+ let ripC = textureSample(u_rippleMap, u_rippleMap_s, ripUv);+ let ripCell = max(mc.u_rippleSize * mc.u_rippleTexel, 1e-5);+ let ripL = textureSample(u_rippleMap, u_rippleMap_s, ripUv - vec2f(mc.u_rippleTexel, 0.0)).r;+ let ripR = textureSample(u_rippleMap, u_rippleMap_s, ripUv + vec2f(mc.u_rippleTexel, 0.0)).r;+ let ripD = textureSample(u_rippleMap, u_rippleMap_s, ripUv - vec2f(0.0, mc.u_rippleTexel)).r;+ let ripU = textureSample(u_rippleMap, u_rippleMap_s, ripUv + vec2f(0.0, mc.u_rippleTexel)).r;+ let ripIn = mc.u_rippleOn > 0.5 && mc.u_waveSpace > 0.5 && all(ripUv >= vec2f(0.0)) && all(ripUv <= vec2f(1.0));+ var ripSlope = vec2f(0.0);+ var ripFoam = 0.0;+ if (ripIn) { ripSlope = vec2f(ripR - ripL, ripU - ripD) * mc.u_rippleRange / ripCell; ripFoam = ripC.g; }var surface = vec3f(0.0);if (mc.u_flowSpeed > 0.0) {// A river: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.@@ -1265,7 +1296,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {}var waves : Waves;waves.crest = surface.z * damp;- var slope = surface.xy * damp;+ var slope = surface.xy * damp + ripSlope;var N = normalize(vec3f(-slope.x, 1.0, -slope.y));var Ngeo = vec3f(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -1335,7 +1366,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {}var onCrest = 0.0;if (mc.u_foamCrest > 0.0) { onCrest = smoothstep(1.0 - 0.3 * mc.u_foamCrest, 1.0, waves.crest) * smoothstep(0.35, 0.75, breakup); }- let foam = clamp(max(shore, onCrest * mc.u_foamCrest), 0.0, 1.0);+ let foam = clamp(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), 0.0, 1.0);var ext = surfaceExtNone(N);ext.misc.x = 0.0204;diff --git a/sdk/src/water/floating.ts b/sdk/src/water/floating.tsindex d638e6ce4..ee180229a 100644--- a/sdk/src/water/floating.ts+++ b/sdk/src/water/floating.ts@@ -38,6 +38,8 @@ export interface FloatingData {radius: number;/** The points of the body, in its own space and world units, the water is asked about. Empty is the one at its origin. */points: Vec3Like[];+ /** How much of a ripple the body makes in a body of water that keeps ripples: a multiplier, 0 for none. */+ wake: number;}/**@@ -46,13 +48,14 @@ export interface FloatingData {* @experimental*/export const Floating: ComponentDef<FloatingData> = defineComponent<FloatingData>('Floating', {- buoyancy: 2, drag: 1, radius: 50, points: [] as Vec3Like[],+ buoyancy: 2, drag: 1, radius: 50, points: [] as Vec3Like[], wake: 1,}, {fields: {buoyancy: { min: 0, max: 20, category: 'Water', tooltip: 'The water\'s density against the body\'s. 1 holds it up exactly when it is wholly under; 2 floats it half under.' },drag: { min: 0, max: 20, category: 'Water', tooltip: 'How hard the water resists the body moving through it, per second.' },radius: { min: 0.01, category: 'Water', tooltip: 'How deep under the surface, in world units, a point of the body is wholly wet.' },points: { category: 'Water', tooltip: 'Points of the body, in its own space, the water is asked about: spread them (the corners of a hull) and waves tip it. Empty is the one at its origin.' },+ wake: { min: 0, max: 10, category: 'Water', tooltip: 'How much of a ripple the body makes in water that keeps ripples (WaterBody Ripples). 0 makes none.' },},});@@ -110,6 +113,24 @@ export function floatingForce(};}+/** How much of a wake, in world units of water height, a step of a point's motion through the surface makes per unit of the multiplier. */+const WAKE_PER_SPEED = 0.08;++/**+ * The bump a point at the surface puts into ripples this step, in world units (negative is a dip), or 0 where it is not touching the surface.+ * `velocity` is the point's velocity relative to the water in world units a second; what goes down into the water pushes it down, and moving along it drags a trough.+ */+export function wakeStrength(sample: WaterSample | null, velocity: [number, number, number], floating: FloatingData, dt: number): number {+ if (!sample || floating.wake <= 0) return 0;+ if (Math.abs(sample.depth) > Math.max(floating.radius, 1e-6)) return 0;+ const n = sample.normal;+ const along = velocity[0] * n[0] + velocity[1] * n[1] + velocity[2] * n[2];+ const sideways = Math.hypot(velocity[0] - along * n[0], velocity[1] - along * n[1], velocity[2] - along * n[2]);+ const push = (along - 0.2 * sideways) * dt * WAKE_PER_SPEED * floating.wake;+ const cap = floating.radius * 0.2;+ return Math.min(Math.max(push, -cap), cap);+}+/** Rotates `v` by the unit quaternion `q`. */function rotate(q: { x: number; y: number; z: number; w: number }, v: Vec3Like): [number, number, number] {const tx = 2 * (q.y * v.z - q.z * v.y), ty = 2 * (q.z * v.x - q.x * v.z), tz = 2 * (q.x * v.y - q.y * v.x);@@ -158,6 +179,13 @@ export function installFloating(app: App): void {const sample = waters.sample(world[0], world[1], world[2]);const result = floatingForce(body, [world[0] / ppu, world[1] / ppu, world[2] / ppu], sample, floating, gravity, ppu, config.fixedTimestep, offsets.length);if (result) module._physics3d_addForce(id, result.force[0], result.force[1], result.force[2], result.point[0], result.point[1], result.point[2]);+ if (sample && floating.wake > 0) {+ const relative: [number, number, number] = [+ body.velocity[0] * ppu - sample.flow[0], body.velocity[1] * ppu - sample.flow[1], body.velocity[2] * ppu - sample.flow[2],+ ];+ const push = wakeStrength(sample, relative, floating, config.fixedTimestep);+ if (push !== 0) waters.disturb(world[0], world[1], world[2], floating.radius, push);+ }}}}, { name: 'FloatingSystem' }));diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.tsindex 95b12a63f..17473cea6 100644--- a/sdk/src/water/index.ts+++ b/sdk/src/water/index.ts@@ -5,7 +5,8 @@ export {} from './waterPlugin';export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './waves';export { UnderwaterPlugin, registerUnderwaterEffect } from './underwater';-export { Floating, FloatingPlugin, floatingForce, type FloatingBody, type FloatingData, type FloatingForce } from './floating';+export { RippleField } from './ripples';+export { Floating, FloatingPlugin, floatingForce, wakeStrength, type FloatingBody, type FloatingData, type FloatingForce } from './floating';export { buildRiverMesh, currentShare } from './riverMesh';export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './waterMesh';export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './shore';diff --git a/sdk/src/water/ripples.ts b/sdk/src/water/ripples.tsnew file mode 100644index 000000000..c2c5a5e55--- /dev/null+++ b/sdk/src/water/ripples.ts@@ -0,0 +1,173 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ripples.ts+ * @brief The disturbance a thing makes in water: a wave equation on a grid, and the foam it leaves.+ *+ * @details A body of water that is asked to ripple keeps a square window of its surface, a few hundred world units across, as a grid of heights, and each+ * step moves it by the wave equation (every cell is pulled toward the mean of its four neighbours, and carries the velocity it had), with a little+ * damping so a ripple dies. A disturbance (a body entering, a body moving, a script's `disturb`) is a smooth bump put into the grid; it spreads+ * as a ring at the wave speed. Beside the height the grid keeps a foam: fed where a disturbance was and where the water moves, and fading with time.+ *+ * It is the CPU's, and a plain array: it runs wherever the app does, is the same on every backend, and can be read back. The window follows the camera+ * (it is re-centred in whole cells and the contents shift with it), so a lake or an ocean of any size has ripples where they are seen, for the+ * price of one grid. The Water shader reads it as a texture (`encode`) for the slope it adds to the waves' and for the foam.+ *+ * The wave equation is stepped in as many substeps as keep the wave from crossing more than half a cell in one: past that it would not be stable.+ */++/** A ripple grid over a square window of a body's own xz plane. */+export class RippleField {+ /** Cells along a side. */+ readonly n: number;+ /** World size of the window along a side. */+ readonly size: number;+ /** World size of one cell. */+ readonly cell: number;+ /** The window's minimum corner in the body's xz plane. */+ originX = 0;+ originZ = 0;+ /** The most height a cell may hold, either way: disturbances that go on (a body moving) saturate here instead of piling up. */+ limit = Infinity;+ private height: Float32Array;+ private previous: Float32Array;+ private next: Float32Array;+ private foam: Float32Array;++ constructor(n: number, size: number) {+ this.n = Math.max(8, Math.floor(n));+ this.size = Math.max(1e-3, size);+ this.cell = this.size / this.n;+ const cells = this.n * this.n;+ this.height = new Float32Array(cells);+ this.previous = new Float32Array(cells);+ this.next = new Float32Array(cells);+ this.foam = new Float32Array(cells);+ }++ /** The cell index holding (x, z), or -1 outside the window. */+ private index(x: number, z: number): number {+ const i = Math.floor((x - this.originX) / this.cell), j = Math.floor((z - this.originZ) / this.cell);+ return i < 0 || j < 0 || i >= this.n || j >= this.n ? -1 : j * this.n + i;+ }++ /**+ * Moves the window so it is centred on (x, z), in whole cells: the grid shifts under it, what was on the side it leaves is gone and what comes in is still water.+ * Returns whether it moved.+ */+ recenter(x: number, z: number): boolean {+ const wantX = Math.round((x - this.size / 2) / this.cell) * this.cell;+ const wantZ = Math.round((z - this.size / 2) / this.cell) * this.cell;+ const di = Math.round((wantX - this.originX) / this.cell), dj = Math.round((wantZ - this.originZ) / this.cell);+ if (di === 0 && dj === 0) return false;+ if (Math.abs(di) >= this.n || Math.abs(dj) >= this.n) {+ this.height.fill(0); this.previous.fill(0); this.foam.fill(0);+ } else {+ for (const field of [this.height, this.previous, this.foam]) this.shift(field, di, dj);+ }+ this.originX = wantX;+ this.originZ = wantZ;+ return true;+ }++ /** Shifts a grid so the cell that was at (i + di, j + dj) is at (i, j): the window moving by (di, dj) cells. */+ private shift(field: Float32Array, di: number, dj: number): void {+ const n = this.n, copy = field.slice();+ field.fill(0);+ for (let j = 0; j < n; j++) {+ const sj = j + dj;+ if (sj < 0 || sj >= n) continue;+ for (let i = 0; i < n; i++) {+ const si = i + di;+ if (si >= 0 && si < n) field[j * n + i] = copy[sj * n + si]!;+ }+ }+ }++ /**+ * A smooth bump of `strength` (a height in world units; negative is a dip) and `radius` put into the water at (x, z). It is put into the current heights and the+ * last step's alike, so it starts at rest and spreads, and it feeds the foam by as much as it is strong.+ */+ disturb(x: number, z: number, radius: number, strength: number): void {+ const r = Math.max(radius, this.cell);+ const i0 = Math.floor((x - r - this.originX) / this.cell), i1 = Math.ceil((x + r - this.originX) / this.cell);+ const j0 = Math.floor((z - r - this.originZ) / this.cell), j1 = Math.ceil((z + r - this.originZ) / this.cell);+ for (let j = Math.max(j0, 0); j <= Math.min(j1, this.n - 1); j++) {+ for (let i = Math.max(i0, 0); i <= Math.min(i1, this.n - 1); i++) {+ const dx = this.originX + (i + 0.5) * this.cell - x, dz = this.originZ + (j + 0.5) * this.cell - z;+ const d2 = (dx * dx + dz * dz) / (r * r);+ if (d2 >= 1) continue;+ const falloff = (1 - d2) * (1 - d2);+ const at = j * this.n + i;+ const room = this.limit;+ this.height[at] = Math.min(Math.max(this.height[at]! + strength * falloff, -room), room);+ this.previous[at] = Math.min(Math.max(this.previous[at]! + strength * falloff, -room), room);+ this.foam[at] = Math.min(this.foam[at]! + Math.min(Math.abs(strength) / Math.max(r * 0.25, 1e-6), 1) * falloff, 1);+ }+ }+ }++ /**+ * Steps the grid `dt` seconds on: waves travelling at `speed` (world units a second), losing `damping` of their height a second, and the foam fading by `foamFade` a second.+ * The window's edge lets waves out (the heights there are held at rest) rather than reflecting them.+ */+ step(dt: number, speed: number, damping: number, foamFade: number): void {+ if (dt <= 0) return;+ const n = this.n;+ const substeps = Math.max(1, Math.ceil((speed * dt) / (0.5 * this.cell)));+ const h = dt / substeps;+ const k = (speed * h / this.cell) ** 2;+ const keep = Math.max(1 - damping * h, 0);+ for (let s = 0; s < substeps; s++) {+ const a = this.height, b = this.previous, out = this.next;+ for (let j = 1; j < n - 1; j++) {+ for (let i = 1; i < n - 1; i++) {+ const at = j * n + i;+ const around = a[at - 1]! + a[at + 1]! + a[at - n]! + a[at + n]! - 4 * a[at]!;+ out[at] = (2 * a[at]! - b[at]! + k * around) * keep;+ }+ }+ // The edge is held at rest: the water beyond it is still water.+ for (let i = 0; i < n; i++) { out[i] = 0; out[(n - 1) * n + i] = 0; out[i * n] = 0; out[i * n + n - 1] = 0; }+ this.previous = this.height;+ this.height = out;+ this.next = b;+ }+ const fade = Math.exp(-Math.max(foamFade, 0) * dt);+ for (let q = 0; q < this.foam.length; q++) this.foam[q]! *= fade;+ }++ /** The height of the ripples at (x, z) in world units, 0 outside the window. */+ heightAt(x: number, z: number): number {+ const at = this.index(x, z);+ return at < 0 ? 0 : this.height[at]!;+ }++ /** The foam at (x, z), 0 to 1, 0 outside the window. */+ foamAt(x: number, z: number): number {+ const at = this.index(x, z);+ return at < 0 ? 0 : this.foam[at]!;+ }++ /** The greatest height anywhere in the grid, for a caller asking whether the water is still. */+ peak(): number {+ let m = 0;+ for (let q = 0; q < this.height.length; q++) m = Math.max(m, Math.abs(this.height[q]!));+ return m;+ }++ /**+ * The grid as RGBA8 for the shader: red the height (0.5 at rest, `range` above or below at 1 and 0), green the foam, blue and alpha unused (255).+ * Row j of the grid is row j of the image, so the shader's uv is (x - originX) / size, (z - originZ) / size.+ */+ encode(range: number, into?: Uint8Array): Uint8Array {+ const out = into && into.length === this.n * this.n * 4 ? into : new Uint8Array(this.n * this.n * 4);+ for (let q = 0; q < this.height.length; q++) {+ out[q * 4] = Math.round(Math.min(Math.max(this.height[q]! / (2 * range) + 0.5, 0), 1) * 255);+ out[q * 4 + 1] = Math.round(Math.min(Math.max(this.foam[q]!, 0), 1) * 255);+ out[q * 4 + 2] = 0;+ out[q * 4 + 3] = 255;+ }+ return out;+ }+}diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 6fdd6a40b..3b08adf7c 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -23,8 +23,8 @@ import {import { Assets } from '../asset/AssetPlugin';import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';-import { createTextureFromPixels } from '../runtime/runtimeAssets';-import { getResourceManager } from '../wasm/resourceManager';+import { createTextureFromPixels, updateTextureSubregion } from '../runtime/runtimeAssets';+import { getResourceManager, provideTextureContent, withdrawTextureContent } from '../wasm/resourceManager';import { TextureContent } from '../wasm';import { TerrainsRes } from '../terrain/terrainPlugin';import { BlendMode } from '../render/blend';@@ -36,6 +36,7 @@ import { ShoreField, type Point2 } from './shore';import { buildRiverMesh, currentShare } from './riverMesh';import { Spline, type SplineData } from '../spline/splinePlugin';import { SplineCurve } from '../spline/curve';+import { RippleField } from './ripples';/** What a body of water is. A river follows the `Spline` on its own entity. */export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;@@ -64,6 +65,13 @@ export interface WaterBodyData {waveLength: number;waveSpeed: number;waveDirection: number;+ /** Cells along a side of the ripple grid; 0 keeps no ripples. The grid is a window of `rippleSize` that follows the camera. */+ ripples: number;+ rippleSize: number;+ /** How fast a ripple spreads (world units a second), how much of its height it loses a second, and how fast the foam it leaves fades a second. */+ rippleSpeed: number;+ rippleDamping: number;+ foamFade: number;}/**@@ -74,6 +82,7 @@ export interface WaterBodyData {export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, cellSize: 1, cells: 64, rings: 5, flowSpeed: 2,waveHeight: 0.3, waveLength: 14, waveSpeed: 1, waveDirection: 30,+ ripples: 0, rippleSize: 64, rippleSpeed: 6, rippleDamping: 0.8, foamFade: 0.4,}, {assetFields: [{ field: 'material', type: 'material' }],fields: {@@ -91,6 +100,11 @@ export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyDwaveLength: { 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.' },+ ripples: { min: 0, max: 256, step: 8, category: 'Ripples', tooltip: 'Cells along a side of the grid that keeps what disturbs the water: bodies moving in it, and what a script disturbs. 0 keeps none.' },+ rippleSize: { min: 4, category: 'Ripples', tooltip: 'The side of the window the ripples are kept in, in world units. It follows the camera.' },+ rippleSpeed: { min: 0.1, max: 40, category: 'Ripples', tooltip: 'How fast a ripple spreads, in world units a second.' },+ rippleDamping: { min: 0, max: 10, category: 'Ripples', tooltip: 'How much of its height a ripple loses each second.' },+ foamFade: { min: 0, max: 10, category: 'Ripples', tooltip: 'How fast the foam a disturbance leaves fades, a second.' },},});@@ -121,6 +135,10 @@ interface Built {curve: SplineCurve | null;widest: number;shoreTexture: number;+ /** The ripples this body keeps, where `ripples` asks for them, and the texture the shader reads them from. */+ ripples: RippleField | null;+ rippleTexture: number;+ rippleBytes: Uint8Array | null;child: Entity;instance: number;epoch: number;@@ -169,7 +187,7 @@ export class Waters {const params = paramsOf(d);// The waves a lake keeps toward its shore are the ones its mesh was built with.const damp = field ? field.damp(q[0], q[2]) : 1;- const h = waveHeight(params, q[0], q[2], time) * damp;+ const h = waveHeight(params, q[0], q[2], time) * damp + (built.ripples ? built.ripples.heightAt(q[0], q[2]) : 0);const [rx, rz] = waveSlope(params, q[0], q[2], time);const sx = rx * damp, sz = rz * damp;const len = Math.hypot(sx, 1, sz);@@ -180,6 +198,44 @@ export class Waters {return null;}+ /**+ * Disturbs the water at the world point (x, y, z): a bump of `strength` world units (negative is a dip) over `radius`, which spreads as a ring and leaves foam.+ * Goes to the body that holds the point, and does nothing where there is none or where the body keeps no ripples.+ */+ disturb(x: number, y: number, z: number, radius: number, strength: number): boolean {+ const world = this.app_?.world;+ if (!world) return false;+ for (const [entity, built] of this.built_) {+ if (!world.valid(entity) || !built.ripples) 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 inside = built.data.form === WaterForm.Ocean || (built.field ? built.field.inside(q[0], q[2]) : false)+ || (built.curve ? built.curve.nearest(q[0], q[2]).distance <= built.curve.width(built.curve.nearest(q[0], q[2]).s) / 2 : false);+ if (!inside) continue;+ built.ripples.disturb(q[0], q[2], radius / scale, strength / scale);+ return true;+ }+ return false;+ }++ /** The height the ripples add to the surface at the world point, for a body that keeps them; 0 elsewhere. */+ rippleAt(x: number, y: number, z: number): number {+ const world = this.app_?.world;+ if (!world) return 0;+ for (const [entity, built] of this.built_) {+ if (!world.valid(entity) || !built.ripples) 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 h = built.ripples.heightAt(q[0], q[2]);+ if (h !== 0) return h * scale;+ }+ return 0;+ }+/** 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;@@ -258,11 +314,12 @@ export class WaterPlugin implements Plugin {let built = waters.built_.get(entity);if (!built || built.signature !== signature) {if (built) this.destroy(app, built);- built = { signature, data: { ...data }, mesh: 0, field: null, curve: null, widest: 0, shoreTexture: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };+ built = { signature, data: { ...data }, mesh: 0, field: null, curve: null, widest: 0, shoreTexture: 0, ripples: null, rippleTexture: 0, rippleBytes: null, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };waters.built_.set(entity, built);this.surface(app, entity, built);}built.data = { ...data };+ this.ripple(app, entity, built, eye ?? this.eye(app), app.getResource(Time).delta);if (!rendering) continue;if (!built.child && !built.pending) void this.build_(app, entity, built);if (built.child && built.instance) this.update(app, entity, built, eye, time);@@ -408,6 +465,69 @@ export class WaterPlugin implements Plugin {return t ? `${terrains.revision_}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${t.worldScale.x}:${t.worldScale.y}:${t.worldScale.z}` : '';}+ /**+ * Keeps a body's ripples: makes the grid when `ripples` asks for one, moves its window to the camera, steps it, and (where drawn) puts it where the shader reads it.+ * It runs headless too, so the surface a test or a server asks about has them.+ */+ private ripple(app: App, entity: Entity, built: Built, eye: [number, number, number] | null, dt: number): void {+ const d = built.data;+ if (d.ripples <= 0) { this.dropRipples(built); return; }+ const n = Math.max(8, Math.floor(d.ripples)), size = Math.max(d.rippleSize, 1e-3);+ if (!built.ripples || built.ripples.n !== n || built.ripples.size !== size) {+ this.dropRipples(built);+ built.ripples = new RippleField(n, size);+ // Until a camera says otherwise a body keeps its window over its middle.+ built.ripples.recenter(built.field ? built.field.minX + built.field.sizeX / 2 : 0, built.field ? built.field.minZ + built.field.sizeZ / 2 : 0);+ }+ const field = built.ripples;+ const t = app.world.tryGet(entity, Transform) as TransformData | null;+ if (t && eye) {+ const q = toLocal(t, eye[0], eye[1], eye[2], t.worldScale.y || 1);+ field.recenter(q[0], q[2]);+ }+ field.step(Math.min(Math.max(dt, 0), 0.1), d.rippleSpeed, d.rippleDamping, d.foamFade);+ if (!built.instance || !app.hasResource(Assets)) return;+ const range = this.rippleRange(d);+ field.limit = range;+ const bytes = field.encode(range, built.rippleBytes ?? undefined);+ built.rippleBytes = bytes;+ if (!built.rippleTexture) {+ built.rippleTexture = createTextureFromPixels(app.wasmModule, { width: n, height: n, pixels: bytes }, TextureContent.Retained, false,+ { filterMode: 'linear', wrapMode: 'clamp' });+ const handle = built.rippleTexture;+ provideTextureContent(handle, () => {+ if (built.rippleTexture !== handle || !built.rippleBytes) return false;+ updateTextureSubregion(app.wasmModule, handle, 0, 0, n, n, built.rippleBytes);+ return true;+ });+ Material.setUniform(built.instance, 'u_rippleMap', Material.tex(handle));+ } else {+ updateTextureSubregion(app.wasmModule, built.rippleTexture, 0, 0, n, n, bytes);+ }+ const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(built.instance, name, value); };+ set('u_rippleOn', 1);+ set('u_rippleOrigin', { x: field.originX, y: field.originZ });+ set('u_rippleSize', field.size);+ set('u_rippleTexel', 1 / n);+ set('u_rippleRange', range);+ }++ /** The height the grid holds and its encoding spans either side of rest: twice the waves' height, or a fiftieth of the window where the water is calm. */+ private rippleRange(d: WaterBodyData): number {+ return Math.max(d.waveHeight * 2, d.rippleSize * 0.02);+ }++ private dropRipples(built: Built): void {+ if (built.rippleTexture) {+ withdrawTextureContent(built.rippleTexture);+ getResourceManager()?.releaseTexture(built.rippleTexture);+ }+ built.rippleTexture = 0;+ built.rippleBytes = null;+ built.ripples = null;+ if (built.instance) Material.setUniform(built.instance, 'u_rippleOn', 0);+ }+/** 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;@@ -439,6 +559,7 @@ export class WaterPlugin implements Plugin {private destroy(app: App, built: Built): void {built.epoch++;if (built.child && app.world.valid(built.child)) app.world.despawn(built.child);+ this.dropRipples(built);if (built.instance) Material.release(built.instance);if (built.shoreTexture) getResourceManager()?.releaseTexture(built.shoreTexture);built.shoreTexture = 0;diff --git a/sdk/tests/water-floating.test.ts b/sdk/tests/water-floating.test.tsindex b865d0822..5eff34807 100644--- a/sdk/tests/water-floating.test.ts+++ b/sdk/tests/water-floating.test.ts@@ -5,7 +5,7 @@ import { floatingForce, type FloatingBody, type FloatingData } from '../src/wateimport type { WaterSample } from '../src/water/waterPlugin';const gravity: [number, number, number] = [0, -9.81, 0];-const floating = (extra: Partial<FloatingData> = {}): FloatingData => ({ buoyancy: 1, drag: 0, radius: 50, points: [], ...extra });+const floating = (extra: Partial<FloatingData> = {}): FloatingData => ({ buoyancy: 1, drag: 0, radius: 50, points: [], wake: 1, ...extra });const body = (extra: Partial<FloatingBody> = {}): FloatingBody => ({ position: [0, 0, 0], velocity: [0, 0, 0], angularVelocity: [0, 0, 0], mass: 100, ...extra });const water = (depth: number, flow: [number, number, number] = [0, 0, 0]): WaterSample => ({entity: 1 as never, depth, normal: [0, 1, 0], flow, surface: [0, 0, 0], inside: true,diff --git a/sdk/tests/water-ripples.test.ts b/sdk/tests/water-ripples.test.tsnew file mode 100644index 000000000..aca97b0df--- /dev/null+++ b/sdk/tests/water-ripples.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { RippleField } from '../src/water/ripples';+import { wakeStrength, type FloatingData } from '../src/water/floating';+import type { WaterSample } from '../src/water/waterPlugin';++const field = (): RippleField => new RippleField(64, 64);++describe('RippleField', () => {+ it('is still until something disturbs it', () => {+ const f = field();+ f.step(0.1, 6, 0.5, 0.4);+ expect(f.peak()).toBe(0);+ expect(f.heightAt(10, 10)).toBe(0);+ });++ it('puts a smooth bump where it is disturbed, and feeds the foam there', () => {+ const f = field();+ f.disturb(32, 32, 4, 1);+ expect(f.heightAt(32, 32)).toBeGreaterThan(0.8);+ expect(f.heightAt(32 + 6, 32)).toBe(0);+ expect(f.foamAt(32, 32)).toBeGreaterThan(0.5);+ f.disturb(32, 32, 4, -1);+ expect(f.heightAt(32, 32)).toBeCloseTo(0, 6);+ });++ it('spreads a bump out as a ring at the wave speed', () => {+ const f = field();+ f.disturb(32, 32, 2, 1);+ // One second at 8 units a second: the ring is about 8 units out and the middle has fallen.+ for (let i = 0; i < 60; i++) f.step(1 / 60, 8, 0, 0);+ let ringAt = 0, ringHeight = 0;+ for (let r = 0; r < 20; r += 0.5) {+ const h = f.heightAt(32 + r, 32);+ if (h > ringHeight) { ringHeight = h; ringAt = r; }+ }+ expect(ringAt).toBeGreaterThan(5);+ expect(ringAt).toBeLessThan(11);+ expect(Math.abs(f.heightAt(32, 32))).toBeLessThan(ringHeight);+ // Round: the same a quarter turn round.+ expect(f.heightAt(32, 32 + ringAt)).toBeCloseTo(f.heightAt(32 + ringAt, 32), 1);+ });++ it('stays stable at a large step by taking substeps', () => {+ const f = field();+ f.disturb(32, 32, 3, 1);+ for (let i = 0; i < 40; i++) f.step(0.1, 20, 0, 0);+ expect(Number.isFinite(f.peak())).toBe(true);+ expect(f.peak()).toBeLessThan(1.5);+ });++ it('loses height to damping, and the foam fades', () => {+ const f = field();+ f.disturb(32, 32, 4, 1);+ const before = f.foamAt(32, 32);+ for (let i = 0; i < 120; i++) f.step(1 / 60, 6, 2, 1);+ expect(f.peak()).toBeLessThan(0.1);+ expect(f.foamAt(32, 32)).toBeLessThan(before * 0.2);+ });++ it('lets waves out at the window\'s edge instead of reflecting them', () => {+ const f = field();+ f.disturb(32, 32, 2, 1);+ for (let i = 0; i < 360; i++) f.step(1 / 60, 10, 0, 0);+ // Six seconds at 10 units a second is far past the 32 units to the edge: what is left is the tail, not a ring coming back.+ expect(f.peak()).toBeLessThan(0.25);+ });++ it('moves its window in whole cells and carries the ripples with it', () => {+ const f = field();+ f.disturb(32, 32, 3, 1);+ const at = f.heightAt(32, 32);+ expect(f.recenter(32 + 10, 32)).toBe(true);+ expect(f.originX).toBeCloseTo(10, 6);+ expect(f.heightAt(32, 32)).toBeCloseTo(at, 6);+ expect(f.recenter(32 + 10, 32)).toBe(false);+ // Far away, nothing is carried: the water there is still.+ f.recenter(5000, 5000);+ expect(f.peak()).toBe(0);+ });++ it('is encoded for the shader: 128 at rest, the foam in green', () => {+ const f = field();+ let px = f.encode(1);+ expect(px[0]).toBe(128);+ expect(px[1]).toBe(0);+ expect(px[3]).toBe(255);+ f.disturb(32, 32, 4, 1);+ px = f.encode(1);+ const at = (Math.floor(32 / f.cell) * f.n + Math.floor(32 / f.cell)) * 4;+ expect(px[at]).toBeGreaterThan(220);+ expect(px[at + 1]).toBeGreaterThan(100);+ f.disturb(32, 32, 4, -2);+ expect(f.encode(1)[at]).toBeLessThan(100);+ });+});++describe('wakeStrength', () => {+ const floating: FloatingData = { buoyancy: 1, drag: 0, radius: 50, points: [], wake: 1 };+ const sample = (depth: number): WaterSample => ({ entity: 1 as never, depth, normal: [0, 1, 0], flow: [0, 0, 0], surface: [0, 0, 0], inside: true });++ it('is a dip for what goes down into the water, and a bump for what comes up', () => {+ expect(wakeStrength(sample(-10), [0, -300, 0], floating, 1 / 60)).toBeLessThan(0);+ expect(wakeStrength(sample(-10), [0, 300, 0], floating, 1 / 60)).toBeGreaterThan(0);+ });++ it('is made by moving along the surface too, and not by standing still', () => {+ expect(wakeStrength(sample(0), [200, 0, 0], floating, 1 / 60)).toBeLessThan(0);+ expect(wakeStrength(sample(0), [0, 0, 0], floating, 1 / 60)).toBeCloseTo(0, 12);+ });++ it('is nothing away from the surface, or with the multiplier at 0, and is capped', () => {+ expect(wakeStrength(sample(-500), [0, -300, 0], floating, 1 / 60)).toBe(0);+ expect(wakeStrength(sample(200), [0, -300, 0], floating, 1 / 60)).toBe(0);+ expect(wakeStrength(sample(-10), [0, -300, 0], { ...floating, wake: 0 }, 1 / 60)).toBe(0);+ expect(wakeStrength(null, [0, -300, 0], floating, 1 / 60)).toBe(0);+ expect(wakeStrength(sample(-10), [0, -1e9, 0], floating, 1 / 60)).toBeCloseTo(-10, 6);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 361e04478..d76f27ddb 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2567,6 +2567,8 @@ export const NOTED = {{"note":"Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries."},"feat(water): a camera under the surface sees through the water, fogged and tinted by what it has crossed":{"note":"A camera under water sees through it. Whenever the active camera is below a water body's surface an Underwater effect is added to the post-process volumes: the light of each pixel is taken out colour by colour (red first) by the distance it crossed, with the same absorption and density the surface's material draws with, and the water gives back its own colour, dimmer the deeper the camera is. The surface seen from below turns over and, past the critical angle, reflects whole (Snell's window)."},+ "feat(water): water keeps ripples and foam, a disturbance spreads as a ring, and what moves in it makes a wake":+ {"note":"A body of water keeps what disturbs it. With `ripples` above 0 the water steps a window of its surface (that follows the camera) with the wave equation: `Waters.disturb(x, y, z, radius, strength)` and a `Floating` body's wake (`wake`) put in bumps that spread as rings, fade, and bend the shading and the reflection, and leave foam that lingers and thins (`rippleSpeed`, `rippleDamping`, `foamFade`). `Waters.sample` carries the ripples, and `Waters.rippleAt` gives them alone."},"feat(water): a waterline across the lens, caustics, light shafts, and a mirror under the surface":{"note":"Under water the picture is lit and bounded like water. A camera with its lens half in the water has a waterline across it, soft and sliding as it dips; what it sees is lit by the web of caustics the waves focus the sun into (the Water material's `u_causticStrength`, `u_causticScale` and `u_causticSpeed`, also drawn on what lies under the water seen from above); the water along each ray scatters the sun into shafts (`u_shaftStrength`); and the surface seen from below, past the critical angle, mirrors the world beneath it."},"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":