tycho_geometry

    Tycho Geometry — zero-dependency pure-MoonBit mesh data, parametric primitive generators, and geometry-only format IO (OBJ)

    geometry
    mesh
    primitives
    obj
    tycho
    Download zip
    Version
    0.11.0
    License
    Apache-2.0
    Last updated
    3 days ago
    Downloads
    38

    #laplaceliu/tycho_geometry

    Zero-dependency pure-MoonBit mesh data, parametric primitive generators, and geometry-only format IO, built on laplaceliu/tycho_math and nothing else.

    This module is the CPU content layer of the Tycho graphics stack (see ADR-003):

    • No GPU / RHI dependency — compiles on native, wasm, and js, and all tests run headless.
    • Mesh data — MeshData with a fixed canonical layout: positions, normals, uvs, indices, plus optional tangents / vertex colors, skinning and multi-material groups. The fields are private; read them with positions() / normals() / uvs() / indices() / tangents() / colors() / skin_joints() / skin_weights() / morph_targets() / groups(), and replace the length-coupled arrays through the validated setters set_normals / set_tangents / set_colors / add_group, which reject anything that breaks the vertex-count or index-range invariant.
    • Line data — LineData for segment lists (positions + paired indices), plus edges (boundary + crease edges by dihedral angle, like EdgesGeometry) and wireframe (every unique triangle edge).
    • Generators — box, plane, circle, ring, sphere, cylinder, cone, capsule, torus, torus_knot, the polyhedron family (polyhedron + tetrahedron / octahedron / dodecahedron / icosahedron, with detail subdivision), lathe, and tube (a catmull_rom_chain helper turns control points into a tube path). circle / ring accept theta_start / theta_length (sectors) and ring a phi_segments radial split.
    • Shapes — Shape2D (outer contour + holes, polylines only), shape / shapes (flat ear-cut triangulation), and extrude / extrude_shapes (lids + walls, either along depth or along a sampled extrude_path, with an optional three.js-style bevel: bevel_enabled / bevel_thickness / bevel_size / bevel_offset / bevel_segments; opt-in unlike three.js and ignored on path extrusion). The ear-cut kernel is a pure-MoonBit port of mapbox/earcut and lives in earcut.mbt.
    • Operations — bounds, compute_vertex_normals, compute_tangents, transformed, merge, to_non_indexed, flipped; LineData mirrors bounds / transformed / merge / to_non_indexed.
    • Typed errors — GeometryError (InvalidMesh / InvalidGltf / UnsupportedExtension) instead of bare fail(...), so callers can distinguish a bad mesh, a bad document and a document that needs a decoder this build does not ship.
    • IO — parse_obj / parse_obj_text (v/vt/vn, polygons, o/g parts, positive and negative indices), and parse_gltf (glTF 2.0 subset: embedded base64 buffers, POSITION/NORMAL/TEXCOORD_0, sparse accessors, TRS/matrix nodes, PBR factors plus base-colour/normal texture references with embedded data: image URIs decoded to bytes, and node TRS animation channels with LINEAR/STEP/CUBICSPLINE samplers). Compressed assets are rejected instead of silently mis-parsed: any extensionsRequired entry (for example KHR_draco_mesh_compression, EXT_meshopt_compression, KHR_texture_basisu) raises UnsupportedExtension(name), and the same check runs per primitive in case the exporter forgot the top-level declaration. extensionsUsed alone is informational and never blocks loading.

    #Conventions

    • Right-handed, +Y up, -Z forward.
    • CCW is the front face (tycho_3d always sets FrontFace::CounterClockwise).
    • UV (0, 0) is the top-left of the image (glTF / Vulkan convention).
    • Units are meters; default primitive size is 1.
    • MeshData indices are always 32-bit; renderers may narrow to 16-bit on upload.

    #Usage

    let cube = @tgeo.box(width=1.0, height=1.0, depth=1.0)
    let ball = @tgeo.sphere(radius=0.5, width_segments=32, height_segments=16)
    let parts = @tgeo.parse_obj_text(text) // Array[(String, MeshData)]

    // 2D shape -> flat mesh / solid / wireframe
    let square = @tgeo.Shape2D::new([
    @tmath.Vec2::new(-0.5, -0.5), @tmath.Vec2::new(0.5, -0.5),
    @tmath.Vec2::new(0.5, 0.5), @tmath.Vec2::new(-0.5, 0.5),
    ])
    let flat = @tgeo.shape(square)
    let solid = @tgeo.extrude(square, options=@tgeo.ExtrudeOptions::new(depth=0.4))
    let outline = @tgeo.edges(solid) // LineData

    GPU residency (GpuMesh) and everything scene/material-related live in laplaceliu/tycho_3d, not here.

    #Test

    moon test --target native

    GeometryError

    pub suberror GeometryError {
    InvalidMesh(String)
    InvalidGltf(String)
    UnsupportedExtension(String)
    }

    Failures raised by the geometry builders and the glTF parser.

    ExtrudeOptions

    pub(all) struct ExtrudeOptions {
    depth : Float
    steps : Int
    extrude_path : Array[
    Vec3
    ]?
    bevel_enabled : Bool
    bevel_thickness : Float
    bevel_size : Float
    bevel_offset : Float
    bevel_segments : Int
    }

    Extrusion parameters. When extrude_path is set it wins over depth and disables the bevel.

    ExtrudeOptions::new

    fn ExtrudeOptions::new(depth? : Float, steps? : Int, extrude_path? : Array[
    Vec3
    ]?, bevel_enabled? : Bool, bevel_thickness? : Float, bevel_size? : Float, bevel_offset? : Float, bevel_segments? : Int) -> ExtrudeOptions

    GltfAlphaMode

    pub(all) enum GltfAlphaMode {
    Opaque
    Mask(Float)
    Blend
    }

    GltfAnimation

    pub(all) struct GltfAnimation {
    name : String
    channels : Array[GltfAnimationChannel]
    }

    GltfAnimationChannel

    pub(all) struct GltfAnimationChannel {
    node : Int
    path : GltfAnimationPath
    interpolation : GltfAnimationInterpolation
    times : Array[Float]
    values : Array[
    Vec4
    ]
    }

    One resolved animation channel: key times plus values (rotation stores the quaternion in xyzw, translation/scale use xyz).

    GltfAnimationInterpolation

    pub(all) enum GltfAnimationInterpolation {
    Step
    Linear
    CubicSpline
    }

    GltfAnimationPath

    pub(all) enum GltfAnimationPath {
    Translation
    Rotation
    Scale
    }

    GltfMaterial

    pub(all) struct GltfMaterial {
    name : String
    base_color :
    Vec4

    metallic : Float
    roughness : Float
    alpha_mode : GltfAlphaMode
    double_sided : Bool
    base_color_tex : Int
    normal_tex : Int
    }

    GltfNode

    pub(all) struct GltfNode {
    name : String
    mesh : Int
    translation :
    Vec3

    rotation :
    Quat

    scale :
    Vec3

    children : Array[Int]
    }

    GltfScene

    pub(all) struct GltfScene {
    meshes : Array[MeshData]
    materials : Array[GltfMaterial]
    nodes : Array[GltfNode]
    roots : Array[Int]
    textures : Array[GltfTexture]
    images : Array[Bytes]
    animations : Array[GltfAnimation]
    }

    GltfTexture

    pub(all) struct GltfTexture {
    source : Int
    }

    LineData

    pub(all) struct LineData {
    positions : FixedArray[
    Vec3
    ]
    indices : FixedArray[UInt]
    }

    LineData::bounds

    Tight AABB of the positions. Empty line data returns a zero box at the origin, same as MeshData::bounds.

    LineData::empty

    fn LineData::empty() -> LineData

    Empty line list (a useful neutral element for merge).

    LineData::merge

    fn LineData::merge(parts : Array[LineData]) -> LineData

    Concatenate line lists, rebasing indices by each part's vertex offset.

    LineData::new

    fn LineData::new(positions : FixedArray[
    Vec3
    ], indices : FixedArray[UInt]) -> LineData

    LineData::segment_count

    fn LineData::segment_count(self : LineData) -> Int

    LineData::to_non_indexed

    fn LineData::to_non_indexed(self : LineData) -> LineData

    Expand to one vertex pair per segment (indices becomes 0,1,2,3,...).

    LineData::transformed

    Rigid + affine transform of the positions (lines carry no normals).

    LineData::vertex_count

    fn LineData::vertex_count(self : LineData) -> Int

    MeshData

    pub(all) struct MeshData {
    // private fields
    }

    MeshData::add_group

    fn MeshData::add_group(self : MeshData, group : MeshGroup) -> Unit raise GeometryError

    Append a material range, rejecting one that runs past the index buffer.

    MeshData::add_morph_target

    fn MeshData::add_morph_target(self : MeshData, positions : FixedArray[
    Vec3
    ]) -> Unit raise GeometryError

    MeshData::bounds

    Tight AABB of the positions. Empty meshes return a zero box at the origin.

    MeshData::colors

    fn MeshData::colors(self : MeshData) -> FixedArray[
    Vec4
    ]?

    Optional linear-space vertex colours.

    MeshData::compute_tangents

    fn MeshData::compute_tangents(self : MeshData) -> Unit

    Per-vertex tangents (Lengyel's method), orthonormalized against the normals. Requires UVs; degenerate UV triangles are skipped and fall back to any orthonormal vector. w stores the bitangent handedness sign.

    MeshData::compute_vertex_normals

    fn MeshData::compute_vertex_normals(self : MeshData) -> Unit

    Area-weighted smooth vertex normals. Triangles are assumed to be CCW when seen from the front (the package-wide convention), so the un-normalized cross product points outward.

    MeshData::flipped

    fn MeshData::flipped(self : MeshData) -> MeshData

    Reverse triangle winding and flip normals (e.g. to turn an outside-out mesh into an inside-out one). Positions and UVs are shared, not copied.

    MeshData::groups

    fn MeshData::groups(self : MeshData) -> Array[MeshGroup]

    Material ranges inside the index buffer.

    MeshData::has_colors

    fn MeshData::has_colors(self : MeshData) -> Bool

    MeshData::has_morph

    fn MeshData::has_morph(self : MeshData) -> Bool

    MeshData::has_skin

    fn MeshData::has_skin(self : MeshData) -> Bool

    MeshData::has_tangents

    fn MeshData::has_tangents(self : MeshData) -> Bool

    MeshData::index_count

    fn MeshData::index_count(self : MeshData) -> Int

    MeshData::indices

    fn MeshData::indices(self : MeshData) -> FixedArray[UInt]

    32-bit triangle indices.

    MeshData::merge

    fn MeshData::merge(parts : Array[MeshData]) -> MeshData

    Concatenate meshes. Indices and groups are rebased by each part's vertex offset. Optional attributes are kept only when every part provides them.

    MeshData::morph_targets

    fn MeshData::morph_targets(self : MeshData) -> Array[MorphTarget]

    Additive per-vertex position deltas.

    MeshData::new

    fn MeshData::new(positions : FixedArray[
    Vec3
    ], normals : FixedArray[
    Vec3
    ], uvs : FixedArray[
    Vec2
    ], indices : FixedArray[UInt]) -> MeshData

    MeshData::normals

    fn MeshData::normals(self : MeshData) -> FixedArray[
    Vec3
    ]

    Per-vertex normals, always the same length as positions().

    MeshData::positions

    fn MeshData::positions(self : MeshData) -> FixedArray[
    Vec3
    ]

    Per-vertex positions (vertex_count() entries).

    MeshData::set_colors

    fn MeshData::set_colors(self : MeshData, colors : FixedArray[
    Vec4
    ]?) -> Unit raise GeometryError

    Replace the vertex colours, rejecting a length mismatch.

    MeshData::set_normals

    fn MeshData::set_normals(self : MeshData, normals : FixedArray[
    Vec3
    ]) -> Unit raise GeometryError

    Replace the normals, rejecting an array whose length disagrees with the vertex count.

    MeshData::set_skin

    fn MeshData::set_skin(self : MeshData, joints : FixedArray[
    Vec4
    ], weights : FixedArray[
    Vec4
    ]) -> Unit raise GeometryError

    Attach four joint influences per vertex (indices into a skeleton palette).

    MeshData::set_tangents

    fn MeshData::set_tangents(self : MeshData, tangents : FixedArray[
    Vec4
    ]?) -> Unit raise GeometryError

    Replace the tangents, rejecting a length mismatch.

    MeshData::skin_joints

    fn MeshData::skin_joints(self : MeshData) -> FixedArray[
    Vec4
    ]?

    Four joint indices per vertex, when skinned.

    MeshData::skin_weights

    fn MeshData::skin_weights(self : MeshData) -> FixedArray[
    Vec4
    ]?

    Four joint weights per vertex, when skinned.

    MeshData::tangents

    fn MeshData::tangents(self : MeshData) -> FixedArray[
    Vec4
    ]?

    Tangents (w is the bitangent handedness sign), when computed.

    MeshData::to_non_indexed

    fn MeshData::to_non_indexed(self : MeshData) -> MeshData

    Expand into a non-indexed mesh (every three indices become three vertices). Groups stay valid because each index becomes one vertex.

    MeshData::transformed

    Rigid + affine transform. Positions use the full affine; normals use the inverse-transpose (non-uniform scale safe); tangents use the linear part.

    MeshData::triangle_count

    fn MeshData::triangle_count(self : MeshData) -> Int

    MeshData::uvs

    fn MeshData::uvs(self : MeshData) -> FixedArray[
    Vec2
    ]

    Per-vertex texture coordinates.

    MeshData::vertex_count

    fn MeshData::vertex_count(self : MeshData) -> Int

    MeshData::with_groups

    fn MeshData::with_groups(self : MeshData, groups : Array[MeshGroup]) -> MeshData

    MeshGroup

    pub(all) struct MeshGroup {
    start : Int
    count : Int
    material_slot : Int
    }

    One contiguous material range inside the index buffer. material_slot is an application-defined index (three.js geometry.groups).

    MeshGroup::new

    fn MeshGroup::new(start : Int, count : Int, material_slot : Int) -> MeshGroup

    MorphTarget

    pub(all) struct MorphTarget {
    positions : FixedArray[
    Vec3
    ]
    }

    One additive morph target: per-vertex position deltas in mesh-local space.

    Shape2D

    pub(all) struct Shape2D {
    contour : Array[
    Vec2
    ]
    holes : Array[Array[
    Vec2
    ]]
    }

    A planar polygon with holes. The contour is closed implicitly (the last point must not repeat the first).

    Shape2D::is_empty

    fn Shape2D::is_empty(self : Shape2D) -> Bool

    box

    fn box(width? : Float, height? : Float, depth? : Float, width_segments? : Int, height_segments? : Int, depth_segments? : Int) -> MeshData

    Axis-aligned box centered at the origin. Group layout matches three.js BoxGeometry: +X, -X, +Y, -Y, +Z, -Z.

    capsule

    fn capsule(radius? : Float, length? : Float, cap_segments? : Int, radial_segments? : Int) -> MeshData

    Capsule along Y: a cylinder of length plus two hemispherical caps of radius. Normals are analytic (distance to the axis segment).

    catmull_rom_chain

    fn catmull_rom_chain(points : Array[
    Vec3
    ], samples_per_segment? : Int, closed? : Bool) -> Array[
    Vec3
    ]

    Sample a Catmull-Rom spline through points.

    Each input segment contributes samples_per_segment samples (end excluded, plus the final point once), so the result can be fed straight to tube. This is the data-only replacement for three.js CatmullRomCurve3.

    circle

    fn circle(radius? : Float, segments? : Int, theta_start? : Float, theta_length? : Float) -> MeshData

    Disc (or disc sector) in the XY plane facing +Z. The seam vertex is duplicated so UVs stay in [0, 1] without wrapping.

    cone

    fn cone(radius? : Float, height? : Float, radial_segments? : Int, height_segments? : Int, open_ended? : Bool, theta_start? : Float, theta_length? : Float) -> MeshData

    Cone = cylinder with a zero top radius (three.js composition pattern).

    cylinder

    fn cylinder(radius_top? : Float, radius_bottom? : Float, height? : Float, radial_segments? : Int, height_segments? : Int, open_ended? : Bool, theta_start? : Float, theta_length? : Float) -> MeshData

    Capped cylinder (optionally a cone frustum). Groups: 0 = side, 1 = top cap, 2 = bottom cap (three.js layout).

    dodecahedron

    fn dodecahedron(radius? : Float, detail? : Int) -> MeshData

    Regular dodecahedron (pentagonal faces triangulated as in three.js).

    edges

    fn edges(mesh : MeshData, threshold_angle? : Float) -> LineData

    Boundary + crease edges. An edge shared by two triangles is emitted only when the angle between their normals exceeds threshold_angle degrees; edges used by a single triangle (mesh boundaries) are always emitted.

    extrude

    fn extrude(s : Shape2D, options? : ExtrudeOptions) -> MeshData

    Extrude one shape into a closed solid.

    The contour is normalized to CCW and holes to CW, so lids face +Z and side walls face outwards regardless of the caller's ring order. Groups match three.js: 0 = lids, 1 = walls.

    extrude_shapes

    fn extrude_shapes(items : Array[Shape2D], options? : ExtrudeOptions) -> MeshData

    Extrude several shapes into one mesh (three.js ExtrudeGeometry accepts a Shape[] too). Every shape contributes a lid group (material_slot 0) and a wall group (material_slot 1), so one two-material setup covers them all.

    icosahedron

    fn icosahedron(radius? : Float, detail? : Int) -> MeshData

    Regular icosahedron.

    is_clockwise

    fn is_clockwise(points : Array[
    Vec2
    ]) -> Bool

    lathe

    fn lathe(profile : Array[
    Vec2
    ], segments? : Int, phi_start? : Float, phi_length? : Float) -> MeshData

    Surface of revolution around the +Y axis.

    profile is a polyline in the XY plane (x is the radius, y the height); it must be ordered from the bottom of the shape to the top so that triangles come out CCW. Triangles are not capped, matching three.js.

    octahedron

    fn octahedron(radius? : Float, detail? : Int) -> MeshData

    Regular octahedron.

    parse_gltf

    fn parse_gltf(text : String) -> GltfScene raise GeometryError

    Parse a glTF document. Buffers must be base64 data: URIs.

    parse_obj

    fn parse_obj(data : Bytes) -> Array[(String, MeshData)]

    Parse OBJ text (as bytes) into named parts. Parts without vn get area-weighted normals; parts without vt get zero UVs.

    parse_obj_text

    fn parse_obj_text(text : String) -> Array[(String, MeshData)]

    Convenience wrapper for callers that already hold a String.

    plane

    fn plane(width? : Float, height? : Float, width_segments? : Int, height_segments? : Int) -> MeshData

    Plane in the XY plane facing +Z, centered at the origin.

    polygon_area

    fn polygon_area(points : Array[
    Vec2
    ]) -> Float

    Signed shoelace area: positive for counter-clockwise rings.

    polyhedron

    fn polyhedron(vertices : Array[
    Vec3
    ], indices : Array[Int], radius? : Float, detail? : Int) -> MeshData

    Generic polyhedron builder: vertices / indices describe the base solid, detail subdivides every face, and all vertices are projected onto the sphere of radius.

    ring

    fn ring(inner? : Float, outer? : Float, theta_segments? : Int, phi_segments? : Int, theta_start? : Float, theta_length? : Float) -> MeshData

    Flat annulus (or annulus sector) in the XY plane facing +Z. phi_segments subdivides radially between inner and outer.

    shape

    fn shape(s : Shape2D) -> MeshData

    Flat triangulation of one shape in the XY plane, facing +Z.

    shapes

    fn shapes(items : Array[Shape2D]) -> MeshData

    Triangulate several shapes into one mesh; each shape becomes one group (material_slot = its index), matching three.js ShapeGeometry.

    sphere

    fn sphere(radius? : Float, width_segments? : Int, height_segments? : Int, phi_start? : Float, phi_length? : Float, theta_start? : Float, theta_length? : Float) -> MeshData

    UV sphere. Poles are at ±Y. phi_* sweeps around Y, theta_* from the north pole downwards (three.js convention).

    tetrahedron

    fn tetrahedron(radius? : Float, detail? : Int) -> MeshData

    Regular tetrahedron (detail > 0 rounds it into a subdivided sphere).

    torus

    fn torus(radius? : Float, tube? : Float, radial_segments? : Int, tubular_segments? : Int, arc? : Float) -> MeshData

    Torus in the XY plane (hole axis = +Z), matching three.js TorusGeometry.

    torus_knot

    fn torus_knot(radius? : Float, tube? : Float, tubular_segments? : Int, radial_segments? : Int, p? : Int, q? : Int) -> MeshData

    (p, q) torus knot: the tube sweeps a curve that winds p times around the knot axis and q times around the torus interior. p and q must be coprime for a single knot (otherwise the result is a torus link).

    triangulate

    Triangulate contour minus holes, returning triangle indices into the concatenated contour ++ holes... vertex array.

    Output triangles are CCW when the contour is CCW (and holes CW); callers that need a fixed orientation should normalize the rings first (Shape2D helpers do).

    tube

    fn tube(path : Array[
    Vec3
    ], tubular_segments? : Int, radius? : Float, radial_segments? : Int, closed? : Bool) -> MeshData

    Tube swept along path (a polyline sampled in 3D). The path is resampled to tubular_segments + 1 rows evenly spaced by arc length, and the cross-section frames are parallel-transported to avoid twisting.

    wireframe

    fn wireframe(mesh : MeshData) -> LineData

    Every unique triangle edge, i.e. the full wireframe of the mesh.