Algorithmadvanced
ROAM
Also called real-time optimally adapting meshes.
Keep a terrain triangulation as a binary triangle tree and split and merge triangles with two priority queues to meet an error bound each frame.
- Time
- O((L + s) log(L + s)) worst
- Space
- Θ(M^2) extra
- Where
- L = the number of leaves at the start and at the end of the frame; M = the grid size in cells along each side; s = the number of splits and merges in the frame
- Model
- Real RAM
- Properties
- not adaptivenot comparison baseddeterministicin placeonlineiterativenot stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich, Mark B. Mineev Weinstein, 1997
ROAM keeps a terrain as the leaves of a binary tree of right triangles, and each frame it splits the leaves with the largest error and merges the pairs with the smallest error, with one priority queue for each. A split that would leave a crack first splits the coarser neighbor across the base, so the mesh has no T-junctions at any time. View-dependent refinement does the same kind of local work on any progressive mesh with stored records, and geometry clipmaps use fixed nested grids in place of a tree. ROAM needs only the height grid and a bound per triangle, which it computes once.
In plain words
Cut a square of terrain along a diagonal into two triangles. Any triangle of this kind can be cut again, from its right angle to the middle of its long side, into two smaller triangles of the same shape. Repeating this gives finer and finer meshes.
ROAM keeps a mesh made of such triangles. For each one it knows, from a table made at the start, how far the flat triangle can be from the true ground below it. Each frame it cuts the triangles whose error looks large from where the viewer is, and joins pairs of triangles whose error looks small. If a cut would make a gap with a larger neighbor, it cuts that neighbor first. The mesh of one frame is the start for the next, so a small move of the viewer gives few changes.
The problem
The input is a height grid on the points with and , the position of the eye, a priority for each triangle and an error bound . A bintree triangle has its right angle at the apex and the base . Its children are and with the midpoint of the base. The two roots split the square along a diagonal. The partner of is the triangle of the same level across its base; together they form a diamond. A mesh is the set of leaves of a cut of the tree. It is conforming when no vertex of a leaf lies inside an edge of another leaf. The output, each frame, is a conforming mesh in which every leaf has , with as few triangles as possible. The paper writes the height as ; this page uses .
The algorithm
FORCE-SPLIT(mesh, t) ▷ t is a leaf with children- 1
stack ← [t] - 2
while the stack is not empty do u ← the top; if u is not a leaf then pop u and go on - 3
b ← the leaf with the base of u as an edge, or nil on the border - 4
if b ≠ nil and the base of b is not the base of u then push b and go on - 5
split u, and split b if b ≠ nil; pop u UPDATE(mesh, p, ε) ▷ one frame- 6
Qs ← a max-heap of the leaves by p - 7
while p(top of Qs) > ε^2 do pop T; if T is a leaf then FORCE-SPLIT(mesh, T) and push the new leaves - 8
Qm ← a min-heap of the mergeable diamonds by the larger p of the two; while p(top of Qm) ≤ ε^2 do merge it and push the parent diamonds that become mergeable - 9
return mesh WEDGIES(tree) ▷ once, before the first frame- 10
for each triangle T of the full tree, finest first do - 11
e_T ← 0 for a leaf, else max(e_T0, e_T1) + |h(c) - (h(v0) + h(v1))/2| - 12
p(T) = e_T^2 / max(dist(eye, T)^2, d0^2) ▷ the priority
Line L4 is the forced split of Section 4.2 of the paper. In a conforming mesh, the leaf across the base of is either the partner of , or a triangle one level coarser whose leg is the base of . In the second case must be split first; the split of makes the partner of , and the next pass splits the diamond.
Lines L10 and L11 compute the wedgie thickness of Section 6.1, Equation 1: the true surface lies within of the plane of above or below each point of . A mergeable diamond is a split triangle and its partner whose four children are all leaves.
Line L12 is the priority of the code: the squared wedgie over the squared distance in the domain from the eye to the triangle, with a floor against a division by zero. It is a heuristic in place of the screen distortion of Section 6.2, which projects the wedgie with the camera. It is squared so that it stays rational, and it is monotone: a child never has a larger priority than its parent. The value of is a tuning.
Example
A forced split. Take , all heights 0 except . The five triangles with a nonzero wedgie have . Asking for the leaf that holds the point at each step gives these calls of FORCE-SPLIT.
| step | the leaf that is asked for | triangles split | leaves after |
|---|---|---|---|
| 1 | the root | 2, a diamond of the two roots | 4 |
| 2 | 1, its base is on the border | 5 | |
| 3 | 3 | 8 | |
| 4 | 1, its base is on the border | 9 |
At step 3 the base of the leaf goes from to , and the leaf across it is the coarser , for which this base is a leg. Line L4 pushes it, line L5 splits it, which makes the partner , and the next pass splits the diamond. So 3 triangles are split, and the point enters the mesh without a T-junction. Step 4 is not needed for accuracy: its triangle has . UPDATE with from any eye gives the 8 leaves after step 3, the smallest conforming mesh that shows the surface exactly.
Error bounds. On an grid with random heights from 0 to 10 (the seed 1), the full tree has 254 triangles, and 126 of them have children. The two roots have the wedgies and 33. With the eye over the point and , UPDATE from the two roots gives these meshes.
| 1/4 | 1/2 | 1 | 2 | |
|---|---|---|---|---|
| leaves | 116 | 110 | 88 | 56 |
With , moving the eye from to and running UPDATE on the old mesh splits 2 triangles and merges none, so the mesh goes from 110 to 112 leaves. The result equals the mesh that a fresh run from the two roots gives for the new eye.
Correctness
The proof file gives the full arguments, and the tests check them on random grids.
- The wedgies. For every triangle and point in it, the surface of the full grid differs from the plane of by at most , and (a proved property, by induction from the finest level).
- Forced splits. From a conforming mesh, FORCE-SPLIT ends, splits , keeps the mesh conforming after each split, and splits at most triangles for a leaf of level (a proved property).
- One frame. With the monotone priority of line L12, UPDATE from any conforming mesh ends with the split set equal to the smallest set that holds every triangle with and is closed under parents and partners. So the result does not depend on the mesh of the last frame (a proved property).
- Optimality. That mesh has the fewest leaves among all conforming meshes whose leaves have , and it is the only one with that number. This is the optimality claim of Section 5.1 in a precise form (a proved property). The test checks it by enumerating all 5489 conforming meshes of the grid.
The claim needs a monotone priority. A priority that can grow from a parent to a child can hide a child with a large error below a parent with a small one, and the split phase then stops before the child is reached. Any other priority, such as the screen distortion of the paper, must be checked for this property before the optimality claim is used.
Proof: The ROAM wedgies bound the surface, forced splits keep the mesh conforming, and with monotone priorities a frame ends at the unique smallest conforming triangulation whose leaves all meet the error boundfull
We use the notation of the page. The domain is the square with , and gives a height to each grid point. A bintree triangle has the apex at its right angle and the base . Its children are and , where is the midpoint of the base. The two roots have level 0, and a child has the level of its parent plus 1. A triangle of level has legs of length and a base of length . The partner of is the triangle of the same level that shares its base, if the base is not on the border of the square. Heights and priorities are exact rationals.
A mesh is the set of leaves of a cut of the bintree: a set of split triangles that holds the parent of each of its members, and whose leaves are the triangles not in whose parent is in (or the roots, when they are not in ). The leaves tile the square. Two bintree triangles are either nested or have disjoint interiors. A mesh is conforming when no vertex of a leaf lies inside an edge of another leaf; then each edge of a leaf is an edge of exactly one other leaf, or lies on the border.
We use one fact of the construction. For each level , the triangles of level form a conforming triangulation of the square, and its vertex set grows with . (Even levels are square grids of spacing cut by diagonals; odd levels are the grids of diamonds between them.) The midpoint of a base of a level triangle is in but not in .
The wedgies
Let be the surface over the finest level: on each leaf of the full bintree, the plane through its three corners. Let be the plane over through its three corners. Lines L10 and L11 compute for a leaf of the full bintree and otherwise. This is Equation (1) of Duchaineau et al., with the height written in place of their .
Lemma 1. For every bintree triangle and every domain point , . Also .
Proof. The second claim holds because the gap term is nonnegative. The first is by induction from the finest level. On a leaf of the full bintree, . For an inner , let . Then . The first term is at most by induction. The difference is affine on , so its largest absolute value on is at a corner. It is 0 at the corners and , which shares with . At it is , because is the midpoint of the base and is affine. So the sum is at most .
Lemma 2. The priority of line L12, , is monotone: .
Proof. by Lemma 1, and , so the distance from the eye to is at least the distance to .
The priority is the square of the bound of the page, so that it stays rational; the order is the same. It is a heuristic for the screen error: it bounds the error of the height as seen from the eye up to the factor of the projection, but not the error of the line of sight as in Section 6.2 of the paper.
Forced splits
Lemma 3. In a conforming mesh, let be a leaf and the leaf that has the base of as an edge. Either is the partner of (the same level, the same base), or the base of is a leg of and has the level of minus 1.
Proof. The shared edge has the length for the level of . If it is the base of , then has level and shares its base with , so is the partner. If it is a leg of , then .
Lemma 4. If the mesh is conforming and is a leaf with children, FORCE-SPLIT (lines L1 to L5) ends, is split at the end, the mesh is conforming after each split, and at most triangles are split.
Proof. A split of a leaf with no base neighbor (base on the border) keeps the mesh conforming: the legs of become the bases of its children with the same neighbors, the new edge is shared by the two children, and the two halves of the base are on the border. A split of a diamond, a leaf and its partner, also keeps it: the two halves of the common base are each shared by one child of and one child of the partner.
The stack holds triangles whose levels decrease by 1 from each entry to the next one above it. This holds at the start. Line L4 pushes only when the base of the top is a leg of , and then has the level of minus 1 by Lemma 3. Line L5 splits the top and its partner, or alone on the border, and these are the two cases that keep the mesh conforming. A split removes only the top entry and its partner, which have the level of the top. All entries below are finer, so they stay leaves. After the split of , its child whose base is the old leg is a leaf, and it is the new base neighbor of the entry below, with the same base. So the next pass splits that entry with it as a diamond.
The stack has at most entries. Each pass pops, pushes, or splits and pops. Each push puts a strictly coarser triangle on top, so there are at most pushes in a row, and each split pops one entry. So the loop ends. The bottom entry is popped only after it is split, because it stays a leaf until line L5 splits it. Each level gives at most one diamond, so at most splits happen.
A conforming mesh is closed under partners
Lemma 5. If a mesh with split set is conforming, then holds the partner of each of its members.
Proof. Let with partner , and suppose . Then lies in a leaf : or a proper ancestor of . The midpoint of the common base is a vertex of a child of , so of a leaf inside . The leaf is not an ancestor of (it is not split) and not inside (it holds ), so it does not overlap the interior of , and , which lies on the boundary of , is not in the interior of . So is on the boundary of . The level of is at most , so the vertices of are in , and is not. So is inside an edge of , and the mesh is not conforming.
One frame
Let , let , and let be the smallest set that holds and the parent and the partner of each of its members. This is the set that target builds. A triangle in has , so it has children.
Theorem 6. Start from any conforming mesh. After UPDATE (lines L6 to L9), the split set is exactly . So the mesh is the set of leaves of , whatever mesh the frame started from.
Proof. The split phase (lines L6 and L7). The heap holds an entry for each leaf: all leaves at the start, and each leaf that a split adds. The phase pops entries in the order of priority, skips those that are no longer leaves, and force-splits a leaf with . It stops at a leaf with , and all remaining entries have a priority no larger. Each force split adds new leaves, so the phase ends after a finite number of splits (the bintree is finite). At its end every leaf has , and the mesh is conforming by Lemma 4. Now let . If were not split, then a leaf would be or an ancestor of , and by Lemma 2. So . By Lemma 5 and the parent rule, .
The merge phase (line L8). A diamond (with its partner , or alone on the border) is mergeable when is split and all children of and of are leaves. A merge removes and from . The new leaves and have as legs the bases of the old children, with the same neighbors, and the common base is shared by and , so the mesh stays conforming. The phase merges only diamonds with , so it never removes a member of , and stays true. A diamond becomes mergeable only when a merge makes the last of its children a leaf, and then its parent diamond is pushed. So when the phase stops, every mergeable diamond has a priority above .
No extra split remains. Suppose is not empty, and let be a member of the greatest level. A child of in would be in by the choice of , and then its parent would be in . So both children of are leaves. The partner , if any, is in by Lemma 5, and not in , because holds the partners of its members and the partner of is . So the children of are leaves too. The diamond of is mergeable, and its priority is at most , because . This contradicts the end of the merge phase. So .
Corollary 7. Among the conforming meshes whose leaves all have , the mesh of Theorem 6 has the fewest triangles, and it is the only one with that number.
Proof. Such a mesh has a split set that holds (the argument of the split phase) and is closed under parents and partners (Lemma 5), so it holds . A mesh with the split set has leaves, because each split adds one leaf. So it has at least leaves, with equality only when its split set is .
This is the optimality statement of Section 5.1 of the paper in a precise form, and it needs the monotone priority of Lemma 2: with a priority that can grow from a parent to a child, the split phase can keep a leaf with a priority of at most that hides a descendant above , and the result is then not accurate. The test checks Theorem 6 against target and Corollary 7 by enumeration of all 5489 conforming meshes of the grid.
Complexity
Lines L10 and L11 visit each of the triangles of the full tree once, so the wedgies take time and space. For a frame that starts and ends with at most leaves and makes splits and merges, the code puts entries in the two heaps, each at , so a frame costs in the worst case. The paper keeps both queues from frame to frame and recomputes only the priorities that change, so the work of a frame is about proportional to the number of changes (Section 5.2). In the code the split heap is built from all leaves each frame, which is simpler and shows the result, not the speed.
Properties
- Conforming at every step. No split or merge makes a crack or a T-junction (a proved property).
- Independent of history. With a monotone priority and a fixed , the mesh of a frame depends only on the view, not on the mesh before it (a proved property).
- Smallest. No conforming mesh with fewer triangles meets the bound at every leaf (a proved property).
- Coherent. A small move of the eye gives few splits and merges; the example moves the eye by one cell and splits 2 triangles (a measurement).
- Pops. A split changes the surface at once. The change is at most the wedgie of the triangle, so a small keeps it small on the screen, but it is still a jump.
Variants and improvements
- Screen distortion. The paper projects the wedgie with the camera, so the error is in pixels and a wedgie seen along the line of sight counts little (Section 6.2, Equations 2 and 3).
- Frustum culling. Each triangle keeps a label for each plane of the view frustum: inside, outside or across. The children of a triangle that is inside a plane are inside it too, so only the labels across a plane need a new test (Section 7.1). See frustum culling.
- A triangle budget. The queues can stop at a target number of triangles in place of an error bound, so that the cost of a frame stays about fixed (a tuning).
- Morphs. Each split and merge can blend the new vertex from the midpoint of the base to its height over a few frames, as in geomorphing.
- Patches. Later systems refine patches of many triangles in place of single triangles, so that the GPU gets large batches. Geometry clipmaps take this further with fixed grids.
When to use it
ROAM fits a height field on a regular grid that is seen from near and far at the same time, as in a flight simulator, when the CPU builds the mesh each frame and a fixed error bound or a fixed triangle count is wanted. On current GPUs, the work per triangle and the many small changes make it slower than methods that draw large fixed grids, such as geometry clipmaps. For meshes that are not height fields, use view-dependent refinement.
Pitfalls
- Splitting one side of a diamond. If line L5 splits and not its partner , the midpoint of the shared base is a vertex of 's children inside an edge of , and the mesh has a T-junction that can show a crack.
- No forced split. If line L4 is left out and line L5 splits when is coarser, the new vertex lies inside a leg of , and the mesh has a T-junction there.
- A wedgie that is not nested. If line L11 uses only the gap without the children, the value is not a bound: a parent with a gap of 0 hides children with a large error, and the split phase stops too early.
- The wrong order. Line L10 must visit the finest triangles first; from coarse to fine, line L11 reads wedgies of the children that are not yet computed.
- No floor in the priority. Line L12 with divides by zero when the eye is above the triangle.
- A distance to one point. If line L12 uses the distance to the center of in place of the nearest point of , a child can be nearer to the eye than its parent's center, the priority is not monotone, and the result of a frame is no longer the smallest accurate mesh.
- Merging a half diamond. If line L8 merges a triangle without its partner, the result has a T-junction at the midpoint of their base.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roam-terrain/. The authors are listed in prov/5KAMME.jsonl.
"""ROAM: a triangle bintree over a height grid, kept as a conforming mesh
by forced splits and diamond merges, with split and merge queues.
The domain is the square [0, M] x [0, M] with M = 2^k. A domain point is a
pair (x, y) of integers; the height of a grid vertex is h[(x, y)]. (The world
of this site is y up; here the pair names a point of the ground plane and the
height is a separate value, as in Duchaineau et al., who call it z.)
A triangle is a tuple (a, v0, v1): the apex a is the right-angle vertex and
(v0, v1) is the base (the hypotenuse). All triangles are counterclockwise.
The children of T = (a, v0, v1) with base midpoint c are T0 = (c, a, v0) and
T1 = (c, v1, a). All arithmetic on heights and priorities is exact.
"""
import heapq
from fractions import Fraction
def midpoint(T):
_, v0, v1 = T
sx, sy = v0[0] + v1[0], v0[1] + v1[1]
if sx % 2 or sy % 2:
return None
return (sx // 2, sy // 2)
def base(T):
return frozenset((T[1], T[2]))
def edges_of(T):
a, v0, v1 = T
return (frozenset((a, v0)), frozenset((v0, v1)), frozenset((v1, a)))
class Bintree:
"""The full triangle bintree of the grid and the wedgie thickness of every triangle."""
def __init__(self, k, h):
m = 2 ** k
self.m = m
self.h = h
self.roots = (((0, 0), (m, 0), (0, m)), ((m, m), (0, m), (m, 0)))
self.children = {}
self.parent = {}
self.all = []
stack = list(self.roots)
while stack:
t = stack.pop()
self.all.append(t)
c = midpoint(t)
if c is None:
continue
a, v0, v1 = t
kids = ((c, a, v0), (c, v1, a))
self.children[t] = kids
for u in kids:
self.parent[u] = t
stack.append(u)
self.err = {}
for t in reversed(self.all): # @line L10
if t in self.children:
t0, t1 = self.children[t]
_, v0, v1 = t
c = midpoint(t)
gap = abs(h[c] - Fraction(h[v0] + h[v1], 2))
self.err[t] = max(self.err[t0], self.err[t1]) + gap # @line L11
else:
self.err[t] = Fraction(0)
def partner(self, t):
"""The triangle of the same level that shares the base of t, or None on the border."""
a, v0, v1 = t
b = (v0[0] + v1[0] - a[0], v0[1] + v1[1] - a[1])
if 0 <= b[0] <= self.m and 0 <= b[1] <= self.m:
return (b, v1, v0)
return None
def dist2_point_triangle(p, t):
"""Exact squared distance from the point p to the closed triangle t."""
a, b, c = t
def cross(o, u, v):
return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])
if cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0:
return Fraction(0)
best = None
for u, v in ((a, b), (b, c), (c, a)):
dx, dy = v[0] - u[0], v[1] - u[1]
s = Fraction((p[0] - u[0]) * dx + (p[1] - u[1]) * dy, dx * dx + dy * dy)
s = min(max(s, Fraction(0)), Fraction(1))
qx, qy = u[0] + s * dx - p[0], u[1] + s * dy - p[1]
d = qx * qx + qy * qy
best = d if best is None else min(best, d)
return best
def make_priority(tree, eye, d0):
"""The squared priority (e_T / max(dist(eye, T), d0))^2 of each triangle."""
cache = {}
def prio(t):
if t not in cache:
e = tree.err[t]
cache[t] = e * e / max(dist2_point_triangle(eye, t), Fraction(d0) ** 2) # @line L12
return cache[t]
return prio
class Mesh:
"""A conforming triangulation made of bintree triangles, with an edge map."""
def __init__(self, tree, active=None):
self.tree = tree
self.active = set()
self.edges = {}
self.added = []
for t in (tree.roots if active is None else active):
self._add(t)
def _add(self, t):
self.active.add(t)
self.added.append(t)
for e in edges_of(t):
self.edges.setdefault(e, set()).add(t)
def _remove(self, t):
self.active.remove(t)
for e in edges_of(t):
s = self.edges[e]
s.discard(t)
if not s:
del self.edges[e]
def split(self, t):
self._remove(t)
for u in self.tree.children[t]:
self._add(u)
def base_neighbor(self, t):
others = self.edges.get(base(t), set()) - {t}
return next(iter(others)) if others else None
def force_split(self, t):
stack = [t] # @line L1
while stack: # @line L2
t = stack[-1]
if t not in self.active:
stack.pop()
continue
b = self.base_neighbor(t) # @line L3
if b is not None and base(b) != base(t):
stack.append(b) # @line L4
continue
self.split(t) # @line L5
if b is not None:
self.split(b)
stack.pop()
def mergeable(self, t):
tree = self.tree
if t not in tree.children or t in self.active:
return False
for u in (t, tree.partner(t)):
if u is not None and not all(k in self.active for k in tree.children[u]):
return False
return True
def merge(self, t):
for u in (t, self.tree.partner(t)):
if u is None:
continue
for k in self.tree.children[u]:
self._remove(k)
self._add(u)
def update(mesh, prio, eps):
"""One frame: split every leaf whose priority is above eps, then merge
every diamond whose priority is at most eps. Returns the mesh."""
tree = mesh.tree
eps2 = Fraction(eps) ** 2
qs = [(-prio(t), t) for t in mesh.active] # @line L6
heapq.heapify(qs)
while qs: # @line L7
p, t = heapq.heappop(qs)
if t not in mesh.active:
continue
if -p <= eps2:
break
mesh.added = []
mesh.force_split(t)
for u in mesh.added:
heapq.heappush(qs, (-prio(u), u))
def diamond(t):
u = tree.partner(t)
key = min(t, u) if u is not None else t
return (max(prio(t), prio(u)) if u is not None else prio(t), key)
qm = []
for t in {tree.parent[u] for u in mesh.active if u in tree.parent}:
if mesh.mergeable(t):
heapq.heappush(qm, diamond(t))
while qm: # @line L8
mp, t = heapq.heappop(qm)
if not mesh.mergeable(t):
continue
if mp > eps2:
break
mesh.merge(t)
for u in (t, tree.partner(t)):
if u is not None and u in tree.parent and mesh.mergeable(tree.parent[u]):
heapq.heappush(qm, diamond(tree.parent[u]))
return mesh # @line L9
def target(tree, prio, eps):
"""A second method: the leaves of the closure of {T : priority > eps}
under the parent and same-level partner relations."""
eps2 = Fraction(eps) ** 2
stack = [t for t in tree.children if prio(t) > eps2]
closed = set()
while stack:
t = stack.pop()
if t in closed:
continue
closed.add(t)
for u in (tree.parent.get(t), tree.partner(t)):
if u is not None:
stack.append(u)
return {t for t in tree.all if t not in closed and (t not in tree.parent or tree.parent[t] in closed)}
def interpolate(t, h, p):
"""The height at domain point p of the plane through the corners of t."""
a, b, c = t
det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
wb = Fraction((p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1]), det)
wc = Fraction((b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1]), det)
return (1 - wb - wc) * h[a] + wb * h[b] + wc * h[c]
def contains(t, p):
a, b, c = t
def cross(o, u, v):
return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
def random_heights(rng, m, amp=10):
return {(x, y): rng.randint(0, amp) for x in range(m + 1) for y in range(m + 1)}
test_roam_terrain.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roam-terrain/. The authors are listed in prov/5KAMME.jsonl.
import random
from fractions import Fraction
from roam_terrain import (
Bintree,
Mesh,
base,
contains,
edges_of,
interpolate,
make_priority,
random_heights,
target,
update,
)
def conforming(mesh):
m = mesh.tree.m
verts = {v for t in mesh.active for v in t}
area2 = 0
for t in mesh.active:
a, b, c = t
area2 += (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
if area2 != 2 * m * m:
return False
for e, ts in mesh.edges.items():
p, q = tuple(e)
border = (p[0] == q[0] and p[0] in (0, m)) or (p[1] == q[1] and p[1] in (0, m))
if len(ts) != (1 if border else 2):
return False
for v in verts:
if v in (p, q):
continue
cr = (q[0] - p[0]) * (v[1] - p[1]) - (q[1] - p[1]) * (v[0] - p[0])
if cr == 0 and min(p[0], q[0]) <= v[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= v[1] <= max(p[1], q[1]):
return False
return True
def setup(rng, k):
m = 2 ** k
tree = Bintree(k, random_heights(rng, m))
eye = (Fraction(rng.randint(0, 4 * m), 4), Fraction(rng.randint(0, 4 * m), 4))
return tree, eye
def test_wedgie_bounds_the_true_surface():
rng = random.Random(1)
tree, _ = setup(rng, 3)
pts = list(tree.h)
for t in tree.all:
worst = max(abs(tree.h[p] - interpolate(t, tree.h, p)) for p in pts if contains(t, p))
assert worst <= tree.err[t]
if t in tree.children:
assert all(tree.err[u] <= tree.err[t] for u in tree.children[t])
def test_partner_is_in_the_tree_and_priorities_are_monotone():
rng = random.Random(2)
tree, eye = setup(rng, 4)
prio = make_priority(tree, eye, 1)
known = set(tree.all)
for t in tree.all:
u = tree.partner(t)
if u is not None:
assert u in known and base(u) == base(t) and tree.partner(u) == t
for c in tree.children.get(t, ()):
assert prio(c) <= prio(t)
def test_force_split_keeps_the_mesh_conforming():
rng = random.Random(3)
tree, _ = setup(rng, 4)
mesh = Mesh(tree)
for _ in range(60):
t = rng.choice(sorted(t for t in mesh.active if t in tree.children))
mesh.force_split(t)
assert t not in mesh.active
assert conforming(mesh)
def test_frame_reaches_the_closure_and_every_leaf_is_accurate():
rng = random.Random(4)
for _ in range(6):
tree, eye = setup(rng, 4)
eps = Fraction(rng.randint(1, 12), 8)
prio = make_priority(tree, eye, 1)
mesh = update(Mesh(tree), prio, eps)
assert mesh.active == target(tree, prio, eps)
assert conforming(mesh)
assert all(prio(t) <= eps * eps for t in mesh.active)
def test_incremental_frames_equal_a_fresh_build():
rng = random.Random(5)
tree, eye = setup(rng, 4)
mesh = Mesh(tree)
eps = Fraction(1, 2)
for _ in range(8):
eye = (min(max(eye[0] + Fraction(rng.randint(-8, 8), 4), 0), 16),
min(max(eye[1] + Fraction(rng.randint(-8, 8), 4), 0), 16))
eps = min(max(eps + Fraction(rng.randint(-2, 2), 8), Fraction(1, 8)), Fraction(2))
prio = make_priority(tree, eye, 1)
update(mesh, prio, eps)
fresh = update(Mesh(tree), prio, eps)
assert mesh.active == fresh.active
assert conforming(mesh)
def test_result_is_the_smallest_accurate_triangulation_by_enumeration():
rng = random.Random(6)
tree, eye = setup(rng, 2)
start = frozenset(tree.roots)
seen = {start}
todo = [start]
while todo:
s = todo.pop()
for t in s:
if t in tree.children:
mesh = Mesh(tree, s)
mesh.force_split(t)
n = frozenset(mesh.active)
if n not in seen:
seen.add(n)
todo.append(n)
assert len(seen) == 5489
assert all(conforming(Mesh(tree, s)) for s in sorted(seen, key=sorted)[::25])
for eps in (Fraction(1, 4), Fraction(1, 2), Fraction(1), Fraction(2)):
prio = make_priority(tree, eye, 1)
ok = [s for s in seen if all(prio(t) <= eps * eps for t in s)]
best = min(len(s) for s in ok)
winners = [s for s in ok if len(s) == best]
got = frozenset(update(Mesh(tree), prio, eps).active)
assert winners == [got]
History
Lindstrom and others had shown continuous terrain level of detail on regular grids at SIGGRAPH 96. Duchaineau, Wolinsky, Sigeti, Miller, Aldrich and Mineev-Weinstein presented ROAM at IEEE Visualization 97. The paper put the forced splits of the triangle bintree, the nested wedgie bounds and the two queues together, and it gave the optimality of the split queue for monotone priorities. Many terrain engines of the following years used ROAM or variants of it. As GPUs grew, methods that send large fixed blocks of triangles, such as geometry clipmaps in 2004, took its place in many systems.
References
- Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich and Mark B. Mineev-Weinstein, ROAMing terrain, real-time optimally adapting meshes, Proceedings of IEEE Visualization 97, 81 to 88, Section 4.1 (the triangle bintree), Section 4.2 (forced splits, Figure 5), Section 5.1 (the split queue and the optimality), Section 5.2 (the merge queue), Section 6.1 (the wedgie thickness, Equation 1), Section 6.2 (the screen distortion, Equations 2 and 3) and Section 7.1 (frustum culling)
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, the part on terrain level of detail in the chapter on acceleration algorithms (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5KAMME Edit this page History Report an error Markdown