Algorithm Search⌘K

Algorithmresearch

Frame-field hex meshing

Also called CubeCover.

Computes a smooth 3D frame field in a solid and an integer-grid map aligned to it, as Nieser, Reitebuch and Polthier did, whose integer isosurfaces form the hexes.

Time
O(F) worst
Space
O(1) extra
Where
F = the number of free cells (one sweep)
Properties
deterministicnot exactiterative
Origin
Matthias Nieser, Ulrich Reitebuch, Konrad Polthier, 2011

A frame field method makes a hex mesh of a solid in three steps. First it computes a frame field: at each point of the solid, a small cube orientation, aligned with the boundary and as smooth as possible. Then it computes an integer grid map, a map from the solid into space whose gradient follows the frames and which sends the singular curves of the field to integer grid lines. Last it extracts the hexes as the preimages of the cells of the integer grid. This page is one method for hexahedral mesh generation, and it guides the hexes by a field that can follow any shape, while that page states the general problem and its limits. The code on this page implements one simple step of the first stage, a local smoothing sweep of a frame field on a grid of cells, and it is not the published field solvers.

In plain words

Fill a solid with many tiny dice. Each die can turn, but the dice next to a wall must lie flat against it. Now turn each inner die a little so that it looks like its neighbours. After many such turns the dice change their direction smoothly through the solid.

Some places cannot be made smooth, and there the dice turn around a line in a way that never fits. These lines become the edges of the mesh where more or fewer than four hexes meet.

Next, draw a 3D grid that follows the dice everywhere, with grid lines through the bad lines. The cells of this grid are the hexes. A die looks the same after a quarter turn, so turning by 90 degrees between two dice costs nothing.

The problem

A frame is a rotation R∈SO(3)R \in SO(3), whose columns and their negatives give the six directions of a cube. Two rotations RR and RgRg with gg in the octahedral group OO, the 24 signed permutation matrices with determinant +1+1, give the same frame. The core step works on a grid of cells, each with a frame. Boundary cells are fixed, and the free cells must be chosen to make the smoothness energy small:

E=∑{i,j} adjacentmin⁡g∈O∥Ri−Rjg∥F2=∑{i,j}(6−2max⁡g∈Otr⁡(RiTRjg)).E = \sum_{\{i, j\} \text{ adjacent}} \min_{g \in O} \lVert R_i - R_j g \rVert_F^2 = \sum_{\{i, j\}} \Big(6 - 2 \max_{g \in O} \operatorname{tr}(R_i^{\mathsf T} R_j g)\Big).

The algorithm

One sweep visits the free cells in a fixed order. At each cell it turns every neighbour frame by the best element of OO, adds the results, and replaces the frame by the nearest rotation to this sum. Line L6 finds that rotation by Horn's quaternion method: it is the eigenvector of the largest eigenvalue of a symmetric 4×44 \times 4 matrix built from the sum, found here by the cyclic Jacobi eigenvalue algorithm.

  1. FRAME-SWEEP(R, free)
  2. 1for each free cell i, in a fixed order do
  3. 2M ← the 3 × 3 zero matrix
  4. 3for each neighbour j of i do
  5. 4G ← R_j g for the g in O that maximizes tr(R_iᵀ R_j g)
  6. 5M ← M + G
  7. 6R_i ← the rotation R that maximizes tr(Rᵀ M), by Horn's quaternion method
  8. 7return R

This is a block Gauss-Seidel step on the energy, one cell at a time. The best rotation for a sum of matrices is the same problem as Wahba's problem, which the Davenport q-method also solves by a 4×44 \times 4 eigenvector.

