CoACD (Collision-Aware Convex Decomposition)

repository·main·Indexed 22 days ago

https://github.com/sarahweiii/coacd

A method for decomposing 3D meshes into approximate convex components designed to preserve collision conditions for physics engines. It provides a C++ library, a Python package via PyPI with a CLI, and a Unity package for version 2020.1 or later. Key features include Monte Carlo Tree Search (MCTS) for optimal cutting, manifold preprocessing, and support for real-world metric scales.

Tokens
4.3K
Snippets
16
Records
20
Agent score
76%

What's inside CoACD

  1. Tuning CoACD results

    main

    Use these strategies to improve decomposition quality:

    1. Balance Detail vs. Count: Adjust the threshold (-t). A higher value results in fewer, coarser components; a lower value results in more, finer-grained components.
    2. Non-Manifold Meshes: If the input is not manifold, adjust prep-resolution (-pr) between 20 and 100. Higher values preserve more detail but increase runtime.
    3. Improve Cutting Strategy: To prioritize component count over speed, increase MCTS parameters: searching depth (-md), searching node (-mn), and searching iteration (-mi).
    4. Skip Preprocessing: If your mesh is already a 2-manifold solid, set --preprocess-mode (-pm) to off to speed up the process and preserve details. Warning: Using off on non-manifold meshes may cause incorrect results.
    5. Reproducibility: Use --seed to ensure the same results across runs, as the algorithm is stochastic.
  2. Install and use CoACD via PyPI

    main

    You can install the CoACD Python package using pip. The input mesh must be a triangle mesh. If using non-triangular faces (like quads or n-gons), triangulate them first (e.g., in Blender).

    To use the package in a script, load your mesh with trimesh, wrap it in a coacd.Mesh object, and call coacd.run_coacd() to get a list of convex hulls.

    import coacd
    import trimesh
    
    # Load mesh
    mesh = trimesh.load(input_file, force="mesh")
    # Wrap for CoACD
    coacd_mesh = coacd.Mesh(mesh.vertices, mesh.faces)
    # Run decomposition
    parts = coacd.run_coacd(coacd_mesh)
  3. Use CoACD in Unity

    main

    Editor Workflow

    1. Add a CoACD component to your object and tweak parameters in the Inspector.
    2. Right-click the component header and select Generate Collision Meshes (for the object) or Generate Collision Meshes for Hierarchy (for the object and its children with MeshFilter).
    3. Unity mesh colliders will be generated as children under a Collision object.

    Runtime API

    You can call the decomposition directly via code: public List<Mesh> RunACD(Mesh mesh);

    // Call the runtime API on the CoACD component
    public List<Mesh> RunACD(Mesh mesh);
  4. Install CoACD for Unity

    main

    CoACD is available as a Unity package for Unity 2020.1 or later.

    1. Open Window -> Package Manager.
    2. Click the + button and select Add package from git URL.
    3. Enter the following URL:

    https://github.com/SarahWeiii/CoACD.git?path=/Packages/info.flandre.coacd#unity 4. Click Add.

  5. Compile CoACD from source

    main

    Prerequisites

    • git and cmake >= 3.24.
    • Compilers:
      • Linux: g++ >= 9, < 12
      • MacOS: clang >= 10.14
      • Windows: MSVC 2019/2022

    Build Steps

    1. Clone the repository with submodules: git clone --recurse-submodules https://github.com/SarahWeiii/CoACD.git
    2. Create a build directory: cd CoACD && mkdir build && cd build
    3. Run CMake and build:

    Linux/MacOS:

    cmake .. -DCMAKE_BUILD_TYPE=Release && make main -j

    Windows (MSVC):

    cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DOPENVDB_CORE_SHARED=OFF -DTBB_TEST=OFF -DCMAKE_CXX_FLAGS="/MT /EHsc"
    cmake --build . --target main --config Release
  6. Use real metric mode in CoACD Python API

    main

    If your mesh is in real-world scale (e.g., meters from a CAD model or 3D scan), you can use real_metric=True. This allows you to specify the threshold directly in meters instead of normalized units.

    # threshold is interpreted as 0.01 meters
    parts = coacd.run_coacd(mesh, threshold=0.01, real_metric=True)
  7. Configure COACD decomposition parameters via Params class

    main

    The coacd::Params class defines the configuration for the Approximate Convex Decomposition algorithm. These parameters control the input/output paths, the Monte Carlo Tree Search (MCTS) behavior, mesh preprocessing, and the decomposition quality.

    Basic Configuration

    • input_model: Path to the input mesh file.
    • output_name: Path where the decomposed output will be saved.
    • remesh_output_name: Path for the remeshed output.
    • mcts_nodes: Number of nodes for the tree search.
    • threshold: Concavity threshold for decomposition.
    • resolution: Resolution used during processing.
    • seed: Random seed for reproducibility.
    • rv_k: Parameter related to random vertex sampling.
    • preprocess_mode: Mode for preprocessing (e.g., "auto").
    • prep_resolution: Resolution for the preprocessing step.
    • pca: Boolean flag to enable Principal Component Analysis.
    • merge: Boolean flag to enable merging of convex hulls.
    • max_convex_hull: Maximum number of convex hulls (set to -1 for default/unlimited).
    • dmc_thres: Threshold for Collision-Aware Concavity.
    • apx_mode: Approximation mode (e.g., "ch").
    • decimate: Boolean flag to enable mesh decimation.
    • max_ch_vertex: Maximum number of vertices per convex hull.
    • extrude: Boolean flag to enable extrusion.
    • extrude_margin: Margin used for extrusion.
    • real_metric: Boolean flag to use real metric mode (threshold in meters).

    MCTS Configuration

    • mcts_iteration: Number of MCTS iterations.
    • mcts_max_depth: Maximum depth of the MCTS tree.
    coacd::Params params;
    params.input_model = "my_model.obj";
    params.threshold = 0.01;
    params.mcts_iteration = 200;
    // Use params to initialize the decomposition process
  8. Reference: CoACD CLI Parameters

    main

    The following flags are available for the ./main executable:

    FlagLong NameDescription
    -i--inputPath for input mesh (.obj)
    -o--outputPath for output (.obj or .wrl)
    -ro--remesh-outputPath for preprocessed mesh output (.obj)
    -pr--prep-resolutionResolution for manifold preprocess (20~100, default = 50)
    -t--thresholdConcavity threshold (0.01~1, default = 0.05)
    -pm--preprocess-modeManifold preprocessing mode: 'auto' (default), 'on', or 'off'
    -nm--no-mergeDisable merge postprocessing (default = false)
    -c--max-convex-hullMax # convex hulls (default = -1; works only when merge is enabled)
    -mi--mcts-iterationMCTS search iterations (60~2000, default = 100)
    -md--mcts-depthMax MCTS search depth (2~7, default = 3)
    -mn--mcts-nodeMax MCTS child nodes (10~40, default = 20)
    -r--resolutionSampling resolution for Hausdorff distance (1e3~1e4, default = 2000)
    --pcaEnable PCA pre-processing (default = false)
    -kValue for $k$ for $R_v$ calculation (default = 0.3)
    -d--decimateEnable max vertex constraint per convex hull (default = false)
    -dt--max-ch-vertexMax vertex value for each convex hull (only when -d is enabled, default = 256)
    -ex--extrudeExtrude neighboring convex hulls along overlapping faces (default = false)
    -em--extrude-marginExtrude margin (only when -ex is enabled, default = 0.01)
    -rm--real-metricEnable real metric mode (threshold in meters, default = false)
    -am--approximate-modeApproximation shape type: 'ch' (convex hulls, default) or 'box' (cubes)
    --seedRandom seed for stochastic sampling (default = random())
  9. Run CoACD CLI (C++ version)

    main

    After compiling, you can run the algorithm using the ./main executable. By default, it accepts an .obj input and produces .obj and .wrl outputs.

    ./main -i PATH_OF_YOUR_MESH -o PATH_OF_OUTPUT
  10. Load and save OBJ files in coacd

    main

    You can interface with the coacd::Model class to read from or write to standard Wavefront OBJ files.

    • bool LoadOBJ(const string &fileName): Loads a mesh from the specified file. Returns true if successful.
    • void SaveOBJ(const string &fileName): Saves the current mesh state to the specified file.
    coacd::Model model;
    model.LoadOBJ("path/to/model.obj");
    // ... process model ...
    model.SaveOBJ("path/to/output.obj");
  11. Manage mesh data with the Model class

    main

    The coacd::Model class is the primary data structure for representing 3D mesh models within the library. It stores geometry as a collection of vertices (points) and face indices (triangles).

    Key capabilities include:

    • Loading/Saving: Import and export meshes using the .obj format via LoadOBJ(fileName) and SaveOBJ(fileName).
    • Geometry Processing: Perform Principal Component Analysis (PCA) with PCA(), align the model to principal axes with AlignToPrincipalAxes(), and normalize the mesh with Normalize().
    • Analysis: Check if the mesh is manifold using IsManifold() or if it is thin using CheckThin().
    • Point Sampling: Generate point sets for collision or analysis using ExtractPointSet(...) or GetPoints(resolution).
    • Convex Hull Computation: Compute various convex approximations like ComputeCH (Convex Hull), ComputeVCH (Volumetric Convex Hull), or ComputeBOX (Bounding Box).
    coacd::Model mesh;
    if (mesh.LoadOBJ("input.obj")) {
        mesh.AlignToPrincipalAxes();
        mesh.SaveOBJ("processed.obj");
    }