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 colour map over the ground - Terrain.colorMap is a picture laid over a whole area and mixed into the ground's colour by its alpha, on the plain shader and on the layered one, with colorMapStrength read each frame
yhh406737e889bb
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 4631ec337..2dfd0d280 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -39,6 +39,8 @@ The ground is one of two kinds, chosen by `extent`:| `erosion` | 0 to 4: how much rain wears the ground (below). 0 leaves it as made. || `splatmap` | Area only. An image whose four channels are the weights of layers 1 to 4. Empty paints by height and slope. || `splatmap2` | Area only. The weights of layers 5 to 8, read with the first. |+| `colorMap` | Area only. A picture laid over the whole area and mixed into the ground's colour by its alpha: a meadow's flowers, the regions of a map, scorched ground. One texture for the whole terrain, on top of the layers; its import Use is Colour. |+| `colorMapStrength` | How much of the colour map is mixed in where its alpha is whole (1). Read each frame: changing it rebuilds nothing. || `layers` | The [terrain layers](#terrain-layers) the ground is drawn with, up to eight, in the order the paint weighs them. Empty draws the four layer colours or the Terrain material's textures. || `rockSlope`, `dirtHeight`, `snowHeight` | How steep ground must be to turn to rock, and the heights, as a share of `height`, where grass gives way to dirt and where snow begins. || `layerColor0`–`3` | Grass, dirt, snow, rock: the colours the ground is drawn in when it has no material. |diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 35eeacfdb..f6590b4cc 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -31,6 +31,8 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是| `erosion` | 0 到 4:雨水把地面侵蚀多少(见下)。0 保持生成时的样子。 || `splatmap` | 仅区域。一张图,四个通道是第 1 到 4 层的权重。为空则按高度和坡度上色。 || `splatmap2` | 仅区域。第 5 到 8 层的权重,与第一张一起读取。 |+| `colorMap` | 仅区域。铺在整块区域上的一张图,按它的 alpha 混进地面颜色:草甸上的花色、地图上的分区、烧焦的地面。整块地形一张,叠在图层之上;导入用途是颜色。 |+| `colorMapStrength` | alpha 为满的地方混入多少颜色图(1)。每帧读取:改它不会重建任何东西。 || `layers` | 绘制地面所用的[地形层](#地形层),最多八个,按地表图权重的顺序。为空则用四种图层颜色或 Terrain 材质的贴图。 || `rockSlope`、`dirtHeight`、`snowHeight` | 地面要多陡才变成岩石,以及草地转为泥土、雪开始出现的高度(占 `height` 的比例)。 || `layerColor0`–`3` | 草、泥土、雪、岩石:没有材质时地面绘制用的颜色。 |diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 4de755ea7..d705aea20 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -85,6 +85,10 @@ export interface TerrainData {splatmap: number;/** An image whose four channels are the weights of layers 5 to 8, read with the first. */splatmap2: number;+ /** A picture laid over the whole of an area and mixed into the ground's colour by its alpha: a meadow's flowers, a map's regions, scorched ground. */+ colorMap: number;+ /** How much of the colour map is mixed in where its alpha is whole. */+ colorMapStrength: number;/*** The terrain layers (`.esterrainlayer` files, up to eight) the ground is drawn with, in the order the paint weighs them. With any,* the ground is drawn on the Terrain Layers shader (its material, if one is named, must be on it); with none, by the four colours.@@ -138,7 +142,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });* @experimental*/export const Terrain: ComponentDef<TerrainData> = /* @__PURE__ */ defineComponent<TerrainData>('Terrain', {- extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, tiles: '', heightmapFormat: HeightmapFormat.Grey, splatmap: 0, splatmap2: 0, layers: [] as string[], material: 0,+ extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, tiles: '', heightmapFormat: HeightmapFormat.Grey, splatmap: 0, splatmap2: 0, colorMap: 0, colorMapStrength: 1, layers: [] as string[], material: 0,// Lengths at the engine's reference of 100 units a metre (ecs/worldUnits.ts): a kilometre of ground 150 m high on 2 m cells in any project.sizeX: 100000, sizeZ: 100000, height: 15000, cellSize: 200, detail: 1, drawDistance: 400000,collision: true, collisionDistance: 6400, collisionLayer: 0, friction: 0.6,@@ -146,7 +150,7 @@ export const Terrain: ComponentDef<TerrainData> = /* @__PURE__ */ defineComponenrockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88,layerColor0: rgb(0.28, 0.46, 0.2), layerColor1: rgb(0.45, 0.36, 0.24), layerColor2: rgb(0.93, 0.95, 0.98), layerColor3: rgb(0.4, 0.38, 0.36),}, {- assetFields: [{ field: 'heightmap', type: 'texture' }, { field: 'splatmap', type: 'texture' }, { field: 'splatmap2', type: 'texture' }, { field: 'material', type: 'material' }],+ assetFields: [{ field: 'heightmap', type: 'texture' }, { field: 'splatmap', type: 'texture' }, { field: 'splatmap2', type: 'texture' }, { field: 'colorMap', type: 'texture' }, { field: 'material', type: 'material' }],worldUnitFields: ['sizeX', 'sizeZ', 'height', 'cellSize', 'drawDistance', 'collisionDistance'],fields: {extent: { enum: [{ label: 'Area', value: TerrainExtent.Area }, { label: 'Infinite', value: TerrainExtent.Infinite }], category: 'Shape', tooltip: 'An area of its own size, from a heightmap or noise; or ground that goes on for ever, from noise read anywhere (the same seed is the same ground).' },@@ -158,6 +162,8 @@ export const Terrain: ComponentDef<TerrainData> = /* @__PURE__ */ defineComponenheightmapFormat: { enum: [{ label: 'Grey (8 or 16 bit)', value: HeightmapFormat.Grey }, { label: 'Red + green (16 bit)', value: HeightmapFormat.RedGreen16 }], category: 'Shape', tooltip: 'How the heightmap holds its heights: grey (or red) at the depth of the file, 16 bits from a 16-bit PNG; or sixteen bits across red (high byte) and green (low byte) of an 8-bit image.', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },splatmap: { tooltip: 'An image whose red, green, blue and alpha are the weights of grass, dirt, snow and rock.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },splatmap2: { tooltip: 'An image whose red, green, blue and alpha are the weights of layers 5 to 8.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },+ colorMap: { tooltip: 'A picture laid over the whole area and mixed into the ground\'s colour by its alpha. Its Use is Colour.', category: 'Layers', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },+ colorMapStrength: { min: 0, max: 1, step: 0.01, slider: true, category: 'Layers', tooltip: 'How much of the colour map is mixed in where its alpha is whole.', shownWhen: { field: 'extent', values: [TerrainExtent.Area] } },layers: { tooltip: 'The terrain layers (.esterrainlayer, up to eight) the ground is drawn with, in the order the paint weighs them. Empty draws the four layer colours.', category: 'Layers' },material: { tooltip: 'A material on the Terrain shader (on Terrain Layers when the ground has layers). Empty uses the stock one.', category: 'Layers' },sizeX: { min: 1, category: 'Shape', tooltip: 'An area\'s size along x; for ground without end, the span its hills are spread over.' },@@ -244,6 +250,8 @@ interface Built {arrays: number[];packed: string;packing: boolean;+ /** Whether the colour map is on the material: so taking it off is written once, and ground without one is written nothing. */+ washed: boolean;}/** Where a terrain's ground stands: still being made, ready, or failed (with why). */@@ -583,10 +591,10 @@ export class Terrains {/** The resource the plugin installs. @experimental */export const TerrainsRes = /* @__PURE__ */ defineResource<Terrains>(/* @__PURE__ */ new Terrains(), 'Terrains');-/** What, changed, rebuilds the ground: everything but the colours, the detail and the collision, which are read each frame. */+/** What, changed, rebuilds the ground: everything but the colours, the colour map, the detail and the collision, which are read each frame. */function signatureOf(data: TerrainData, at: { x: number; z: number }): string {const { layerColor0: _a, layerColor1: _b, layerColor2: _c, layerColor3: _d, detail: _e, drawDistance: _f,- collision: _g, collisionDistance: _h, collisionLayer: _i, friction: _j, layers, ...rest } = data;+ collision: _g, collisionDistance: _h, collisionLayer: _i, friction: _j, colorMap: _k, colorMapStrength: _l, layers, ...rest } = data;// Which layers are only what the arrays are packed from; whether there are any is which shader the ground is drawn with.const shape = { ...rest, layered: (layers?.length ?? 0) > 0 };// Ground read from a provider is the world's where the terrain stands: moved, it is read again; and a game's own provider is read@@ -667,7 +675,7 @@ export class TerrainPlugin implements Plugin {signature, data: { ...data }, source: null, surface: null, epoch: (built?.epoch ?? 0) + 1, loading: true, cancel: null,table: new PageTable(ATLAS_SIZE), heights: 0, paint: 0, mesh: 0, instance: 0,nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null, edits: 0,- paint2: 0, arrays: [], packed: '', packing: false,+ paint2: 0, arrays: [], packed: '', packing: false, washed: false,};terrains.built_.set(entity, built);void this.load(app, entity, built);@@ -1007,6 +1015,13 @@ export class TerrainPlugin implements Plugin {set('u_terrainEye', { x: eyeAt[0] + t.worldPosition.x, y: eyeAt[1] + t.worldPosition.y, z: eyeAt[2] + t.worldPosition.z, w: 1 });const b = source.bounds;set('u_terrainBounds', b ? { x: b[0], y: b[1], z: b[2], w: b[3] } : { x: -1e9, y: -1e9, z: 1e9, w: 1e9 });+ const wash = b && built.data.colorMap ? built.data.colorMapStrength : 0;+ if (wash > 0 && b) {+ set('u_colorMap', Material.tex(built.data.colorMap));+ set('u_colorMapArea', { x: b[0], y: b[1], z: b[2] - b[0], w: b[3] - b[1] });+ }+ if (wash > 0 || built.washed) set('u_colorMapStrength', wash);+ built.washed = wash > 0;// The four layer colours are the Terrain shader's; ground with layers is drawn by another, which has no such params.if (!built.data.material && (built.data.layers?.length ?? 0) === 0) {const d = built.data;diff --git a/sdk/src/terrain/terrainShader.ts b/sdk/src/terrain/terrainShader.tsindex 80f0454a7..74343a674 100644--- a/sdk/src/terrain/terrainShader.ts+++ b/sdk/src/terrain/terrainShader.ts@@ -130,6 +130,11 @@ const TERRAIN = `#pragma shader "Terrain"// Ground at the water: below u_wetLevel + u_wetBand (world heights) it darkens and shines, most at the waterline. A band of 0 draws none.#pragma param u_wetLevel float default(0) range(-100000,100000) ui(slider) unit(length)#pragma param u_wetBand float default(0) range(0,100000) ui(slider) unit(length)+// A picture laid over the whole ground and mixed into its colour by the picture's alpha: where it lies (its corner and its size on the+// terrain's own x and z) and how much of it.+#pragma param u_colorMap texture default(white)+#pragma param u_colorMapStrength float default(0) range(0,1) ui(slider)+#pragma param u_colorMapArea vec4 default(0,0,1,1)#pragma param u_roughness float default(0.92) range(0,1) ui(slider)// The ground in pages (pages.ts; the Terrain component writes these): heights and normals, and the paint, in two atlases; heights over// u_heightRange above u_terrainOrigin; level 0 drawn out to u_lodRange0, each level twice as far; nothing off u_terrainBounds.@@ -297,6 +302,12 @@ void main() {bool upright = abs(normalize(cross(dpx, dpy)).y) > 0.5;if (abs(det) > 1e-12 && u_relief > 0.0 && upright) N = Nb;+ if (u_colorMapStrength > 0.0) {+ vec2 over = (Pw.xz - u_terrainOrigin.xz - u_colorMapArea.xy) / max(u_colorMapArea.zw, vec2(1e-4));+ vec4 wash = texture(u_colorMap, over);+ bool on = all(greaterThanEqual(over, vec2(0.0))) && all(lessThanEqual(over, vec2(1.0)));+ albedo = mix(albedo, wash.rgb, on ? wash.a * u_colorMapStrength : 0.0);+ }// Wet at the water: darker, and smooth enough to shine.float wet = u_wetBand > 0.0 ? 1.0 - smoothstep(u_wetLevel, u_wetLevel + u_wetBand, P.y) : 0.0;albedo *= mix(1.0, 0.55, wet);@@ -457,6 +468,11 @@ fn packNormal(n : vec3f) -> vec2f {let upright = abs(normalize(cross(dpx, dpy)).y) > 0.5;if (abs(det) > 1e-12 && mc.u_relief > 0.0 && upright) { Ns = Nb; }+ if (mc.u_colorMapStrength > 0.0) {+ let over = (Pw.xz - mc.u_terrainOrigin.xz - mc.u_colorMapArea.xy) / max(mc.u_colorMapArea.zw, vec2f(1e-4));+ let wash = textureSampleLevel(u_colorMap, u_colorMap_s, over, 0.0);+ if (all(over >= vec2f(0.0)) && all(over <= vec2f(1.0))) { albedo = mix(albedo, wash.rgb, vec3f(wash.a * mc.u_colorMapStrength)); }+ }var wet = 0.0;if (mc.u_wetBand > 0.0) { wet = 1.0 - smoothstep(mc.u_wetLevel, mc.u_wetLevel + mc.u_wetBand, P.y); }albedo = albedo * mix(1.0, 0.55, wet);@@ -515,6 +531,11 @@ const TERRAIN_LAYERS = `#pragma shader "Terrain Layers"// Ground at the water: below u_wetLevel + u_wetBand (world heights) it darkens and shines, most at the waterline. A band of 0 draws none.#pragma param u_wetLevel float default(0) range(-100000,100000) ui(slider) unit(length)#pragma param u_wetBand float default(0) range(0,100000) ui(slider) unit(length)+// A picture laid over the whole ground and mixed into its colour by the picture's alpha: where it lies (its corner and its size on the+// terrain's own x and z) and how much of it.+#pragma param u_colorMap texture default(white)+#pragma param u_colorMapStrength float default(0) range(0,1) ui(slider)+#pragma param u_colorMapArea vec4 default(0,0,1,1)// The ground in pages, as the Terrain shader has them, with the paint of layers 5 to 8 in an atlas of its own.#pragma param u_terrainPages float default(0) range(0,1) ui(slider)#pragma param u_heightPages texture default(white) texel(data)@@ -719,6 +740,12 @@ void main() {colour *= mix(1.0, 0.7 + 0.6 * broad, u_macroVariation);N = normalize(N + slope);+ if (u_colorMapStrength > 0.0) {+ vec2 over = (Pw.xz - u_terrainOrigin.xz - u_colorMapArea.xy) / max(u_colorMapArea.zw, vec2(1e-4));+ vec4 wash = texture(u_colorMap, over);+ bool on = all(greaterThanEqual(over, vec2(0.0))) && all(lessThanEqual(over, vec2(1.0)));+ colour = mix(colour, wash.rgb, on ? wash.a * u_colorMapStrength : 0.0);+ }// Wet at the water: darker, and smooth enough to shine.float wet = u_wetBand > 0.0 ? 1.0 - smoothstep(u_wetLevel, u_wetLevel + u_wetBand, P.y) : 0.0;colour *= mix(1.0, 0.55, wet);@@ -935,6 +962,11 @@ fn packNormal(n : vec3f) -> vec2f {colour = colour * mix(1.0, 0.7 + 0.6 * broad, mc.u_macroVariation);N = normalize(N + slope);+ if (mc.u_colorMapStrength > 0.0) {+ let over = (Pw.xz - mc.u_terrainOrigin.xz - mc.u_colorMapArea.xy) / max(mc.u_colorMapArea.zw, vec2f(1e-4));+ let wash = textureSampleLevel(u_colorMap, u_colorMap_s, over, 0.0);+ if (all(over >= vec2f(0.0)) && all(over <= vec2f(1.0))) { colour = mix(colour, wash.rgb, vec3f(wash.a * mc.u_colorMapStrength)); }+ }var wet = 0.0;if (mc.u_wetBand > 0.0) { wet = 1.0 - smoothstep(mc.u_wetLevel, mc.u_wetLevel + mc.u_wetBand, P.y); }colour = colour * mix(1.0, 0.55, wet);diff --git a/sdk/tests/world-units.test.ts b/sdk/tests/world-units.test.tsindex dcc8f8274..0f54cba49 100644--- a/sdk/tests/world-units.test.ts+++ b/sdk/tests/world-units.test.ts@@ -42,6 +42,8 @@ describe('world-unit defaults', () => {expect([t.sizeX, t.sizeZ, t.height, t.cellSize, t.drawDistance, t.collisionDistance].map((v) => Math.round(v * 1000) / 1000)).toEqual([1000, 1000, 150, 2, 4000, 64]);// What is not a length stays: how many hills, how steep rock is.expect(t.frequency).toBe(3);+ // And the colour map: none, and all of one when it is set.+ expect([t.colorMap, t.colorMapStrength]).toEqual([0, 1]);});it('never touch a value the scene states, nor a field that is not a length', () => {