The full method. A frame field pipeline goes on from the field, in words:

  1. Compute a smooth frame field on a tetrahedral mesh, aligned with the boundary. Published methods use a representation that has the cube symmetry built in, such as the rotations of the polynomial x4+y4+z4x^4 + y^4 + z^4 in a basis of spherical harmonics, and minimize a Dirichlet energy.
  2. Find the singular curves of the field and repair those that no hex mesh can have.
  3. Cut the solid to a ball and compute a map ff whose gradient follows the frames. Across each cut, the two sides of ff must differ by an element of OO and an integer shift, and the singular curves must map to integer grid lines. This is a mixed integer problem, often solved by rounding the integers one at a time.
  4. Extract the hexes as the preimages under ff of the cells of the integer grid.

Example

Take the 3×3×33 \times 3 \times 3 grid of cells with all frames equal to the identity, except the center cell, which is turned by an angle θ\theta about the zz axis. The center has 6 neighbours, so before the sweep E=6 (4−4cos⁡θ′)E = 6\,(4 - 4\cos\theta'), where θ′\theta' is the distance from θ\theta to the nearest multiple of 90∘90^\circ.

θ\theta EE before best gg in L4 new center frame EE after
30∘30^\circ 24−123≈3.21524 - 12\sqrt3 \approx 3.215 identity identity 00
45∘45^\circ 24−122≈7.02924 - 12\sqrt2 \approx 7.029 identity (a tie with the quarter turn) identity 00
60∘60^\circ 24−123≈3.21524 - 12\sqrt3 \approx 3.215 the quarter turn the quarter turn 00

The turns by 30∘30^\circ and 60∘60^\circ have the same energy, because a quarter turn changes nothing. At 60∘60^\circ the sweep moves the frame to the quarter turn, which is the same frame as the identity.

On a 4×4×44 \times 4 \times 4 grid with fixed identity frames on the boundary and 8 random inner frames (seed 0 in the tests), three sweeps give the measured energies 41.4341.43, 14.2314.23, 0.840.84 and 0.030.03.

Correctness

The full proof is below. The energy does not change when a frame is replaced by an equal frame RgRg, so it measures frames, not matrices. At a cell, with the matches of L4 fixed, the energy of its edges is 6d−2tr⁡(RiTM)6d - 2\operatorname{tr}(R_i^{\mathsf T} M). Line L6 maximizes the trace over all rotations, so the energy does not rise, and choosing the best matches again can only lower it. So one sweep never increases EE, and repeated sweeps converge to some value.

What is proved is only this monotone decrease, in exact arithmetic. The code works in floating point, and the tests check each claim to 10−910^{-9}. They compare the edge energy with a brute force over the 24 matrices of OO, check Horn's rotation against random rotations and small turns on 500 random matrices, and check on 12 random grids that every local step does not raise the energy and that each sweep lowers it. A sweep can stop at a local minimum with singular curves inside, so the limit need not be the least energy. For the whole pipeline there is no general guarantee: the field can have singular curves that no hex mesh can have, the integer grid map can fold, and the survey of Pietroni and others lists these as open problems. The quality of the meshes in the published papers is measured on test models, not proved.

Proof: A local frame update never increases the smoothness energyfull

Setting. The cells of a grid carry rotations Ri∈SO(3)R_i \in SO(3). The octahedral group OO is the set of the 24 signed permutation matrices with determinant +1+1. It is a subgroup of SO(3)SO(3), so for g∈Og \in O also g−1=gT∈Og^{-1} = g^{\mathsf T} \in O. For two face-adjacent cells,

e(i,j)=min⁡g∈O∥Ri−Rjg∥F2,E=∑{i,j}e(i,j),e(i, j) = \min_{g \in O} \lVert R_i - R_j g \rVert_F^2, \qquad E = \sum_{\{i, j\}} e(i, j),

where the sum is over the unordered pairs of face-adjacent cells. FRAME-SWEEP visits the free cells in a fixed order (L1). At the cell ii it takes, for each neighbour jj, a gj∈Og_j \in O that maximizes tr⁡(RiTRjgj)\operatorname{tr}(R_i^{\mathsf T} R_j g_j) (L4), forms M=∑jRjgjM = \sum_j R_j g_j (L2, L3 and L5), and replaces RiR_i by a rotation R′R' that maximizes tr⁡(R′TM)\operatorname{tr}(R'^{\mathsf T} M) (L6). The rotation of L6 is found by Horn's method. For a quaternion q=(w,x,y,z)q = (w, x, y, z), let R(q)R(q) be the matrix with entries that are the usual quadratic forms in qq, so that R(q)R(q) is a rotation when ∣q∣=1|q| = 1. Let NN be the symmetric 4×44 \times 4 matrix with Naa=f(ea)N_{aa} = f(e_a) and Nab=12(f(ea+eb)−f(ea)−f(eb))N_{ab} = \frac12 (f(e_a + e_b) - f(e_a) - f(e_b)) for a≠ba \ne b, where f(q)=tr⁡(R(q)TM)f(q) = \operatorname{tr}(R(q)^{\mathsf T} M), and let qq be a unit eigenvector for the largest eigenvalue of NN. Then R′=R(q)R' = R(q).

