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(worldgen): a chunk of decoration or grass is drawn out to the distance its rule names, however little stands in it - a chunk with one group of rocks was culled 60 m away under a rule that said 1200
yhhc396fc2adbef
diff --git a/sdk/src/foliage/foliagePlugin.ts b/sdk/src/foliage/foliagePlugin.tsindex 6004c9a04..6aede164f 100644--- a/sdk/src/foliage/foliagePlugin.ts+++ b/sdk/src/foliage/foliagePlugin.ts@@ -29,6 +29,7 @@ import { currentWeather, currentWeatherDrive, WeatherDrive } from '../postprocesimport { isEditor, isPlayMode } from '../ecs/env';import type { Zones } from '../worldgen/zones';import { installFoliageContacts } from './foliageContacts';+import { lodCullSizeWithin, lodSizeAtDistance, lodSphereRadius } from '../render/lodDistance';import {buildBillboardMesh, buildGrassMesh, buildInstancedMesh, scatterCell,type Ground, type Plant,@@ -390,12 +391,13 @@ export class FoliagePlugin implements Plugin {} as Partial<MeshRendererData>);const lodDef = getComponent('LODGroup');if (lodDef) {- // The engine measures a cell by how much of the screen its bounding sphere covers: radius over distance, for a 60 degree view.- const radius = Math.hypot(side, side) * 0.5;- const sizeAt = (distance: number): number => radius / (Math.max(1, distance) * 0.577);+ // The component's distances as the screen sizes the engine compares, on the sphere it will measure: the one round the+ // plants this cell grew, not round the cell — a cell with a few plants at one edge is a fraction of its own square.+ const radius = lodSphereRadius(handles.length > 1 ? meshes : [meshes[0]]);world.insert(cell, lodDef, {lod1: handles[1] ?? 0, lod2: 0, lod3: 0,- lod1Size: sizeAt(data.lodDistance), lod2Size: 0, lod3Size: 0, cullSize: sizeAt(data.drawDistance), hysteresis: 0.1, enabled: true,+ lod1Size: lodSizeAtDistance(radius, data.lodDistance), lod2Size: 0, lod3Size: 0,+ cullSize: lodCullSizeWithin(radius, data.drawDistance), hysteresis: 0.1, enabled: true,});}return { entity: cell, handles };diff --git a/sdk/src/render/lodDistance.ts b/sdk/src/render/lodDistance.tsnew file mode 100644index 000000000..6a39f5fed--- /dev/null+++ b/sdk/src/render/lodDistance.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file lodDistance.ts+ * @brief A rule that says a distance, as the screen size a LODGroup is told.+ *+ * @details A LODGroup's thresholds are fractions of the screen's height, measured+ * on the bounding sphere of the geometry it actually draws. A rule a+ * person writes is a distance — "draw this out to 600 m" — so something+ * turns one into the other, and it has to use the sphere the engine will+ * measure: the half-diagonal of the box that holds every level of the+ * group (`lod::boundingSphere` over `gatherLodLevels`).+ *+ * A guessed radius is how a chunk comes to vanish in front of the player.+ * A chunk of a world is as big as what stands in it: a 192 m square with+ * one group of rocks in a corner has a sphere of a few metres, and a+ * threshold worked out for the square's own diagonal culled it at a few+ * percent of the distance its rule named.+ */++/** The field of view the distances are meant in. A narrower one draws further, as a zoom should. */+export const LOD_REFERENCE_FOV_DEG = 60;++const HALF_VIEW = Math.tan((LOD_REFERENCE_FOV_DEG / 2) * Math.PI / 180);++/** A box as mesh data carries it. */+export interface LodBox {+ aabbMin: readonly [number, number, number];+ aabbMax: readonly [number, number, number];+}++/**+ * The radius the engine measures a LODGroup by: the half-diagonal of the one box+ * that holds every level's geometry. Zero when no level is given.+ */+export function lodSphereRadius(levels: readonly (LodBox | null | undefined)[]): number {+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];+ let any = false;+ for (const level of levels) {+ if (!level) continue;+ any = true;+ for (let i = 0; i < 3; i++) {+ lo[i] = Math.min(lo[i]!, level.aabbMin[i]!);+ hi[i] = Math.max(hi[i]!, level.aabbMax[i]!);+ }+ }+ if (!any) return 0;+ return Math.hypot(hi[0]! - lo[0]!, hi[1]! - lo[1]!, hi[2]! - lo[2]!) / 2;+}++/**+ * The share of the screen's height a sphere of `radius` covers with its centre+ * `distance` away, in the reference view: the LODGroup threshold that falls at+ * that distance. A level takes over, or the group is culled, once the sphere is+ * smaller than its threshold — that is, further than `distance`.+ */+export function lodSizeAtDistance(radius: number, distance: number): number {+ return radius / (Math.max(1, distance) * HALF_VIEW);+}++/**+ * The cull threshold that keeps a group drawn while any of its sphere is within+ * `distance`: the centre may be a radius further than the part nearest the eye.+ */+export function lodCullSizeWithin(radius: number, distance: number): number {+ return lodSizeAtDistance(radius, distance + radius);+}diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex ec1044c6f..82a728d6e 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -51,6 +51,7 @@ import { worldRules, worldRulesRevision, type PlacementLayer, type RecipeMember,import { Zones, type ZoneDef } from './zones';import { PlacementDiffs } from './diffs';import { isRulesFile } from './rulesAsset';+import { lodCullSizeWithin, lodSizeAtDistance, lodSphereRadius } from '../render/lodDistance';import { enableSceneOrigins, sceneOriginOf } from '../scene/sceneOrigins';/** The fields of the `WorldGen` component. @experimental */@@ -208,7 +209,7 @@ interface Unit {interface PlacedChunk {assets?: AssetLease<AssetScope>;/** A kind of decoration: its near mesh and, when it has one, its far cards; drawn near out to `lodDistance`, out to `drawDistance`. */- decor: { mesh: number; material: number; data: MeshData; far: MeshData | null; origin: [number, number, number]; radius: number; lodDistance: number; drawDistance: number }[];+ decor: { mesh: number; material: number; data: MeshData; far: MeshData | null; origin: [number, number, number]; lodDistance: number; drawDistance: number }[];objects: Placement[];/** The plants of the rules' `plants` in it, by kind, standing relative to `at` (the chunk's centre), and what grew them once published. */planted: Map<number, Plant[]> | null;@@ -890,7 +891,7 @@ export class WorldGenPlugin implements Plugin {out.decor.push({mesh: list[0]!.mesh, material: list[0]!.material, data: buildInstancedMesh(source, plants), origin,far: far ? buildBillboardMesh(plants, width, source.aabbMax[1] - source.aabbMin[1], far, undefined, far.tent === true) : null,- radius: Math.SQRT2 * size / 2, lodDistance: layer.lodDistance ?? layer.drawDistance, drawDistance: layer.drawDistance,+ lodDistance: layer.lodDistance ?? layer.drawDistance, drawDistance: layer.drawDistance,});}return out;@@ -954,11 +955,12 @@ export class WorldGenPlugin implements Plugin {} as Partial<MeshRendererData>);const lodDef = getComponent('LODGroup');if (lodDef) {- // Measured as the engine measures it, by the share of the screen the chunk's sphere covers, for a 60 degree view.- const sizeAt = (distance: number): number => d.radius / (Math.max(1, distance) * 0.577);+ // The layer's distances as the screen sizes the engine compares, on the sphere it will measure: the one round+ // what this chunk actually holds, which for a chunk with one group of rocks in it is a small part of the chunk.+ const radius = lodSphereRadius([d.data, farHandle ? d.far : null]);world.insert(e, lodDef, {- lod1: farHandle, lod2: 0, lod3: 0, lod1Size: farHandle ? sizeAt(d.lodDistance) : 0, lod2Size: 0, lod3Size: 0,- cullSize: sizeAt(d.drawDistance + d.radius), hysteresis: 0.1, enabled: true,+ lod1: farHandle, lod2: 0, lod3: 0, lod1Size: farHandle ? lodSizeAtDistance(radius, d.lodDistance) : 0, lod2Size: 0, lod3Size: 0,+ cullSize: lodCullSizeWithin(radius, d.drawDistance), hysteresis: 0.1, enabled: true,});}world.setParent(e, parent);diff --git a/sdk/tests/lod-distance.test.ts b/sdk/tests/lod-distance.test.tsnew file mode 100644index 000000000..206cdd52f--- /dev/null+++ b/sdk/tests/lod-distance.test.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A distance a rule names, as the screen size a LODGroup compares — on the sphere the engine measures.+ */+import { describe, it, expect } from 'vitest';+import { LOD_REFERENCE_FOV_DEG, lodCullSizeWithin, lodSizeAtDistance, lodSphereRadius } from '../src/render/lodDistance';++/** The engine's side (lod::screenRelativeSize, on the view's axis): how far a sphere is when it covers `size` of the screen. */+const distanceAtSize = (radius: number, size: number, fovDeg = LOD_REFERENCE_FOV_DEG): number =>+ radius / (size * Math.tan((fovDeg / 2) * Math.PI / 180));++describe('lodSphereRadius', () => {+ it('is the half-diagonal of the box that holds every level', () => {+ const fine = { aabbMin: [0, 0, 0] as const, aabbMax: [6, 0, 8] as const };+ expect(lodSphereRadius([fine])).toBeCloseTo(5);+ // The far cards stand taller than the near mesh: the engine measures the union.+ const far = { aabbMin: [0, 0, 0] as const, aabbMax: [6, 24, 8] as const };+ expect(lodSphereRadius([fine, far])).toBeCloseTo(13);+ expect(lodSphereRadius([fine, null])).toBeCloseTo(5);+ expect(lodSphereRadius([])).toBe(0);+ });+});++describe('a distance as a LODGroup threshold', () => {+ // A 192 m chunk of a generated world with one group of rocks in a corner. Sized by the chunk's own diagonal (136 m)+ // it was culled 60 m away under a rule that said 1200.+ it('culls a chunk where its rule says, however little stands in it', () => {+ for (const radius of [5, 40, 136, 400]) {+ const cull = lodCullSizeWithin(radius, 1200);+ // Drawn while any of the sphere is within the distance: the centre is a radius further.+ expect(distanceAtSize(radius, cull)).toBeCloseTo(1200 + radius, 3);+ }+ });++ it('hands over to the far level at the distance named', () => {+ for (const radius of [5, 136]) {+ expect(distanceAtSize(radius, lodSizeAtDistance(radius, 300))).toBeCloseTo(300, 3);+ }+ });++ it('keeps the far level ahead of the cull, as a group needs its sizes to descend', () => {+ expect(lodSizeAtDistance(20, 300)).toBeGreaterThan(lodCullSizeWithin(20, 1200));+ });++ it('draws further through a narrower view, as a zoom should', () => {+ const cull = lodCullSizeWithin(20, 600);+ expect(distanceAtSize(20, cull, 30)).toBeGreaterThan(distanceAtSize(20, cull, 60));+ });+});