Sign in

    moon-geometry

    Pure MoonBit computational geometry library: convex hull, Delaunay, Voronoi, polygon boolean ops, transforms, Minkowski

    computational-geometry
    convex-hull
    delaunay
    voronoi
    polygon
    Download zip
    Author
    Version
    0.251.0
    License
    MIT
    Last updated
    1 hour ago
    Downloads
    24

    No dependencies

    #Moon Geometry

    纯 MoonBit 计算几何库 | 2026 MoonBit 十月赛参赛项目 Pure MoonBit computational geometry library | 2026 MoonBit October Hackathon entry

    License: MIT MoonBit Tests Targets

    Moon Geometry 是一个纯 MoonBit 实现的计算几何库,零 C FFI 依赖,四目标(native / wasm-gc / js / wasm)原生支持。为 CAD、碰撞检测、GIS、路径规划、图像处理等场景提供可复用的几何算法基础组件。

    Moon Geometry is a pure MoonBit computational geometry library with zero C FFI dependencies, supporting all four backends natively. It provides reusable geometric algorithm primitives for CAD, collision detection, GIS, path planning, and image processing.

    #特性 | Features

    • 基础几何类型 | Basic types: Point2D / Point3D / Segment / Line / Polygon / Triangle / Circle / Rectangle
    • 凸包 | Convex hull: Graham scan, Andrew's monotone chain (O(n log n)) | Graham 扫描法、Andrew 单调链法
    • 多边形操作 | Polygon ops: area (Shoelace), perimeter, centroid, point-in-polygon, convexity, orientation, Douglas-Peucker | 面积、周长、质心、点在多边形内、凸性判断、方向判定、Douglas-Peucker 简化
    • Delaunay 三角剖分 | Delaunay triangulation: Bowyer-Watson incremental insertion (O(n²) expected) | Bowyer-Watson 增量插入法
    • Voronoi 图 | Voronoi diagram: Delaunay duality, circumcenters as vertices | Delaunay 对偶,外心为顶点
    • 几何变换 | Transforms: translate, rotate, scale, affine, mirror, shear | 平移、旋转、缩放、仿射、镜像、剪切
    • 距离计算 | Distance: point-to-segment/polygon, segment-to-segment, polygon-to-polygon | 点到线段/多边形、线段间、多边形间
    • 包围体 | Bounding: AABB, min-area bounding rect (rotating calipers), bounding circle | 轴对齐包围盒、最小面积包围矩形、包围圆
    • 圆相交 | Circle intersection: circle-segment, circle-circle, circle-line, circle-polygon | 圆与线段/圆/直线/多边形相交
    • 多边形三角剖分 | Polygon triangulation: ear clipping for simple polygons | ear clipping 简单多边形三角剖分
    • Minkowski 运算 | Minkowski ops: sum/difference of convex polygons, collision detection | 凸多边形 Minkowski 和/差、碰撞检测
    • 旋转卡壳 | Rotating calipers: convex polygon diameter, width, farthest pair, min-perimeter rect | 凸多边形直径、宽度、最远点对、最小周长矩形
    • 椭圆几何 | Ellipse: area, perimeter, eccentricity, foci, contains, line intersection | 面积、周长、离心率、焦点、包含、直线相交
    • 贝塞尔曲线 | Bezier: quadratic/cubic eval, derivative, length, bbox, subdivide | 二次/三次求值、导数、弧长、包围盒、细分
    • 几何拟合 | Fitting: least-squares line/circle fit, orthogonal regression, centroid | 最小二乘直线/圆拟合、正交回归、质心
    • 扫描线 | Sweep line: segment intersection detection, simple polygon test | 线段相交检测、简单多边形检测
    • 凸多边形操作 | Convex polygon: O(log n) point query, tangent, SAT intersect, support function | O(log n) 点查询、切线、SAT 相交、支持函数
    • 统一导入 | Unified import: import "walkzzz/moon-geometry" re-exports all APIs | 单包导入重导出全部 API
    • 纯 MoonBit 零依赖 | Pure MoonBit, zero deps: no C FFI, single codebase for all targets | 无 C FFI,四目标共用代码库
    • 退化情况全覆盖 | Full degenerate coverage: collinear, coincident, empty, single/two-point | 共线点、重合点、空输入、单点/两点退化
    • 统一公差体系 | Tolerance system: configurable ToleranceCtx for distance/angle/area, default/strict/loose presets | 可配置 ToleranceCtx 公差上下文,预设 default/strict/loose
    • 退化构型鲁棒性 | Degenerate robustness: detect collinear/overlap/zero-area/self-intersect/small-angle, remove coincident points | 检测共线/重叠/零面积/自交/极小角度,移除重合点
    • 拓扑一致性验证 | Topology validation: closed manifold check, non-manifold edges, dangling edges, isolated vertices, normal consistency | 闭合流形检测、非流形边、悬挂边、孤立顶点、法向一致性
    • 增量计算 | Incremental computation: incremental Delaunay with dynamic insert/remove, supports interactive editing | 增量 Delaunay 动态插入/删除,支持交互式编辑

    #安装 | Installation

    moon add walkzzz/moon-geometry

    #项目结构 | Project Structure

    283 个模块按 10 个领域分类组织 | 283 modules organized into 10 domain categories:

    base/ # (32) Core types & robust arithmetic | 基础类型与鲁棒算术 geometry/ # (65) Convex hull, polygon, triangulation, computational geometry | 凸包、多边形、三角剖分、计算几何 transform/ # (19) Geometric transforms & differential geometry | 几何变换与微分几何 spatial/ # (30) Spatial data structures & distance metrics | 空间数据结构与距离度量 curves/ # (27) Curves, splines & algebraic geometry | 曲线、样条与代数几何 mesh/ # (27) Mesh processing & topological data analysis | 网格处理与拓扑数据分析 numerics/ # (24) Numerical optimization & PDE solvers | 数值优化与偏微分方程求解 applied/ # (29) Robotics, ML, point cloud & statistics | 机器人、机器学习、点云与统计 io/ # (18) File I/O & graphics rendering | 文件输入输出与图形渲染 testing/ # (12) Testing infrastructure & utilities | 测试基础设施与工具

    #快速示例 | Quick Example

    // 1. 凸包计算 | Convex hull
    let points = [
    @moon_geometry.Point2D::new(0.0, 0.0),
    @moon_geometry.Point2D::new(4.0, 0.0),
    @moon_geometry.Point2D::new(4.0, 4.0),
    @moon_geometry.Point2D::new(0.0, 4.0),
    @moon_geometry.Point2D::new(2.0, 2.0), // 内部点 | interior point
    ]
    let hull = @moon_geometry.convex_hull_andrew(points) // 凸包顶点(逆时针)

    // 2. 多边形面积 | Polygon area
    let polygon = [
    @moon_geometry.Point2D::new(0.0, 0.0),
    @moon_geometry.Point2D::new(4.0, 0.0),
    @moon_geometry.Point2D::new(4.0, 4.0),
    @moon_geometry.Point2D::new(0.0, 4.0),
    ]
    let area = @moon_geometry.polygon_area(polygon) // 16.0

    // 3. Delaunay 三角剖分 | Delaunay triangulation
    let tri = @moon_geometry.delaunay_triangulation(points)

    // 4. 几何变换 | Transform
    let affine = @moon_geometry.Affine2::new(
    1.0, 0.0, 0.0, // a, b, c
    0.0, 1.0, 0.0, // d, e, f
    )
    let transformed = affine.apply(@moon_geometry.Point2D::new(1.0, 1.0))

    // 5. 距离计算 | Distance
    let dist = @moon_geometry.Point2D::new(0.0, 0.0).dist(
    @moon_geometry.Point2D::new(3.0, 4.0)
    ) // 5.0

    // 6. 点在多边形内 | Point in polygon
    let inside = @moon_geometry.point_in_polygon(
    @moon_geometry.Point2D::new(2.0, 2.0),
    polygon
    ) // true

    // 7. Trait 多态 | Trait polymorphism (Measurable)
    let circle = @moon_geometry.Circle::new(
    @moon_geometry.Point2D::new(0.0, 0.0),
    5.0
    )
    let circle_area = circle.area() // 78.54...

    // 8. 形式化验证 | Proof-carrying code
    // dist 函数带有非负性契约: proof_ensure: result => result >= 0.0

    #API 概览 | API Overview

    模块Module主要 APIKey APIs
    点PointsPoint2D::new/dist/dot/cross/add/sub/mulPoint3D 同构
    线段/直线Segment/LineSegment::length/midpointLine::from_points/point_distance
    多边形Polygonpolygon_area/perimeter/centroidis_convex, point_in_polygon, simplify_polygon
    凸包Convex hullconvex_hull_andrew, convex_hull_grahamccw
    相交Intersectionsegments_intersect, segment_intersectionline_segment_intersection
    最近点对Closest pairclosest_pair分治 O(n log n)
    布尔运算Boolean opsclip_polygon, polygon_intersectionpolygon_union_area, polygon_difference_area
    三角剖分Triangulationdelaunay_triangulationvoronoi_diagram
    变换Transformtranslate, rotate, scaleaffine_transform, mirror_line, shear
    距离Distancepoint_to_segment_distance, polygon_to_polygon_distancesegment_to_segment_distance
    包围体Boundingaabb, aabb_polygonmin_area_bounding_rect, bounding_circle
    圆相交Circle opscircle_segment_intersect, circle_circle_intersectcircle_line_intersect, circle_polygon_intersect
    三角剖分Triangulatetriangulate_polygonear clipping
    MinkowskiMinkowskiminkowski_sum_convex, minkowski_difference_convexconvex_polygons_collide
    旋转卡壳Rotating calipersconvex_polygon_diameter, convex_polygon_widthfarthest_point_pair
    椭圆Ellipseellipse_new, ellipse_area, ellipse_perimeterellipse_contains, ellipse_foci
    贝塞尔Bezierbezier2_new, bezier2_eval, bezier3_newbezier2_length, bezier3_subdivide
    拟合Fittingfit_line, fit_circle, fit_line_orthogonalcentroid
    扫描线Sweep linehas_any_intersection, count_intersectionsis_simple_polygon_chain
    凸多边形Convex polygonpoint_in_convex_polygon, convex_polygons_intersecttangent_from_point, support_function
    向量Vectorvec_normalize, vec_reflect, vec_projectvec_lerp, vec_perp, vec_angle_between
    矩阵Matrixmat2_new, mat2_det, mat2_mul, mat2_inversemat2_rotation, mat2_scaling, mat2_trace
    角度Angledeg_to_rad, rad_to_deg, normalize_anglenormalize_angle_signed, angle_diff, angle_bisector
    常数Constantspi, two_pi, half_pi, euler_esqrt2, sqrt3, golden_ratio, geom_eps
    区间Intervalinterval_new, interval_contains, interval_intersectinterval_union, interval_overlaps, interval_length
    AABB树AABB treebuild_aabb_tree, query_aabb, query_point_aabbcount_leaves
    哈希Hashcell_index, cell_hash, segment_hashcell_index_3d, hash_combine
    比较Comparerobust_orientation, robust_left_turn, compare_pointsrobust_collinear, points_equal
    射线Rayray_new, ray_segment_intersect, ray_polygon_containsray_line_intersect, ray_polygon_intersect
    平面Planeplane_from_normal_point, plane_distance, plane_projectplane_from_three_points, plane_line_intersect
    K-d树K-d treebuild_kdtree, kdtree_nearest, kdtree_range_query最近邻搜索
    四叉树Quadtreebuild_quadtree, quadtree_range_queryquadtree_count
    网格索引Grid indexbuild_grid_index, grid_query_radius, grid_query_rectgrid_query_cell, grid_size
    范围树Range treebuild_range_tree, range_queryrange_query_x, range_query_y
    有序搜索Sort searchbinary_search, lower_bound, upper_boundunique_sorted, kth_element, merge_sorted
    桶PR树Bucket PRbuild_bucket_pr, bucket_pr_nearestbucket_pr_count
    空间哈希Spatial hashbuild_spatial_hash, spatial_hash_query_radiusspatial_hash_nearby, spatial_hash_size
    层次包围体BVHbuild_bvh, bvh_query, bvh_query_pointbvh_count_leaves
    半平面Half-planeHalfPlane, half_plane_contains, half_plane_intersecthalf_plane_eval
    凸裁剪Convex clipclip_convex_by_line, clip_convex_by_half_planeconvex_area
    点集运算Convex sumpoint_set_sum, point_set_difference, point_set_scalepoint_set_centroid, point_set_equal
    极对偶Polar dualpolar_dual_point, polar_dualorigin_inside, dual_area
    线性规划Linear progLPResult, linear_program_2d, is_feasiblefind_feasible_point
    三维凸包3D convex hullHullFace, convex_hull_3d, hull_face_counthull_volume
    支持函数Supportsupport_point_set, support_circle, support_valuesupport_segment, width_in_direction
    分离轴Separatingfind_separating_axis, separating_distanceare_separated
    多边形偏移Polygon offsetpolygon_offset_outward, polygon_offset_inwardpolygon_offset_area, polygon_offset_valid
    带孔多边形Polygon holesPolygonWithHoles, polygon_with_holes_areapolygon_with_holes_contains, polygon_with_holes_perimeter
    可见性Visibilityis_visible, visibility_polygonvisibility_polygon_convex, visible_vertex_count
    美术馆Art galleryart_gallery_guard_count, art_gallery_place_guardsart_gallery_covers_vertices, art_gallery_estimate
    多边形核Polygon kernelpolygon_kernel, is_star_shapedpolygon_kernel_area, kernel_point
    凸分解Convex decompconvex_decomposition, convex_decomp_countconvex_decomp_lower_bound, convex_decomp_area
    多边形对称Polygon symmetryhas_reflection_symmetry, has_rotation_symmetrypolygon_symmetry_order, has_any_symmetry
    多边形覆盖Polygon covercover_by_rectangles, cover_by_trianglescover_area_rectangles, cover_area_triangles
    耳裁剪Ear clipis_ear, find_ear, ear_clip_triangulateear_clip_count, ear_clip_area
    单调剖分Monotoneis_y_monotone, is_x_monotonetriangulate_monotone, monotone_triangulate_count
    Catmull-RomCatmull-Romcatmull_rom_eval, catmull_rom_pointscatmull_rom_derivative
    HermiteHermitehermite_eval, hermite_pointshermite_derivative, cardinal_tangents
    B样条B-splinebspline_basis, bspline_eval, bspline_pointsuniform_knots
    LagrangeLagrangelagrange_eval, lagrange_basislagrange_interpolate, lagrange_nodes_distinct
    样条工具Splinespline_length, spline_curvaturespline_curvature_profile, spline_total_curvature
    弧长Curve arcarc_length, arc_length_atarc_length_parametrize, arc_length_to_param
    曲线相交Curve intersectsegments_cross, curve_self_intersectcurve_self_intersect_count, curves_intersect
    折线Polylinepolyline_length, polyline_simplifypolyline_subdivide, polyline_segment_count
    弧长工具Arc lengtharc_length_segment, arc_length_totalarc_length_cumulative, arc_length_average
    曲率Curvaturecurvature_at, curvature_signedcurvature_profile, curvature_radius

    完整接口见 moon info 生成的 .mbti 文件。Full interface in .mbti files generated by moon info.

    #测试 | Tests

    moon test # 全部 2307 测试 | all 2307 tests moon test --target native # 四目标分别验证 | verify each backend moon test --target wasm-gc moon test --target js moon test --target wasm

    四目标全绿:2307 × 4 = 9228 次测试通过。 All four targets pass: 2307 × 4 = 9228 test runs green.

    #使用场景 | Use Cases

    场景Scenario推荐模块Recommended modules
    CAD/几何建模CAD/Geometry modelingbase/core, geometry/hull, geometry/polygon, curves/bezier, transform/affine2
    碰撞检测Collision detectionapplied/collision_detect, applied/gjk, applied/sat, geometry/minkowski
    路径规划Path planningapplied/rrt, applied/prm, applied/a_star, applied/shortest_path
    GIS/地理信息GIS/Geospatialtesting/gis_projection, testing/gis_buffer, io/geojson_io, applied/tin
    网格处理Mesh processingmesh/mesh_data, mesh/mesh_simplify, mesh/mesh_smooth, mesh/marching_cubes
    数据可视化Data visualizationio/svg_out, io/rasterization, io/ray_tracing
    机器学习Machine learningapplied/clustering, applied/icp, applied/shape_matching
    数值优化Numerical optimizationnumerics/gradient_descent, numerics/newton_method, numerics/levenberg_marquardt
    拓扑分析Topological analysismesh/persistent_homology, mesh/alpha_complex, mesh/reeb_graph
    鲁棒计算Robust computationbase/robust_arith, base/exact_predicates, base/adaptive_pred

    #Trait 系统 | Trait System

    库提供 12 个 pub(open) trait,支持跨包多态调度:

    Trait方法实现类型
    PointTransformapply, apply_batchAffine2, Rigid, Similarity
    Curve2Deval, derivative, lengthBezier2, Bezier3
    MeasurableareaCircle, Rectangle, Triangle, Ellipse
    PerimeterMeasurableperimeterCircle, Rectangle, Ellipse
    ContainablecontainsCircle, Rectangle, Ellipse
    Measurable3Dvolume, surface_areaAABB3D, BoundingSphere, OBB, Polyhedron
    ComposablecomposeAffine2, Rigid, Similarity, Homography
    VertexCountablevertex_countDCEL, Delaunay3D, PlanarGraph, Mesh, Polyhedron, ...
    FaceCountableface_countDCEL, PlanarGraph, DynamicHull3D, Mesh, Polyhedron, ...
    EdgeCountableedge_countDCEL, PlanarGraph, Mesh, Polyhedron, ReebGraph
    Bounded2DbboxBezier2, Bezier3
    SubdivisiblesubdivideBezier2, Bezier3

    #形式化验证 | Formal Verification

    核心函数带有 proof_ensure 契约,确保数学性质正确:

    函数契约性质
    Point2D::distresult >= 0.0距离非负性
    Point2D::dist_sqresult >= 0.0距离平方非负性
    Point2D::dotresult == other.x * self.x + other.y * self.y点积对称性
    Point2D::crossresult == -(other.x * self.y - other.y * self.x)叉积反对称性
    turnresult == -(...)叉积反对称性
    approx_eqresult == ((b - a).abs() <= eps)近似比较对称性
    polyline_lengthresult >= 0.0折线长度非负性
    min_dist_to_setresult >= 0.0最小距离非负性

    #交付路线图 | Roadmap

    阶段Phase内容Content状态Status
    Week 1Week 1基础类型 + 凸包 + 多边形操作Basic types + hull + polygon ops✅ 完成✅ Done
    Week 2Week 2线段相交 + 最近点对 + 布尔运算Intersection + closest pair + boolean✅ 完成✅ Done
    Week 3Week 3Delaunay 三角剖分 + Voronoi 图Delaunay + Voronoi✅ 完成✅ Done
    Week 4Week 4变换 + 距离 + 包围盒 + 发布Transform + distance + bounding + publish✅ 完成✅ Done
    Phase 1-2Phase 1-2测试补充 + 圆相交 + 三角剖分 + MinkowskiTests + circle ops + triangulate + Minkowski✅ 完成✅ Done
    v0.6.0v0.6.0旋转卡壳 + 椭圆 + 贝塞尔曲线Rotating calipers + ellipse + bezier✅ 完成✅ Done
    v0.7.0v0.7.0拟合 + 扫描线 + 凸多边形操作Fitting + sweep line + convex polygon✅ 完成✅ Done
    v0.8.0v0.8.0向量 + 矩阵 + 角度 + 常数 + 区间Vector + matrix + angle + constants + interval✅ 完成✅ Done
    v0.9.0v0.9.0AABB树 + 哈希 + 比较 + 射线 + 平面AABB tree + hash + compare + ray + plane✅ 完成✅ Done
    v1.0.0v1.0.0空间数据结构(8模块)Spatial data structures (8 modules)✅ 完成✅ Done
    v1.1.0v1.1.0凸性与优化(8模块)Convexity & optimization (8 modules)✅ 完成✅ Done
    v1.2.0v1.2.0多边形算法(10模块)Polygon algorithms (10 modules)✅ 完成✅ Done
    v1.3.0v1.3.0曲线与样条(10模块)Curves & splines (10 modules)✅ 完成✅ Done
    v1.4.0v1.4.0距离度量(8模块)Distance metrics (8 modules)✅ 完成✅ Done
    v1.5.0v1.5.0平面细分(8模块)Planar subdivision (8 modules)✅ 完成✅ Done
    v1.6.0v1.6.0几何变换(8模块)Geometric transforms (8 modules)✅ 完成✅ Done
    v1.7.0v1.7.0网格处理(6模块)Mesh processing (6 modules)✅ 完成✅ Done
    v2.0.0v2.0.0优化与输出(5模块)Optimization & output (5 modules)✅ 完成✅ Done
    v0.108.0v0.108.0高级凸几何(8模块)Advanced convex geometry (8 modules)✅ 完成✅ Done
    v0.116.0v0.116.0高级多边形(8模块)Advanced polygon algorithms (8 modules)✅ 完成✅ Done
    v0.124.0v0.124.0高级空间结构(8模块)Advanced spatial structures (8 modules)✅ 完成✅ Done
    v0.132.0v0.132.0高级图算法(8模块)Advanced graph algorithms (8 modules)✅ 完成✅ Done
    v0.140.0v0.140.0数值计算(8模块)Numerical computation (8 modules)✅ 完成✅ Done
    v0.156.0v0.156.0曲面(8模块)Surface modules (8 modules)✅ 完成✅ Done
    v0.156.0v0.156.0应用算法(8模块)Application algorithms (8 modules)✅ 完成✅ Done
    v0.160.0v0.160.03D几何与多面体(10模块)3D geometry & polyhedra (10 modules)✅ 完成✅ Done
    v0.230.0v0.230.0扩展模块(70模块)Extension modules (70 modules)✅ 完成✅ Done
    v0.231.0v0.231.0计算代数几何(10模块)Computational algebraic geometry (10 modules)✅ 完成✅ Done
    v0.232.0v0.232.0微分几何与离散曲面(10模块)Differential geometry & discrete surfaces (10 modules)✅ 完成✅ Done
    v0.233.0v0.233.0持久拓扑与高级数值(20模块)Persistent topology & advanced numerics (20 modules)✅ 完成✅ Done
    v0.234.0v0.234.0ML几何+机器人+图形+PDE(40模块)ML geometry + robotics + graphics + PDE (40 modules)✅ 完成✅ Done
    v0.235.0v0.235.0代数结构+鲁棒几何+优化+应用(40模块)Algebra structures + robust geometry + optimization + applications (40 modules)✅ 完成✅ Done
    v0.236.0v0.236.0形式化验证+MOCK/FAKE+E2E+AI属性测试(5模块)Formal verification + MOCK/FAKE + E2E + AI property tests (5 modules)✅ 完成✅ Done
    v0.237.0v0.237.0Trait 去重(PointTransform trait, cross/approx_eq/map_points 统一)Trait-based deduplication✅ 完成✅ Done
    v0.238.0v0.238.0目录重构(401模块→24分类子目录)Directory restructuring (401 modules → 24 categories)✅ 完成✅ Done
    v0.239.0v0.239.0Warning 治理(204→0)Warning governance (204→0)✅ 完成✅ Done
    v0.240.0v0.240.0Curve2D trait + 代码去重Curve2D trait + code dedup✅ 完成✅ Done
    v0.245.0v0.245.0项目瘦身(401→283 模块)Project slimming (401→283)✅ 完成✅ Done
    v0.249.0v0.249.010 分类合并 + CRAP 优化 + 形式化验证10-category merge + CRAP optimization + proof✅ 完成✅ Done

    #设计参考 | Design References

    • CGAL — 算法参考 | algorithm reference
    • Shapely — API 设计参考 | API design reference
    • scipy.spatial — Delaunay/Voronoi 对照验证 | validation

    本项目为原创实现,使用 Double 浮点运算,以 MoonBit 原生类型系统组织几何类型。 Original implementation using Double floating-point arithmetic, organized with MoonBit's native type system.

    #许可证 | License

    ⚠️ Package is too large to be displayed

    This package contains over 1628 items.

    Source Files