Claim. In exact arithmetic:

  1. e(i,j)=6−2max⁡g∈Otr⁡(RiTRjg)e(i, j) = 6 - 2 \max_{g \in O} \operatorname{tr}(R_i^{\mathsf T} R_j g), and e(i,j)≥0e(i, j) \ge 0. The value does not change if RiR_i is replaced by RihR_i h or RjR_j by RjhR_j h with h∈Oh \in O, and e(i,j)=e(j,i)e(i, j) = e(j, i).
  2. R(q)R(q) from L6 maximizes tr⁡(RTM)\operatorname{tr}(R^{\mathsf T} M) over all rotations RR.
  3. One update at a cell does not increase EE. It lowers EE strictly unless the old RiR_i already maximizes tr⁡(RTM)\operatorname{tr}(R^{\mathsf T} M).
  4. A sweep stops after O(F)O(F) steps for FF free cells, and the energies of repeated sweeps form a sequence that does not increase and converges.

Proof of part 1. For rotations AA and BB, ∥A−B∥F2=tr⁡(ATA)+tr⁡(BTB)−2tr⁡(ATB)=6−2tr⁡(ATB)\lVert A - B \rVert_F^2 = \operatorname{tr}(A^{\mathsf T} A) + \operatorname{tr}(B^{\mathsf T} B) - 2 \operatorname{tr}(A^{\mathsf T} B) = 6 - 2 \operatorname{tr}(A^{\mathsf T} B), because ATA=BTB=IA^{\mathsf T} A = B^{\mathsf T} B = I. Take A=RiA = R_i and B=RjgB = R_j g, and the minimum over gg becomes the maximum of the trace. A squared norm is at least 00. If RjR_j is replaced by RjhR_j h, then gg runs over hgh g, which is all of OO again because OO is a group. If RiR_i is replaced by RihR_i h, then ∥Rih−Rjg∥=∥Ri−Rjgh−1∥\lVert R_i h - R_j g \rVert = \lVert R_i - R_j g h^{-1} \rVert, because right multiplication by a rotation keeps the Frobenius norm, and gh−1g h^{-1} runs over OO. For the symmetry, ∥Ri−Rjg∥=∥Rig−1−Rj∥=∥Rj−Rig−1∥\lVert R_i - R_j g \rVert = \lVert R_i g^{-1} - R_j \rVert = \lVert R_j - R_i g^{-1} \rVert.

Proof of part 2. Each entry of R(q)R(q) is a quadratic form in qq, so f(q)=tr⁡(R(q)TM)f(q) = \operatorname{tr}(R(q)^{\mathsf T} M) is a quadratic form in qq. A quadratic form qTNqq^{\mathsf T} N q with NN symmetric has qTNq=Naaq^{\mathsf T} N q = N_{aa} at eae_a and Naa+2Nab+NbbN_{aa} + 2 N_{ab} + N_{bb} at ea+ebe_a + e_b, so the formulas for NN recover the unique symmetric matrix with f(q)=qTNqf(q) = q^{\mathsf T} N q for every qq. Every rotation is R(q)R(q) for some unit quaternion qq. Hence the largest value of tr⁡(RTM)\operatorname{tr}(R^{\mathsf T} M) over rotations is the largest value of qTNqq^{\mathsf T} N q over unit vectors q∈R4q \in \mathbb{R}^4. By the Rayleigh quotient theorem for symmetric matrices, this is the largest eigenvalue of NN, and it is taken at each unit eigenvector of that eigenvalue.

