Skip to content

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

feat(2d): a palette effect holds the whole picture to one set of colours, dithered

yhhd0966fe34211
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 3a5dc9989..2fdb30bbf 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -48,6 +48,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `filmGrain` | Noise the size of a film crystal, strongest in the mid-tones, crawling with the clock | `intensity`, `size`, `response` |
| `lensFlare` | Ghosts and a halo thrown by whatever is brighter than a threshold, with a colour fringe | `intensity`, `threshold`, `ghosts`, `dispersal`, `haloWidth`, `chromatic`, `tint` |
| `pixelate` | Block quantization | `pixelSize` |
+| `palette` | Holds the picture to a palette: each pixel becomes the nearest colour of a strip image (N by 1, one colour a pixel, up to 64), after an ordered dither. Put it last and set the texture to the palette image (import it with nearest filtering) | `strength`, `dither`, `ditherScale` (match the art's pixel size), `palette` |
| `outline` | Ink-edge outlines (Sobel edge darkening) | `intensity`, `threshold`, `thickness` |
| `depthOutline` | Black outline where the depth steps (a silhouette, not shading) | `intensity`, `threshold`, `thickness` |
| `edgeOutline` | A coloured line at silhouettes **and** creases: where the camera distance steps, and where the surface normal turns (needs surfaces that write a normal: lit meshes, Model, Toon) | `intensity`, `depthThreshold`, `normalThreshold`, `thickness`, colour `lineColor` |
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx
index e6808eb91..d24291f4c 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
@@ -47,6 +47,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `taa` | 时间性抗锯齿:边缘跨多帧平滑,移动网格按它自己的运动跟随 | `blend`、`objectMotion` |
| `lensDistortion` | 桶形 / 枕形畸变 | `strength`、`zoom` |
| `pixelate` | 块状量化 | `pixelSize` |
+| `palette` | 把画面收进一套调色板:每个像素变成色板条图(N×1,每像素一种颜色,最多 64 色)里最接近的颜色,先做有序抖动。放在效果链最后,把贴图设成色板图片(导入时用最近邻过滤) | `strength`、`dither`、`ditherScale`(与美术的像素大小一致)、`palette` |
| `outline` | 墨线描边(Sobel 边缘压暗) | `intensity`、`threshold`、`thickness` |
| `depthOutline` | 深度跳变处的黑色轮廓(轮廓,不是着色) | `intensity`、`threshold`、`thickness` |
| `edgeOutline` | 轮廓**和**折痕处画一条有颜色的线:相机距离跳变处,以及表面法线转折处(需要写法线的表面:受光网格、Model、Toon) | `intensity`、`depthThreshold`、`normalThreshold`、`thickness`、颜色 `lineColor` |
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index 3a8abec96..5f956605d 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -84,7 +84,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
export const POST_PROCESS_EFFECT_GROUP: Readonly<Record<string, Subsystem>> = {
blur: 'fxBasic', bloom: 'fxBasic', vignette: 'fxBasic', grayscale: 'fxBasic', colorGrade: 'fxBasic',
chromaticAberration: 'fxBasic', tonemap: 'fxBasic', fxaa: 'fxBasic', lensDistortion: 'fxBasic', pixelate: 'fxBasic',
- outline: 'fxBasic', depthOutline: 'fxBasic', edgeOutline: 'fxBasic', lutGrade: 'fxBasic', agx: 'fxBasic', sharpen: 'fxBasic', filmGrain: 'fxBasic',
+ outline: 'fxBasic', depthOutline: 'fxBasic', edgeOutline: 'fxBasic', lutGrade: 'fxBasic', palette: 'fxBasic', agx: 'fxBasic', sharpen: 'fxBasic', filmGrain: 'fxBasic',
motionBlur: 'fxBasic', lensFlare: 'fxBasic',
mist2d: 'fxAtmosphere', rain2d: 'fxAtmosphere', fog2d: 'fxAtmosphere', distanceFog: 'fxAtmosphere', skyAtmosphere: 'fxAtmosphere', heightFog: 'fxAtmosphere', rain: 'fxAtmosphere',
voxelGI: 'fxLighting', ssgi: 'fxLighting', contactShadows: 'fxLighting', lightShafts: 'fxLighting',
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 408080bca..afd3955f8 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -898,6 +898,23 @@ registerEffect({
// A graded look read off a table by the picture as the display shows it: the last pass's, after the output transform and the transfer
// function, which no effect in the chain can be (they run on scene values, before both). For a look authored against the finished image.
+// A look held to a few colours: every pixel becomes the nearest of a palette read from a strip image (N by 1, up to 64 colours), after an ordered
+// dither that spreads a gradient over neighbouring colours. For pixel art that must keep to one palette however the lights and the weather move.
+registerEffect({
+ type: 'palette',
+ label: 'Palette',
+ factory: () => postProcessEffects.createPalette(),
+ uniforms: [
+ { name: 'u_strength', label: 'Strength', min: 0, max: 1, step: 0.01, defaultValue: 1, neutralValue: 0 },
+ // How far the choice is spread between neighbouring colours, and the size in device pixels of one cell of the dither (match the art's pixel size).
+ { name: 'u_dither', label: 'Dither', min: 0, max: 1, step: 0.01, defaultValue: 0.5 },
+ { name: 'u_ditherScale', label: 'Dither Scale', min: 1, max: 16, step: 1, defaultValue: 1 },
+ ],
+ textures: [
+ { name: 'u_palette', label: 'Palette (N x 1 image, one colour a pixel, up to 64)' },
+ ],
+});
+
registerEffect({
type: 'displayLut',
label: 'Display LUT',
@@ -916,7 +933,7 @@ const CATEGORIES: Record<EffectCategory, string[]> = {
light: ['ssao', 'gtao', 'ssgi', 'ssr', 'voxelGI', 'contactShadows', 'lightShafts', 'subsurface'],
atmosphere: ['mist2d', 'rain2d', 'fog2d', 'distanceFog', 'heightFog', 'skyAtmosphere', 'rain'],
aa: ['fxaa', 'taa'],
- stylize: ['blur', 'pixelate', 'outline', 'depthOutline', 'edgeOutline'],
+ stylize: ['blur', 'pixelate', 'palette', 'outline', 'depthOutline', 'edgeOutline'],
};
for (const [category, types] of Object.entries(CATEGORIES) as [EffectCategory, string[]][]) {
for (const type of types) {
diff --git a/sdk/src/postprocess/sources/basic.ts b/sdk/src/postprocess/sources/basic.ts
index 8abed605f..1c0c1e1be 100644
--- a/sdk/src/postprocess/sources/basic.ts
+++ b/sdk/src/postprocess/sources/basic.ts
@@ -1030,6 +1030,92 @@ void main() {
return textureSampleLevel(t0, s0, uv, 0.0);
}
#pragma end
+`;
+ return Material.compileShader(source);
+ },
+ createPalette(): ShaderHandle {
+ // Every pixel becomes the nearest colour of a palette read from a strip image (one colour a pixel, up to 64), after an ordered dither
+ // that spreads the choice between neighbouring colours so a gradient reads as a pattern and not a band. The nearest is found in sRGB,
+ // the space a palette is authored in, with the weights of the "redmean" distance.
+ const source = `#pragma shader "PP Palette"
+#pragma version 300 es
+#pragma domain PostProcess
+#pragma param u_strength float default(1) range(0,1)
+#pragma param u_dither float default(0.5) range(0,1)
+#pragma param u_ditherScale float default(1) range(1,16)
+#pragma param u_palette texture default(white) texel(data)
+
+#pragma fragment
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+out vec4 fragColor;
+
+vec3 palToSrgb(vec3 c) { return mix(c * 12.92, 1.055 * pow(max(c, 0.0), vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); }
+vec3 palToLinear(vec3 c) { return mix(c / 12.92, pow((max(c, 0.0) + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); }
+float bayer2(vec2 a) { a = floor(a); return fract(a.x / 2.0 + a.y * a.y * 0.75); }
+float bayer8(vec2 a) { return (bayer2(0.25 * a) * 0.25 + bayer2(0.5 * a)) * 0.25 + bayer2(a); }
+
+void main() {
+ vec4 src = texture(u_texture, v_texCoord);
+ int n = min(textureSize(u_palette, 0).x, 64);
+ if (n <= 1) { fragColor = src; return; }
+ vec3 c = src.rgb;
+#ifdef ES_LINEAR
+ c = palToSrgb(c);
+#endif
+ vec2 px = floor(v_texCoord * u_viewport.xy / max(u_ditherScale, 1.0));
+ vec3 aim = clamp(c + (bayer8(px) - 0.5) * u_dither * 0.25, 0.0, 1.0);
+ vec3 best = c;
+ float bestD = 1e9;
+ for (int i = 0; i < n; i++) {
+ vec3 p = texelFetch(u_palette, ivec2(i, 0), 0).rgb;
+ vec3 d = aim - p;
+ float m = (aim.r + p.r) * 0.5;
+ float dist = (2.0 + m) * d.r * d.r + 4.0 * d.g * d.g + (3.0 - m) * d.b * d.b;
+ if (dist < bestD) { bestD = dist; best = p; }
+ }
+ vec3 outc = mix(c, best, u_strength);
+#ifdef ES_LINEAR
+ outc = palToLinear(outc);
+#endif
+ fragColor = vec4(outc, src.a);
+}
+#pragma end
+
+#pragma fragment wgsl
+fn palToSrgb(c : vec3f) -> vec3f { return mix(c * 12.92, 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), c)); }
+fn palToLinear(c : vec3f) -> vec3f { return mix(c / 12.92, pow((max(c, vec3f(0.0)) + 0.055) / 1.055, vec3f(2.4)), step(vec3f(0.04045), c)); }
+fn bayer2(a0 : vec2f) -> f32 { let a = floor(a0); return fract(a.x / 2.0 + a.y * a.y * 0.75); }
+fn bayer8(a : vec2f) -> f32 { return (bayer2(0.25 * a) * 0.25 + bayer2(0.5 * a)) * 0.25 + bayer2(a); }
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);
+ let n = min(i32(textureDimensions(u_palette).x), 64);
+ if (n <= 1) { return src; }
+ var c = src.rgb;
+#ifdef ES_LINEAR
+ c = palToSrgb(c);
+#endif
+ let px = floor(v.v_texCoord * tc.u_viewport.xy / max(mc.u_ditherScale, 1.0));
+ let aim = clamp(c + (bayer8(px) - 0.5) * mc.u_dither * 0.25, vec3f(0.0), vec3f(1.0));
+ var best = c;
+ var bestD = 1e9;
+ for (var i = 0; i < n; i = i + 1) {
+ let p = textureLoad(u_palette, vec2i(i, 0), 0).rgb;
+ let d = aim - p;
+ let m = (aim.r + p.r) * 0.5;
+ let dist = (2.0 + m) * d.r * d.r + 4.0 * d.g * d.g + (3.0 - m) * d.b * d.b;
+ if (dist < bestD) { bestD = dist; best = p; }
+ }
+ var outc = mix(c, best, mc.u_strength);
+#ifdef ES_LINEAR
+ outc = palToLinear(outc);
+#endif
+ return vec4f(outc, src.a);
+}
+#pragma end
`;
return Material.compileShader(source);
},
diff --git a/sdk/tests/palette-effect.test.ts b/sdk/tests/palette-effect.test.ts
new file mode 100644
index 000000000..a6c827fba
--- /dev/null
+++ b/sdk/tests/palette-effect.test.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The palette effect: held to a strip image's colours, dithered, the same in both shader languages.
+ */
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { getEffectDef } from '../src/postprocess/effects';
+
+const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'postprocess', 'sources', 'basic.ts'), 'utf8');
+const palette = source.slice(source.indexOf('createPalette()'), source.indexOf('registerBasicEffectSources'));
+
+describe('the palette effect', () => {
+ it('is a stylize effect that reads its colours from a strip image', () => {
+ const def = getEffectDef('palette');
+ expect(def).toBeDefined();
+ expect(def!.category).toBe('stylize');
+ expect(def!.uniforms.map((u) => u.name)).toEqual(['u_strength', 'u_dither', 'u_ditherScale']);
+ expect(def!.textures!.map((t) => t.name)).toEqual(['u_palette']);
+ // A scene with no strength changes nothing.
+ expect(def!.uniforms[0]!.neutralValue).toBe(0);
+ });
+
+ it('reads the strip raw and a texel at a time, so no filter blends two colours, in both languages', () => {
+ expect(palette).toContain('texel(data)');
+ expect(palette).toContain('texelFetch(u_palette, ivec2(i, 0), 0)');
+ expect(palette).toContain('textureLoad(u_palette, vec2i(i, 0), 0)');
+ });
+
+ it('leaves the picture alone with a palette of one colour (none was given), and goes through sRGB where the buffer is linear', () => {
+ expect(palette).toContain('if (n <= 1) { fragColor = src; return; }');
+ expect(palette).toContain('if (n <= 1) { return src; }');
+ expect((palette.match(/#ifdef ES_LINEAR/g) ?? []).length).toBe(4);
+ });
+
+ it('spreads the choice with the same ordered dither in both languages', () => {
+ expect(palette).toContain('float bayer8(vec2 a) { return (bayer2(0.25 * a) * 0.25 + bayer2(0.5 * a)) * 0.25 + bayer2(a); }');
+ expect(palette).toContain('fn bayer8(a : vec2f) -> f32 { return (bayer2(0.25 * a) * 0.25 + bayer2(0.5 * a)) * 0.25 + bayer2(a); }');
+ });
+});
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index 835159158..51dd14c7c 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(42);
+ expect(CASES.filter((c) => c.name.startsWith('postProcessEffects.ts')).length).toBe(43);
expect(CASES.filter((c) => c.name.startsWith('editorGridRenderer.ts')).length).toBe(1);
});