1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//! Dynamic Level of Detail (LOD) controller.
//!
//! Monitors GPU frame time and automatically adjusts the geodesic count to
//! maintain a smooth 60 fps target.
//!
//! # Algorithm
//!
//! The controller uses a PI-style feedback loop on the measured frame time:
//!
//! - If `frame_time > 16 ms` (below 60 fps): reduce geodesic count by one step.
//! - If `frame_time < 8 ms` (above 125 fps): increase geodesic count by one step.
//! - Changes are hysteresis-gated: at least `cooldown_frames` must elapse
//! between adjustments to avoid oscillation.
//!
//! The step size grows when the frame time is far from target (proportional
//! action) and shrinks close to target (fine-grained adjustment).
#![allow(dead_code)]
// ── Configuration ─────────────────────────────────────────────────────────────
/// Configuration for the LOD controller.
#[derive(Debug, Clone)]
pub struct LodConfig {
/// Minimum number of geodesics (absolute floor).
pub min_geodesics: usize,
/// Maximum number of geodesics (absolute ceiling).
pub max_geodesics: usize,
/// Target frame time in milliseconds (default: 16.67 ms = 60 fps).
pub target_ms: f32,
/// Upper threshold: reduce geodesics when frame time exceeds this (ms).
pub reduce_threshold_ms: f32,
/// Lower threshold: increase geodesics when frame time is below this (ms).
pub increase_threshold_ms: f32,
/// Minimum frames between geodesic count changes (hysteresis).
pub cooldown_frames: u32,
/// Initial step size for geodesic count changes.
pub base_step: usize,
/// EMA coefficient for frame time smoothing (0 < alpha <= 1).
pub smooth_alpha: f32,
}
impl Default for LodConfig {
fn default() -> Self {
Self {
min_geodesics: 4,
max_geodesics: 200,
target_ms: 16.667,
reduce_threshold_ms: 16.0,
increase_threshold_ms: 8.0,
cooldown_frames: 30,
base_step: 2,
smooth_alpha: 0.1,
}
}
}
// ── Controller ────────────────────────────────────────────────────────────────
/// Stateful LOD controller.
///
/// Call [`LodController::update`] once per frame with the measured frame time,
/// then read [`LodController::geodesic_count`] to get the recommended count.
pub struct LodController {
/// Thresholds and limits the controller works within.
pub config: LodConfig,
/// Current recommended geodesic count.
pub geodesic_count: usize,
/// Exponentially smoothed frame time in ms.
smoothed_ms: f32,
/// Frames since last count change.
cooldown_remaining: u32,
/// Total frames processed.
frame_count: u64,
/// Running statistics for diagnostics.
stats: LodStats,
}
/// Diagnostics emitted by the LOD controller.
#[derive(Debug, Clone, Default)]
pub struct LodStats {
/// Total number of upward adjustments (geodesic count increased).
pub increases: u32,
/// Total number of downward adjustments (geodesic count decreased).
pub decreases: u32,
/// Minimum smoothed frame time observed (ms).
pub min_frame_ms: f32,
/// Maximum smoothed frame time observed (ms).
pub max_frame_ms: f32,
/// Current smoothed frame time (ms).
pub current_frame_ms: f32,
}
/// The action taken by the LOD controller on a given frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LodAction {
/// No change this frame.
Unchanged,
/// Geodesic count was increased.
Increased {
/// Count before the change.
from: usize,
/// Count after the change.
to: usize,
},
/// Geodesic count was decreased.
Decreased {
/// Count before the change.
from: usize,
/// Count after the change.
to: usize,
},
}
impl LodController {
/// Create a controller with the given initial geodesic count.
pub fn new(initial_geodesics: usize, config: LodConfig) -> Self {
let clamped = initial_geodesics.clamp(config.min_geodesics, config.max_geodesics);
Self {
geodesic_count: clamped,
smoothed_ms: config.target_ms,
cooldown_remaining: config.cooldown_frames,
frame_count: 0,
stats: LodStats {
min_frame_ms: f32::MAX,
max_frame_ms: 0.0,
..Default::default()
},
config,
}
}
/// Feed the measured frame time (in milliseconds) for this frame.
///
/// Returns the [`LodAction`] taken (or [`LodAction::Unchanged`]).
pub fn update(&mut self, frame_ms: f32) -> LodAction {
self.frame_count += 1;
// EMA smoothing.
let a = self.config.smooth_alpha;
self.smoothed_ms = (1.0 - a) * self.smoothed_ms + a * frame_ms;
// Update stats.
self.stats.current_frame_ms = self.smoothed_ms;
if self.smoothed_ms < self.stats.min_frame_ms {
self.stats.min_frame_ms = self.smoothed_ms;
}
if self.smoothed_ms > self.stats.max_frame_ms {
self.stats.max_frame_ms = self.smoothed_ms;
}
// Cooldown.
if self.cooldown_remaining > 0 {
self.cooldown_remaining -= 1;
return LodAction::Unchanged;
}
let old_count = self.geodesic_count;
if self.smoothed_ms > self.config.reduce_threshold_ms {
// Too slow → reduce.
let excess = self.smoothed_ms - self.config.target_ms;
let step = (self.config.base_step + (excess / 4.0) as usize).min(20);
let new_count = old_count
.saturating_sub(step)
.max(self.config.min_geodesics);
if new_count < old_count {
self.geodesic_count = new_count;
self.cooldown_remaining = self.config.cooldown_frames;
self.stats.decreases += 1;
log::debug!(
"[lod] frame={:.1}ms → reduce {} → {} geodesics",
self.smoothed_ms,
old_count,
new_count
);
return LodAction::Decreased {
from: old_count,
to: new_count,
};
}
} else if self.smoothed_ms < self.config.increase_threshold_ms {
// Too fast → increase.
let headroom = self.config.increase_threshold_ms - self.smoothed_ms;
let step = (self.config.base_step + (headroom / 2.0) as usize).min(10);
let new_count = (old_count + step).min(self.config.max_geodesics);
if new_count > old_count {
self.geodesic_count = new_count;
self.cooldown_remaining = self.config.cooldown_frames;
self.stats.increases += 1;
log::debug!(
"[lod] frame={:.1}ms → increase {} → {} geodesics",
self.smoothed_ms,
old_count,
new_count
);
return LodAction::Increased {
from: old_count,
to: new_count,
};
}
}
LodAction::Unchanged
}
/// Return a snapshot of the controller's diagnostics.
pub fn stats(&self) -> &LodStats {
&self.stats
}
/// Smoothed frame time in ms.
pub fn smoothed_frame_ms(&self) -> f32 {
self.smoothed_ms
}
/// Number of frames processed so far.
pub fn frame_count(&self) -> u64 {
self.frame_count
}
/// Force-set the geodesic count without going through the feedback loop.
/// Useful when the user overrides the count manually.
pub fn force_set(&mut self, count: usize) {
self.geodesic_count = count.clamp(self.config.min_geodesics, self.config.max_geodesics);
self.cooldown_remaining = self.config.cooldown_frames;
}
}
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
fn make_controller(initial: usize) -> LodController {
LodController::new(
initial,
LodConfig {
min_geodesics: 4,
max_geodesics: 100,
cooldown_frames: 0, // no cooldown for tests
..Default::default()
},
)
}
#[test]
fn test_lod_reduces_when_slow() {
let mut ctrl = make_controller(30);
// Feed a very slow frame time repeatedly.
let mut decreased = false;
for _ in 0..20 {
let action = ctrl.update(33.0); // 30 fps
decreased |= matches!(action, LodAction::Decreased { .. });
}
assert!(decreased, "should reduce geodesics on slow frame");
assert!(ctrl.geodesic_count < 30, "geodesic count should decrease");
}
#[test]
fn test_lod_increases_when_fast() {
let mut ctrl = make_controller(30);
let mut action = LodAction::Unchanged;
for _ in 0..20 {
action = ctrl.update(3.0); // very fast
}
assert!(
matches!(action, LodAction::Increased { .. }),
"should increase geodesics on fast frame: {:?}",
action
);
assert!(ctrl.geodesic_count > 30, "geodesic count should increase");
}
#[test]
fn test_lod_unchanged_at_target() {
let mut ctrl = make_controller(30);
let mut last_action = LodAction::Unchanged;
for _ in 0..50 {
last_action = ctrl.update(12.0); // between 8 and 16 ms → stable
}
assert_eq!(
last_action,
LodAction::Unchanged,
"should be stable at target"
);
}
#[test]
fn test_lod_clamps_to_min() {
let mut ctrl = make_controller(5);
for _ in 0..100 {
ctrl.update(100.0); // extremely slow
}
assert!(ctrl.geodesic_count >= ctrl.config.min_geodesics);
}
#[test]
fn test_lod_clamps_to_max() {
let mut ctrl = make_controller(90);
for _ in 0..100 {
ctrl.update(0.1); // extremely fast
}
assert!(ctrl.geodesic_count <= ctrl.config.max_geodesics);
}
#[test]
fn test_lod_force_set() {
let mut ctrl = make_controller(30);
ctrl.force_set(50);
assert_eq!(ctrl.geodesic_count, 50);
}
#[test]
fn test_lod_stats_tracked() {
let mut ctrl = make_controller(30);
ctrl.update(20.0);
ctrl.update(10.0);
assert!(ctrl.stats().max_frame_ms >= ctrl.stats().min_frame_ms);
}
}