Proof of part 3. Only the edges at ii depend on RiR_i. With the gjg_j of L4, the energy of these edges before the update is

∑je(i,j)=∑j(6−2tr⁡(RiTRjgj))=6d−2tr⁡(RiTM),\sum_j e(i, j) = \sum_j \big(6 - 2 \operatorname{tr}(R_i^{\mathsf T} R_j g_j)\big) = 6 d - 2 \operatorname{tr}(R_i^{\mathsf T} M),

with dd the number of neighbours, by part 1 and the choice of gjg_j. After the update, with the same gjg_j, the sum 6d−2tr⁡(R′TM)6 d - 2 \operatorname{tr}(R'^{\mathsf T} M) is at most the old value by part 2. The true energy after the update takes the best gg for each edge, which is at most the value with the fixed gjg_j. So the edges at ii do not gain energy, and the other edges are unchanged. If the old RiR_i does not maximize tr⁡(RTM)\operatorname{tr}(R^{\mathsf T} M), the inequality of part 2 is strict, and so is the decrease.

Proof of part 4. A sweep visits each free cell once. A cell has at most 6 neighbours, L4 tries 24 matrices for each, and L6 works on a fixed 4×44 \times 4 matrix, so each visit takes O(1)O(1) steps. By part 3 the energy does not increase after any visit, and by part 1 it is at least 00. A sequence of reals that does not increase and is bounded below converges. ■\blacksquare

Remarks. The limit need not be the least energy. A field can stop at a local minimum with singular curves inside. The code works in floating point and runs a cyclic Jacobi solver until the off-diagonal part is tiny, so the tests check the claims up to a tolerance of 10−910^{-9}. The claims say nothing about the integer grid map or the hex mesh that a full method builds from the field. That step has no general guarantee.

Complexity

A free cell has at most 6 neighbours, L4 tries 24 matrices for each, and L6 works on a fixed 4×44 \times 4 matrix. So one sweep takes O(F)O(F) time for FF free cells and O(1)O(1) extra space. The number of sweeps needed is not bounded in general. In a full method, the integer grid map, a mixed integer problem, is the costly step.

Properties

  • Symmetry built into the energy. The best match over OO makes the energy depend only on the frames, so a quarter turn between two cells costs nothing.
  • Monotone. Each local update lowers the energy or keeps it, but it can stop in a local minimum.
  • Not exact. The rotation of L6 comes from an iterative eigen solver in floating point.
  • General output. A frame field can describe the singular structure of any hex mesh, so the method is not limited to a class of shapes, unlike sweeping or polycubes.
  • Over-general. A smooth field can also have singularities that no hex mesh has, such as a curve where 3 and 5 hexes meet on its two sides.

Variants and improvements

  • Spherical harmonics. Huang, Tong, Wei and Bao write a frame as a vector of 9 coefficients, solve a relaxed smooth problem, and project back onto frames.
  • Frames at vertices. Ray, Sokolov and Lévy put the frames on the vertices of the tetrahedral mesh and make the projection fast.
  • Fixed singularities. Some methods let the user fix the singular curves first and then compute a field with exactly these singularities.
  • Robust extraction. Lyon, Bommes and Kobbelt extract the hexes from a map that is only mostly valid.
  • Hex-dominant output. When the map folds in a few places, some methods keep a hex-dominant mesh with a few other cells there.

When to use it

Use a frame field method when the hexes must follow curved boundaries or inner features at many angles and some failures are acceptable, as in research codes and for smooth shapes. For a solid with a sweep direction, sweeping is safer. For box-like shapes, a polycube gives a simpler structure. The local sweep on this page is a teaching step and a cheap smoother, not a full field solver.

Pitfalls

  • Local minima. Random initial frames can lead to a field with extra singular curves. Start from a good guess, such as the boundary frames spread inward.
  • Non-meshable singularities. Check the singular curves of the field before the map, and repair them.
  • Ties in L4. At an angle of 45∘45^\circ two matches are equally good. A fixed rule, such as the first in a fixed order, keeps the sweep deterministic.
  • Floating point. Stop the Jacobi solver with a relative test. An absolute test such as 10−1510^{-15} on the squared off-diagonal left eigenvector errors near 10−810^{-8} in the tests.
  • No guarantee of hexes. Even a good field can give a map that folds, and then the extraction gives no valid hex mesh.

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.

frame_field_hex_meshing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frame-field-hex-meshing/. The authors are listed in prov/WR7B7E.jsonl.

"""One smoothing sweep of a 3D frame field on a grid of cells.

A frame is a rotation matrix R whose three columns, with their negatives, are
the six directions of a cube. Two rotations R and R g with g in the
octahedral group O (the 24 signed permutation matrices with determinant +1)
describe the same frame. The smoothness energy of an edge between cells i
and j is the least squared distance between the two frames,

    e(i, j) = min over g in O of |R_i - R_j g|^2 = 6 - 2 max over g of tr(R_i^T R_j g),

and the energy of a field is the sum over the face-adjacent pairs of cells.
One sweep visits the free cells in a fixed order. For each it matches every
neighbour frame to the current frame by the best g, and replaces the frame by
the rotation closest to the sum of the matched neighbours, found by Horn's
quaternion method with a cyclic Jacobi eigen solver. This is a simple local
step, not the published methods of Huang and others (2011) or Ray and others
(2016). Floating point arithmetic is used, with tolerances in the tests.
"""

import math
from itertools import permutations, product
from typing import Dict, List, Sequence, Tuple

Matrix = List[List[float]]
Cell = Tuple[int, int, int]


def mat_mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
    return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]


