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 mesh hands over to a cheaper one as it shrinks on screen

esenginec42cb9864cfe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82061685a..a2bb514b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,37 @@ published separately; it ships inside the editor.
### Added
+- **Level of detail: an object can hand over to a cheaper mesh once it is small
+ on screen.** A rock a hundred units away and a rock two thousand units away
+ were drawn with the same number of triangles, and at two thousand almost all of
+ them landed inside one pixel. `LODGroup` sits beside a `MeshRenderer` — the
+ renderer's own mesh stays level 0, and the group names the stand-ins.
+
+ The thresholds are fractions of the viewport HEIGHT, not distances, and that is
+ the whole design. A distance answers the same for a tower and a pebble, the
+ same at 30 degrees of field of view and at 60, and does not vary at all under
+ an orthographic camera; a screen fraction covers all three and is free of the
+ resolution besides. Each boundary carries a hysteresis band, so a camera merely
+ breathing across one does not swap the mesh every frame.
+
+ **The choice belongs to the camera, not the entity.** Two cameras in one frame
+ see one object at two sizes and may draw it at two levels; there is no
+ `currentLOD` on the entity to read or to set. Bounds come from the union of
+ every level, so what is measured does not change with what is drawn — bounds
+ read off the current mesh feed back into the choice that picked it. Culling
+ runs first, and instancing is untouched: choosing a level changes which
+ geometry a draw names and nothing else, so props sharing a level still fold
+ into one instanced call.
+
+ Measured on a receding field (`bench/lod/`): at ten thousand props, 1.91M
+ triangles and 3.5 ms of GPU become 42k and 0.27 ms, for a quarter of a
+ millisecond of selection CPU. Ten pixel/counter gates cover it, each shown red under the mistake it
+ exists to catch — a world distance tuned to pass the level gate still fails the
+ field-of-view one; bounds read off the current level still fail the level gate;
+ a level memory shared between views fails only the two-camera gate. The
+ third-person sample carries a field of 35 rocks, and `verify-third-person`
+ reads the levels the PACKAGED game chose.
+
- **An inventory of what the engine's runtime contract facts actually are.** The
`EsEventOut` hole above was not thin test coverage — the ABI compatibility
system did not know a fact lived there. Those are different severities and
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index a7ffc8819..3cad5086c 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -321,6 +321,7 @@ export default defineConfig({
collapsed: true,
items: [
{ label: 'Profiling & Diagnostics', translations: { 'zh-CN': '性能剖析与诊断' }, slug: 'performance/profiling' },
+ { label: 'Level of Detail', translations: { 'zh-CN': '细节层次(LOD)' }, slug: 'performance/level-of-detail' },
],
},
{
diff --git a/docs/astro/src/content/docs/performance/level-of-detail.mdx b/docs/astro/src/content/docs/performance/level-of-detail.mdx
new file mode 100644
index 000000000..129f96716
--- /dev/null
+++ b/docs/astro/src/content/docs/performance/level-of-detail.mdx
@@ -0,0 +1,128 @@
+---
+title: Level of Detail
+description: Swap a mesh for a cheaper stand-in as it shrinks on screen, with LODGroup — thresholds, hysteresis, and how it interacts with culling, instancing and multiple cameras.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+A rock a hundred units away and a rock two thousand units away are drawn with the
+same number of triangles, and at two thousand units almost all of them land inside
+a single pixel. **`LODGroup`** lets an object hand over to a cheaper mesh once it
+is small enough that nobody can tell — the single biggest saving available to a
+scene with many props in it.
+
+In Estella's own third-person sample, a field of 35 rocks drops from
+1.9 million triangles to 42 thousand and from 3.5 ms of GPU time to 0.27 ms at ten
+thousand props ([the numbers](#what-it-buys)).
+
+## The LODGroup component
+
+`LODGroup` sits on the **same entity as a `MeshRenderer`**. The renderer says what
+the object *is* — that mesh is level 0, the full-detail one. The group says what
+may stand in for it as it shrinks:
+
+```typescript
+world.insert(rock, MeshRenderer, { mesh: 'assets/models/rock-lod0.esmesh', lit: true });
+world.insert(rock, LODGroup, {
+ lod1: 'assets/models/rock-lod1.esmesh',
+ lod2: 'assets/models/rock-lod2.esmesh',
+ lod1Size: 0.25, // below a quarter of the screen height, lod1 takes over
+ lod2Size: 0.11, // below an eighth, lod2
+ cullSize: 0.02, // below a fiftieth, nothing is drawn at all
+ hysteresis: 0.1,
+});
+```
+
+Remove the component and the full-detail mesh comes back — nothing else about the
+renderer changes.
+
+## The sizes are fractions of the screen, not distances
+
+`lod1Size` and its siblings are the fraction of the **viewport's height** the
+object's bounds cover. `1.0` is an object exactly one screen tall; `0.02` is a
+fiftieth of one.
+
+That is deliberately not a distance, because a distance answers the same at every
+scale and through every lens:
+
+- a tower and a pebble a hundred metres away are not the same size on screen;
+- a 30° field of view shows an object twice as big as a 60° one, from the same spot;
+- an orthographic camera's answer does not change with distance at all.
+
+A screen fraction covers all three, and it is free of the resolution too — the
+same number is right on a phone and on a desktop.
+
+<Aside type="tip">
+To pick thresholds, put the camera where a level's action happens and look at the
+object. The size you want is roughly "the fraction of the window's height it
+covers"; anything under about 5% is a candidate for the coarsest mesh you have.
+</Aside>
+
+## Hysteresis — why the levels do not flicker
+
+A boundary crossed at exactly one number flips back and forth for a camera that is
+merely breathing, and a mesh swapping every frame is far more visible than the
+swap itself. `hysteresis` makes each boundary asymmetric: an object hands *down* to
+the coarser mesh at the threshold, and only comes back up once it has grown past
+it by that fraction.
+
+At the default `0.1`, a `lod1Size` of `0.20` means:
+
+- shrinking past **0.20** → level 1 takes over;
+- growing back past **0.22** → level 0 returns.
+
+Set it to `0` and you get a bare threshold, which flickers. It applies to
+`cullSize` too, so an object at the edge of visibility does not blink.
+
+## What the selection is, and is not
+
+**It belongs to the camera, not the entity.** Two cameras in one frame — a main
+view and a minimap, or a split screen — see the same object at two different sizes
+and may draw it at two different levels. There is no `currentLOD` on the entity to
+read or to set.
+
+**It is measured on the whole group's bounds.** The bounds used to choose are the
+union of every level's, so they do not change with the level being drawn. Bounds
+read off the current mesh would feed back into the choice that picked it and
+oscillate.
+
+**Culling runs first.** An object the frustum already rejected is never measured,
+so the cost is paid only for what could have been seen.
+
+**Instancing is unaffected.** Choosing a level changes which geometry a draw names
+and nothing else, so props sharing a level still fold into one instanced call.
+A field at three levels reaches the GPU as roughly three draws, not as one per prop.
+
+## Authoring rules
+
+- **Fill the slots in order** — `lod1`, then `lod2`, then `lod3`. A slot left empty
+ ends the ladder, and anything after it is never reached (the engine warns).
+- **The sizes must descend.** `lod2Size` below `lod1Size`, and so on.
+- **`cullSize: 0`** disables culling entirely, so the group is never invisible.
+- **A skinned group must share one skeleton.** Every level of a skinned mesh needs
+ the same joint count; a level that disagrees is drawn in its bind pose, and the
+ engine says so.
+
+## What it buys
+
+Measured on a receding field of props, 512×512, WebGL2:
+
+| props | triangles | GPU |
+|---|---|---|
+| 1 000, always full detail | 195 776 | 0.505 ms |
+| 1 000, with `LODGroup` | 4 248 | 0.116 ms |
+| 10 000, always full detail | 1 912 960 | 3.595 ms |
+| 10 000, with `LODGroup` | 42 392 | 0.27 ms |
+
+Selection costs 0.2–0.3 ms of CPU per ten thousand props, which is the trade:
+CPU spent choosing, GPU saved drawing. The exchange rate improves with the count,
+which is the point — it is the mechanism that decides whether a field of ten
+thousand props is shippable at all.
+
+## What this is not
+
+`LODGroup` is about **one object at different sizes**. It is not a streaming
+system: every level's mesh is resident, nothing is loaded or unloaded, and an
+object that is `cullSize`-small is simply not drawn rather than removed from the
+world. Combining distant objects into one merged proxy (HLOD) and loading a world
+in pieces are separate concerns.
diff --git a/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx b/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx
new file mode 100644
index 000000000..0c77b325e
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/performance/level-of-detail.mdx
@@ -0,0 +1,106 @@
+---
+title: 细节层次(LOD)
+description: 用 LODGroup 在物体屏幕占比变小时换成更便宜的替身网格 —— 阈值、迟滞,以及它与剔除、实例化和多相机的关系。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+一块一百单位外的石头和一块两千单位外的石头,现在用同样多的三角形绘制;而在两千单位外,
+它们几乎全部落进同一个像素里。**`LODGroup`** 让一个物体在小到没人分辨得出来时,交给
+更便宜的网格去画 —— 这是道具密集的场景里最大的一笔节省。
+
+在 Estella 自带的第三人称示例里,一片 35 块石头的场地就用上了它;在一万个道具的规模上,
+三角形从 191 万降到 4.2 万,GPU 时间从 3.5 ms 降到 0.27 ms([数字在下面](#这笔交易换来了什么))。
+
+## LODGroup 组件
+
+`LODGroup` 挂在**和 `MeshRenderer` 同一个实体**上。渲染器说这个物体**是什么** ——
+那个网格就是 level 0,即最精细的一级;组件说的是它变小之后谁可以顶替它:
+
+```typescript
+world.insert(rock, MeshRenderer, { mesh: 'assets/models/rock-lod0.esmesh', lit: true });
+world.insert(rock, LODGroup, {
+ lod1: 'assets/models/rock-lod1.esmesh',
+ lod2: 'assets/models/rock-lod2.esmesh',
+ lod1Size: 0.25, // 小于屏幕高度的四分之一 → 换 lod1
+ lod2Size: 0.11, // 小于八分之一 → 换 lod2
+ cullSize: 0.02, // 小于五十分之一 → 干脆不画
+ hysteresis: 0.1,
+});
+```
+
+把这个组件去掉,最精细的网格就回来了 —— 渲染器的其他部分一点没变。
+
+## 这些尺寸是屏幕占比,不是距离
+
+`lod1Size` 和它的兄弟们,是物体包围体覆盖**视口高度**的比例。`1.0` 表示物体正好一屏高,
+`0.02` 表示五十分之一屏高。
+
+它刻意不是距离,因为距离在不同尺度、不同镜头下给的是同一个答案:
+
+- 一百米外的高塔和一颗石子,在屏幕上不是一个大小;
+- 同一个位置,30° 视场看到的物体是 60° 的两倍大;
+- 正交相机的答案根本不随距离改变。
+
+屏幕占比同时覆盖这三件事,而且与分辨率无关 —— 同一个数字在手机上和桌面上都对。
+
+<Aside type="tip">
+挑阈值的方法:把相机放在关卡里真正发生动作的位置,看着那个物体。你要的数字大致就是
+「它占窗口高度的几分之几」;低于 5% 左右的,就是最粗一级网格的候选。
+</Aside>
+
+## 迟滞 —— 为什么级别不会闪
+
+一条只用一个数字划的边界,会因为相机的轻微呼吸而来回翻转;而每帧都在换网格,远比换本身
+更显眼。`hysteresis` 让每条边界变得不对称:物体在阈值处**往下**交给更粗的网格,但要长回
+到超出阈值那么一个比例之后,才会换回精细的一级。
+
+默认 `0.1` 时,`lod1Size = 0.20` 的含义是:
+
+- 缩小穿过 **0.20** → level 1 接手;
+- 重新长过 **0.22** → level 0 才回来。
+
+把它设成 `0` 就是一条裸阈值,会闪。它同样作用于 `cullSize`,所以在可见边缘的物体不会眨眼。
+
+## 这个选择是什么、不是什么
+
+**它属于相机,不属于实体。** 同一帧里的两个相机 —— 主视角和小地图,或者分屏 ——
+看到的是同一个物体的两个尺寸,可以画成两个不同的级别。实体上没有 `currentLOD`
+可读、也没有可写。
+
+**它是在整组的包围体上量的。** 用来做判断的包围体是所有级别的并集,所以它不随当前
+画的是哪一级而改变。若按当前网格取包围体,就会反过来影响挑出它的那个判断,进而振荡。
+
+**剔除先跑。** 视锥已经拒绝掉的物体根本不会被测量,所以这份开销只花在可能被看见的东西上。
+
+**实例化不受影响。** 选级只改变一次 draw 引用哪份几何,别的都不变,所以同一级的道具照旧
+合并成一次 instanced draw。三个级别的一片场地到达 GPU 时大约是三次 draw,而不是每个道具一次。
+
+## 编辑规则
+
+- **槽位按顺序填** —— 先 `lod1`,再 `lod2`,再 `lod3`。留空的槽位就是梯子的终点,它后面的
+ 一律到不了(引擎会告警)。
+- **尺寸必须递减。** `lod2Size` 小于 `lod1Size`,依此类推。
+- **`cullSize: 0`** 完全关掉剔除,于是这一组永远不会消失。
+- **蒙皮的一组必须共用一副骨架。** 蒙皮网格的每一级都要有相同的关节数;对不上的那一级会
+ 画成绑定姿势,引擎会说出来。
+
+## 这笔交易换来了什么
+
+在一片纵深排布的道具场地上实测,512×512,WebGL2:
+
+| 道具数 | 三角形 | GPU |
+|---|---|---|
+| 1 000,始终最高精度 | 195 776 | 0.505 ms |
+| 1 000,带 `LODGroup` | 4 248 | 0.116 ms |
+| 10 000,始终最高精度 | 1 912 960 | 3.595 ms |
+| 10 000,带 `LODGroup` | 42 392 | 0.27 ms |
+
+每一万个道具的选级大约花掉 0.2–0.3 ms 的 CPU,这就是那笔交易:花 CPU 去挑,省 GPU 去画。
+数量越大,汇率越划算 —— 这正是重点,它决定了一万个道具的场地到底能不能发出去。
+
+## 它不做什么
+
+`LODGroup` 讲的是**同一个物体在不同尺寸下**的事。它不是流式加载:每一级的网格都常驻,
+不会加载也不会卸载;小到 `cullSize` 以下的物体只是不画,并没有从世界里移走。
+把远处的物体合并成一个代理(HLOD),以及把世界分块加载,都是另外的题目。
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 1e09c3432..d98645441 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -75,6 +75,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
PostProcessVolume: { category: 'graphics', summary: 'A stack of full-screen effects (bloom, vignette, colour grading) applied after the scene is drawn.', doc: 'graphics/post-processing', anchor: 'using-a-postprocessvolume', anchorZh: '使用-postprocessvolume' },
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
+ LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
Video: { category: 'graphics', summary: 'Plays a video stream onto a surface in the world or the UI.', doc: 'graphics/video', anchor: 'the-video-component', anchorZh: 'video-组件' },
// ── UI ─────────────────────────────────────────────────────────────────────
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 5d4ed1124..76d098b53 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1833,6 +1833,72 @@
}
]
},
+ {
+ "name": "LODGroup",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "lod1",
+ "type": "Asset<mesh>",
+ "default": "none",
+ "doc": "Geometry drawn below the LOD 1 screen size."
+ },
+ {
+ "key": "lod2",
+ "type": "Asset<mesh>",
+ "default": "none",
+ "doc": "Geometry drawn below the LOD 2 screen size."
+ },
+ {
+ "key": "lod3",
+ "type": "Asset<mesh>",
+ "default": "none",
+ "doc": "Geometry drawn below the LOD 3 screen size."
+ },
+ {
+ "key": "lod1Size",
+ "type": "number",
+ "default": "0.5",
+ "doc": "Screen height fraction below which LOD 1 takes over.",
+ "range": "0–1"
+ },
+ {
+ "key": "lod2Size",
+ "type": "number",
+ "default": "0.25",
+ "doc": "Screen height fraction below which LOD 2 takes over.",
+ "range": "0–1"
+ },
+ {
+ "key": "lod3Size",
+ "type": "number",
+ "default": "0.1",
+ "doc": "Screen height fraction below which LOD 3 takes over.",
+ "range": "0–1"
+ },
+ {
+ "key": "cullSize",
+ "type": "number",
+ "default": "0.02",
+ "doc": "Screen height fraction below which nothing is drawn (0 = never).",
+ "range": "0–1"
+ },
+ {
+ "key": "hysteresis",
+ "type": "number",
+ "default": "0.1",
+ "doc": "Extra fraction to grow past a threshold before the finer level returns.",
+ "range": "0–1",
+ "advanced": true
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Off: the MeshRenderer's own mesh is always drawn."
+ }
+ ]
+ },
{
"name": "Light",
"source": "cpp",
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 8a80eb4d8..96667798d 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -28,6 +28,7 @@ addDraggable: (entity: Entity, component: Draggable) => void
addDragonBonesAnimation: (entity: Entity, component: DragonBonesAnimation) => void
addFlexContainer: (entity: Entity, component: FlexContainer) => void
addInteractable: (entity: Entity, component: Interactable) => void
+addLODGroup: (entity: Entity, component: LODGroup) => void
addLight: (entity: Entity, component: Light) => void
addMeshCollider3D: (entity: Entity, component: MeshCollider3D) => void
addMeshRenderer: (entity: Entity, component: MeshRenderer) => void
@@ -71,6 +72,7 @@ getDraggable: (entity: Entity) => Draggable
getDragonBonesAnimation: (entity: Entity) => DragonBonesAnimation
getFlexContainer: (entity: Entity) => FlexContainer
getInteractable: (entity: Entity) => Interactable
+getLODGroup: (entity: Entity) => LODGroup
getLight: (entity: Entity) => Light
getMeshCollider3D: (entity: Entity) => MeshCollider3D
getMeshRenderer: (entity: Entity) => MeshRenderer
@@ -110,6 +112,7 @@ hasDraggable: (entity: Entity) => boolean
hasDragonBonesAnimation: (entity: Entity) => boolean
hasFlexContainer: (entity: Entity) => boolean
hasInteractable: (entity: Entity) => boolean
+hasLODGroup: (entity: Entity) => boolean
hasLight: (entity: Entity) => boolean
hasMeshCollider3D: (entity: Entity) => boolean
hasMeshRenderer: (entity: Entity) => boolean
@@ -150,6 +153,7 @@ removeDraggable: (entity: Entity) => void
removeDragonBonesAnimation: (entity: Entity) => void
removeFlexContainer: (entity: Entity) => void
removeInteractable: (entity: Entity) => void
+removeLODGroup: (entity: Entity) => void
removeLight: (entity: Entity) => void
removeMeshCollider3D: (entity: Entity) => void
removeMeshRenderer: (entity: Entity) => void
@@ -406,6 +410,7 @@ renderer_setDepthLayers: ((mask: number) => void) | undefined
renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setStage: (stage: number) => void
renderer_setTextureParams: (textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number) => void
+renderer_setViewId: ((view: number) => void) | undefined
renderer_setViewport: (x: number, y: number, w: number, h: number) => void
renderer_setYSortLayers: ((mask: number) => void) | undefined
renderer_submitAll: (registry: CppRegistry, vpX: number, vpY: number, vpW: number, vpH: number) => void
diff --git a/sdk/src/ecs/bridge/nativeBindings.ts b/sdk/src/ecs/bridge/nativeBindings.ts
index 7e6f93dad..f96dcd1ce 100644
--- a/sdk/src/ecs/bridge/nativeBindings.ts
+++ b/sdk/src/ecs/bridge/nativeBindings.ts
@@ -182,6 +182,8 @@ export const RENDERER_OPTIONAL_BINDINGS = {
beginScreenOverlay: 'es_renderer_beginScreenOverlay',
submitScreenOverlay: 'es_renderer_submitScreenOverlay',
endScreenOverlay: 'es_renderer_endScreenOverlay',
+ /** The view a collect looks from; hosts predating it share one LOD memory. */
+ setViewId: 'es_renderer_setViewId',
} as const;
/** Whether the host bound the whole frame surface — the gate for the SDK driving
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 8f00f3cf1..351dbe593 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -164,6 +164,7 @@ export interface NativeEngineApi {
renderer_setEntityDrawOrder?(registry: unknown, entitiesPtr: number, count: number): void;
renderer_setStage?(stage: number): void;
renderer_setTextureParams?(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void;
+ renderer_setViewId?(view: number): void;
renderer_setViewport?(x: number, y: number, w: number, h: number): void;
renderer_setYSortLayers?(mask: number): void;
renderer_submitAll?(registry: unknown, vpX: number, vpY: number, vpW: number, vpH: number): void;
@@ -409,6 +410,7 @@ export function createNativeEngineApi(
bind('renderer_setEntityDrawOrder', 'es_renderer_setEntityDrawOrder', true);
bind('renderer_setStage', 'es_renderer_setStage', false);
bind('renderer_setTextureParams', 'es_renderer_setTextureParams', false);
+ bind('renderer_setViewId', 'es_renderer_setViewId', false);
bind('renderer_setViewport', 'es_renderer_setViewport', false);
bind('renderer_setYSortLayers', 'es_renderer_setYSortLayers', false);
bind('renderer_submitAll', 'es_renderer_submitAll', true);
diff --git a/sdk/src/ecs/bridge/nativeRenderer.ts b/sdk/src/ecs/bridge/nativeRenderer.ts
index e4a4f65ad..8b5bc9629 100644
--- a/sdk/src/ecs/bridge/nativeRenderer.ts
+++ b/sdk/src/ecs/bridge/nativeRenderer.ts
@@ -111,6 +111,10 @@ export function createNativeRendererBackend(
const fn = scope[RENDERER_OPTIONAL_BINDINGS.setCullingMask];
if (typeof fn === 'function') (fn as (m: number) => void)(mask >>> 0);
},
+ setViewId: (view): void => {
+ const fn = scope[RENDERER_OPTIONAL_BINDINGS.setViewId];
+ if (typeof fn === 'function') (fn as (v: number) => void)(view >>> 0);
+ },
getStats: (): RenderStats => {
const read = (name: string): number => {
const fn = scope[name];
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index aa9591c43..f98e251ac 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -741,6 +741,62 @@ export function createInteractableData(): InteractablePtrData {
};
}
+export interface LODGroupPtrData {
+ lod1: number;
+ lod2: number;
+ lod3: number;
+ lod1Size: number;
+ lod2Size: number;
+ lod3Size: number;
+ cullSize: number;
+ hysteresis: number;
+ enabled: boolean;
+}
+
+export function fillLODGroup(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: LODGroupPtrData,
+): void {
+ out.lod1 = u32[ptr >> 2];
+ out.lod2 = u32[(ptr + 4) >> 2];
+ out.lod3 = u32[(ptr + 8) >> 2];
+ out.lod1Size = f32[(ptr + 12) >> 2];
+ out.lod2Size = f32[(ptr + 16) >> 2];
+ out.lod3Size = f32[(ptr + 20) >> 2];
+ out.cullSize = f32[(ptr + 24) >> 2];
+ out.hysteresis = f32[(ptr + 28) >> 2];
+ out.enabled = u8[ptr + 32] !== 0;
+}
+
+export function writeLODGroup(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: LODGroupPtrData,
+): void {
+ u32[ptr >> 2] = data.lod1;
+ u32[(ptr + 4) >> 2] = data.lod2;
+ u32[(ptr + 8) >> 2] = data.lod3;
+ f32[(ptr + 12) >> 2] = data.lod1Size;
+ f32[(ptr + 16) >> 2] = data.lod2Size;
+ f32[(ptr + 20) >> 2] = data.lod3Size;
+ f32[(ptr + 24) >> 2] = data.cullSize;
+ f32[(ptr + 28) >> 2] = data.hysteresis;
+ u8[ptr + 32] = data.enabled ? 1 : 0;
+}
+
+export function createLODGroupData(): LODGroupPtrData {
+ return {
+ lod1: 0,
+ lod2: 0,
+ lod3: 0,
+ lod1Size: 0,
+ lod2Size: 0,
+ lod3Size: 0,
+ cullSize: 0,
+ hysteresis: 0,
+ enabled: false,
+ };
+}
+
export interface LightPtrData {
type: number;
color: Color;
@@ -2162,6 +2218,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
DragonBonesAnimation: { fill: fillDragonBonesAnimation, write: writeDragonBonesAnimation, create: createDragonBonesAnimationData },
FlexContainer: { fill: fillFlexContainer, write: writeFlexContainer, create: createFlexContainerData },
Interactable: { fill: fillInteractable, write: writeInteractable, create: createInteractableData },
+ LODGroup: { fill: fillLODGroup, write: writeLODGroup, create: createLODGroupData },
Light: { fill: fillLight, write: writeLight, create: createLightData },
MeshCollider3D: { fill: fillMeshCollider3D, write: writeMeshCollider3D, create: createMeshCollider3DData },
MeshRenderer: { fill: fillMeshRenderer, write: writeMeshRenderer, create: createMeshRendererData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 6e4893a58..0894b0168 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 = 'fac7d5103ea562aa';
+export const ABI_LAYOUT_HASH = '7756afcaec734824';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -414,6 +414,34 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: [],
},
+ LODGroup: {
+ defaults: {
+ lod1: 0,
+ lod2: 0,
+ lod3: 0,
+ lod1Size: 0.5,
+ lod2Size: 0.25,
+ lod3Size: 0.1,
+ cullSize: 0.02,
+ hysteresis: 0.1,
+ enabled: true,
+ },
+ assetFields: [{ field: 'lod1', type: 'mesh' as AssetFieldType }, { field: 'lod2', type: 'mesh' as AssetFieldType }, { field: 'lod3', type: 'mesh' as AssetFieldType }],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ lod1: { tooltip: "Geometry drawn below the LOD 1 screen size." },
+ lod2: { tooltip: "Geometry drawn below the LOD 2 screen size." },
+ lod3: { tooltip: "Geometry drawn below the LOD 3 screen size." },
+ lod1Size: { min: 0, max: 1, tooltip: "Screen height fraction below which LOD 1 takes over." },
+ lod2Size: { min: 0, max: 1, tooltip: "Screen height fraction below which LOD 2 takes over." },
+ lod3Size: { min: 0, max: 1, tooltip: "Screen height fraction below which LOD 3 takes over." },
+ cullSize: { min: 0, max: 1, tooltip: "Screen height fraction below which nothing is drawn (0 = never)." },
+ hysteresis: { min: 0, max: 1, tooltip: "Extra fraction to grow past a threshold before the finer level returns.", advanced: true },
+ enabled: { tooltip: "Off: the MeshRenderer's own mesh is always drawn." },
+ },
+ },
Light: {
defaults: {
type: 0,
@@ -1239,6 +1267,24 @@ export interface InteractableData {
raycastTarget: boolean;
}
+/**
+ * The fields of the engine's `LODGroup` component, generated from
+ * the C++ struct so the two shapes cannot drift.
+ *
+ * @beta
+ */
+export interface LODGroupData {
+ lod1: number;
+ lod2: number;
+ lod3: number;
+ lod1Size: number;
+ lod2Size: number;
+ lod3Size: number;
+ cullSize: number;
+ hysteresis: number;
+ enabled: boolean;
+}
+
export interface LightData {
type: LightType;
color: Color;
diff --git a/sdk/src/render/renderPipeline.ts b/sdk/src/render/renderPipeline.ts
index bb4bf980d..993af943e 100644
--- a/sdk/src/render/renderPipeline.ts
+++ b/sdk/src/render/renderPipeline.ts
@@ -197,6 +197,7 @@ export class RenderPipeline {
Renderer.begin(viewProjection, 0, /*clear color+depth*/ 3, params.clearColor);
// The mask is sticky in the draw list; this path has no camera to own one.
Renderer.setCullingMask(0xFFFFFFFF);
+ Renderer.setViewId(0);
this.submitScene(registry, viewProjection, { x: 0, y: 0, w: width, h: height }, elapsed);
Renderer.end();
}
@@ -243,6 +244,9 @@ export class RenderPipeline {
Renderer.begin(viewProjection, params.renderTarget ?? 0, clearFlags, params.clearColor, scene);
// Set after begin (which clears the draw list) and before the collect it gates.
Renderer.setCullingMask(params.cullingMask ?? 0xFFFFFFFF);
+ // The camera IS the view: a level picked from how big something looks is
+ // this camera's answer, and the next camera must be free to disagree.
+ Renderer.setViewId(cameraEntity ?? 0);
this.submitScene(registry, viewProjection, scene, elapsed);
Renderer.end();
diff --git a/sdk/src/render/renderer.ts b/sdk/src/render/renderer.ts
index c1211da7e..42b3bc6a5 100644
--- a/sdk/src/render/renderer.ts
+++ b/sdk/src/render/renderer.ts
@@ -70,6 +70,7 @@ export interface RendererBackend {
setYSortLayers(mask: number): void;
setDepthLayers(mask: number): void;
setCullingMask(mask: number): void;
+ setViewId(view: number): void;
getStats(): RenderStats;
}
@@ -160,6 +161,7 @@ function wasmBackend(m: ESEngineModule): RendererBackend {
setYSortLayers: (mask) => m.renderer_setYSortLayers?.(mask >>> 0),
setDepthLayers: (mask) => m.renderer_setDepthLayers?.(mask >>> 0),
setCullingMask: (mask) => m.renderer_setCullingMask?.(mask >>> 0),
+ setViewId: (view) => m.renderer_setViewId?.(view >>> 0),
getStats: () => ({
drawCalls: m.renderer_getDrawCalls(),
triangles: m.renderer_getTriangles(),
@@ -484,6 +486,15 @@ export const Renderer = {
backend?.setCullingMask(mask);
},
+ /**
+ * Names the view the NEXT collect looks from — the camera entity, so a level
+ * chosen by how big something looks is remembered per camera. Set per camera
+ * before submitting it; 0 is the shared default view.
+ */
+ setViewId(view: number): void {
+ backend?.setViewId(view);
+ },
+
setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void {
module?.renderer_setTextureParams?.(textureId, minFilter, magFilter, wrapS, wrapT);
},
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 64f1996fb..8c05db531 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -530,6 +530,7 @@ export interface ESEngineModule {
renderer_setYSortLayers?(mask: number): void;
renderer_setDepthLayers?(mask: number): void;
renderer_setCullingMask?(mask: number): void;
+ renderer_setViewId?(view: number): void;
renderer_setColorSpace?(linear: number): void;
/** Reseed the engine's randomness so a run reproduces (core/RandomSource.hpp). */
engine_setRandomSeed?(seed: number): void;
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 6edcf426a..50d9e09f0 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -210,6 +210,20 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'raycastTarget', type: 'bool', offset: 2 },
],
},
+ LODGroup: {
+ ptrFn: 'getLODGroupPtr',
+ fields: [
+ { name: 'lod1', type: 'u32', offset: 0 },
+ { name: 'lod2', type: 'u32', offset: 4 },
+ { name: 'lod3', type: 'u32', offset: 8 },
+ { name: 'lod1Size', type: 'f32', offset: 12 },
+ { name: 'lod2Size', type: 'f32', offset: 16 },
+ { name: 'lod3Size', type: 'f32', offset: 20 },
+ { name: 'cullSize', type: 'f32', offset: 24 },
+ { name: 'hysteresis', type: 'f32', offset: 28 },
+ { name: 'enabled', type: 'bool', offset: 32 },
+ ],
+ },
Light: {
ptrFn: 'getLightPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index f594ebd00..f549c58b4 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -517,6 +517,18 @@ export interface Interactable {
raycastTarget: boolean;
}
+export interface LODGroup {
+ lod1: number;
+ lod2: number;
+ lod3: number;
+ lod1Size: number;
+ lod2Size: number;
+ lod3Size: number;
+ cullSize: number;
+ hysteresis: number;
+ enabled: boolean;
+}
+
export interface Light {
type: number;
color: Vec4;
@@ -902,6 +914,10 @@ export interface Registry {
getInteractable(entity: Entity): Interactable;
addInteractable(entity: Entity, component: Interactable): void;
removeInteractable(entity: Entity): void;
+ hasLODGroup(entity: Entity): boolean;
+ getLODGroup(entity: Entity): LODGroup;
+ addLODGroup(entity: Entity, component: LODGroup): void;
+ removeLODGroup(entity: Entity): void;
hasLight(entity: Entity): boolean;
getLight(entity: Entity): Light;
addLight(entity: Entity, component: Light): void;
@@ -1027,6 +1043,7 @@ export interface ESEngineModule {
DragonBonesAnimation: new () => DragonBonesAnimation;
FlexContainer: new () => FlexContainer;
Interactable: new () => Interactable;
+ LODGroup: new () => LODGroup;
Light: new () => Light;
MeshCollider3D: new () => MeshCollider3D;
MeshRenderer: new () => MeshRenderer;
diff --git a/sdk/tests/camera-render-order.test.ts b/sdk/tests/camera-render-order.test.ts
index 80cc84490..06fd5e24b 100644
--- a/sdk/tests/camera-render-order.test.ts
+++ b/sdk/tests/camera-render-order.test.ts
@@ -63,6 +63,7 @@ describe('render order: transforms resolve before cameras are read', () => {
beginScreenOverlay: () => {}, submitScreenOverlay: () => {}, endScreenOverlay: () => {},
setStage: () => {}, setViewport: () => {},
setYSortLayers: () => {}, setDepthLayers: () => {}, setCullingMask: () => {},
+ setViewId: () => {},
getStats: () => ({ drawCalls: 0, triangles: 0, sprites: 0, text: 0, skeletal: 0, meshes: 0, culled: 0 }),
};
}
diff --git a/sdk/tests/render-present.test.ts b/sdk/tests/render-present.test.ts
index 610d98f2f..5dfc0f0a0 100644
--- a/sdk/tests/render-present.test.ts
+++ b/sdk/tests/render-present.test.ts
@@ -13,7 +13,8 @@ vi.mock('../src/render/renderer', () => ({
Renderer: {
init: vi.fn(), resize: vi.fn(), begin: vi.fn(), flush: vi.fn(), end: vi.fn(),
submitAll: vi.fn(), setStage: vi.fn(), setClearColor: vi.fn(),
- setViewport: vi.fn(), setCullingMask: vi.fn(), updateTransforms: vi.fn(),
+ setViewport: vi.fn(), setCullingMask: vi.fn(), setViewId: vi.fn(),
+ updateTransforms: vi.fn(),
beginFrame: vi.fn(),
},
}));
diff --git a/sdk/tests/renderPipeline.test.ts b/sdk/tests/renderPipeline.test.ts
index d17424ebf..fef487035 100644
--- a/sdk/tests/renderPipeline.test.ts
+++ b/sdk/tests/renderPipeline.test.ts
@@ -19,6 +19,7 @@ vi.mock('../src/render/renderer', () => ({
setClearColor: vi.fn(),
setViewport: vi.fn(),
setCullingMask: vi.fn(),
+ setViewId: vi.fn(),
updateTransforms: vi.fn(),
beginFrame: vi.fn(),
},
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index 597b7a8e6..effd511db 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -19,6 +19,7 @@
#include "esengine/ecs/components/DragonBonesAnimation.hpp"
#include "esengine/ecs/components/FlexContainer.hpp"
#include "esengine/ecs/components/Interactable.hpp"
+#include "esengine/ecs/components/LODGroup.hpp"
#include "esengine/ecs/components/Light.hpp"
#include "esengine/ecs/components/MeshRenderer.hpp"
#include "esengine/ecs/components/ParticleEmitter.hpp"
@@ -134,6 +135,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::Interactable>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "LODGroup") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::LODGroup>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "Light") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::Light>(Entity::fromRaw(raw));
@@ -333,6 +339,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::Interactable>());
};
}
+ if (std::strcmp(name, "LODGroup") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::LODGroup>());
+ };
+ }
if (std::strcmp(name, "Light") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::Light>());
@@ -472,6 +483,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "DragonBonesAnimation") == 0) return true;
if (std::strcmp(name, "FlexContainer") == 0) return true;
if (std::strcmp(name, "Interactable") == 0) return true;
+ if (std::strcmp(name, "LODGroup") == 0) return true;
if (std::strcmp(name, "Light") == 0) return true;
if (std::strcmp(name, "MeshCollider3D") == 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 4fd2cda34..d53c5c6ef 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 0xa3962ff88387fdfcULL
-#define ES_ENGINE_ABI_DIGEST_64 0xaa8849ed8d31d9a0ULL
+#define ES_ENGINE_ABI_DIGEST_32 0x6aac26f71f4dcdf4ULL
+#define ES_ENGINE_ABI_DIGEST_64 0xa8244cac94602de0ULL
#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 a2ab3447d..cc316121b 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 4dea57b14e10801b
+ * @schema_hash 723eabb232b5334a
*/
-#define ES_EDITOR_API_SCHEMA_HASH "4dea57b14e10801b"
+#define ES_EDITOR_API_SCHEMA_HASH "723eabb232b5334a"
#include <emscripten/bind.h>
#include <string>
@@ -22,6 +22,7 @@
#include "../ecs/components/FlexContainer.hpp"
#include "../ecs/components/Hierarchy.hpp"
#include "../ecs/components/Interactable.hpp"
+#include "../ecs/components/LODGroup.hpp"
#include "../ecs/components/Light.hpp"
#include "../ecs/components/MeshRenderer.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
@@ -76,6 +77,7 @@ std::vector<std::string> editor_getComponentNames() {
"DragonBonesAnimation",
"FlexContainer",
"Interactable",
+ "LODGroup",
"Light",
"MeshCollider3D",
"MeshRenderer",
@@ -302,6 +304,18 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"blockRaycast","type":"bool","group":"Interactable"},
{"key":"raycastTarget","type":"bool","group":"Interactable"}
])JSON";
+ } else if (name == "LODGroup") {
+ return R"JSON([
+ {"key":"lod1","type":"asset","group":"LODGroup"},
+ {"key":"lod2","type":"asset","group":"LODGroup"},
+ {"key":"lod3","type":"asset","group":"LODGroup"},
+ {"key":"lod1Size","type":"float","group":"LODGroup"},
+ {"key":"lod2Size","type":"float","group":"LODGroup"},
+ {"key":"lod3Size","type":"float","group":"LODGroup"},
+ {"key":"cullSize","type":"float","group":"LODGroup"},
+ {"key":"hysteresis","type":"float","group":"LODGroup"},
+ {"key":"enabled","type":"bool","group":"LODGroup"}
+ ])JSON";
} else if (name == "Light") {
return R"JSON([
{"key":"type","type":"int","group":"Light"},
@@ -756,6 +770,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "Interactable") {
if (!reg.has<esengine::ecs::Interactable>(entity)) reg.emplace<esengine::ecs::Interactable>(entity);
return true;
+ } else if (name == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) reg.emplace<esengine::ecs::LODGroup>(entity);
+ return true;
} else if (name == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) reg.emplace<esengine::ecs::Light>(entity);
return true;
@@ -868,6 +885,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::FlexContainer>(entity)) { reg.remove<esengine::ecs::FlexContainer>(entity); return true; }
} else if (name == "Interactable") {
if (reg.has<esengine::ecs::Interactable>(entity)) { reg.remove<esengine::ecs::Interactable>(entity); return true; }
+ } else if (name == "LODGroup") {
+ if (reg.has<esengine::ecs::LODGroup>(entity)) { reg.remove<esengine::ecs::LODGroup>(entity); return true; }
} else if (name == "Light") {
if (reg.has<esengine::ecs::Light>(entity)) { reg.remove<esengine::ecs::Light>(entity); return true; }
} else if (name == "MeshCollider3D") {
@@ -938,6 +957,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "DragonBonesAnimation") return reg.has<esengine::ecs::DragonBonesAnimation>(entity);
if (name == "FlexContainer") return reg.has<esengine::ecs::FlexContainer>(entity);
if (name == "Interactable") return reg.has<esengine::ecs::Interactable>(entity);
+ if (name == "LODGroup") return reg.has<esengine::ecs::LODGroup>(entity);
if (name == "Light") return reg.has<esengine::ecs::Light>(entity);
if (name == "MeshCollider3D") return reg.has<esengine::ecs::MeshCollider3D>(entity);
if (name == "MeshRenderer") return reg.has<esengine::ecs::MeshRenderer>(entity);
@@ -986,6 +1006,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::DragonBonesAnimation>(entity)) result.push_back("DragonBonesAnimation");
if (reg.has<esengine::ecs::FlexContainer>(entity)) result.push_back("FlexContainer");
if (reg.has<esengine::ecs::Interactable>(entity)) result.push_back("Interactable");
+ if (reg.has<esengine::ecs::LODGroup>(entity)) result.push_back("LODGroup");
if (reg.has<esengine::ecs::Light>(entity)) result.push_back("Light");
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) result.push_back("MeshCollider3D");
if (reg.has<esengine::ecs::MeshRenderer>(entity)) result.push_back("MeshRenderer");
@@ -1171,6 +1192,16 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "padding.bottom") { c.padding.bottom = value; }
else { return false; }
return true;
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "lod1Size") { c.lod1Size = value; }
+ else if (field == "lod2Size") { c.lod2Size = value; }
+ else if (field == "lod3Size") { c.lod3Size = value; }
+ else if (field == "cullSize") { c.cullSize = value; }
+ else if (field == "hysteresis") { c.hysteresis = value; }
+ else { return false; }
+ return true;
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
auto& c = reg.get<esengine::ecs::Light>(entity);
@@ -1637,6 +1668,14 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "padding.top") { return c.padding.top; }
else if (field == "padding.right") { return c.padding.right; }
else if (field == "padding.bottom") { return c.padding.bottom; }
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "lod1Size") { return c.lod1Size; }
+ else if (field == "lod2Size") { return c.lod2Size; }
+ else if (field == "lod3Size") { return c.lod3Size; }
+ else if (field == "cullSize") { return c.cullSize; }
+ else if (field == "hysteresis") { return c.hysteresis; }
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::Light>(entity);
@@ -1996,6 +2035,14 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "alignContent") { c.alignContent = static_cast<AlignContent>(value); }
else { return false; }
return true;
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "lod1") { c.lod1 = resource::MeshHandle(static_cast<u32>(value)); }
+ else if (field == "lod2") { c.lod2 = resource::MeshHandle(static_cast<u32>(value)); }
+ else if (field == "lod3") { c.lod3 = resource::MeshHandle(static_cast<u32>(value)); }
+ else { return false; }
+ return true;
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
auto& c = reg.get<esengine::ecs::Light>(entity);
@@ -2210,6 +2257,12 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
else if (field == "justifyContent") { return static_cast<i32>(c.justifyContent); }
else if (field == "alignItems") { return static_cast<i32>(c.alignItems); }
else if (field == "alignContent") { return static_cast<i32>(c.alignContent); }
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "lod1") { return static_cast<i32>(c.lod1.id()); }
+ else if (field == "lod2") { return static_cast<i32>(c.lod2.id()); }
+ else if (field == "lod3") { return static_cast<i32>(c.lod3.id()); }
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::Light>(entity);
@@ -2425,6 +2478,12 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "raycastTarget") { c.raycastTarget = value; }
else { return false; }
return true;
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
auto& c = reg.get<esengine::ecs::Light>(entity);
@@ -2645,6 +2704,10 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "enabled") { return c.enabled; }
else if (field == "blockRaycast") { return c.blockRaycast; }
else if (field == "raycastTarget") { return c.raycastTarget; }
+ } else if (comp == "LODGroup") {
+ if (!reg.has<esengine::ecs::LODGroup>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::LODGroup>(entity);
+ if (field == "enabled") { return c.enabled; }
} else if (comp == "Light") {
if (!reg.has<esengine::ecs::Light>(entity)) return false;
const auto& c = reg.get<esengine::ecs::Light>(entity);
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 764af6419..1cde28c47 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -775,6 +775,12 @@ void renderer_setCullingMask(u32 mask) {
if (auto* frame = g_renderFrame) frame->setCullingMask(mask);
}
+// A camera's own identity, which is what makes a LOD level the VIEW's answer and
+// not the entity's: two cameras looking at one object may settle on two levels.
+void renderer_setViewId(u32 view) {
+ if (auto* frame = g_renderFrame) frame->setViewId(view);
+}
+
void renderer_setColorSpace(u32 linear) {
// Valid pre-init: the global reaches every later shader compile, and
// RenderFrame::init adopts it. A live frame applies immediately (editor
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 4b7f6e745..e574578d8 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -146,6 +146,9 @@ void renderer_setYSortLayers(u32 mask);
void renderer_setDepthLayers(u32 mask);
/** Sorting layers the next collect draws (bit i = layer i). Set per camera. */
void renderer_setCullingMask(u32 mask);
+/** Names the view the next collect looks from, which its LOD levels are remembered
+ * under. Set per camera, before renderer_submitAll; 0 = the shared default view. */
+void renderer_setViewId(u32 view);
/** Project colorSpace: 1 = linear-light rendering (set before shaders compile). */
void renderer_setColorSpace(u32 linear);
void renderer_diagnose();
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 927e75df3..90de3d552 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -22,6 +22,7 @@
#include "../ecs/components/FlexContainer.hpp"
#include "../ecs/components/Hierarchy.hpp"
#include "../ecs/components/Interactable.hpp"
+#include "../ecs/components/LODGroup.hpp"
#include "../ecs/components/Light.hpp"
#include "../ecs/components/MeshRenderer.hpp"
#include "../ecs/components/ParticleEmitter.hpp"
@@ -523,6 +524,50 @@ FlexContainerJS flexcontainerToJS(const esengine::ecs::FlexContainer& c) {
return js;
}
+struct LODGroupJS {
+ u32 lod1;
+ u32 lod2;
+ u32 lod3;
+ f32 lod1Size;
+ f32 lod2Size;
+ f32 lod3Size;
+ f32 cullSize;
+ f32 hysteresis;
+ bool enabled;
+};
+
+void lodgroupApplyJS(esengine::ecs::LODGroup& c, const LODGroupJS& js) {
+ c.lod1 = resource::MeshHandle(js.lod1);
+ c.lod2 = resource::MeshHandle(js.lod2);
+ c.lod3 = resource::MeshHandle(js.lod3);
+ c.lod1Size = js.lod1Size;
+ c.lod2Size = js.lod2Size;
+ c.lod3Size = js.lod3Size;
+ c.cullSize = js.cullSize;
+ c.hysteresis = js.hysteresis;
+ c.enabled = js.enabled;
+}
+
+esengine::ecs::LODGroup lodgroupFromJS(const LODGroupJS& js) {
+ esengine::ecs::LODGroup c;
+ lodgroupApplyJS(c, js);
+ return c;
+}
+
+LODGroupJS lodgroupToJS(const esengine::ecs::LODGroup& c) {
+ LODGroupJS js;
+ js.lod1 = c.lod1.id();
+ js.lod2 = c.lod2.id();
+ js.lod3 = c.lod3.id();
+ js.lod1Size = c.lod1Size;
+ js.lod2Size = c.lod2Size;
+ js.lod3Size = c.lod3Size;
+ js.cullSize = c.cullSize;
+ js.hysteresis = c.hysteresis;
+ js.enabled = c.enabled;
+ return js;
+}
+
struct LightJS {
i32 type;
glm::vec4 color;
@@ -1495,6 +1540,17 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("blockRaycast", &esengine::ecs::Interactable::blockRaycast)
.field("raycastTarget", &esengine::ecs::Interactable::raycastTarget);
+ value_object<LODGroupJS>("LODGroup")
+ .field("lod1", &LODGroupJS::lod1)
+ .field("lod2", &LODGroupJS::lod2)
+ .field("lod3", &LODGroupJS::lod3)
+ .field("lod1Size", &LODGroupJS::lod1Size)
+ .field("lod2Size", &LODGroupJS::lod2Size)
+ .field("lod3Size", &LODGroupJS::lod3Size)
+ .field("cullSize", &LODGroupJS::cullSize)
+ .field("hysteresis", &LODGroupJS::hysteresis)
+ .field("enabled", &LODGroupJS::enabled);
+
value_object<LightJS>("Light")
.field("type", &LightJS::type)
.field("color", &LightJS::color)
@@ -2143,6 +2199,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Interactable>(entity);
}))
+ // LODGroup
+ .function("hasLODGroup", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::LODGroup>(static_cast<Entity>(e));
+ }))
+ .function("getLODGroup", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::LODGroup>(entity)) return LODGroupJS{};
+ return lodgroupToJS(r.get<esengine::ecs::LODGroup>(entity));
+ }))
+ .function("addLODGroup", optional_override([](Registry& r, u32 e, const LODGroupJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::LODGroup>(entity)) {
+ lodgroupApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::LODGroup>(entity, lodgroupFromJS(js));
+ }))
+ .function("removeLODGroup", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::LODGroup>(entity)) return;
+ r.remove<esengine::ecs::LODGroup>(entity);
+ }))
+
// Light
.function("hasLight", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Light>(static_cast<Entity>(e));
@@ -2721,6 +2801,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("DragonBonesAnimation")));
arr.set(i++, val(std::string("FlexContainer")));
arr.set(i++, val(std::string("Interactable")));
+ arr.set(i++, val(std::string("LODGroup")));
arr.set(i++, val(std::string("Light")));
arr.set(i++, val(std::string("MeshCollider3D")));
arr.set(i++, val(std::string("MeshRenderer")));
@@ -2872,6 +2953,15 @@ static_assert(offsetof(esengine::ecs::FlexContainer, padding) == 16, "ABI offset
static_assert(offsetof(esengine::ecs::Interactable, enabled) == 0, "ABI offset drift: esengine::ecs::Interactable.enabled (EHT expected 0)");
static_assert(offsetof(esengine::ecs::Interactable, blockRaycast) == 1, "ABI offset drift: esengine::ecs::Interactable.blockRaycast (EHT expected 1)");
static_assert(offsetof(esengine::ecs::Interactable, raycastTarget) == 2, "ABI offset drift: esengine::ecs::Interactable.raycastTarget (EHT expected 2)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod1) == 0, "ABI offset drift: esengine::ecs::LODGroup.lod1 (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod2) == 4, "ABI offset drift: esengine::ecs::LODGroup.lod2 (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod3) == 8, "ABI offset drift: esengine::ecs::LODGroup.lod3 (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod1Size) == 12, "ABI offset drift: esengine::ecs::LODGroup.lod1Size (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod2Size) == 16, "ABI offset drift: esengine::ecs::LODGroup.lod2Size (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::LODGroup, lod3Size) == 20, "ABI offset drift: esengine::ecs::LODGroup.lod3Size (EHT expected 20)");
+static_assert(offsetof(esengine::ecs::LODGroup, cullSize) == 24, "ABI offset drift: esengine::ecs::LODGroup.cullSize (EHT expected 24)");
+static_assert(offsetof(esengine::ecs::LODGroup, hysteresis) == 28, "ABI offset drift: esengine::ecs::LODGroup.hysteresis (EHT expected 28)");
+static_assert(offsetof(esengine::ecs::LODGroup, enabled) == 32, "ABI offset drift: esengine::ecs::LODGroup.enabled (EHT expected 32)");
static_assert(offsetof(esengine::ecs::Light, type) == 0, "ABI offset drift: esengine::ecs::Light.type (EHT expected 0)");
static_assert(offsetof(esengine::ecs::Light, color) == 4, "ABI offset drift: esengine::ecs::Light.color (EHT expected 4)");
static_assert(offsetof(esengine::ecs::Light, intensity) == 20, "ABI offset drift: esengine::ecs::Light.intensity (EHT expected 20)");
@@ -3118,7 +3208,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "fac7d5103ea562aa";
+static const char* kEsAbiLayoutHash = "7756afcaec734824";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 2c142dc96..6427eb9a7 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -724,6 +724,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_setYSortLayers", &esengine::renderer_setYSortLayers);
emscripten::function("renderer_setDepthLayers", &esengine::renderer_setDepthLayers);
emscripten::function("renderer_setCullingMask", &esengine::renderer_setCullingMask);
+ emscripten::function("renderer_setViewId", &esengine::renderer_setViewId);
emscripten::function("renderer_setColorSpace", &esengine::renderer_setColorSpace);
diff --git a/src/esengine/ecs/components/LODGroup.hpp b/src/esengine/ecs/components/LODGroup.hpp
new file mode 100644
index 000000000..d1c4149ba
--- /dev/null
+++ b/src/esengine/ecs/components/LODGroup.hpp
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file LODGroup.hpp
+ * @brief The cheaper geometry that may stand in for a MeshRenderer once it is small.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../resource/Handle.hpp"
+
+namespace esengine::ecs {
+
+/**
+ * @brief Stand-in geometry chosen by how much of the screen the object covers.
+ *
+ * @details The MeshRenderer beside it stays level 0; this says what may be drawn
+ * instead as it shrinks. Thresholds are fractions of the viewport HEIGHT,
+ * which hold across resolutions, fields of view and both projections where
+ * a distance holds across none. Selection belongs to the VIEW, not the entity.
+ */
+ES_COMPONENT(stability=beta)
+struct LODGroup {
+ /** @brief Geometry drawn once the object is smaller than @ref lod1Size. */
+ ES_PROPERTY(asset = mesh, tooltip="Geometry drawn below the LOD 1 screen size.")
+ resource::MeshHandle lod1;
+
+ /** @brief Geometry drawn once the object is smaller than @ref lod2Size. */
+ ES_PROPERTY(asset = mesh, tooltip="Geometry drawn below the LOD 2 screen size.")
+ resource::MeshHandle lod2;
+
+ /** @brief Geometry drawn once the object is smaller than @ref lod3Size. */
+ ES_PROPERTY(asset = mesh, tooltip="Geometry drawn below the LOD 3 screen size.")
+ resource::MeshHandle lod3;
+
+ /** @brief Fraction of the viewport height below which @ref lod1 replaces the
+ * MeshRenderer's own mesh. The sizes must descend. */
+ ES_PROPERTY(min=0, max=1, tooltip="Screen height fraction below which LOD 1 takes over.")
+ f32 lod1Size{0.5f};
+
+ ES_PROPERTY(min=0, max=1, tooltip="Screen height fraction below which LOD 2 takes over.")
+ f32 lod2Size{0.25f};
+
+ ES_PROPERTY(min=0, max=1, tooltip="Screen height fraction below which LOD 3 takes over.")
+ f32 lod3Size{0.1f};
+
+ /** @brief Fraction of the viewport height below which nothing is drawn at all.
+ * 0 disables it, so a group without one is never invisible. */
+ ES_PROPERTY(min=0, max=1, tooltip="Screen height fraction below which nothing is drawn (0 = never).")
+ f32 cullSize{0.02f};
+
+ /** @brief How much further than a threshold the object must grow before the
+ * finer level comes back — 0.1 turns a 0.20 boundary into 0.20 down,
+ * 0.22 up. Zero lets a level flip every frame at the boundary. */
+ ES_PROPERTY(min=0, max=1, advanced, tooltip="Extra fraction to grow past a threshold before the finer level returns.")
+ f32 hysteresis{0.1f};
+
+ ES_PROPERTY(tooltip="Off: the MeshRenderer's own mesh is always drawn.")
+ bool enabled{true};
+
+ LODGroup() = default;
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hpp
index d7707ed76..c48016785 100644
--- a/src/esengine/renderer/RenderTypePlugin.hpp
+++ b/src/esengine/renderer/RenderTypePlugin.hpp
@@ -5,6 +5,8 @@
#include "../core/Types.hpp"
#include "./frame/RenderStage.hpp"
#include "./frame/Frustum.hpp"
+#include "./lod/LodSelection.hpp"
+#include "./lod/LodViewState.hpp"
#include "./frame/FrameConstants.hpp"
#include "./draw/RenderItem.hpp"
#include "./draw/DrawCommand.hpp"
@@ -168,6 +170,21 @@ struct RenderCollectContext {
* what its frustum skipped is `render.shadow.collects`.
*/
u32 culled = 0;
+
+ /**
+ * @brief Which view is looking, where its level choices are kept, and where
+ * the selections it makes are counted.
+ *
+ * @details A null `state` is what a collect that must not select says: the
+ * shadow pass draws level 0 rather than borrowing a camera's answer,
+ * which would make the answer the entity's rather than the view's.
+ */
+ struct LodView {
+ u32 view = 0;
+ lod::LodViewState* state = nullptr;
+ lod::SelectionCounts* counts = nullptr;
+ };
+ LodView lod;
};
/** @brief Decomposes @p transform and returns its world position shifted toward the
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 06e68a71b..2e6219406 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -287,6 +287,12 @@ void RenderFrame::beginFrame() {
frame_collected_ = false;
frame_depth_seen_ = false;
applySceneDepthNeed();
+
+ // Counted over the whole frame rather than per camera, because a selection is
+ // one view's answer: the same object seen by two cameras is two selections, and
+ // that they can differ is the whole claim.
+ lod_counts_ = {};
+ lod_view_state_.beginFrame();
}
void RenderFrame::applySceneDepthNeed() {
@@ -313,6 +319,9 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::H
view_projection_ = view_projection;
frustum_.extractFromMatrix(view_projection);
+ // A camera that names no view looks from the shared default one rather than
+ // remembering the levels the previous camera settled on.
+ view_id_ = 0;
current_target_ = target;
current_stage_ = RenderStage::Transparent;
in_frame_ = true;
@@ -482,6 +491,12 @@ void RenderFrame::flush() {
ES_PROFILE_COUNTER("render.meshes", stats_.meshes);
ES_PROFILE_COUNTER("render.triangles", stats_.triangles);
ES_PROFILE_COUNTER("render.text", stats_.text);
+ ES_PROFILE_COUNTER("render.lod.groups", lod_counts_.selections);
+ ES_PROFILE_COUNTER("render.lod.level0", lod_counts_.level[0]);
+ ES_PROFILE_COUNTER("render.lod.level1", lod_counts_.level[1]);
+ ES_PROFILE_COUNTER("render.lod.level2", lod_counts_.level[2]);
+ ES_PROFILE_COUNTER("render.lod.level3", lod_counts_.level[3]);
+ ES_PROFILE_COUNTER("render.lod.culled", lod_counts_.culled);
ES_PROFILE_COUNTER("render.shapes", stats_.shapes);
#ifdef ES_ENABLE_PARTICLES
ES_PROFILE_COUNTER("render.particles", stats_.particles);
@@ -646,6 +661,7 @@ void RenderFrame::renderSurface(ecs::Registry& registry, const glm::mat4& viewPr
// preview is pixel-identical to the viewport.
view_projection_ = viewProjection;
frustum_.extractFromMatrix(viewProjection);
+ view_id_ = kPreviewViewId;
current_stage_ = RenderStage::Transparent;
pool_.beginFrame();
draw_list_.clear();
@@ -1555,6 +1571,7 @@ void RenderFrame::collectAll(ecs::Registry& registry) {
// entities are laid out in pixels centred on the origin, and drawing them
// through a view matrix puts a HUD wherever the view happens to be looking.
collectCtx.screen_ui = screen_domain_;
+ collectCtx.lod = {view_id_, &lod_view_state_, &lod_counts_};
collectSky(collectCtx);
for (auto& plugin : plugins_) plugin->collect(collectCtx);
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index 5ea40c4ba..13fac3316 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -273,6 +273,15 @@ public:
/// Layers the camera about to be collected renders — see DrawList::setCullingMask.
void setCullingMask(u32 mask) { draw_list_.setCullingMask(mask); }
+ /**
+ * @brief Names the view the camera about to be collected looks from, which is
+ * what its LOD levels are remembered under.
+ *
+ * @details Reset by begin(), so a camera that names none looks from the shared
+ * default view rather than inheriting the last camera's memory.
+ */
+ void setViewId(u32 view) { view_id_ = view; }
+
/**
* @brief Switch the frame to linear-light rendering (project colorSpace).
* @details Sets the global ES_LINEAR shader input, linearizes CPU-side
@@ -432,6 +441,14 @@ private:
std::vector<PendingSkeletalBatch> pending;
PreviewSurface surface;
};
+ /// The view an offscreen preview looks from: its own, so a thumbnail neither
+ /// reads nor writes the level a camera settled on for the same object.
+ static constexpr u32 kPreviewViewId = 0xFFFFFFFEu;
+
+ u32 view_id_ = 0;
+ lod::LodViewState lod_view_state_;
+ lod::SelectionCounts lod_counts_;
+
std::unordered_map<SkeletalPreviewId, Unique<SkeletalPreview>> skeletal_previews_;
/** Never reused, so a destroyed id can only ever be a destroyed id. */
SkeletalPreviewId next_skeletal_preview_ = 1;
diff --git a/src/esengine/renderer/lod/LodSelection.hpp b/src/esengine/renderer/lod/LodSelection.hpp
new file mode 100644
index 000000000..f9ac17025
--- /dev/null
+++ b/src/esengine/renderer/lod/LodSelection.hpp
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file LodSelection.hpp
+ * @brief Which representation an object's size on screen asks for.
+ *
+ * @details Header-only and free of the renderer, so the arithmetic can be held
+ * against its own claims without a device: a projection, a sphere and
+ * the level last shown are the whole input.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../math/Math.hpp"
+
+#include <glm/gtc/quaternion.hpp>
+
+#include <cmath>
+
+namespace esengine::lod {
+
+/** @brief How many stand-ins a group may declare beyond the renderer's own mesh. */
+inline constexpr u8 kMaxStandIns = 3;
+
+/** @brief The level of an object small enough that nothing is drawn for it. */
+inline constexpr u8 kCulled = 0xFFu;
+
+/**
+ * @brief What a point at or behind the eye reports.
+ *
+ * @details It has no finite projection, and the only useful answer there is the
+ * one that picks the nearest level rather than the farthest.
+ */
+inline constexpr f32 kSizeAtEye = 1e30f;
+
+/**
+ * @brief The screen sizes a group hands over at, in the order it hands them over.
+ *
+ * @details `takeOver[i]` is the boundary between level `i` and level `i+1` and
+ * must descend; `cull` is the last boundary of all. `hysteresis` is the
+ * fraction a boundary is raised by to be crossed toward the FINER side.
+ */
+struct LevelSet {
+ f32 takeOver[kMaxStandIns]{};
+ f32 cull = 0.0f;
+ f32 hysteresis = 0.0f;
+ u8 count = 0;
+};
+
+/**
+ * @brief The sphere a group is measured by: its centre in the world and its radius.
+ *
+ * @details A sphere rather than the turned box, because the radius is the same at
+ * every angle — a box's projected size breathes as its owner spins, which
+ * at a boundary is a level that changes for no reason but rotation.
+ */
+inline void boundingSphere(const glm::vec3& position, const glm::quat& rotation,
+ const glm::vec3& scale, const glm::vec3& localMin,
+ const glm::vec3& localMax, glm::vec3& outCentre, f32& outRadius) {
+ const glm::vec3 scaledHalf = glm::abs((localMax - localMin) * 0.5f * scale);
+ outCentre = position + glm::mat3_cast(rotation) * ((localMin + localMax) * 0.5f * scale);
+ outRadius = glm::length(scaledHalf);
+}
+
+/**
+ * @brief How much of the viewport's HEIGHT a sphere covers: 1 = one screen high.
+ *
+ * @details The gradient of NDC y with respect to world position, times the radius;
+ * NDC spans 2, so that ratio IS the fraction. Both projections are in the
+ * matrix, so one expression answers for both. A fraction of the height is
+ * free of the viewport's pixel count and of its aspect.
+ */
+inline f32 screenRelativeSize(const glm::mat4& viewProjection, const glm::vec3& centre,
+ f32 radius) {
+ const glm::vec4 clip = viewProjection * glm::vec4(centre, 1.0f);
+ if (clip.w <= 1e-6f) return kSizeAtEye;
+ const glm::vec3 row1(viewProjection[0][1], viewProjection[1][1], viewProjection[2][1]);
+ const glm::vec3 row3(viewProjection[0][3], viewProjection[1][3], viewProjection[2][3]);
+ // The term in ndcY is the stretch toward the edges of a perspective frame; it
+ // falls out on its own under a projection that has none.
+ const glm::vec3 gradient = (row1 - (clip.y / clip.w) * row3) / clip.w;
+ return radius * glm::length(gradient);
+}
+
+/**
+ * @brief The level @p size asks for, given the one shown last.
+ *
+ * @details Each boundary is asymmetric — `takeOver * (1 + hysteresis)` to come back
+ * toward the fine side, the bare threshold to go coarse — because a
+ * boundary that is not a wall flips every frame for a breathing camera.
+ * @p current biases by one band only, so a stale one costs a frame.
+ */
+inline u8 selectLevel(const LevelSet& set, f32 size, u8 current) {
+ u8 level = 0;
+ for (u8 i = 0; i < set.count && i < kMaxStandIns; ++i) {
+ const u8 candidate = static_cast<u8>(i + 1);
+ const bool coarseSide = current >= candidate;
+ if (size >= set.takeOver[i] * (coarseSide ? 1.0f + set.hysteresis : 1.0f)) break;
+ level = candidate;
+ }
+ if (set.cull > 0.0f) {
+ const bool wasCulled = current == kCulled;
+ if (size < set.cull * (wasCulled ? 1.0f + set.hysteresis : 1.0f)) return kCulled;
+ }
+ return level;
+}
+
+/**
+ * @brief What a frame's selections came to, counted where each one is made.
+ *
+ * @details One SELECTION per view per object, not one per object: a frame with two
+ * cameras counts the same object twice, and the two counts differing is
+ * the only evidence that the two views decided independently.
+ */
+struct SelectionCounts {
+ u32 selections = 0;
+ u32 level[kMaxStandIns + 1]{};
+ u32 culled = 0;
+
+ void record(u8 level_) {
+ ++selections;
+ if (level_ == kCulled) ++culled;
+ else if (level_ <= kMaxStandIns) ++level[level_];
+ }
+};
+
+} // namespace esengine::lod
diff --git a/src/esengine/renderer/lod/LodViewState.hpp b/src/esengine/renderer/lod/LodViewState.hpp
new file mode 100644
index 000000000..7b1530b37
--- /dev/null
+++ b/src/esengine/renderer/lod/LodViewState.hpp
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file LodViewState.hpp
+ * @brief The level each view last drew an object at — what hysteresis remembers.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+
+#include <iterator>
+#include <unordered_map>
+
+namespace esengine::lod {
+
+/**
+ * @brief Levels remembered per (view, entity) pair.
+ *
+ * @details Keyed by the view because a level is an answer to "how big does it look
+ * from HERE": a minimap and a main camera looking at one object in one
+ * frame must be able to disagree. Kept on the entity it would be one
+ * answer, and whichever camera drew last would decide for all of them.
+ */
+class LodViewState {
+public:
+ /** @brief How many frames an untouched pair is kept before it is dropped. */
+ static constexpr u64 kKeepFrames = 120;
+
+ /** @brief Opens a frame and, now and then, drops what no view still asks about
+ * — an entity that died leaves a pair nothing will ever touch again. */
+ void beginFrame() {
+ ++frame_;
+ if (frame_ % kKeepFrames != 0) return;
+ for (auto it = entries_.begin(); it != entries_.end();) {
+ it = (frame_ - it->second.stamp > kKeepFrames) ? entries_.erase(it) : std::next(it);
+ }
+ }
+
+ /** @brief The level @p view last drew @p entity at; level 0 for a pair it has
+ * never seen, which is the unbiased answer a first sighting wants. */
+ u8 lastLevel(u32 view, Entity entity) const {
+ const auto it = entries_.find(key(view, entity));
+ return it == entries_.end() ? 0 : it->second.level;
+ }
+
+ void remember(u32 view, Entity entity, u8 level) {
+ auto& entry = entries_[key(view, entity)];
+ entry.level = level;
+ entry.stamp = frame_;
+ }
+
+ void clear() { entries_.clear(); }
+
+ usize size() const { return entries_.size(); }
+
+private:
+ struct Entry {
+ u64 stamp = 0;
+ u8 level = 0;
+ };
+
+ static u64 key(u32 view, Entity entity) {
+ return (static_cast<u64>(view) << 32) | static_cast<u64>(entity.raw);
+ }
+
+ std::unordered_map<u64, Entry> entries_;
+ u64 frame_ = 0;
+};
+
+} // namespace esengine::lod
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index 724aa3b4b..3bb519334 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -8,6 +8,7 @@
#include "../rhi/ShaderEmbeds.generated.hpp"
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/MeshRenderer.hpp"
+#include "../../ecs/components/LODGroup.hpp"
#include "../../resource/Mesh.hpp"
#include "../../resource/ShaderParser.hpp"
#include "../../core/Log.hpp"
@@ -78,6 +79,83 @@ u32 skinPose(ecs::Registry& registry, Entity entity, const Mesh& mesh,
return count;
}
+/**
+ * @brief The levels a group can actually be drawn at, in the order they take over.
+ *
+ * @details Entry 0 is the renderer's own mesh: a group says what may STAND IN for
+ * it. `localMin/Max` are the UNION over every entry, so what is measured
+ * does not change with what is drawn — bounds read off the current level
+ * feed back into the choice that picked it and oscillate.
+ */
+struct LodLevels {
+ const Mesh* mesh[lod::kMaxStandIns + 1]{};
+ lod::LevelSet set;
+ glm::vec3 localMin{0.0f};
+ glm::vec3 localMax{0.0f};
+ /// A slot filled after an empty one, which nothing will ever select.
+ bool gap = false;
+ /// Thresholds that do not descend, or a stand-in the base's skeleton cannot pose.
+ bool disordered = false;
+ bool skinMismatch = false;
+};
+
+/**
+ * @brief Reads a group into the levels it can be drawn at. False when it declares
+ * no usable stand-in, which leaves the renderer's own mesh the whole answer.
+ */
+bool gatherLodLevels(resource::ResourceManager& resources, const ecs::LODGroup& group,
+ const Mesh& base, LodLevels& out) {
+ out = LodLevels{};
+ out.mesh[0] = &base;
+ out.localMin = base.localMin;
+ out.localMax = base.localMax;
+ out.set.cull = group.cullSize;
+ out.set.hysteresis = group.hysteresis;
+
+ const resource::MeshHandle handles[lod::kMaxStandIns] = {group.lod1, group.lod2, group.lod3};
+ const f32 sizes[lod::kMaxStandIns] = {group.lod1Size, group.lod2Size, group.lod3Size};
+ for (u8 i = 0; i < lod::kMaxStandIns; ++i) {
+ const Mesh* standIn = handles[i].isValid() ? resources.getMesh(handles[i]) : nullptr;
+ if (!standIn || !standIn->isDrawable()) {
+ // Ordered slots: a level nothing hands over TO is a level nothing
+ // reaches, so the run ends here and a later one is an authoring gap.
+ for (u8 j = static_cast<u8>(i + 1); j < lod::kMaxStandIns; ++j) {
+ if (handles[j].isValid()) out.gap = true;
+ }
+ break;
+ }
+ if (base.isSkinned() && standIn->inverseBind.size() != base.inverseBind.size()) {
+ out.skinMismatch = true;
+ break;
+ }
+ if (i > 0 && sizes[i] >= sizes[i - 1]) out.disordered = true;
+ out.mesh[i + 1] = standIn;
+ out.set.takeOver[i] = sizes[i];
+ out.set.count = static_cast<u8>(i + 1);
+ out.localMin = glm::min(out.localMin, standIn->localMin);
+ out.localMax = glm::max(out.localMax, standIn->localMax);
+ }
+ return out.set.count > 0;
+}
+
+/** @brief Says once what a group declares that nothing will ever use. */
+void reportLodAuthoring(const LodLevels& levels, bool& warned) {
+ if (warned || !(levels.gap || levels.disordered || levels.skinMismatch)) return;
+ warned = true;
+ if (levels.gap) {
+ ES_LOG_WARN("LODGroup: a stand-in slot is empty, so every slot after it is unreachable —"
+ " fill lod1, then lod2, then lod3");
+ }
+ if (levels.disordered) {
+ ES_LOG_WARN("LODGroup: the screen sizes do not descend, so a level is handed over to"
+ " before the one before it");
+ }
+ if (levels.skinMismatch) {
+ ES_LOG_WARN("LODGroup: a stand-in has a different joint count from level 0; every level of"
+ " a skinned group must share the skeleton");
+ }
+}
+
u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned, bool depthOnly,
bool envMapped) {
return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)
@@ -198,13 +276,45 @@ 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 (shadowDepth && !resident) continue;
- const glm::vec3 localMin = resident ? resident->localMin : glm::vec3(mesh.localMin, 0.0f);
- const glm::vec3 localMax = resident ? resident->localMax : glm::vec3(mesh.localMax, 0.0f);
+
+ // A collect with no LOD memory must not select: a shadow map's own screen
+ // size means nothing to a player, and borrowing a camera's answer would
+ // make the answer the entity's rather than each view's.
+ LodLevels levels;
+ const ecs::LODGroup* group = nullptr;
+ if (collect_ctx.lod.state && resident) {
+ const auto* declared = registry.tryGet<ecs::LODGroup>(entity);
+ if (declared && declared->enabled
+ && gatherLodLevels(ctx.resources, *declared, *resident, levels)) {
+ group = declared;
+ reportLodAuthoring(levels, warned_lod_);
+ }
+ }
+ const glm::vec3 localMin = group ? levels.localMin
+ : resident ? resident->localMin : glm::vec3(mesh.localMin, 0.0f);
+ const glm::vec3 localMax = group ? levels.localMax
+ : resident ? resident->localMax : glm::vec3(mesh.localMax, 0.0f);
glm::vec3 aabbCenter(0.0f), halfExtents(0.0f);
orientedWorldAabb(position, rotation, scale, localMin, localMax, aabbCenter, halfExtents);
if (!frustum.intersectsAABB(aabbCenter, halfExtents)) { ++collect_ctx.culled; continue; }
+ // Nothing visible is worth measuring precisely, so the cull runs first; what
+ // survives it is measured on the sphere the whole group shares.
+ if (group) {
+ glm::vec3 centre(0.0f);
+ f32 radius = 0.0f;
+ lod::boundingSphere(position, rotation, scale, localMin, localMax, centre, radius);
+ const f32 screenSize = lod::screenRelativeSize(ctx.view_projection, centre, radius);
+ auto& state = *collect_ctx.lod.state;
+ const u8 level = lod::selectLevel(levels.set, screenSize,
+ state.lastLevel(collect_ctx.lod.view, entity));
+ state.remember(collect_ctx.lod.view, entity, level);
+ if (collect_ctx.lod.counts) collect_ctx.lod.counts->record(level);
+ if (level == lod::kCulled) { ++collect_ctx.culled; continue; }
+ resident = levels.mesh[level];
+ }
+
u32 textureId = ctx.white_texture_id;
if (mesh.texture.isValid()) {
if (Texture* tex = ctx.resources.getTexture(mesh.texture)) {
diff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hpp
index 6391f4a1f..545ef8075 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.hpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp
@@ -43,6 +43,7 @@ private:
bool skinned, bool depthOnly = false, bool envMapped = false);
bool warned_material_ = false; ///< A material on resident geometry is said once.
bool warned_bones_ = false; ///< A skin over the pose budget is said once.
+ bool warned_lod_ = false; ///< A group that cannot be honoured is said once.
};
} // namespace esengine
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index f4e0f840a..bc9a8fbdb 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 0xaa8849ed8d31d9a0ULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0xa8244cac94602de0ULL
/* 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 06587ff87..e59877648 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 0xaa8849ed8d31d9a0ULL
+#define ES_ABI_ENGINE_DIGEST 0xa8244cac94602de0ULL
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 480aecd25..6f3fb3bc8 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 0xaa8849ed8d31d9a0ULL
+#define ES_ABI_ENGINE_DIGEST 0xa8244cac94602de0ULL
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 cdbca52d7..1c20d3431 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 0xaa8849ed8d31d9a0ULL
+#define ES_EXPECTED_CONTRACT_HASH 0xa8244cac94602de0ULL
/* 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