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(render): Contact Shadows and Screen Space GI effects, and the weather softens the sun's shadows
yhh9baab8bc601f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a0ec2f423..ce3a4970b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **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.- **Weather.** A Weather component puts a scene under clear, mist, overcast, rain or storm, turns between them and cycles by itself. A preset is a set of multipliers of what the scene already has — the sun at a fraction of its strength, the fog thicker, the picture greyer — plus absolute levels for rain and wetness, so one preset fits any project. The component drives the directional and ambient lights (in play mode only), the effects the scene's volumes resolve (Height Fog, Rain, Screen Space Reflections, Colour Grade, Auto Exposure), and takes `registerWeatherPreset` for weathers of a project's own. Volumes whose effects differ only in numbers now write the numbers into the passes they have instead of rebuilding them. Reflection probes follow the weather: the ambient light scales what baked probes show and how much colour they keep. The Ambient `Light` gains `reflectionScale` and `reflectionSaturation`, which the weather drives. Rain stays off what stands under a roof, and the Weather component turns a looping rain track up and down. The frame draws the scene once from straight above, depth only, around the camera whenever a `rain` effect is in the chain, and the effect keeps wetness, puddles, ripples and streaks off ground that something stands over; `soundSource` names the `AudioSource` the weather drives.- **Quality levels are edited in Settings.** Settings → Project → Rendering edits each quality level, including which effects it runs. **Editing level** picks Low, Medium or High and the groups below — Rendering (render scale, minimum scale, MSAA), Shadows, Reflections and particles, Post-processing — show and change that level, so a level is read the way Unity's Quality page reads: a level, then its settings by subsystem. Post-processing lists every effect the engine has, ticked where the level runs it; an unticked one is skipped at that level wherever a camera's volume asks for it, with all of its passes. Device rules — the model, GPU, memory and core conditions Auto chooses a level by — are a table, shown when the mode is Auto, that says so on a row with no condition instead of dropping it while it is typed. Only what you change is saved to `project.esproject`, as a difference to that level, so an engine default that improves later still reaches a project that never touched it; a row's "changed" mark and reset follow the default of the level it is showing. The old per-level shadow distance rows are the Shadows group's Distance now. The effects a level leaves out had been matched by the prefix of a pass's name, which found none of Auto Exposure's passes; they are now matched by effect type. A new Quality Levels page in the performance docs describes it.- **A G-buffer, and reflections that read it.** Reflections now know how rough and how metal each surface is, from a G-buffer the frame draws on request. A post-process shader that says `#pragma gbuffer` makes the scene target carry a second RGBA8 colour attachment, written in the same pass by the scene's own shaders — octahedral normal in `r`/`g`, roughness in `b`, metalness in `a` (0 where nothing wrote) — and finds it at `u_gbuffer`. A frame whose chain has no such effect makes none and compiles no variant. The render device grew multiple colour attachments for it on both backends: WebGL2 attaches and resolves a second target and sets the draw buffers per pipeline, and WebGPU declares the second target on every pipeline of the pass (written by the ones that write it, an empty write mask for the rest), clears it to zero and resolves it with the colour. Pipelines say whether they write it (`PipelineDesc::gbuffer`), a blended draw never does, and the second output is its own shader variant (`ES_GBUFFER`), so no pass pays for what it did not ask for. The built-in Model shader — what an imported glTF material becomes — writes it from the material's roughness, metalness and normal map. `ssr` reads it: it takes the surface's own normal (normal-map detail that depth cannot see), weighs and blurs the reflection by roughness, reflects a metal at nearly full strength where a dielectric reflects 4%, skips a surface rougher than `maxRoughness` before marching the ray, and takes the Rain effect's `wetness` as a film that smooths the ground. Where nothing wrote a record, it falls back to depth and the dielectric it has always assumed. Verified in the editor on both backends: of two floors that differ only in their material's roughness, the glossy one changes ten times the pixels the rough one does. Quality levels can also leave out expensive effects now: quality levels can now skip expensive post-process effects by name. A level's `skipEffects` lists the effects it leaves out, each named by its effect type (`ssr`, `taa`, `depthOfField`, `lightShafts`, `autoExposure`, …), and an effect leaves with all of its passes however they are named; a project's own list in its quality profile replaces the level's. By default low leaves out reflections, temporal anti-aliasing, depth of field and light shafts, and medium leaves out reflections and depth of field; high leaves out nothing. These defaults come from the work each effect does per pixel, not from a weak device: the editor's new `fx-cost` check measured every effect on Bistro at 2560×1600 on a fast desktop GPU, and none added more than about 6 ms (reflections ~5, bloom ~4, the example's whole eight-effect chain ~11, the rest within the ±3 ms the run drifts by), so the levels have not been checked against the hardware they are for. Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen.diff --git a/desktop b/desktopindex ebf266904..1dc126381 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit ebf2669045c96a0a7ea090f2c84461ae3f095eb9+Subproject commit 1dc1263818058f1a859ab10d18ce5f81c209762cdiff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdxindex cfc480bcb..7f6bbd9ec 100644--- a/docs/astro/src/content/docs/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx@@ -25,6 +25,8 @@ several can stack in one frame at no extra target cost beyond the passes.| `distanceFog` | Linear fog by distance from the camera | `near`, `far`, `intensity`, colour || `heightFog` | Exponential height fog with the sun's glow and a hazy horizon | `density`, `heightFalloff`, `baseHeight`, `sunAzimuth`, `sunElevation`, `skyFog`, colours || `lightShafts` | Sun rays through whatever stands in front of it | `intensity`, `sunAzimuth`, `sunElevation`, `decay`, `reach` |+| `contactShadows` | The small sharp shadows at a contact a shadow map is too coarse to hold | `intensity`, `length`, `thickness` |+| `ssgi` | One bounce of diffuse light between the surfaces the camera sees | `intensity`, `radius`, `thickness`, `maxBounce` || `autoExposure` | Eye adaptation: exposure follows how bright the picture is | `bias`, `speedUp`, `speedDown`, `minEV`, `maxEV` || `depthOfField` | Blur by distance from a focus | `focusDistance`, `focusRange`, `aperture`, `maxBlur` || `rain` | Falling rain, wet ground, puddles, ripples and splashes | `intensity`, `wetness`, `wind`, `speed`, `puddles`, `puddleScale` |@@ -76,6 +78,20 @@ The clock is the game's. A capture that has to be the same on every run sets `tiwants. What this is not: the ground's shape is read from what the camera sees (a hollow behind a wall is not known),and the rain is a screen-space layer, not particles that collide with the world.+### Contact shadows and bounce light++`contactShadows` marches a short ray from each pixel toward the sun (the scene's own directional light, like the fog) in the depth+buffer, `length` world units long, and darkens the pixel by `intensity` where the ray passes just behind what the depth buffer shows+(`thickness` says how thick a thing may be and still count). It is for what a shadow map is too coarse to hold — a lamp's foot, a fold of+cloth, the crack under a door — and is laid over the finished picture, so it is a correction at the contact and not a second shadow.++`ssgi` is one bounce of **diffuse light** from what the camera can see. It needs the [G-buffer](#the-g-buffer): from each surface eight+rays leave over its hemisphere around the stored normal, each is marched six steps up to `radius` in the depth buffer, and what it lands on+gives out its colour (the scene's, so the bounce feeds itself over frames). The gather runs at half size into a float target; the second pass averages+the neighbours that lie on the same surface and adds the light times the receiver's own colour, so a red wall tints the white floor+beside it and a grey wall bounces grey. It is a screen-space estimate — it sees only what is on screen, and a light that moves lights its+surroundings with it, which a baked light cannot do — and it is noisier than it looks in one frame: `taa` averages what is left.+### Auto exposure`autoExposure` is the eye: it measures how bright the picture is and settles the exposure that putsdiff --git a/docs/astro/src/content/docs/graphics/weather.mdx b/docs/astro/src/content/docs/graphics/weather.mdxindex 06965f873..4c3651488 100644--- a/docs/astro/src/content/docs/graphics/weather.mdx+++ b/docs/astro/src/content/docs/graphics/weather.mdx@@ -31,6 +31,8 @@ A turn is eased, so it starts and ends gently, and a finished turn lands on itsauthored with — the weather scales your number, never its own last answer — and they are put back when the weatheris taken away or `Lights` is switched off. Only while the game runs: in the editor the lights are left alone, sopreviewing a weather never changes the scene you save.+- **Shadows.** The directional light's shadows get softer (a source `shadowSoftness` suns wide) and lighter (`shadowStrength` times+ 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.- **Rain.** The Rain effect is brought with the weather (when the scene has none) at the preset's strength, and Rain anddiff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdxindex 425365e33..12ad3a66c 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx@@ -24,6 +24,8 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess| `distanceFog` | 按到相机的距离做线性雾 | `near`、`far`、`intensity`、颜色 || `heightFog` | 指数高度雾,带太阳辉光和朦胧的地平线 | `density`、`heightFalloff`、`baseHeight`、`sunAzimuth`、`sunElevation`、`skyFog`、颜色 || `lightShafts` | 太阳光穿过前方遮挡物形成的光束 | `intensity`、`sunAzimuth`、`sunElevation`、`decay`、`reach` |+| `contactShadows` | 阴影贴图太粗放不下的接触处的小而锐利的阴影 | `intensity`、`length`、`thickness` |+| `ssgi` | 相机看得见的表面之间的一次漫反射光弹射 | `intensity`、`radius`、`thickness`、`maxBounce` || `autoExposure` | 眼睛适应:曝光跟随画面亮度 | `bias`、`speedUp`、`speedDown`、`minEV`、`maxEV` || `depthOfField` | 按到焦点的距离模糊 | `focusDistance`、`focusRange`、`aperture`、`maxBlur` || `rain` | 下雨、潮湿的地面、水坑、涟漪与水花 | `intensity`、`wetness`、`wind`、`speed`、`puddles`、`puddleScale` |@@ -61,6 +63,17 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess时钟是游戏的。要在每次运行都相同的截图,把 `timeScale` 设为 0,`phase` 设为想要的时间。它不是什么:地面的形状是从相机看到的东西里读出来的(墙后面的凹处它不知道),雨是屏幕空间的一层,不是会与世界碰撞的粒子。+### 接触阴影与弹射光++`contactShadows` 从每个像素朝太阳(场景自己的方向光,和雾一样)在深度缓冲里步进一条长 `length` 世界单位的短射线,射线刚好经过深度缓冲所示表面+后面的地方就把像素压暗 `intensity`(`thickness` 说一个东西多厚还算数)。它用来补阴影贴图太粗放不下的东西——灯的脚、衣褶、门下的缝——+盖在完成的画面上,所以它是接触处的一次修正,不是第二套阴影。++`ssgi` 是相机看得见的东西带来的**漫反射光**的一次弹射。它需要 [G-buffer](#g-buffer):每个表面绕存下的法线向半球发出八条射线,+每条在深度缓冲里走六步、最远 `radius`,落到的东西给出它的颜色(用场景的颜色,所以弹射光会在帧与帧之间自己喂自己)。收集在半尺寸的浮点目标上进行;+第二遍把同一个表面上的邻居平均起来,再把光乘以接收者自己的颜色加上去,所以红墙把旁边的白地面染红,灰墙弹出的是灰。它是屏幕空间的估计——+只看得到屏幕上有的东西,而移动的光会带着周围一起被照亮,这是烘焙光做不到的——一帧里它比看起来更吵:剩下的由 `taa` 平均掉。+### 自动曝光`autoExposure` 就是眼睛:它测量画面有多亮,并稳定到把画面放在中灰的曝光上。测量的是亮度**对数**的平均,diff --git a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdxindex a2b9c6a9d..6b4a3b536 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/weather.mdx@@ -27,6 +27,8 @@ description: 一个 Weather 组件,让场景处于晴、薄雾、阴天、雨或- **灯光。** 方向光被缩放(并着色),环境光被缩放,依据的是它们创作时的强度——天气缩放的是你的数字,而不是它自己上一次的结果——天气被拿走或关掉 `Lights` 时它们会被还原。只在游戏运行时:编辑器里灯光不动,所以预览天气不会改动你要保存的场景。+- **阴影。** 随着天空阴下来,方向光的阴影变得更软(光源宽 `shadowSoftness` 个太阳)、更淡(创作的深浅乘以 `shadowStrength`),+ 就像阴天的影子融进地面。- **雾。** Height Fog 的密度、太阳辉光和它带的体积光被缩放,天空雾霾被提高,颜色向天气的颜色移动。- **雨。** 场景没有 Rain 效果时天气会带来一个,强度按预设;Rain 和屏幕空间反射还会得到天气留下的湿度和水坑。场景自己创作了雨,天气只能把它提高。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 670bd5ce1..9e61c2cbd 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -10882,6 +10882,8 @@ rain: numberreflection: numberreflectionSaturation: numbersaturation: number+shadowSoftness: number+shadowStrength: numbersky: numberskyFog: numbersound: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 450c578ed..320a6de48 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -11095,6 +11095,8 @@ rain: numberreflection: numberreflectionSaturation: numbersaturation: number+shadowSoftness: number+shadowStrength: numbersky: numberskyFog: numbersound: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cb0180167..62de3c7e9 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -10877,6 +10877,8 @@ rain: numberreflection: numberreflectionSaturation: numbersaturation: number+shadowSoftness: number+shadowStrength: numbersky: numberskyFog: numbersound: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex fa9ceff26..7fd99a262 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -11176,6 +11176,8 @@ rain: numberreflection: numberreflectionSaturation: numbersaturation: number+shadowSoftness: number+shadowStrength: numbersky: numberskyFog: numbersound: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 73e910f33..c67d0dc46 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -10908,6 +10908,8 @@ rain: numberreflection: numberreflectionSaturation: numbersaturation: number+shadowSoftness: number+shadowStrength: numbersky: numberskyFog: numbersound: numberdiff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.tsindex 1fe16b36e..aa606e025 100644--- a/sdk/src/postprocess/effects.ts+++ b/sdk/src/postprocess/effects.ts@@ -270,6 +270,44 @@ registerEffect({],});+registerEffect({+ type: 'ssgi',+ label: 'Screen Space GI',+ factory: () => postProcessEffects.createSsgiApply(),+ uniforms: [+ // How much of the bounced light is added: 1 is what the surfaces gave out, scaled by the receiver's colour.+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 4, step: 0.01, defaultValue: 1, neutralValue: 0 },+ // A WORLD length: how far from a surface the rays look for something to bounce light from.+ { name: 'u_radius', label: 'Radius', min: 10, max: 1500, step: 5, defaultValue: 150 },+ // A WORLD length: how thick a thing the rays can land on, so a far wall is not taken for the one beside it.+ { name: 'u_thickness', label: 'Thickness', min: 1, max: 300, step: 1, defaultValue: 30 },+ // Brighter than this a surface does not bounce, so one lamp does not light the street from a single pixel.+ { name: 'u_maxBounce', label: 'Max Bounce', min: 0.5, max: 16, step: 0.5, defaultValue: 3 },+ ],+ // What each surface receives, at half size and in a float; then the neighbours on the same surface averaged and added.+ multiPass: [+ { name: 'ssgi_gather', factory: () => postProcessEffects.createSsgiGather(), scale: 0.5 },+ { name: 'ssgi_apply', factory: () => postProcessEffects.createSsgiApply() },+ ],+});++registerEffect({+ type: 'contactShadows',+ label: 'Contact Shadows',+ factory: () => postProcessEffects.createContactShadows(),+ uniforms: [+ // How dark a contact shadow is.+ { name: 'u_intensity', label: 'Intensity', min: 0, max: 1, step: 0.01, defaultValue: 0.6, neutralValue: 0 },+ // A WORLD length: how far from a surface the ray looks for something standing in the light's way.+ { name: 'u_length', label: 'Length', min: 5, max: 600, step: 1, defaultValue: 60 },+ // A WORLD length: how thick a thing can be and still shadow, so a far wall does not shadow what is in front of it.+ { name: 'u_thickness', label: 'Thickness', min: 0.5, max: 80, step: 0.5, defaultValue: 8 },+ { name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },+ { name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },+ { name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 35 },+ ],+});+registerEffect({type: 'lightShafts',label: 'Light Shafts',diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.tsindex 1f8c7c6c4..ae84804a3 100644--- a/sdk/src/postprocess/postProcessEffects.ts+++ b/sdk/src/postprocess/postProcessEffects.ts@@ -1724,6 +1724,383 @@ fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {return Material.compileShader(source);},+ /**+ * Screen-space global illumination, pass 1 of 2: what each surface receives from the others. From each surface a few+ * rays leave over its hemisphere (cosine weighted, around the normal the G-buffer holds), each is marched a short way in+ * the depth buffer, and what it lands on contributes the colour it is lit with — a red wall tints the white floor beside+ * it, a sunlit patch lights the shade next to it. The scene's colour stands for the light a surface gives out (its direct+ * and indirect light together, so the bounce feeds itself over frames). Eight rays a pixel are noise; the pass runs at+ * half size into a float target, and the next pass averages the neighbours that lie on the same surface.+ */+ createSsgiGather(): ShaderHandle {+ const GLSL = `+const int RAYS = 8;+const int STEPS = 6;+float ign(vec2 p) {+ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));+}+/// A direction over the hemisphere of N, cosine weighted, from two numbers in [0, 1).+vec3 cosineDirection(vec3 N, float u, float v) {+ float r = sqrt(u);+ float phi = 6.2831853 * v;+ vec3 up = abs(N.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);+ vec3 T = normalize(cross(up, N));+ vec3 B = cross(N, T);+ return normalize(T * (r * cos(phi)) + B * (r * sin(phi)) + N * sqrt(max(1.0 - u, 0.0)));+}`;+ const WGSL = `+const RAYS : i32 = 8;+const STEPS : i32 = 6;+fn ign(p : vec2f) -> f32 {+ return fract(52.9829189 * fract(dot(p, vec2f(0.06711056, 0.00583715))));+}+fn cosineDirection(N : vec3f, u : f32, v : f32) -> vec3f {+ let r = sqrt(u);+ let phi = 6.2831853 * v;+ var up = vec3f(1.0, 0.0, 0.0);+ if (abs(N.y) < 0.99) { up = vec3f(0.0, 1.0, 0.0); }+ let T = normalize(cross(up, N));+ let B = cross(N, T);+ return normalize(T * (r * cos(phi)) + B * (r * sin(phi)) + N * sqrt(max(1.0 - u, 0.0)));+}`;+ const source = `#pragma shader "PP SSGI Gather"+#pragma version 300 es+#pragma domain PostProcess+#pragma param u_radius float default(150) range(10,1500)+#pragma param u_thickness float default(30) range(1,300)+#pragma param u_maxBounce float default(3) range(0.5,16)+#pragma gbuffer+#pragma highprecision++#pragma fragment+precision highp float;++in vec2 v_texCoord;+uniform sampler2D u_texture;+uniform highp sampler2D u_sceneDepth;+uniform sampler2D u_gbuffer;+out vec4 fragColor;++${SSAO_GLSL}+${GBUFFER_GLSL}+${GLSL}++void main() {+ ivec2 size = textureSize(u_sceneDepth, 0);+ ivec2 c = screenTexel(v_texCoord, size);+ float d = depthAt(c, size);+ if (d >= 1.0) { fragColor = vec4(0.0); return; }+ Surface sf = readSurface(c);+ if (!sf.known) { fragColor = vec4(0.0); return; }++ vec3 P = worldFromDepth(uvOfTexel(c, size), d);+ vec3 N = sf.normal;+ if (dot(N, viewDirection(P)) < 0.0) N = -N;++ float rot = ign(gl_FragCoord.xy);+ float turn = ign(gl_FragCoord.yx + vec2(5.588238 * u_time.x * 60.0, 0.0));+ vec3 gathered = vec3(0.0);+ for (int k = 0; k < RAYS; ++k) {+ // A stratified pair per ray, shifted per pixel: the rays of one pixel never bunch, and its neighbours differ.+ float u = fract((float(k) + 0.5) / float(RAYS) + rot);+ float v = fract(float(k) * 0.61803399 + turn);+ vec3 dir = cosineDirection(N, u, v);+ for (int i = 1; i <= STEPS; ++i) {+ float f = float(i) / float(STEPS);+ float t = u_radius * f * f;+ vec3 Q = P + N * (u_radius * 0.01) + dir * t;+ vec4 q = u_projection * vec4(Q, 1.0);+ if (q.w <= 1e-4) break;+ vec2 uv = q.xy / q.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) break;+ ivec2 tx = screenTexel(uv, size);+ if (depthAt(tx, size) >= 1.0) continue;+ float surface = (u_projection * vec4(worldAt(tx, size), 1.0)).w;+ float behind = q.w - surface;+ if (behind > u_thickness * 0.05 && behind < u_thickness) {+ // What that surface gives out, less as it is further: the light of a far wall is spread thin.+ vec3 hit = min(texture(u_texture, uv).rgb, vec3(u_maxBounce));+ gathered += hit * (1.0 - f * 0.6);+ break;+ }+ }+ }+ fragColor = vec4(gathered / float(RAYS), 1.0);+}+#pragma end++#pragma fragment wgsl+${SSAO_WGSL}+${GBUFFER_WGSL}+${WGSL}++@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+ let size = vec2i(textureDimensions(t7, 0));+ let c = screenTexel(v.v_texCoord, size);+ let d = depthAt(c, size);+ if (d >= 1.0) { return vec4f(0.0); }+ let sf = readSurface(c);+ if (!sf.known) { return vec4f(0.0); }++ let P = worldFromDepth(uvOfTexel(c, size), d);+ var N = sf.normal;+ if (dot(N, viewDirection(P)) < 0.0) { N = -N; }++ let rot = ign(v.pos.xy);+ let turn = ign(v.pos.yx + vec2f(5.588238 * tc.u_time.x * 60.0, 0.0));+ var gathered = vec3f(0.0);+ for (var k : i32 = 0; k < RAYS; k = k + 1) {+ let u = fract((f32(k) + 0.5) / f32(RAYS) + rot);+ let w = fract(f32(k) * 0.61803399 + turn);+ let dir = cosineDirection(N, u, w);+ for (var i : i32 = 1; i <= STEPS; i = i + 1) {+ let f = f32(i) / f32(STEPS);+ let t = mc.u_radius * f * f;+ let Q = P + N * (mc.u_radius * 0.01) + dir * t;+ let q = frame.projection * vec4f(Q, 1.0);+ if (q.w <= 1e-4) { break; }+ let uv = vec2f(q.x / q.w * 0.5 + 0.5, 0.5 - q.y / q.w * 0.5);+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { break; }+ let tx = screenTexel(uv, size);+ if (depthAt(tx, size) >= 1.0) { continue; }+ let surface = (frame.projection * vec4f(worldAt(tx, size), 1.0)).w;+ let behind = q.w - surface;+ if (behind > mc.u_thickness * 0.05 && behind < mc.u_thickness) {+ let hit = min(textureSampleLevel(t0, s0, uv, 0.0).rgb, vec3f(mc.u_maxBounce));+ gathered = gathered + hit * (1.0 - f * 0.6);+ break;+ }+ }+ }+ return vec4f(gathered / f32(RAYS), 1.0);+}+#pragma end+`;+ return Material.compileShader(source);+ },++ /**+ * Screen-space global illumination, pass 2 of 2: the bounce, cleaned and laid over the picture. Each pixel averages the+ * gathered light of the pixels around it that lie on the same surface (close in depth, facing the same way), which turns+ * eight noisy rays into something near two hundred; what the receiver adds is that light times its own colour, since+ * light that bounced off a surface carries the surface's tint, so a grey wall bounces grey.+ */+ createSsgiApply(): ShaderHandle {+ const source = `#pragma shader "PP SSGI Apply"+#pragma version 300 es+#pragma domain PostProcess+#pragma param u_intensity float default(1) range(0,4)+#pragma gbuffer++#pragma fragment+precision highp float;++in vec2 v_texCoord;+uniform sampler2D u_texture;+uniform sampler2D u_sceneTexture;+uniform highp sampler2D u_sceneDepth;+uniform sampler2D u_gbuffer;+out vec4 fragColor;++${SSAO_GLSL}+${GBUFFER_GLSL}++void main() {+ vec4 src = texture(u_sceneTexture, v_texCoord);+ ivec2 size = textureSize(u_sceneDepth, 0);+ ivec2 c = screenTexel(v_texCoord, size);+ float d = depthAt(c, size);+ Surface sf = readSurface(c);+ if (d >= 1.0 || !sf.known || u_intensity <= 0.0) { fragColor = src; return; }++ vec3 P = worldFromDepth(uvOfTexel(c, size), d);+ float reach = max(length(worldAt(c + ivec2(2, 0), size) - P), 1e-3);+ vec2 texel = 1.0 / vec2(textureSize(u_texture, 0));+ vec3 sum = vec3(0.0);+ float wsum = 0.0;+ for (int j = -2; j <= 2; ++j) {+ for (int i = -2; i <= 2; ++i) {+ vec2 uv = v_texCoord + vec2(float(i), float(j)) * texel;+ ivec2 t = screenTexel(uv, size);+ float dt = depthAt(t, size);+ if (dt >= 1.0) continue;+ Surface st = readSurface(t);+ if (!st.known) continue;+ // The same surface: nearby in the world and facing the same way.+ float apart = length(worldAt(t, size) - P) / (reach * 8.0);+ float w = exp(-apart * apart * 4.0) * pow(max(dot(sf.normal, st.normal), 0.0), 8.0);+ sum += texture(u_texture, uv).rgb * w;+ wsum += w;+ }+ }+ vec3 gathered = wsum > 1e-4 ? sum / wsum : vec3(0.0);+ // The bounced light wears the receiver's own colour (its chroma, kept below white so a bright surface does not run away).+ float lum = max(dot(src.rgb, vec3(0.2126, 0.7152, 0.0722)), 0.02);+ vec3 albedo = mix(vec3(0.55), clamp(src.rgb / lum, vec3(0.0), vec3(1.6)) * 0.55, 0.7);+ fragColor = vec4(src.rgb + albedo * gathered * u_intensity, src.a);+}+#pragma end++#pragma fragment wgsl+${SSAO_WGSL}+${GBUFFER_WGSL}++@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+ let src = textureSampleLevel(t1, s1, v.v_texCoord, 0.0);+ let size = vec2i(textureDimensions(t7, 0));+ let c = screenTexel(v.v_texCoord, size);+ let d = depthAt(c, size);+ let sf = readSurface(c);+ if (d >= 1.0 || !sf.known || mc.u_intensity <= 0.0) { return src; }++ let P = worldFromDepth(uvOfTexel(c, size), d);+ let reach = max(length(worldAt(c + vec2i(2, 0), size) - P), 1e-3);+ let texel = 1.0 / vec2f(vec2i(textureDimensions(t0, 0)));+ var sum = vec3f(0.0);+ var wsum = 0.0;+ for (var j : i32 = -2; j <= 2; j = j + 1) {+ for (var i : i32 = -2; i <= 2; i = i + 1) {+ let uv = v.v_texCoord + vec2f(f32(i), f32(j)) * texel;+ let t = screenTexel(uv, size);+ let dt = depthAt(t, size);+ if (dt >= 1.0) { continue; }+ let st = readSurface(t);+ if (!st.known) { continue; }+ let apart = length(worldAt(t, size) - P) / (reach * 8.0);+ let w = exp(-apart * apart * 4.0) * pow(max(dot(sf.normal, st.normal), 0.0), 8.0);+ sum = sum + textureSampleLevel(t0, s0, uv, 0.0).rgb * w;+ wsum = wsum + w;+ }+ }+ var gathered = vec3f(0.0);+ if (wsum > 1e-4) { gathered = sum / wsum; }+ let lum = max(dot(src.rgb, vec3f(0.2126, 0.7152, 0.0722)), 0.02);+ let albedo = mix(vec3f(0.55), clamp(src.rgb / lum, vec3f(0.0), vec3f(1.6)) * 0.55, 0.7);+ return vec4f(src.rgb + albedo * gathered * mc.u_intensity, src.a);+}+#pragma end+`;+ return Material.compileShader(source);+ },++ /**+ * Contact shadows: the small, sharp shadows a shadow map is too coarse to hold — a lamp's foot on the ground, a+ * fold of cloth, the crack under a door. From each pixel a short ray is marched toward the sun in the depth buffer; a+ * step that lands just behind what the buffer shows is a surface standing between this point and the light. It is+ * laid over the finished picture, so it darkens what is already lit by the same amount whatever the light did: a+ * correction at the contact, not a replacement for the shadow map. The sun is the scene's own directional light.+ */+ createContactShadows(): ShaderHandle {+ const source = `#pragma shader "PP Contact Shadows"+#pragma version 300 es+#pragma domain PostProcess+#pragma param u_intensity float default(0.6) range(0,1)+#pragma param u_length float default(60) range(5,600)+#pragma param u_thickness float default(8) range(0.5,80)+#pragma param u_followSun float default(1) range(0,1)+#pragma param u_sunAzimuth float default(40) range(0,360)+#pragma param u_sunElevation float default(35) range(-10,90)+#pragma lights++#pragma fragment+precision highp float;++in vec2 v_texCoord;+uniform sampler2D u_texture;+uniform highp sampler2D u_sceneDepth;+out vec4 fragColor;++const int STEPS = 20;++${SSAO_GLSL}++float ign(vec2 p) {+ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));+}++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);+ if (d >= 1.0 || u_intensity <= 0.0) { fragColor = src; return; }++ vec4 lightDir, lightColor;+ ivec2 tiles;+ findSun(lightDir, lightColor, tiles);+ float az = radians(u_sunAzimuth);+ float el = radians(u_sunElevation);+ vec3 L = (u_followSun > 0.5 && lightDir.w > 0.5) ? lightDir.xyz+ : vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));++ vec3 P = worldFromDepth(uvOfTexel(c, size), d);+ float jitter = ign(gl_FragCoord.xy);+ float occluded = 0.0;+ for (int i = 0; i < STEPS; ++i) {+ float t = (float(i) + jitter + 0.5) / float(STEPS) * u_length;+ vec3 Q = P + L * t;+ vec4 q = u_projection * vec4(Q, 1.0);+ if (q.w <= 1e-4) break;+ vec2 uv = q.xy / q.w * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) break;+ ivec2 tx = screenTexel(uv, size);+ if (depthAt(tx, size) >= 1.0) continue;+ float surface = (u_projection * vec4(worldAt(tx, size), 1.0)).w;+ // Behind what the buffer shows by more than the surface's own noise, and by less than a wall's thickness.+ float behind = q.w - surface;+ if (behind > u_thickness * 0.08 + t * 0.01 && behind < u_thickness) { occluded = 1.0; break; }+ }+ // The nearer the blocker, the harder the contact: fades along the ray's length.+ fragColor = vec4(src.rgb * (1.0 - u_intensity * occluded), src.a);+}+#pragma end++#pragma fragment wgsl+const STEPS : i32 = 20;++${SSAO_WGSL}++fn ign(p : vec2f) -> f32 {+ return fract(52.9829189 * fract(dot(p, vec2f(0.06711056, 0.00583715))));+}++@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);+ if (d >= 1.0 || mc.u_intensity <= 0.0) { return src; }++ let found = findSun();+ let az = radians(mc.u_sunAzimuth);+ let el = radians(mc.u_sunElevation);+ var L = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ if (mc.u_followSun > 0.5 && found.dir.w > 0.5) { L = found.dir.xyz; }++ let P = worldFromDepth(uvOfTexel(c, size), d);+ let jitter = ign(v.pos.xy);+ var occluded = 0.0;+ for (var i : i32 = 0; i < STEPS; i = i + 1) {+ let t = (f32(i) + jitter + 0.5) / f32(STEPS) * mc.u_length;+ let Q = P + L * t;+ let q = frame.projection * vec4f(Q, 1.0);+ if (q.w <= 1e-4) { break; }+ // This device's uv runs down the rows, so clip y is flipped on the way back.+ let uv = vec2f(q.x / q.w * 0.5 + 0.5, 0.5 - q.y / q.w * 0.5);+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { break; }+ let tx = screenTexel(uv, size);+ if (depthAt(tx, size) >= 1.0) { continue; }+ let surface = (frame.projection * vec4f(worldAt(tx, size), 1.0)).w;+ let behind = q.w - surface;+ if (behind > mc.u_thickness * 0.08 + t * 0.01 && behind < mc.u_thickness) { occluded = 1.0; break; }+ }+ return vec4f(src.rgb * (1.0 - mc.u_intensity * occluded), src.a);+}+#pragma end+`;+ return Material.compileShader(source);+ },+/*** Light shafts: the sun's light through whatever stands between it and the camera, found in* screen space. From each pixel a short march toward the sun's position on screen collectsdiff --git a/sdk/src/postprocess/weather.ts b/sdk/src/postprocess/weather.tsindex 13d0b5c90..f30a6ae36 100644--- a/sdk/src/postprocess/weather.ts+++ b/sdk/src/postprocess/weather.ts@@ -23,6 +23,11 @@ export interface WeatherState {sky: number;/** × the directional light's colour. */sunTint: [number, number, number];+ /** How soft its shadows are, in suns: 1 leaves them as authored, 8 makes the source eight times wider across the+ * sky — an overcast sky's shadows are barely there, and the ones that are fade into the ground. */+ shadowSoftness: number;+ /** × how dark the light's shadows are. */+ shadowStrength: number;/** × Height Fog's density. */fogDensity: number;/** The colour fog moves toward, and how far (0 = its own colour). */@@ -54,7 +59,7 @@ export interface WeatherState {export type WeatherPreset = Partial<WeatherState>;const NEUTRAL: WeatherState = {- sun: 1, sky: 1, sunTint: [1, 1, 1],+ 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,@@ -89,22 +94,22 @@ function define(id: number, name: string, preset: WeatherPreset): void {define(WEATHER_CLEAR, 'clear', {});define(WEATHER_MIST, 'mist', {- sun: 0.45, sky: 0.9, fogDensity: 8, fogTint: [0.86, 0.86, 0.84], fogTintAmount: 0.7, fogGlow: 1.8, skyFog: 1.7,+ sun: 0.45, sky: 0.9, shadowSoftness: 3, shadowStrength: 0.8, fogDensity: 8, fogTint: [0.86, 0.86, 0.84], fogTintAmount: 0.7, fogGlow: 1.8, skyFog: 1.7,saturation: 0.86, contrast: 0.94, exposure: 0.2, wetness: 0.2, puddles: 0.1, ssr: 1.3, reflection: 0.85,reflectionSaturation: 0.9,});define(WEATHER_OVERCAST, 'overcast', {- sun: 0.25, sky: 0.85, sunTint: [0.9, 0.93, 1], fogDensity: 3, fogTint: [0.62, 0.66, 0.72], fogTintAmount: 0.5,+ sun: 0.25, sky: 0.85, sunTint: [0.9, 0.93, 1], shadowSoftness: 8, shadowStrength: 0.5, fogDensity: 3, fogTint: [0.62, 0.66, 0.72], fogTintAmount: 0.5,fogGlow: 0.3, skyFog: 1.4, saturation: 0.85, contrast: 0.96, exposure: 0.25, wetness: 0.1, ssr: 1.2,reflection: 0.7, reflectionSaturation: 0.7,});define(WEATHER_RAIN, 'rain', {- sun: 0.04, sky: 0.75, sunTint: [0.8, 0.86, 1], fogDensity: 5.5, fogTint: [0.58, 0.63, 0.7], fogTintAmount: 0.8,+ sun: 0.04, sky: 0.75, sunTint: [0.8, 0.86, 1], shadowSoftness: 10, shadowStrength: 0.3, fogDensity: 5.5, fogTint: [0.58, 0.63, 0.7], fogTintAmount: 0.8,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, sound: 1,});define(WEATHER_STORM, 'storm', {- sun: 0.02, sky: 0.5, sunTint: [0.7, 0.78, 1], fogDensity: 8, fogTint: [0.4, 0.44, 0.5], fogTintAmount: 0.9,+ 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,ssr: 3, reflection: 0.4, reflectionSaturation: 0.35, sound: 1.6,});diff --git a/sdk/src/postprocess/weatherSystem.ts b/sdk/src/postprocess/weatherSystem.tsindex 93d126ffb..21f29c521 100644--- a/sdk/src/postprocess/weatherSystem.ts+++ b/sdk/src/postprocess/weatherSystem.ts@@ -28,6 +28,8 @@ interface LightBase {color: { r: number; g: number; b: number; a: number };reflectionScale: number;reflectionSaturation: number;+ sourceAngle: number;+ shadowStrength: number;applied: number;}@@ -49,6 +51,7 @@ function restoreLights(world: World): void {world.set(entity, Light, {...data, intensity: base.intensity, color: { ...base.color },reflectionScale: base.reflectionScale, reflectionSaturation: base.reflectionSaturation,+ sourceAngle: base.sourceAngle, shadowStrength: base.shadowStrength,});}}@@ -64,6 +67,7 @@ function applyLights(world: World, state: WeatherState, drive: number): void {base = {intensity: data.intensity, color: { ...data.color },reflectionScale: data.reflectionScale ?? 1, reflectionSaturation: data.reflectionSaturation ?? 1,+ sourceAngle: data.sourceAngle ?? 0, shadowStrength: data.shadowStrength ?? 1,applied: Number.NaN,};bases.set(entity, base);@@ -74,14 +78,20 @@ function applyLights(world: World, state: WeatherState, drive: number): void {const scale = lights ? (sun ? state.sun : state.sky) : 1;// The key is what the light would be told: nothing is written for a frame that would say the same again.const key = scale + (lights && sun ? state.sunTint[0] * 7 + state.sunTint[1] * 13 + state.sunTint[2] * 29 : 0)- + (reflections ? state.reflection * 101 + state.reflectionSaturation * 211 : 0);+ + (reflections ? state.reflection * 101 + state.reflectionSaturation * 211 : 0)+ + (lights && sun ? state.shadowSoftness * 307 + state.shadowStrength * 401 : 0);if (base.applied === key) continue;base.applied = key;const color = lights && sun? { r: base.color.r * state.sunTint[0], g: base.color.g * state.sunTint[1], b: base.color.b * state.sunTint[2], a: base.color.a }: { ...base.color };+ // A sun's width in the sky is 0.53 degrees: softer shadows are a wider source, and a hard-edged light (0) gains the+ // difference too, so the setting always means something.+ const widen = lights && sun ? Math.max(state.shadowSoftness - 1, 0) * 0.53 : 0;world.set(entity, Light, {...data, intensity: base.intensity * scale, color,+ sourceAngle: base.sourceAngle + widen,+ shadowStrength: lights && sun ? Math.min(base.shadowStrength * state.shadowStrength, 1) : base.shadowStrength,reflectionScale: reflections ? base.reflectionScale * state.reflection : base.reflectionScale,reflectionSaturation: reflections ? base.reflectionSaturation * state.reflectionSaturation : base.reflectionSaturation,});diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.tsindex d871d868d..bb1ffa5ec 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(30);+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(33);expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 1a06ce61d..6097c5efa 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2503,6 +2503,8 @@ export const NOTED = {{"note":"Auto Exposure can meter the middle of the picture or a spot, and Depth of Field focuses by itself and blurs a light into the shape of its aperture."},"feat(runtime): rain stays off what is under a roof, and the weather turns a rain track up and down":{"note":"Rain stays off what stands under a roof, and the Weather component turns a looping rain track up and down."},+ "feat(render): Contact Shadows and Screen Space GI effects, and the weather softens the sun's shadows":+ {"note":"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."},"feat(render): reflections no longer guess a surface, plain meshes record themselves, and what the ray never finds is the sky":{"note":"Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen."},};