def transpose(a: Sequence[Sequence[float]]) -> Matrix:
    return [[a[j][i] for j in range(3)] for i in range(3)]


def det(a: Sequence[Sequence[float]]) -> float:
    return (
        a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
        - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
        + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
    )


def inner(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> float:
    """tr(a^T b), the sum of the products of matching entries."""
    return sum(a[i][j] * b[i][j] for i in range(3) for j in range(3))


def octahedral_group() -> List[Matrix]:
    """The 24 signed permutation matrices with determinant +1."""
    out = []
    for perm in permutations(range(3)):
        for signs in product((1, -1), repeat=3):
            g = [[0.0] * 3 for _ in range(3)]
            for i in range(3):
                g[i][perm[i]] = float(signs[i])
            if det(g) > 0:
                out.append(g)
    return out


OCTA = octahedral_group()


def best_match(r_i: Matrix, r_j: Matrix) -> Matrix:
    """R_j g for the g in O that maximizes tr(R_i^T R_j g); the first one on a tie."""
    best, best_val = None, -math.inf
    for g in OCTA:
        m = mat_mul(r_j, g)
        val = inner(r_i, m)
        if val > best_val + 1e-12:
            best, best_val = m, val
    return best


def edge_energy(r_i: Matrix, r_j: Matrix) -> float:
    return 6.0 - 2.0 * inner(r_i, best_match(r_i, r_j))


def quat_to_matrix(q: Sequence[float]) -> Matrix:
    """The rotation of the quaternion (w, x, y, z), scaled by |q|^2 when q is not a unit."""
    w, x, y, z = q
    return [
        [w * w + x * x - y * y - z * z, 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), w * w - x * x + y * y - z * z, 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), w * w - x * x - y * y + z * z],
    ]


