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
fix(terrain): the ground's lengths follow the project's units - a new Terrain is a kilometre on 2 m cells in a centimetre project and a metre one, its shaders' tiles, relief and wet line say unit(length), a layer with no tile repeats every 4 m, and ground with layers is no longer sent four colours its shader does not have
yhh859854ff7f11
diff --git a/examples/wilds/assets/scenes/main.esscene b/examples/wilds/assets/scenes/main.essceneindex 353d292fe..c679a1119 100644--- a/examples/wilds/assets/scenes/main.esscene+++ b/examples/wilds/assets/scenes/main.esscene@@ -252,6 +252,7 @@"sizeZ": 3200,"height": 560,"cellSize": 4,+ "collisionDistance": 64,"detail": 1.4,"heightmap": "assets/textures/height.png","rockSlope": 0.34,diff --git a/examples/wilds/tools/build.mjs b/examples/wilds/tools/build.mjsindex 540c1de53..5aa59f909 100644--- a/examples/wilds/tools/build.mjs+++ b/examples/wilds/tools/build.mjs@@ -349,7 +349,7 @@ function scene() {entity(4, 'Terrain', [{ type: 'Transform', data: {} },{ type: 'Terrain', data: {- sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 4, detail: 1.4,+ sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, cellSize: 4, detail: 1.4, collisionDistance: 64,heightmap: 'assets/textures/height.png', heightmapFormat: 1, rockSlope: 0.34, dirtHeight: 0.5, snowHeight: 0.84, material: 'assets/materials/terrain.esmaterial' } },]),entity(5, 'Lake', [diff --git a/examples/worldgen/assets/scenes/main.esscene b/examples/worldgen/assets/scenes/main.essceneindex 6ba53ba24..65915c498 100644--- a/examples/worldgen/assets/scenes/main.esscene+++ b/examples/worldgen/assets/scenes/main.esscene@@ -240,6 +240,7 @@"dirtHeight": 0.55,"snowHeight": 0.86,"cellSize": 4,+ "collisionDistance": 64,"detail": 1.4,"drawDistance": 9000,"material": "assets/materials/terrain.esmaterial"diff --git a/examples/worldgen/tools/build.mjs b/examples/worldgen/tools/build.mjsindex e22678270..e56c3f62d 100644--- a/examples/worldgen/tools/build.mjs+++ b/examples/worldgen/tools/build.mjs@@ -236,7 +236,7 @@ function scene() {entity(4, 'Ground', [{ type: 'Transform', data: {} },{ type: 'Terrain', data: {- extent: 1, provider: 'estella:noise', world: 'demo', generatorVersion: 1, ...GROUND, cellSize: 4, detail: 1.4, drawDistance: 9000,+ extent: 1, provider: 'estella:noise', world: 'demo', generatorVersion: 1, ...GROUND, cellSize: 4, detail: 1.4, drawDistance: 9000, collisionDistance: 64,material: 'assets/materials/terrain.esmaterial' } },]),entity(5, 'World', [diff --git a/sdk/src/terrain/layers.ts b/sdk/src/terrain/layers.tsindex 33a68d689..6b5fee282 100644--- a/sdk/src/terrain/layers.ts+++ b/sdk/src/terrain/layers.ts@@ -15,6 +15,7 @@* but its tile.*/import type { AssetLoader, LoadContext } from '../asset/AssetLoader';+import { worldUnitScale } from '../ecs/worldUnits';/** One kind of ground, as a `.esterrainlayer` file holds it. @experimental */export interface TerrainLayerDef {@@ -37,7 +38,9 @@ export interface TerrainLayerDef {heightBlend?: number;}-const DEFAULTS: TerrainLayerDef = { tile: 4, tint: [1, 1, 1], roughness: 0.9, normalStrength: 1 };+/** A layer file that names no tile repeats every 4 m: 400 units at the engine's reference, in the project's own (ecs/worldUnits.ts). */+const DEFAULT_TILE = 400;+const DEFAULTS: TerrainLayerDef = { tile: DEFAULT_TILE, tint: [1, 1, 1], roughness: 0.9, normalStrength: 1 };/** A layer from a file's JSON, with what it leaves out at its defaults; throws naming the first field it cannot take. */export function parseTerrainLayer(json: unknown, file = 'terrain layer'): TerrainLayerDef {@@ -60,7 +63,7 @@ export function parseTerrainLayer(json: unknown, file = 'terrain layer'): Terraithrow new Error(`${file}.tint: three numbers, red, green and blue`);return {albedo: path('albedo'), normal: path('normal'), mask: path('mask'),- tile: num('tile', DEFAULTS.tile, 1e-3, 1e6),+ tile: num('tile', DEFAULT_TILE * worldUnitScale(), 1e-3, 1e6),tint: tint as [number, number, number],roughness: num('roughness', DEFAULTS.roughness, 0, 1),normalStrength: num('normalStrength', DEFAULTS.normalStrength, 0, 4),diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex f5265455b..4de755ea7 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -139,13 +139,15 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });*/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,- sizeX: 1000, sizeZ: 1000, height: 150, cellSize: 2, detail: 1, drawDistance: 4000,- collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,+ // 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,seed: 1, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, resolution: 257, warp: 0, erosion: 0,rockSlope: 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' }],+ 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).' },provider: { category: 'Shape', tooltip: 'The generator the ground is made by, without end or (with no heightmap) in an area: estella:noise, or one the game registers. The same provider, world, seed and version are the same ground on every machine, and two areas side by side join.' },@@ -1005,7 +1007,8 @@ 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 });- if (!built.data.material) {+ // 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;for (const [i, c] of [d.layerColor0, d.layerColor1, d.layerColor2, d.layerColor3].entries()) set(`u_tint${i}`, { x: c.r, y: c.g, z: c.b, w: c.a });}diff --git a/sdk/src/terrain/terrainShader.ts b/sdk/src/terrain/terrainShader.tsindex b04536a6c..80f0454a7 100644--- a/sdk/src/terrain/terrainShader.ts+++ b/sdk/src/terrain/terrainShader.ts@@ -107,10 +107,10 @@ const TERRAIN = `#pragma shader "Terrain"#pragma param u_tint1 color default(0.45,0.36,0.24,1)#pragma param u_tint2 color default(0.93,0.95,0.98,1)#pragma param u_tint3 color default(0.4,0.38,0.36,1)-#pragma param u_tile0 float default(24) range(1,800) ui(slider)-#pragma param u_tile1 float default(24) range(1,800) ui(slider)-#pragma param u_tile2 float default(24) range(1,800) ui(slider)-#pragma param u_tile3 float default(40) range(1,800) ui(slider)+#pragma param u_tile0 float default(2400) range(100,80000) ui(slider) unit(length)+#pragma param u_tile1 float default(2400) range(100,80000) ui(slider) unit(length)+#pragma param u_tile2 float default(2400) range(100,80000) ui(slider) unit(length)+#pragma param u_tile3 float default(4000) range(100,80000) ui(slider) unit(length)// How much a layer with more weight takes over from the others at the seam: 1 is a plain blend, higher a harder edge.#pragma param u_sharpness float default(1.6) range(1,8) ui(slider)// How much the seams follow the layers' own relief (their brightness): rock shows through the gaps in the grass before the grass gives way,@@ -126,10 +126,10 @@ const TERRAIN = `#pragma shader "Terrain"// The wide, slow variation in brightness laid over every layer so a big meadow is not one colour.#pragma param u_macroVariation float default(0.35) range(0,1) ui(slider)// How deep, in world units, the layers' relief is drawn into the light (their brightness taken as height); 0 leaves the ground smooth.-#pragma param u_relief float default(0.05) range(0,100000) ui(slider)+#pragma param u_relief float default(5) range(0,10000000) ui(slider) unit(length)// 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)-#pragma param u_wetBand float default(0) range(0,100000) ui(slider)+#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)#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.@@ -513,8 +513,8 @@ const TERRAIN_LAYERS = `#pragma shader "Terrain Layers"// How steep the ground must be (1 minus its normal's up) before the layers are also projected from the sides.#pragma param u_triplanarFrom float default(0.15) range(0,1) ui(slider)// 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)-#pragma param u_wetBand float default(0) range(0,100000) ui(slider)+#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)// 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)diff --git a/sdk/tests/shader-param-units.test.ts b/sdk/tests/shader-param-units.test.tsindex 3fef84973..ddac5bacc 100644--- a/sdk/tests/shader-param-units.test.ts+++ b/sdk/tests/shader-param-units.test.ts@@ -6,6 +6,7 @@ import { setWorldUnitsPerMeter } from '../src/ecs/worldUnits';import { WATER_SHADER_TEMPLATE } from '../src/water/waterShader';import { WaterBody } from '../src/water/waterPlugin';import { WaterZone } from '../src/water/zone';+import { TERRAIN_LAYERS_SHADER_TEMPLATE, TERRAIN_SHADER_TEMPLATE } from '../src/terrain/terrainShader';const SOURCE = `#pragma shader "T"#pragma param u_reach float default(250) range(10,4000) unit(length)@@ -30,6 +31,20 @@ describe('a shader param that is a world length', () => {expect(param(SOURCE, 'u_gain').default).toEqual([2]);});+ it('is how the ground says its lengths: a layer 24 m across, relief of 5 cm, the wet line where the scene puts it', () => {+ const ground = TERRAIN_SHADER_TEMPLATE.source, layered = TERRAIN_LAYERS_SHADER_TEMPLATE.source;+ expect(param(ground, 'u_tile0').default).toEqual([2400]);+ expect(param(ground, 'u_relief').default).toEqual([5]);+ setWorldUnitsPerMeter(1);+ expect(param(ground, 'u_tile0').default[0]).toBeCloseTo(24, 9);+ expect(param(ground, 'u_tile3').default[0]).toBeCloseTo(40, 9);+ expect(param(ground, 'u_relief').default[0]).toBeCloseTo(0.05, 9);+ // A slider's reach is a length too: either ground shader's wet line can be put a kilometre up, whatever a unit is.+ for (const source of [ground, layered]) {+ for (const name of ['u_wetLevel', 'u_wetBand']) expect(param(source, name).range!.max).toBeCloseTo(1000, 9);+ }+ });+it('is how the water says its lengths: the same water in a centimetre project and a metre one', () => {const lengths = ['u_waveLength', 'u_rippleLength', 'u_distortionRange', 'u_foamWidth', 'u_fallbackDepth', 'u_causticScale'];const cm = lengths.map((n) => param(WATER_SHADER_TEMPLATE.source, n).default[0]!);diff --git a/sdk/tests/terrain-layers.test.ts b/sdk/tests/terrain-layers.test.tsindex 9aed923c7..9d8bcce4b 100644--- a/sdk/tests/terrain-layers.test.ts+++ b/sdk/tests/terrain-layers.test.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';+import { setWorldUnitsPerMeter, REFERENCE_UNITS_PER_METER } from '../src/ecs/worldUnits';import { packLayers, parseTerrainLayer, type LayerImage } from '../src/terrain/layers';import { FieldSource } from '../src/terrain/source';import { makePage, PAGE_SIDE } from '../src/terrain/pages';@@ -11,12 +12,22 @@ const solid = (size: number, rgba: [number, number, number, number]): LayerImagereturn { width: size, height: size, pixels };};+afterEach(() => setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER));+describe('a terrain layer file', () => {it('takes what it names and puts the rest at their defaults', () => {const l = parseTerrainLayer({ albedo: 'assets/grass.png', tile: 3 });expect(l).toMatchObject({ albedo: 'assets/grass.png', normal: undefined, mask: undefined, tile: 3, tint: [1, 1, 1], roughness: 0.9, normalStrength: 1 });});+ it('repeats every 4 m when it names no tile, in the units of the project', () => {+ expect(parseTerrainLayer({}).tile).toBe(400);+ setWorldUnitsPerMeter(1);+ expect(parseTerrainLayer({}).tile).toBeCloseTo(4);+ // What a file states is the project's already.+ expect(parseTerrainLayer({ tile: 3 }).tile).toBe(3);+ });+it('keeps a height blend of its own only when it names one', () => {expect(parseTerrainLayer({ tile: 3 }).heightBlend).toBeUndefined();expect(parseTerrainLayer({ tile: 3, heightBlend: 0.15 }).heightBlend).toBe(0.15);diff --git a/sdk/tests/terrain-provider.test.ts b/sdk/tests/terrain-provider.test.tsindex ccdb20d73..e825da1b4 100644--- a/sdk/tests/terrain-provider.test.ts+++ b/sdk/tests/terrain-provider.test.ts@@ -1,11 +1,12 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { App } from '../src/app/app';import { AppContext, setDefaultContext } from '../src/ecs/context';import { setEditorMode, setPlayMode } from '../src/ecs/env';import { Transform } from '../src/ecs/component';import { createMockModule } from './mocks/wasm';+import { setWorldUnitsPerMeter, REFERENCE_UNITS_PER_METER } from '../src/ecs/worldUnits';import { Terrain, TerrainExtent, TerrainPlugin, TerrainsRes, paintWeights } from '../src/terrain/terrainPlugin';import {noiseProvider, ProviderSource, registerTerrainProvider, TerrainUnavailable, type TerrainProvider, type TerrainRegion,@@ -13,6 +14,10 @@ import {import { makePage, PAGE_SIDE, PAGE_TEXELS, type PageImage } from '../src/terrain/pages';import { flattenModifier, type NoiseParams } from '../src/terrain/source';+// These scenes are written in metres: a project of one unit a metre, so the Terrain's own defaults are metres beside them.+beforeAll(() => setWorldUnitsPerMeter(1));+afterAll(() => setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER));+const params: NoiseParams = { seed: 7, frequency: 3, octaves: 5, persistence: 0.5, ridged: 0.35, warp: 0.3, erosion: 1, sizeX: 2000, height: 300,rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };const paint = (h: number, ny: number) => paintWeights(h / 300, ny, params);diff --git a/sdk/tests/terrain-surface.test.ts b/sdk/tests/terrain-surface.test.tsindex e0114a9b9..ce34e7fe7 100644--- a/sdk/tests/terrain-surface.test.ts+++ b/sdk/tests/terrain-surface.test.ts@@ -3,7 +3,7 @@/*** @file The ground is one set of triangles: what is drawn near the eye, what bodies collide with and what heightAt answers.*/-import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';import { App } from '../src/app/app';import { AppContext, setDefaultContext } from '../src/ecs/context';import { setEditorMode, setPlayMode } from '../src/ecs/env';@@ -21,8 +21,13 @@ import { Physics3D, Physics3DPlugin, Physics3DRuntime } from '../src/physics3d/Pimport type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';import type { ESEngineModule } from '../src/wasm';import type { Entity } from '../src/types';+import { setWorldUnitsPerMeter, REFERENCE_UNITS_PER_METER } from '../src/ecs/worldUnits';import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';+// These scenes are written in metres: a project of one unit a metre, so the Terrain's own defaults are metres beside them.+beforeAll(() => setWorldUnitsPerMeter(1));+afterAll(() => setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER));+const params: NoiseParams = { seed: 3, frequency: 4, octaves: 5, persistence: 0.5, ridged: 0.3, warp: 0.2, erosion: 1, sizeX: 400, height: 40,rockSlope: 0.35, dirtHeight: 0.62, snowHeight: 0.88 };const terrainOf = (over: Record<string, unknown> = {}) => ({ ...Terrain._default, extent: TerrainExtent.Infinite, cellSize: 2, ...params, ...over });diff --git a/sdk/tests/world-units.test.ts b/sdk/tests/world-units.test.tsindex 2fea080e0..dcc8f8274 100644--- a/sdk/tests/world-units.test.ts+++ b/sdk/tests/world-units.test.ts@@ -10,6 +10,7 @@ import { defineComponent } from '../src/ecs/component';import { CharacterController3D, BoxCollider3D } from '../src/physics3d/Physics3DComponents';import { FirstPersonController, FirstPersonViewModel } from '../src/gameplay/FirstPersonController';import { NavVolume } from '../src/ai/nav/NavVolume';+import { Terrain } from '../src/terrain/terrainPlugin';import { getComponent } from '../src/ecs/component';afterEach(() => setWorldUnitsPerMeter(REFERENCE_UNITS_PER_METER));@@ -34,6 +35,15 @@ describe('world-unit defaults', () => {expect(NavVolume.create().cellSize).toBeCloseTo(0.5);});+ it('make a new Terrain a kilometre of ground on 2 m cells whatever a unit is in the project', () => {+ expect(Terrain._default).toMatchObject({ sizeX: 100000, sizeZ: 100000, height: 15000, cellSize: 200, drawDistance: 400000, collisionDistance: 6400 });+ setWorldUnitsPerMeter(1);+ const t = Terrain._default;+ 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);+ });+it('never touch a value the scene states, nor a field that is not a length', () => {setWorldUnitsPerMeter(1);const fp = FirstPersonController.create({ moveSpeed: 5 });