Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rtxpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from .lod import (
compute_lod_level,
compute_lod_distances,
LODBudgetController,
simplify_mesh,
build_lod_chain,
)
Expand Down
146 changes: 146 additions & 0 deletions rtxpy/lod.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,152 @@ def compute_tile_roughness(tile_2d):
return float(np.nanstd(residuals))


class LODBudgetController:
"""Adjust ``lod_distance_factor`` to hold a target frame time.

Closes the loop between measured render cost and LOD thresholds.
Each frame the measured frame time is folded into an exponential
moving average (EMA). When the EMA is slower than the target by
more than ``dead_band`` the factor shrinks, pulling LOD transitions
closer to the camera (fewer triangles); when it is faster by more
than ``dead_band`` the factor grows (more detail). Inside the dead
band the factor is left alone so it does not oscillate.

The step is proportional to the relative error, clamped to
``max_step`` of the current factor per frame, and the factor is
kept within ``[min_factor, max_factor]``.

Parameters
----------
target_fps : float
Frame rate to aim for. The target frame time is
``1000 / target_fps`` milliseconds.
min_factor, max_factor : float
Bounds on the returned ``lod_distance_factor``.
alpha : float
EMA smoothing weight for the newest sample, in ``(0, 1]``.
dead_band : float
Fractional tolerance around the target, in ``[0, 1)``. E.g.
0.1 leaves the factor unchanged while the EMA is within 10%.
step_scale : float
Fractional factor change per unit of relative error.
max_step : float
Largest fractional change applied in a single frame.
initial_factor : float
Starting factor, clamped into ``[min_factor, max_factor]``.
Defaults to 3.0, the ``TerrainLODManager`` default.

Examples
--------
>>> ctrl = LODBudgetController(target_fps=30, initial_factor=3.0)
>>> ctrl.update(66.0) < 3.0 # twice the 33 ms budget: less detail
True
"""

def __init__(self, target_fps=30, min_factor=1.0, max_factor=10.0,
alpha=0.1, dead_band=0.1, step_scale=0.02, max_step=0.05,
initial_factor=3.0):
if not target_fps > 0:
raise ValueError(f"target_fps must be positive, got {target_fps!r}")
if not 0 < min_factor <= max_factor:
raise ValueError(
"require 0 < min_factor <= max_factor, got "
f"min_factor={min_factor!r}, max_factor={max_factor!r}")
if not 0 < alpha <= 1:
raise ValueError(f"alpha must be in (0, 1], got {alpha!r}")
if not 0 <= dead_band < 1:
raise ValueError(f"dead_band must be in [0, 1), got {dead_band!r}")
if not step_scale >= 0:
raise ValueError(f"step_scale must be >= 0, got {step_scale!r}")
if not 0 <= max_step < 1:
raise ValueError(f"max_step must be in [0, 1), got {max_step!r}")

self._target_ms = 1000.0 / float(target_fps)
self._min_factor = float(min_factor)
self._max_factor = float(max_factor)
self._alpha = float(alpha)
self._dead_band = float(dead_band)
self._step_scale = float(step_scale)
self._max_step = float(max_step)
self._factor = min(max(float(initial_factor), self._min_factor),
self._max_factor)
self._ema = None
self._direction = 0
self.enabled = True

@property
def current_factor(self):
"""The ``lod_distance_factor`` to apply to LOD managers."""
return self._factor

@property
def ema_frame_time(self):
"""Smoothed frame time in milliseconds (None before any sample)."""
return self._ema

@property
def target_frame_time(self):
"""Target frame time in milliseconds."""
return self._target_ms

@property
def direction(self):
"""Last adjustment: +1 more detail, -1 less detail, 0 stable."""
return self._direction

def update(self, frame_time_ms):
"""Record one frame's render time and return the adjusted factor.

Call once per frame. Non-finite or non-positive samples are
ignored. While :attr:`enabled` is False the EMA keeps tracking
frame time but the factor stays at its last value.

Parameters
----------
frame_time_ms : float
Measured render time of the last frame, in milliseconds.

Returns
-------
float
The (possibly unchanged) ``lod_distance_factor``.
"""
ft = float(frame_time_ms)
if not np.isfinite(ft) or ft <= 0.0:
self._direction = 0
return self._factor

if self._ema is None:
self._ema = ft
else:
self._ema = self._alpha * ft + (1.0 - self._alpha) * self._ema

if not self.enabled:
self._direction = 0
return self._factor

rel_err = (self._ema - self._target_ms) / self._target_ms
if abs(rel_err) <= self._dead_band:
self._direction = 0
return self._factor

step = min(self._step_scale * abs(rel_err), self._max_step)
if rel_err > 0:
new_factor = self._factor * (1.0 - step)
else:
new_factor = self._factor * (1.0 + step)
new_factor = min(max(new_factor, self._min_factor), self._max_factor)

if new_factor > self._factor:
self._direction = 1
elif new_factor < self._factor:
self._direction = -1
else:
self._direction = 0
self._factor = new_factor
return self._factor


def simplify_mesh(vertices, indices, ratio):
"""Simplify a triangle mesh using quadric decimation.

Expand Down
Loading