tycho

    Tycho RHI — unified pure-MoonBit render hardware interface: Vulkan 1.3, Direct3D 12, Metal, and WebGPU (native + browser) drivers behind one virtual ABI

    graphics
    rhi
    vulkan
    dx12
    metal
    webgpu
    gpu
    tycho
    Download zip
    Version
    0.12.2
    License
    Apache-2.0
    Last updated
    16 minutes ago
    Downloads
    103

    #laplaceliu/tycho

    Unified pure-MoonBit Render Hardware Interface (RHI) built atop laplaceliu/tycho_vulkan, laplaceliu/tycho_dx12, laplaceliu/tycho_metal, laplaceliu/tycho_webgpu, laplaceliu/tycho_window, and laplaceliu/tycho_shader with zero C stubs in the RHI.

    #Install

    moon add laplaceliu/tycho

    No cc-link-flags are required. laplaceliu/tycho_vulkan, laplaceliu/tycho_metal, and laplaceliu/tycho_window resolve the Vulkan loader (libvulkan.so.1 / vulkan-1.dll / libvulkan.1.dylib / libMoltenVK.dylib), Apple Metal (Metal.framework + QuartzCore.framework), and the OS windowing libraries (libwayland-client, libX11, user32, AppKit + QuartzCore) at runtime through dlopen / LoadLibraryA, so downstream moon.pkg files only need the imports.

    Requirements: on Vulkan, a 1.3 loader + driver (dynamicRendering + synchronization2, or 1.1/1.2 KHR fallbacks); on macOS Metal (BackendKind::Metal), built-in Metal.framework + QuartzCore.framework; on Windows DX12 (BackendKind::Dx12), built-in d3d12.dll + dxgi.dll. No Vulkan SDK, -I, VULKAN_SDK, or -lvulkan / -lX11 / -framework dev package is needed at build time; the runtime libraries only have to be present at runtime.

    #Features (Vulkan 1.3 Backend)

    • Backend-opaque handles: Device, Swapchain, Pipeline, Buffer, Texture, Sampler, CommandBuffer, Fence, TimestampPool, BindlessHeap, AccelStruct
    • Vulkan 1.3 Dynamic Rendering + Synchronization2, 2 frames-in-flight, X11 + runtime-loaded Wayland swapchains, and automatic recreation on resize / OUT_OF_DATE
    • Pure-MoonBit free-list GPU memory sub-allocator (RegionPool / SubAllocator) with GpuOnly/CpuToGpu/GpuToCpu tiers, deferred deletion queue, and VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT when Ray Query is supported
    • SPIR-V Auto-Reflection: PipelineDesc::from_spirv and Device::create_compute_pipeline_auto derive vertex layouts, descriptor bindings (UBO, texture, SSBO, storage image, OpTypeAccelerationStructureKHR), push constant ranges, and MRT attachment counts directly from SPIR-V bytecode
    • Modern GPU Features: MRT, 4x MSAA Offscreen Resolve, Hardware Mipmap Generation, Compute Storage Images, Indirect / Indirect-Count Draw, Bindless Heap, Mesh Shaders, StencilState + dynamic set_stencil_reference, Inline Ray Query (create_blas / create_tlas / bind_accel_struct), and GPU Timestamp Queries (TimestampPool)
    • Deterministic backend errors: a cross-backend misuse (DX12 resource on a Vulkan command buffer or vice versa, a command the other backend does not implement) is recorded in CommandBuffer::first_error and raised from Device::end_commands / Swapchain::end_frame as RhiError::BackendUnsupported. Recording calls never drop a mistake silently.
    • Grouped pipeline state: PipelineDesc stores its drawing state as raster : RasterState, depth_stencil : DepthStencilState? and color_targets : Array[ColorTargetState] instead of 20 mirror fields, and PipelineDesc::graphics(vert, frag, raster=…, depth_stencil=…, color_targets=…) builds it without 38 flat arguments. PipelineDesc::new(...) keeps the flat keyword signature for existing call sites, raster_state() / depth_stencil_state() / color_target_states() expose views over the same storage, and color_target(i) / effective_blend_mode() give the backends the per-attachment view.
    • Scoped passes and bind groups: CommandBuffer::render_pass(colors, depth?, fn(pass) { … }) and swapchain_pass(sc, load_op?, clear_color?, fn(pass) { … }) close the pass even when the callback raises, so a recording session cannot be left half-open; compute_pass(fn) does the same for dispatch. BindGroup records a descriptor set once (.uniform(…).texture(…).storage(…)) for bind_group(group) to replay per draw. The 3D renderer records its shadow-atlas, main, bloom and tonemap passes this way, and the 2D renderer uses it for every self-contained pass (downsample, blur H/V, MSAA resolve, batched path flush, present).
    • Composable resource descriptors: TextureDesc (width/height/format/usage/dimension/mip_levels/samples) plus TextureUsage and BufferUsage bitflags replace the factory-per-combination API: Device::create_texture_desc and Device::create_buffer_usage express things like a Storage | Indirect draw buffer or a RenderAttachment | Sampled target, while the existing create_texture* / create_buffer* helpers stay as thin wrappers.
    • Wide vertex formats: VertexFormat covers Float1/Float2/Float3/Float4, Int1/Uint1, packed Unorm8x4 and Uint16x4, mapped to the matching VkFormat/DXGI_FORMAT (per-vertex code + byte size live in VertexFormat::code / bytes).
    • Native optional parameters: pipeline/sampler/render-target descriptions use MoonBit optional arguments (depth_format? : TextureFormat, compare_op? : CompareOp, resolve_texture? : Texture, …), so call sites read depth_format=TextureFormat::Depth32F instead of depth_format=Some(TextureFormat::Depth32F), and an existing Option forwards with depth_format?=maybe_depth.

    #Math

    The RHI depends on laplaceliu/tycho_math so the whole stack speaks one math dialect (column-major, GPU-upload ready, explicit clip space). The dependency is used only in the façade, for typed conveniences:

    • RayInstanceDesc::from_affine3(blas, Affine3) — and the identity default of RayInstanceDesc::new — produce the row-major 3x4 TLAS transform via Affine3::to_vk_transform_3x4(), so the VkTransformMatrixKHR layout lives in one place.
    • CommandBuffer::push_constants_mat4(pipe, Mat4).

    The raw APIs stay first-class: Buffer::upload_floats, push_constants_floats / push_constants_bytes still take FixedArray[Float] / Bytes, so you can bypass math entirely, and the Vulkan backend (vk_backend.mbt) never imports @tmath so it remains replaceable. tools/check-gates.py math-layering enforces both directions: tycho_math keeps zero laplaceliu/* dependencies and never references the RHI.

    Every typed helper is a thin wrapper over the raw call (raw stays the primitive), and falls into one of two classes: completeness twins of an existing raw call (upload_mat4, push_constants_mat4, RayInstanceDesc::from_affine3), which are covered by equivalence tests with non-degenerate matrices, and exploratory APIs, which require a real call site before they are added because a test cannot validate an API's shape. See ADR-002 §3.

    AccelStruct

    BindingLayout

    Where a pipeline's shader expects each kind of resource.

    The RHI binds by slot; WGSL binds by number. Until now the two agreed only because a single global formula (textures 0..n, samplers n..2n, push 2n) happened to fit the one converted shader. It does not scale: any shader that occupies a binding of its own -- 2d's blur uses binding 2, prim2d uses 0 and 1 for storage buffers -- collides with it.

    So the layout travels with the pipeline. legacy reproduces the old formula exactly, which is what every SPIR-V pipeline still means.

    BindlessHeap

    Buffer

    BufferUsage

    Composable buffer usage flags. BufferKind remains the shortcut for the common single-purpose cases; this type expresses the combinations GPU-driven pipelines need (Storage | Indirect, Storage | Vertex, ...).

    ColorTargetState

    One colour attachment: format plus its write mask and blend state.

    CommandBuffer

    ComputePass

    CursorMode

    CursorShape

    DepthStencilState

    Depth/stencil state, grouped out of the flat PipelineDesc.

    DepthTargetDesc

    Device

    DeviceCapabilities

    Event

    ExternalSurface

    Host-owned surface handle passed into SwapchainDesc when the OS/app owns window creation (mandatory on iOS/Android, optional on desktop/web). display / handle meanings match ExternalSurfaceKind:
    • Xlib: (Display*, Window)
    • Wayland: (wl_display*, wl_surface*)
    • Win32: (HINSTANCE, HWND)
    • MetalLayer: (0, CAMetalLayer*)
    • AndroidNativeWindow: (0, ANativeWindow*)
    • WebCanvas: (canvas_id, 0)

    ExternalSurfaceKind

    Native surface kind for externally owned surfaces (iOS CAMetalLayer, Android ANativeWindow, embedded desktop windows, or an existing web canvas). Pure L1 data so rhi/types stays independent of plat.

    Fence

    KeyCode

    Logical key identity. The platform layer reports X11 keysyms for historical reasons; from_keysym / to_keysym translate losslessly, and keys the enum does not name are preserved as Unknown(keysym).

    MeshPipelineDesc

    Modifiers

    Keyboard modifiers, decoded from the X11-compatible mask the platform layer reports (Shift=1, Lock=2, Ctrl=4, Mod1/Alt=8, Mod4/Super=64).

    MouseButton

    Pipeline

    PrimitiveTopology

    RasterState

    Rasterisation state, grouped out of the flat PipelineDesc.

    RayGeometryDesc

    RayInstanceDesc

    RenderPass

    RenderTargetDesc

    RhiError

    Sampler

    ShaderLanguage

    The shader blob format a backend can consume (ADR-005 D7).

    The same FixedArray[UInt32] channel carries whichever of these the device wants -- SPIR-V words as-is, WGSL as UTF-8 zero-padded to a 4-byte boundary -- so a pipeline descriptor does not need a dozen shader fields. What the caller must not do is guess: ask the device.

    Dxil exists so that asking has an honest answer before a DX12 backend can build pipelines; a caller that only knows SPIR-V and WGSL must report it as unsupported rather than shipping the wrong bytes.

    StencilFaceState

    Surface

    What a backend needs to hand to a graphics API in order to create a surface. a / b are the native display and window handles (or the CAMetalLayer pointer, or a canvas id on the web); their meaning is fixed per kind.

    SurfaceKind

    Swapchain

    Target

    Texture

    TextureDesc

    One descriptor for every texture shape: 2D, 2D array and cubemap, with composable usage flags instead of a factory per combination.

    TextureDimension

    TextureUsage

    Composable texture usage flags.

    TimestampPool

    VertexAttribute

    VertexBufferLayout

    Window

    WindowError

    WindowSystem

    backend_error

    Wrap the message recorded by the last failing backend call.

    check

    fn check(code : Int) -> Unit raise
    RhiError

    Turn a backend return code into a RhiError, 0 meaning success.

    A backend entry point that fails must record a message, but a missing one used to produce a bare RhiError: with nothing after it, which is impossible to act on. The code goes into the message in that case so the failure still identifies itself.

    event_from_code

    fn event_from_code(kind : Int, a : Int, b : Int, c : Int) ->
    Event

    external_surface_from_plat

    Convert a platform @tycho_plat.Surface (desktop window, iOS CAMetalLayer, Android ANativeWindow, or web canvas) into an L1 @types.ExternalSurface suitable for SwapchainDesc::new(..., external_surface=...).

    last_backend_error

    fn last_backend_error() -> String

    The bare message recorded by the last failing backend call, for logging.

    surface_candidates

    fn surface_candidates(kind :
    SurfaceKind
    ) -> Array[String]

    Candidate instance extensions required to present through kind, in the order they should be enabled. Empty when the kind has no Vulkan surface (the web canvas).

    surface_extensions_for

    fn surface_extensions_for(kind :
    SurfaceKind
    , available : Array[String]) -> Array[String]

    The subset of surface_candidates(kind) that available actually contains. Enable exactly this list, never the raw candidates.

    surface_supported

    fn surface_supported(kind :
    SurfaceKind
    , available : Array[String]) -> Bool

    Whether this surface kind can present through Vulkan at all on a loader that reports available. False both for kinds without a Vulkan surface (web) and for loaders missing the platform extension.

    wait_events

    fn wait_events(timeout_ms : Int) -> Unit

    Wait for the next batch of platform events (compositor-driven).

    Source Files