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(render): a MeshInstances component draws one mesh at many places, and plants are grown as instances of it

yhh9649578c478c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84edd17e1..f698676e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **Plants are instances of one mesh.** A generated world's and a `PlacedFoliage`'s plants no longer merge their vertices a cell at a time: a new `MeshInstances` component places one resident mesh at many places (sixty-four bytes a plant), and the engine culls each plant against the view, takes a cheaper mesh past a distance and draws none past another, as one instanced draw that cells sharing a mesh and a material merge into. The geometry exists once however many plants there are, so a planet's plants take a tenth of the memory and a fraction of the draws, and a cell is grown in microseconds instead of a few milliseconds.
- **A project can keep folders out of its asset database.** `assetExclude` in the project manifest names folders (a source-art repository, docs, a server) the asset scan does not index, does not write a `.meta` into and the editor does not watch.
- **Small plants need not cast a shadow.** A plant part takes `castShadows: false`, so ground cover too small to be worth a shadow-map draw is left out of the shadow pass.
- **A project plugin that needs trust says so.** Opening a project whose editor plugin has not been trusted shows a notice with a way to review it, instead of leaving its missing pieces (a ground that is not drawn) unexplained.
diff --git a/docs/astro/src/content/docs/graphics/foliage.mdx b/docs/astro/src/content/docs/graphics/foliage.mdx
index 6055eb6c2..b4aaa5aa9 100644
--- a/docs/astro/src/content/docs/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/graphics/foliage.mdx
@@ -57,12 +57,14 @@ transform, a renderer and a draw each. **`PlacedFoliage`** keeps them as data in
| `kinds` | What each kind is made of: its `parts` (a `mesh`, a cheaper `lod1Mesh`, a `material`, a `texture`, a `tint` and whether it is `opaque`), the `lodDistance` past which the cheaper mesh stands in and the `drawDistance` past which it is not drawn, and a far version, `far` parts drawn from `drawDistance` out to `farDistance`. |
| `records` | Where each plant stands: six numbers a plant, the kind's index, x, y, z in the entity's space, the turn about the vertical in radians, and the scale. |
-The cells round the streaming sources (or the eye) are grown, each as one mesh for every kind in it and part of that kind, and let go with their meshes past the
-distance. A cell appears at once and fills in over the frames after it, each mesh a few milliseconds of the frame's budget, nearest first. A mesh keeps every channel
-the artist made (a normal map, a second uv, a vertex colour); nothing is painted over it, so a plant is drawn with an ordinary material, not the wind's.
-
-The far version is the hierarchical level of detail: a tree's crossed cards, baked to an atlas of their own, merged a cell at a time, shown where the eye is past
-what the kind draws as itself. It is cheap enough that the whole area stands at once. A kind with no far version is not drawn past `drawDistance`.
+The cells round the streaming sources (or the eye) are grown and let go past the distance. A cell appears at once and fills in over the frames after it, each kind
+and part of it a few microseconds of the frame's budget, nearest first. Each part is one entity that draws the part's mesh, shared by every cell, at every place a plant
+stands: a **`MeshInstances`** component holds the places (sixty-four bytes a plant) and the engine culls each plant against the view, takes the cheaper mesh for the plants
+past `lodDistance` and none past `drawDistance`. The geometry exists once however many plants there are, and draws that share a mesh and a material are one draw. A mesh
+keeps every channel the artist made (a normal map, a second uv, a vertex colour); nothing is painted over it, so a plant is drawn with an ordinary material, not the wind's.
+
+The far version is the hierarchical level of detail: a tree's crossed cards, baked to an atlas of their own, a set of placements like the plants themselves that is drawn
+from `drawDistance` out to `farDistance` from the eye. It is cheap enough that the whole area stands at once. A kind with no far version is not drawn past `drawDistance`.
A kind with no cards of its own can use its cheaper mesh as its far version and set `farKeep`, the share of its plants the far version draws (above 0 to 1):
every n-th is kept, n the nearest whole number to 1 / `farKeep`, each grown by the square root of n (at most twofold) so the ground they cover is what it was.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
index 14b182239..3b8188111 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/foliage.mdx
@@ -43,9 +43,9 @@ description: 一个 Foliage 组件,把草或网格散布到一片区域或地形
| `kinds` | 每种植物由什么组成:`parts` 部件(`mesh` 网格、更省的 `lod1Mesh`、`material` 材质、`texture` 贴图、`tint` 色调、是否 `opaque`);超过 `lodDistance` 换成更省的网格,超过 `drawDistance` 不再绘制;以及远景版本 `far` 部件,从 `drawDistance` 一直画到 `farDistance`。 |
| `records` | 每棵植物的位置:每棵六个数,种类序号、x、y、z(在实体空间里)、绕竖直轴的转角(弧度)、缩放。 |
-镜头(或流式加载源)周围的格子会被生长出来,每格里每种植物的每个部件合成一个网格,离开距离就连同网格一起释放。格子会立刻出现,之后的几帧里逐步填满:每个网格只占帧预算里的几毫秒,由近到远。网格保留美术做的所有通道(法线贴图、第二套 uv、顶点色),不会被覆盖,所以植物用普通材质绘制,而不是带风的材质。
+镜头(或流式加载源)周围的格子会被生长出来,离开距离就释放。格子会立刻出现,之后的几帧里逐步填满:每个种类的每个部件占帧预算里很小一块,由近到远。每个部件是一个实体,画的是该部件的网格(所有格子共用这一份),摆在每棵植物所在的位置:**`MeshInstances`** 组件存着这些位置(每棵 64 字节),引擎逐棵按视野剔除,超过 `lodDistance` 的用更省的网格,超过 `drawDistance` 的不画。几何体不论多少棵都只有一份,网格和材质相同的绘制合成一次。网格保留美术做的所有通道(法线贴图、第二套 uv、顶点色),不会被覆盖,所以植物用普通材质绘制,而不是带风的材质。
-远景版本就是层级细节(HLOD):树的交叉卡片烘到自己的图集上,按格子合并,镜头比该种类自身的绘制距离更远时显示。它便宜到整个区域可以一次全部长出。没有远景版本的种类,超过 `drawDistance` 就不画。
+远景版本就是层级细节(HLOD):树的交叉卡片烘到自己的图集上,和植物本身一样是一组摆放位置,从 `drawDistance` 起画到离镜头 `farDistance`。它便宜到整个区域可以一次全部长出。没有远景版本的种类,超过 `drawDistance` 就不画。
没有自己卡片的种类可以拿更省的网格当远景版本,并设置 `farKeep`:远景版本画多少比例的植物(大于 0 到 1)。每 n 棵保留一棵,n 取最接近 1 / `farKeep` 的整数,保留下来的放大到原来的 n 的平方根倍(最多两倍),覆盖的地面面积不变。这样远处的地被只花近处一个比例的代价,其余由地面自己的纹理承担。
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 4772f3ef7..8cec11e4c 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; }) => void
made: number
pending: number
queue: { cell: GrownCell; run: () => void; }[]
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 52d411340..486ad4540 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 115 public · 159 beta · 1843 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"7cf803aca319cd32"
+"91648bb4a306e016"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 36c743bcc..fdf3bcfac 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 115 public · 164 beta · 1862 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"7cf803aca319cd32"
+"91648bb4a306e016"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 95c358bb5..325716d70 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -33,6 +33,7 @@ addLODGroup: (entity: Entity, component: LODGroup) => void
addLight: (entity: Entity, component: Light) => void
addLightProbeVolume: (entity: Entity, component: LightProbeVolume) => void
addMeshCollider3D: (entity: Entity, component: MeshCollider3D) => void
+addMeshInstances: (entity: Entity, component: MeshInstances) => void
addMeshLightmap: (entity: Entity, component: MeshLightmap) => void
addMeshMorph: (entity: Entity, component: MeshMorph) => void
addMeshRenderer: (entity: Entity, component: MeshRenderer) => void
@@ -90,6 +91,7 @@ getLODGroup: (entity: Entity) => LODGroup
getLight: (entity: Entity) => Light
getLightProbeVolume: (entity: Entity) => LightProbeVolume
getMeshCollider3D: (entity: Entity) => MeshCollider3D
+getMeshInstances: (entity: Entity) => MeshInstances
getMeshLightmap: (entity: Entity) => MeshLightmap
getMeshMorph: (entity: Entity) => MeshMorph
getMeshRenderer: (entity: Entity) => MeshRenderer
@@ -141,6 +143,7 @@ hasLODGroup: (entity: Entity) => boolean
hasLight: (entity: Entity) => boolean
hasLightProbeVolume: (entity: Entity) => boolean
hasMeshCollider3D: (entity: Entity) => boolean
+hasMeshInstances: (entity: Entity) => boolean
hasMeshLightmap: (entity: Entity) => boolean
hasMeshMorph: (entity: Entity) => boolean
hasMeshRenderer: (entity: Entity) => boolean
@@ -195,6 +198,7 @@ removeLODGroup: (entity: Entity) => void
removeLight: (entity: Entity) => void
removeLightProbeVolume: (entity: Entity) => void
removeMeshCollider3D: (entity: Entity) => void
+removeMeshInstances: (entity: Entity) => void
removeMeshLightmap: (entity: Entity) => void
removeMeshMorph: (entity: Entity) => void
removeMeshRenderer: (entity: Entity) => void
@@ -366,6 +370,7 @@ material_define: (materialId: number, shaderHandle: number, blendMode: number, f
material_setTexture: (materialId: number, name: string, textureHandle: number) => void
material_setUniform: (materialId: number, name: string, arity: number, v0: number, v1: number, v2: number, v3: number) => void
material_undefine: (materialId: number) => void
+meshInstances_set: ((registry: CppRegistry, entity: number, dataPtr: number, count: number) => void) | undefined
meshRenderer_localBounds: ((registry: CppRegistry, entity: number) => { minX: number; minY: number; maxX: number; maxY: number; } | null) | undefined
meshRenderer_makeAllResident: ((registry: CppRegistry) => number) | undefined
meshRenderer_setGeometry: ((registry: CppRegistry, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number) => void) | undefined
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 114e69570..b4c524e04 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -76,6 +76,7 @@ export interface NativeEngineApi {
material_setTexture?(materialId: number, name: string, textureHandle: number): void;
material_setUniform?(materialId: number, name: string, arity: number, v0: number, v1: number, v2: number, v3: number): void;
material_undefine?(materialId: number): void;
+ meshInstances_set?(registry: unknown, entity: number, dataPtr: number, count: number): void;
meshRenderer_makeAllResident?(registry: unknown): number;
meshRenderer_setGeometry?(registry: unknown, entity: number, posUvPtr: number, vertexCount: number, colorsPtr: number, indicesPtr: number, indexCount: number): void;
meshRenderer_setMaterialAll?(registry: unknown, materialId: number): number;
@@ -400,6 +401,7 @@ export function createNativeEngineApi(
bind('material_setTexture', 'es_material_setTexture', false);
bind('material_setUniform', 'es_material_setUniform', false);
bind('material_undefine', 'es_material_undefine', false);
+ bind('meshInstances_set', 'es_meshInstances_set', true);
bind('meshRenderer_makeAllResident', 'es_meshRenderer_makeAllResident', true);
bind('meshRenderer_setGeometry', 'es_meshRenderer_setGeometry', true);
bind('meshRenderer_setMaterialAll', 'es_meshRenderer_setMaterialAll', true);
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 70a252372..eb8947c6f 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -993,6 +993,42 @@ export function createMeshCollider3DData(): MeshCollider3DPtrData {
};
}
+export interface MeshInstancesPtrData {
+ lod1Mesh: number;
+ lodDistance: number;
+ minDistance: number;
+ drawDistance: number;
+}
+
+export function fillMeshInstances(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: MeshInstancesPtrData,
+): void {
+ out.lod1Mesh = u32[ptr >> 2];
+ out.lodDistance = f32[(ptr + 4) >> 2];
+ out.minDistance = f32[(ptr + 8) >> 2];
+ out.drawDistance = f32[(ptr + 12) >> 2];
+}
+
+export function writeMeshInstances(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: MeshInstancesPtrData,
+): void {
+ u32[ptr >> 2] = data.lod1Mesh;
+ f32[(ptr + 4) >> 2] = data.lodDistance;
+ f32[(ptr + 8) >> 2] = data.minDistance;
+ f32[(ptr + 12) >> 2] = data.drawDistance;
+}
+
+export function createMeshInstancesData(): MeshInstancesPtrData {
+ return {
+ lod1Mesh: 0,
+ lodDistance: 0,
+ minDistance: 0,
+ drawDistance: 0,
+ };
+}
+
export interface MeshLightmapPtrData {
lightmap: number;
scaleOffset: Vec4;
@@ -2670,6 +2706,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
Light: { fill: fillLight, write: writeLight, create: createLightData },
LightProbeVolume: { fill: fillLightProbeVolume, write: writeLightProbeVolume, create: createLightProbeVolumeData },
MeshCollider3D: { fill: fillMeshCollider3D, write: writeMeshCollider3D, create: createMeshCollider3DData },
+ MeshInstances: { fill: fillMeshInstances, write: writeMeshInstances, create: createMeshInstancesData },
MeshLightmap: { fill: fillMeshLightmap, write: writeMeshLightmap, create: createMeshLightmapData },
MeshRenderer: { fill: fillMeshRenderer, write: writeMeshRenderer, create: createMeshRendererData },
Occluder: { fill: fillOccluder, write: writeOccluder, create: createOccluderData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 839a52ed4..a81370d95 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '7cf803aca319cd32';
+export const ABI_LAYOUT_HASH = '91648bb4a306e016';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -552,6 +552,24 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
layer: { min: 0, max: 15, advanced: true },
},
},
+ MeshInstances: {
+ defaults: {
+ lod1Mesh: 0,
+ lodDistance: 0,
+ minDistance: 0,
+ drawDistance: 0,
+ },
+ assetFields: [{ field: 'lod1Mesh', type: 'mesh' as AssetFieldType }],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ lod1Mesh: { tooltip: "The cheaper mesh used past the LOD distance. Needs the same channels as the mesh." },
+ lodDistance: { tooltip: "Distance (metres) past which the cheaper mesh is used. 0 = never." },
+ minDistance: { tooltip: "Distance (metres) nearer than which an instance is not drawn. 0 = from the eye." },
+ drawDistance: { tooltip: "Distance (metres) past which an instance is not drawn. 0 = unlimited." },
+ },
+ },
MeshLightmap: {
defaults: {
lightmap: 0,
@@ -1582,6 +1600,13 @@ export interface MeshCollider3DData {
enabled: boolean;
}
+export interface MeshInstancesData {
+ lod1Mesh: number;
+ lodDistance: number;
+ minDistance: number;
+ drawDistance: number;
+}
+
export interface MeshLightmapData {
lightmap: number;
scaleOffset: Vec4;
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index 4ea1a6930..9c83ddab8 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -299,6 +299,37 @@ export function buildPlacedMesh(source: MeshData, plants: readonly Plant[]): Mes
return { channels: source.channels, vertexStride: stride, vertexCount: count * plants.length, vertices, indices, aabbMin: min, aabbMax: max };
}
+/** Floats a placement takes in the engine's `MeshInstances`: three rows of a model matrix (translation last), then a tint. */
+export const PLACEMENT_FLOATS = 16;
+
+/**
+ * Where each plant stands, as the placements of a `MeshInstances`: the same turn about the vertical, scale, lean with the ground and position that
+ * buildPlacedMesh bakes into vertices, left as a matrix for the engine to apply to the one mesh every plant of the kind shares. `tint` is
+ * multiplied into the renderer's colour per plant.
+ */
+export function buildPlacements(plants: readonly Plant[]): Float32Array {
+ const out = new Float32Array(plants.length * PLACEMENT_FLOATS);
+ const column = [0, 0, 0];
+ plants.forEach((plant, n) => {
+ const cos = Math.cos(plant.yaw), sin = Math.sin(plant.yaw), scale = plant.scale;
+ const lean = plant.up ? leanTo(plant.up) : null;
+ const at = n * PLACEMENT_FLOATS;
+ // The columns of the turn about the vertical, (cos, 0, -sin), (0, 1, 0) and (sin, 0, cos), each leant and scaled; the rows are written across them.
+ for (let c = 0; c < 3; c++) {
+ column[0] = c === 0 ? cos : c === 2 ? sin : 0;
+ column[1] = c === 1 ? 1 : 0;
+ column[2] = c === 0 ? -sin : c === 2 ? cos : 0;
+ if (lean) lean(column);
+ for (let row = 0; row < 3; row++) out[at + row * 4 + c] = column[row]! * scale;
+ }
+ out[at + 3] = plant.x;
+ out[at + 7] = plant.y;
+ out[at + 11] = plant.z;
+ out[at + 12] = out[at + 13] = out[at + 14] = out[at + 15] = 1;
+ });
+ return out;
+}
+
/**
* The mesh with its normals turned toward up by `amount` (0 leaves them, 1 makes them all up): a card that stands for a crown lit as a rounded thing
* rather than as the flat it is. A copy; the source is shared by every plant of the kind.
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
index 0a5406c73..b5c2992dd 100644
--- a/sdk/src/foliage/plantGrowth.ts
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -4,68 +4,67 @@
* @file plantGrowth.ts
* @brief Growing plants a cell at a time inside the frame's budget: what `PlacedFoliage` and a generated world's plants share.
*
- * @details A cell is an entity that stands at once, empty, and fills in over the frames after it: every kind in it and every part of that kind is
- * one mesh (a batch of plants no bigger than a few milliseconds of work), made from the plants' own meshes with every channel kept (see
- * buildPlacedMesh). Past the kind's distance a cheaper mesh stands in (a `LODGroup`), and past that its far version (a tree's crossed
- * cards, merged a cell at a time) is shown where the eye is: the hierarchical level of detail. The pieces wait in one queue for the whole
- * app and are made while the frame's budget lasts, nearest asked first; a cell let go first leaves its pieces unmade.
- *
- * The thresholds are made from the sphere of each piece's own mesh, as the engine measures a renderer, and not from the cell's: a tree's crown
- * and its trunk have spheres of their own, and a cell's radius would hand over, and cull, a third as far as the kind says.
+ * @details A cell is an entity that stands at once, empty, and fills in over the frames after it. Every kind in it and every part of that kind is
+ * ONE entity holding where each plant stands (`MeshInstances`), drawing the part's mesh, which every cell shares: the geometry exists
+ * once however many plants there are, a plant costs sixty-four bytes, and the engine culls each plant against the view and picks its
+ * mesh by its distance (the part's cheaper mesh past the kind's `lodDistance`, nothing past `drawDistance`). The far version (a tree's
+ * crossed cards) is the same, a set of its own that begins where the kind ends: the hierarchical level of detail, with nothing on this
+ * side choosing between the two. Draws that share a mesh and a material are one draw in the engine, so a forest of cells is a few.
+ * The pieces wait in one queue for the whole app and are made while the frame's budget lasts, nearest asked first; a cell let go
+ * first leaves its pieces unmade.
*/
import type { App } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
import { defineResource } from '../ecs/resource';
-import {
- Camera, getComponent, MeshRenderer, RuntimeOnly, Transform,
- type CameraData, type MeshRendererData, type TransformData,
-} from '../ecs/component';
+import { getComponent, MeshRenderer, RuntimeOnly, Transform, type MeshRendererData } from '../ecs/component';
+import { engineApi } from '../ecs/bridge/engineApi';
+import type { CppRegistry } from '../wasm';
+import { withScratch } from '../wasm/wasmScratch';
import { Assets } from '../asset/AssetPlugin';
import type { Assets as AssetsApi } from '../asset/Assets';
-import type { MeshData } from '../asset/meshFormat';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Entity } from '../types';
-import { buildPlacedMesh, softenNormals, thinPlants, type Plant } from './builder';
+import { buildPlacements, PLACEMENT_FLOATS, softenNormals, thinPlants, type Plant } from './builder';
import type { PlacedKind, PlacedPart } from './plantKind';
-/** A part with what it needs in hand: its geometry read, its handles made. */
-export interface ReadyPart { part: PlacedPart; source: MeshData; lod1: MeshData | null; material: number; texture: number }
+/** A part with what it needs in hand: the handles of its meshes (shared by every cell) and of its material and texture. */
+export interface ReadyPart { part: PlacedPart; mesh: number; lod1: number; material: number; texture: number }
-/** Every kind's parts in hand, and the parts that stand for each far off. */
-export interface ReadyKinds { kinds: ReadyPart[][]; far: ReadyPart[][] }
+/** Every kind's parts in hand, and the parts that stand for each far off; `owned` are the meshes made here, which `releaseKinds` gives back. */
+export interface ReadyKinds { kinds: ReadyPart[][]; far: ReadyPart[][]; owned: number[] }
-/** One grown cell: its entity (none where nothing stands), the meshes it owns so far, and whether it has been let go. */
+/** One grown cell: its entity (none where nothing stands), what it owns so far, and whether it has been let go. */
export interface GrownCell { entity: Entity | null; handles: number[]; dead: boolean }
-/** The most vertices one mesh of a cell takes: a piece of work of a few milliseconds, which a frame's budget can fit between others. */
-const BATCH_VERTICES = 24000;
-
-interface FarCell {
- /** Where the cell is, in the world's x and z. */
- x: number;
- z: number;
- /** Half the cell's side: how far from its centre it reaches. */
- half: number;
- owner: Entity;
- kinds: readonly PlacedKind[];
- children: { entity: Entity; kind: number; shown: boolean }[];
-}
-
-/** Reads the geometry and makes the handles of every part of every kind. */
+/**
+ * Loads the meshes, materials and textures of every part of every kind, once. A part whose normals are turned toward up (`soft`) is a mesh of its own,
+ * made here, and a part whose geometry cannot be read is left out.
+ */
export async function prepareKinds(assets: AssetsApi, kinds: readonly PlacedKind[]): Promise<ReadyKinds> {
+ const owned: number[] = [];
+ const handleOf = async (path: string, soft: number): Promise<number> => {
+ const loaded = (await assets.load<{ handle: number }>('mesh', path)).handle;
+ if (!soft) return loaded;
+ const source = await assets.readMeshData(loaded);
+ const made = source ? assets.createMesh(softenNormals(source, soft)) : 0;
+ if (made === 0) return loaded;
+ owned.push(made);
+ return made;
+ };
const ready = async (part: PlacedPart, withLod: boolean): Promise<ReadyPart | null> => {
- const source = await assets.readMeshData((await assets.load<{ handle: number }>('mesh', part.mesh)).handle);
- if (!source) { log.warn('foliage', `the geometry of ${part.mesh} cannot be read, so its plants are left out`); return null; }
- let lod1: MeshData | null = null;
- if (withLod && part.lod1Mesh) lod1 = await assets.readMeshData((await assets.load<{ handle: number }>('mesh', part.lod1Mesh)).handle);
+ let mesh = 0;
+ try { mesh = await handleOf(part.mesh, part.soft ?? 0); } catch { mesh = 0; }
+ if (mesh === 0) { log.warn('foliage', `the geometry of ${part.mesh} cannot be read, so its plants are left out`); return null; }
+ let lod1 = 0;
+ if (withLod && part.lod1Mesh) { try { lod1 = await handleOf(part.lod1Mesh, part.soft ?? 0); } catch { lod1 = 0; } }
return {
- part, source: part.soft ? softenNormals(source, part.soft) : source, lod1,
+ part, mesh, lod1,
material: part.material ? (await assets.loadMaterial(part.material)).handle : 0,
texture: part.texture ? (await assets.loadTexture(part.texture)).handle : 0,
};
};
- const out: ReadyKinds = { kinds: [], far: [] };
+ const out: ReadyKinds = { kinds: [], far: [], owned };
for (const kind of kinds) {
const parts: ReadyPart[] = [], far: ReadyPart[] = [];
for (const part of kind.parts) { const r = await ready(part, true); if (r) parts.push(r); }
@@ -76,151 +75,102 @@ export async function prepareKinds(assets: AssetsApi, kinds: readonly PlacedKind
return out;
}
-/** The growth of every plant in an app: the pieces waiting, and the far cells standing. */
+/** Gives back the meshes `prepareKinds` made; the ones it only loaded stay with the asset system. */
+export function releaseKinds(assets: AssetsApi, ready: ReadyKinds): void {
+ for (const handle of ready.owned) assets.releaseBuiltMesh(handle);
+ ready.owned.length = 0;
+}
+
+/** The growth of every plant in an app: the pieces waiting. */
export class PlantGrowth {
/** The pieces not yet made, in the order they were asked. */
readonly queue: { cell: GrownCell; run: () => void }[] = [];
- private readonly far_ = new Set<FarCell>();
app_: App | null = null;
- /** How many meshes are still waiting to be made. */
+ /** How many pieces are still waiting to be made. */
get pending(): number { return this.queue.length; }
/** Pieces made so far, and the milliseconds spent making them: what the growth has cost, for a profile to read. */
made = 0;
spentMs = 0;
+ /**
+ * Makes one entity under `parent` that draws `part`'s mesh at every place in `plants`, relative to `parent`. `from` and `to` are the distances
+ * from the eye between which a plant is drawn (0 for no limit); `lod` is the distance past which the part's cheaper mesh stands in.
+ */
+ private place(app: App, parent: Entity, name: string, part: ReadyPart, plants: readonly Plant[], lod: number, from: number, to: number): void {
+ const world = app.world;
+ const e = world.spawn(name);
+ world.insert(e, RuntimeOnly);
+ world.insert(e, Transform, {});
+ world.insert(e, MeshRenderer, {
+ mesh: part.mesh, material: part.material, texture: part.texture, lit: true, opaque: part.part.opaque !== false, cullBackfaces: false,
+ castShadows: part.part.castShadows !== false,
+ color: { r: part.part.tint[0], g: part.part.tint[1], b: part.part.tint[2], a: part.part.tint[3] },
+ } as Partial<MeshRendererData>);
+ const placements = getComponent('MeshInstances');
+ if (placements) world.insert(e, placements, { lod1Mesh: part.lod1, lodDistance: part.lod1 ? lod : 0, minDistance: from, drawDistance: to });
+ world.setParent(e, parent);
+ const api = engineApi(app);
+ const set = api?.meshInstances_set;
+ if (!set || !api._malloc || !api._free || !api.HEAPU8 || plants.length === 0) return;
+ const data = buildPlacements(plants);
+ const registry = world.getCppRegistry() as CppRegistry;
+ withScratch({ _malloc: api._malloc, _free: api._free }, (alloc) => {
+ const ptr = alloc(data.byteLength);
+ // Read after the allocation: it may have grown the memory, which replaces the buffer.
+ new Float32Array(api.HEAPU8!.buffer, ptr, data.length).set(data);
+ set(registry, e, ptr, data.length / PLACEMENT_FLOATS);
+ });
+ }
+
/**
* Grows `cell`, whose entity the caller has made and stands at the cell's centre: the plants of each kind in `byKind` (relative to that centre),
- * as pieces of work. `side` is the cell's side, for where the far version is shown from.
+ * a piece of work a kind's part.
*/
growCell(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>): void {
const world = app.world, entity = cell.entity;
if (entity === null) return;
- const assets = app.getResource(Assets);
- const lodDef = getComponent('LODGroup');
- const sphereOf = (m: MeshData): number => 0.5 * Math.hypot(m.aabbMax[0] - m.aabbMin[0], m.aabbMax[1] - m.aabbMin[1], m.aabbMax[2] - m.aabbMin[2]);
- const sizeAt = (radius: number, distance: number): number => radius / (Math.max(1, distance) * 0.577);
- const made = (mesh: MeshData): number => {
- const handle = assets.createMesh(mesh);
- if (handle === 0) throw new Error('the engine refused the geometry of a cell of plants');
- cell.handles.push(handle);
- return handle;
- };
for (const [kindIndex, plants] of byKind) {
const kind = kinds[kindIndex], parts = ready.kinds[kindIndex];
if (!kind || !parts) continue;
parts.forEach((r, j) => {
- const per = Math.max(1, Math.floor(BATCH_VERTICES / Math.max(1, r.source.vertexCount)));
- for (let from = 0; from < plants.length; from += per) {
- const batch = plants.slice(from, from + per);
- this.queue.push({ cell, run: () => {
- if (!world.valid(entity)) return;
- try {
- const near = buildPlacedMesh(r.source, batch);
- const e = world.spawn(`${kindIndex}:${j}`);
- world.insert(e, RuntimeOnly);
- world.insert(e, Transform, {});
- world.insert(e, MeshRenderer, {
- mesh: made(near), material: r.material, texture: r.texture, lit: true, opaque: r.part.opaque !== false, cullBackfaces: false, castShadows: r.part.castShadows !== false,
- color: { r: r.part.tint[0], g: r.part.tint[1], b: r.part.tint[2], a: r.part.tint[3] },
- } as Partial<MeshRendererData>);
- if (lodDef) {
- const coarse = r.lod1 ? buildPlacedMesh(r.lod1, batch) : null;
- const far = coarse ? made(coarse) : 0;
- // The engine's bounds for the group are the union of its levels, so the sphere is the union's.
- const radius = sphereOf(coarse ? {
- ...near,
- aabbMin: near.aabbMin.map((v, i) => Math.min(v, coarse.aabbMin[i]!)) as [number, number, number],
- aabbMax: near.aabbMax.map((v, i) => Math.max(v, coarse.aabbMax[i]!)) as [number, number, number],
- } : near);
- world.insert(e, lodDef, {
- lod1: far, lod2: 0, lod3: 0, lod1Size: far ? sizeAt(radius, kind.lodDistance) : 0, lod2Size: 0, lod3Size: 0,
- cullSize: sizeAt(radius, kind.drawDistance + radius), hysteresis: 0.1, enabled: true,
- });
- }
- world.setParent(e, entity);
- } catch (error) {
- log.error('foliage', 'growing a piece of a cell of plants failed', error);
- }
- } });
- }
+ this.queue.push({ cell, run: () => {
+ if (!world.valid(entity)) return;
+ try {
+ this.place(app, entity, `${kindIndex}:${j}`, r, plants, kind.lodDistance, 0, kind.drawDistance);
+ } catch (error) {
+ log.error('foliage', 'growing a piece of a cell of plants failed', error);
+ }
+ } });
});
}
}
/**
- * Grows the far version of `cell`: each kind with one, its plants as one mesh a far part, hidden until the eye is far enough (`kind.drawDistance`
- * to `kind.farDistance` from the cell, at world x and z `at`, reaching `half` each way). Cheap enough (a tree is two cards) to be made at once.
+ * 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.
*/
- growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, at: { x: number; z: number; half?: number }): void {
- const world = app.world, entity = cell.entity;
+ growFar(app: App, cell: GrownCell, kinds: readonly PlacedKind[], ready: ReadyKinds, byKind: ReadonlyMap<number, readonly Plant[]>, _at?: { x: number; z: number; half?: number }): void {
+ const entity = cell.entity;
if (entity === null) return;
- const assets = app.getResource(Assets);
- const children: FarCell['children'] = [];
for (const [kindIndex, plants] of byKind) {
- const parts = ready.far[kindIndex];
- if (!parts || parts.length === 0) continue;
- const kept = thinPlants(plants, kinds[kindIndex]?.farKeep ?? 1);
- for (const r of parts) {
- const handle = assets.createMesh(buildPlacedMesh(r.source, kept));
- if (handle === 0) continue;
- cell.handles.push(handle);
- const e = world.spawn(`far ${kindIndex}`);
- world.insert(e, RuntimeOnly);
- world.insert(e, Transform, {});
- world.insert(e, MeshRenderer, {
- mesh: handle, material: r.material, texture: r.texture, lit: true, opaque: r.part.opaque !== false, cullBackfaces: false, castShadows: r.part.castShadows !== false, enabled: false,
- color: { r: r.part.tint[0], g: r.part.tint[1], b: r.part.tint[2], a: r.part.tint[3] },
- } as Partial<MeshRendererData>);
- world.setParent(e, entity);
- children.push({ entity: e, kind: kindIndex, shown: false });
- }
+ const parts = ready.far[kindIndex], kind = kinds[kindIndex];
+ if (!kind || !parts || parts.length === 0) continue;
+ const kept = thinPlants(plants, kind.farKeep ?? 1);
+ for (const r of parts) this.place(app, entity, `far ${kindIndex}`, r, kept, 0, kind.drawDistance, kind.farDistance);
}
- if (children.length > 0) this.far_.add({ x: at.x, z: at.z, half: at.half ?? 0, owner: entity, kinds, children });
}
- /** Lets a cell go: what it made is despawned and given back, and what it had not yet made is left unmade. */
+ /** Lets a cell go: what it made is despawned, and what it had not yet made is left unmade. */
release(app: App, cell: GrownCell): void {
cell.dead = true;
- for (const f of this.far_) if (f.owner === cell.entity) this.far_.delete(f);
if (cell.entity !== null && app.world.valid(cell.entity)) app.world.despawn(cell.entity);
- const assets = app.getResource(Assets);
- for (const handle of cell.handles) assets.releaseBuiltMesh(handle);
cell.handles.length = 0;
}
- /** Shows a far part where the eye is past what its kind draws as itself, and hides it nearer and further. */
- private showFar(app: App): void {
- if (this.far_.size === 0) return;
- const world = app.world;
- let eye: { x: number; z: number } | null = null;
- for (const e of world.getEntitiesWithComponents([Camera, Transform])) {
- if (!(world.get(e, Camera) as CameraData).isActive) continue;
- const w = (world.get(e, Transform) as TransformData).worldPosition;
- eye = { x: w.x, z: w.z };
- break;
- }
- if (!eye) return;
- for (const cell of this.far_) {
- // A cell that spans a good part of the distances shows wherever any of it is past what its kind draws and within how far it goes.
- const dx = Math.abs(cell.x - eye.x), dz = Math.abs(cell.z - eye.z);
- const nearest = Math.hypot(Math.max(dx - cell.half, 0), Math.max(dz - cell.half, 0));
- const furthest = Math.hypot(dx + cell.half, dz + cell.half);
- for (const child of cell.children) {
- const kind = cell.kinds[child.kind];
- if (!kind) continue;
- const show = furthest > kind.drawDistance && nearest < kind.farDistance;
- if (show === child.shown || !world.valid(child.entity)) continue;
- child.shown = show;
- world.insert(child.entity, MeshRenderer, { ...(world.get(child.entity, MeshRenderer) as MeshRendererData), enabled: show });
- }
- }
- }
-
/** One frame of it: the far versions shown where they should be, and the queue worked through while the frame's budget lasts, one piece at least. */
step(app: App): void {
- this.showFar(app);
const bakes = bakesOf(app);
let first = true;
while (this.queue.length > 0 && (first || bakes.hasTime())) {
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index af28d45b3..dff76dc54 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -447,6 +447,12 @@ export interface ESEngineModule {
indicesPtr: number, indexCount: number
): void;
+ /**
+ * The placements of a MeshInstances component: sixteen f32 an instance (the model's three rows, then a tint). Empty clears the set.
+ * Reached through the generated engine surface (see foliage/plantGrowth.ts); declared here because embind registers it by hand for the web.
+ */
+ meshInstances_set?(registry: CppRegistry, entity: number, dataPtr: number, count: number): void;
+
// Material API. Materials are engine-side data: the SDK compiles a shader
// here, then pushes the resolved render state (flags pack depthTest bit 0,
// depthWrite bit 1, CullMode bits 2-3) and the param values. Reached through
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 5bd56d734..394eeb397 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -273,6 +273,15 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 16 },
],
},
+ MeshInstances: {
+ ptrFn: 'getMeshInstancesPtr',
+ fields: [
+ { name: 'lod1Mesh', type: 'u32', offset: 0 },
+ { name: 'lodDistance', type: 'f32', offset: 4 },
+ { name: 'minDistance', type: 'f32', offset: 8 },
+ { name: 'drawDistance', type: 'f32', offset: 12 },
+ ],
+ },
MeshLightmap: {
ptrFn: 'getMeshLightmapPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index b01a93e7a..ef46e2f67 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -647,6 +647,13 @@ export interface MeshCollider3D {
enabled: boolean;
}
+export interface MeshInstances {
+ lod1Mesh: number;
+ lodDistance: number;
+ minDistance: number;
+ drawDistance: number;
+}
+
export interface MeshLightmap {
lightmap: number;
scaleOffset: Vec4;
@@ -1109,6 +1116,10 @@ export interface Registry {
getMeshCollider3D(entity: Entity): MeshCollider3D;
addMeshCollider3D(entity: Entity, component: MeshCollider3D): void;
removeMeshCollider3D(entity: Entity): void;
+ hasMeshInstances(entity: Entity): boolean;
+ getMeshInstances(entity: Entity): MeshInstances;
+ addMeshInstances(entity: Entity, component: MeshInstances): void;
+ removeMeshInstances(entity: Entity): void;
hasMeshLightmap(entity: Entity): boolean;
getMeshLightmap(entity: Entity): MeshLightmap;
addMeshLightmap(entity: Entity, component: MeshLightmap): void;
@@ -1271,6 +1282,7 @@ export interface ESEngineModule {
Light: new () => Light;
LightProbeVolume: new () => LightProbeVolume;
MeshCollider3D: new () => MeshCollider3D;
+ MeshInstances: new () => MeshInstances;
MeshLightmap: new () => MeshLightmap;
MeshMorph: new () => MeshMorph;
MeshRenderer: new () => MeshRenderer;
diff --git a/sdk/tests/foliage-placements.test.ts b/sdk/tests/foliage-placements.test.ts
new file mode 100644
index 000000000..1e2bdb34e
--- /dev/null
+++ b/sdk/tests/foliage-placements.test.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { buildPlacedMesh, buildPlacements, PLACEMENT_FLOATS, type Plant } from '../src/foliage/builder';
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';
+
+/** One triangle with a vertex off every axis, so a turn, a scale or a lean moves each of them. */
+function triangle(): MeshData {
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const vertices = new Uint8Array(3 * vertexStride);
+ const f = new Float32Array(vertices.buffer);
+ [[1, 0.5, 0.25], [-0.5, 2, 1], [0.25, 1, -1.5]].forEach((p, v) => f.set([...p, 0, 1, 0], v * (vertexStride / 4)));
+ return { channels, vertexStride, vertexCount: 3, vertices, indices: new Uint32Array([0, 1, 2]), aabbMin: [-0.5, 0.5, -1.5], aabbMax: [1, 2, 1] };
+}
+
+/** A placement's three rows applied to a point, as the engine applies them to the mesh's vertices. */
+const apply = (rows: Float32Array, at: number, p: number[]): number[] =>
+ [0, 1, 2].map((r) => rows[at + r * 4]! * p[0]! + rows[at + r * 4 + 1]! * p[1]! + rows[at + r * 4 + 2]! * p[2]! + rows[at + r * 4 + 3]!);
+
+describe('plant placements', () => {
+ const plants: Plant[] = [
+ { x: 3, y: 1, z: -2, yaw: 0.7, scale: 1.4, phase: 0, shade: 1 },
+ { x: -5, y: 0.5, z: 4, yaw: 3.1, scale: 0.6, phase: 0, shade: 1, up: [0.3, 0.9, 0.1] },
+ ];
+
+ it('place a mesh where merging its copies would have put the vertices', () => {
+ const source = triangle();
+ const merged = buildPlacedMesh(source, plants);
+ const rows = buildPlacements(plants);
+ const world = new Float32Array(merged.vertices.buffer);
+ const words = merged.vertexStride / 4;
+ plants.forEach((_, n) => {
+ for (let v = 0; v < 3; v++) {
+ const local = Array.from(new Float32Array(source.vertices.buffer).subarray(v * words, v * words + 3));
+ const placed = apply(rows, n * PLACEMENT_FLOATS, local);
+ const baked = Array.from(world.subarray((n * 3 + v) * words, (n * 3 + v) * words + 3));
+ placed.forEach((c, i) => expect(c).toBeCloseTo(baked[i]!, 4));
+ }
+ });
+ });
+
+ it('take sixteen numbers a plant, tinted white', () => {
+ const rows = buildPlacements(plants);
+ expect(rows.length).toBe(plants.length * PLACEMENT_FLOATS);
+ expect(Array.from(rows.subarray(12, 16))).toEqual([1, 1, 1, 1]);
+ expect(rows[3]).toBe(3);
+ expect(rows[7]).toBe(1);
+ expect(rows[11]).toBe(-2);
+ });
+});
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index 753f93602..21d84ad74 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -161,6 +161,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::MeshCollider3D>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "MeshInstances") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::MeshInstances>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "MeshLightmap") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::MeshLightmap>(Entity::fromRaw(raw));
@@ -415,6 +420,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshCollider3D>());
};
}
+ if (std::strcmp(name, "MeshInstances") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::MeshInstances>());
+ };
+ }
if (std::strcmp(name, "MeshLightmap") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshLightmap>());
@@ -593,6 +603,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "Light") == 0) return true;
if (std::strcmp(name, "LightProbeVolume") == 0) return true;
if (std::strcmp(name, "MeshCollider3D") == 0) return true;
+ if (std::strcmp(name, "MeshInstances") == 0) return true;
if (std::strcmp(name, "MeshLightmap") == 0) return true;
if (std::strcmp(name, "MeshMorph") == 0) return true;
if (std::strcmp(name, "MeshRenderer") == 0) return true;
diff --git a/src/esengine/aot/EngineDigest.generated.h b/src/esengine/aot/EngineDigest.generated.h
index 72d33bcae..0e236a417 100644
--- a/src/esengine/aot/EngineDigest.generated.h
+++ b/src/esengine/aot/EngineDigest.generated.h
@@ -6,7 +6,7 @@
/* One per address width, because the width is IN the digest: a host that
took the other one would refuse every module built for it. */
-#define ES_ENGINE_ABI_DIGEST_32 0x3688504ce5043a13ULL
-#define ES_ENGINE_ABI_DIGEST_64 0x469de615bfcdb967ULL
+#define ES_ENGINE_ABI_DIGEST_32 0xdb9af7d81251cf95ULL
+#define ES_ENGINE_ABI_DIGEST_64 0x3a95e34eb4bec721ULL
#define ES_ENGINE_ABI_DIGEST \
(sizeof(es_addr_t) == 8 ? ES_ENGINE_ABI_DIGEST_64 : ES_ENGINE_ABI_DIGEST_32)
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 430837071..186df76c4 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 000c86a1b1333822
+ * @schema_hash 3a26328c6019f91c
*/
-#define ES_EDITOR_API_SCHEMA_HASH "000c86a1b1333822"
+#define ES_EDITOR_API_SCHEMA_HASH "3a26328c6019f91c"
#include <emscripten/bind.h>
#include <string>
@@ -87,6 +87,7 @@ std::vector<std::string> editor_getComponentNames() {
"Light",
"LightProbeVolume",
"MeshCollider3D",
+ "MeshInstances",
"MeshLightmap",
"MeshMorph",
"MeshRenderer",
@@ -384,6 +385,13 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"layer","type":"int","group":"MeshCollider3D"},
{"key":"enabled","type":"bool","group":"MeshCollider3D"}
])JSON";
+ } else if (name == "MeshInstances") {
+ return R"JSON([
+ {"key":"lod1Mesh","type":"asset","group":"MeshInstances"},
+ {"key":"lodDistance","type":"float","group":"MeshInstances"},
+ {"key":"minDistance","type":"float","group":"MeshInstances"},
+ {"key":"drawDistance","type":"float","group":"MeshInstances"}
+ ])JSON";
} else if (name == "MeshLightmap") {
return R"JSON([
{"key":"lightmap","type":"asset","group":"MeshLightmap"},
@@ -915,6 +923,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "MeshCollider3D") {
if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) reg.emplace<esengine::ecs::MeshCollider3D>(entity);
return true;
+ } else if (name == "MeshInstances") {
+ if (!reg.has<esengine::ecs::MeshInstances>(entity)) reg.emplace<esengine::ecs::MeshInstances>(entity);
+ return true;
} else if (name == "MeshLightmap") {
if (!reg.has<esengine::ecs::MeshLightmap>(entity)) reg.emplace<esengine::ecs::MeshLightmap>(entity);
return true;
@@ -1056,6 +1067,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::LightProbeVolume>(entity)) { reg.remove<esengine::ecs::LightProbeVolume>(entity); return true; }
} else if (name == "MeshCollider3D") {
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) { reg.remove<esengine::ecs::MeshCollider3D>(entity); return true; }
+ } else if (name == "MeshInstances") {
+ if (reg.has<esengine::ecs::MeshInstances>(entity)) { reg.remove<esengine::ecs::MeshInstances>(entity); return true; }
} else if (name == "MeshLightmap") {
if (reg.has<esengine::ecs::MeshLightmap>(entity)) { reg.remove<esengine::ecs::MeshLightmap>(entity); return true; }
} else if (name == "MeshMorph") {
@@ -1144,6 +1157,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "Light") return reg.has<esengine::ecs::Light>(entity);
if (name == "LightProbeVolume") return reg.has<esengine::ecs::LightProbeVolume>(entity);
if (name == "MeshCollider3D") return reg.has<esengine::ecs::MeshCollider3D>(entity);
+ if (name == "MeshInstances") return reg.has<esengine::ecs::MeshInstances>(entity);
if (name == "MeshLightmap") return reg.has<esengine::ecs::MeshLightmap>(entity);
if (name == "MeshMorph") return reg.has<esengine::ecs::MeshMorph>(entity);
if (name == "MeshRenderer") return reg.has<esengine::ecs::MeshRenderer>(entity);
@@ -1203,6 +1217,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::Light>(entity)) result.push_back("Light");
if (reg.has<esengine::ecs::LightProbeVolume>(entity)) result.push_back("LightProbeVolume");
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) result.push_back("MeshCollider3D");
+ if (reg.has<esengine::ecs::MeshInstances>(entity)) result.push_back("MeshInstances");
if (reg.has<esengine::ecs::MeshLightmap>(entity)) result.push_back("MeshLightmap");
if (reg.has<esengine::ecs::MeshMorph>(entity)) result.push_back("MeshMorph");
if (reg.has<esengine::ecs::MeshRenderer>(entity)) result.push_back("MeshRenderer");
@@ -1450,6 +1465,14 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = value; }
else { return false; }
return true;
+ } else if (comp == "MeshInstances") {
+ if (!reg.has<esengine::ecs::MeshInstances>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshInstances>(entity);
+ if (field == "lodDistance") { c.lodDistance = value; }
+ else if (field == "minDistance") { c.minDistance = value; }
+ else if (field == "drawDistance") { c.drawDistance = value; }
+ else { return false; }
+ return true;
} else if (comp == "MeshLightmap") {
if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return false;
auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
@@ -2007,6 +2030,12 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "MeshInstances") {
+ if (!reg.has<esengine::ecs::MeshInstances>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::MeshInstances>(entity);
+ if (field == "lodDistance") { return c.lodDistance; }
+ else if (field == "minDistance") { return c.minDistance; }
+ else if (field == "drawDistance") { return c.drawDistance; }
} else if (comp == "MeshLightmap") {
if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
@@ -2429,6 +2458,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "layer") { c.layer = static_cast<u32>(value); }
else { return false; }
return true;
+ } else if (comp == "MeshInstances") {
+ if (!reg.has<esengine::ecs::MeshInstances>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshInstances>(entity);
+ if (field == "lod1Mesh") { c.lod1Mesh = resource::MeshHandle(static_cast<u32>(value)); }
+ else { return false; }
+ return true;
} else if (comp == "MeshLightmap") {
if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return false;
auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
@@ -2702,6 +2737,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
if (field == "mesh") { return static_cast<i32>(c.mesh.id()); }
else if (field == "layer") { return static_cast<i32>(c.layer); }
+ } else if (comp == "MeshInstances") {
+ if (!reg.has<esengine::ecs::MeshInstances>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::MeshInstances>(entity);
+ if (field == "lod1Mesh") { return static_cast<i32>(c.lod1Mesh.id()); }
} else if (comp == "MeshLightmap") {
if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 6ed0dc08f..115607a57 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -250,6 +250,44 @@ void meshRenderer_setGeometry(ecs::Registry& registry, u32 entity,
mesh->localMax = mx;
}
+// The placements of a MeshInstances, copied in and measured: the corners of where the instances stand and the
+// greatest scale among them, which with the mesh's reach is what bounds the set. The collect trusts the count.
+void meshInstances_set(ecs::Registry& registry, u32 entity, uintptr_t dataPtr, u32 count) {
+ const Entity ent = Entity::fromRaw(entity);
+ auto* set = registry.tryGet<ecs::MeshInstances>(ent);
+ if (!set) {
+ ES_LOG_WARN("meshInstances_set: entity {} has no MeshInstances component", entity);
+ return;
+ }
+ constexpr u32 kFloats = 16;
+ if (dataPtr == 0 || count == 0) {
+ set->transforms.clear();
+ set->originMin = set->originMax = glm::vec3(0.0f);
+ set->maxScale = 1.0f;
+ return;
+ }
+ const f32* data = boundarySpan<f32>(dataPtr, static_cast<u64>(count) * kFloats, "meshInstances_set.transforms");
+ if (!data) return;
+ set->transforms.assign(data, data + static_cast<usize>(count) * kFloats);
+ glm::vec3 mn(data[3], data[7], data[11]);
+ glm::vec3 mx = mn;
+ f32 scale = 0.0f;
+ for (u32 i = 0; i < count; ++i) {
+ const f32* r = data + static_cast<usize>(i) * kFloats;
+ const glm::vec3 at(r[3], r[7], r[11]);
+ mn = glm::min(mn, at);
+ mx = glm::max(mx, at);
+ // The longest column of the linear part: how far the instance stretches its mesh.
+ const f32 c0 = r[0] * r[0] + r[4] * r[4] + r[8] * r[8];
+ const f32 c1 = r[1] * r[1] + r[5] * r[5] + r[9] * r[9];
+ const f32 c2 = r[2] * r[2] + r[6] * r[6] + r[10] * r[10];
+ scale = std::max(scale, std::max(c0, std::max(c1, c2)));
+ }
+ set->originMin = mn;
+ set->originMax = mx;
+ set->maxScale = std::sqrt(scale);
+}
+
// Geometry that STAYS on the GPU: interleaved f32 [x,y,z,u,v] plus optional RGBA8
// colors, validated exactly as the inline path is. createMesh appends the
// per-object transform, so nothing here knows how a mesh reaches the shader.
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 4025c66cc..c930d01c8 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -89,6 +89,8 @@ void meshRenderer_setGeometry(
uintptr_t colorsPtr,
uintptr_t indicesPtr, u32 indexCount
);
+/** @brief The placements of a MeshInstances: sixteen f32 an instance (see the component). Empty clears the set. */
+void meshInstances_set(ecs::Registry& registry, u32 entity, uintptr_t dataPtr, u32 count);
/** @brief Geometry from an .esmesh channel table; returns its handle, 0 on failure. */
u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
uintptr_t vertexPtr, u32 vertexBytes,
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index be290925f..9a0dcbd67 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -766,6 +766,35 @@ MeshCollider3DJS meshcollider3dToJS(const esengine::ecs::MeshCollider3D& c) {
return js;
}
+struct MeshInstancesJS {
+ u32 lod1Mesh;
+ f32 lodDistance;
+ f32 minDistance;
+ f32 drawDistance;
+};
+
+void meshinstancesApplyJS(esengine::ecs::MeshInstances& c, const MeshInstancesJS& js) {
+ c.lod1Mesh = resource::MeshHandle(js.lod1Mesh);
+ c.lodDistance = js.lodDistance;
+ c.minDistance = js.minDistance;
+ c.drawDistance = js.drawDistance;
+}
+
+esengine::ecs::MeshInstances meshinstancesFromJS(const MeshInstancesJS& js) {
+ esengine::ecs::MeshInstances c;
+ meshinstancesApplyJS(c, js);
+ return c;
+}
+
+MeshInstancesJS meshinstancesToJS(const esengine::ecs::MeshInstances& c) {
+ MeshInstancesJS js;
+ js.lod1Mesh = c.lod1Mesh.id();
+ js.lodDistance = c.lodDistance;
+ js.minDistance = c.minDistance;
+ js.drawDistance = c.drawDistance;
+ return js;
+}
+
struct MeshLightmapJS {
u32 lightmap;
glm::vec4 scaleOffset;
@@ -1945,6 +1974,12 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("layer", &MeshCollider3DJS::layer)
.field("enabled", &MeshCollider3DJS::enabled);
+ value_object<MeshInstancesJS>("MeshInstances")
+ .field("lod1Mesh", &MeshInstancesJS::lod1Mesh)
+ .field("lodDistance", &MeshInstancesJS::lodDistance)
+ .field("minDistance", &MeshInstancesJS::minDistance)
+ .field("drawDistance", &MeshInstancesJS::drawDistance);
+
value_object<MeshLightmapJS>("MeshLightmap")
.field("lightmap", &MeshLightmapJS::lightmap)
.field("scaleOffset", &MeshLightmapJS::scaleOffset);
@@ -2340,6 +2375,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (r.has<esengine::ecs::Light>(entity)) { if (!names.empty()) names += "|"; names += "Light"; }
if (r.has<esengine::ecs::LightProbeVolume>(entity)) { if (!names.empty()) names += "|"; names += "LightProbeVolume"; }
if (r.has<esengine::ecs::MeshCollider3D>(entity)) { if (!names.empty()) names += "|"; names += "MeshCollider3D"; }
+ if (r.has<esengine::ecs::MeshInstances>(entity)) { if (!names.empty()) names += "|"; names += "MeshInstances"; }
if (r.has<esengine::ecs::MeshLightmap>(entity)) { if (!names.empty()) names += "|"; names += "MeshLightmap"; }
if (r.has<esengine::ecs::MeshMorph>(entity)) { if (!names.empty()) names += "|"; names += "MeshMorph"; }
if (r.has<esengine::ecs::MeshRenderer>(entity)) { if (!names.empty()) names += "|"; names += "MeshRenderer"; }
@@ -2394,6 +2430,7 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
if (name == "Light") return static_cast<int>(componentTypeId<esengine::ecs::Light>());
if (name == "LightProbeVolume") return static_cast<int>(componentTypeId<esengine::ecs::LightProbeVolume>());
if (name == "MeshCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::MeshCollider3D>());
+ if (name == "MeshInstances") return static_cast<int>(componentTypeId<esengine::ecs::MeshInstances>());
if (name == "MeshLightmap") return static_cast<int>(componentTypeId<esengine::ecs::MeshLightmap>());
if (name == "MeshMorph") return static_cast<int>(componentTypeId<esengine::ecs::MeshMorph>());
if (name == "MeshRenderer") return static_cast<int>(componentTypeId<esengine::ecs::MeshRenderer>());
@@ -2858,6 +2895,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::MeshCollider3D>(entity);
}))
+ // MeshInstances
+ .function("hasMeshInstances", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::MeshInstances>(static_cast<Entity>(e));
+ }))
+ .function("getMeshInstances", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshInstances>(entity)) return MeshInstancesJS{};
+ return meshinstancesToJS(r.get<esengine::ecs::MeshInstances>(entity));
+ }))
+ .function("addMeshInstances", optional_override([](Registry& r, u32 e, const MeshInstancesJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::MeshInstances>(entity)) {
+ meshinstancesApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::MeshInstances>(entity, meshinstancesFromJS(js));
+ }))
+ .function("removeMeshInstances", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshInstances>(entity)) return;
+ r.remove<esengine::ecs::MeshInstances>(entity);
+ }))
+
// MeshLightmap
.function("hasMeshLightmap", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::MeshLightmap>(static_cast<Entity>(e));
@@ -3604,6 +3665,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("Light")));
arr.set(i++, val(std::string("LightProbeVolume")));
arr.set(i++, val(std::string("MeshCollider3D")));
+ arr.set(i++, val(std::string("MeshInstances")));
arr.set(i++, val(std::string("MeshLightmap")));
arr.set(i++, val(std::string("MeshMorph")));
arr.set(i++, val(std::string("MeshRenderer")));
@@ -3805,6 +3867,10 @@ static_assert(offsetof(esengine::ecs::MeshCollider3D, friction) == 4, "ABI offse
static_assert(offsetof(esengine::ecs::MeshCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::MeshCollider3D.restitution (EHT expected 8)");
static_assert(offsetof(esengine::ecs::MeshCollider3D, layer) == 12, "ABI offset drift: esengine::ecs::MeshCollider3D.layer (EHT expected 12)");
static_assert(offsetof(esengine::ecs::MeshCollider3D, enabled) == 16, "ABI offset drift: esengine::ecs::MeshCollider3D.enabled (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::MeshInstances, lod1Mesh) == 0, "ABI offset drift: esengine::ecs::MeshInstances.lod1Mesh (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::MeshInstances, lodDistance) == 4, "ABI offset drift: esengine::ecs::MeshInstances.lodDistance (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::MeshInstances, minDistance) == 8, "ABI offset drift: esengine::ecs::MeshInstances.minDistance (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::MeshInstances, drawDistance) == 12, "ABI offset drift: esengine::ecs::MeshInstances.drawDistance (EHT expected 12)");
static_assert(offsetof(esengine::ecs::MeshLightmap, lightmap) == 0, "ABI offset drift: esengine::ecs::MeshLightmap.lightmap (EHT expected 0)");
static_assert(offsetof(esengine::ecs::MeshLightmap, scaleOffset) == 4, "ABI offset drift: esengine::ecs::MeshLightmap.scaleOffset (EHT expected 4)");
static_assert(offsetof(esengine::ecs::MeshRenderer, texture) == 0, "ABI offset drift: esengine::ecs::MeshRenderer.texture (EHT expected 0)");
@@ -4084,7 +4150,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "7cf803aca319cd32";
+static const char* kEsAbiLayoutHash = "91648bb4a306e016";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 3581d8b19..e9eb9c812 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -536,6 +536,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_entityVisibleToCamera", &esengine::renderer_entityVisibleToCamera);
emscripten::function("renderer_submitTextBatch", &esengine::renderer_submitTextBatch);
emscripten::function("meshRenderer_setGeometry", &esengine::meshRenderer_setGeometry);
+ emscripten::function("meshInstances_set", &esengine::meshInstances_set);
emscripten::function("mesh_createFromChannels", &esengine::mesh_createFromChannels);
emscripten::function("mesh_rematerializeFromChannels", &esengine::mesh_rematerializeFromChannels);
emscripten::function("mesh_release", &esengine::mesh_release);
diff --git a/src/esengine/ecs/components/MeshRenderer.hpp b/src/esengine/ecs/components/MeshRenderer.hpp
index 5442a7118..d4b318fe5 100644
--- a/src/esengine/ecs/components/MeshRenderer.hpp
+++ b/src/esengine/ecs/components/MeshRenderer.hpp
@@ -170,6 +170,51 @@ struct MeshMorph {
MeshMorph() = default;
};
+// =============================================================================
+// MeshInstances Component
+// =============================================================================
+
+/**
+ * @brief Many placements of the one mesh a @ref MeshRenderer draws, as ONE renderable.
+ *
+ * @details The mesh stays one and resident; this holds where each copy stands. The collect culls each copy against the view, picks its mesh by
+ * its distance from the eye and writes the survivors as the instances of one draw per mesh. The entity's Transform places the whole
+ * set: an instance is relative to it.
+ */
+ES_COMPONENT()
+struct MeshInstances {
+ /** @brief The cheaper mesh that stands in past @ref lodDistance; invalid = the mesh itself at every distance. It
+ * must carry the same channels as the entity's mesh, or it is not used. */
+ ES_PROPERTY(asset = mesh, tooltip="The cheaper mesh used past the LOD distance. Needs the same channels as the mesh.")
+ resource::MeshHandle lod1Mesh;
+
+ /** @brief Metres from the eye past which @ref lod1Mesh is drawn; 0 = never. */
+ ES_PROPERTY(tooltip="Distance (metres) past which the cheaper mesh is used. 0 = never.")
+ f32 lodDistance{0.0f};
+
+ /** @brief Metres from the eye BEFORE which an instance is not drawn; 0 = from the eye outward. A far version of a plant is a set
+ * with this at the distance the near one ends, so the two hand over per instance without anything choosing between them. */
+ ES_PROPERTY(tooltip="Distance (metres) nearer than which an instance is not drawn. 0 = from the eye.")
+ f32 minDistance{0.0f};
+
+ /** @brief Metres from the eye past which an instance is not drawn; 0 = at any distance. A shadow map is cut by the
+ * distance from the CAMERA, not from the light, so a caster too far to be seen does not cast. */
+ ES_PROPERTY(tooltip="Distance (metres) past which an instance is not drawn. 0 = unlimited.")
+ f32 drawDistance{0.0f};
+
+ /** @brief Sixteen floats an instance: the model's three rows (translation in .w) then its tint RGBA, which is
+ * multiplied into the renderer's colour. Set by meshInstances_set, not by reflection. */
+ std::vector<f32> transforms;
+
+ /** @brief The corners of the instances' ORIGINS and the greatest scale among them: with the mesh's own reach, what
+ * bounds the set. Recomputed on upload. */
+ glm::vec3 originMin{0.0f};
+ glm::vec3 originMax{0.0f};
+ f32 maxScale{1.0f};
+
+ MeshInstances() = default;
+};
+
// =============================================================================
// MeshLightmap Component
// =============================================================================
diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hpp
index 515de93bf..faab2268a 100644
--- a/src/esengine/renderer/RenderTypePlugin.hpp
+++ b/src/esengine/renderer/RenderTypePlugin.hpp
@@ -85,6 +85,10 @@ struct RenderFrameContext {
/// previous picture was actually drawn on.
glm::mat4 motion_prev_view_projection{1.0f};
glm::vec2 motion_prev_jitter{0.0f};
+ /// Where the SCENE camera is, in every collect of the frame (a shadow map's included): what a distance-limited draw measures from.
+ /// Absent for an orthographic camera, which has no position to be far from.
+ glm::vec3 view_eye{0.0f};
+ bool has_view_eye = false;
};
/** @brief What every plugin needs to know about the camera, derived once per collect
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 58bc31059..99ad114e0 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -33,11 +33,13 @@ void rewriteTexIndex(TransientBufferPool& pool, const DrawCommand& cmd, i32 slot
* run needs it: the caller leaves the draws apart rather than draw stray bytes.
*/
bool relocateInstance(TransientBufferPool& pool, DrawCommand& cmd, u32 expectedAt) {
- const u32 at = pool.allocVertices(LayoutId::MeshInstance, cmd.instance_stride);
+ // Every record of the draw: one for an entity, as many as it has instances for a set of placements.
+ const u32 bytes = cmd.instance_stride * std::max(cmd.instance_count, 1u);
+ const u32 at = pool.allocVertices(LayoutId::MeshInstance, bytes);
if (expectedAt != NO_EXPECTED_OFFSET && at != expectedAt) return false;
// After the alloc: growing the staging can move it.
u8* base = pool.vertexData(LayoutId::MeshInstance);
- std::memmove(base + at, base + cmd.vertex_byte_offset, cmd.instance_stride);
+ std::memmove(base + at, base + cmd.vertex_byte_offset, bytes);
cmd.vertex_byte_offset = at;
return true;
}
@@ -236,7 +238,7 @@ void DrawList::finalize(TransientBufferPool& pool) {
// One more instance in this run, and its own irradiance with
// it: the merge is the last place an instance's probe and its
// position in the run are both known.
- probe_slots_.push_back(commands_[i].probe_index);
+ probe_slots_.insert(probe_slots_.end(), std::max(commands_[i].instance_count, 1u), commands_[i].probe_index);
didMerge = true;
} else {
blocker = BatchBreak::Instanced;
@@ -273,7 +275,7 @@ void DrawList::finalize(TransientBufferPool& pool) {
run_first_.push_back(static_cast<u32>(run_entities_.size()));
if (commands_[writeIdx].instance_count != 0) {
commands_[writeIdx].probe_base = static_cast<u32>(probe_slots_.size());
- probe_slots_.push_back(commands_[writeIdx].probe_index);
+ probe_slots_.insert(probe_slots_.end(), commands_[writeIdx].instance_count, commands_[writeIdx].probe_index);
}
commands_[writeIdx].break_reason = blocker;
++breaks[static_cast<u32>(blocker)];
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 2edb70a88..1e0c28482 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -1312,7 +1312,7 @@ void RenderFrame::buildSpriteMasks(ecs::Registry& registry) {
}
RenderFrameContext RenderFrame::makeContext() {
- return {
+ RenderFrameContext ctx{
context_,
resource_manager_,
context_.getWhiteTextureId(),
@@ -1325,6 +1325,10 @@ RenderFrameContext RenderFrame::makeContext() {
shadow_texture_id_,
environment_texture_id_
};
+ const glm::vec4 eye = cameraFromViewProjection(view_projection_);
+ ctx.has_view_eye = eye.w > 0.5f;
+ if (ctx.has_view_eye) ctx.view_eye = glm::vec3(eye);
+ return ctx;
}
/// Where a light aims: the entity's forward, its rotation applied to -Z. A light
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index 4a054a350..692d87829 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -544,6 +544,88 @@ void MeshPlugin::trackPose(const RenderFrameContext& ctx, Entity entity, const g
pose.frame = ctx.motion_frame;
}
+namespace {
+/**
+ * @brief Writes the placements of a MeshInstances as instances of one draw per level of detail.
+ *
+ * @details Each placement is judged on its own: past `drawDistance` from the eye it is not drawn, outside the view it is not drawn, and
+ * past `lodDistance` it is the cheaper mesh. The eye is the SCENE camera's whatever pass this is, so a shadow map is cut
+ * by the distance from the camera and not from the light. What stays is a record each (the entity's model times the
+ * placement, its tint, its normal matrix) and one draw a level.
+ */
+template <typename Emit>
+void emitPlacements(const RenderFrameContext& ctx, RenderCollectContext& collect, const ecs::MeshInstances& set,
+ const ecs::MeshRenderer& mesh, const glm::vec3& position, const glm::quat& rotation,
+ const glm::vec3& scale, const Mesh& fine, const Mesh* coarse, u32& records, Emit&& emit) {
+ static thread_local std::vector<u32> nearList, farList;
+ nearList.clear();
+ farList.clear();
+ const glm::mat4 entityModel = glm::translate(glm::mat4(1.0f), position) * glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0f), scale);
+ const f32 entityScale = std::max(std::abs(scale.x), std::max(std::abs(scale.y), std::abs(scale.z)));
+ const f32 reach = glm::length(glm::max(glm::abs(fine.localMin), glm::abs(fine.localMax)));
+ const bool eyeKnown = ctx.has_view_eye;
+ const u32 count = static_cast<u32>(set.transforms.size() / 16);
+ u32 tooFar = 0, outside = 0;
+ for (u32 i = 0; i < count; ++i) {
+ const f32* r = set.transforms.data() + static_cast<usize>(i) * 16;
+ const glm::vec3 at = glm::vec3(entityModel * glm::vec4(r[3], r[7], r[11], 1.0f));
+ const f32 c0 = r[0] * r[0] + r[4] * r[4] + r[8] * r[8];
+ const f32 c1 = r[1] * r[1] + r[5] * r[5] + r[9] * r[9];
+ const f32 c2 = r[2] * r[2] + r[6] * r[6] + r[10] * r[10];
+ const f32 radius = reach * std::sqrt(std::max(c0, std::max(c1, c2))) * entityScale;
+ f32 distance = 0.0f;
+ if (eyeKnown) {
+ distance = glm::distance(at, ctx.view_eye);
+ if (set.drawDistance > 0.0f && distance - radius > set.drawDistance) { ++tooFar; continue; }
+ if (distance + radius < set.minDistance) continue;
+ }
+ if (!collect.visible(at, glm::vec3(radius), false)) { ++outside; continue; }
+ (coarse && eyeKnown && set.lodDistance > 0.0f && distance > set.lodDistance ? farList : nearList).push_back(i);
+ }
+ ES_PROFILE_COUNTER("render.placements.seen", count);
+ ES_PROFILE_COUNTER("render.placements.tooFar", tooFar);
+ ES_PROFILE_COUNTER("render.placements.outside", outside);
+ ES_PROFILE_COUNTER("render.placements.coarse", farList.size());
+ ES_PROFILE_COUNTER("render.placements.eye", eyeKnown ? 1 : 0);
+ // The frame's record texture holds so many; past it the tail would draw unplaced, which is worse than not at all.
+ const u32 room = records < MESH_INSTANCE_MAX_RECORDS ? MESH_INSTANCE_MAX_RECORDS - records : 0;
+ if (nearList.size() > room) nearList.resize(room);
+ if (farList.size() > room - nearList.size()) farList.resize(room - nearList.size());
+ records += static_cast<u32>(nearList.size() + farList.size());
+
+ auto& buffers = collect.buffer_pool;
+ const auto write = [&](const std::vector<u32>& list, const Mesh& geo) {
+ if (list.empty()) return;
+ const u32 offset = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE * static_cast<u32>(list.size()));
+ auto* dst = buffers.vertexData(LayoutId::MeshInstance) + offset;
+ std::memset(dst, 0, static_cast<usize>(MESH_INSTANCE_STRIDE) * list.size());
+ for (const u32 i : list) {
+ const f32* r = set.transforms.data() + static_cast<usize>(i) * 16;
+ glm::mat4 placed(1.0f);
+ placed[0] = {r[0], r[4], r[8], 0.0f};
+ placed[1] = {r[1], r[5], r[9], 0.0f};
+ placed[2] = {r[2], r[6], r[10], 0.0f};
+ placed[3] = {r[3], r[7], r[11], 1.0f};
+ const glm::mat4 model = entityModel * placed;
+ for (u32 row = 0; row < 3; ++row) {
+ const glm::vec4 m{model[0][row], model[1][row], model[2][row], model[3][row]};
+ std::memcpy(dst + (MESH_INSTANCE_TEXEL_MODEL + row) * 16, &m, 16);
+ }
+ const glm::vec4 tint = mesh.color * glm::vec4(r[12], r[13], r[14], r[15]);
+ std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &tint, 16);
+ if (geo.hasNormals) {
+ const glm::mat3 nrm = glm::transpose(glm::inverse(glm::mat3(model)));
+ for (u32 row = 0; row < 3; ++row) std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &nrm[row][0], 12);
+ }
+ dst += MESH_INSTANCE_STRIDE;
+ }
+ emit(geo, offset, static_cast<u32>(list.size()));
+ };
+ write(nearList, fine);
+ if (coarse) write(farList, *coarse);
+}
+} // namespace
+
void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
auto& registry = collect_ctx.registry;
auto& clips = collect_ctx.clip_state;
@@ -574,7 +656,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
const bool timing = FrameProfiler::get().enabled();
f64 phase[5] = {0, 0, 0, 0, 0};
f64 mark = timing ? es_profile_now_ms() : 0.0;
- u32 walked = 0, coldDecompose = 0, lodGathers = 0, programAsks = 0;
+ u32 walked = 0, coldDecompose = 0, lodGathers = 0, programAsks = 0, instanceRecords = 0;
const auto tick = [&](int slot) {
if (!timing) return;
const f64 now = es_profile_now_ms();
@@ -624,6 +706,9 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
// below, which bakes world space into vertices for the BATCH shader — a
// shader that writes colour, not the depth this pass is here to collect.
if (depthPass && !resident) continue;
+ // Many placements of one mesh, drawn as instances of it. What is placed does not move on its own, so the motion pass has nothing to say.
+ const ecs::MeshInstances* placements = resident ? registry.tryGet<ecs::MeshInstances>(entity) : nullptr;
+ if (placements && (placements->transforms.empty() || motion)) continue;
// What light passes through (water) stands in no light's way.
if (shadowDepth && !mesh.castShadows) continue;
// Only a surface that draws opaque and unblended has a motion worth writing: what is blended over
@@ -635,7 +720,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
// make the answer the entity's rather than each view's.
LodLevels levels;
const ecs::LODGroup* group = nullptr;
- if (collect_ctx.lod.state && resident) {
+ if (collect_ctx.lod.state && resident && !placements) {
const auto* declared = registry.tryGet<ecs::LODGroup>(entity);
if (declared && declared->enabled) {
++lodGathers;
@@ -646,9 +731,14 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
}
}
tick(1);
- const glm::vec3 localMin = group ? levels.localMin
+ // A set of placements is bounded by where they stand, grown by how far the mesh reaches from its origin at the greatest scale.
+ const glm::vec3 reach = (placements ? glm::max(glm::abs(resident->localMin), glm::abs(resident->localMax)) * placements->maxScale
+ : glm::vec3(0.0f));
+ const glm::vec3 localMin = placements ? placements->originMin - reach
+ : group ? levels.localMin
: resident ? resident->localMin : glm::vec3(mesh.localMin, 0.0f);
- const glm::vec3 localMax = group ? levels.localMax
+ const glm::vec3 localMax = placements ? placements->originMax + reach
+ : group ? levels.localMax
: resident ? resident->localMax : glm::vec3(mesh.localMax, 0.0f);
// BEFORE the cull, because whether this draw depth-tests decides if an
@@ -958,27 +1048,46 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
key.layoutId = LayoutId::MeshInstance;
key.instanceCount = 1;
key.instanceStride = MESH_INSTANCE_STRIDE;
- key.vertexBuffer = resident->vertexBuffer;
- key.indexBuffer = resident->indexBuffer;
- key.vertexLayout = resident->layout;
const bool wire = shading == ShadingMode::Wireframe;
if (wire) key.depthBias = kWireFillBias;
- pushBatchDraw(draw_list, clips, instOffset, 0, 0, resident->indexCount, key);
- // A cutout that asks for tips gets its soft outer band as a second, blended draw of the same
- // instance: no depth written, sorted with the other blended draws, and no surface record.
- if (!depthPass && !wire && key.materialId != 0 && ctx.materials && ctx.materials->hasTipPass(key.materialId)) {
- const u32 tipProgram = ctx.materials->meshProgram(key.materialId, ctx.resources, resident->hasNormals, skinned,
- key.envTextureId != 0, resident->hasLightmapUV, false,
- resident->hasTangents, true);
- if (tipProgram != 0) {
- BatchDrawKey tips = key;
- tips.shaderId = tipProgram;
- tips.stage = RenderStage::Transparent;
- tips.blend = BlendMode::Normal;
- tips.depthWrite = false;
- pushBatchDraw(draw_list, clips, instOffset, 0, 0, resident->indexCount, tips);
+ // One draw of `count` records from `offset`, of the geometry `geo`. A cutout that asks for tips gets its soft outer band
+ // as a second, blended draw of the same instances: no depth written, sorted with the other blended draws, and no
+ // surface record.
+ const auto emit = [&](const Mesh& geo, u32 offset, u32 count) {
+ BatchDrawKey drawn = key;
+ drawn.instanceCount = count;
+ drawn.vertexBuffer = geo.vertexBuffer;
+ drawn.indexBuffer = geo.indexBuffer;
+ drawn.vertexLayout = geo.layout;
+ pushBatchDraw(draw_list, clips, offset, 0, 0, geo.indexCount, drawn);
+ if (!depthPass && !wire && key.materialId != 0 && ctx.materials && ctx.materials->hasTipPass(key.materialId)) {
+ const u32 tipProgram = ctx.materials->meshProgram(key.materialId, ctx.resources, geo.hasNormals, skinned,
+ key.envTextureId != 0, geo.hasLightmapUV, false,
+ geo.hasTangents, true);
+ if (tipProgram != 0) {
+ BatchDrawKey tips = drawn;
+ tips.shaderId = tipProgram;
+ tips.stage = RenderStage::Transparent;
+ tips.blend = BlendMode::Normal;
+ tips.depthWrite = false;
+ pushBatchDraw(draw_list, clips, offset, 0, 0, geo.indexCount, tips);
+ }
+ }
+ };
+ if (placements) {
+ // The record written for the entity above is not drawn: the instances are, each with a record of its own.
+ const Mesh* coarse = placements->lod1Mesh.isValid() ? ctx.resources.getMesh(placements->lod1Mesh) : nullptr;
+ if (coarse && (!coarse->isDrawable() || coarse->hasNormals != resident->hasNormals
+ || coarse->hasTangents != resident->hasTangents || coarse->hasLightmapUV != resident->hasLightmapUV)) {
+ coarse = nullptr;
}
+ emitPlacements(ctx, collect_ctx, *placements, mesh, position, rotation, scale, *resident, coarse, instanceRecords, emit);
+ continue;
}
+ key.vertexBuffer = resident->vertexBuffer;
+ key.indexBuffer = resident->indexBuffer;
+ key.vertexLayout = resident->layout;
+ emit(*resident, instOffset, 1);
// The edges, as a second draw of the same instance with its own ink: same
// vertices, the mesh's line list, tested against the surface just drawn.
if (wire && resident->hasEdges()) {
@@ -1045,6 +1154,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
// cost grew are different problems and the milliseconds cannot tell them
// apart. `coldDecompose` is the one that only a first look can be high.
ES_PROFILE_COUNTER("render.mesh.walked", walked);
+ ES_PROFILE_COUNTER("render.mesh.placements", instanceRecords);
ES_PROFILE_COUNTER("render.mesh.coldDecompose", coldDecompose);
ES_PROFILE_COUNTER("render.mesh.lodGathers", lodGathers);
ES_PROFILE_COUNTER("render.mesh.programAsks", programAsks);
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index 24cb053cd..b71cf2c3c 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0x469de615bfcdb967ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0x3a95e34eb4bec721ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index 5aef62949..4bb27af5b 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x469de615bfcdb967ULL
+#define ES_ABI_ENGINE_DIGEST 0x3a95e34eb4bec721ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
index 80f665b02..b3140604d 100644
--- a/tests/aot/generated/move_system_decl.c
+++ b/tests/aot/generated/move_system_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x469de615bfcdb967ULL
+#define ES_ABI_ENGINE_DIGEST 0x3a95e34eb4bec721ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index 64d6c1fef..7d158a2df 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,6 +1,6 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_EXPECTED_CONTRACT_HASH 0x469de615bfcdb967ULL
+#define ES_EXPECTED_CONTRACT_HASH 0x3a95e34eb4bec721ULL
/* And which BUILD the artifact beside this one is, which the sidecar
written with it has to carry too. */
#define ES_EXPECTED_MODULE_CONTRACT 0x10bf77bb714ea1e3ULL
diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cpp
index ab2598803..e93a6d73e 100644
--- a/tests/renderer/test_batch_builder.cpp
+++ b/tests/renderer/test_batch_builder.cpp
@@ -1786,6 +1786,34 @@ TEST_CASE("finalize: the same mesh drawn three times is one instanced draw") {
CHECK(instanceMarks(h, cmd) == std::vector<f32>{2.0f, 3.0f, 1.0f});
}
+/** Submits `count` instances of `key`'s mesh as ONE draw (a set of placements), the n-th record marked `mark + n`. */
+void pushMeshInstances(Harness& h, BatchDrawKey key, u32 count, f32 mark, f32 depth) {
+ const u32 at = h.pool.allocVertices(LayoutId::MeshInstance, key.instanceStride * count);
+ for (u32 n = 0; n < count; ++n) {
+ *reinterpret_cast<f32*>(h.pool.vertexData(LayoutId::MeshInstance) + at + n * key.instanceStride) = mark + static_cast<f32>(n);
+ }
+ key.instanceCount = count;
+ key.depth = depth;
+ pushBatchDraw(h.list, h.clips, at, 0, 0, 36, key);
+}
+
+TEST_CASE("finalize: draws that each place the mesh many times merge with every record carried") {
+ Harness h;
+ const BatchDrawKey key = meshKey(5);
+ // Three draws of 3, 2 and 4 instances; depths reorder them so no two runs are adjacent in the pool.
+ pushMeshInstances(h, key, 3, 10.0f, 10.0f);
+ pushMeshInstances(h, key, 2, 20.0f, 30.0f);
+ pushMeshInstances(h, key, 4, 30.0f, 20.0f);
+
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 1);
+ const DrawCommand& cmd = h.list.command(0);
+ CHECK(cmd.instance_count == 9);
+ // Nearest first: the draw at depth 30 (marks 20, 21), then 20 (30..33), then 10 (10..12), each whole.
+ CHECK(instanceMarks(h, cmd) == std::vector<f32>{20.0f, 21.0f, 30.0f, 31.0f, 32.0f, 33.0f, 10.0f, 11.0f, 12.0f});
+}
+
/** Two mesh draws, the second differing only as `vary` says. How many draws survive. */
u32 drawsAfterMerge(const std::function<void(BatchDrawKey&, u32&)>& vary) {
Harness h;