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(terrain): a material that fades into the ground it meets, a road laid over a terrain, and snow on whatever faces the sky
yhhaa1ea948590e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6836bb65f..c96149411 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **What stands on the ground can blend into it.** The `builtin:ground-blend` material fades a rock or a foundation into whatever is behind it, on both backends, with nothing baked, and can bring a second layer up from the ground or paint one with vertex colours. `RoadDecal` lays a mesh along a Spline over a terrain with soft edges. The `snowCover` post effect and a Snow weather lay snow on whatever faces the sky, terrain and meshes alike.- **GPU particles can hit things, tell each other, and drag trails.** `collisionMode: Depth` collides with what the camera sees, `Sdf` with `ParticleCollider` spheres, boxes and capsules that need no physics (and run on the CPU too). A GPU emitter's births, deaths and collisions go to a buffer: a `gpuSimulation` child spawns from it in its own kernel, with no trip to the CPU, and `collisionEvents` read back to the game a frame or two late. `trailEnabled` now works on the GPU.- **Plants can be touched, felled and harvested.** A `FoliageContact` on a character parts `Foliage` grass around it, on both backends. A kind in `PlacedFoliage` or `WorldRules.plants` with an `interaction` leans away with any material, becomes an entity with a physics capsule while something is near, and can be damaged, felled and harvested through `PlantInteractionRes`, with stumps, regrowth and `saveState` / `loadState`; what became of a plant outlasts its chunk.- **A side-on character comes ready to run and jump.** `PlatformerController2D` beside a `CharacterController2D` reads the keyboard or a game's input, and has coyote time, a jump buffer, jump cut, air jumps and a drop through one-way platforms. `CharacterController2D` gains `stepHeight`, `followPlatform` (it rides what it stands on, sideways too), `dynamicBodies` (block, push or ignore them), `constantSlopeSpeed` and `dropThrough`, and reports `floorEntity` and `floorVelocity`. The 2D platformer template and example use it.diff --git a/desktop b/desktopindex 5b91b3457..a507f07fe 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 5b91b3457d6248dfa2db46f692640aa637e16ed0+Subproject commit a507f07fe7ed416a0f8b15a382bb1e2f20cdf0b3diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 08f009dc7..24f670125 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -302,6 +302,35 @@ The ground collides: the finest nodes within `collisionDistance` of every movingSet `sea` and the planet has a sea: a translucent, lit sphere at `seaLevel` above the radius, in which the ground that dips below it stands (waves and shore foam are the flat water's and come to the sphere later). The sky follows the horizon round: give `skyAtmosphere` and `heightFog` the planet's radius and centre and they work out the sky and the haze for the ground the camera stands on, with the sun a fixed direction, so a place's day and night are where it is on the planet.+## Blending what stands on the ground++Three things hide the line where a model meets the ground. None of them needs the ground to know.++**The Ground Blend material.** The `builtin:ground-blend` shader is the [Model](/docs/graphics/materials/) shader, with every map and param it has, for a rock, a kerb or a foundation. Where the surface comes close to what stands behind it, it gives way to the picture of that very pixel, so whatever the ground is drawn with (its layers, its light, its shadows) is what the seam fades into, with nothing baked. It works on anything behind it, not only a terrain.++| Param | What it does |+|---|---|+| `u_blendDistance` | How high above what is behind the surface has fully arrived, in world units. It is a height and not a distance along the view, so the band holds as the camera tilts. `0` leaves a hard edge. |+| `u_blendNoise`, `u_blendNoiseScale` | How much the edge wanders, and the world size of its wander, so it is not a ruled line. |+| `u_layer2`, `u_layer2Tint`, `u_layer2Roughness` | A second layer: dirt, moss, wet stone. |+| `u_layer2Tile` | The length of one repeat of it in the world, read from above so it lines up across objects. `0` reads the mesh's own uv. |+| `u_layerReach` | How far up from what is behind it the second layer climbs, as a distance field does. |+| `u_vertexBlend` | `1` lets a vertex colour's red paint the second layer, and stops the colour tinting the surface. |++Such a material is drawn after a copy of the opaque scene is taken, the way water is, and a scene with one takes that copy even with no post effect of its own.++**A road.** A `RoadDecal` on an entity with a `Spline` lays the entity's `MeshRenderer` along the curve and over the ground, row by row, and is laid again when the spline or the ground changes. Each edge fades over `edgeFade` of its half width, so give it a blended material. With no terrain it lies along the curve as drawn.++| Field | What it does |+|---|---|+| `step`, `across` | How far apart its rows are along the curve, and how many cells across. Finer follows the ground and the bends more closely. |+| `widthScale` | Times the width each spline point says. |+| `lift` | How far above the ground it lies. Far off the ground is drawn coarser than it is asked, so a road seen from far needs more. |+| `edgeFade` | The share of its half width over which each edge fades. |+| `tile` | The length of one repeat of its texture along the curve. |++**Snow and wet.** The `snowCover` [post effect](/docs/graphics/post-processing/) lays snow on whatever faces the sky and stands under nothing, the terrain and the rock on it alike, with no material changed: `u_amount`, `u_snowLine` and `u_snowLineBand` (the height it stops at), `u_slopeLimit` and `u_grainScale`. The `Snow` [weather](/docs/graphics/weather/) brings it. The `rain` effect with `u_intensity` at `0` and `u_wetness` up is the same for a wet ground, under no rain.+## Limits- **Collision is the finest level.** Far off the ground is drawn coarser than it collides, which is unseen from where anything collides@@ -312,5 +341,7 @@ Set `sea` and the planet has a sea: a translucent, lit sphere at `seaLevel` abov- **Position only.** The terrain follows its entity's position; its rotation and scale are not taken into account, by `heightAt` or bythe shader that lifts the ground. Keep the entity unrotated and unscaled, and set the ground's size with `sizeX`, `sizeZ` and `height`.- **An infinite ground is made by its provider.** It takes no heightmap or splatmap, and its erosion (the engine's noise) paints no dirt.+- **Ground Blend fades into what is seen behind it.** Where nothing is close behind the surface (a rock's side seen against a far valley) there is no seam to hide and none is hidden. A wall just behind a Ground Blend object counts as close, as the ground does. Two such objects do not fade into each other: neither is in the copy the other reads. It needs float render targets; without them it draws as a plain Model.+- **`snowCover` is laid on the picture.** It has no depth, so it does not round an edge or bury a stone, and it is limited to what the camera sees.- **Pages are made a few a frame**, so on the first frames, or after a jump of the eye, the ground is drawn coarse for a moment andsharpens rather than stalling a frame.diff --git a/docs/astro/src/content/docs/graphics/weather.mdx b/docs/astro/src/content/docs/graphics/weather.mdxindex a5649fc31..b416a68c6 100644--- a/docs/astro/src/content/docs/graphics/weather.mdx+++ b/docs/astro/src/content/docs/graphics/weather.mdx@@ -1,6 +1,6 @@---title: Weather-description: A Weather component that puts a scene under clear, mist, overcast, rain or storm, turns between them, and cycles by itself.+description: A Weather component that puts a scene under clear, mist, overcast, rain, storm or snow, turns between them, and cycles by itself.---A scene's weather is not a pile of effect parameters. A project's fog is in its own units and its sun is as bright@@ -21,7 +21,7 @@ Add a `Weather` component to one entity.| Field | What it does ||---|---|-| `preset` | The weather the scene is in: Clear, Mist, Overcast, Rain, Storm. Default Clear. |+| `preset` | The weather the scene is in: Clear, Mist, Overcast, Rain, Storm, Snow. Default Clear. || `target` | The weather it is turning into; None for none (the default). || `progress` | How far along that turn it is (0–1, default 0). The game advances it; set it in the editor to preview a half-turn. || `duration` | Seconds a turn takes (default 6). |@@ -32,13 +32,13 @@ Add a `Weather` component to one entity.A turn is eased, so it starts and ends gently, and a finished turn lands on its target and clears itself.-+-*The **Weather** component: the five weathers to switch between, and the transition below them.*+*The **Weather** component: the weathers to switch between, and the transition below them.*## In the editor-The Details panel shows the five built-in weathers as buttons (a project's own preset id still works and shows as Custom), the+The Details panel shows the built-in weathers as buttons (a project's own preset id still works and shows as Custom), themove toward the next one as a progress you can drag, the cycle and what the weather drives, and a readout of what it is doingto the picture right now — the key light's scale, the fog's, the wetness and the rain. Rain and fog reach the picture through aPost Process Volume, which the panel says.@@ -53,6 +53,7 @@ Post Process Volume, which the panel says.the authored darkness) as the sky clouds over, the way an overcast sky's shadows fade into the ground.- **Fog.** Height Fog's density, its sun glow and the volumetric light it carries are scaled, its sky haze is raised, andits colour moves toward the weather's.+- **Snow.** The [Snow Cover](/docs/graphics/terrain/#blending-what-stands-on-the-ground) effect is brought with the weather (when the scene has none) and lies on whatever faces the sky. It goes with the same `Rain` drive.- **Rain.** The Rain effect is brought with the weather (when the scene has none) at the preset's strength, and Rain andScreen Space Reflections are given the wetness and puddles it leaves. Where the scene authored its own rain, theweather can only raise it.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex aaf978225..04fcb2eff 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -226,8 +226,39 @@ registerPlanetProvider({设置 `sea` 星球就有海:一个半透明、受光的球面,高出半径 `seaLevel`,低于它的地面站在水里(波浪和岸边泡沫是平面水体的,之后会来到球面)。天空跟着地平线转:给 `skyAtmosphere` 和 `heightFog` 填上星球的半径和中心,它们就按相机站着的那片地面算天空和雾,太阳是固定方向,所以一个地方的昼夜取决于它在星球上的位置。+## 让地面上的东西融入地面++有三种手段能藏住模型和地面之间的那条线,它们都不需要地面知道。++**Ground Blend 材质。** `builtin:ground-blend` 着色器就是 [Model](/docs/zh-cn/graphics/materials/) 着色器,贴图和参数一个不少,用于岩石、路缘、建筑地基。表面靠近身后的东西时,会淡出成那个像素的画面,所以无论地面用什么绘制(图层、光照、阴影),接缝都会融进去,不需要任何烘焙。它对身后的任何东西都有效,不只是地形。++| 参数 | 作用 |+|---|---|+| `u_blendDistance` | 表面比身后的东西高出多少才完全显现,世界单位。这是高度,不是沿视线的距离,所以相机倾斜时带宽基本不变。`0` 表示硬边。 |+| `u_blendNoise`、`u_blendNoiseScale` | 边缘的抖动程度和世界尺寸,这样它不是一条尺子画的线。 |+| `u_layer2`、`u_layer2Tint`、`u_layer2Roughness` | 第二层:泥土、苔藓、湿石头。 |+| `u_layer2Tile` | 第二层在世界中一次重复的长度,从上方投射,所以跨物体也能对齐。`0` 用网格自己的 uv。 |+| `u_layerReach` | 第二层从身后的东西向上爬多高,效果类似距离场。 |+| `u_vertexBlend` | `1` 让顶点色的红通道绘制第二层,并且不再用顶点色给表面染色。 |++这种材质和水一样,在拷贝不透明场景之后绘制;场景里有它时,即使没有任何后处理也会拷贝。++**道路。** 在带 `Spline` 的实体上加 `RoadDecal`,它会让实体的 `MeshRenderer` 沿曲线逐行贴合地面,样条或地面变化时重新生成。两侧边缘在半宽的 `edgeFade` 比例内淡出,所以要配混合材质。没有地形时,它按曲线本身的位置铺设。++| 字段 | 作用 |+|---|---|+| `step`、`across` | 沿曲线的行距和横向格数。越细越贴合地面和弯道。 |+| `widthScale` | 样条点宽度的倍数。 |+| `lift` | 离地高度。地面在远处画得比查询结果粗,所以从远处看的道路需要大一些。 |+| `edgeFade` | 每侧边缘淡出占半宽的比例。 |+| `tile` | 纹理沿曲线一次重复的长度。 |++**积雪和湿润。** `snowCover` [后处理效果](/docs/zh-cn/graphics/post-processing/)把雪铺在朝天且上方没有遮挡的表面上,地形和上面的岩石一视同仁,不用改任何材质:`u_amount`、`u_snowLine` 和 `u_snowLineBand`(雪线高度)、`u_slopeLimit`、`u_grainScale`。`Snow` [天气](/docs/zh-cn/graphics/weather/)会自动带上它。`rain` 效果把 `u_intensity` 设为 `0`、调高 `u_wetness`,就是不下雨的湿地面。+## 限制+- **Ground Blend 淡出成身后看到的东西。** 身后没有贴近的东西时(比如岩石侧面背后是远处的山谷),就没有接缝要藏,也不会藏。紧贴在 Ground Blend 物体身后的墙和地面一样算贴近。两个这样的物体不会互相融合,因为它们都不在对方读取的拷贝里。它需要浮点渲染目标,没有时就是普通的 Model。+- **`snowCover` 是铺在画面上的。** 它没有厚度,不会让边缘变圆,也埋不住石头,并且只作用于相机看到的部分。- **碰撞按最细一级。** 远处的地面画得比碰撞粗,但碰撞发生的地方看不出来;只有运动的物体在 `collisionDistance` 内才有可碰的地面。- **上色精度就是页的精度。** 图层权重和高度一起采样,每格两个,所以近处比这更细的 splatmap 会被平均,远处更粗。- **没有洞、洞穴或悬挑。** 高度场在每个位置只有一个高度。洞穴和桥是和它放在一起的网格。diff --git a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdxindex 2dbbf990e..e4cc168d5 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx@@ -1,6 +1,6 @@---title: 天气-description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或暴风雨之下,在它们之间过渡,并能自己循环。+description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨、暴风雨或雪之下,在它们之间过渡,并能自己循环。---场景的天气不是一堆特效参数。项目的雾有它自己的单位,太阳有作者给它的亮度,所以天气表达成**场景已有设定的倍率**——@@ -18,7 +18,7 @@ description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或| 字段 | 作用 ||---|---|-| `preset` | 场景所处的天气:晴、薄雾、阴天、雨、暴风雨。默认晴。 |+| `preset` | 场景所处的天气:晴、薄雾、阴天、雨、暴风雨、雪。默认晴。 || `target` | 正在转向的天气;无则为 None(默认)。 || `progress` | 这次转变走了多远(0–1,默认 0)。游戏会推进它;在编辑器里设置它可以预览转到一半。 || `duration` | 一次转变用多少秒(默认 6)。 |@@ -29,13 +29,13 @@ description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或转变带缓动,开始和结束都平缓,完成的转变落在目标上并清空自己。-+-***Weather** 组件:可切换的五种天气,以及下面的过渡。*+***Weather** 组件:可切换的内建天气,以及下面的过渡。*## 在编辑器里-Details 面板把五种内建天气显示为按钮(项目自己的预设 id 仍然有效,显示为自定义),把向下一种天气的过渡显示为可拖动的进度,还有循环、它驱动的内容,以及它此刻对画面做了什么的读数——主光的缩放、雾的缩放、潮湿和降雨。雨和雾通过 Post Process Volume 进入画面,面板里会这样说明。+Details 面板把内建天气显示为按钮(项目自己的预设 id 仍然有效,显示为自定义),把向下一种天气的过渡显示为可拖动的进度,还有循环、它驱动的内容,以及它此刻对画面做了什么的读数——主光的缩放、雾的缩放、潮湿和降雨。雨和雾通过 Post Process Volume 进入画面,面板里会这样说明。## 天气改变什么@@ -44,6 +44,7 @@ Details 面板把五种内建天气显示为按钮(项目自己的预设 id 仍- **阴影。** 随着天空阴下来,方向光的阴影变得更软(光源宽 `shadowSoftness` 个太阳)、更淡(创作的深浅乘以 `shadowStrength`),就像阴天的影子融进地面。- **雾。** Height Fog 的密度、太阳辉光和它带的体积光被缩放,天空雾霾被提高,颜色向天气的颜色移动。+- **雪。** 场景没有 Snow Cover 效果时天气会带来一个,雪落在所有朝天的表面上,详见[地形](/docs/zh-cn/graphics/terrain/)。它和雨共用 `Rain` 驱动。- **雨。** 场景没有 Rain 效果时天气会带来一个,强度按预设;Rain 和屏幕空间反射还会得到天气留下的湿度和水坑。场景自己创作了雨,天气只能把它提高。- **反射。** 烘焙的反射探针显示的是它烘焙时的天空,所以下雨的街道会映出晴天的街道。环境光带有 `reflectionScale` 和diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 1942e1b33..34409d43d 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": 178,- "experimental": 2934,+ "experimental": 2939,"deprecated": 3},- "total": 3227,+ "total": 3232,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex c394b0d04..67bce6418 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -194,6 +194,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {PlatformerController2D: { category: 'physics', summary: 'Runs and jumps a CharacterController2D from the keyboard or a game, with coyote time, a jump buffer and dropping through one-way platforms.', doc: 'gameplay/physics', anchor: 'platformer-controller' },FoliageContact: { category: 'physics', summary: 'Something plants feel: grass parts around it, shrubs lean away, and placed plants near it become entities with colliders.', doc: 'graphics/foliage', anchor: 'touching-plants' },PlantProxy: { category: 'physics', summary: 'The entity standing in for a placed plant while something is near it, which a ray or a collision finds.', doc: 'graphics/foliage', anchor: 'touching-plants' },+ RoadDecal: { category: 'world', summary: 'Lays the entity\'s mesh along a Spline and over the ground, its edges fading into what it lies on.', doc: 'graphics/terrain', anchor: 'blending-what-stands-on-the-ground' },OneWayPlatform2D: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },DistanceJoint2D: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },HingeJoint2D: { category: 'physics', summary: 'Pins two bodies at a point and lets them rotate — a hinge, with optional limits and a motor.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 171e156c0..7256f85e8 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -6030,6 +6030,62 @@}]},+ {+ "name": "RoadDecal",+ "source": "ts",+ "fields": [+ {+ "key": "step",+ "type": "number",+ "default": "20",+ "doc": "How far apart its rows are along the curve. Finer follows the ground and the bends more closely.",+ "range": "≥ 0.01"+ },+ {+ "key": "across",+ "type": "number",+ "default": "4",+ "doc": "How many cells across. More follows a ground that crowns or slopes under the road.",+ "range": "1–32, step 1"+ },+ {+ "key": "widthScale",+ "type": "number",+ "default": "1",+ "doc": "Times the width each spline point says.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "lift",+ "type": "number",+ "default": "0.5",+ "doc": "How far above the ground it lies. Enough to win against the ground from as far as it is seen.",+ "range": "≥ 0, step 0.01"+ },+ {+ "key": "edgeFade",+ "type": "number",+ "default": "0.35",+ "doc": "The share of its half width over which each edge fades into the ground.",+ "range": "0–1, step 0.01"+ },+ {+ "key": "tile",+ "type": "number",+ "default": "200",+ "doc": "The length of one repeat of its texture along the curve.",+ "range": "≥ 0.01"+ }+ ],+ "animatable": [+ "step",+ "across",+ "widthScale",+ "lift",+ "edgeFade",+ "tile"+ ]+ },{"name": "RuntimeOnly","source": "ts",@@ -9808,7 +9864,8 @@"Mist","Overcast","Rain",- "Storm"+ "Storm",+ "Snow"]},{@@ -9821,7 +9878,8 @@"Mist","Overcast","Rain",- "Storm"+ "Storm",+ "Snow"]},{diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.tsindex 47b466db4..ddbcc9dc8 100644--- a/pipeline/src/project/targetSupport.ts+++ b/pipeline/src/project/targetSupport.ts@@ -48,7 +48,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>foliage: ['Foliage', 'PlacedFoliage', 'FoliageContact', 'PlantProxy'],worldgen: ['WorldGen', 'WorldZone'],water: ['WaterBody', 'WaterZone', 'Floating'],- spline: ['Spline', 'PathFollower', 'TerrainBand2D'],+ spline: ['Spline', 'PathFollower', 'TerrainBand2D', 'RoadDecal'],rig2d: ['Bone2D', 'IK2D', 'BoneConstraint2D'],importedScene: ['NodeVisibility', 'ParticleModelUnits'],// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 8ae23fcc9..8b2df0346 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 · 166 beta · 2071 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2072 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -13116,6 +13116,11 @@ readonly (readonly [number, number, number, number])[]3```+## WEATHER_SNOW — const @experimental+```+5+```+## WEATHER_STORM — const @experimental```4@@ -13322,6 +13327,7 @@ shadowSoftness: numbershadowStrength: numbersky: numberskyFog: number+snow: numbersound: numberssr: numbersun: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d7a328b30..87cba80c0 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 · 171 beta · 2090 experimental · 3 deprecated+Symbols: 115 public · 171 beta · 2091 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -13332,6 +13332,11 @@ readonly (readonly [number, number, number, number])[]3```+## WEATHER_SNOW — const @experimental+```+5+```+## WEATHER_STORM — const @experimental```4@@ -13538,6 +13543,7 @@ shadowSoftness: numbershadowStrength: numbersky: numberskyFog: number+snow: numbersound: numberssr: numbersun: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 3900405d2..b7f129df1 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 · 168 beta · 2070 experimental · 3 deprecated+Symbols: 115 public · 168 beta · 2071 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13111,6 +13111,11 @@ readonly (readonly [number, number, number, number])[]3```+## WEATHER_SNOW — const @experimental+```+5+```+## WEATHER_STORM — const @experimental```4@@ -13317,6 +13322,7 @@ shadowSoftness: numbershadowStrength: numbersky: numberskyFog: number+snow: numbersound: numberssr: numbersun: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex efdee775a..c757b105b 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 · 166 beta · 2092 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2093 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13413,6 +13413,11 @@ readonly (readonly [number, number, number, number])[]3```+## WEATHER_SNOW — const @experimental+```+5+```+## WEATHER_STORM — const @experimental```4@@ -13619,6 +13624,7 @@ shadowSoftness: numbershadowStrength: numbersky: numberskyFog: number+snow: numbersound: numberssr: numbersun: numberdiff --git a/sdk/etc/spline.api.md b/sdk/etc/spline.api.mdindex f39fdd053..55f634aeb 100644--- a/sdk/etc/spline.api.md+++ b/sdk/etc/spline.api.md@@ -1,7 +1,7 @@# API surface — esengine/spline<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 16 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 20 experimental · 0 deprecated## PathFollower — const @experimental```@@ -28,6 +28,27 @@ spline: number{ readonly None: 0; readonly FaceXZ: 1; readonly FaceXY: 2; }```+## RoadDecal — const @experimental+```+ComponentDef<RoadDecalData>+```++## RoadDecalData — interface @experimental+```+across: number+edgeFade: number+lift: number+step: number+tile: number+widthScale: number+```++## RoadGround — interface @experimental+```+heightAt: (x: number, z: number) => number | null+normalAt: ((x: number, z: number) => readonly [number, number, number] | null) | undefined+```+## Spline — const @experimental```ComponentDef<SplineData>@@ -100,6 +121,11 @@ geometry: MeshRendererGeometryoutline: Vec2[]```+## buildRoadDecal — function @experimental+```+(spline: SplineData, road: RoadDecalData, origin: { x: number; y: number; z: number; }, ground: RoadGround | null): MeshData | null+```+## buildTerrainBand — function @experimental```(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 911420bd4..2ca137bcc 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 · 166 beta · 2083 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2084 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13118,6 +13118,11 @@ readonly (readonly [number, number, number, number])[]3```+## WEATHER_SNOW — const @experimental+```+5+```+## WEATHER_STORM — const @experimental```4@@ -13350,6 +13355,7 @@ shadowSoftness: numbershadowStrength: numbersky: numberskyFog: number+snow: numbersound: numberssr: numbersun: numberdiff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex c935122af..9230abacc 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -187,6 +187,7 @@ export {WEATHER_OVERCAST,WEATHER_RAIN,WEATHER_STORM,+ WEATHER_SNOW,WEATHER_NONE,type WeatherState,type WeatherPreset,diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.tsindex 1fb02165e..e41550401 100644--- a/sdk/src/ecs/component.ts+++ b/sdk/src/ecs/component.ts@@ -1384,7 +1384,7 @@ export const PostProcessVolume = defineComponent<PostProcessVolumeData>('PostPro});export interface WeatherData {- /** The weather the scene is in (the built-in presets: Clear, Mist, Overcast, Rain, Storm). */+ /** The weather the scene is in (the built-in presets: Clear, Mist, Overcast, Rain, Storm, Snow). */preset: number;/** The weather it is turning into; -1 for none. */target: number;@@ -1405,7 +1405,7 @@ export interface WeatherData {const WEATHER_PRESET_OPTIONS = [{ label: 'Clear', value: 0 }, { label: 'Mist', value: 1 }, { label: 'Overcast', value: 2 },- { label: 'Rain', value: 3 }, { label: 'Storm', value: 4 },+ { label: 'Rain', value: 3 }, { label: 'Storm', value: 4 }, { label: 'Snow', value: 5 },];/**diff --git a/sdk/src/postprocess.ts b/sdk/src/postprocess.tsindex b5a9fd79c..2d9b1ec47 100644--- a/sdk/src/postprocess.ts+++ b/sdk/src/postprocess.ts@@ -33,6 +33,7 @@ export {WEATHER_OVERCAST,WEATHER_RAIN,WEATHER_STORM,+ WEATHER_SNOW,WEATHER_NONE,type WeatherState,type WeatherPreset,diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.tsindex ee5f023be..703a1a0ee 100644--- a/sdk/src/postprocess/effects.ts+++ b/sdk/src/postprocess/effects.ts@@ -713,6 +713,28 @@ registerEffect({],});+registerEffect({+ type: 'snowCover',+ label: 'Snow Cover',+ factory: () => postProcessEffects.createSnowCover(),+ uniforms: [+ // How much lies: a dusting in the low places at a little, everything closed over at 1.+ { name: 'u_amount', label: 'Amount', min: 0, max: 1, step: 0.01, defaultValue: 1, neutralValue: 0 },+ // The height it stops at, in world units, and how far it thins out above that.+ { name: 'u_snowLine', label: 'Snow Line', min: -100000, max: 100000, step: 1, defaultValue: -100000 },+ { name: 'u_snowLineBand', label: 'Snow Line Band', min: 0, max: 100000, step: 1, defaultValue: 100 },+ // How much a surface must face up to hold it: 1 only the flat, 0 almost a wall.+ { name: 'u_slopeLimit', label: 'Slope Limit', min: 0, max: 1, step: 0.01, defaultValue: 0.55 },+ // The world size of the drifts.+ { name: 'u_grainScale', label: 'Drift Size', min: 1, max: 100000, step: 1, defaultValue: 120 },+ // The same map of what stands over each place as the rain's: no snow under an awning.+ { name: 'u_shelterRange', label: 'Shelter Range', min: 100, max: 30000, step: 100, defaultValue: 3000 },+ ],+ colors: [+ { name: 'u_snowColor', label: 'Snow Colour', defaultValue: { r: 0.92, g: 0.95, b: 1, a: 1 } },+ ],+});+registerEffect({type: 'ssao',label: 'Ambient Occlusion',@@ -937,7 +959,7 @@ const CATEGORIES: Record<EffectCategory, string[]> = {lens: ['bloom', 'depthOfField', 'motionBlur', 'lensFlare', 'filmGrain', 'chromaticAberration', 'lensDistortion', 'vignette', 'sharpen'],color: ['tonemap', 'agx', 'colorGrade', 'lutGrade', 'displayLut', 'autoExposure', 'grayscale'],light: ['ssao', 'gtao', 'ssgi', 'ssr', 'voxelGI', 'contactShadows', 'lightShafts', 'subsurface'],- atmosphere: ['mist2d', 'rain2d', 'fog2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],+ atmosphere: ['mist2d', 'rain2d', 'fog2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain', 'snowCover'],aa: ['fxaa', 'taa'],stylize: ['blur', 'pixelate', 'palette', 'outline', 'depthOutline', 'edgeOutline'],};diff --git a/sdk/src/postprocess/index.ts b/sdk/src/postprocess/index.tsindex a9ac7c6bc..94a2d315b 100644--- a/sdk/src/postprocess/index.ts+++ b/sdk/src/postprocess/index.ts@@ -44,6 +44,7 @@ export {WEATHER_OVERCAST,WEATHER_RAIN,WEATHER_STORM,+ WEATHER_SNOW,WEATHER_NONE,type WeatherState,type WeatherPreset,diff --git a/sdk/src/postprocess/sources/atmosphere.ts b/sdk/src/postprocess/sources/atmosphere.tsindex 586e4ddc7..c86382588 100644--- a/sdk/src/postprocess/sources/atmosphere.ts+++ b/sdk/src/postprocess/sources/atmosphere.ts@@ -2376,6 +2376,162 @@ fn shelteredAt(W : vec3f) -> f32 {return vec4f(col, src.a);}#pragma end+`;+ return Material.compileShader(source);+ },+ /**+ * Snow lying on the picture: whatever faces the sky and is not under something takes it, a terrain and the rock standing on it+ * alike, with no material of theirs knowing. It thins with the slope and below `u_snowLine`, and it is lit by what the picture+ * already says of the place, so a shadow on the ground is a shadow on the snow.+ */+ createSnowCover(): ShaderHandle {+ const source = `#pragma shader "PP Snow Cover"+#pragma version 300 es+#pragma domain PostProcess+#pragma param u_amount float default(1) range(0,1)+#pragma param u_snowLine float default(-100000) range(-100000,100000)+#pragma param u_snowLineBand float default(100) range(0,100000)+#pragma param u_slopeLimit float default(0.55) range(0,1)+#pragma param u_grainScale float default(120) range(1,100000)+#pragma param u_snowColor color default(0.92,0.95,1,1)+#pragma param u_shelterRange float default(3000) range(100,30000)+#pragma param u_shelterBias float default(40) range(1,500)+#pragma param u_coverActive float default(0) range(0,1)+#pragma param u_coverMatrix0 color default(1,0,0,0)+#pragma param u_coverMatrix1 color default(0,1,0,0)+#pragma param u_coverMatrix2 color default(0,0,1,0)+#pragma param u_coverMatrix3 color default(0,0,0,1)+#pragma param u_rainCover texture default(white)+#pragma gbuffer++#pragma fragment+precision highp float;++in vec2 v_texCoord;+uniform sampler2D u_texture;+uniform highp sampler2D u_sceneDepth;+uniform highp sampler2D u_gbuffer;+out vec4 fragColor;++${SSAO_GLSL}+${GBUFFER_GLSL}++float snowHash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }+float snowNoise(vec2 p) {+ vec2 i = floor(p);+ vec2 f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(snowHash(i), snowHash(i + vec2(1.0, 0.0)), f.x), mix(snowHash(i + vec2(0.0, 1.0)), snowHash(i + vec2(1.0, 1.0)), f.x), f.y);+}+float shelteredAt(vec3 W) {+ if (u_coverActive < 0.5) return 0.0;+ vec4 c = mat4(u_coverMatrix0, u_coverMatrix1, u_coverMatrix2, u_coverMatrix3) * vec4(W, 1.0);+ vec2 uv = c.xy / c.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 0.0;+ float stored = dot(texture(u_rainCover, uv).rgb, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));+ float here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);+ return stored < here - u_shelterBias / (4.0 * u_shelterRange) ? 1.0 : 0.0;+}++void main() {+ vec4 src = texture(u_texture, v_texCoord);+ ivec2 size = textureSize(u_sceneDepth, 0);+ ivec2 c = screenTexel(v_texCoord, size);+ float d = depthAt(c, size);+ vec3 col = src.rgb;+ Surface surface = readSurface(c);+ if (d < 1.0 && u_amount > 0.0 && !surface.water) {+ vec3 P = worldFromDepth(uvOfTexel(c, size), d);+ float dl = depthAt(c + ivec2(-1, 0), size);+ float dr = depthAt(c + ivec2( 1, 0), size);+ float dd = depthAt(c + ivec2(0, -1), size);+ float du = depthAt(c + ivec2(0, 1), size);+ vec3 ax = abs(dr - d) < abs(dl - d) ? worldAt(c + ivec2(1, 0), size) - P : P - worldAt(c + ivec2(-1, 0), size);+ vec3 ay = abs(du - d) < abs(dd - d) ? worldAt(c + ivec2(0, 1), size) - P : P - worldAt(c + ivec2(0, -1), size);+ vec3 N = normalize(cross(ax, ay));+ if (dot(N, viewDirection(P)) < 0.0) N = -N;+ // The surface's own normal where it wrote one, so a rock's bumps hold snow on their tops and shed it from their sides.+ vec3 Ns = surface.known ? surface.normal : N;+ if (dot(Ns, viewDirection(P)) < 0.0) Ns = -Ns;+ float grain = snowNoise(P.xz / u_grainScale) * 0.6 + snowNoise(P.xz / (u_grainScale * 0.43) + 3.7) * 0.28 + snowNoise(P.xz / (u_grainScale * 0.19) + 9.1) * 0.12;+ float faces = smoothstep(u_slopeLimit - 0.12, u_slopeLimit + 0.12, Ns.y + (grain - 0.5) * 0.25);+ float height = u_snowLineBand > 0.0 ? smoothstep(0.0, 1.0, (P.y - u_snowLine) / u_snowLineBand + grain - 0.5) : step(u_snowLine, P.y);+ float lies = faces * height * (1.0 - shelteredAt(P + vec3(0.0, 1.0, 0.0)));+ // Deeper snow closes over the ground from the grain's high places down; a dusting leaves the low ones bare.+ float cover = smoothstep(1.0 - u_amount * 1.15, 1.15 - u_amount, grain + 0.15) * lies;+ vec3 white = u_snowColor.rgb;+#ifdef ES_LINEAR+ white = srgbToLinear(white);+#endif+ float light = dot(src.rgb, vec3(0.2126, 0.7152, 0.0722));+ col = mix(col, white * (0.32 + 0.68 * smoothstep(0.0, 0.45, light)), cover);+ }+ fragColor = vec4(col, src.a);+}+#pragma end++#pragma fragment wgsl+${SSAO_WGSL}+${GBUFFER_WGSL}++fn snowHash(p : vec2f) -> f32 { return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453); }+fn snowNoise(p : vec2f) -> f32 {+ let i = floor(p);+ var f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(snowHash(i), snowHash(i + vec2f(1.0, 0.0)), f.x), mix(snowHash(i + vec2f(0.0, 1.0)), snowHash(i + vec2f(1.0, 1.0)), f.x), f.y);+}+fn shelteredAt(W : vec3f) -> f32 {+ if (mc.u_coverActive < 0.5) { return 0.0; }+ let m = mat4x4f(mc.u_coverMatrix0, mc.u_coverMatrix1, mc.u_coverMatrix2, mc.u_coverMatrix3);+ let c = m * vec4f(W, 1.0);+ let uv = c.xy / c.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 0.0; }+ // This device's texture rows run the other way from the clip space the map was drawn in.+ let stored = dot(textureSampleLevel(u_rainCover, u_rainCover_s, vec2f(uv.x, 1.0 - uv.y), 0.0).rgb,+ vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));+ let here = clamp(c.z / c.w * 0.5 + 0.5, 0.0, 1.0);+ return select(0.0, 1.0, stored < here - mc.u_shelterBias / (4.0 * mc.u_shelterRange));+}++@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);+ let size = vec2i(textureDimensions(t7, 0));+ let c = screenTexel(v.v_texCoord, size);+ let d = depthAt(c, size);+ var col = src.rgb;+ let surface = readSurface(c);+ if (d < 1.0 && mc.u_amount > 0.0 && !surface.water) {+ let P = worldFromDepth(uvOfTexel(c, size), d);+ let dl = depthAt(c + vec2i(-1, 0), size);+ let dr = depthAt(c + vec2i( 1, 0), size);+ let dd = depthAt(c + vec2i(0, -1), size);+ let du = depthAt(c + vec2i(0, 1), size);+ var ax = P - worldAt(c + vec2i(-1, 0), size);+ if (abs(dr - d) < abs(dl - d)) { ax = worldAt(c + vec2i(1, 0), size) - P; }+ var ay = P - worldAt(c + vec2i(0, -1), size);+ if (abs(du - d) < abs(dd - d)) { ay = worldAt(c + vec2i(0, 1), size) - P; }+ var N = normalize(cross(ax, ay));+ if (dot(N, viewDirection(P)) < 0.0) { N = -N; }+ var Ns = N;+ if (surface.known) { Ns = surface.normal; }+ if (dot(Ns, viewDirection(P)) < 0.0) { Ns = -Ns; }+ let grain = snowNoise(P.xz / mc.u_grainScale) * 0.6 + snowNoise(P.xz / (mc.u_grainScale * 0.43) + 3.7) * 0.28 + snowNoise(P.xz / (mc.u_grainScale * 0.19) + 9.1) * 0.12;+ let faces = smoothstep(mc.u_slopeLimit - 0.12, mc.u_slopeLimit + 0.12, Ns.y + (grain - 0.5) * 0.25);+ var height = step(mc.u_snowLine, P.y);+ if (mc.u_snowLineBand > 0.0) { height = smoothstep(0.0, 1.0, (P.y - mc.u_snowLine) / mc.u_snowLineBand + grain - 0.5); }+ let lies = faces * height * (1.0 - shelteredAt(P + vec3f(0.0, 1.0, 0.0)));+ let cover = smoothstep(1.0 - mc.u_amount * 1.15, 1.15 - mc.u_amount, grain + 0.15) * lies;+ var white = mc.u_snowColor.rgb;+#ifdef ES_LINEAR+ white = srgbToLinear(white);+#endif+ let light = dot(src.rgb, vec3f(0.2126, 0.7152, 0.0722));+ col = mix(col, white * (0.32 + 0.68 * smoothstep(0.0, 0.45, light)), cover);+ }+ return vec4f(col, src.a);+}+#pragma end`;return Material.compileShader(source);},diff --git a/sdk/src/postprocess/weather.ts b/sdk/src/postprocess/weather.tsindex d5ab626e4..c491045f0 100644--- a/sdk/src/postprocess/weather.ts+++ b/sdk/src/postprocess/weather.ts@@ -46,6 +46,8 @@ export interface WeatherState {rain: number;wetness: number;puddles: number;+ /** How much snow lies, 0..1. Absolute. */+ snow: number;/** × Screen Space Reflections' strength. */ssr: number;/** × what baked reflection probes show, and × their colour (1 keeps it, 0 is grey): a probe was baked under@@ -68,7 +70,7 @@ const NEUTRAL: WeatherState = {sun: 1, sky: 1, sunTint: [1, 1, 1], shadowSoftness: 1, shadowStrength: 1,fogDensity: 1, fogTint: [0.7, 0.72, 0.76], fogTintAmount: 0, fogGlow: 1, skyFog: 1,saturation: 1, contrast: 1, exposure: 0,- rain: 0, wetness: 0, puddles: 0, ssr: 1,+ rain: 0, wetness: 0, puddles: 0, snow: 0, ssr: 1,reflection: 1, reflectionSaturation: 1, overcast: 0, sound: 0, wind: 1, waves: 1,};@@ -78,6 +80,7 @@ export const WEATHER_MIST = 1;export const WEATHER_OVERCAST = 2;export const WEATHER_RAIN = 3;export const WEATHER_STORM = 4;+export const WEATHER_SNOW = 5;/** What `target` says when there is nothing to move toward. */export const WEATHER_NONE = -1;@@ -114,6 +117,10 @@ define(WEATHER_RAIN, 'rain', {fogGlow: 0, skyFog: 1.7, saturation: 0.73, contrast: 0.93, exposure: 0.45, rain: 1.1, wetness: 1, puddles: 0.6,ssr: 2.6, reflection: 0.55, reflectionSaturation: 0.5, overcast: 0.9, sound: 1, wind: 1.9, waves: 1.5,});+define(WEATHER_SNOW, 'snow', {+ sun: 0.7, sky: 1.05, sunTint: [0.92, 0.95, 1], shadowSoftness: 2, shadowStrength: 0.7, fogDensity: 1.8, fogTint: [0.82, 0.85, 0.9], fogTintAmount: 0.5,+ skyFog: 1.3, saturation: 0.85, contrast: 0.96, exposure: 0.1, snow: 0.85, overcast: 0.75, wind: 0.8,+});define(WEATHER_STORM, 'storm', {sun: 0.02, sky: 0.5, sunTint: [0.7, 0.78, 1], shadowSoftness: 10, shadowStrength: 0.2, fogDensity: 8, fogTint: [0.4, 0.44, 0.5], fogTintAmount: 0.9,fogGlow: 0, skyFog: 1.8, saturation: 0.6, contrast: 0.9, exposure: 0.8, rain: 2.2, wetness: 1, puddles: 1,@@ -282,6 +289,11 @@ export function applyWeatherToEffects(effects: Map<string, BlendedEffect>, statessr.uniforms.set('u_puddles', Math.max(value(ssr, 'ssr', 'u_puddles'), state.puddles));}}+ if ((drive & WeatherDrive.Rain) && (state.snow > 0.001 || effects.has('snowCover'))) {+ const authored = effects.has('snowCover');+ const snow = entry(effects, 'snowCover');+ snow.uniforms.set('u_amount', authored ? Math.max(value(snow, 'snowCover', 'u_amount'), state.snow) : state.snow);+ }if (drive & WeatherDrive.Grade) {const neutral = Math.abs(state.saturation - 1) < 1e-3 && Math.abs(state.contrast - 1) < 1e-3;const grade = effects.get('colorGrade');diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex 7583b3d18..435ea0fd5 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -11,6 +11,7 @@* frame clock as tc.u_time / tc.u_viewport.*/+import { deriveGroundBlend } from './groundBlendShader';import { paramDefaultValue, reflectEsshader } from './shaderReflect';export interface BuiltinShaderTemplate {@@ -1192,6 +1193,9 @@ export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [template('model', 'Model','What an imported model\'s material says: normal map, emission, occlusion, alpha cutoff.',MODEL),+ template('ground-blend', 'Ground Blend',+ 'Model, for what stands in the ground: fades into whatever is behind where it meets it, and can bring a second layer up from there or paint one with vertex colours.',+ deriveGroundBlend(MODEL)),template('toon', 'Toon','Lit in steps: the light cut into flat bands, a shade colour where it does not reach, a flat highlight and a rim. Shadows are part of a step.',TOON),diff --git a/sdk/src/render/groundBlendShader.ts b/sdk/src/render/groundBlendShader.tsnew file mode 100644index 000000000..3635e138e--- /dev/null+++ b/sdk/src/render/groundBlendShader.ts@@ -0,0 +1,168 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file groundBlendShader.ts+ * @brief The Model shader, for a rock, a kerb or a foundation that has to stand in the ground rather than on it.+ *+ * @details Where the surface comes close to what stands behind it, it gives way to the picture of that very pixel, so whatever+ * the ground is drawn with, its layers, its light and its shadows are what the seam fades into, with nothing baked and+ * nothing to keep in step. The same closeness can bring a second layer up the surface (dirt climbing a rock), and a+ * vertex colour's red can paint that layer by hand. How close is measured as height above what is behind, not along the+ * view, so the band does not widen and narrow as the camera tilts.+ *+ * Derived from Model, so a material moved onto it keeps every map and param it had. Such a material is drawn after a copy+ * of the opaque scene is taken, which is the whole of its cost.+ */++/** The fade and the second layer, added to Model's params. */+const PARAMS = `// How high above what stands behind it the surface has fully arrived, in world units. 0 leaves a hard edge.+#pragma param u_blendDistance float default(30) range(0,100000) ui(slider)+// How much the edge of that fade wanders, and the world size of its wander.+#pragma param u_blendNoise float default(0.5) range(0,1) ui(slider)+#pragma param u_blendNoiseScale float default(40) range(0.01,100000) ui(slider)+// A second layer: its picture, its colour, how rough it is, and how long one repeat is in the world (0 reads the mesh's own uv).+#pragma param u_layer2 texture default(white)+#pragma param u_layer2Tint color default(1,1,1,1)+#pragma param u_layer2Roughness float default(1) range(0,1) ui(slider)+#pragma param u_layer2Tile float default(0) range(0,100000) ui(slider)+// 1 lets a vertex colour's red paint the second layer, and stops the colour tinting the surface.+#pragma param u_vertexBlend float default(0) range(0,1) ui(slider)+// How far up from what stands behind it the second layer reaches, as a distance field does. 0 keeps it off.+#pragma param u_layerReach float default(0) range(0,100000) ui(slider)+#pragma param u_sceneDepthMap texture default(white) texel(data)+`;++const GLSL_HELPERS = `+float groundNoiseHash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }+// Soft noise in the world, about 0..1, so the seam is not a ruled line round the object.+float groundNoise(vec2 p) {+ vec2 i = floor(p);+ vec2 f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(groundNoiseHash(i), groundNoiseHash(i + vec2(1.0, 0.0)), f.x),+ mix(groundNoiseHash(i + vec2(0.0, 1.0)), groundNoiseHash(i + vec2(1.0, 1.0)), f.x), f.y);+}+`;++const WGSL_HELPERS = `+fn groundNoiseHash(p : vec2f) -> f32 { return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453); }+fn groundNoise(p : vec2f) -> f32 {+ let i = floor(p);+ var f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(groundNoiseHash(i), groundNoiseHash(i + vec2f(1.0, 0.0)), f.x),+ mix(groundNoiseHash(i + vec2f(0.0, 1.0)), groundNoiseHash(i + vec2f(1.0, 1.0)), f.x), f.y);+}+`;++const GLSL_SURFACE = ` float groundFade = 1.0;+ float layerWeight = u_vertexBlend > 0.5 ? v_color.r : 0.0;+ vec3 groundBehind = vec3(0.0);+#ifdef MESH_NORMALS+ if (texture(u_sceneDepthMap, vec2(0.5)).a < 0.75 && texture(u_sceneColor, vec2(0.5)).a < 0.75) {+ highp vec3 W = v_worldXYZ;+ vec4 onScreen = u_projection * vec4(W, 1.0);+ vec2 groundUv = clamp(onScreen.xy / max(onScreen.w, 1e-4) * 0.5 + 0.5, vec2(0.001), vec2(0.999));+ highp float own = u_camera.w > 0.5 ? length(W - u_camera.xyz) : -dot(W, u_camera.xyz);+ highp float along = texture(u_sceneDepthMap, groundUv).r - own;+ // Height above what is behind, which is the ray's fall: it does not change as the camera tilts. Past a dozen times the+ // band along the ray, what is behind is some other surface beyond, however level with this one it happens to be.+ highp float above = abs(viewDirection(W).y) * max(along, 0.0);+ float reach = max(u_blendDistance, u_layerReach);+ float near = 1.0 - smoothstep(8.0, 12.0, along / max(reach, 1e-3));+ float wander = (groundNoise(W.xz / max(u_blendNoiseScale, 0.01)) - 0.5) * u_blendNoise;+ if (u_blendDistance > 0.0) {+ groundFade = mix(1.0, smoothstep(0.0, 1.0, above / u_blendDistance + wander), near);+ groundBehind = texture(u_sceneColor, groundUv).rgb;+ }+ if (u_layerReach > 0.0) layerWeight = max(layerWeight, near * (1.0 - smoothstep(0.0, 1.0, above / u_layerReach + wander)));+ }+#endif+ vec4 base = texture(u_textures[0], v_texCoord) * u_tint;+ if (u_vertexBlend <= 0.5) base *= v_color;+ if (layerWeight > 0.0) {+#ifdef MESH_NORMALS+ vec2 layerUv = u_layer2Tile > 0.0 ? v_worldXYZ.xz / u_layer2Tile : v_texCoord;+#else+ vec2 layerUv = v_texCoord;+#endif+ base = mix(base, texture(u_layer2, layerUv) * u_layer2Tint, layerWeight);+ }+`;++const WGSL_SURFACE = `#ifdef MESH_NORMALS+ // Before any branch: a derivative needs every fragment of its quad.+ let layerWorld = v.v_worldXYZ.xz / max(mc.u_layer2Tile, 1e-4);+ let layerWorldDx = dpdx(layerWorld);+ let layerWorldDy = dpdy(layerWorld);+#endif+ var groundFade = 1.0;+ var layerWeight = 0.0;+ if (mc.u_vertexBlend > 0.5) { layerWeight = v.v_color.r; }+ var groundBehind = vec3f(0.0);+#ifdef MESH_NORMALS+ let groundWanted = textureSampleLevel(u_sceneDepthMap, u_sceneDepthMap_s, vec2f(0.5), 0.0).a < 0.75+ && textureSampleLevel(u_sceneColor, u_sceneColor_s, vec2f(0.5), 0.0).a < 0.75;+ if (groundWanted) {+ let W = v.v_worldXYZ;+ let onScreen = frame.projection * vec4f(W, 1.0);+ let screenW = max(onScreen.w, 1e-4);+ // This device's rows run down the texture, so clip y is flipped on the way to a uv.+ let groundUv = clamp(vec2f(onScreen.x / screenW * 0.5 + 0.5, 0.5 - onScreen.y / screenW * 0.5), vec2f(0.001), vec2f(0.999));+ var own = -dot(W, frame.camera.xyz);+ if (frame.camera.w > 0.5) { own = length(W - frame.camera.xyz); }+ let along = textureSampleLevel(u_sceneDepthMap, u_sceneDepthMap_s, groundUv, 0.0).r - own;+ let above = abs(viewDirection(W).y) * max(along, 0.0);+ let reach = max(mc.u_blendDistance, mc.u_layerReach);+ let near = 1.0 - smoothstep(8.0, 12.0, along / max(reach, 1e-3));+ let wander = (groundNoise(W.xz / max(mc.u_blendNoiseScale, 0.01)) - 0.5) * mc.u_blendNoise;+ if (mc.u_blendDistance > 0.0) {+ groundFade = mix(1.0, smoothstep(0.0, 1.0, above / mc.u_blendDistance + wander), near);+ groundBehind = textureSampleLevel(u_sceneColor, u_sceneColor_s, groundUv, 0.0).rgb;+ }+ if (mc.u_layerReach > 0.0) { layerWeight = max(layerWeight, near * (1.0 - smoothstep(0.0, 1.0, above / mc.u_layerReach + wander))); }+ }+#endif+ var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * mc.u_tint;+ if (mc.u_vertexBlend <= 0.5) { base = base * v.v_color; }+ if (layerWeight > 0.0) {+#ifdef MESH_NORMALS+ var layerUv = v.v_texCoord;+ var layerDx = duvx;+ var layerDy = duvy;+ if (mc.u_layer2Tile > 0.0) {+ layerUv = layerWorld;+ layerDx = layerWorldDx;+ layerDy = layerWorldDy;+ }+ base = mix(base, textureSampleGrad(u_layer2, u_layer2_s, layerUv, layerDx, layerDy) * mc.u_layer2Tint, layerWeight);+#else+ base = mix(base, textureSampleGrad(u_layer2, u_layer2_s, v.v_texCoord, duvx, duvy) * mc.u_layer2Tint, layerWeight);+#endif+ }+`;++function swap(source: string, from: string, to: string): string {+ if (!source.includes(from)) throw new Error(`the Model shader no longer has what Ground Blend is made from: ${from.slice(0, 60)}`);+ return source.replace(from, () => to);+}++/** Ground Blend from the Model shader's source. A refraction reads the same picture, and the two would fight over it, so it is taken out. */+export function deriveGroundBlend(model: string): string {+ let s = swap(model, '#pragma shader "Model"', '#pragma shader "Ground Blend"');+ s = swap(s, '#pragma param u_transmission float default(0) range(0,1) ui(slider)\n', '');+ // With no such param the engine knows this always wants the copy (MaterialStore::usesSceneColor), and the branch below is never taken.+ s = s.replace(/mc\.u_transmission/g, '0.0').replace(/u_transmission/g, '0.0');+ s = swap(s, '#pragma param u_iridescence float', `${PARAMS}#pragma param u_iridescence float`);+ s = swap(s, 'float specularAA(highp vec3', `${GLSL_HELPERS}float specularAA(highp vec3`);+ s = swap(s, 'fn specularAA(dndx : vec3f', `${WGSL_HELPERS}fn specularAA(dndx : vec3f`);+ s = swap(s, ' vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;\n', GLSL_SURFACE);+ s = swap(s, ' var base = textureSampleGrad(t0, s0, v.v_texCoord, duvx, duvy) * v.v_color * mc.u_tint;\n', WGSL_SURFACE);+ s = swap(s, 'float roughness = u_roughness * mr.g;', 'float roughness = mix(u_roughness * mr.g, u_layer2Roughness, layerWeight);');+ s = swap(s, 'var roughness = mc.u_roughness * mr.g;', 'var roughness = mix(mc.u_roughness * mr.g, mc.u_layer2Roughness, layerWeight);');+ s = swap(s, 'fragColor = vec4(lit + seen + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, alpha);',+ 'fragColor = vec4(mix(groundBehind, lit + seen + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, groundFade), alpha);');+ s = swap(s, 'frag.color = vec4f(lit + seen + emit, alpha);', 'frag.color = vec4f(mix(groundBehind, lit + seen + emit, groundFade), alpha);');+ s = swap(s, 'return vec4f(lit + seen + emit, alpha);', 'return vec4f(mix(groundBehind, lit + seen + emit, groundFade), alpha);');+ return s;+}diff --git a/sdk/src/spline/index.ts b/sdk/src/spline/index.tsindex 65085ce42..b64fcf1ca 100644--- a/sdk/src/spline/index.ts+++ b/sdk/src/spline/index.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { Spline, SplinePlugin, splinePlugin, PathFollower, PathMode, PathOrient, pathPlace, type SplineData, type PathFollowerData } from './splinePlugin';export { TerrainBand2D, buildTerrainBand, type TerrainBand2DData, type TerrainBandBuild } from './terrainBand2D';+export { RoadDecal, buildRoadDecal, type RoadDecalData, type RoadGround } from './roadDecal';export { SplineCurve, type SplinePoint, type SplineNearest } from './curve';// Importing this subpath INSTALLS splines — see tilemap/index.ts.diff --git a/sdk/src/spline/roadDecal.ts b/sdk/src/spline/roadDecal.tsnew file mode 100644index 000000000..d438045b0--- /dev/null+++ b/sdk/src/spline/roadDecal.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file roadDecal.ts+ * @brief A road, a track or a stain laid along a Spline and over the ground, its edges fading into what it lies on.+ *+ * @details A decal is cut from meshes, and a terrain is no mesh: it is drawn from height pages, coarser with distance. So this asks+ * the ground where it is, row by row across the curve, and draws the strip as the entity's own MeshRenderer, so a material+ * on it can be anything. Its colour's alpha falls to nothing at both edges, so the seam with the ground is a gradient and+ * not a line. It is made again when the spline, its fields or the ground change. The terrain module is optional and asked by+ * name: with none, the strip lies along the curve as drawn.+ */+import type { App } from '../app/app';+import type { Entity } from '../types';+import { defineComponent, MeshRenderer, Transform, type ComponentDef, type MeshRendererData, type TransformData } from '../ecs/component';+import { defineSystem, Schedule } from '../ecs/system';+import { Assets } from '../asset/AssetPlugin';+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';+import { SplineCurve } from './curve';+import { Spline, type SplineData } from './splineComponent';++/** The fields of the `RoadDecal` component. @experimental */+export interface RoadDecalData {+ /** How far apart its rows are along the curve, in world units: finer follows the ground and the bends more closely. */+ step: number;+ /** How many cells across. More follows a ground that crowns or slopes under the road. */+ across: number;+ /** × the width each spline point says. */+ widthScale: number;+ /** How far above the ground it lies, in world units. Enough to win against the ground from as far as it is seen. */+ lift: number;+ /** The share of its half width over which each edge fades, 0 to 1. */+ edgeFade: number;+ /** The length of one repeat of its texture along the curve, in world units. */+ tile: number;+}++/**+ * Lays the entity's MeshRenderer along the `Spline` of the same entity and over the ground.+ *+ * @experimental+ */+export const RoadDecal: ComponentDef<RoadDecalData> = defineComponent<RoadDecalData>('RoadDecal', {+ step: 20, across: 4, widthScale: 1, lift: 0.5, edgeFade: 0.35, tile: 200,+}, {+ fields: {+ step: { min: 0.01, unit: 'wu', tooltip: 'How far apart its rows are along the curve. Finer follows the ground and the bends more closely.' },+ across: { min: 1, max: 32, step: 1, tooltip: 'How many cells across. More follows a ground that crowns or slopes under the road.' },+ widthScale: { min: 0, step: 0.01, tooltip: 'Times the width each spline point says.' },+ lift: { min: 0, step: 0.01, unit: 'wu', tooltip: 'How far above the ground it lies. Enough to win against the ground from as far as it is seen.' },+ edgeFade: { min: 0, max: 1, step: 0.01, tooltip: 'The share of its half width over which each edge fades into the ground.' },+ tile: { min: 0.01, unit: 'wu', tooltip: 'The length of one repeat of its texture along the curve.' },+ },+});++/** What the ground answers, from a terrain or a planet's surface. Read by name: a game with neither pays for neither. */+export interface RoadGround {+ heightAt(x: number, z: number): number | null;+ normalAt?(x: number, z: number): readonly [number, number, number] | null;+}++/**+ * The strip's geometry, relative to `origin`. Null where it has nothing to lay. Positions lie on the ground where it answers and on the curve+ * where it does not; texture v runs along the curve in world units over `tile`, and u across from 0 to 1.+ */+export function buildRoadDecal(spline: SplineData, road: RoadDecalData, origin: { x: number; y: number; z: number }, ground: RoadGround | null): MeshData | null {+ if (spline.points.length < 2) return null;+ const curve = new SplineCurve(spline.points, spline.closed);+ if (!(curve.length > 1e-3)) return null;+ const rows = Math.max(1, Math.min(4096, Math.ceil(curve.length / Math.max(road.step, 1e-3))));+ const cells = Math.max(1, Math.min(32, Math.floor(road.across)));+ const fade = Math.min(1, Math.max(0, road.edgeFade));+ 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 = (rows + 1) * (cells + 1);+ const vertices = new Uint8Array(vertexCount * vertexStride);+ const view = new DataView(vertices.buffer);+ const at = (semantic: number): number => channels.find((c) => c.semantic === semantic)!.offset;+ const posAt = at(MeshChannel.Position), uvAt = at(MeshChannel.TexCoord0), colorAt = at(MeshChannel.Color), normalAt = at(MeshChannel.Normal);+ const min: [number, number, number] = [Infinity, Infinity, Infinity];+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ let vertex = 0;+ for (let r = 0; r <= rows; r++) {+ const s = curve.length * (r / rows);+ const [cx, cy, cz] = curve.position(s);+ const [tx, , tz] = curve.tangent(s);+ const len = Math.hypot(tx, tz) || 1;+ // Across the road on the ground: a curve climbing a hill still has a level side.+ const sx = -tz / len, sz = tx / len;+ const half = curve.width(s) * 0.5 * road.widthScale;+ for (let c = 0; c <= cells; c++, vertex++) {+ const u = c / cells;+ const offset = (u * 2 - 1) * half;+ const wx = origin.x + cx + sx * offset, wz = origin.z + cz + sz * offset;+ const y = ground?.heightAt(wx, wz) ?? origin.y + cy;+ const n = ground?.normalAt?.(wx, wz) ?? [0, 1, 0];+ const p = [wx - origin.x, y + road.lift - origin.y, wz - origin.z] as const;+ const base = vertex * vertexStride;+ for (let k = 0; k < 3; k++) {+ view.setFloat32(base + posAt + k * 4, p[k]!, true);+ view.setFloat32(base + normalAt + k * 4, n[k]!, true);+ if (p[k]! < min[k]!) min[k] = p[k]!;+ if (p[k]! > max[k]!) max[k] = p[k]!;+ }+ view.setFloat32(base + uvAt, u, true);+ view.setFloat32(base + uvAt + 4, s / Math.max(road.tile, 1e-3), true);+ const edge = 1 - Math.abs(u * 2 - 1);+ const alpha = fade > 0 ? Math.min(1, edge / fade) : 1;+ view.setUint8(base + colorAt, 255);+ view.setUint8(base + colorAt + 1, 255);+ view.setUint8(base + colorAt + 2, 255);+ // Eased, so the edge has no line of its own where the fade begins.+ view.setUint8(base + colorAt + 3, Math.round(alpha * alpha * (3 - 2 * alpha) * 255));+ }+ }+ const indices = new Uint32Array(rows * cells * 6);+ let i = 0;+ for (let r = 0; r < rows; r++) {+ for (let c = 0; c < cells; c++) {+ const a = r * (cells + 1) + c, b = a + 1, d = a + cells + 1, e = d + 1;+ indices[i++] = a; indices[i++] = b; indices[i++] = d;+ indices[i++] = b; indices[i++] = e; indices[i++] = d;+ }+ }+ return { channels, vertexStride, vertexCount, vertices, indices, aabbMin: min, aabbMax: max };+}++/** The ground, whichever module answers it, and how to tell when it has changed. */+function groundOf(app: App): { query: RoadGround; revision: number; waiting: boolean } | null {+ const terrains = app.getResourceByName?.('Terrains') as (RoadGround & { revision_?: number; loading?: boolean; built_?: Map<unknown, unknown> }) | undefined;+ if (!terrains || typeof terrains.heightAt !== 'function' || !terrains.built_?.size) return null;+ return { query: terrains, revision: terrains.revision_ ?? 0, waiting: !!terrains.loading };+}++/** Keeps every `RoadDecal` lying on the ground. Called once by the spline plugin. */+export function installRoadDecals(app: App): void {+ const built = new Map<Entity, { key: string; handle: number }>();+ const letGo = (entity: Entity): void => {+ const held = built.get(entity);+ built.delete(entity);+ if (held?.handle && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(held.handle);+ };+ app.world.onDespawn(letGo);+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ const world = app.world;+ if (!app.hasResource(Assets)) return;+ const assets = app.getResource(Assets);+ for (const entity of [...built.keys()]) if (!world.valid(entity) || !world.has(entity, RoadDecal)) letGo(entity);+ for (const entity of world.getEntitiesWithComponents([RoadDecal, Spline, Transform])) {+ const ground = groundOf(app);+ // Laid on a ground still being read, it would lie on nothing and be laid again a moment later.+ if (ground?.waiting) continue;+ const road = world.get(entity, RoadDecal) as RoadDecalData;+ const spline = world.get(entity, Spline) as SplineData;+ const t = world.get(entity, Transform) as TransformData;+ const origin = t.worldPosition;+ const key = JSON.stringify([spline.points, spline.closed, road, ground?.revision ?? -1, origin.x, origin.y, origin.z]);+ const held = built.get(entity);+ if (held?.key === key) continue;+ const mesh = buildRoadDecal(spline, road, origin, ground?.query ?? null);+ const handle = mesh ? assets.createMesh(mesh) : 0;+ if (held?.handle) assets.releaseBuiltMesh(held.handle);+ built.set(entity, { key, handle });+ const renderer = world.has(entity, MeshRenderer) ? world.get(entity, MeshRenderer) as MeshRendererData : null;+ world.insert(entity, MeshRenderer, { ...renderer, enabled: true, mesh: handle, opaque: false, castShadows: false, cullBackfaces: false } as Partial<MeshRendererData>);+ }+ }, { name: 'RoadDecalSystem' }));+}diff --git a/sdk/src/spline/splinePlugin.ts b/sdk/src/spline/splinePlugin.tsindex cf0dc4dbc..07665f11f 100644--- a/sdk/src/spline/splinePlugin.ts+++ b/sdk/src/spline/splinePlugin.ts@@ -15,6 +15,7 @@ import { playModeOnly } from '../ecs/env';import { defineComponent, Transform, type ComponentDef, type TransformData } from '../ecs/component';import { SplineCurve, type SplinePoint } from './curve';import { installTerrainBands } from './terrainBand2D';+import { installRoadDecals } from './roadDecal';import { Spline, type SplineData } from './splineComponent';export { Spline, type SplineData } from './splineComponent';@@ -100,6 +101,7 @@ export class SplinePlugin implements Plugin {defineSystem([Res(Time)], (time: TimeData) => this.follow(app, time.delta), { name: 'PathFollowerSystem' }),{ runIf: playModeOnly });installTerrainBands(app);+ installRoadDecals(app);}private curveOf(app: App, entity: number): { curve: SplineCurve; at: TransformData } | null {diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex 46ae3da81..53abd11f3 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -2019,6 +2019,10 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"label": "Storm","value": 4,},+ {+ "label": "Snow",+ "value": 5,+ },],},"progress": {@@ -2052,6 +2056,10 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"label": "Storm","value": 4,},+ {+ "label": "Snow",+ "value": 5,+ },],},},diff --git a/sdk/tests/road-decal.test.ts b/sdk/tests/road-decal.test.tsnew file mode 100644index 000000000..b5369015f--- /dev/null+++ b/sdk/tests/road-decal.test.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** The strip a road lays on the ground: where its vertices go is what decides whether it lies on the hills or cuts through them. */+import { describe, expect, it } from 'vitest';+import { MeshChannel, type MeshData } from '../src/asset/meshFormat';+import { buildRoadDecal, type RoadDecalData, type RoadGround } from '../src/spline/roadDecal';+import type { SplineData } from '../src/spline/splineComponent';++const ROAD: RoadDecalData = { step: 10, across: 4, widthScale: 1, lift: 0.5, edgeFade: 0.5, tile: 100 };+const straight = (width = 40): SplineData => ({ closed: false, points: [{ x: 0, y: 7, z: 0, width }, { x: 100, y: 7, z: 0, width }] });+const ORIGIN = { x: 0, y: 0, z: 0 };++function read(mesh: MeshData) {+ const view = new DataView(mesh.vertices.buffer);+ const at = (semantic: number) => mesh.channels.find((c) => c.semantic === semantic)!.offset;+ const out: { x: number; y: number; z: number; u: number; v: number; alpha: number; ny: number }[] = [];+ for (let i = 0; i < mesh.vertexCount; i++) {+ const b = i * mesh.vertexStride;+ out.push({+ x: view.getFloat32(b + at(MeshChannel.Position), true), y: view.getFloat32(b + at(MeshChannel.Position) + 4, true), z: view.getFloat32(b + at(MeshChannel.Position) + 8, true),+ u: view.getFloat32(b + at(MeshChannel.TexCoord0), true), v: view.getFloat32(b + at(MeshChannel.TexCoord0) + 4, true),+ alpha: view.getUint8(b + at(MeshChannel.Color) + 3) / 255, ny: view.getFloat32(b + at(MeshChannel.Normal) + 4, true),+ });+ }+ return out;+}++describe('a road on the ground', () => {+ it('lies where the ground says, a lift above it, wherever the curve itself was drawn', () => {+ const hills: RoadGround = { heightAt: (x, z) => Math.sin(x * 0.1) * 20 + z * 0.5 };+ const mesh = buildRoadDecal(straight(), ROAD, ORIGIN, hills)!;+ for (const p of read(mesh)) expect(p.y).toBeCloseTo(Math.sin(p.x * 0.1) * 20 + p.z * 0.5 + 0.5, 2);+ });++ it('lies along the curve as drawn with no ground to ask, or where the ground has no answer', () => {+ for (const p of read(buildRoadDecal(straight(), ROAD, ORIGIN, null)!)) expect(p.y).toBeCloseTo(7.5, 3);+ const edge: RoadGround = { heightAt: (x) => (x < 50 ? 3 : null) };+ const pts = read(buildRoadDecal(straight(), ROAD, ORIGIN, edge)!);+ expect(pts.find((p) => p.x < 40)!.y).toBeCloseTo(3.5, 3);+ expect(pts.find((p) => p.x > 60)!.y).toBeCloseTo(7.5, 3);+ });++ it('is measured from the entity, whose place it is drawn through', () => {+ const hills: RoadGround = { heightAt: () => 10 };+ const pts = read(buildRoadDecal(straight(), ROAD, { x: 1000, y: 4, z: -500 }, hills)!);+ expect(pts[0]!.y).toBeCloseTo(6.5, 3);+ expect(pts[0]!.x).toBeCloseTo(0, 3);+ });++ it('asks the ground at the world place, not the local one', () => {+ const seen: number[] = [];+ buildRoadDecal(straight(), { ...ROAD, step: 100 }, { x: 1000, y: 0, z: 0 }, { heightAt: (x) => { seen.push(x); return 0; } });+ expect(Math.min(...seen)).toBeGreaterThanOrEqual(1000);+ });++ it('is as wide as the spline says, times its scale', () => {+ const z = (scale: number) => read(buildRoadDecal(straight(40), { ...ROAD, widthScale: scale }, ORIGIN, null)!).map((p) => p.z);+ expect(Math.max(...z(1)) - Math.min(...z(1))).toBeCloseTo(40, 3);+ expect(Math.max(...z(0.5)) - Math.min(...z(0.5))).toBeCloseTo(20, 3);+ });++ it('fades to nothing at both edges and is whole down the middle', () => {+ const pts = read(buildRoadDecal(straight(), ROAD, ORIGIN, null)!);+ expect(pts.filter((p) => p.u === 0 || p.u === 1).every((p) => p.alpha === 0)).toBe(true);+ expect(pts.filter((p) => p.u === 0.5).every((p) => p.alpha === 1)).toBe(true);+ });++ it('keeps a hard edge when told to', () => {+ const pts = read(buildRoadDecal(straight(), { ...ROAD, edgeFade: 0 }, ORIGIN, null)!);+ expect(pts.every((p) => p.alpha === 1)).toBe(true);+ });++ it('repeats its texture along the curve by world length', () => {+ const pts = read(buildRoadDecal(straight(), ROAD, ORIGIN, null)!);+ expect(Math.max(...pts.map((p) => p.v))).toBeCloseTo(1, 3);+ const longer = read(buildRoadDecal(straight(), { ...ROAD, tile: 25 }, ORIGIN, null)!);+ expect(Math.max(...longer.map((p) => p.v))).toBeCloseTo(4, 3);+ });++ it('takes the ground\'s normal, so it is lit as the ground is', () => {+ const pts = read(buildRoadDecal(straight(), ROAD, ORIGIN, { heightAt: () => 0, normalAt: () => [0, 0.6, 0.8] })!);+ expect(pts[0]!.ny).toBeCloseTo(0.6, 3);+ });++ it('has triangles that face up and name only its own vertices', () => {+ const mesh = buildRoadDecal(straight(), ROAD, ORIGIN, null)!;+ expect(Math.max(...mesh.indices)).toBeLessThan(mesh.vertexCount);+ const pts = read(mesh);+ const [a, b, c] = [pts[mesh.indices[0]!]!, pts[mesh.indices[1]!]!, pts[mesh.indices[2]!]!];+ const ny = (b.z - a.z) * (c.x - a.x) - (b.x - a.x) * (c.z - a.z);+ expect(ny).toBeGreaterThan(0);+ });++ it('lays nothing for a curve with nothing in it', () => {+ expect(buildRoadDecal({ closed: false, points: [{ x: 0, y: 0, z: 0, width: 1 }] }, ROAD, ORIGIN, null)).toBeNull();+ expect(buildRoadDecal({ closed: false, points: [{ x: 5, y: 0, z: 5, width: 1 }, { x: 5, y: 0, z: 5, width: 1 }] }, ROAD, ORIGIN, null)).toBeNull();+ });+});diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.tsindex 51dd14c7c..59498e099 100644--- a/sdk/tests/shader-twins.test.ts+++ b/sdk/tests/shader-twins.test.ts@@ -53,7 +53,7 @@ describe('embedded .esshader structure', () => {it('found the filter, effect and grid sources', () => {expect(CASES.filter((c) => c.name.startsWith('filters.ts')).length).toBe(1);expect(CASES.filter((c) => c.name.startsWith('spriteFilter.ts')).length).toBe(2);- expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(43);+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(44);expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);});diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex 6ceb5ac3c..f41bf6ee2 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -367,6 +367,13 @@ void DrawList::stageBlocks(const PerDrawBlockSet& blocks) {}}+bool DrawList::anyNeedsScenePicture(const MaterialStore& materials) const {+ for (usize i = 0; i < commands_.size(); ++i) {+ if (commands_[i].material_id != 0 && materials.needsScenePicture(commands_[i].material_id)) return true;+ }+ return false;+}+bool DrawList::anyUsesSceneColor(const MaterialStore& materials) const {for (u32 i = 0; i < merged_draw_calls_; ++i) {if (commands_[i].material_id != 0 && materials.usesSceneColor(commands_[i].material_id)) return true;diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex 82f2441eb..99095041a 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -82,6 +82,8 @@ public:/// Whether any merged draw reads the picture behind it.bool anyUsesSceneColor(const MaterialStore& materials) const;+ /** @brief Whether a draw is of a material that does not work without a picture of the scene (MaterialStore::needsScenePicture). */+ bool anyNeedsScenePicture(const MaterialStore& materials) const;/// Whether the list holds a blended draw that does not refract: what has to be ordered against a refracting surface by where it is, not by when it was drawn.bool anyBlendedWithoutSceneColor(const MaterialStore& materials) const;/// Whether any merged draw reads the distance to the opaque scene behind it.diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 45b0eabd0..954b60e08 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -391,7 +391,9 @@ void RenderFrame::beginFrame() {if (frame_collected_) {depth_answered_ = true;if (frame_depth_seen_) depth_seen_ = true;+ scene_picture_seen_ = frame_scene_picture_seen_;}+ frame_scene_picture_seen_ = false;frame_collected_ = false;frame_depth_seen_ = false;applySceneDepthNeed();@@ -421,8 +423,8 @@ void RenderFrame::applySceneDepthNeed() {#ifdef ES_ENABLE_GPU_PARTICLEScomputeNeedsDepth = gpu_particles_ && gpu_particles_->wantsDepth();#endif- post_process_->setComputeNeedsDepth(computeNeedsDepth);- post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_ || computeNeedsDepth+ post_process_->setComputeNeedsDepth(computeNeedsDepth || scene_picture_seen_);+ post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_ || computeNeedsDepth || scene_picture_seen_|| draw_list_.depthMask() != 0);#endif}@@ -2713,6 +2715,7 @@ void RenderFrame::collectAll(ecs::Registry& registry, bool sceneGBuffer) {// editor's grid draws into it between begin() and this collect.frame_collected_ = true;frame_depth_seen_ = frame_depth_seen_ || draw_list_.needsDepth();+ frame_scene_picture_seen_ = frame_scene_picture_seen_ || draw_list_.anyNeedsScenePicture(context_.materials());}void RenderFrame::collectMotion(ecs::Registry& registry) {diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 5dd7f4358..90b1c6fd2 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -677,6 +677,9 @@ private:bool depth_seen_ = false;/// This frame's cameras, OR-ed; rolled into depth_seen_ at the next beginFrame.bool frame_depth_seen_ = false;+ /// A draw last frame could not work without a picture of the scene, so this frame's scene is drawn where one can be read.+ bool scene_picture_seen_ = false;+ bool frame_scene_picture_seen_ = false;/// Whether this frame collected at all — an uncollected frame answers nothing,/// so it must not be read as "nothing here needs depth".bool frame_collected_ = false;diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex cb16be430..83748c7b0 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -384,6 +384,13 @@ public:const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;return layout && layout->findTexture("u_sceneDepthMap") != nullptr;}+ /// Whether @p materialId is nothing without that copy: it fades into what is behind it, where water only falls back to a plainer look.+ /// Seeing one is why a frame with no chain of its own takes one.+ bool needsScenePicture(u32 materialId) const {+ const MaterialRecord* m = find(materialId);+ const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;+ return layout && layout->find("u_blendDistance") != nullptr;+ }/// The copy of the opaque scene's distances the frame took, or invalid when it took none. Bound to a material's `u_sceneDepthMap` unit.void setSceneDepth(TextureHandle texture) { sceneDepth_ = texture; }diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex cf1947a7b..2046cc999 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -125,6 +125,7 @@ const DISPOSITION = {Planet: ['owed', 'authored by a game today (star-neighbors, a round planet from its own generator); an example that registers a planet provider is owed'],MeshInstances: ['derived', 'the foliage and world generation systems write it, one entity a kind and part of a cell; its places are data a system computes, not something a scene authors'],ParticleCollider: ['owed', 'no example has a GPU emitter bouncing off a shape yet; the particle-gpu scenes are where the first one goes'],+ RoadDecal: ['owed', 'no example lays a road over a terrain yet; wilds is where the first one goes'],PlantProxy: ['derived', 'the plant interaction makes it for a plant near a contact, and takes it away again; a scene never holds one'],FoliageContact: ['owed', 'no example has a character walking through plants yet; wilds gains one when it gets a player'],PlacedFoliage: ['derived', 'a generated world grows its plants through the same machinery without the component, and a project that places plants by hand writes the kinds and records with a script from its own rules; the lists are generated data, not something a scene is authored by hand with'],diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjsindex 59525d85e..970545bc6 100644--- a/tools/check-gizmo-coverage.mjs+++ b/tools/check-gizmo-coverage.mjs@@ -202,6 +202,7 @@ const DISPOSITION = {'CharacterController2D.skinWidth': ['no-place', 'a contact skin held off the collider; drawn, it is that outline\'s own line width'],'CharacterController2D.stepHeight': ['no-place', 'the highest ledge it walks up: a limit on motion, not a volume'],'FoliageContact.radius': ['no-place', 'how far plants lean from it, seen on the plants themselves; a ring drawn for it would sit under the grass'],+ 'RoadDecal.widthScale': ['no-place', 'a multiplier on the widths its Spline already draws, and the strip it lays shows the result'],'CharacterController3D.stepHeight': ['no-place', 'the tallest step it will climb — a limit on motion, not a volume'],'NavVolume.cellSize': ['no-place', 'the voxel the box is diced into; the box is what has a place'],'NavVolume.cellHeight': ['no-place', 'the voxel the box is diced into; the box is what has a place'],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7147a6b36..3b07eab75 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4232,6 +4232,8 @@ export const NOTED = {{"note": "Particles and plain sprites in a Canvas paint by their place in its tree."},"fix(text): stopping lets go of the labels the engine holds, so the next Play cannot draw them on other entities":{"note": "Labels no longer come back as black boxes after a change between Plays."},+ "feat(terrain): a material that fades into the ground it meets, a road laid over a terrain, and snow on whatever faces the sky":+ {"note": "What stands on the ground can blend into it."},"fix(assets): one hot load at a time per asset, so two rescans cannot lose a texture":{"note": "A texture stays on a scene that rescans as it is placed."},"feat(rig): the 2D rig editor, from an image to a character in the scene":