Path: blob/master/thirdparty/meshoptimizer/simplifier.cpp
20837 views
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details1#include "meshoptimizer.h"23#include <assert.h>4#include <float.h>5#include <math.h>6#include <string.h>78#ifndef TRACE9#define TRACE 010#endif1112#if TRACE13#include <stdio.h>14#endif1516#if TRACE17#define TRACESTATS(i) stats[i]++;18#else19#define TRACESTATS(i) (void)020#endif2122// This work is based on:23// Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 199724// Michael Garland. Quadric-based polygonal surface simplification. 199925// Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 200026// Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 200327// Peter Van Sandt, Yannis Chronis, Jignesh M. Patel. Efficiently Searching In-Memory Sorted Arrays: Revenge of the Interpolation Search? 201928// Hugues Hoppe. New Quadric Metric for Simplifying Meshes with Appearance Attributes. 199929// Hugues Hoppe, Steve Marschner. Efficient Minimization of New Quadric Metric for Simplifying Meshes with Appearance Attributes. 200030namespace meshopt31{3233struct EdgeAdjacency34{35struct Edge36{37unsigned int next;38unsigned int prev;39};4041unsigned int* offsets;42Edge* data;43};4445static void prepareEdgeAdjacency(EdgeAdjacency& adjacency, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator)46{47adjacency.offsets = allocator.allocate<unsigned int>(vertex_count + 1);48adjacency.data = allocator.allocate<EdgeAdjacency::Edge>(index_count);49}5051static void updateEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* remap)52{53size_t face_count = index_count / 3;54unsigned int* offsets = adjacency.offsets + 1;55EdgeAdjacency::Edge* data = adjacency.data;5657// fill edge counts58memset(offsets, 0, vertex_count * sizeof(unsigned int));5960for (size_t i = 0; i < index_count; ++i)61{62unsigned int v = remap ? remap[indices[i]] : indices[i];63assert(v < vertex_count);6465offsets[v]++;66}6768// fill offset table69unsigned int offset = 0;7071for (size_t i = 0; i < vertex_count; ++i)72{73unsigned int count = offsets[i];74offsets[i] = offset;75offset += count;76}7778assert(offset == index_count);7980// fill edge data81for (size_t i = 0; i < face_count; ++i)82{83unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2];8485if (remap)86{87a = remap[a];88b = remap[b];89c = remap[c];90}9192data[offsets[a]].next = b;93data[offsets[a]].prev = c;94offsets[a]++;9596data[offsets[b]].next = c;97data[offsets[b]].prev = a;98offsets[b]++;99100data[offsets[c]].next = a;101data[offsets[c]].prev = b;102offsets[c]++;103}104105// finalize offsets106adjacency.offsets[0] = 0;107assert(adjacency.offsets[vertex_count] == index_count);108}109110struct PositionHasher111{112const float* vertex_positions;113size_t vertex_stride_float;114const unsigned int* sparse_remap;115116size_t hash(unsigned int index) const117{118unsigned int ri = sparse_remap ? sparse_remap[index] : index;119const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + ri * vertex_stride_float);120121unsigned int x = key[0], y = key[1], z = key[2];122123// replace negative zero with zero124x = (x == 0x80000000) ? 0 : x;125y = (y == 0x80000000) ? 0 : y;126z = (z == 0x80000000) ? 0 : z;127128// scramble bits to make sure that integer coordinates have entropy in lower bits129x ^= x >> 17;130y ^= y >> 17;131z ^= z >> 17;132133// Optimized Spatial Hashing for Collision Detection of Deformable Objects134return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791);135}136137bool equal(unsigned int lhs, unsigned int rhs) const138{139unsigned int li = sparse_remap ? sparse_remap[lhs] : lhs;140unsigned int ri = sparse_remap ? sparse_remap[rhs] : rhs;141142const float* lv = vertex_positions + li * vertex_stride_float;143const float* rv = vertex_positions + ri * vertex_stride_float;144145return lv[0] == rv[0] && lv[1] == rv[1] && lv[2] == rv[2];146}147};148149struct RemapHasher150{151unsigned int* remap;152153size_t hash(unsigned int id) const154{155return id * 0x5bd1e995;156}157158bool equal(unsigned int lhs, unsigned int rhs) const159{160return remap[lhs] == rhs;161}162};163164static size_t hashBuckets2(size_t count)165{166size_t buckets = 1;167while (buckets < count + count / 4)168buckets *= 2;169170return buckets;171}172173template <typename T, typename Hash>174static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty)175{176assert(buckets > 0);177assert((buckets & (buckets - 1)) == 0);178179size_t hashmod = buckets - 1;180size_t bucket = hash.hash(key) & hashmod;181182for (size_t probe = 0; probe <= hashmod; ++probe)183{184T& item = table[bucket];185186if (item == empty)187return &item;188189if (hash.equal(item, key))190return &item;191192// hash collision, quadratic probing193bucket = (bucket + probe + 1) & hashmod;194}195196assert(false && "Hash table is full"); // unreachable197return NULL;198}199200static void buildPositionRemap(unsigned int* remap, unsigned int* wedge, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap, meshopt_Allocator& allocator)201{202PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float), sparse_remap};203204size_t table_size = hashBuckets2(vertex_count);205unsigned int* table = allocator.allocate<unsigned int>(table_size);206memset(table, -1, table_size * sizeof(unsigned int));207208// build forward remap: for each vertex, which other (canonical) vertex does it map to?209// we use position equivalence for this, and remap vertices to other existing vertices210for (size_t i = 0; i < vertex_count; ++i)211{212unsigned int index = unsigned(i);213unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u);214215if (*entry == ~0u)216*entry = index;217218remap[index] = *entry;219}220221allocator.deallocate(table);222223if (!wedge)224return;225226// build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex?227// entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i228for (size_t i = 0; i < vertex_count; ++i)229wedge[i] = unsigned(i);230231for (size_t i = 0; i < vertex_count; ++i)232if (remap[i] != i)233{234unsigned int r = remap[i];235236wedge[i] = wedge[r];237wedge[r] = unsigned(i);238}239}240241static unsigned int* buildSparseRemap(unsigned int* indices, size_t index_count, size_t vertex_count, size_t* out_vertex_count, meshopt_Allocator& allocator)242{243// use a bit set to compute the precise number of unique vertices244unsigned char* filter = allocator.allocate<unsigned char>((vertex_count + 7) / 8);245246for (size_t i = 0; i < index_count; ++i)247{248unsigned int index = indices[i];249assert(index < vertex_count);250filter[index / 8] = 0;251}252253size_t unique = 0;254for (size_t i = 0; i < index_count; ++i)255{256unsigned int index = indices[i];257unique += (filter[index / 8] & (1 << (index % 8))) == 0;258filter[index / 8] |= 1 << (index % 8);259}260261unsigned int* remap = allocator.allocate<unsigned int>(unique);262size_t offset = 0;263264// temporary map dense => sparse; we allocate it last so that we can deallocate it265size_t revremap_size = hashBuckets2(unique);266unsigned int* revremap = allocator.allocate<unsigned int>(revremap_size);267memset(revremap, -1, revremap_size * sizeof(unsigned int));268269// fill remap, using revremap as a helper, and rewrite indices in the same pass270RemapHasher hasher = {remap};271272for (size_t i = 0; i < index_count; ++i)273{274unsigned int index = indices[i];275unsigned int* entry = hashLookup2(revremap, revremap_size, hasher, index, ~0u);276277if (*entry == ~0u)278{279remap[offset] = index;280*entry = unsigned(offset);281offset++;282}283284indices[i] = *entry;285}286287allocator.deallocate(revremap);288289assert(offset == unique);290*out_vertex_count = unique;291292return remap;293}294295enum VertexKind296{297Kind_Manifold, // not on an attribute seam, not on any boundary298Kind_Border, // not on an attribute seam, has exactly two open edges299Kind_Seam, // on an attribute seam with exactly two attribute seam edges300Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex301Kind_Locked, // none of the above; these vertices can't move302303Kind_Count304};305306// manifold vertices can collapse onto anything307// border/seam vertices can collapse onto border/seam respectively, or locked308// complex vertices can collapse onto complex/locked309// a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex310// for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore311const unsigned char kCanCollapse[Kind_Count][Kind_Count] = {312{1, 1, 1, 1, 1},313{0, 1, 0, 0, 1},314{0, 0, 1, 0, 1},315{0, 0, 0, 1, 1},316{0, 0, 0, 0, 0},317};318319// if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge320// note that for seam edges, the opposite edge isn't present in the attribute-based topology321// but is present if you consider a position-only mesh variant322// while many complex collapses have the opposite edge, since complex vertices collapse to the323// same wedge, keeping opposite edges separate improves the quality by considering both targets324const unsigned char kHasOpposite[Kind_Count][Kind_Count] = {325{1, 1, 1, 1, 1},326{1, 0, 1, 0, 0},327{1, 1, 1, 0, 1},328{1, 0, 0, 0, 0},329{1, 0, 1, 0, 0},330};331332static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b)333{334unsigned int count = adjacency.offsets[a + 1] - adjacency.offsets[a];335const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[a];336337for (size_t i = 0; i < count; ++i)338if (edges[i].next == b)339return true;340341return false;342}343344static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b, const unsigned int* remap, const unsigned int* wedge)345{346unsigned int v = a;347348do349{350unsigned int count = adjacency.offsets[v + 1] - adjacency.offsets[v];351const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[v];352353for (size_t i = 0; i < count; ++i)354if (remap[edges[i].next] == remap[b])355return true;356357v = wedge[v];358} while (v != a);359360return false;361}362363static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned int* loopback, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_lock, const unsigned int* sparse_remap, unsigned int options)364{365memset(loop, -1, vertex_count * sizeof(unsigned int));366memset(loopback, -1, vertex_count * sizeof(unsigned int));367368// incoming & outgoing open edges: ~0u if no open edges, i if there are more than 1369// note that this is the same data as required in loop[] arrays; loop[] data is only used for border/seam by default370// in permissive mode we also use it to guide complex-complex collapses, so we fill it for all vertices371unsigned int* openinc = loopback;372unsigned int* openout = loop;373374for (size_t i = 0; i < vertex_count; ++i)375{376unsigned int vertex = unsigned(i);377378unsigned int count = adjacency.offsets[vertex + 1] - adjacency.offsets[vertex];379const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[vertex];380381for (size_t j = 0; j < count; ++j)382{383unsigned int target = edges[j].next;384385if (target == vertex)386{387// degenerate triangles have two distinct edges instead of three, and the self edge388// is bi-directional by definition; this can break border/seam classification by "closing"389// the open edge from another triangle and falsely marking the vertex as manifold390// instead we mark the vertex as having >1 open edges which turns it into locked/complex391openinc[vertex] = openout[vertex] = vertex;392}393else if (!hasEdge(adjacency, target, vertex))394{395openinc[target] = (openinc[target] == ~0u) ? vertex : target;396openout[vertex] = (openout[vertex] == ~0u) ? target : vertex;397}398}399}400401#if TRACE402size_t stats[4] = {};403#endif404405for (size_t i = 0; i < vertex_count; ++i)406{407if (remap[i] == i)408{409if (wedge[i] == i)410{411// no attribute seam, need to check if it's manifold412unsigned int openi = openinc[i], openo = openout[i];413414// note: we classify any vertices with no open edges as manifold415// this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold416// it's unclear if this is a problem in practice417if (openi == ~0u && openo == ~0u)418{419result[i] = Kind_Manifold;420}421else if (openi != ~0u && openo != ~0u && remap[openi] == remap[openo] && openi != i)422{423// classify half-seams as seams (the branch below would mis-classify them as borders)424// half-seam is a single vertex that connects to both vertices of a potential seam425// treating these as seams allows collapsing the "full" seam vertex onto them426result[i] = Kind_Seam;427}428else if (openi != i && openo != i)429{430result[i] = Kind_Border;431}432else433{434result[i] = Kind_Locked;435TRACESTATS(0);436}437}438else if (wedge[wedge[i]] == i)439{440// attribute seam; need to distinguish between Seam and Locked441unsigned int w = wedge[i];442unsigned int openiv = openinc[i], openov = openout[i];443unsigned int openiw = openinc[w], openow = openout[w];444445// seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap446if (openiv != ~0u && openiv != i && openov != ~0u && openov != i &&447openiw != ~0u && openiw != w && openow != ~0u && openow != w)448{449if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw] && remap[openiv] != remap[openov])450{451result[i] = Kind_Seam;452}453else454{455result[i] = Kind_Locked;456TRACESTATS(1);457}458}459else460{461result[i] = Kind_Locked;462TRACESTATS(2);463}464}465else466{467// more than one vertex maps to this one; we don't have classification available468result[i] = Kind_Locked;469TRACESTATS(3);470}471}472else473{474assert(remap[i] < i);475476result[i] = result[remap[i]];477}478}479480if (options & meshopt_SimplifyPermissive)481for (size_t i = 0; i < vertex_count; ++i)482if (result[i] == Kind_Seam || result[i] == Kind_Locked)483{484if (remap[i] != i)485{486// only process primary vertices; wedges will be updated to match the primary vertex487result[i] = result[remap[i]];488continue;489}490491bool protect = false;492493// vertex_lock may protect any wedge, not just the primary vertex, so we switch to complex only if no wedges are protected494unsigned int v = unsigned(i);495do496{497unsigned int rv = sparse_remap ? sparse_remap[v] : v;498protect |= vertex_lock && (vertex_lock[rv] & meshopt_SimplifyVertex_Protect) != 0;499v = wedge[v];500} while (v != i);501502// protect if any adjoining edge doesn't have an opposite edge (indicating vertex is on the border)503do504{505const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[v]];506size_t count = adjacency.offsets[v + 1] - adjacency.offsets[v];507508for (size_t j = 0; j < count; ++j)509protect |= !hasEdge(adjacency, edges[j].next, v, remap, wedge);510v = wedge[v];511} while (v != i);512513result[i] = protect ? result[i] : int(Kind_Complex);514}515516if (vertex_lock)517{518// vertex_lock may lock any wedge, not just the primary vertex, so we need to lock the primary vertex and relock any wedges519for (size_t i = 0; i < vertex_count; ++i)520{521unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);522523if (vertex_lock[ri] & meshopt_SimplifyVertex_Lock)524result[remap[i]] = Kind_Locked;525}526527for (size_t i = 0; i < vertex_count; ++i)528if (result[remap[i]] == Kind_Locked)529result[i] = Kind_Locked;530}531532if (options & meshopt_SimplifyLockBorder)533for (size_t i = 0; i < vertex_count; ++i)534if (result[i] == Kind_Border)535result[i] = Kind_Locked;536537#if TRACE538printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n",539int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3]));540#endif541}542543struct Vector3544{545float x, y, z;546};547548static float rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap = NULL, float* out_offset = NULL)549{550size_t vertex_stride_float = vertex_positions_stride / sizeof(float);551552float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX};553float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX};554555for (size_t i = 0; i < vertex_count; ++i)556{557unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);558const float* v = vertex_positions_data + ri * vertex_stride_float;559560if (result)561{562result[i].x = v[0];563result[i].y = v[1];564result[i].z = v[2];565}566567for (int j = 0; j < 3; ++j)568{569float vj = v[j];570571minv[j] = minv[j] > vj ? vj : minv[j];572maxv[j] = maxv[j] < vj ? vj : maxv[j];573}574}575576float extent = 0.f;577578extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]);579extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]);580extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]);581582if (result)583{584float scale = extent == 0 ? 0.f : 1.f / extent;585586for (size_t i = 0; i < vertex_count; ++i)587{588result[i].x = (result[i].x - minv[0]) * scale;589result[i].y = (result[i].y - minv[1]) * scale;590result[i].z = (result[i].z - minv[2]) * scale;591}592}593594if (out_offset)595{596out_offset[0] = minv[0];597out_offset[1] = minv[1];598out_offset[2] = minv[2];599}600601return extent;602}603604static void rescaleAttributes(float* result, const float* vertex_attributes_data, size_t vertex_count, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned int* attribute_remap, const unsigned int* sparse_remap)605{606size_t vertex_attributes_stride_float = vertex_attributes_stride / sizeof(float);607608for (size_t i = 0; i < vertex_count; ++i)609{610unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);611612for (size_t k = 0; k < attribute_count; ++k)613{614unsigned int rk = attribute_remap[k];615float a = vertex_attributes_data[ri * vertex_attributes_stride_float + rk];616617result[i * attribute_count + k] = a * attribute_weights[rk];618}619}620}621622static void finalizeVertices(float* vertex_positions_data, size_t vertex_positions_stride, float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, size_t vertex_count, const Vector3* vertex_positions, const float* vertex_attributes, const unsigned int* sparse_remap, const unsigned int* attribute_remap, float vertex_scale, const float* vertex_offset, const unsigned char* vertex_kind, const unsigned char* vertex_update, const unsigned char* vertex_lock)623{624size_t vertex_positions_stride_float = vertex_positions_stride / sizeof(float);625size_t vertex_attributes_stride_float = vertex_attributes_stride / sizeof(float);626627for (size_t i = 0; i < vertex_count; ++i)628{629if (!vertex_update[i])630continue;631632unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i);633634// updating externally locked vertices is not allowed635if (vertex_lock && (vertex_lock[ri] & meshopt_SimplifyVertex_Lock) != 0)636continue;637638// moving locked vertices may result in floating point drift639if (vertex_kind[i] != Kind_Locked)640{641const Vector3& p = vertex_positions[i];642float* v = vertex_positions_data + ri * vertex_positions_stride_float;643644v[0] = p.x * vertex_scale + vertex_offset[0];645v[1] = p.y * vertex_scale + vertex_offset[1];646v[2] = p.z * vertex_scale + vertex_offset[2];647}648649if (attribute_count)650{651const float* sa = vertex_attributes + i * attribute_count;652float* va = vertex_attributes_data + ri * vertex_attributes_stride_float;653654for (size_t k = 0; k < attribute_count; ++k)655{656unsigned int rk = attribute_remap[k];657658va[rk] = sa[k] / attribute_weights[rk];659}660}661}662}663664static const size_t kMaxAttributes = 32;665666struct Quadric667{668// a00*x^2 + a11*y^2 + a22*z^2 + 2*a10*xy + 2*a20*xz + 2*a21*yz + 2*b0*x + 2*b1*y + 2*b2*z + c669float a00, a11, a22;670float a10, a20, a21;671float b0, b1, b2, c;672float w;673};674675struct QuadricGrad676{677// gx*x + gy*y + gz*z + gw678float gx, gy, gz, gw;679};680681struct Reservoir682{683float x, y, z;684float r, g, b;685float w;686};687688struct Collapse689{690unsigned int v0;691unsigned int v1;692693union694{695unsigned int bidi;696float error;697unsigned int errorui;698};699};700701static float normalize(Vector3& v)702{703float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);704705if (length > 0)706{707v.x /= length;708v.y /= length;709v.z /= length;710}711712return length;713}714715static void quadricAdd(Quadric& Q, const Quadric& R)716{717Q.a00 += R.a00;718Q.a11 += R.a11;719Q.a22 += R.a22;720Q.a10 += R.a10;721Q.a20 += R.a20;722Q.a21 += R.a21;723Q.b0 += R.b0;724Q.b1 += R.b1;725Q.b2 += R.b2;726Q.c += R.c;727Q.w += R.w;728}729730static void quadricAdd(QuadricGrad& G, const QuadricGrad& R)731{732G.gx += R.gx;733G.gy += R.gy;734G.gz += R.gz;735G.gw += R.gw;736}737738static void quadricAdd(QuadricGrad* G, const QuadricGrad* R, size_t attribute_count)739{740for (size_t k = 0; k < attribute_count; ++k)741{742G[k].gx += R[k].gx;743G[k].gy += R[k].gy;744G[k].gz += R[k].gz;745G[k].gw += R[k].gw;746}747}748749static float quadricEval(const Quadric& Q, const Vector3& v)750{751float rx = Q.b0;752float ry = Q.b1;753float rz = Q.b2;754755rx += Q.a10 * v.y;756ry += Q.a21 * v.z;757rz += Q.a20 * v.x;758759rx *= 2;760ry *= 2;761rz *= 2;762763rx += Q.a00 * v.x;764ry += Q.a11 * v.y;765rz += Q.a22 * v.z;766767float r = Q.c;768r += rx * v.x;769r += ry * v.y;770r += rz * v.z;771772return r;773}774775static float quadricError(const Quadric& Q, const Vector3& v)776{777float r = quadricEval(Q, v);778float s = Q.w == 0.f ? 0.f : 1.f / Q.w;779780return fabsf(r) * s;781}782783static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribute_count, const Vector3& v, const float* va)784{785float r = quadricEval(Q, v);786787// see quadricFromAttributes for general derivation; here we need to add the parts of (eval(pos) - attr)^2 that depend on attr788for (size_t k = 0; k < attribute_count; ++k)789{790float a = va[k];791float g = v.x * G[k].gx + v.y * G[k].gy + v.z * G[k].gz + G[k].gw;792793r += a * (a * Q.w - 2 * g);794}795796// note: unlike position error, we do not normalize by Q.w to retain edge scaling as described in quadricFromAttributes797return fabsf(r);798}799800static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w)801{802float aw = a * w;803float bw = b * w;804float cw = c * w;805float dw = d * w;806807Q.a00 = a * aw;808Q.a11 = b * bw;809Q.a22 = c * cw;810Q.a10 = a * bw;811Q.a20 = a * cw;812Q.a21 = b * cw;813Q.b0 = a * dw;814Q.b1 = b * dw;815Q.b2 = c * dw;816Q.c = d * dw;817Q.w = w;818}819820static void quadricFromPoint(Quadric& Q, float x, float y, float z, float w)821{822Q.a00 = Q.a11 = Q.a22 = w;823Q.a10 = Q.a20 = Q.a21 = 0;824Q.b0 = -x * w;825Q.b1 = -y * w;826Q.b2 = -z * w;827Q.c = (x * x + y * y + z * z) * w;828Q.w = w;829}830831static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)832{833Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};834Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};835836// normal = cross(p1 - p0, p2 - p0)837Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};838float area = normalize(normal);839840float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z;841842// we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes843quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight);844}845846static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight)847{848Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};849850// edge length; keep squared length around for projection correction851float lengthsq = p10.x * p10.x + p10.y * p10.y + p10.z * p10.z;852float length = sqrtf(lengthsq);853854// p20p = length of projection of p2-p0 onto p1-p0; note that p10 is unnormalized so we need to correct it later855Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};856float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z;857858// perp = perpendicular vector from p2 to line segment p1-p0859// note: since p10 is unnormalized we need to correct the projection; we scale p20 instead to take advantage of normalize below860Vector3 perp = {p20.x * lengthsq - p10.x * p20p, p20.y * lengthsq - p10.y * p20p, p20.z * lengthsq - p10.z * p20p};861normalize(perp);862863float distance = perp.x * p0.x + perp.y * p0.y + perp.z * p0.z;864865// note: the weight is scaled linearly with edge length; this has to match the triangle weight866quadricFromPlane(Q, perp.x, perp.y, perp.z, -distance, length * weight);867}868869static void quadricFromAttributes(Quadric& Q, QuadricGrad* G, const Vector3& p0, const Vector3& p1, const Vector3& p2, const float* va0, const float* va1, const float* va2, size_t attribute_count)870{871// for each attribute we want to encode the following function into the quadric:872// (eval(pos) - attr)^2873// where eval(pos) interpolates attribute across the triangle like so:874// eval(pos) = pos.x * gx + pos.y * gy + pos.z * gz + gw875// where gx/gy/gz/gw are gradients876Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};877Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};878879// normal = cross(p1 - p0, p2 - p0)880Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};881float area = sqrtf(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z) * 0.5f;882883// quadric is weighted with the square of edge length (= area)884// this equalizes the units with the positional error (which, after normalization, is a square of distance)885// as a result, a change in weighted attribute of 1 along distance d is approximately equivalent to a change in position of d886float w = area;887888// we compute gradients using barycentric coordinates; barycentric coordinates can be computed as follows:889// v = (d11 * d20 - d01 * d21) / denom890// w = (d00 * d21 - d01 * d20) / denom891// u = 1 - v - w892// here v0, v1 are triangle edge vectors, v2 is a vector from point to triangle corner, and dij = dot(vi, vj)893// note: v2 and d20/d21 can not be evaluated here as v2 is effectively an unknown variable; we need these only as variables for derivation of gradients894const Vector3& v0 = p10;895const Vector3& v1 = p20;896float d00 = v0.x * v0.x + v0.y * v0.y + v0.z * v0.z;897float d01 = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z;898float d11 = v1.x * v1.x + v1.y * v1.y + v1.z * v1.z;899float denom = d00 * d11 - d01 * d01;900float denomr = denom == 0 ? 0.f : 1.f / denom;901902// precompute gradient factors903// these are derived by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w and factoring out expressions that are shared between attributes904float gx1 = (d11 * v0.x - d01 * v1.x) * denomr;905float gx2 = (d00 * v1.x - d01 * v0.x) * denomr;906float gy1 = (d11 * v0.y - d01 * v1.y) * denomr;907float gy2 = (d00 * v1.y - d01 * v0.y) * denomr;908float gz1 = (d11 * v0.z - d01 * v1.z) * denomr;909float gz2 = (d00 * v1.z - d01 * v0.z) * denomr;910911memset(&Q, 0, sizeof(Quadric));912913Q.w = w;914915for (size_t k = 0; k < attribute_count; ++k)916{917float a0 = va0[k], a1 = va1[k], a2 = va2[k];918919// compute gradient of eval(pos) for x/y/z/w920// the formulas below are obtained by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w921float gx = gx1 * (a1 - a0) + gx2 * (a2 - a0);922float gy = gy1 * (a1 - a0) + gy2 * (a2 - a0);923float gz = gz1 * (a1 - a0) + gz2 * (a2 - a0);924float gw = a0 - p0.x * gx - p0.y * gy - p0.z * gz;925926// quadric encodes (eval(pos)-attr)^2; this means that the resulting expansion needs to compute, for example, pos.x * pos.y * K927// since quadrics already encode factors for pos.x * pos.y, we can accumulate almost everything in basic quadric fields928// note: for simplicity we scale all factors by weight here instead of outside the loop929Q.a00 += w * (gx * gx);930Q.a11 += w * (gy * gy);931Q.a22 += w * (gz * gz);932933Q.a10 += w * (gy * gx);934Q.a20 += w * (gz * gx);935Q.a21 += w * (gz * gy);936937Q.b0 += w * (gx * gw);938Q.b1 += w * (gy * gw);939Q.b2 += w * (gz * gw);940941Q.c += w * (gw * gw);942943// the only remaining sum components are ones that depend on attr; these will be addded during error evaluation, see quadricError944G[k].gx = w * gx;945G[k].gy = w * gy;946G[k].gz = w * gz;947G[k].gw = w * gw;948}949}950951static void quadricVolumeGradient(QuadricGrad& G, const Vector3& p0, const Vector3& p1, const Vector3& p2)952{953Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z};954Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z};955956// normal = cross(p1 - p0, p2 - p0)957Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x};958float area = normalize(normal) * 0.5f;959960G.gx = normal.x * area;961G.gy = normal.y * area;962G.gz = normal.z * area;963G.gw = (-p0.x * normal.x - p0.y * normal.y - p0.z * normal.z) * area;964}965966static bool quadricSolve(Vector3& p, const Quadric& Q, const QuadricGrad& GV)967{968// solve A*p = -b where A is the quadric matrix and b is the linear term969float a00 = Q.a00, a11 = Q.a11, a22 = Q.a22;970float a10 = Q.a10, a20 = Q.a20, a21 = Q.a21;971float x0 = -Q.b0, x1 = -Q.b1, x2 = -Q.b2;972973float eps = 1e-6f * Q.w;974975// LDL decomposition: A = LDL^T976float d0 = a00;977float l10 = a10 / d0;978float l20 = a20 / d0;979980float d1 = a11 - a10 * l10;981float dl21 = a21 - a20 * l10;982float l21 = dl21 / d1;983984float d2 = a22 - a20 * l20 - dl21 * l21;985986// solve L*y = x987float y0 = x0;988float y1 = x1 - l10 * y0;989float y2 = x2 - l20 * y0 - l21 * y1;990991// solve D*z = y992float z0 = y0 / d0;993float z1 = y1 / d1;994float z2 = y2 / d2;995996// augment system with linear constraint GV using Lagrange multiplier997float a30 = GV.gx, a31 = GV.gy, a32 = GV.gz;998float x3 = -GV.gw;9991000float l30 = a30 / d0;1001float dl31 = a31 - a30 * l10;1002float l31 = dl31 / d1;1003float dl32 = a32 - a30 * l20 - dl31 * l21;1004float l32 = dl32 / d2;1005float d3 = 0.f - a30 * l30 - dl31 * l31 - dl32 * l32;10061007float y3 = x3 - l30 * y0 - l31 * y1 - l32 * y2;1008float z3 = fabsf(d3) > eps ? y3 / d3 : 0.f; // if d3 is zero, we can ignore the constraint10091010// substitute L^T*p = z1011float lambda = z3;1012float pz = z2 - l32 * lambda;1013float py = z1 - l21 * pz - l31 * lambda;1014float px = z0 - l10 * py - l20 * pz - l30 * lambda;10151016p.x = px;1017p.y = py;1018p.z = pz;10191020return fabsf(d0) > eps && fabsf(d1) > eps && fabsf(d2) > eps;1021}10221023static void quadricReduceAttributes(Quadric& Q, const Quadric& A, const QuadricGrad* G, size_t attribute_count)1024{1025// update vertex quadric with attribute quadric; multiply by vertex weight to minimize normalized error1026Q.a00 += A.a00 * Q.w;1027Q.a11 += A.a11 * Q.w;1028Q.a22 += A.a22 * Q.w;1029Q.a10 += A.a10 * Q.w;1030Q.a20 += A.a20 * Q.w;1031Q.a21 += A.a21 * Q.w;1032Q.b0 += A.b0 * Q.w;1033Q.b1 += A.b1 * Q.w;1034Q.b2 += A.b2 * Q.w;10351036float iaw = A.w == 0 ? 0.f : Q.w / A.w;10371038// update linear system based on attribute gradients (BB^T/a)1039for (size_t k = 0; k < attribute_count; ++k)1040{1041const QuadricGrad& g = G[k];10421043Q.a00 -= (g.gx * g.gx) * iaw;1044Q.a11 -= (g.gy * g.gy) * iaw;1045Q.a22 -= (g.gz * g.gz) * iaw;1046Q.a10 -= (g.gx * g.gy) * iaw;1047Q.a20 -= (g.gx * g.gz) * iaw;1048Q.a21 -= (g.gy * g.gz) * iaw;10491050Q.b0 -= (g.gx * g.gw) * iaw;1051Q.b1 -= (g.gy * g.gw) * iaw;1052Q.b2 -= (g.gz * g.gw) * iaw;1053}1054}10551056static void fillFaceQuadrics(Quadric* vertex_quadrics, QuadricGrad* volume_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap)1057{1058for (size_t i = 0; i < index_count; i += 3)1059{1060unsigned int i0 = indices[i + 0];1061unsigned int i1 = indices[i + 1];1062unsigned int i2 = indices[i + 2];10631064Quadric Q;1065quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f);10661067quadricAdd(vertex_quadrics[remap[i0]], Q);1068quadricAdd(vertex_quadrics[remap[i1]], Q);1069quadricAdd(vertex_quadrics[remap[i2]], Q);10701071if (volume_gradients)1072{1073QuadricGrad GV;1074quadricVolumeGradient(GV, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2]);10751076quadricAdd(volume_gradients[remap[i0]], GV);1077quadricAdd(volume_gradients[remap[i1]], GV);1078quadricAdd(volume_gradients[remap[i2]], GV);1079}1080}1081}10821083static void fillVertexQuadrics(Quadric* vertex_quadrics, const Vector3* vertex_positions, size_t vertex_count, const unsigned int* remap, unsigned int options)1084{1085// by default, we use a very small weight to improve triangulation and numerical stability without affecting the shape or error1086float factor = (options & meshopt_SimplifyRegularize) ? 1e-1f : 1e-7f;10871088for (size_t i = 0; i < vertex_count; ++i)1089{1090if (remap[i] != i)1091continue;10921093const Vector3& p = vertex_positions[i];1094float w = vertex_quadrics[i].w * factor;10951096Quadric Q;1097quadricFromPoint(Q, p.x, p.y, p.z, w);10981099quadricAdd(vertex_quadrics[i], Q);1100}1101}11021103static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)1104{1105for (size_t i = 0; i < index_count; i += 3)1106{1107static const int next[4] = {1, 2, 0, 1};11081109for (int e = 0; e < 3; ++e)1110{1111unsigned int i0 = indices[i + e];1112unsigned int i1 = indices[i + next[e]];11131114unsigned char k0 = vertex_kind[i0];1115unsigned char k1 = vertex_kind[i1];11161117// check that either i0 or i1 are border/seam and are on the same edge loop1118// note that we need to add the error even for edged that connect e.g. border & locked1119// if we don't do that, the adjacent border->border edge won't have correct errors for corners1120if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam)1121continue;11221123if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1)1124continue;11251126if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0)1127continue;11281129unsigned int i2 = indices[i + next[e + 1]];11301131// we try hard to maintain border edge geometry; seam edges can move more freely1132// due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical1133const float kEdgeWeightSeam = 0.5f; // applied twice due to opposite edges1134const float kEdgeWeightBorder = 10.f;11351136float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam;11371138Quadric Q;1139quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);11401141Quadric QT;1142quadricFromTriangle(QT, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight);11431144// mix edge quadric with triangle quadric to stabilize collapses in both directions; both quadrics inherit edge weight so that their error is added1145QT.w = 0;1146quadricAdd(Q, QT);11471148quadricAdd(vertex_quadrics[remap[i0]], Q);1149quadricAdd(vertex_quadrics[remap[i1]], Q);1150}1151}1152}11531154static void fillAttributeQuadrics(Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const float* vertex_attributes, size_t attribute_count)1155{1156for (size_t i = 0; i < index_count; i += 3)1157{1158unsigned int i0 = indices[i + 0];1159unsigned int i1 = indices[i + 1];1160unsigned int i2 = indices[i + 2];11611162Quadric QA;1163QuadricGrad G[kMaxAttributes];1164quadricFromAttributes(QA, G, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], &vertex_attributes[i0 * attribute_count], &vertex_attributes[i1 * attribute_count], &vertex_attributes[i2 * attribute_count], attribute_count);11651166quadricAdd(attribute_quadrics[i0], QA);1167quadricAdd(attribute_quadrics[i1], QA);1168quadricAdd(attribute_quadrics[i2], QA);11691170quadricAdd(&attribute_gradients[i0 * attribute_count], G, attribute_count);1171quadricAdd(&attribute_gradients[i1 * attribute_count], G, attribute_count);1172quadricAdd(&attribute_gradients[i2 * attribute_count], G, attribute_count);1173}1174}11751176// does triangle ABC flip when C is replaced with D?1177static bool hasTriangleFlip(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d)1178{1179Vector3 eb = {b.x - a.x, b.y - a.y, b.z - a.z};1180Vector3 ec = {c.x - a.x, c.y - a.y, c.z - a.z};1181Vector3 ed = {d.x - a.x, d.y - a.y, d.z - a.z};11821183Vector3 nbc = {eb.y * ec.z - eb.z * ec.y, eb.z * ec.x - eb.x * ec.z, eb.x * ec.y - eb.y * ec.x};1184Vector3 nbd = {eb.y * ed.z - eb.z * ed.y, eb.z * ed.x - eb.x * ed.z, eb.x * ed.y - eb.y * ed.x};11851186float ndp = nbc.x * nbd.x + nbc.y * nbd.y + nbc.z * nbd.z;1187float abc = nbc.x * nbc.x + nbc.y * nbc.y + nbc.z * nbc.z;1188float abd = nbd.x * nbd.x + nbd.y * nbd.y + nbd.z * nbd.z;11891190// scale is cos(angle); somewhat arbitrarily set to ~75 degrees1191// note that the "pure" check is ndp <= 0 (90 degree cutoff) but that allows flipping through a series of close-to-90 collapses1192return ndp <= 0.25f * sqrtf(abc * abd);1193}11941195static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, const unsigned int* collapse_remap, unsigned int i0, unsigned int i1)1196{1197assert(collapse_remap[i0] == i0);1198assert(collapse_remap[i1] == i1);11991200const Vector3& v0 = vertex_positions[i0];1201const Vector3& v1 = vertex_positions[i1];12021203const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];1204size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0];12051206for (size_t i = 0; i < count; ++i)1207{1208unsigned int a = collapse_remap[edges[i].next];1209unsigned int b = collapse_remap[edges[i].prev];12101211// skip triangles that will get collapsed by i0->i1 collapse or already got collapsed previously1212if (a == i1 || b == i1 || a == b)1213continue;12141215// early-out when at least one triangle flips due to a collapse1216if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))1217{1218#if TRACE >= 21219printf("edge block %d -> %d: flip welded %d %d %d\n", i0, i1, a, i0, b);1220#endif12211222return true;1223}1224}12251226return false;1227}12281229static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, unsigned int i0, const Vector3& v1)1230{1231const Vector3& v0 = vertex_positions[i0];12321233const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];1234size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0];12351236for (size_t i = 0; i < count; ++i)1237{1238unsigned int a = edges[i].next, b = edges[i].prev;12391240if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1))1241return true;1242}12431244return false;1245}12461247static float getNeighborhoodRadius(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, unsigned int i0)1248{1249const Vector3& v0 = vertex_positions[i0];12501251const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]];1252size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0];12531254float result = 0.f;12551256for (size_t i = 0; i < count; ++i)1257{1258unsigned int a = edges[i].next, b = edges[i].prev;12591260const Vector3& va = vertex_positions[a];1261const Vector3& vb = vertex_positions[b];12621263float da = (va.x - v0.x) * (va.x - v0.x) + (va.y - v0.y) * (va.y - v0.y) + (va.z - v0.z) * (va.z - v0.z);1264float db = (vb.x - v0.x) * (vb.x - v0.x) + (vb.y - v0.y) * (vb.y - v0.y) + (vb.z - v0.z) * (vb.z - v0.z);12651266result = result < da ? da : result;1267result = result < db ? db : result;1268}12691270return sqrtf(result);1271}12721273static unsigned int getComplexTarget(unsigned int v, unsigned int target, const unsigned int* remap, const unsigned int* loop, const unsigned int* loopback)1274{1275unsigned int r = remap[target];12761277// use loop metadata to guide complex collapses towards the correct wedge1278// this works for edges on attribute discontinuities because loop/loopback track the single half-edge without a pair, similar to seams1279if (loop[v] != ~0u && remap[loop[v]] == r)1280return loop[v];1281else if (loopback[v] != ~0u && remap[loopback[v]] == r)1282return loopback[v];1283else1284return target;1285}12861287static size_t boundEdgeCollapses(const EdgeAdjacency& adjacency, size_t vertex_count, size_t index_count, unsigned char* vertex_kind)1288{1289size_t dual_count = 0;12901291for (size_t i = 0; i < vertex_count; ++i)1292{1293unsigned char k = vertex_kind[i];1294unsigned int e = adjacency.offsets[i + 1] - adjacency.offsets[i];12951296dual_count += (k == Kind_Manifold || k == Kind_Seam) ? e : 0;1297}12981299assert(dual_count <= index_count);13001301// pad capacity by 3 so that we can check for overflow once per triangle instead of once per edge1302return (index_count - dual_count / 2) + 3;1303}13041305static size_t pickEdgeCollapses(Collapse* collapses, size_t collapse_capacity, const unsigned int* indices, size_t index_count, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)1306{1307size_t collapse_count = 0;13081309for (size_t i = 0; i < index_count; i += 3)1310{1311static const int next[3] = {1, 2, 0};13121313// this should never happen as boundEdgeCollapses should give an upper bound for the collapse count, but in an unlikely event it does we can just drop extra collapses1314if (collapse_count + 3 > collapse_capacity)1315break;13161317for (int e = 0; e < 3; ++e)1318{1319unsigned int i0 = indices[i + e];1320unsigned int i1 = indices[i + next[e]];13211322// this can happen either when input has a zero-length edge, or when we perform collapses for complex1323// topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them1324// we leave edges like this alone since they may be important for preserving mesh integrity1325if (remap[i0] == remap[i1])1326continue;13271328unsigned char k0 = vertex_kind[i0];1329unsigned char k1 = vertex_kind[i1];13301331// the edge has to be collapsible in at least one direction1332if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0]))1333continue;13341335// manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges1336if (kHasOpposite[k0][k1] && remap[i1] > remap[i0])1337continue;13381339// two vertices are on a border or a seam, but there's no direct edge between them1340// this indicates that they belong to two different edge loops and we should not collapse this edge1341// loop[] and loopback[] track half edges so we only need to check one of them1342if ((k0 == Kind_Border || k0 == Kind_Seam) && k1 != Kind_Manifold && loop[i0] != i1)1343continue;1344if ((k1 == Kind_Border || k1 == Kind_Seam) && k0 != Kind_Manifold && loopback[i1] != i0)1345continue;13461347// edge can be collapsed in either direction - we will pick the one with minimum error1348// note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional1349if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0])1350{1351Collapse c = {i0, i1, {/* bidi= */ 1}};1352collapses[collapse_count++] = c;1353}1354else1355{1356// edge can only be collapsed in one direction1357unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1;1358unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0;13591360Collapse c = {e0, e1, {/* bidi= */ 0}};1361collapses[collapse_count++] = c;1362}1363}1364}13651366return collapse_count;1367}13681369static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const float* vertex_attributes, const Quadric* vertex_quadrics, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback)1370{1371for (size_t i = 0; i < collapse_count; ++i)1372{1373Collapse& c = collapses[i];13741375unsigned int i0 = c.v0;1376unsigned int i1 = c.v1;1377bool bidi = c.bidi;13781379float ei = quadricError(vertex_quadrics[remap[i0]], vertex_positions[i1]);1380float ej = bidi ? quadricError(vertex_quadrics[remap[i1]], vertex_positions[i0]) : FLT_MAX;13811382#if TRACE >= 31383float di = ei, dj = ej;1384#endif13851386if (attribute_count)1387{1388ei += quadricError(attribute_quadrics[i0], &attribute_gradients[i0 * attribute_count], attribute_count, vertex_positions[i1], &vertex_attributes[i1 * attribute_count]);1389ej += bidi ? quadricError(attribute_quadrics[i1], &attribute_gradients[i1 * attribute_count], attribute_count, vertex_positions[i0], &vertex_attributes[i0 * attribute_count]) : 0;13901391// seam edges need to aggregate attribute errors between primary and secondary edges, as attribute quadrics are separate1392if (vertex_kind[i0] == Kind_Seam)1393{1394// for seam collapses we need to find the seam pair; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges)1395unsigned int s0 = wedge[i0];1396unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0];13971398assert(wedge[s0] == i0); // s0 may be equal to i0 for half-seams1399assert(s1 != ~0u && remap[s1] == remap[i1]);14001401// note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe1402s1 = (s1 != ~0u) ? s1 : wedge[i1];14031404ei += quadricError(attribute_quadrics[s0], &attribute_gradients[s0 * attribute_count], attribute_count, vertex_positions[s1], &vertex_attributes[s1 * attribute_count]);1405ej += bidi ? quadricError(attribute_quadrics[s1], &attribute_gradients[s1 * attribute_count], attribute_count, vertex_positions[s0], &vertex_attributes[s0 * attribute_count]) : 0;1406}1407else1408{1409// complex edges can have multiple wedges, so we need to aggregate errors for all wedges based on the selected target1410if (vertex_kind[i0] == Kind_Complex)1411for (unsigned int v = wedge[i0]; v != i0; v = wedge[v])1412{1413unsigned int t = getComplexTarget(v, i1, remap, loop, loopback);14141415ei += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]);1416}14171418if (vertex_kind[i1] == Kind_Complex && bidi)1419for (unsigned int v = wedge[i1]; v != i1; v = wedge[v])1420{1421unsigned int t = getComplexTarget(v, i0, remap, loop, loopback);14221423ej += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]);1424}1425}1426}14271428// pick edge direction with minimal error (branchless)1429bool rev = bidi & (ej < ei);14301431c.v0 = rev ? i1 : i0;1432c.v1 = rev ? i0 : i1;1433c.error = ej < ei ? ej : ei;14341435#if TRACE >= 31436if (bidi)1437printf("edge eval %d -> %d: error %f (pos %f, attr %f); reverse %f (pos %f, attr %f)\n",1438rev ? i1 : i0, rev ? i0 : i1,1439sqrtf(rev ? ej : ei), sqrtf(rev ? dj : di), sqrtf(rev ? ej - dj : ei - di),1440sqrtf(rev ? ei : ej), sqrtf(rev ? di : dj), sqrtf(rev ? ei - di : ej - dj));1441else1442printf("edge eval %d -> %d: error %f (pos %f, attr %f)\n", i0, i1, sqrtf(c.error), sqrtf(di), sqrtf(ei - di));1443#endif1444}1445}14461447static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count)1448{1449// we use counting sort to order collapses by error; since the exact sort order is not as critical,1450// only top 12 bits of exponent+mantissa (8 bits of exponent and 4 bits of mantissa) are used.1451// to avoid excessive stack usage, we clamp the exponent range as collapses with errors much higher than 1 are not useful.1452const unsigned int sort_bits = 12;1453const unsigned int sort_bins = 2048 + 512; // exponent range [-127, 32)14541455// fill histogram for counting sort1456unsigned int histogram[sort_bins];1457memset(histogram, 0, sizeof(histogram));14581459for (size_t i = 0; i < collapse_count; ++i)1460{1461// skip sign bit since error is non-negative1462unsigned int error = collapses[i].errorui;1463unsigned int key = (error << 1) >> (32 - sort_bits);1464key = key < sort_bins ? key : sort_bins - 1;14651466histogram[key]++;1467}14681469// compute offsets based on histogram data1470size_t histogram_sum = 0;14711472for (size_t i = 0; i < sort_bins; ++i)1473{1474size_t count = histogram[i];1475histogram[i] = unsigned(histogram_sum);1476histogram_sum += count;1477}14781479assert(histogram_sum == collapse_count);14801481// compute sort order based on offsets1482for (size_t i = 0; i < collapse_count; ++i)1483{1484// skip sign bit since error is non-negative1485unsigned int error = collapses[i].errorui;1486unsigned int key = (error << 1) >> (32 - sort_bits);1487key = key < sort_bins ? key : sort_bins - 1;14881489sort_order[histogram[key]++] = unsigned(i);1490}1491}14921493static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char* collapse_locked, const Collapse* collapses, size_t collapse_count, const unsigned int* collapse_order, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback, const Vector3* vertex_positions, const EdgeAdjacency& adjacency, size_t triangle_collapse_goal, float error_limit, float& result_error)1494{1495size_t edge_collapses = 0;1496size_t triangle_collapses = 0;14971498// most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit1499// note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses1500size_t edge_collapse_goal = triangle_collapse_goal / 2;15011502#if TRACE1503size_t stats[7] = {};1504#endif15051506for (size_t i = 0; i < collapse_count; ++i)1507{1508const Collapse& c = collapses[collapse_order[i]];15091510TRACESTATS(0);15111512if (c.error > error_limit)1513{1514TRACESTATS(4);1515break;1516}15171518if (triangle_collapses >= triangle_collapse_goal)1519{1520TRACESTATS(5);1521break;1522}15231524// we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked1525// as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor1526float error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;15271528// on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd1529// topology, we only abort if we got over 1/6 collapses accordingly.1530if (c.error > error_goal && c.error > result_error && triangle_collapses > triangle_collapse_goal / 6)1531{1532TRACESTATS(6);1533break;1534}15351536unsigned int i0 = c.v0;1537unsigned int i1 = c.v1;15381539unsigned int r0 = remap[i0];1540unsigned int r1 = remap[i1];15411542unsigned char kind = vertex_kind[i0];15431544// we don't collapse vertices that had source or target vertex involved in a collapse1545// it's important to not move the vertices twice since it complicates the tracking/remapping logic1546// it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass1547if (collapse_locked[r0] | collapse_locked[r1])1548{1549TRACESTATS(1);1550continue;1551}15521553if (hasTriangleFlips(adjacency, vertex_positions, collapse_remap, r0, r1))1554{1555// adjust collapse goal since this collapse is invalid and shouldn't factor into error goal1556edge_collapse_goal++;15571558TRACESTATS(2);1559continue;1560}15611562#if TRACE >= 21563printf("edge commit %d -> %d: kind %d->%d, error %f\n", i0, i1, vertex_kind[i0], vertex_kind[i1], sqrtf(c.error));1564#endif15651566assert(collapse_remap[r0] == r0);1567assert(collapse_remap[r1] == r1);15681569if (kind == Kind_Complex)1570{1571// remap all vertices in the complex to the target vertex1572unsigned int v = i0;15731574do1575{1576unsigned int t = getComplexTarget(v, i1, remap, loop, loopback);15771578collapse_remap[v] = t;1579v = wedge[v];1580} while (v != i0);1581}1582else if (kind == Kind_Seam)1583{1584// for seam collapses we need to move the seam pair together; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges)1585unsigned int s0 = wedge[i0];1586unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0];1587assert(wedge[s0] == i0); // s0 may be equal to i0 for half-seams1588assert(s1 != ~0u && remap[s1] == r1);15891590// additional asserts to verify that the seam pair is consistent1591assert(kind != vertex_kind[i1] || s1 == wedge[i1]);1592assert(loop[i0] == i1 || loopback[i0] == i1);1593assert(loop[s0] == s1 || loopback[s0] == s1);15941595// note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe1596s1 = (s1 != ~0u) ? s1 : wedge[i1];15971598collapse_remap[i0] = i1;1599collapse_remap[s0] = s1;1600}1601else1602{1603assert(wedge[i0] == i0);16041605collapse_remap[i0] = i1;1606}16071608// note: we technically don't need to lock r1 if it's a locked vertex, as it can't move and its quadric won't be used1609// however, this results in slightly worse error on some meshes because the locked collapses get an unfair advantage wrt scheduling1610collapse_locked[r0] = 1;1611collapse_locked[r1] = 1;16121613// border edges collapse 1 triangle, other edges collapse 2 or more1614triangle_collapses += (kind == Kind_Border) ? 1 : 2;1615edge_collapses++;16161617result_error = result_error < c.error ? c.error : result_error;1618}16191620#if TRACE1621float error_goal_last = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX;1622float error_goal_limit = error_goal_last < error_limit ? error_goal_last : error_limit;16231624printf("removed %d triangles, error %e (goal %e); evaluated %d/%d collapses (done %d, skipped %d, invalid %d); %s\n",1625int(triangle_collapses), sqrtf(result_error), sqrtf(error_goal_limit),1626int(stats[0]), int(collapse_count), int(edge_collapses), int(stats[1]), int(stats[2]),1627stats[4] ? "error limit" : (stats[5] ? "count limit" : (stats[6] ? "error goal" : "out of collapses")));1628#endif16291630return edge_collapses;1631}16321633static void updateQuadrics(const unsigned int* collapse_remap, size_t vertex_count, Quadric* vertex_quadrics, QuadricGrad* volume_gradients, Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, size_t attribute_count, const Vector3* vertex_positions, const unsigned int* remap, float& vertex_error)1634{1635for (size_t i = 0; i < vertex_count; ++i)1636{1637if (collapse_remap[i] == i)1638continue;16391640unsigned int i0 = unsigned(i);1641unsigned int i1 = collapse_remap[i];16421643unsigned int r0 = remap[i0];1644unsigned int r1 = remap[i1];16451646// ensure we only update vertex_quadrics once: primary vertex must be moved if any wedge is moved1647if (i0 == r0)1648{1649quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]);16501651if (volume_gradients)1652quadricAdd(volume_gradients[r1], volume_gradients[r0]);1653}16541655if (attribute_count)1656{1657quadricAdd(attribute_quadrics[i1], attribute_quadrics[i0]);1658quadricAdd(&attribute_gradients[i1 * attribute_count], &attribute_gradients[i0 * attribute_count], attribute_count);16591660if (i0 == r0)1661{1662// when attributes are used, distance error needs to be recomputed as collapses don't track it; it is safe to do this after the quadric adjustment1663float derr = quadricError(vertex_quadrics[r0], vertex_positions[r1]);1664vertex_error = vertex_error < derr ? derr : vertex_error;1665}1666}1667}1668}16691670static void solvePositions(Vector3* vertex_positions, size_t vertex_count, const Quadric* vertex_quadrics, const QuadricGrad* volume_gradients, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const EdgeAdjacency& adjacency, const unsigned char* vertex_kind, const unsigned char* vertex_update)1671{1672#if TRACE1673size_t stats[6] = {};1674#endif16751676for (size_t i = 0; i < vertex_count; ++i)1677{1678if (!vertex_update[i])1679continue;16801681// moving vertices on an attribute discontinuity may result in extrapolating UV outside of the chart bounds1682// moving vertices on a border requires a stronger edge quadric to preserve the border geometry1683if (vertex_kind[i] == Kind_Locked || vertex_kind[i] == Kind_Seam || vertex_kind[i] == Kind_Border)1684continue;16851686if (remap[i] != i)1687{1688vertex_positions[i] = vertex_positions[remap[i]];1689continue;1690}16911692TRACESTATS(0);16931694const Vector3& vp = vertex_positions[i];16951696Quadric Q = vertex_quadrics[i];1697QuadricGrad GV = {};16981699// add a point quadric for regularization to stabilize the solution1700Quadric R;1701quadricFromPoint(R, vp.x, vp.y, vp.z, Q.w * 1e-4f);1702quadricAdd(Q, R);17031704if (attribute_count)1705{1706// optimal point simultaneously minimizes attribute quadrics for all wedges1707unsigned int v = unsigned(i);1708do1709{1710quadricReduceAttributes(Q, attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count);1711v = wedge[v];1712} while (v != i);17131714// minimizing attribute quadrics results in volume loss so we incorporate volume gradient as a constraint1715if (volume_gradients)1716GV = volume_gradients[i];1717}17181719Vector3 p;1720if (!quadricSolve(p, Q, GV))1721{1722TRACESTATS(2);1723continue;1724}17251726// reject updates that move the vertex too far from its neighborhood1727// this detects and fixes most cases when the quadric is not well-defined1728float nr = getNeighborhoodRadius(adjacency, vertex_positions, unsigned(i));1729float dp = (p.x - vp.x) * (p.x - vp.x) + (p.y - vp.y) * (p.y - vp.y) + (p.z - vp.z) * (p.z - vp.z);17301731if (dp > nr * nr)1732{1733TRACESTATS(3);1734continue;1735}17361737// reject updates that would flip a neighboring triangle, as we do for edge collapse1738if (hasTriangleFlips(adjacency, vertex_positions, unsigned(i), p))1739{1740TRACESTATS(4);1741continue;1742}17431744// reject updates that increase positional error too much; allow some tolerance to improve attribute quality1745if (quadricError(vertex_quadrics[i], p) > quadricError(vertex_quadrics[i], vp) * 1.5f + 1e-6f)1746{1747TRACESTATS(5);1748continue;1749}17501751TRACESTATS(1);1752vertex_positions[i] = p;1753}17541755#if TRACE1756printf("updated %d/%d positions; failed solve %d bounds %d flip %d error %d\n", int(stats[1]), int(stats[0]), int(stats[2]), int(stats[3]), int(stats[4]), int(stats[5]));1757#endif1758}17591760static void solveAttributes(Vector3* vertex_positions, float* vertex_attributes, size_t vertex_count, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned char* vertex_update)1761{1762for (size_t i = 0; i < vertex_count; ++i)1763{1764if (!vertex_update[i])1765continue;17661767if (remap[i] != i)1768continue;17691770for (size_t k = 0; k < attribute_count; ++k)1771{1772unsigned int shared = ~0u;17731774// for complex vertices, preserve attribute continuity and use highest weight wedge if values were shared1775if (vertex_kind[i] == Kind_Complex)1776{1777shared = unsigned(i);17781779for (unsigned int v = wedge[i]; v != i; v = wedge[v])1780if (vertex_attributes[v * attribute_count + k] != vertex_attributes[i * attribute_count + k])1781shared = ~0u;1782else if (shared != ~0u && attribute_quadrics[v].w > attribute_quadrics[shared].w)1783shared = v;1784}17851786// update attributes for all wedges1787unsigned int v = unsigned(i);1788do1789{1790unsigned int r = (shared == ~0u) ? v : shared;17911792const Vector3& p = vertex_positions[i]; // same for all wedges1793const Quadric& A = attribute_quadrics[r];1794const QuadricGrad& G = attribute_gradients[r * attribute_count + k];17951796float iw = A.w == 0 ? 0.f : 1.f / A.w;1797float av = (G.gx * p.x + G.gy * p.y + G.gz * p.z + G.gw) * iw;17981799vertex_attributes[v * attribute_count + k] = av;1800v = wedge[v];1801} while (v != i);1802}1803}1804}18051806static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap, const unsigned int* remap)1807{1808size_t write = 0;18091810for (size_t i = 0; i < index_count; i += 3)1811{1812unsigned int v0 = collapse_remap[indices[i + 0]];1813unsigned int v1 = collapse_remap[indices[i + 1]];1814unsigned int v2 = collapse_remap[indices[i + 2]];18151816// we never move the vertex twice during a single pass1817assert(collapse_remap[v0] == v0);1818assert(collapse_remap[v1] == v1);1819assert(collapse_remap[v2] == v2);18201821// collapse zero area triangles even if they are not topologically degenerate1822// this is required to cleanup manifold->seam collapses when a vertex is collapsed onto a seam pair1823// as well as complex collapses and some other cases where cross wedge collapses are performed1824unsigned int r0 = remap[v0];1825unsigned int r1 = remap[v1];1826unsigned int r2 = remap[v2];18271828if (r0 != r1 && r0 != r2 && r1 != r2)1829{1830indices[write + 0] = v0;1831indices[write + 1] = v1;1832indices[write + 2] = v2;1833write += 3;1834}1835}18361837return write;1838}18391840static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap)1841{1842for (size_t i = 0; i < vertex_count; ++i)1843{1844// note: this is a no-op for vertices that were remapped1845// ideally we would clear the loop entries for those for consistency, even though they aren't going to be used1846// however, the remapping process needs loop information for remapped vertices, so this would require a separate pass1847if (loop[i] != ~0u)1848{1849unsigned int l = loop[i];1850unsigned int r = collapse_remap[l];18511852// i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes1853if (i == r)1854loop[i] = (loop[l] != ~0u) ? collapse_remap[loop[l]] : ~0u;1855else1856loop[i] = r;1857}1858}1859}18601861static unsigned int follow(unsigned int* parents, unsigned int index)1862{1863while (index != parents[index])1864{1865unsigned int parent = parents[index];1866parents[index] = parents[parent];1867index = parent;1868}18691870return index;1871}18721873static size_t buildComponents(unsigned int* components, size_t vertex_count, const unsigned int* indices, size_t index_count, const unsigned int* remap)1874{1875for (size_t i = 0; i < vertex_count; ++i)1876components[i] = unsigned(i);18771878// compute a unique (but not sequential!) index for each component via union-find1879for (size_t i = 0; i < index_count; i += 3)1880{1881static const int next[4] = {1, 2, 0, 1};18821883for (int e = 0; e < 3; ++e)1884{1885unsigned int i0 = indices[i + e];1886unsigned int i1 = indices[i + next[e]];18871888unsigned int r0 = remap[i0];1889unsigned int r1 = remap[i1];18901891r0 = follow(components, r0);1892r1 = follow(components, r1);18931894// merge components with larger indices into components with smaller indices1895// this guarantees that the root of the component is always the one with the smallest index1896if (r0 != r1)1897components[r0 < r1 ? r1 : r0] = r0 < r1 ? r0 : r1;1898}1899}19001901// make sure each element points to the component root *before* we renumber the components1902for (size_t i = 0; i < vertex_count; ++i)1903if (remap[i] == i)1904components[i] = follow(components, unsigned(i));19051906unsigned int next_component = 0;19071908// renumber components using sequential indices1909// a sequential pass is sufficient because component root always has the smallest index1910// note: it is unsafe to use follow() in this pass because we're replacing component links with sequential indices inplace1911for (size_t i = 0; i < vertex_count; ++i)1912{1913if (remap[i] == i)1914{1915unsigned int root = components[i];1916assert(root <= i); // make sure we already computed the component for non-roots1917components[i] = (root == i) ? next_component++ : components[root];1918}1919else1920{1921assert(remap[i] < i); // make sure we already computed the component1922components[i] = components[remap[i]];1923}1924}19251926return next_component;1927}19281929static void measureComponents(float* component_errors, size_t component_count, const unsigned int* components, const Vector3* vertex_positions, size_t vertex_count)1930{1931memset(component_errors, 0, component_count * 4 * sizeof(float));19321933// compute approximate sphere center for each component as an average1934for (size_t i = 0; i < vertex_count; ++i)1935{1936unsigned int c = components[i];1937assert(components[i] < component_count);19381939Vector3 v = vertex_positions[i]; // copy avoids aliasing issues19401941component_errors[c * 4 + 0] += v.x;1942component_errors[c * 4 + 1] += v.y;1943component_errors[c * 4 + 2] += v.z;1944component_errors[c * 4 + 3] += 1; // weight1945}19461947// complete the center computation, and reinitialize [3] as a radius1948for (size_t i = 0; i < component_count; ++i)1949{1950float w = component_errors[i * 4 + 3];1951float iw = w == 0.f ? 0.f : 1.f / w;19521953component_errors[i * 4 + 0] *= iw;1954component_errors[i * 4 + 1] *= iw;1955component_errors[i * 4 + 2] *= iw;1956component_errors[i * 4 + 3] = 0; // radius1957}19581959// compute squared radius for each component1960for (size_t i = 0; i < vertex_count; ++i)1961{1962unsigned int c = components[i];19631964float dx = vertex_positions[i].x - component_errors[c * 4 + 0];1965float dy = vertex_positions[i].y - component_errors[c * 4 + 1];1966float dz = vertex_positions[i].z - component_errors[c * 4 + 2];1967float r = dx * dx + dy * dy + dz * dz;19681969component_errors[c * 4 + 3] = component_errors[c * 4 + 3] < r ? r : component_errors[c * 4 + 3];1970}19711972// we've used the output buffer as scratch space, so we need to move the results to proper indices1973for (size_t i = 0; i < component_count; ++i)1974{1975#if TRACE >= 21976printf("component %d: center %f %f %f, error %e\n", int(i),1977component_errors[i * 4 + 0], component_errors[i * 4 + 1], component_errors[i * 4 + 2], sqrtf(component_errors[i * 4 + 3]));1978#endif1979// note: we keep the squared error to make it match quadric error metric1980component_errors[i] = component_errors[i * 4 + 3];1981}1982}19831984static size_t pruneComponents(unsigned int* indices, size_t index_count, const unsigned int* components, const float* component_errors, size_t component_count, float error_cutoff, float& nexterror)1985{1986(void)component_count;19871988size_t write = 0;1989float min_error = FLT_MAX;19901991for (size_t i = 0; i < index_count; i += 3)1992{1993unsigned int v0 = indices[i + 0], v1 = indices[i + 1], v2 = indices[i + 2];1994unsigned int c = components[v0];1995assert(c == components[v1] && c == components[v2]);19961997if (component_errors[c] > error_cutoff)1998{1999min_error = min_error > component_errors[c] ? component_errors[c] : min_error;20002001indices[write + 0] = v0;2002indices[write + 1] = v1;2003indices[write + 2] = v2;2004write += 3;2005}2006}20072008#if TRACE2009size_t pruned_components = 0;2010for (size_t i = 0; i < component_count; ++i)2011pruned_components += (component_errors[i] >= nexterror && component_errors[i] <= error_cutoff);20122013printf("pruned %d triangles in %d components (goal %e); next %e\n", int((index_count - write) / 3), int(pruned_components), sqrtf(error_cutoff), min_error < FLT_MAX ? sqrtf(min_error) : min_error * 2);2014#endif20152016// update next error with the smallest error of the remaining components2017nexterror = min_error;2018return write;2019}20202021struct CellHasher2022{2023const unsigned int* vertex_ids;20242025size_t hash(unsigned int i) const2026{2027unsigned int h = vertex_ids[i];20282029// MurmurHash2 finalizer2030h ^= h >> 13;2031h *= 0x5bd1e995;2032h ^= h >> 15;2033return h;2034}20352036bool equal(unsigned int lhs, unsigned int rhs) const2037{2038return vertex_ids[lhs] == vertex_ids[rhs];2039}2040};20412042struct IdHasher2043{2044size_t hash(unsigned int id) const2045{2046unsigned int h = id;20472048// MurmurHash2 finalizer2049h ^= h >> 13;2050h *= 0x5bd1e995;2051h ^= h >> 15;2052return h;2053}20542055bool equal(unsigned int lhs, unsigned int rhs) const2056{2057return lhs == rhs;2058}2059};20602061struct TriangleHasher2062{2063const unsigned int* indices;20642065size_t hash(unsigned int i) const2066{2067const unsigned int* tri = indices + i * 3;20682069// Optimized Spatial Hashing for Collision Detection of Deformable Objects2070return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791);2071}20722073bool equal(unsigned int lhs, unsigned int rhs) const2074{2075const unsigned int* lt = indices + lhs * 3;2076const unsigned int* rt = indices + rhs * 3;20772078return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2];2079}2080};20812082static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, const unsigned char* vertex_lock, size_t vertex_count, int grid_size)2083{2084assert(grid_size >= 1 && grid_size <= 1024);2085float cell_scale = float(grid_size - 1);20862087for (size_t i = 0; i < vertex_count; ++i)2088{2089const Vector3& v = vertex_positions[i];20902091int xi = int(v.x * cell_scale + 0.5f);2092int yi = int(v.y * cell_scale + 0.5f);2093int zi = int(v.z * cell_scale + 0.5f);20942095if (vertex_lock && (vertex_lock[i] & meshopt_SimplifyVertex_Lock))2096vertex_ids[i] = (1 << 30) | unsigned(i);2097else2098vertex_ids[i] = (xi << 20) | (yi << 10) | zi;2099}2100}21012102static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count)2103{2104size_t result = 0;21052106for (size_t i = 0; i < index_count; i += 3)2107{2108unsigned int id0 = vertex_ids[indices[i + 0]];2109unsigned int id1 = vertex_ids[indices[i + 1]];2110unsigned int id2 = vertex_ids[indices[i + 2]];21112112result += (id0 != id1) & (id0 != id2) & (id1 != id2);2113}21142115return result;2116}21172118static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count)2119{2120CellHasher hasher = {vertex_ids};21212122memset(table, -1, table_size * sizeof(unsigned int));21232124size_t result = 0;21252126for (size_t i = 0; i < vertex_count; ++i)2127{2128unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u);21292130if (*entry == ~0u)2131{2132*entry = unsigned(i);2133vertex_cells[i] = unsigned(result++);2134}2135else2136{2137vertex_cells[i] = vertex_cells[*entry];2138}2139}21402141return result;2142}21432144static size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count)2145{2146IdHasher hasher;21472148memset(table, -1, table_size * sizeof(unsigned int));21492150size_t result = 0;21512152for (size_t i = 0; i < vertex_count; ++i)2153{2154unsigned int id = vertex_ids[i];2155unsigned int* entry = hashLookup2(table, table_size, hasher, id, ~0u);21562157result += (*entry == ~0u);2158*entry = id;2159}21602161return result;2162}21632164static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells)2165{2166for (size_t i = 0; i < index_count; i += 3)2167{2168unsigned int i0 = indices[i + 0];2169unsigned int i1 = indices[i + 1];2170unsigned int i2 = indices[i + 2];21712172unsigned int c0 = vertex_cells[i0];2173unsigned int c1 = vertex_cells[i1];2174unsigned int c2 = vertex_cells[i2];21752176int single_cell = (c0 == c1) & (c0 == c2);21772178Quadric Q;2179quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f);21802181if (single_cell)2182{2183quadricAdd(cell_quadrics[c0], Q);2184}2185else2186{2187quadricAdd(cell_quadrics[c0], Q);2188quadricAdd(cell_quadrics[c1], Q);2189quadricAdd(cell_quadrics[c2], Q);2190}2191}2192}21932194static void fillCellReservoirs(Reservoir* cell_reservoirs, size_t cell_count, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, size_t vertex_count, const unsigned int* vertex_cells)2195{2196static const float dummy_color[] = {0.f, 0.f, 0.f};21972198size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float);21992200for (size_t i = 0; i < vertex_count; ++i)2201{2202unsigned int cell = vertex_cells[i];2203const Vector3& v = vertex_positions[i];2204Reservoir& r = cell_reservoirs[cell];22052206const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color;22072208r.x += v.x;2209r.y += v.y;2210r.z += v.z;2211r.r += color[0];2212r.g += color[1];2213r.b += color[2];2214r.w += 1.f;2215}22162217for (size_t i = 0; i < cell_count; ++i)2218{2219Reservoir& r = cell_reservoirs[i];22202221float iw = r.w == 0.f ? 0.f : 1.f / r.w;22222223r.x *= iw;2224r.y *= iw;2225r.z *= iw;2226r.r *= iw;2227r.g *= iw;2228r.b *= iw;2229}2230}22312232static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count)2233{2234memset(cell_remap, -1, cell_count * sizeof(unsigned int));22352236for (size_t i = 0; i < vertex_count; ++i)2237{2238unsigned int cell = vertex_cells[i];2239float error = quadricError(cell_quadrics[cell], vertex_positions[i]);22402241if (cell_remap[cell] == ~0u || cell_errors[cell] > error)2242{2243cell_remap[cell] = unsigned(i);2244cell_errors[cell] = error;2245}2246}2247}22482249static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Reservoir* cell_reservoirs, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t vertex_count)2250{2251static const float dummy_color[] = {0.f, 0.f, 0.f};22522253size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float);22542255memset(cell_remap, -1, cell_count * sizeof(unsigned int));22562257for (size_t i = 0; i < vertex_count; ++i)2258{2259unsigned int cell = vertex_cells[i];2260const Vector3& v = vertex_positions[i];2261const Reservoir& r = cell_reservoirs[cell];22622263const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color;22642265float pos_error = (v.x - r.x) * (v.x - r.x) + (v.y - r.y) * (v.y - r.y) + (v.z - r.z) * (v.z - r.z);2266float col_error = (color[0] - r.r) * (color[0] - r.r) + (color[1] - r.g) * (color[1] - r.g) + (color[2] - r.b) * (color[2] - r.b);2267float error = pos_error + color_weight * col_error;22682269if (cell_remap[cell] == ~0u || cell_errors[cell] > error)2270{2271cell_remap[cell] = unsigned(i);2272cell_errors[cell] = error;2273}2274}2275}22762277static size_t filterTriangles(unsigned int* destination, unsigned int* tritable, size_t tritable_size, const unsigned int* indices, size_t index_count, const unsigned int* vertex_cells, const unsigned int* cell_remap)2278{2279TriangleHasher hasher = {destination};22802281memset(tritable, -1, tritable_size * sizeof(unsigned int));22822283size_t result = 0;22842285for (size_t i = 0; i < index_count; i += 3)2286{2287unsigned int c0 = vertex_cells[indices[i + 0]];2288unsigned int c1 = vertex_cells[indices[i + 1]];2289unsigned int c2 = vertex_cells[indices[i + 2]];22902291if (c0 != c1 && c0 != c2 && c1 != c2)2292{2293unsigned int a = cell_remap[c0];2294unsigned int b = cell_remap[c1];2295unsigned int c = cell_remap[c2];22962297if (b < a && b < c)2298{2299unsigned int t = a;2300a = b, b = c, c = t;2301}2302else if (c < a && c < b)2303{2304unsigned int t = c;2305c = b, b = a, a = t;2306}23072308destination[result * 3 + 0] = a;2309destination[result * 3 + 1] = b;2310destination[result * 3 + 2] = c;23112312unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u);23132314if (*entry == ~0u)2315*entry = unsigned(result++);2316}2317}23182319return result * 3;2320}23212322static float interpolate(float y, float x0, float y0, float x1, float y1, float x2, float y2)2323{2324// three point interpolation from "revenge of interpolation search" paper2325float num = (y1 - y) * (x1 - x2) * (x1 - x0) * (y2 - y0);2326float den = (y2 - y) * (x1 - x2) * (y0 - y1) + (y0 - y) * (x1 - x0) * (y1 - y2);2327return x1 + (den == 0.f ? 0.f : num / den);2328}23292330} // namespace meshopt23312332// Note: this is only exposed for development purposes; do *not* use2333enum2334{2335meshopt_SimplifyInternalSolve = 1 << 29,2336meshopt_SimplifyInternalDebug = 1 << 302337};23382339size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2340{2341using namespace meshopt;23422343assert(index_count % 3 == 0);2344assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2345assert(vertex_positions_stride % sizeof(float) == 0);2346assert(target_index_count <= index_count);2347assert(target_error >= 0);2348assert((options & ~(meshopt_SimplifyLockBorder | meshopt_SimplifySparse | meshopt_SimplifyErrorAbsolute | meshopt_SimplifyPrune | meshopt_SimplifyRegularize | meshopt_SimplifyPermissive | meshopt_SimplifyInternalSolve | meshopt_SimplifyInternalDebug)) == 0);2349assert(vertex_attributes_stride >= attribute_count * sizeof(float) && vertex_attributes_stride <= 256);2350assert(vertex_attributes_stride % sizeof(float) == 0);2351assert(attribute_count <= kMaxAttributes);2352for (size_t i = 0; i < attribute_count; ++i)2353assert(attribute_weights[i] >= 0);23542355meshopt_Allocator allocator;23562357unsigned int* result = destination;2358if (result != indices)2359memcpy(result, indices, index_count * sizeof(unsigned int));23602361// build an index remap and update indices/vertex_count to minimize the subsequent work2362// note: as a consequence, errors will be computed relative to the subset extent2363unsigned int* sparse_remap = NULL;2364if (options & meshopt_SimplifySparse)2365sparse_remap = buildSparseRemap(result, index_count, vertex_count, &vertex_count, allocator);23662367// build adjacency information2368EdgeAdjacency adjacency = {};2369prepareEdgeAdjacency(adjacency, index_count, vertex_count, allocator);2370updateEdgeAdjacency(adjacency, result, index_count, vertex_count, NULL);23712372// build position remap that maps each vertex to the one with identical position2373// wedge table stores next vertex with identical position for each vertex2374unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);2375unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count);2376buildPositionRemap(remap, wedge, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap, allocator);23772378// classify vertices; vertex kind determines collapse rules, see kCanCollapse2379unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count);2380unsigned int* loop = allocator.allocate<unsigned int>(vertex_count);2381unsigned int* loopback = allocator.allocate<unsigned int>(vertex_count);2382classifyVertices(vertex_kind, loop, loopback, vertex_count, adjacency, remap, wedge, vertex_lock, sparse_remap, options);23832384#if TRACE2385size_t unique_positions = 0;2386for (size_t i = 0; i < vertex_count; ++i)2387unique_positions += remap[i] == i;23882389printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions));23902391size_t kinds[Kind_Count] = {};2392for (size_t i = 0; i < vertex_count; ++i)2393kinds[vertex_kind[i]] += remap[i] == i;23942395printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n",2396int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked]));2397#endif23982399Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2400float vertex_offset[3] = {};2401float vertex_scale = rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap, vertex_offset);24022403float* vertex_attributes = NULL;2404unsigned int attribute_remap[kMaxAttributes];24052406if (attribute_count)2407{2408// remap attributes to only include ones with weight > 0 to minimize memory/compute overhead for quadrics2409size_t attributes_used = 0;2410for (size_t i = 0; i < attribute_count; ++i)2411if (attribute_weights[i] > 0)2412attribute_remap[attributes_used++] = unsigned(i);24132414attribute_count = attributes_used;2415vertex_attributes = allocator.allocate<float>(vertex_count * attribute_count);2416rescaleAttributes(vertex_attributes, vertex_attributes_data, vertex_count, vertex_attributes_stride, attribute_weights, attribute_count, attribute_remap, sparse_remap);2417}24182419Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count);2420memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric));24212422Quadric* attribute_quadrics = NULL;2423QuadricGrad* attribute_gradients = NULL;2424QuadricGrad* volume_gradients = NULL;24252426if (attribute_count)2427{2428attribute_quadrics = allocator.allocate<Quadric>(vertex_count);2429memset(attribute_quadrics, 0, vertex_count * sizeof(Quadric));24302431attribute_gradients = allocator.allocate<QuadricGrad>(vertex_count * attribute_count);2432memset(attribute_gradients, 0, vertex_count * attribute_count * sizeof(QuadricGrad));24332434if (options & meshopt_SimplifyInternalSolve)2435{2436volume_gradients = allocator.allocate<QuadricGrad>(vertex_count);2437memset(volume_gradients, 0, vertex_count * sizeof(QuadricGrad));2438}2439}24402441fillFaceQuadrics(vertex_quadrics, volume_gradients, result, index_count, vertex_positions, remap);2442fillVertexQuadrics(vertex_quadrics, vertex_positions, vertex_count, remap, options);2443fillEdgeQuadrics(vertex_quadrics, result, index_count, vertex_positions, remap, vertex_kind, loop, loopback);24442445if (attribute_count)2446fillAttributeQuadrics(attribute_quadrics, attribute_gradients, result, index_count, vertex_positions, vertex_attributes, attribute_count);24472448unsigned int* components = NULL;2449float* component_errors = NULL;2450size_t component_count = 0;2451float component_nexterror = 0;24522453if (options & meshopt_SimplifyPrune)2454{2455components = allocator.allocate<unsigned int>(vertex_count);2456component_count = buildComponents(components, vertex_count, result, index_count, remap);24572458component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents2459measureComponents(component_errors, component_count, components, vertex_positions, vertex_count);24602461component_nexterror = FLT_MAX;2462for (size_t i = 0; i < component_count; ++i)2463component_nexterror = component_nexterror > component_errors[i] ? component_errors[i] : component_nexterror;24642465#if TRACE2466printf("components: %d (min error %e)\n", int(component_count), sqrtf(component_nexterror));2467#endif2468}24692470#if TRACE2471size_t pass_count = 0;2472#endif24732474size_t collapse_capacity = boundEdgeCollapses(adjacency, vertex_count, index_count, vertex_kind);24752476Collapse* edge_collapses = allocator.allocate<Collapse>(collapse_capacity);2477unsigned int* collapse_order = allocator.allocate<unsigned int>(collapse_capacity);2478unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count);2479unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count);24802481size_t result_count = index_count;2482float result_error = 0;2483float vertex_error = 0;24842485// target_error input is linear; we need to adjust it to match quadricError units2486float error_scale = (options & meshopt_SimplifyErrorAbsolute) ? vertex_scale : 1.f;2487float error_limit = (target_error * target_error) / (error_scale * error_scale);24882489while (result_count > target_index_count)2490{2491// note: throughout the simplification process adjacency structure reflects welded topology for result-in-progress2492updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap);24932494size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, collapse_capacity, result, result_count, remap, vertex_kind, loop, loopback);2495assert(edge_collapse_count <= collapse_capacity);24962497// no edges can be collapsed any more due to topology restrictions2498if (edge_collapse_count == 0)2499break;25002501#if TRACE2502printf("pass %d:%c", int(pass_count++), TRACE >= 2 ? '\n' : ' ');2503#endif25042505rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_attributes, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, loop, loopback);25062507sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count);25082509size_t triangle_collapse_goal = (result_count - target_index_count) / 3;25102511for (size_t i = 0; i < vertex_count; ++i)2512collapse_remap[i] = unsigned(i);25132514memset(collapse_locked, 0, vertex_count);25152516size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, loop, loopback, vertex_positions, adjacency, triangle_collapse_goal, error_limit, result_error);25172518// no edges can be collapsed any more due to hitting the error limit or triangle collapse limit2519if (collapses == 0)2520break;25212522updateQuadrics(collapse_remap, vertex_count, vertex_quadrics, volume_gradients, attribute_quadrics, attribute_gradients, attribute_count, vertex_positions, remap, vertex_error);25232524// updateQuadrics will update vertex error if we use attributes, but if we don't then result_error and vertex_error are equivalent2525vertex_error = attribute_count == 0 ? result_error : vertex_error;25262527// note: we update loops following edge collapses, but after this we might still have stale loop data2528// this can happen when a triangle with a loop edge gets collapsed along a non-loop edge2529// that works since a loop that points to a vertex that is no longer connected is not affecting collapse logic2530remapEdgeLoops(loop, vertex_count, collapse_remap);2531remapEdgeLoops(loopback, vertex_count, collapse_remap);25322533result_count = remapIndexBuffer(result, result_count, collapse_remap, remap);25342535if ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= vertex_error)2536result_count = pruneComponents(result, result_count, components, component_errors, component_count, vertex_error, component_nexterror);2537}25382539// at this point, component_nexterror might be stale: component it references may have been removed through a series of edge collapses2540bool component_nextstale = true;25412542// we're done with the regular simplification but we're still short of the target; try pruning more aggressively towards error_limit2543while ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= error_limit)2544{2545#if TRACE2546printf("pass %d: cleanup; ", int(pass_count++));2547#endif25482549float component_cutoff = component_nexterror * 1.5f < error_limit ? component_nexterror * 1.5f : error_limit;25502551// track maximum error in eligible components as we are increasing resulting error2552float component_maxerror = 0;2553for (size_t i = 0; i < component_count; ++i)2554if (component_errors[i] > component_maxerror && component_errors[i] <= component_cutoff)2555component_maxerror = component_errors[i];25562557size_t new_count = pruneComponents(result, result_count, components, component_errors, component_count, component_cutoff, component_nexterror);2558if (new_count == result_count && !component_nextstale)2559break;25602561component_nextstale = false; // pruneComponents guarantees next error is up to date2562result_count = new_count;2563result_error = result_error < component_maxerror ? component_maxerror : result_error;2564vertex_error = vertex_error < component_maxerror ? component_maxerror : vertex_error;2565}25662567#if TRACE2568printf("result: %d triangles, error: %e (pos %.3e); total %d passes\n", int(result_count / 3), sqrtf(result_error), sqrtf(vertex_error), int(pass_count));2569#endif25702571// if solve is requested, update input buffers destructively from internal data2572if (options & meshopt_SimplifyInternalSolve)2573{2574unsigned char* vertex_update = collapse_locked; // reuse as scratch space2575memset(vertex_update, 0, vertex_count);25762577// limit quadric solve to vertices that are still used in the result2578for (size_t i = 0; i < result_count; ++i)2579{2580unsigned int v = result[i];25812582// mark the vertex for finalizeVertices and root vertex for solve*2583vertex_update[remap[v]] = vertex_update[v] = 1;2584}25852586// edge adjacency may be stale as we haven't updated it after last series of edge collapses2587updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap);25882589solvePositions(vertex_positions, vertex_count, vertex_quadrics, volume_gradients, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, adjacency, vertex_kind, vertex_update);25902591if (attribute_count)2592solveAttributes(vertex_positions, vertex_attributes, vertex_count, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, vertex_update);25932594finalizeVertices(const_cast<float*>(vertex_positions_data), vertex_positions_stride, const_cast<float*>(vertex_attributes_data), vertex_attributes_stride, attribute_weights, attribute_count, vertex_count, vertex_positions, vertex_attributes, sparse_remap, attribute_remap, vertex_scale, vertex_offset, vertex_kind, vertex_update, vertex_lock);2595}25962597// if debug visualization data is requested, fill it instead of index data; for simplicity, this doesn't work with sparsity2598if ((options & meshopt_SimplifyInternalDebug) && !sparse_remap)2599{2600assert(Kind_Count <= 8 && vertex_count < (1 << 28)); // 3 bit kind, 1 bit loop26012602for (size_t i = 0; i < result_count; i += 3)2603{2604unsigned int a = result[i + 0], b = result[i + 1], c = result[i + 2];26052606result[i + 0] |= (vertex_kind[a] << 28) | (unsigned(loop[a] == b || loopback[b] == a) << 31);2607result[i + 1] |= (vertex_kind[b] << 28) | (unsigned(loop[b] == c || loopback[c] == b) << 31);2608result[i + 2] |= (vertex_kind[c] << 28) | (unsigned(loop[c] == a || loopback[a] == c) << 31);2609}2610}26112612// convert resulting indices back into the dense space of the larger mesh2613if (sparse_remap)2614for (size_t i = 0; i < result_count; ++i)2615result[i] = sparse_remap[result[i]];26162617// result_error is quadratic; we need to remap it back to linear2618if (out_result_error)2619*out_result_error = sqrtf(result_error) * error_scale;26202621return result_count;2622}26232624size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2625{2626assert((options & meshopt_SimplifyInternalSolve) == 0); // use meshopt_simplifyWithUpdate instead26272628return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, 0, NULL, 0, NULL, target_index_count, target_error, options, out_result_error);2629}26302631size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2632{2633assert((options & meshopt_SimplifyInternalSolve) == 0); // use meshopt_simplifyWithUpdate instead26342635return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, vertex_attributes_data, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, out_result_error);2636}26372638size_t meshopt_simplifyWithUpdate(unsigned int* indices, size_t index_count, float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error)2639{2640return meshopt_simplifyEdge(indices, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, vertex_attributes_data, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options | meshopt_SimplifyInternalSolve, out_result_error);2641}26422643size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* out_result_error)2644{2645using namespace meshopt;26462647assert(index_count % 3 == 0);2648assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2649assert(vertex_positions_stride % sizeof(float) == 0);2650assert(target_index_count <= index_count);26512652// we expect to get ~2 triangles/vertex in the output2653size_t target_cell_count = target_index_count / 6;26542655meshopt_Allocator allocator;26562657Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2658rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);26592660// find the optimal grid size using guided binary search2661#if TRACE2662printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3));2663printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3));2664#endif26652666unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);26672668const int kInterpolationPasses = 5;26692670// invariant: # of triangles in min_grid <= target_count2671int min_grid = int(1.f / (target_error < 1e-3f ? 1e-3f : (target_error < 1.f ? target_error : 1.f)));2672int max_grid = 1025;2673size_t min_triangles = 0;2674size_t max_triangles = index_count / 3;26752676// when we're error-limited, we compute the triangle count for the min. size; this accelerates convergence and provides the correct answer when we can't use a larger grid2677if (min_grid > 1 || vertex_lock)2678{2679computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, min_grid);2680min_triangles = countTriangles(vertex_ids, indices, index_count);2681}26822683// instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...2684int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);26852686for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)2687{2688if (min_triangles >= target_index_count / 3 || max_grid - min_grid <= 1)2689break;26902691// we clamp the prediction of the grid size to make sure that the search converges2692int grid_size = next_grid_size;2693grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size);26942695computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, grid_size);2696size_t triangles = countTriangles(vertex_ids, indices, index_count);26972698#if TRACE2699printf("pass %d (%s): grid size %d, triangles %d, %s\n",2700pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"),2701grid_size, int(triangles),2702(triangles <= target_index_count / 3) ? "under" : "over");2703#endif27042705float tip = interpolate(float(size_t(target_index_count / 3)), float(min_grid), float(min_triangles), float(grid_size), float(triangles), float(max_grid), float(max_triangles));27062707if (triangles <= target_index_count / 3)2708{2709min_grid = grid_size;2710min_triangles = triangles;2711}2712else2713{2714max_grid = grid_size;2715max_triangles = triangles;2716}27172718// we start by using interpolation search - it usually converges faster2719// however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)2720next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;2721}27222723if (min_triangles == 0)2724{2725if (out_result_error)2726*out_result_error = 1.f;27272728return 0;2729}27302731// build vertex->cell association by mapping all vertices with the same quantized position to the same cell2732size_t table_size = hashBuckets2(vertex_count);2733unsigned int* table = allocator.allocate<unsigned int>(table_size);27342735unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);27362737computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, min_grid);2738size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);27392740// build a quadric for each target cell2741Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count);2742memset(cell_quadrics, 0, cell_count * sizeof(Quadric));27432744fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells);27452746// for each target cell, find the vertex with the minimal error2747unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);2748float* cell_errors = allocator.allocate<float>(cell_count);27492750fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count);27512752// compute error2753float result_error = 0.f;27542755for (size_t i = 0; i < cell_count; ++i)2756result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;27572758// vertex collapses often result in duplicate triangles; we need a table to filter them out2759size_t tritable_size = hashBuckets2(min_triangles);2760unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size);27612762// note: this is the first and last write to destination, which allows aliasing destination with indices2763size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap);27642765#if TRACE2766printf("result: grid size %d, %d cells, %d triangles (%d unfiltered), error %e\n", min_grid, int(cell_count), int(write / 3), int(min_triangles), sqrtf(result_error));2767#endif27682769if (out_result_error)2770*out_result_error = sqrtf(result_error);27712772return write;2773}27742775size_t meshopt_simplifyPrune(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, float target_error)2776{2777using namespace meshopt;27782779assert(index_count % 3 == 0);2780assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2781assert(vertex_positions_stride % sizeof(float) == 0);2782assert(target_error >= 0);27832784meshopt_Allocator allocator;27852786unsigned int* result = destination;2787if (result != indices)2788memcpy(result, indices, index_count * sizeof(unsigned int));27892790// build position remap that maps each vertex to the one with identical position2791unsigned int* remap = allocator.allocate<unsigned int>(vertex_count);2792buildPositionRemap(remap, NULL, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, allocator);27932794Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2795rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, NULL);27962797unsigned int* components = allocator.allocate<unsigned int>(vertex_count);2798size_t component_count = buildComponents(components, vertex_count, indices, index_count, remap);27992800float* component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents2801measureComponents(component_errors, component_count, components, vertex_positions, vertex_count);28022803float component_nexterror = 0;2804size_t result_count = pruneComponents(result, index_count, components, component_errors, component_count, target_error * target_error, component_nexterror);28052806return result_count;2807}28082809size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count)2810{2811using namespace meshopt;28122813assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2814assert(vertex_positions_stride % sizeof(float) == 0);2815assert(vertex_colors_stride == 0 || (vertex_colors_stride >= 12 && vertex_colors_stride <= 256));2816assert(vertex_colors_stride % sizeof(float) == 0);2817assert(vertex_colors == NULL || vertex_colors_stride != 0);2818assert(target_vertex_count <= vertex_count);28192820size_t target_cell_count = target_vertex_count;28212822if (target_cell_count == 0)2823return 0;28242825meshopt_Allocator allocator;28262827Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count);2828rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride);28292830// find the optimal grid size using guided binary search2831#if TRACE2832printf("source: %d vertices\n", int(vertex_count));2833printf("target: %d cells\n", int(target_cell_count));2834#endif28352836unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count);28372838size_t table_size = hashBuckets2(vertex_count);2839unsigned int* table = allocator.allocate<unsigned int>(table_size);28402841const int kInterpolationPasses = 5;28422843// invariant: # of vertices in min_grid <= target_count2844int min_grid = 0;2845int max_grid = 1025;2846size_t min_vertices = 0;2847size_t max_vertices = vertex_count;28482849// instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size...2850int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f);28512852for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass)2853{2854assert(min_vertices < target_vertex_count);2855assert(max_grid - min_grid > 1);28562857// we clamp the prediction of the grid size to make sure that the search converges2858int grid_size = next_grid_size;2859grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size);28602861computeVertexIds(vertex_ids, vertex_positions, NULL, vertex_count, grid_size);2862size_t vertices = countVertexCells(table, table_size, vertex_ids, vertex_count);28632864#if TRACE2865printf("pass %d (%s): grid size %d, vertices %d, %s\n",2866pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"),2867grid_size, int(vertices),2868(vertices <= target_vertex_count) ? "under" : "over");2869#endif28702871float tip = interpolate(float(target_vertex_count), float(min_grid), float(min_vertices), float(grid_size), float(vertices), float(max_grid), float(max_vertices));28722873if (vertices <= target_vertex_count)2874{2875min_grid = grid_size;2876min_vertices = vertices;2877}2878else2879{2880max_grid = grid_size;2881max_vertices = vertices;2882}28832884if (vertices == target_vertex_count || max_grid - min_grid <= 1)2885break;28862887// we start by using interpolation search - it usually converges faster2888// however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN)2889next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2;2890}28912892if (min_vertices == 0)2893return 0;28942895// build vertex->cell association by mapping all vertices with the same quantized position to the same cell2896unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count);28972898computeVertexIds(vertex_ids, vertex_positions, NULL, vertex_count, min_grid);2899size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count);29002901// accumulate points into a reservoir for each target cell2902Reservoir* cell_reservoirs = allocator.allocate<Reservoir>(cell_count);2903memset(cell_reservoirs, 0, cell_count * sizeof(Reservoir));29042905fillCellReservoirs(cell_reservoirs, cell_count, vertex_positions, vertex_colors, vertex_colors_stride, vertex_count, vertex_cells);29062907// for each target cell, find the vertex with the minimal error2908unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count);2909float* cell_errors = allocator.allocate<float>(cell_count);29102911// we scale the color weight to bring it to the same scale as position so that error addition makes sense2912float color_weight_scaled = color_weight * (min_grid == 1 ? 1.f : 1.f / (min_grid - 1));29132914fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_reservoirs, vertex_positions, vertex_colors, vertex_colors_stride, color_weight_scaled * color_weight_scaled, vertex_count);29152916// copy results to the output2917assert(cell_count <= target_vertex_count);2918memcpy(destination, cell_remap, sizeof(unsigned int) * cell_count);29192920#if TRACE2921// compute error2922float result_error = 0.f;29232924for (size_t i = 0; i < cell_count; ++i)2925result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error;29262927printf("result: %d cells, %e error\n", int(cell_count), sqrtf(result_error));2928#endif29292930return cell_count;2931}29322933float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)2934{2935using namespace meshopt;29362937assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256);2938assert(vertex_positions_stride % sizeof(float) == 0);29392940float extent = rescalePositions(NULL, vertex_positions, vertex_count, vertex_positions_stride);29412942return extent;2943}294429452946