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(worldgen): a layer plans the far versions of its plants sparsely, and a failed asset load is tried again

yhh904d0314d3ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58f0e5b3b..9d3f203b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ published separately; it ships inside the editor.
### Added
+- **A far world is planned sparsely, and a failed asset load is tried again.** A layer's `farSpacing` plans the far versions of its plants that much further apart, so ground cover that keeps a quarter of its plants far off no longer plans all of them first, and the far plants of a planet settle in a quarter of the time. A world whose recipes' assets fail to load while the project is still opening tries again, a few times and a little later each time, instead of staying empty.
- **A quality level sets how far plants keep their detail.** A level's profile takes a `detailScale` (0.25 to 1; Low 0.5, Medium 0.8, High 1): a placed plant changes to its cheaper mesh, stops being drawn and stops casting a shadow at that share of its distances, so the same world draws a fraction of the triangles on a phone. It is a row in Project Settings → Rendering → Quality Levels.
- **Placed plants cast shadows only as far as twice their detailed distance.** `MeshInstances` takes a `shadowDistance` (metres from the eye past which an instance casts no shadow); a plant kind with a cheaper mesh sets it to twice that mesh's distance, so a tree far off is drawn into the shadow maps no more than its shadow is worth.
- **The editor lets go of a generated world while the game plays.** The game runs in a realm of its own that builds its own copy of a generated world; the editor's copy is released for as long as it runs and made again on Stop, so the two are not held together.
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index ba1905426..0ce6ea769 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -110,7 +110,7 @@ Plants are grown a cell at a time by the same machinery as a [placed foliage](/d
Layers are passes, in order: big things first. Each takes one candidate a cell of a grid `spacing` apart, jittered, with a priority
drawn for it. Of two candidates whose groups would overlap, the higher priority stands; every candidate keeps clear of the footprints
of the layers before it, so a fern does not grow through a trunk and a stone does not sit inside a boulder. A layer is published in
-chunks of `chunkSize` out to `drawDistance`. `occupies: false` makes a layer that later ones may overlap (ground cover).
+chunks of `chunkSize` out to `drawDistance`. `occupies: false` makes a layer that later ones may overlap (ground cover). `farSpacing` (default 1) plans the far versions of a layer's plants that much further apart: ground cover whose far versions keep a quarter of the plants is planned at 2, so a quarter of the candidates are worked out and none is made only to be thrown away.
## Zones
diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
index bdcd124c4..60ca1fc7e 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -84,7 +84,7 @@ registerWorldRules({
### 层
-层是按顺序进行的几遍布置:先大后小。每层在间距为 `spacing` 的网格里每格取一个抖动后的候选点,并为它抽一个优先级。两个候选点的组会重叠时,优先级高的成立;每个候选点都避开前面各层的占地,所以蕨类不会长穿树干,石头不会嵌进巨石里。一层以 `chunkSize` 大小的区块发布到 `drawDistance`。`occupies: false` 让后面的层可以和它重叠(地被)。
+层是按顺序进行的几遍布置:先大后小。每层在间距为 `spacing` 的网格里每格取一个抖动后的候选点,并为它抽一个优先级。两个候选点的组会重叠时,优先级高的成立;每个候选点都避开前面各层的占地,所以蕨类不会长穿树干,石头不会嵌进巨石里。一层以 `chunkSize` 大小的区块发布到 `drawDistance`。`occupies: false` 让后面的层可以和它重叠(地被)。`farSpacing`(默认 1)让这一层植物的远景版本按更大的间距规划:远景只保留四分之一的地被设为 2,只需要算四分之一的候选点,不再先全算出来再丢掉。
## 区域
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 8cec11e4c..196acd533 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -162,7 +162,7 @@ z: number
```
app_: App | null
growCell: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>) => void
-growFar: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number; }) => void
+growFar: (app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number; }, thinnedBy?: number) => void
made: number
pending: number
queue: { cell: GrownCell; run: () => void; }[]
@@ -259,6 +259,6 @@ Plugin
## thinPlants — function @experimental
```
-(plants: readonly Plant[], keep: number): readonly Plant[]
+(plants: readonly Plant[], keep: number, already?: number): readonly Plant[]
```
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 96be3b511..98bc164bf 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6690,6 +6690,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 7924ec35e..fad381430 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6893,6 +6893,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 0a3b5100a..8e4d95ebe 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6685,6 +6685,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d67a220a4..f1c493d55 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6978,6 +6978,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 86d7ed729..353a4de21 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6692,6 +6692,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.md
index 451b48c26..a63a429b5 100644
--- a/sdk/etc/worldgen.api.md
+++ b/sdk/etc/worldgen.api.md
@@ -148,6 +148,7 @@ version: 1
```
chunkSize: number | undefined
drawDistance: number
+farSpacing: number | undefined
id: string
lodDistance: number | undefined
occupies: boolean | undefined
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index 9c83ddab8..ce4cf4867 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -352,13 +352,14 @@ export function softenNormals(source: MeshData, amount: number): MeshData {
/**
* The plants a far version draws, when it draws a share `keep` of them (above 0 to 1): every n-th, n the nearest whole number to 1 / keep, each grown by the
* square root of n (to a most of twice) so the ground they cover is what it was. The same plants every time: what is kept is a matter of order.
+ * `already` is how many times thinner the plants were planned than they would be (a far plan with sparser spacing): the n-th is then every n / `already`-th.
*/
-export function thinPlants(plants: readonly Plant[], keep: number): readonly Plant[] {
+export function thinPlants(plants: readonly Plant[], keep: number, already = 1): readonly Plant[] {
const n = Math.max(1, Math.round(1 / Math.min(Math.max(keep, 1e-3), 1)));
if (n === 1) return plants;
- const grow = Math.min(Math.sqrt(n), 2);
+ const grow = Math.min(Math.sqrt(n), 2), every = Math.max(1, Math.round(n / Math.max(already, 1)));
const out: Plant[] = [];
- for (let i = 0; i < plants.length; i += n) out.push({ ...plants[i]!, scale: plants[i]!.scale * grow });
+ for (let i = 0; i < plants.length; i += every) out.push({ ...plants[i]!, scale: plants[i]!.scale * grow });
return out;
}
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
index 5fe2a440d..55f288362 100644
--- a/sdk/src/foliage/plantGrowth.ts
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -156,15 +156,16 @@ export class PlantGrowth {
/**
* Grows the far version of `cell`: each kind with one, its plants (thinned to the kind's `farKeep`) as a set of the far part's, drawn from
- * where the kind stops (`drawDistance`) out to `farDistance` from the eye. Cheap enough (a tree is two cards) to be made at once.
+ * where the kind stops (`drawDistance`) out to `farDistance` from the eye. Cheap enough (a tree is two cards) to be made at once. `thinnedBy` is how many
+ * times thinner they were planned already (a far plan), so they are not thinned twice.
*/
- growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number }): void {
+ growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number }, thinnedBy = 1): void {
const entity = cell.entity;
if (entity === null) return;
for (const [kindIndex, plants] of byKind) {
const parts = ready.far[kindIndex], kind = kinds[kindIndex];
if (!kind || !parts || parts.length === 0) continue;
- const kept = thinPlants(plants, kind.farKeep ?? 1);
+ const kept = thinPlants(plants, kind.farKeep ?? 1, thinnedBy);
for (const r of parts) this.place(app, entity, `far ${kindIndex}`, r, kept, 0, kind.drawDistance, kind.farDistance, 0, true);
}
}
diff --git a/sdk/src/worldgen/rules.ts b/sdk/src/worldgen/rules.ts
index 5f8f10eb3..cac7aab86 100644
--- a/sdk/src/worldgen/rules.ts
+++ b/sdk/src/worldgen/rules.ts
@@ -100,6 +100,11 @@ export interface PlacementLayer {
/** Past this, decoration that has a far version is drawn as it; the layer's draw distance when absent. */
lodDistance?: number;
chunkSize?: number;
+ /**
+ * How much further apart the far versions of this layer's plants are planned than the layer's `spacing` (default 1): a plant kind that keeps a quarter
+ * of its plants far off is planned at 2, which is a quarter of the candidates to work out instead of all of them and three in four thrown away.
+ */
+ farSpacing?: number;
/** Whether later layers keep clear of its footprints (default true). */
occupies?: boolean;
}
diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.ts
index 71b93d0ae..5ca5cd307 100644
--- a/sdk/src/worldgen/rulesAsset.ts
+++ b/sdk/src/worldgen/rulesAsset.ts
@@ -131,6 +131,7 @@ export function parseWorldRules(json: unknown, file = 'world rules'): WorldRules
return {
...(o as object),
id: str(o.id, `${where}.id`), spacing: num(o.spacing, `${where}.spacing`, 1e-6), drawDistance: num(o.drawDistance, `${where}.drawDistance`, 0),
+ ...(o.farSpacing === undefined ? {} : { farSpacing: num(o.farSpacing, `${where}.farSpacing`, 1) }),
} as PlacementLayer;
});
const recipeIds = new Set(recipes.map((x) => x.id)), layerIds = new Set(layers.map((x) => x.id));
diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.ts
index 500e0b714..de4b8ad7b 100644
--- a/sdk/src/worldgen/worldgenPlugin.ts
+++ b/sdk/src/worldgen/worldgenPlugin.ts
@@ -142,6 +142,8 @@ interface BuiltWorld {
data: WorldGenData;
rules: WorldRules | null;
plan: WorldPlan | null;
+ /** The same plan with the sparser spacing the layers that have a `farSpacing` are planned at for their far versions; null when none has one. */
+ farPlan: WorldPlan | null;
failure: string | null;
/** The terrain's and the water's revisions the plan was read from. */
ground: string;
@@ -167,6 +169,8 @@ interface PlacedChunk {
grown: GrownCell | null;
/** Made for the far layer: only the far versions of its plants, which are shown from past what their kinds draw as themselves. */
far: boolean;
+ /** How many times thinner than the layer's own spacing the plants were planned (its `farSpacing` squared): the far version does not thin them again. */
+ thinnedBy: number;
entities: Entity[];
meshes: number[];
}
@@ -236,6 +240,20 @@ export class WorldGens {
/** The resource the plugin installs. @experimental */
export const WorldGenRes = defineResource<WorldGens>(new WorldGens(), 'WorldGens');
+/**
+ * Runs an asset load again when it fails, a few times and a little later each time. Reading a project's files is slowest while the project is still being
+ * opened (the asset database is scanned and cooked against it), and a load that waited out its timeout then is not a world that cannot be shown.
+ */
+async function retried<T>(load: () => Promise<T>, attempts = 5): Promise<T> {
+ for (let n = 1; ; n++) {
+ try { return await load(); } catch (error) {
+ if (n >= attempts) throw error;
+ log.warn('worldgen', `loading the world's assets failed (${error instanceof Error ? error.message : String(error)}); trying again`);
+ await new Promise<void>((resolve) => setTimeout(resolve, 2000 * n));
+ }
+ }
+}
+
export class WorldGenPlugin implements Plugin {
name = 'worldgen';
@@ -275,7 +293,7 @@ export class WorldGenPlugin implements Plugin {
/** A WorldGen's rules and plan, or why it has none. */
private make(app: App, gens: WorldGens, entity: Entity, data: WorldGenData, had: BuiltWorld | undefined): BuiltWorld {
- const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, failure: null, ground: '', authored: had?.authored ?? new Set(), levelling: new Set(), plants: null, plantsReady: null };
+ const built: BuiltWorld = { signature: `${JSON.stringify(data)}#${worldRulesRevision()}`, data: { ...data }, rules: null, plan: null, farPlan: null, failure: null, ground: '', authored: had?.authored ?? new Set(), levelling: new Set(), plants: null, plantsReady: null };
// Rules in a project file are read first, then made like rules registered by code.
if (isRulesFile(data.rules)) {
if (!app.hasResource(Assets)) {
@@ -329,7 +347,7 @@ export class WorldGenPlugin implements Plugin {
if (rules.plants && Object.keys(rules.plants).length > 0 && app.hasResource(Assets)) {
const set = expandPlants(rules.plants);
built.plants = set;
- void prepareKinds(app.getResource(Assets), set.kinds).then((ready) => {
+ void retried(() => prepareKinds(app.getResource(Assets), set.kinds)).then((ready) => {
if (gens.built_.get(entity) === built) built.plantsReady = ready;
}, (e: unknown) => {
built.failure = `the plants' assets could not be loaded: ${e instanceof Error ? e.message : String(e)}`;
@@ -339,7 +357,7 @@ export class WorldGenPlugin implements Plugin {
// Recipes name their meshes and materials by path: with a renderer they are loaded first, and the plan is made with them.
const refs = assetRefsOf(rules);
if (refs.length > 0 && app.hasResource(Assets)) {
- void this.resolve(app, rules, refs).then((resolved) => {
+ void retried(() => this.resolve(app, rules, refs)).then((resolved) => {
if (gens.built_.get(entity) !== built) return;
built.rules = resolved;
this.plan(app, gens, entity, built, resolved);
@@ -399,9 +417,14 @@ export class WorldGenPlugin implements Plugin {
});
built.plan = new WorldPlan(rules, env, zones, data.seed, data.world);
const plan = built.plan;
+ const sparse = rules.layers.some((l) => (l.farSpacing ?? 1) > 1);
+ built.farPlan = sparse
+ ? new WorldPlan({ ...rules, layers: rules.layers.map((l) => (l.farSpacing ?? 1) > 1 ? { ...l, spacing: l.spacing * l.farSpacing! } : l) }, env, zones, data.seed, data.world)
+ : null;
// A zone that changes, or a placement a player changes, makes again only the chunks it reaches.
zones.onChange = (bounds, zone) => {
plan.invalidate();
+ built.farPlan?.invalidate();
const chunks = chunksOf(app);
for (const l of rules.layers) {
// A group kept out lets a neighbour it had beaten stand, which may beat its own: a few cells round are made again.
@@ -483,7 +506,7 @@ export class WorldGenPlugin implements Plugin {
const water = waterOf(app);
// What the plan read the ground and the water from: when either changes everything is read again.
const ground = `${terrains?.revision_ ?? 0}:${water?.revision_ ?? 0}`;
- if (ground !== built.ground) { plan.invalidate(); built.ground = ground; }
+ if (ground !== built.ground) { plan.invalidate(); built.farPlan?.invalidate(); built.ground = ground; }
const waiting = !!terrains?.loading || !!water?.baking;
if (terrains) {
for (const id of [...built.levelling]) {
@@ -534,7 +557,8 @@ export class WorldGenPlugin implements Plugin {
const x0 = cx * fsize, z0 = cz * fsize;
if (waiting || (terrains && ![[x0, z0], [x0 + fsize, z0], [x0, z0 + fsize], [x0 + fsize, z0 + fsize]].every(([x, z]) => terrains.groundKnownAt(x!, z!)))) return null;
if (!built.plantsReady) return null;
- return this.chunk(app, plan, diffs, layer, x0, z0, fsize, rendering, built.plants, true);
+ const sparse = (layer.farSpacing ?? 1) > 1 && built.farPlan;
+ return this.chunk(app, sparse ? built.farPlan! : plan, diffs, layer, x0, z0, fsize, rendering, built.plants, true, sparse ? layer.farSpacing! ** 2 : 1);
},
publish: (_cx, _cz, value) => this.place(app, gens, entity, value),
release: (_cx, _cz, value) => this.unplace(app, gens, value),
@@ -544,7 +568,7 @@ export class WorldGenPlugin implements Plugin {
/** What one chunk of a layer places: its decoration merged by mesh, and its interactive placements, with the changes laid over. */
private chunk(app: App, plan: WorldPlan, diffs: PlacementDiffs, layer: PlacementLayer, x0: number, z0: number, size: number,
- rendering: boolean, plants: PlantSet | null, far = false): PlacedChunk | Promise<PlacedChunk> {
+ rendering: boolean, plants: PlantSet | null, far = false, thinnedBy = 1): PlacedChunk | Promise<PlacedChunk> {
const placements: Placement[] = [];
for (const p of plan.placementsIn(x0, z0, x0 + size, z0 + size, [layer.id])) {
if (diffs.isRemoved(p.id)) continue;
@@ -555,7 +579,7 @@ export class WorldGenPlugin implements Plugin {
const decor = rendering && !far ? placements.filter((p) => p.interactive === null && p.mesh) : [];
const meshes = [...new Set(decor.map((p) => p.mesh))];
const finish = (): PlacedChunk => {
- const out: PlacedChunk = { decor: [], objects, planted: null, at: [x0 + size / 2, 0, z0 + size / 2], side: size, grown: null, far, entities: [], meshes: [] };
+ const out: PlacedChunk = { decor: [], objects, planted: null, at: [x0 + size / 2, 0, z0 + size / 2], side: size, grown: null, far, thinnedBy, entities: [], meshes: [] };
// The plants: each at its kind (its colouring there), relative to the chunk's centre, sunk by what its kind says.
if (plants && rendering) {
const by = new Map<number, Plant[]>();
@@ -629,7 +653,7 @@ export class WorldGenPlugin implements Plugin {
chunk.entities.push(e);
chunk.grown = { entity: e, handles: [], dead: false };
const growth = plantGrowthOf(app);
- if (chunk.far) growth.growFar(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted, { x: chunk.at[0], z: chunk.at[2], half: chunk.side / 2 });
+ if (chunk.far) growth.growFar(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted, { x: chunk.at[0], z: chunk.at[2], half: chunk.side / 2 }, chunk.thinnedBy);
else growth.growCell(app, chunk.grown, built.plants.kinds, built.plantsReady, chunk.planted);
}
for (const d of chunk.decor) {
diff --git a/sdk/tests/foliage-builder.test.ts b/sdk/tests/foliage-builder.test.ts
index cb6c2a755..24606c1b2 100644
--- a/sdk/tests/foliage-builder.test.ts
+++ b/sdk/tests/foliage-builder.test.ts
@@ -259,5 +259,13 @@ describe('thinning plants for a far version', () => {
expect(thinPlants(plants, 0.05)[0]!.scale).toBe(2);
expect(plants[0]!.scale).toBe(1);
});
-});
+ it('does not thin again what was planned thinner already, and still grows them for the share kept', () => {
+ // A quarter kept, planned four times thinner: every plant is kept, grown as a quarter's would be.
+ const planned = thinPlants(plants, 0.25, 4);
+ expect(planned.map((p) => p.x)).toEqual(plants.map((p) => p.x));
+ expect(planned[0]!.scale).toBeCloseTo(2);
+ // Planned twice as thin, a quarter wanted: every second of what is left.
+ expect(thinPlants(plants, 0.25, 2).map((p) => p.x)).toEqual([0, 2, 4, 6, 8, 10]);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index eeed745e4..05e0c73b7 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2910,6 +2910,8 @@ export const NOTED = {
{"note":"Placed plants cast shadows only as far as twice their detailed distance."},
"feat(render): a quality level sets how far plants keep their detail":
{"note":"A quality level sets how far plants keep their detail."},
+ "feat(worldgen): a layer plans the far versions of its plants sparsely, and a failed asset load is tried again":
+ {"note":"A far world is planned sparsely, and a failed asset load is tried again."},
"feat(assets): a project names folders its asset database leaves alone":
{"note":"A project can keep folders out of its asset database."},
"feat(worldgen): a plant part may cast no shadow, and far cells are capped at two cells wide":