def horn_matrix(m: Matrix) -> Matrix:
    """The symmetric 4 x 4 matrix N with q^T N q = tr(R(q)^T m) for every quaternion q."""

    def f(q):
        return inner(quat_to_matrix(q), m)

    e = [[1.0 if i == k else 0.0 for k in range(4)] for i in range(4)]
    n = [[0.0] * 4 for _ in range(4)]
    for a in range(4):
        n[a][a] = f(e[a])
        for b in range(a + 1, 4):
            s = [e[a][k] + e[b][k] for k in range(4)]
            n[a][b] = n[b][a] = (f(s) - n[a][a] - f(e[b])) / 2.0
    return n


def jacobi_eigen(a: Matrix, sweeps: int = 50, tol: float = 1e-28):
    """Eigenvalues and eigenvectors (columns of v) of a symmetric matrix by cyclic Jacobi.

    Stops when the squared off-diagonal mass is below tol times the squared Frobenius norm.
    """
    n = len(a)
    a = [row[:] for row in a]
    v = [[1.0 if i == k else 0.0 for k in range(n)] for i in range(n)]
    total = sum(x * x for row in a for x in row)
    for _ in range(sweeps):
        off = sum(a[i][k] ** 2 for i in range(n) for k in range(n) if i != k)
        if off <= tol * total:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if abs(a[p][q]) < 1e-300:
                    continue
                theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    return [a[i][i] for i in range(n)], v


def closest_rotation(m: Matrix) -> Matrix:
    """The rotation R that maximizes tr(R^T m), by Horn's quaternion method."""
    vals, vecs = jacobi_eigen(horn_matrix(m))
    k = max(range(4), key=lambda i: vals[i])
    q = [vecs[i][k] for i in range(4)]
    norm = math.sqrt(sum(x * x for x in q))
    return quat_to_matrix([x / norm for x in q])


def neighbours(c: Cell, cells: Dict[Cell, Matrix]) -> List[Cell]:
    out = []
    for t in range(3):
        for step in (-1, 1):
            nb = list(c)
            nb[t] += step
            if tuple(nb) in cells:
                out.append(tuple(nb))
    return out


def field_energy(frames: Dict[Cell, Matrix]) -> float:
    """The sum of the edge energies over the face-adjacent pairs of cells."""
    total = 0.0
    for c in frames:
        for nb in neighbours(c, frames):
            if nb > c:
                total += edge_energy(frames[c], frames[nb])
    return total


def frame_sweep(frames: Dict[Cell, Matrix], free: Sequence[Cell]) -> Dict[Cell, Matrix]:
    """One Gauss-Seidel sweep of the local frame update over the free cells, in place."""
    for c in free:  # @line L1
        m = [[0.0] * 3 for _ in range(3)]  # @line L2
        for nb in neighbours(c, frames):  # @line L3
            matched = best_match(frames[c], frames[nb])  # @line L4
            m = [[m[i][j] + matched[i][j] for j in range(3)] for i in range(3)]  # @line L5
        frames[c] = closest_rotation(m)  # @line L6
    return frames  # @line L7


def axis_rotation(axis: int, angle: float) -> Matrix:
    """The rotation by angle (radians) about the coordinate axis 0, 1 or 2."""
    c, s = math.cos(angle), math.sin(angle)
    i, j = [t for t in range(3) if t != axis]
    r = [[1.0 if a == b else 0.0 for b in range(3)] for a in range(3)]
    r[i][i], r[i][j], r[j][i], r[j][j] = c, -s, s, c
    return r
test_frame_field_hex_meshing.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frame-field-hex-meshing/. The authors are listed in prov/WR7B7E.jsonl.

import math
import random
from itertools import product

from frame_field_hex_meshing import (
    OCTA,
    axis_rotation,
    closest_rotation,
    det,
    edge_energy,
    field_energy,
    frame_sweep,
    horn_matrix,
    inner,
    jacobi_eigen,
    mat_mul,
    quat_to_matrix,
    transpose,
)

