Meshing in CFD — Theory, Techniques, Quality and Optimization
Understand the mathematical foundations of computational meshing, structured and unstructured grids, boundary-layer resolution, mesh quality, OpenFOAM snappyHexMesh, optimization, and grid convergence.
1. Introduction
Computational Fluid Dynamics (CFD) is based on the numerical solution of governing equations for fluid flow, heat transfer, and related physical processes. These equations are defined over continuous spatial domains, but numerical solvers represent the domain using a finite number of computational cells or elements.
The process of dividing the computational domain into these discrete entities is called meshing or grid generation.
Meshing is not merely a preprocessing operation. It directly influences how accurately the governing equations can be discretized, how effectively gradients and fluxes can be calculated, and how efficiently the numerical system can be solved.
A poor mesh can produce excessive numerical diffusion, inaccurate wall shear stress, incorrect pressure drop, unreliable heat-transfer predictions, and convergence difficulties. A carefully designed mesh can improve numerical accuracy while keeping memory requirements and computational cost manageable.
The objective is not to create the finest possible mesh. It is to create a mesh that adequately resolves the relevant physics, supports the selected numerical schemes, satisfies geometric quality requirements, and produces sufficiently accurate engineering quantities.
This article develops meshing principles from first principles and connects them to practical OpenFOAM workflows.
Learning objectives
By the end of this module, you should be able to:
- Explain why a computational mesh is required.
- Understand the relationship between mesh resolution and discretization error.
- Distinguish structured, unstructured, hybrid, Cartesian, polyhedral, and adaptive meshes.
- Estimate characteristic cell sizes and near-wall resolution.
- Understand boundary-layer meshing and the dimensionless wall distance, y+.
- Interpret skewness, non-orthogonality, aspect ratio, and other mesh-quality metrics.
- Generate meshes using blockMesh and snappyHexMesh.
- Understand and configure OpenFOAM mesh-quality controls.
- Diagnose common mesh-generation failures.
- Optimize mesh distribution and computational cost.
- Perform mesh-refinement and grid-convergence studies.
- Implement a basic mesh-connectivity and geometric-quality analysis in C++.
2. Why Does CFD Require a Mesh?
2.1 Continuous governing equations
Consider incompressible Newtonian flow with constant density and viscosity.
The continuity equation is
where is the velocity vector.
The momentum equation can be written as
where:
- is velocity.
- is time.
- is pressure.
- is fluid density.
- is kinematic viscosity.
- represents body-force acceleration.
These equations describe the evolution of the flow field at every point in the domain.
However, solving them analytically is possible only for a limited number of simplified problems. Practical geometries generally require numerical methods.
2.2 Discretizing the computational domain
Consider a three-dimensional domain . The mesh divides it into a finite collection of cells:
where:
- is the total number of cells.
- is the volume of cell .
For a finite-volume method, the governing equations are integrated over each control volume.
For a transported quantity ,
where:
- is the flux of the transported quantity.
- is the outward face-normal vector.
- represents source terms.
- is the boundary of cell .
The mesh supplies the cell volumes, face areas, face normals, neighbour relationships, and geometric distances needed to calculate the discrete equations.
The mesh therefore defines the geometric framework of the numerical approximation.
2.3 How a finite-volume mesh conserves a quantity
For two neighbouring cells, the flux leaving the first cell through their common face should equal the flux entering the second cell, with the opposite sign.
If the shared-face flux is , then its contribution to the two cells is
where and denote contributions to the corresponding cell balances, using a consistent face orientation.
When the cell equations are summed over the domain, internal-face contributions cancel pairwise. Boundary fluxes and source terms remain.
This cancellation is a fundamental property of conservative finite-volume formulations.
A poor mesh does not automatically destroy conservation if the method is implemented correctly. However, distorted cells can reduce the accuracy of reconstructed gradients and fluxes, even when the discrete balance is conservative.
2.4 Mesh resolution and physical length scales
Suppose the velocity changes rapidly near a wall but remains nearly uniform in the core of a pipe.
A uniform mesh with very small cells everywhere would resolve the wall region but waste computational resources in the nearly uniform core.
A better approach uses small cells near the wall and larger cells where the solution varies more gradually.
The key idea is:
Mesh resolution should follow the relevant physical length scales, not simply the geometric dimensions of the entire domain.
3. Mesh Resolution and Discretization Error
3.1 What is discretization error?
Discretization error is the difference between the exact solution of the continuous mathematical problem and the numerical solution produced by the discrete equations.
For a sufficiently smooth solution and a suitable numerical scheme, a quantity of interest may approximately follow
where:
- is the computed result for representative spacing .
- is the limiting value as approaches zero.
- is an error coefficient.
- is the order of convergence.
This relationship is an approximation. It assumes that the solution is in a suitable convergence regime and that other errors do not dominate.
3.2 What happens when the mesh is too coarse?
An insufficiently resolved mesh can cause:
- Excessive numerical diffusion.
- Incorrect velocity gradients.
- Poor representation of recirculation regions.
- Inaccurate wall shear stress.
- Incorrect heat-transfer rates.
- Poor resolution of jets and wakes.
- Misrepresentation of small gaps and geometric features.
- Increased sensitivity to numerical schemes and mesh alignment.
For example, a coarse mesh may predict a weaker velocity gradient in a shear layer, causing the layer to appear artificially thick.
Similarly, an under-resolved wake may show excessive mixing due to numerical diffusion rather than the physical turbulent mixing being modelled.
3.3 Why a finer mesh is not always sufficient
A fine mesh cannot correct every modelling error.
The accuracy of a CFD prediction also depends on:
- Physical assumptions.
- Turbulence and multiphase models.
- Boundary conditions.
- Numerical schemes.
- Temporal resolution.
- Iterative convergence.
- Geometry accuracy.
A very fine mesh with an unsuitable turbulence model can produce a highly resolved but physically inaccurate result.
3.4 Computational cost of refinement
For approximately uniform three-dimensional refinement,
Halving the characteristic cell spacing therefore increases the cell count by approximately a factor of eight.
This estimate applies to uniform refinement. Local refinement and changes in cell topology can produce different growth rates.
For transient calculations, refinement may also require smaller time steps, increasing computational cost further.
The goal is to achieve the required accuracy at an acceptable cost.
4. Types of Computational Meshes
4.1 Structured meshes
Structured meshes have an orderly connectivity pattern in which neighbouring cells can generally be identified using logical indices.
Typical examples include Cartesian grids and body-fitted multiblock hexahedral meshes.
Advantages:
- Efficient connectivity and data access.
- Predictable cell arrangement.
- Good alignment with dominant flow directions.
- Effective boundary-layer resolution.
- Often efficient memory usage.
Limitations:
- Complex geometry can require substantial block decomposition.
- Matching block interfaces can be difficult.
- Local refinement may require careful topology management.
Structured meshes are particularly useful for channels, ducts, turbomachinery passages, and geometries with predictable topology.
4.2 Unstructured meshes
Unstructured meshes use flexible connectivity to accommodate complex geometries.
Common cell types include tetrahedra and polyhedra.
Advantages:
- Flexible representation of complicated CAD surfaces.
- Convenient local refinement.
- Reduced dependence on structured block topology.
Limitations:
- Connectivity structures can require additional memory.
- Cell alignment may be less effective for strongly directional flow.
- Quality can vary significantly around complicated surfaces.
4.3 Hybrid meshes
Hybrid meshes combine multiple cell types.
A common arrangement uses prismatic layers near solid walls and tetrahedral or polyhedral cells in the outer flow region.
This combines boundary-layer control with geometric flexibility.
Hybrid meshes are widely used in industrial aerodynamics, internal flows, heat exchangers, and complex equipment.
4.4 Cartesian and cut-cell meshes
Cartesian meshes use predominantly axis-aligned cells. Cut-cell methods represent complex boundaries through intersections between surfaces and background cells.
Advantages include convenient automated refinement and relatively simple background-grid generation.
Challenges include small cut cells, geometric reconstruction, and appropriate treatment of wall gradients.
4.5 Polyhedral meshes
Polyhedral cells have more than four faces in three dimensions.
They can accommodate complex connectivity and are frequently used for complicated industrial geometries.
However, polyhedral cells are not automatically more accurate than hexahedral cells. Accuracy depends on their geometry, the discretization scheme, local resolution, and the physical problem.
4.6 Adaptive meshes
Adaptive mesh refinement changes local resolution according to indicators such as:
- Velocity gradients.
- Pressure gradients.
- Temperature gradients.
- Vorticity.
- Interface curvature.
- Estimated discretization error.
- Shock or discontinuity indicators.
Adaptive methods can concentrate cells in dynamically important regions.
Their disadvantages include additional implementation complexity, mesh-management overhead, and the need to control refinement and coarsening carefully.
5. Cell Size and Mesh Distribution
5.1 Characteristic cell size
For a three-dimensional cell with volume , an equivalent cubic length can be defined as
This provides a simple scalar measure of cell size.
However, it does not fully describe anisotropic cells. For a thin boundary-layer cell, the wall-normal spacing may be far smaller than the streamwise and spanwise dimensions.
Consequently, cell size should be interpreted together with cell shape and orientation.
5.2 Refinement ratio
A refinement ratio can be defined as
For , the fine mesh has smaller representative spacing.
For example, if the coarse mesh spacing is and the fine mesh spacing is ,
The number of cells may increase substantially as the mesh is refined, depending on whether refinement is one-dimensional, two-dimensional, three-dimensional, or local.
5.3 Geometric grading
Geometric grading changes cell dimensions progressively in a specified direction.
For a first-cell thickness and growth ratio ,
The total thickness of layers is
For ,
For example, ten layers with a first-layer thickness of and a growth ratio of have a total thickness of approximately .
The appropriate growth ratio depends on the flow physics, mesh topology, and mesher. The objective is to provide adequate resolution while avoiding unnecessarily abrupt changes in cell dimensions.
6. Boundary-Layer Meshing
6.1 Physical origin of the boundary layer
For a stationary no-slip wall,
The fluid velocity increases away from the wall, creating a strong velocity gradient in the wall-normal direction.
The wall shear stress is
where:
- is dynamic viscosity.
- is tangential velocity.
- is the wall-normal coordinate.
The accuracy of the wall shear stress depends on how effectively the numerical method represents the near-wall velocity gradient.
For heat transfer,
where is thermal conductivity and the sign depends on the chosen wall-normal convention.
An inadequate near-wall mesh can therefore affect friction, pressure drop, and heat-transfer predictions.
6.2 Dimensionless wall distance
The dimensionless wall distance is defined as
where
Here:
- is the distance from the wall to the first cell centre.
- is friction velocity.
- is kinematic viscosity.
- is density.
The target value depends on the near-wall turbulence treatment.
Low- wall-resolved RANS approaches often target values around 1, while wall-function approaches typically target the range required by their particular formulation.
Automatic or all- treatments may accommodate a wider range, but their applicability must be assessed using the model documentation and validation evidence.
There is no single universally correct target for all turbulence models.
6.3 Estimating the first-cell height
Rearranging the definition gives
Suppose water has
and the estimated friction velocity is
For a target ,
The first-cell-centre distance is approximately .
For a nearly planar wall and a cell whose centre lies halfway through its wall-normal thickness, the first-layer thickness is approximately .
This is only an initial estimate. The computed wall shear stress should be used to evaluate the actual field after the simulation.
6.4 Boundary-layer mesh design
A suitable boundary-layer mesh should account for:
- First-cell height.
- Number of layers.
- Layer growth ratio.
- Total layer thickness.
- Boundary-layer thickness.
- Wall curvature.
- Local separation and reattachment.
- Narrow gaps and geometric transitions.
A high layer count alone does not guarantee adequate resolution. The layers must cover the relevant region without creating severe distortions or terminating unexpectedly.
6.5 RANS, LES, and DNS requirements
Different turbulence approaches have different resolution requirements.
- RANS: models the effects of turbulent fluctuations and typically uses substantially fewer cells than scale-resolving methods.
- LES: resolves larger turbulent structures and models smaller scales. Its mesh must support the intended resolved turbulence content.
- DNS: aims to resolve all dynamically relevant turbulent scales and therefore has extremely demanding spatial and temporal requirements at high Reynolds numbers.
A mesh suitable for an industrial RANS calculation should not automatically be assumed suitable for LES or DNS.
7. Mesh-Quality Metrics
Mesh quality describes geometric properties that influence numerical approximation and solver robustness.
No single metric determines whether a mesh is suitable. Several metrics must be interpreted together.
7.1 Non-orthogonality
Non-orthogonality measures the angle between the face normal and the line connecting the centres of adjacent cells.
A common definition is
where:
- connects neighbouring cell centres.
- is the face-area vector.
A value near zero indicates that the face normal aligns with the cell-centre connection.
Large non-orthogonality can complicate gradient reconstruction and diffusive-flux evaluation.
7.2 Skewness
Skewness measures the distortion of a face relative to the geometric relationship expected by the mesh generator.
High skewness can reduce the accuracy of interpolation and gradient reconstruction.
The exact definition and numerical scale depend on the meshing software. Thresholds should therefore be interpreted using the relevant software documentation.
7.3 Aspect ratio
A simplified aspect ratio is
where and represent the maximum and minimum characteristic cell dimensions.
A high aspect ratio is not automatically undesirable. Thin boundary-layer cells are deliberately anisotropic.
Problems arise when cell orientation and geometry are unsuitable for the dominant gradients or when high aspect ratio is combined with severe skewness or non-orthogonality.
7.4 Cell-volume variation
A conceptual measure of neighbouring-cell volume variation is
where and are the larger and smaller volumes of adjacent cells.
Large abrupt changes can complicate interpolation and gradient reconstruction.
This conceptual ratio should not be confused with a particular software’s definition of a mesh-quality metric such as OpenFOAM’s minVolRatio.
7.5 Face twist and cell validity
Additional metrics assess:
- Face twist and planarity.
- Cell determinant or Jacobian-related quality.
- Minimum volume.
- Minimum face area.
- Tetrahedral decomposition quality.
- Concavity.
- Interpolation weights.
Negative or invalid cell volumes indicate serious geometric problems. However, positive cell volumes alone do not establish that a mesh is suitable.
7.6 Quality metrics are diagnostic tools
| Metric | Primary concern | Typical corrective action |
|---|---|---|
| Non-orthogonality | Diffusive fluxes and gradient correction | Improve cell alignment or topology |
| Skewness | Interpolation and gradient reconstruction | Improve snapping and surface resolution |
| Aspect ratio | Directional resolution | Align anisotropic cells with the physics |
| Volume variation | Abrupt cell-size changes | Smooth refinement transitions |
| Invalid cell volume | Cell inversion or invalid geometry | Repair geometry and regenerate |
| Poor boundary-layer coverage | Wall gradients and near-wall modelling | Redesign the prism-layer mesh |
The maximum values and spatial distributions of relevant metrics are usually more informative than averages alone.
8. OpenFOAM Meshing Workflow
OpenFOAM provides several meshing utilities. The appropriate approach depends on geometry complexity, cell topology, and near-wall requirements.
8.1 blockMesh
blockMesh generates a mesh from a block description in system/blockMeshDict.
A basic workflow is:
- Define vertices.
- Construct hexahedral blocks.
- Specify the number of cells in each direction.
- Define grading.
- Assign boundary patches.
- Generate and verify the mesh.
Typical commands:
blockMesh
checkMesh
blockMesh is particularly useful for channels, ducts, idealized geometries, and background meshes.
8.2 snappyHexMesh
snappyHexMesh generates a predominantly hexahedral mesh around triangulated surfaces.
Its principal stages are:
- Castellation: refine the background mesh near surfaces and selected regions.
- Snapping: move mesh points toward surfaces and features.
- Layer addition: insert near-wall prism layers where permitted by geometry and quality constraints.
A typical sequence is:
blockMesh
surfaceFeatureExtract
snappyHexMesh -overwrite
checkMesh -allTopology -allGeometry
The exact feature-extraction setup depends on the surface geometry and OpenFOAM version.
8.3 Surface preparation
Before volume meshing, inspect the geometry for:
- Gaps and intersecting surfaces.
- Duplicate faces.
- Tiny edges and sliver triangles.
- Non-manifold edges.
- Incorrect surface normals.
- Missing boundary patches.
- Narrow gaps relative to the background mesh.
Simplifying geometry can reduce cell count, but small features should only be removed when they are not important to the physical prediction.
8.4 Local refinement
Refinement should be concentrated around:
- Leading and trailing edges.
- Narrow gaps.
- Boundary layers.
- Jets and wakes.
- Separated shear layers.
- Strong thermal gradients.
- Fluid-solid interfaces.
- Other regions that influence the quantities of interest.
Avoid refining the entire domain uniformly unless the physical problem justifies it.
8.5 Prism-layer addition
Layer addition is often one of the most difficult stages of snappyHexMesh.
Common failure locations include sharp corners, narrow gaps, strongly curved surfaces, and regions where layers collide.
A systematic diagnostic approach is:
- Inspect surface quality.
- Check local background resolution.
- Verify first-layer height and growth ratio.
- Compare total layer thickness with available space.
- Inspect layer-termination controls.
- Review intermediate meshes.
- Adjust the geometry or meshing strategy before relaxing quality limits.
Reducing layer count may be necessary, but the resulting near-wall resolution must still be suitable for the selected model.
9. Understanding the OpenFOAM meshQualityDict
The following example is based on the OpenFOAM.com v2512 configuration supplied for this module.
/*--------------------------------*- C++ -*----------------------------------*\
| OpenFOAM.com v2512 reference CHT case |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object meshQualityDict;
}
maxNonOrtho 65;
maxBoundarySkewness 20;
maxInternalSkewness 4;
maxConcave 80;
minVol 1e-15;
minTetQuality 1e-30;
minArea -1;
minTwist 0.02;
minDeterminant 0.001;
minFaceWeight 0.02;
minVolRatio 0.01;
minTriangleTwist -1;
nSmoothScale 4;
errorReduction 0.75;
NOTE: These values are case-specific controls, not universal targets for every mesh.
9.1 Interpretation of the parameters
| Parameter | Value | Interpretation |
|---|---|---|
maxNonOrtho | 65 | Maximum permitted non-orthogonality for applicable checks |
maxBoundarySkewness | 20 | Boundary-face skewness limit |
maxInternalSkewness | 4 | Internal-face skewness limit |
maxConcave | 80 | Permitted concavity measure under the mesher’s definition |
minVol | 1e-15 | Minimum volume-related quality threshold; verify its implementation and units |
minTetQuality | 1e-30 | Extremely permissive lower threshold for tetrahedral decomposition quality |
minArea | -1 | Disables the minimum-area check under the documented convention |
minTwist | 0.02 | Lower limit for the face-twist metric |
minDeterminant | 0.001 | Lower limit for the normalized cell determinant |
minFaceWeight | 0.02 | Lower limit for the face interpolation-weight metric |
minVolRatio | 0.01 | Lower limit for the mesher’s cell-volume-ratio metric |
minTriangleTwist | -1 | Disables the triangle-twist-specific check under the documented convention |
nSmoothScale | 4 | Number of smoothing iterations used when distributing displacement corrections |
errorReduction | 0.75 | Controls displacement reduction at problematic points in applicable mesh-generation stages |
Consult the OpenFOAM mesh-quality documentation for version-specific definitions.
9.2 Important engineering observations
Non-orthogonality: A threshold of 65 degrees is a permitted limit, not an ideal target. Cells near this limit can still challenge numerical schemes.
Skewness: A more permissive boundary threshold does not mean distorted boundary faces are harmless. Boundary regions often contain the gradients most important to the engineering result.
Tetrahedral quality: A threshold of 1e-30 is extremely permissive. It should not be interpreted as a strong safeguard against degenerate tetrahedral decomposition.
Minimum volume: The value 1e-15 must be interpreted according to the relevant OpenFOAM implementation and mesh units. It is not a universal dimensionless quality threshold.
Disabled checks: The values -1 disable their corresponding checks under the documented convention. Other metrics may identify related problems, but this does not make the disabled checks redundant in every case.
Smoothing controls: Smoothing and displacement reduction can help prevent local quality deterioration, but they cannot repair fundamentally defective geometry.
9.3 Verify the final mesh
Use:
checkMesh -allTopology -allGeometry
For multi-region cases, check the supported region-specific options in the installed version and inspect every relevant region.
Also examine:
- Maximum non-orthogonality.
- Skewness distribution.
- Cell volumes.
- Boundary-layer coverage.
- Patch assignments.
- Fluid-solid interfaces.
- Local refinement transitions.
A successful mesh-generation run does not establish mesh independence or physical accuracy.
10. Common Meshing Problems and Solutions
10.1 Excessive non-orthogonality
Possible causes:
- Poor local topology.
- Abrupt cell-size transitions.
- Distorted cells around sharp features.
- Poor surface snapping.
Corrective actions:
- Improve cell alignment.
- Adjust local refinement.
- Repair geometry.
- Review snapping controls.
- Consider a different topology if the problem persists.
10.2 High skewness
Possible causes:
- Coarse background mesh near small features.
- Poor surface triangulation.
- Excessive snapping displacement.
- Complex intersections.
Corrective actions:
- Improve the surface mesh.
- Refine around important features.
- Adjust snapping tolerances.
- Remove irrelevant geometric details carefully.
10.3 Failed boundary-layer insertion
Possible causes:
- Insufficient space.
- Excessive layer thickness.
- Large growth ratio.
- Sharp curvature.
- Narrow gaps.
- Poor surface quality.
Corrective actions:
- Reduce total layer thickness.
- Adjust the growth ratio.
- Refine the background mesh.
- Improve geometry.
- Review layer termination and feature-angle settings.
10.4 Invalid or negative cell volumes
Possible causes:
- Cell inversion.
- Collapsed prism layers.
- Severe snapping distortion.
- Defective geometry.
Corrective actions:
- Identify the offending region.
- Inspect the local mesh and surface.
- Correct the underlying geometry or mesh controls.
- Regenerate the mesh.
- Repeat topology and geometry checks.
Do not treat a solver crash as a substitute for identifying the geometric problem.
10.5 Excessive cell count
Possible causes:
- Overly fine background mesh.
- Unnecessary feature refinement.
- Excessive surface triangulation.
- Redundant refinement regions.
Corrective actions:
- Simplify irrelevant geometry.
- Reduce background resolution where justified.
- Refine selectively.
- Compare engineering outputs before and after refinement.
The aim is to remove cells that contribute little to the accuracy of the quantities of interest.
11. Mesh Optimization
11.1 Optimize resolution, not just cell count
A useful mesh strategy distinguishes:
- Critical regions: boundary layers, shear layers, narrow gaps, interfaces, and strong gradients.
- Transition regions: areas connecting fine and coarse resolution.
- Low-sensitivity regions: areas where additional resolution has little effect on the outputs of interest.
This classification should be revisited after inspecting the computed solution.
11.2 Engineering quantities of interest
Monitor outputs such as:
- Pressure drop.
- Drag and lift coefficients.
- Wall shear stress.
- Heat-transfer rate.
- Mass and energy balance.
- Recirculation length.
- Turbine or pump torque.
- Hydraulic efficiency.
- Phase fraction or cavitation indicators.
A visually smoother contour is not sufficient evidence that the mesh is better.
11.3 Cost-aware refinement workflow
A practical procedure is:
- Generate a baseline mesh.
- Run the solver to adequate convergence.
- Record the important engineering outputs.
- Inspect mesh quality and solution gradients.
- Refine regions where the outputs remain sensitive.
- Repeat the simulation.
- Compare accuracy, cell count, memory, and runtime.
- Retain the refinement when its benefits justify the additional cost.
12. Mesh Independence and Grid Convergence
12.1 What is mesh independence?
Mesh independence means that further mesh refinement produces changes smaller than a defined tolerance for the relevant quantities of interest.
It does not mean that the computed solution is identical on every mesh or that the result necessarily matches reality.
12.2 Three-mesh comparison
A common study uses coarse, medium, and fine meshes.
| Mesh | Representative spacing | Cell count | Pressure drop |
|---|---|---|---|
| Coarse | |||
| Medium | |||
| Fine |
The entries must be obtained from actual simulations.
The relative difference between two mesh results can be calculated as
where and are the corresponding results.
If the reference quantity is close to zero, use an absolute tolerance or another appropriate engineering scale.
12.3 Richardson extrapolation
For three systematically refined meshes with a common refinement ratio , an approximate observed convergence order may be estimated by
where the subscripts refer to coarse, medium, and fine solutions.
This formula assumes suitable convergence behaviour and should not be applied blindly to irregular refinement sequences or oscillatory results.
12.4 Grid Convergence Index
The Grid Convergence Index (GCI) provides a structured framework for reporting uncertainty associated with spatial discretization.
Richardson extrapolation and GCI are most appropriate when the refinement sequence is sufficiently systematic and the observed results support the assumptions behind the method.
A mesh study should document:
- Mesh-generation settings.
- Cell counts and representative spacing.
- Near-wall resolution.
- Relevant quality metrics.
- Solver convergence.
- Changes in engineering outputs.
- The tolerance used to judge adequacy.
- Any non-monotonic convergence.
12.5 Verification versus validation
Verification asks whether the numerical problem has been solved adequately, including spatial and temporal discretization and iterative convergence.
Validation asks whether the model represents the physical system adequately, typically through comparison with experiments or trusted reference data.
A mesh-independent result can still be physically inaccurate because of turbulence modelling, boundary conditions, geometry, or omitted physics.
These are separate questions and should be addressed separately.
13. A Simple C++ Mesh-Quality Example
The following standalone example illustrates how cell-centre connectivity can be used to estimate a basic internal-face non-orthogonality metric.
It is an educational demonstration, not a replacement for OpenFOAM’s checkMesh. It assumes that face areas, cell centres, and connectivity have already been computed correctly.
13.1 Mathematical definition
For neighbouring cell centres and ,
Let be the face-area vector oriented consistently with the connection from to .
The angle is
The implementation must clamp the cosine to the interval to protect against floating-point roundoff.
13.2 C++ implementation
#include <algorithm>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <vector>
struct Vec3
{
double x, y, z;
Vec3 operator-(const Vec3& b) const
{
return {x - b.x, y - b.y, z - b.z};
}
double dot(const Vec3& b) const
{
return x*b.x + y*b.y + z*b.z;
}
double magnitude() const
{
return std::sqrt(dot(*this));
}
};
double nonOrthogonalityDegrees(
const Vec3& cellP,
const Vec3& cellN,
const Vec3& faceArea
)
{
const Vec3 d = cellN - cellP;
const double dMag = d.magnitude();
const double sMag = faceArea.magnitude();
if (dMag <= 0.0 || sMag <= 0.0)
{
throw std::runtime_error(
"Invalid cell-centre distance or face area"
);
}
double cosine = d.dot(faceArea) / (dMag * sMag);
cosine = std::clamp(cosine, -1.0, 1.0);
const double radians = std::acos(cosine);
return radians * 180.0 / std::acos(-1.0);
}
int main()
{
const Vec3 cellP{0.0, 0.0, 0.0};
const Vec3 cellN{1.0, 0.1, 0.0};
// Face area vector points in the positive x direction.
const Vec3 faceArea{1.0, 0.0, 0.0};
const double angle =
nonOrthogonalityDegrees(cellP, cellN, faceArea);
std::cout
<< "Non-orthogonality: "
<< angle
<< " degrees\n";
return 0;
}
Compile using a C++17-compatible compiler:
g++ -std=c++17 mesh_quality.cpp -o mesh_quality
./mesh_quality
For the illustrative coordinates, the calculated angle is approximately .
13.3 Limitations of the example
This simplified calculation does not reproduce every detail of OpenFOAM’s mesh-quality algorithms.
A production implementation must account for:
- Consistent face-area orientation.
- Boundary-face treatment.
- Degenerate and invalid cells.
- Mesh topology.
- The precise quality definitions used by the target solver.
- Numerical robustness and geometric tolerances.
The example is intended to demonstrate the geometric mathematics behind one quality metric.
14. Engineering Best Practices
Before meshing
- Define the engineering quantities of interest.
- Identify relevant physical length scales.
- Select a suitable mesh topology.
- Repair geometry and verify boundary patches.
- Estimate near-wall resolution from the intended turbulence treatment.
- Identify important gaps, wakes, interfaces, and gradients.
During meshing
- Begin with a suitable background mesh.
- Apply local refinement based on physical relevance.
- Preserve important geometric features.
- Design boundary layers using first-layer height, growth ratio, and total thickness together.
- Monitor mesh-quality failures at each stage.
- Investigate repeated snapping or layer-addition problems.
- Record significant changes to meshing parameters.
After meshing
- Run
checkMeshwith appropriate geometry and topology checks. - Inspect the distribution of quality metrics.
- Verify cell volumes and boundary-patch assignments.
- Check boundary-layer coverage and wall resolution.
- Inspect fluid-solid interfaces in conjugate heat-transfer cases.
- Monitor solver residuals, conservation balances, and engineering outputs.
- Perform mesh-refinement studies.
- Validate against suitable reference data when available.
- Document the limitations of the mesh.
15. Key Lessons
-
Meshing is part of the numerical model. It defines the spatial representation used by the solver.
-
Resolution should follow the physics. Boundary layers, shear layers, wakes, interfaces, and narrow gaps often require targeted refinement.
-
Mesh quality and mesh resolution are different. A well-shaped mesh can still be too coarse, and a fine mesh can still contain unacceptable distortions.
-
Near-wall resolution depends on the physical model. The first-cell height and layer arrangement should match the intended turbulence and wall treatment.
-
Quality thresholds are not accuracy guarantees. Passing
checkMeshdoes not establish mesh independence. -
Local refinement can be more efficient than global refinement. Additional cells should be justified by their contribution to the quantities of interest.
-
Verification and validation answer different questions. Numerical convergence does not prove physical accuracy.
-
Reproducibility matters. Geometry, dictionaries, software versions, diagnostic outputs, and convergence evidence should be retained.
16. Limitations and Further Reading
The recommendations in this module are general principles rather than a universal meshing prescription. Suitable cell sizes, quality limits, boundary-layer parameters, and refinement strategies depend on the geometry, governing physics, numerical method, solver, and required engineering accuracy.
The OpenFOAM configuration presented here illustrates selected mesh-quality controls. It is not a complete meshing setup, and its values should be verified against the documentation for the installed distribution and version.
References
- OpenCFD Ltd., snappyHexMesh documentation.
- OpenCFD Ltd., Mesh-quality controls.
- OpenCFD Ltd., OpenFOAM User Guide.
- J. H. Ferziger, M. Perić, and R. L. Street, Computational Methods for Fluid Dynamics, Springer.
- P. J. Roache, Verification and Validation in Computational Science and Engineering, Hermosa Publishers.
- I. B. Celik et al., “Procedure for Estimation and Reporting of Uncertainty Due to Discretization in CFD Applications,” Journal of Fluids Engineering, 130(7), 078001, 2008. DOI: 10.1115/1.2960953.