EYE = [[1.0 if a == b else 0.0 for b in range(3)] for a in range(3)]


def random_rotation(rng):
    q = [rng.gauss(0, 1) for _ in range(4)]
    n = math.sqrt(sum(x * x for x in q))
    return quat_to_matrix([x / n for x in q])


def small_rotation(rng, eps):
    axis = [rng.gauss(0, 1) for _ in range(3)]
    n = math.sqrt(sum(x * x for x in axis))
    half = eps / 2
    return quat_to_matrix([math.cos(half)] + [math.sin(half) * x / n for x in axis])


def close(a, b, tol=1e-9):
    return all(abs(a[i][j] - b[i][j]) < tol for i in range(3) for j in range(3))


def grid(n, interior):
    frames = {c: [row[:] for row in EYE] for c in product(range(n), repeat=3)}
    free = [c for c in sorted(frames) if all(0 < c[t] < n - 1 for t in range(3))]
    for c, r in zip(free, interior):
        frames[c] = r
    return frames, free


def test_octahedral_group():
    assert len(OCTA) == 24
    keys = {tuple(map(tuple, g)) for g in OCTA}
    assert len(keys) == 24 and tuple(map(tuple, EYE)) in keys
    for g in OCTA:
        assert det(g) == 1 and close(mat_mul(transpose(g), g), EYE)
        for h in OCTA:
            assert tuple(map(tuple, mat_mul(g, h))) in keys


def test_page_example():
    for deg, before, turn in ((30, 24 - 12 * math.sqrt(3), 0), (45, 24 - 12 * math.sqrt(2), 0), (60, 24 - 12 * math.sqrt(3), 90)):
        frames, free = grid(3, [axis_rotation(2, math.radians(deg))])
        assert free == [(1, 1, 1)]
        assert abs(field_energy(frames) - before) < 1e-9
        frame_sweep(frames, free)
        assert abs(field_energy(frames)) < 1e-9
        assert close(frames[(1, 1, 1)], axis_rotation(2, math.radians(turn)))


def test_edge_energy_against_brute_force_and_symmetry():
    rng = random.Random(24)
    for _ in range(100):
        a, b = random_rotation(rng), random_rotation(rng)
        brute = min(sum((a[i][j] - mat_mul(b, g)[i][j]) ** 2 for i in range(3) for j in range(3)) for g in OCTA)
        assert abs(edge_energy(a, b) - brute) < 1e-9
        g, h = rng.choice(OCTA), rng.choice(OCTA)
        assert abs(edge_energy(mat_mul(a, g), mat_mul(b, h)) - brute) < 1e-9
        assert abs(edge_energy(b, a) - brute) < 1e-9


def test_closest_rotation_random():
    rng = random.Random(1987)
    for trial in range(500):
        if trial % 3 == 0:
            m = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(3)]
        else:
            m = [[0.0] * 3 for _ in range(3)]
            for _ in range(rng.randint(1, 6)):
                r = random_rotation(rng)
                m = [[m[i][j] + r[i][j] for j in range(3)] for i in range(3)]
        # Horn's matrix gives the trace for every quaternion
        n = horn_matrix(m)
        q = [rng.gauss(0, 1) for _ in range(4)]
        assert abs(sum(q[a] * n[a][b] * q[b] for a in range(4) for b in range(4)) - inner(quat_to_matrix(q), m)) < 1e-9
        # the Jacobi solver gives eigenpairs
        vals, vecs = jacobi_eigen(n)
        for k in range(4):
            v = [vecs[i][k] for i in range(4)]
            nv = [sum(n[i][j] * v[j] for j in range(4)) for i in range(4)]
            assert all(abs(nv[i] - vals[k] * v[i]) < 1e-9 for i in range(4))
        r = closest_rotation(m)
        assert close(mat_mul(transpose(r), r), EYE) and abs(det(r) - 1) < 1e-9
        best = inner(r, m)
        # first order condition: R^T M is symmetric at a maximizer
        s = mat_mul(transpose(r), m)
        assert all(abs(s[i][j] - s[j][i]) < 1e-8 for i in range(3) for j in range(3))
        # brute force: no random rotation and no small turn of R does better
        for _ in range(20):
            assert inner(random_rotation(rng), m) <= best + 1e-9
        for _ in range(6):
            assert inner(mat_mul(r, small_rotation(rng, 1e-3)), m) <= best + 1e-9


def test_closest_rotation_of_a_scaled_rotation():
    rng = random.Random(5)
    for _ in range(50):
        r0 = random_rotation(rng)
        c = rng.uniform(0.1, 10)
        assert close(closest_rotation([[c * x for x in row] for row in r0]), r0, 1e-8)


def test_sweep_decreases_the_energy():
    for seed in range(12):
        rng = random.Random(seed)
        frames, free = grid(4, [random_rotation(rng) for _ in range(8)])
        start = field_energy(frames)
        e = start
        for c in free:
            frame_sweep(frames, [c])
            e_new = field_energy(frames)
            assert e_new <= e + 1e-9
            e = e_new
        assert e < start - 1e-6
        for c in frames:
            r = frames[c]
            assert close(mat_mul(transpose(r), r), EYE) and abs(det(r) - 1) < 1e-9
    # the measured run on the page
    rng = random.Random(0)
    frames, free = grid(4, [random_rotation(rng) for _ in range(8)])
    energies = [field_energy(frames)]
    for _ in range(3):
        frame_sweep(frames, free)
        energies.append(field_energy(frames))
    assert [round(x, 2) for x in energies] == [41.43, 14.23, 0.84, 0.03]

History

Frame fields grew out of 2D cross fields for quad meshing. In 2011 Huang, Tong, Wei and Bao computed boundary-aligned smooth 3D frame fields with spherical harmonics, and Nieser, Reitebuch and Polthier showed how to turn a frame field into an integer grid map whose level sets give a hex mesh. Li and others repaired singularities in 2012. Ray, Sokolov and Lévy made the field practical in 2016, and Lyon, Bommes and Kobbelt made the extraction robust in the same year. Horn's quaternion method of 1987 for the best rotation is a much older result from photogrammetry.

References

  1. M. Nieser, U. Reitebuch and K. Polthier, CubeCover, parameterization of 3D volumes, Computer Graphics Forum 30(5), 2011, 1397 to 1406, the integer grid map that follows a frame field, with integer transitions and singularities on grid lines (general locator)
  2. Jin Huang, Yiying Tong, Hongyu Wei and Hujun Bao, Boundary aligned smooth 3D cross-frame field, ACM Transactions on Graphics 30(6), 2011, frames as rotations of the polynomial x^4 + y^4 + z^4 in the spherical harmonics basis, and the smoothness energy (general locator)
  3. Nicolas Ray, Dmitry Sokolov and Bruno Lévy, Practical 3D frame field generation, ACM Transactions on Graphics 35(6), 2016, article 233, frames at vertices, boundary constraints and a faster projection onto frames (general locator)
  4. Max Lyon, David Bommes and Leif Kobbelt, HexEx, robust hexahedral mesh extraction, ACM Transactions on Graphics 35(4), 2016, article 123, the extraction of the hexes from the integer level sets of the map (general locator)
  5. Berthold K. P. Horn, Closed-form solution of absolute orientation using unit quaternions, Journal of the Optical Society of America A 4(4), 1987, 629 to 642, the best rotation as the eigenvector of the largest eigenvalue of a symmetric 4 x 4 matrix, used in L6 (general locator)
  6. Nico Pietroni, Marcel Campen, Alla Sheffer, Gianmarco Cherchi, David Bommes, Xifeng Gao, Riccardo Scateni, Franck Ledoux, Jean-François Remacle and Marco Livesu, Hex-mesh generation and processing, a survey, arXiv 2202.12670, 2022, the section on frame fields, its three steps, the octahedral symmetry, and the singularities that no hex mesh can have

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example